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