Upsie, usleep is 10^6 times smaller than sleep
[citadel.git] / citadel / threads.c
1 /*
2  * Thread handling stuff for Citadel server
3  *
4  * Copyright (c) 1987-2011 by the citadel.org team
5  *
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, version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <stdio.h>
18 #include <sys/types.h>
19 #include <errno.h>
20 #include <sys/socket.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <signal.h>
24 #include <syslog.h>
25
26 #include "sysdep.h"
27 #if TIME_WITH_SYS_TIME
28 # include <sys/time.h>
29 # include <time.h>
30 #else
31 # if HAVE_SYS_TIME_H
32 #  include <sys/time.h>
33 # else
34 #  include <time.h>
35 # endif
36 #endif
37
38 #ifdef HAVE_SYSCALL_H
39 # include <syscall.h>
40 #else 
41 # if HAVE_SYS_SYSCALL_H
42 #  include <sys/syscall.h>
43 # endif
44 #endif
45
46 #include <libcitadel.h>
47
48 #include "threads.h"
49 #include "ctdl_module.h"
50 #include "modules_init.h"
51 #include "housekeeping.h"
52 #include "config.h"
53 #include "citserver.h"
54 #include "sysdep_decls.h"
55 #include "context.h"
56 #include "event_client.h"
57
58
59 int num_workers = 0;                            /* Current number of worker threads */
60 int active_workers = 0;                         /* Number of ACTIVE worker threads */
61 pthread_key_t ThreadKey;
62 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
63 struct thread_tsd masterTSD;
64 int server_shutting_down = 0;                   /* set to nonzero during shutdown */
65
66
67
68 void InitializeSemaphores(void)
69 {
70         int i;
71
72         /* Set up a bunch of semaphores to be used for critical sections */
73         for (i=0; i<MAX_SEMAPHORES; ++i) {
74                 pthread_mutex_init(&Critters[i], NULL);
75         }
76 }
77
78
79
80
81 /*
82  * Obtain a semaphore lock to begin a critical section.
83  * but only if no one else has one
84  */
85 int try_critical_section(int which_one)
86 {
87         /* For all types of critical sections except those listed here,
88          * ensure nobody ever tries to do a critical section within a
89          * transaction; this could lead to deadlock.
90          */
91         if (    (which_one != S_FLOORCACHE)
92                 && (which_one != S_RPLIST)
93         ) {
94                 cdb_check_handles();
95         }
96         return (pthread_mutex_trylock(&Critters[which_one]));
97 }
98
99
100 /*
101  * Obtain a semaphore lock to begin a critical section.
102  */
103 void begin_critical_section(int which_one)
104 {
105         /* For all types of critical sections except those listed here,
106          * ensure nobody ever tries to do a critical section within a
107          * transaction; this could lead to deadlock.
108          */
109         if (    (which_one != S_FLOORCACHE)
110                 && (which_one != S_RPLIST)
111         ) {
112                 cdb_check_handles();
113         }
114         pthread_mutex_lock(&Critters[which_one]);
115 }
116
117 /*
118  * Release a semaphore lock to end a critical section.
119  */
120 void end_critical_section(int which_one)
121 {
122         pthread_mutex_unlock(&Critters[which_one]);
123 }
124
125
126
127
128 /*
129  * Return a pointer to our thread-specific (not session-specific) data.
130  */ 
131 struct thread_tsd *MyThread(void) {
132         register struct thread_tsd *c;
133         return ((c = (struct thread_tsd *) pthread_getspecific(ThreadKey), c == NULL) ? &masterTSD : c);
134 }
135
136
137
138 /* 
139  * Called by CtdlThreadCreate()
140  * We have to pass through here before starting our thread in order to create a set of data
141  * that is thread-specific rather than session-specific.
142  */
143 void *CTC_backend(void *supplied_start_routine)
144 {
145         struct thread_tsd *mytsd;
146         void *(*start_routine)(void*) = supplied_start_routine;
147
148         mytsd = (struct thread_tsd *) malloc(sizeof(struct thread_tsd));
149         memset(mytsd, 0, sizeof(struct thread_tsd));
150         pthread_setspecific(ThreadKey, (const void *) mytsd);
151
152         start_routine(NULL);
153
154         free(mytsd);
155         return(NULL);
156 }
157
158  
159 /*
160  * Function to create a thread.
161  */ 
162 void CtdlThreadCreate(void *(*start_routine)(void*))
163 {
164         pthread_t thread;
165         pthread_attr_t attr;
166         int ret = 0;
167
168
169         ret = pthread_attr_init(&attr);
170         ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE);
171         ret = pthread_create(&thread, &attr, CTC_backend, (void *)start_routine);
172         if (ret != 0) syslog(LOG_EMERG, "pthread_create() : %s", strerror(errno));
173 }
174
175
176 void InitializeMasterTSD(void) {
177         memset(&masterTSD, 0, sizeof(struct thread_tsd));
178 }
179
180 extern void ShutDownEventQueues(void);
181
182 int EventQShuttingDown = 0;
183 int EVQShutDown = 0;
184 /*
185  * Initialize the thread system
186  */
187 void go_threading(void)
188 {
189         if (pthread_key_create(&ThreadKey, NULL) != 0) {
190                 syslog(LOG_EMERG, "pthread_key_create() : %s", strerror(errno));
191                 abort();
192         }
193
194         /* Second call to module init functions now that threading is up */
195         initialise_modules(1);
196
197         /* Begin with one worker thread.  We will expand the pool if necessary */
198         CtdlThreadCreate(worker_thread);
199
200         /* The supervisor thread monitors worker threads and spawns more of them if it finds that
201          * they are all in use.  FIXME make the 256 max threads a configurable value.
202          */
203         while (!server_shutting_down) {
204                 if ((active_workers == num_workers) && (num_workers < 256)) {
205                         CtdlThreadCreate(worker_thread);
206                 }
207                 usleep(1000000);
208         }
209
210         /* When we get to this point we are getting ready to shut down our Citadel server */
211         if (!EventQShuttingDown)
212         {
213                 EventQShuttingDown = 1;
214                 ShutDownEventQueues();
215         }
216         while (!EVQShutDown)
217                 usleep(1000000);
218
219
220         terminate_all_sessions();               /* close all client sockets */
221         CtdlShutdownServiceHooks();             /* close all listener sockets to prevent new connections */
222         PerformSessionHooks(EVT_SHUTDOWN);      /* run any registered shutdown hooks */
223
224         int countdown = 30;
225         while ( (num_workers > 0) && (countdown-- > 0)) {
226                 syslog(LOG_DEBUG, "Waiting %d seconds for %d worker threads to exit",
227                         countdown, num_workers
228                 );
229                 usleep(1000000);
230         }
231 }