228a5b0aa6f85b6e7f908481f6fe6ffe862b3daf
[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 <errno.h>
16 #include <stdio.h>
17 #include <syslog.h>
18 #include <libcitadel.h>
19 #include "modules_init.h"
20 #include "serv_extensions.h"
21 #include "ctdl_module.h"
22 #include "context.h"
23 #include "threads.h"
24
25
26 int num_workers = 0;                            /* Current number of worker threads */
27 int active_workers = 0;                         /* Number of ACTIVE worker threads */
28 pthread_key_t ThreadKey;
29 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
30 struct thread_tsd masterTSD;
31 int server_shutting_down = 0;                   /* set to nonzero during shutdown */
32
33 pthread_mutex_t ThreadCountMutex;;
34
35
36 void InitializeSemaphores(void)
37 {
38         int i;
39
40         /* Set up a bunch of semaphores to be used for critical sections */
41         for (i=0; i<MAX_SEMAPHORES; ++i) {
42                 pthread_mutex_init(&Critters[i], NULL);
43         }
44 }
45
46
47
48
49 /*
50  * Obtain a semaphore lock to begin a critical section.
51  * but only if no one else has one
52  */
53 int try_critical_section(int which_one)
54 {
55         /* For all types of critical sections except those listed here,
56          * ensure nobody ever tries to do a critical section within a
57          * transaction; this could lead to deadlock.
58          */
59         if (    (which_one != S_FLOORCACHE)
60                 && (which_one != S_RPLIST)
61         ) {
62                 cdb_check_handles();
63         }
64         return (pthread_mutex_trylock(&Critters[which_one]));
65 }
66
67
68 /*
69  * Obtain a semaphore lock to begin a critical section.
70  */
71 void begin_critical_section(int which_one)
72 {
73         /* For all types of critical sections except those listed here,
74          * ensure nobody ever tries to do a critical section within a
75          * transaction; this could lead to deadlock.
76          */
77         if (    (which_one != S_FLOORCACHE)
78                 && (which_one != S_RPLIST)
79         ) {
80                 cdb_check_handles();
81         }
82         pthread_mutex_lock(&Critters[which_one]);
83 }
84
85 /*
86  * Release a semaphore lock to end a critical section.
87  */
88 void end_critical_section(int which_one)
89 {
90         pthread_mutex_unlock(&Critters[which_one]);
91 }
92
93
94
95
96 /*
97  * Return a pointer to our thread-specific (not session-specific) data.
98  */ 
99 struct thread_tsd *MyThread(void) {
100         register struct thread_tsd *c;
101         return ((c = (struct thread_tsd *) pthread_getspecific(ThreadKey), c == NULL) ? &masterTSD : c);
102 }
103
104
105
106 /* 
107  * Called by CtdlThreadCreate()
108  * We have to pass through here before starting our thread in order to create a set of data
109  * that is thread-specific rather than session-specific.
110  */
111 void *CTC_backend(void *supplied_start_routine)
112 {
113         struct thread_tsd *mytsd;
114         void *(*start_routine)(void*) = supplied_start_routine;
115
116         mytsd = (struct thread_tsd *) malloc(sizeof(struct thread_tsd));
117         memset(mytsd, 0, sizeof(struct thread_tsd));
118         pthread_setspecific(ThreadKey, (const void *) mytsd);
119
120         start_routine(NULL);
121
122 //      free(mytsd);
123         return(NULL);
124 }
125
126  
127 /*
128  * Function to create a thread.
129  */ 
130 void CtdlThreadCreate(void *(*start_routine)(void*))
131 {
132         pthread_t thread;
133         pthread_attr_t attr;
134         int ret = 0;
135
136
137         ret = pthread_attr_init(&attr);
138         ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE);
139         ret = pthread_create(&thread, &attr, CTC_backend, (void *)start_routine);
140         if (ret != 0) syslog(LOG_EMERG, "pthread_create() : %s", strerror(errno));
141 }
142
143
144 void InitializeMasterTSD(void) {
145         memset(&masterTSD, 0, sizeof(struct thread_tsd));
146 }
147
148 extern void ShutDownEventQueues(void);
149
150 int EventQShuttingDown = 0;
151 int EVQShutDown = 0;
152 /*
153  * Initialize the thread system
154  */
155 void go_threading(void)
156 {
157         if (pthread_key_create(&ThreadKey, NULL) != 0) {
158                 syslog(LOG_EMERG, "pthread_key_create() : %s", strerror(errno));
159                 abort();
160         }
161
162         pthread_mutex_init(&ThreadCountMutex, NULL);
163
164         /* Second call to module init functions now that threading is up */
165         initialise_modules(1);
166
167         /* Begin with one worker thread.  We will expand the pool if necessary */
168         CtdlThreadCreate(worker_thread);
169
170         /* The supervisor thread monitors worker threads and spawns more of them if it finds that
171          * they are all in use.
172          */
173         while (!server_shutting_down) {
174                 if ((active_workers == num_workers) && (num_workers < config.c_max_workers)) {
175                         CtdlThreadCreate(worker_thread);
176                 }
177                 usleep(1000000);
178         }
179
180         /* When we get to this point we are getting ready to shut down our Citadel server */
181         if (!EventQShuttingDown)
182         {
183                 EventQShuttingDown = 1;
184                 ShutDownEventQueues();
185         }
186         while (!EVQShutDown)
187                 usleep(1000000);
188
189
190         terminate_all_sessions();               /* close all client sockets */
191         CtdlShutdownServiceHooks();             /* close all listener sockets to prevent new connections */
192         PerformSessionHooks(EVT_SHUTDOWN);      /* run any registered shutdown hooks */
193
194         int countdown = 30;
195         while ( (num_workers > 0) && (countdown-- > 0)) {
196                 syslog(LOG_DEBUG, "Waiting %d seconds for %d worker threads to exit",
197                         countdown, num_workers
198                 );
199                 usleep(1000000);
200         }
201 }