2 * Thread handling stuff for Citadel server
4 * Copyright (c) 1987-2011 by the citadel.org team
6 * This program is open source software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <sys/types.h>
26 #include <sys/socket.h>
33 #if TIME_WITH_SYS_TIME
34 # include <sys/time.h>
38 # include <sys/time.h>
47 # if HAVE_SYS_SYSCALL_H
48 # include <sys/syscall.h>
52 #include <libcitadel.h>
55 #include "ctdl_module.h"
56 #include "modules_init.h"
57 #include "housekeeping.h"
59 #include "citserver.h"
60 #include "sysdep_decls.h"
64 * define this to use the new worker_thread method of handling connections
69 * New thread interface.
70 * To create a thread you must call one of the create thread functions.
71 * You must pass it the address of (a pointer to a CtdlThreadNode initialised to NULL) like this
72 * struct CtdlThreadNode *node = NULL;
74 * If the thread is created *node will point to the thread control structure for the created thread.
75 * If the thread creation fails *node remains NULL
76 * Do not free the memory pointed to by *node, it doesn't belong to you.
77 * This new interface duplicates much of the eCrash stuff. We should go for closer integration since that would
78 * remove the need for the calls to eCrashRegisterThread and friends
81 static int num_threads = 0; /* Current number of threads */
82 static int num_workers = 0; /* Current number of worker threads */
83 long statcount = 0; /* are we doing a stats check? */
84 static long stats_done = 0;
86 CtdlThreadNode *CtdlThreadList = NULL;
87 CtdlThreadNode *CtdlThreadSchedList = NULL;
89 static CtdlThreadNode *GC_thread = NULL;
90 static char *CtdlThreadStates[CTDL_THREAD_LAST_STATE];
91 double CtdlThreadLoadAvg = 0;
92 double CtdlThreadWorkerAvg = 0;
93 citthread_key_t ThreadKey;
95 citthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
99 void InitialiseSemaphores(void)
103 /* Set up a bunch of semaphores to be used for critical sections */
104 for (i=0; i<MAX_SEMAPHORES; ++i) {
105 citthread_mutex_init(&Critters[i], NULL);
113 * Obtain a semaphore lock to begin a critical section.
114 * but only if no one else has one
116 int try_critical_section(int which_one)
118 /* For all types of critical sections except those listed here,
119 * ensure nobody ever tries to do a critical section within a
120 * transaction; this could lead to deadlock.
122 if ( (which_one != S_FLOORCACHE)
123 #ifdef DEBUG_MEMORY_LEAKS
124 && (which_one != S_DEBUGMEMLEAKS)
126 && (which_one != S_RPLIST)
130 return (citthread_mutex_trylock(&Critters[which_one]));
135 * Obtain a semaphore lock to begin a critical section.
137 void begin_critical_section(int which_one)
139 /* syslog(LOG_DEBUG, "begin_critical_section(%d)\n", which_one); */
141 /* For all types of critical sections except those listed here,
142 * ensure nobody ever tries to do a critical section within a
143 * transaction; this could lead to deadlock.
145 if ( (which_one != S_FLOORCACHE)
146 #ifdef DEBUG_MEMORY_LEAKS
147 && (which_one != S_DEBUGMEMLEAKS)
149 && (which_one != S_RPLIST)
153 citthread_mutex_lock(&Critters[which_one]);
157 * Release a semaphore lock to end a critical section.
159 void end_critical_section(int which_one)
161 citthread_mutex_unlock(&Critters[which_one]);
166 * A function to destroy the TSD
168 static void ctdl_thread_internal_dest_tsd(void *arg)
178 * A function to initialise the thread TSD
180 void ctdl_thread_internal_init_tsd(void)
184 if ((ret = citthread_key_create(&ThreadKey, ctdl_thread_internal_dest_tsd))) {
185 syslog(LOG_EMERG, "citthread_key_create: %s\n", strerror(ret));
191 * Ensure that we have a key for thread-specific data.
193 * This should be called immediately after startup by any thread
196 void CtdlThreadAllocTSD(void)
200 if (citthread_getspecific(ThreadKey) != NULL)
203 tsd = malloc(sizeof(ThreadTSD));
207 memset(tsd->cursors, 0, sizeof tsd->cursors);
210 citthread_setspecific(ThreadKey, tsd);
214 void ctdl_thread_internal_free_tsd(void)
216 ctdl_thread_internal_dest_tsd(citthread_getspecific(ThreadKey));
217 citthread_setspecific(ThreadKey, NULL);
221 void ctdl_thread_internal_cleanup(void)
224 CtdlThreadNode *this_thread, *that_thread;
226 for (i=0; i<CTDL_THREAD_LAST_STATE; i++)
228 free (CtdlThreadStates[i]);
231 /* Clean up the scheduled thread list */
232 this_thread = CtdlThreadSchedList;
235 that_thread = this_thread;
236 this_thread = this_thread->next;
237 citthread_mutex_destroy(&that_thread->ThreadMutex);
238 citthread_cond_destroy(&that_thread->ThreadCond);
239 citthread_mutex_destroy(&that_thread->SleepMutex);
240 citthread_cond_destroy(&that_thread->SleepCond);
241 citthread_attr_destroy(&that_thread->attr);
244 ctdl_thread_internal_free_tsd();
247 void ctdl_thread_internal_init(void)
249 CtdlThreadNode *this_thread;
252 CtdlThreadStates[CTDL_THREAD_INVALID] = strdup ("Invalid Thread");
253 CtdlThreadStates[CTDL_THREAD_VALID] = strdup("Valid Thread");
254 CtdlThreadStates[CTDL_THREAD_CREATE] = strdup("Thread being Created");
255 CtdlThreadStates[CTDL_THREAD_CANCELLED] = strdup("Thread Cancelled");
256 CtdlThreadStates[CTDL_THREAD_EXITED] = strdup("Thread Exited");
257 CtdlThreadStates[CTDL_THREAD_STOPPING] = strdup("Thread Stopping");
258 CtdlThreadStates[CTDL_THREAD_STOP_REQ] = strdup("Thread Stop Requested");
259 CtdlThreadStates[CTDL_THREAD_SLEEPING] = strdup("Thread Sleeping");
260 CtdlThreadStates[CTDL_THREAD_RUNNING] = strdup("Thread Running");
261 CtdlThreadStates[CTDL_THREAD_BLOCKED] = strdup("Thread Blocked");
263 /* Get ourself a thread entry */
264 this_thread = malloc(sizeof(CtdlThreadNode));
265 if (this_thread == NULL) {
266 syslog(LOG_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
269 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
270 memset (this_thread, 0, sizeof(CtdlThreadNode));
272 citthread_mutex_init (&(this_thread->ThreadMutex), NULL);
273 citthread_cond_init (&(this_thread->ThreadCond), NULL);
274 citthread_mutex_init (&(this_thread->SleepMutex), NULL);
275 citthread_cond_init (&(this_thread->SleepCond), NULL);
277 /* We are garbage collector so create us as running */
278 this_thread->state = CTDL_THREAD_RUNNING;
280 if ((ret = citthread_attr_init(&this_thread->attr))) {
281 syslog(LOG_EMERG, "Thread system, citthread_attr_init: %s\n", strerror(ret));
286 this_thread->name = "Garbage Collection Thread";
288 this_thread->tid = citthread_self();
289 GC_thread = this_thread;
292 num_threads++; // Increase the count of threads in the system.
294 this_thread->next = CtdlThreadList;
295 CtdlThreadList = this_thread;
296 if (this_thread->next)
297 this_thread->next->prev = this_thread;
298 /* Set up start times */
299 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
300 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
305 * A function to update a threads load averages
307 void ctdl_thread_internal_update_avgs(CtdlThreadNode *this_thread)
309 struct timeval now, result;
310 double last_duration;
312 gettimeofday(&now, NULL);
313 timersub(&now, &(this_thread->last_state_change), &result);
314 /* I don't think these mutex's are needed here */
315 citthread_mutex_lock(&this_thread->ThreadMutex);
316 // result now has a timeval for the time we spent in the last state since we last updated
317 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
318 if (this_thread->state == CTDL_THREAD_SLEEPING)
319 this_thread->avg_sleeping += last_duration;
320 if (this_thread->state == CTDL_THREAD_RUNNING)
321 this_thread->avg_running += last_duration;
322 if (this_thread->state == CTDL_THREAD_BLOCKED)
323 this_thread->avg_blocked += last_duration;
324 memcpy (&this_thread->last_state_change, &now, sizeof (struct timeval));
325 citthread_mutex_unlock(&this_thread->ThreadMutex);
329 * A function to chenge the state of a thread
331 void ctdl_thread_internal_change_state (CtdlThreadNode *this_thread, enum CtdlThreadState new_state)
334 * Wether we change state or not we need update the load values
336 ctdl_thread_internal_update_avgs(this_thread);
337 /* This mutex not needed here? */
338 citthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
339 if ((new_state == CTDL_THREAD_STOP_REQ) && (this_thread->state > CTDL_THREAD_STOP_REQ))
340 this_thread->state = new_state;
341 if (((new_state == CTDL_THREAD_SLEEPING) || (new_state == CTDL_THREAD_BLOCKED)) && (this_thread->state == CTDL_THREAD_RUNNING))
342 this_thread->state = new_state;
343 if ((new_state == CTDL_THREAD_RUNNING) && ((this_thread->state == CTDL_THREAD_SLEEPING) || (this_thread->state == CTDL_THREAD_BLOCKED)))
344 this_thread->state = new_state;
345 citthread_mutex_unlock(&this_thread->ThreadMutex);
350 * A function to tell all threads to exit
352 void CtdlThreadStopAll(void)
354 /* First run any registered shutdown hooks. This probably doesn't belong here. */
355 PerformSessionHooks(EVT_SHUTDOWN);
357 /* then close all tcp ports so nobody else can talk to us anymore. */
358 CtdlShutdownServiceHooks();
359 //FIXME: The signalling of the condition should not be in the critical_section
360 // We need to build a list of threads we are going to signal and then signal them afterwards
362 CtdlThreadNode *this_thread;
364 begin_critical_section(S_THREAD_LIST);
365 this_thread = CtdlThreadList;
366 // Ask the GC thread to stop first so everything knows we are shutting down.
367 GC_thread->state = CTDL_THREAD_STOP_REQ;
370 if (!citthread_equal(this_thread->tid, GC_thread->tid))
371 citthread_kill(this_thread->tid, SIGHUP);
373 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
374 citthread_cond_signal(&this_thread->ThreadCond);
375 citthread_cond_signal(&this_thread->SleepCond);
376 this_thread->stop_ticker = time(NULL);
377 syslog(LOG_DEBUG, "Thread system stopping thread \"%s\" (0x%08lx).\n",
378 this_thread->name, this_thread->tid);
379 this_thread = this_thread->next;
381 end_critical_section(S_THREAD_LIST);
386 * A function to wake up all sleeping threads
388 void CtdlThreadWakeAll(void)
390 CtdlThreadNode *this_thread;
392 syslog(LOG_DEBUG, "Thread system waking all threads.\n");
394 begin_critical_section(S_THREAD_LIST);
395 this_thread = CtdlThreadList;
398 if (!this_thread->thread_func)
400 citthread_cond_signal(&this_thread->ThreadCond);
401 citthread_cond_signal(&this_thread->SleepCond);
403 this_thread = this_thread->next;
405 end_critical_section(S_THREAD_LIST);
410 * A function to return the number of threads running in the system
412 int CtdlThreadGetCount(void)
417 int CtdlThreadGetWorkers(void)
422 double CtdlThreadGetWorkerAvg(void)
426 begin_critical_section(S_THREAD_LIST);
427 ret = CtdlThreadWorkerAvg;
428 end_critical_section(S_THREAD_LIST);
432 double CtdlThreadGetLoadAvg(void)
434 double load_avg[3] = {0.0, 0.0, 0.0};
439 /* Borrowed this straight from procps */
440 smp_num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
441 if(smp_num_cpus<1) smp_num_cpus=1; /* SPARC glibc is buggy */
443 #ifdef HAVE_GETLOADAVG
444 ret = getloadavg(load_avg, 3);
448 return load_avg[0] / smp_num_cpus;
450 * This old chunk of code return a value that indicated the load on citserver
451 * This value could easily reach 100 % even when citserver was doing very little and
452 * hence the machine has much more spare capacity.
453 * Because this value was used to determine if the machine was under heavy load conditions
454 * from other processes in the system then citserver could be strangled un-necesarily
455 * What we are actually trying to achieve is to strangle citserver if the machine is heavily loaded.
456 * So we have changed this.
458 begin_critical_section(S_THREAD_LIST);
459 ret = CtdlThreadLoadAvg;
460 end_critical_section(S_THREAD_LIST);
469 * A function to rename a thread
470 * Returns a const char *
472 const char *CtdlThreadName(const char *name)
474 const char *old_name;
478 syslog(LOG_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread. %s\n", name);
489 * A function to force a thread to exit
491 void CtdlThreadCancel(CtdlThreadNode *thread)
493 CtdlThreadNode *this_thread;
498 this_thread = thread;
501 syslog(LOG_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
506 if (!this_thread->thread_func)
508 syslog(LOG_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
513 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
514 citthread_cancel(this_thread->tid);
519 * A function for a thread to check if it has been asked to stop
521 int CtdlThreadCheckStop(void)
527 syslog(LOG_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
536 syslog(LOG_DEBUG, "Thread \"%s\" caught signal %d.\n", CT->name, CT->signal);
537 if (CT->signal == SIGHUP)
538 CT->state = CTDL_THREAD_STOP_REQ;
541 if(state == CTDL_THREAD_STOP_REQ)
543 CT->state = CTDL_THREAD_STOPPING;
546 else if((state < CTDL_THREAD_STOP_REQ) && (state > CTDL_THREAD_CREATE))
555 * A function to ask a thread to exit
556 * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
558 void CtdlThreadStop(CtdlThreadNode *thread)
560 CtdlThreadNode *this_thread;
565 this_thread = thread;
568 if (!(this_thread->thread_func))
569 return; // Don't stop garbage collector
571 if (!citthread_equal(this_thread->tid, GC_thread->tid))
572 citthread_kill(this_thread->tid, SIGHUP);
574 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
575 citthread_cond_signal(&this_thread->ThreadCond);
576 citthread_cond_signal(&this_thread->SleepCond);
577 this_thread->stop_ticker = time(NULL);
581 * So we now have a sleep command that works with threads but it is in seconds
583 void CtdlThreadSleep(int secs)
585 struct timespec wake_time;
586 struct timeval time_now;
591 syslog(LOG_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
595 memset (&wake_time, 0, sizeof(struct timespec));
596 gettimeofday(&time_now, NULL);
597 wake_time.tv_sec = time_now.tv_sec + secs;
598 wake_time.tv_nsec = time_now.tv_usec * 10;
600 ctdl_thread_internal_change_state (CT, CTDL_THREAD_SLEEPING);
602 citthread_mutex_lock(&CT->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
603 citthread_cond_timedwait(&CT->SleepCond, &CT->ThreadMutex, &wake_time);
604 citthread_mutex_unlock(&CT->ThreadMutex);
606 ctdl_thread_internal_change_state (CT, CTDL_THREAD_RUNNING);
611 * Routine to clean up our thread function on exit
613 static void ctdl_internal_thread_cleanup(void *arg)
616 * In here we were called by the current thread because it is exiting
617 * NB. WE ARE THE CURRENT THREAD
621 const char *name = CT->name;
622 const pid_t tid = CT->tid;
624 syslog(LOG_NOTICE, "Thread \"%s\" (0x%08lx) exited.\n", name, (unsigned long) tid);
628 syslog(LOG_NOTICE, "some ((unknown ? ? ?) Thread exited.\n");
631 #ifdef HAVE_BACKTRACE
632 /// eCrash_UnregisterThread();
635 citthread_mutex_lock(&CT->ThreadMutex);
636 CT->state = CTDL_THREAD_EXITED; // needs to be last thing else house keeping will unlink us too early
637 citthread_mutex_unlock(&CT->ThreadMutex);
641 * A quick function to show the load averages
643 void ctdl_thread_internal_calc_loadavg(void)
645 CtdlThreadNode *that_thread;
646 double load_avg, worker_avg;
649 that_thread = CtdlThreadList;
654 /* Update load averages */
655 ctdl_thread_internal_update_avgs(that_thread);
656 citthread_mutex_lock(&that_thread->ThreadMutex);
657 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;
658 that_thread->avg_sleeping /= 2;
659 that_thread->avg_running /= 2;
660 that_thread->avg_blocked /= 2;
661 load_avg += that_thread->load_avg;
662 if (that_thread->flags & CTDLTHREAD_WORKER)
664 worker_avg += that_thread->load_avg;
667 #ifdef WITH_THREADLOG
668 syslog(LOG_DEBUG, "CtdlThread, \"%s\" (%lu) \"%s\" %.2f %.2f %.2f %.2f\n",
671 CtdlThreadStates[that_thread->state],
672 that_thread->avg_sleeping,
673 that_thread->avg_running,
674 that_thread->avg_blocked,
675 that_thread->load_avg);
677 citthread_mutex_unlock(&that_thread->ThreadMutex);
678 that_thread = that_thread->next;
680 CtdlThreadLoadAvg = load_avg/num_threads;
681 CtdlThreadWorkerAvg = worker_avg/workers;
682 #ifdef WITH_THREADLOG
683 syslog(LOG_INFO, "System load average %.2f, workers averag %.2f, threads %d, workers %d, sessions %d\n", CtdlThreadGetLoadAvg(), CtdlThreadWorkerAvg, num_threads, num_workers, num_sessions);
689 * Garbage collection routine.
690 * Gets called by main() in a loop to clean up the thread list periodically.
692 void CtdlThreadGC (void)
697 /* FIXME this is a big deal, but I think it's causing corruption */
700 CtdlThreadNode *this_thread, *that_thread;
701 int workers = 0, sys_workers;
704 begin_critical_section(S_THREAD_LIST);
706 /* Handle exiting of garbage collector thread */
708 CtdlThreadList->state = CTDL_THREAD_EXITED;
710 #ifdef WITH_THREADLOG
711 syslog(LOG_DEBUG, "Thread system running garbage collection.\n");
714 * Woke up to do garbage collection
716 this_thread = CtdlThreadList;
719 that_thread = this_thread;
720 this_thread = this_thread->next;
722 if ((that_thread->state == CTDL_THREAD_STOP_REQ || that_thread->state == CTDL_THREAD_STOPPING)
723 && (!citthread_equal(that_thread->tid, citthread_self())))
725 syslog(LOG_DEBUG, "Waiting for thread %s (0x%08lx) to exit.\n", that_thread->name, that_thread->tid);
726 terminate_stuck_sessions();
731 * Catch the situation where a worker was asked to stop but couldn't and we are not
734 that_thread->stop_ticker = 0;
737 if (that_thread->stop_ticker + 5 == time(NULL))
739 syslog(LOG_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);
740 if ((that_thread->flags & CTDLTHREAD_WORKER) == 0)
741 syslog(LOG_INFO, "Thread System: A non worker thread would have been canceled this may cause message loss.\n");
742 // that_thread->state = CTDL_THREAD_CANCELLED;
743 that_thread->stop_ticker++;
744 // citthread_cancel(that_thread->tid);
748 /* Do we need to clean up this thread? */
749 if ((that_thread->state != CTDL_THREAD_EXITED) && (that_thread->state != CTDL_THREAD_CANCELLED))
751 if(that_thread->flags & CTDLTHREAD_WORKER)
752 workers++; /* Sanity check on number of worker threads */
756 if (citthread_equal(that_thread->tid, citthread_self()) && that_thread->thread_func)
758 end_critical_section(S_THREAD_LIST);
759 syslog(LOG_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
764 if (num_threads <= 0)
766 end_critical_section(S_THREAD_LIST);
767 syslog(LOG_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
772 if(that_thread->flags & CTDLTHREAD_WORKER)
773 num_workers--; /* This is a wroker thread so reduce the count. */
775 /* If we are unlinking the list head then the next becomes the list head */
776 if(that_thread->prev)
777 that_thread->prev->next = that_thread->next;
779 CtdlThreadList = that_thread->next;
780 if(that_thread->next)
781 that_thread->next->prev = that_thread->prev;
783 citthread_cond_signal(&that_thread->ThreadCond);
784 citthread_cond_signal(&that_thread->SleepCond); // Make sure this thread is awake
785 citthread_mutex_lock(&that_thread->ThreadMutex); // Make sure it has done what its doing
786 citthread_mutex_unlock(&that_thread->ThreadMutex);
788 * Join on the thread to do clean up and prevent memory leaks
789 * Also makes sure the thread has cleaned up after itself before we remove it from the list
790 * We can join on the garbage collector thread the join should just return EDEADLCK
792 ret = citthread_join (that_thread->tid, NULL);
794 syslog(LOG_DEBUG, "Garbage collection on own thread.\n");
795 else if (ret == EINVAL)
796 syslog(LOG_DEBUG, "Garbage collection, that thread already joined on.\n");
797 else if (ret == ESRCH)
798 syslog(LOG_DEBUG, "Garbage collection, no thread to join on.\n");
800 syslog(LOG_DEBUG, "Garbage collection, citthread_join returned an unknown error(%d).\n", ret);
802 * Now we own that thread entry
804 syslog(LOG_INFO, "Garbage Collection for thread \"%s\" (0x%08lx).\n",
805 that_thread->name, that_thread->tid);
806 citthread_mutex_destroy(&that_thread->ThreadMutex);
807 citthread_cond_destroy(&that_thread->ThreadCond);
808 citthread_mutex_destroy(&that_thread->SleepMutex);
809 citthread_cond_destroy(&that_thread->SleepCond);
810 citthread_attr_destroy(&that_thread->attr);
813 sys_workers = num_workers;
814 end_critical_section(S_THREAD_LIST);
816 /* Sanity check number of worker threads */
817 if (workers != sys_workers)
820 "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n",
831 * Runtime function for a Citadel Thread.
832 * This initialises the threads environment and then calls the user supplied thread function
833 * Note that this is the REAL thread function and wraps the users thread function.
835 static void *ctdl_internal_thread_func (void *arg)
837 CtdlThreadNode *this_thread;
840 /* lock and unlock the thread list.
841 * This causes this thread to wait until all its creation stuff has finished before it
842 * can continue its execution.
844 begin_critical_section(S_THREAD_LIST);
845 this_thread = (CtdlThreadNode *) arg;
846 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
848 // Register the cleanup function to take care of when we exit.
849 citthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
850 // Get our thread data structure
851 CtdlThreadAllocTSD();
853 this_thread->pid = getpid();
854 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
855 /* Only change to running state if we weren't asked to stop during the create cycle
856 * Other wise there is a window to allow this threads creation to continue to full grown and
857 * therby prevent a shutdown of the server.
859 if (!CtdlThreadCheckStop())
861 citthread_mutex_lock(&this_thread->ThreadMutex);
862 this_thread->state = CTDL_THREAD_RUNNING;
863 citthread_mutex_unlock(&this_thread->ThreadMutex);
865 end_critical_section(S_THREAD_LIST);
867 // Register for tracing
868 #ifdef HAVE_BACKTRACE
869 /// eCrash_RegisterThread(this_thread->name, 0);
872 // Tell the world we are here
873 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
874 this_thread->reltid = syscall(SYS_gettid);
876 syslog(LOG_NOTICE, "Created a new thread \"%s\" (0x%08lx).\n",
877 this_thread->name, this_thread->tid);
880 * run the thread to do the work but only if we haven't been asked to stop
882 if (!CtdlThreadCheckStop())
883 ret = (this_thread->thread_func)(this_thread->user_args);
886 * Our thread is exiting either because it wanted to end or because the server is stopping
887 * We need to clean up
889 citthread_cleanup_pop(1); // Execute our cleanup routine and remove it
898 * Function to initialise an empty thread structure
900 CtdlThreadNode *ctdl_internal_init_thread_struct(CtdlThreadNode *this_thread, long flags)
904 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
905 memset (this_thread, 0, sizeof(CtdlThreadNode));
907 /* Create the mutex's early so we can use them */
908 citthread_mutex_init (&(this_thread->ThreadMutex), NULL);
909 citthread_cond_init (&(this_thread->ThreadCond), NULL);
910 citthread_mutex_init (&(this_thread->SleepMutex), NULL);
911 citthread_cond_init (&(this_thread->SleepCond), NULL);
913 this_thread->state = CTDL_THREAD_CREATE;
915 if ((ret = citthread_attr_init(&this_thread->attr))) {
916 citthread_mutex_unlock(&this_thread->ThreadMutex);
917 citthread_mutex_destroy(&(this_thread->ThreadMutex));
918 citthread_cond_destroy(&(this_thread->ThreadCond));
919 citthread_mutex_destroy(&(this_thread->SleepMutex));
920 citthread_cond_destroy(&(this_thread->SleepCond));
921 syslog(LOG_EMERG, "Thread system, citthread_attr_init: %s\n", strerror(ret));
926 /* Our per-thread stacks need to be bigger than the default size,
927 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
928 * crashes on 64-bit Linux.
930 if (flags & CTDLTHREAD_BIGSTACK)
932 #ifdef WITH_THREADLOG
933 syslog(LOG_INFO, "Thread system. Creating BIG STACK thread.\n");
935 if ((ret = citthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
936 citthread_mutex_unlock(&this_thread->ThreadMutex);
937 citthread_mutex_destroy(&(this_thread->ThreadMutex));
938 citthread_cond_destroy(&(this_thread->ThreadCond));
939 citthread_mutex_destroy(&(this_thread->SleepMutex));
940 citthread_cond_destroy(&(this_thread->SleepCond));
941 citthread_attr_destroy(&this_thread->attr);
942 syslog(LOG_EMERG, "Thread system, citthread_attr_setstacksize: %s\n",
949 /* Set this new thread with an avg_blocked of 2. We do this so that its creation affects the
950 * load average for the system. If we don't do this then we create a mass of threads at the same time
951 * because the creation didn't affect the load average.
953 this_thread->avg_blocked = 2;
955 return (this_thread);
962 * Internal function to create a thread.
964 CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
967 CtdlThreadNode *this_thread;
969 if (num_threads >= 32767)
971 syslog(LOG_EMERG, "Thread system. Thread list full.\n");
975 this_thread = malloc(sizeof(CtdlThreadNode));
976 if (this_thread == NULL) {
977 syslog(LOG_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
981 /* Initialise the thread structure */
982 if (ctdl_internal_init_thread_struct(this_thread, flags) == NULL)
985 syslog(LOG_EMERG, "Thread system, can't initialise CtdlThreadNode, exiting\n");
989 * If we got here we are going to create the thread so we must initilise the structure
990 * first because most implimentations of threading can't create it in a stopped state
991 * and it might want to do things with its structure that aren't initialised otherwise.
995 this_thread->name = name;
999 this_thread->name = "Un-named Thread";
1002 this_thread->flags = flags;
1003 this_thread->thread_func = thread_func;
1004 this_thread->user_args = args;
1006 begin_critical_section(S_THREAD_LIST);
1008 * We pass this_thread into the thread as its args so that it can find out information
1009 * about itself and it has a bit of storage space for itself, not to mention that the REAL
1010 * thread function needs to finish off the setup of the structure
1012 if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1014 end_critical_section(S_THREAD_LIST);
1015 syslog(LOG_ALERT, "Thread system, Can't create thread: %s\n",
1017 citthread_mutex_unlock(&this_thread->ThreadMutex);
1018 citthread_mutex_destroy(&(this_thread->ThreadMutex));
1019 citthread_cond_destroy(&(this_thread->ThreadCond));
1020 citthread_mutex_destroy(&(this_thread->SleepMutex));
1021 citthread_cond_destroy(&(this_thread->SleepCond));
1022 citthread_attr_destroy(&this_thread->attr);
1026 num_threads++; // Increase the count of threads in the system.
1027 if(this_thread->flags & CTDLTHREAD_WORKER)
1030 this_thread->next = CtdlThreadList;
1031 CtdlThreadList = this_thread;
1032 if (this_thread->next)
1033 this_thread->next->prev = this_thread;
1034 ctdl_thread_internal_calc_loadavg();
1036 end_critical_section(S_THREAD_LIST);
1042 * Wrapper function to create a thread
1043 * ensures the critical section and other protections are in place.
1044 * char *name = name to give to thread, if NULL, use generic name
1045 * int flags = flags to determine type of thread and standard facilities
1047 CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1049 CtdlThreadNode *ret = NULL;
1051 ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1057 CtdlThreadNode *ctdl_thread_internal_start_scheduled (CtdlThreadNode *this_thread)
1061 begin_critical_section(S_THREAD_LIST);
1063 * We pass this_thread into the thread as its args so that it can find out information
1064 * about itself and it has a bit of storage space for itself, not to mention that the REAL
1065 * thread function needs to finish off the setup of the structure
1067 if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1069 end_critical_section(S_THREAD_LIST);
1070 syslog(LOG_DEBUG, "Failed to start scheduled thread \"%s\": %s\n", this_thread->name, strerror(ret));
1071 citthread_mutex_destroy(&(this_thread->ThreadMutex));
1072 citthread_cond_destroy(&(this_thread->ThreadCond));
1073 citthread_mutex_destroy(&(this_thread->SleepMutex));
1074 citthread_cond_destroy(&(this_thread->SleepCond));
1075 citthread_attr_destroy(&this_thread->attr);
1081 num_threads++; // Increase the count of threads in the system.
1082 if(this_thread->flags & CTDLTHREAD_WORKER)
1085 this_thread->next = CtdlThreadList;
1086 CtdlThreadList = this_thread;
1087 if (this_thread->next)
1088 this_thread->next->prev = this_thread;
1090 ctdl_thread_internal_calc_loadavg();
1091 end_critical_section(S_THREAD_LIST);
1099 void ctdl_thread_internal_check_scheduled(void)
1101 CtdlThreadNode *this_thread, *that_thread;
1104 /* Don't start scheduled threads if the system wants single user mode */
1105 if (CtdlWantSingleUser())
1108 if (try_critical_section(S_SCHEDULE_LIST))
1109 return; /* If this list is locked we wait till the next chance */
1113 #ifdef WITH_THREADLOG
1114 syslog(LOG_DEBUG, "Checking for scheduled threads to start.\n");
1117 this_thread = CtdlThreadSchedList;
1120 that_thread = this_thread;
1121 this_thread = this_thread->next;
1123 if (now > that_thread->when)
1125 /* Unlink from schedule list */
1126 if (that_thread->prev)
1127 that_thread->prev->next = that_thread->next;
1129 CtdlThreadSchedList = that_thread->next;
1130 if (that_thread->next)
1131 that_thread->next->prev = that_thread->prev;
1133 that_thread->next = that_thread->prev = NULL;
1134 #ifdef WITH_THREADLOG
1135 syslog(LOG_DEBUG, "About to start scheduled thread \"%s\".\n", that_thread->name);
1137 if (CT->state > CTDL_THREAD_STOP_REQ)
1138 { /* Only start it if the system is not stopping */
1139 if (ctdl_thread_internal_start_scheduled (that_thread))
1141 #ifdef WITH_THREADLOG
1142 syslog(LOG_INFO, "Thread system, Started a scheduled thread \"%s\" (0x%08lx).\n",
1143 that_thread->name, that_thread->tid);
1148 #ifdef WITH_THREADLOG
1151 syslog(LOG_DEBUG, "Thread \"%s\" will start in %ld seconds.\n",
1152 that_thread->name, that_thread->when - time(NULL));
1156 end_critical_section(S_SCHEDULE_LIST);
1161 * A warapper function for select so we can show a thread as blocked
1163 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
1167 ctdl_thread_internal_change_state(CT, CTDL_THREAD_BLOCKED);
1168 if (!CtdlThreadCheckStop())
1169 ret = select(n, readfds, writefds, exceptfds, timeout);
1171 * If the select returned <= 0 then it failed due to an error
1172 * or timeout so this thread could stop if asked to do so.
1173 * Anything else means it needs to continue unless the system is shutting down
1178 * The select says this thread needs to do something useful.
1179 * This thread was in an idle state so it may have been asked to stop
1180 * but if the system isn't shutting down this thread is no longer
1181 * idle and select has given it a task to do so it must not stop
1182 * In this condition we need to force it into the running state.
1183 * CtdlThreadGC will clear its ticker for us.
1185 * FIXME: there is still a small hole here. It is possible for the sequence of locking
1186 * to allow the state to get changed to STOP_REQ just after this code if the other thread
1187 * has decided to change the state before this lock, it there fore has to wait till the lock
1188 * completes but it will continue to change the state. We need something a bit better here.
1190 citthread_mutex_lock(&CT->ThreadMutex); /* To prevent race condition of a sleeping thread */
1191 if (GC_thread->state > CTDL_THREAD_STOP_REQ && CT->state <= CTDL_THREAD_STOP_REQ)
1193 syslog(LOG_DEBUG, "Thread %s (0x%08lx) refused stop request.\n", CT->name, CT->tid);
1194 CT->state = CTDL_THREAD_RUNNING;
1196 citthread_mutex_unlock(&CT->ThreadMutex);
1199 ctdl_thread_internal_change_state(CT, CTDL_THREAD_RUNNING);
1206 void *new_worker_thread(void *arg);
1207 extern void close_masters (void);
1210 void *simulation_worker (void*arg) {
1211 struct CitContext *this;
1213 this = CreateNewContext();
1215 this->kill_me = KILLME_SIMULATION_WORKER;
1216 this->state = CON_IDLE;
1217 dead_session_purge(1);
1218 begin_critical_section(S_SESSION_TABLE);
1220 end_critical_section(S_SESSION_TABLE);
1225 void *simulation_thread (void *arg)
1227 long stats = statcount;
1229 while(stats && !CtdlThreadCheckStop()) {
1230 CtdlThreadCreate("Connection simulation worker", CTDLTHREAD_BIGSTACK, simulation_worker, NULL);
1233 CtdlThreadStopAll();
1237 void go_threading(void)
1240 CtdlThreadNode *last_worker;
1241 struct timeval start, now, result;
1242 double last_duration;
1245 * Initialise the thread system
1247 ctdl_thread_internal_init();
1249 /* Second call to module init functions now that threading is up */
1251 initialise_modules(1);
1252 CtdlThreadCreate("select_on_master", CTDLTHREAD_BIGSTACK, select_on_master, NULL);
1255 syslog(LOG_EMERG, "Running connection simulation stats\n");
1256 gettimeofday(&start, NULL);
1257 CtdlThreadCreate("Connection simulation master", CTDLTHREAD_BIGSTACK, simulation_thread, NULL);
1262 * This thread is now used for garbage collection of other threads in the thread list
1264 syslog(LOG_INFO, "Startup thread %ld becoming garbage collector,\n", (long) citthread_self());
1267 * We do a lot of locking and unlocking of the thread list in here.
1268 * We do this so that we can repeatedly release time for other threads
1269 * that may be waiting on the thread list.
1270 * We are a low priority thread so we can afford to do this
1273 while (CtdlThreadGetCount())
1276 exit_signal = CT->signal;
1279 CtdlThreadStopAll();
1281 check_sched_shutdown();
1282 if (CT->state > CTDL_THREAD_STOP_REQ)
1284 begin_critical_section(S_THREAD_LIST);
1285 ctdl_thread_internal_calc_loadavg();
1286 end_critical_section(S_THREAD_LIST);
1288 ctdl_thread_internal_check_scheduled(); /* start scheduled threads */
1291 /* Reduce the size of the worker thread pool if necessary. */
1292 if ((CtdlThreadGetWorkers() > config.c_min_workers + 1) && (CtdlThreadWorkerAvg < 20) && (CT->state > CTDL_THREAD_STOP_REQ))
1294 /* Ask a worker thread to stop as we no longer need it */
1295 begin_critical_section(S_THREAD_LIST);
1296 last_worker = CtdlThreadList;
1299 citthread_mutex_lock(&last_worker->ThreadMutex);
1300 if (last_worker->flags & CTDLTHREAD_WORKER && (last_worker->state > CTDL_THREAD_STOPPING) && (last_worker->Context == NULL))
1302 citthread_mutex_unlock(&last_worker->ThreadMutex);
1305 citthread_mutex_unlock(&last_worker->ThreadMutex);
1306 last_worker = last_worker->next;
1308 end_critical_section(S_THREAD_LIST);
1311 #ifdef WITH_THREADLOG
1312 syslog(LOG_DEBUG, "Thread system, stopping excess worker thread \"%s\" (0x%08lx).\n",
1317 CtdlThreadStop(last_worker);
1322 * If all our workers are working hard, start some more to help out
1325 /* FIXME: come up with a better way to dynamically alter the number of threads
1326 * based on the system load
1329 if ((((CtdlThreadGetWorkers() < config.c_max_workers) && (CtdlThreadGetWorkerAvg() > 60)) || CtdlThreadGetWorkers() < config.c_min_workers) && (CT->state > CTDL_THREAD_STOP_REQ))
1331 /* Only start new threads if we are not going to overload the machine */
1332 /* Temporarily set to 10 should be enough to make sure we don't stranglew the server
1333 * at least until we make this a config option */
1334 if (CtdlThreadGetLoadAvg() < ((double)10.00)) {
1335 for (i=0; i<5 ; i++) {
1336 CtdlThreadCreate("Worker Thread",
1337 CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER,
1344 syslog(LOG_WARNING, "Server strangled due to machine load average too high.\n");
1350 if (CtdlThreadGetCount() <= 1) // Shutting down clean up the garbage collector
1355 #ifdef THREADS_USESIGNALS
1356 if (CtdlThreadGetCount() && CT->state > CTDL_THREAD_STOP_REQ)
1358 if (CtdlThreadGetCount())
1363 * If the above loop exits we must be shutting down since we obviously have no threads
1365 ctdl_thread_internal_cleanup();
1368 gettimeofday(&now, NULL);
1369 timersub(&now, &start, &result);
1370 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
1371 syslog(LOG_EMERG, "Simulated %ld connections in %f seconds\n", stats_done, last_duration);