r1515: move dublicate code to a function
[garming/samba-autobuild/.git] / source4 / smbd / process_thread.c
1 /* 
2    Unix SMB/CIFS implementation.
3    thread model: standard (1 thread per client connection)
4    Copyright (C) Andrew Tridgell 2003
5    Copyright (C) James J Myers 2003 <myersjj@samba.org>
6    Copyright (C) Stefan (metze) Metzmacher 2004
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24 #include "pthread.h"
25 #ifdef HAVE_BACKTRACE
26 #include "execinfo.h"
27 #endif
28
29 static void *thread_connection_fn(void *thread_parm)
30 {
31         struct event_context *ev = thread_parm;
32         /* wait for action */
33         event_loop_wait(ev);
34
35 #if 0
36         pthread_cleanup_pop(1);  /* will invoke terminate_mt_connection() */
37 #endif
38         return NULL;
39 }
40
41 static int thread_get_id(struct smbsrv_request *req)
42 {
43         return (int)pthread_self();
44 }
45
46 /*
47   called when a listening socket becomes readable
48 */
49 static void thread_accept_connection(struct event_context *ev, struct fd_event *srv_fde, 
50                               time_t t, uint16_t flags)
51 {               
52         int accepted_fd, rc;
53         struct sockaddr addr;
54         socklen_t in_addrlen = sizeof(addr);
55         pthread_t thread_id;
56         pthread_attr_t thread_attr;
57         struct server_socket *server_socket = srv_fde->private;
58         struct server_connection *conn;
59
60         /* accept an incoming connection. */
61         accepted_fd = accept(srv_fde->fd,&addr,&in_addrlen);
62         if (accepted_fd == -1) {
63                 DEBUG(0,("standard_accept_connection: accept: %s\n",
64                          strerror(errno)));
65                 return;
66         }
67         
68         /* create new detached thread for this connection.  The new
69            thread gets a new event_context with a single fd_event for
70            receiving from the new socket. We set that thread running
71            with the main event loop, then return. When we return the
72            main event_context is continued.
73         */
74
75
76         ev = event_context_init();
77         if (!ev) {
78                 DEBUG(0,("thread_accept_connection: failed to create event_context!\n"));
79                 return; 
80         }
81
82         conn = server_setup_connection(ev, server_socket, accepted_fd, t);
83         if (!conn) {
84                 DEBUG(0,("server_setup_connection(ev, server_socket, accepted_fd) failed\n"));
85                 return;
86         }
87
88         /* TODO: is this MUTEX_LOCK in the right place here?
89          *       --metze
90          */
91         MUTEX_LOCK_BY_ID(MUTEX_SMBD);
92         DLIST_ADD(server_socket->connection_list,conn);
93         MUTEX_UNLOCK_BY_ID(MUTEX_SMBD);
94         
95         pthread_attr_init(&thread_attr);
96         pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
97         rc = pthread_create(&thread_id, &thread_attr, thread_connection_fn, ev);
98         pthread_attr_destroy(&thread_attr);
99         if (rc == 0) {
100                 DEBUG(4,("accept_connection_thread: created thread_id=%lu for fd=%d\n", 
101                         (unsigned long int)thread_id, accepted_fd));
102         } else {
103                 DEBUG(0,("accept_connection_thread: thread create failed for fd=%d, rc=%d\n", accepted_fd, rc));
104         }
105 }
106
107 /* called when a SMB connection goes down */
108 static void thread_terminate_connection(struct server_connection *conn, const char *reason) 
109 {
110         DEBUG(0,("thread_terminate_connection: reason[%s]\n",reason));
111         conn->service->ops->close_connection(conn,reason);
112         server_destroy_connection(conn);
113         /* terminate this thread */
114         pthread_exit(NULL);  /* thread cleanup routine will do actual cleanup */
115 }
116
117 /*
118   mutex init function for thread model
119 */
120 static int thread_mutex_init(smb_mutex_t *mutex, const char *name)
121 {
122         pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
123         mutex->mutex = memdup(&m, sizeof(m));
124         if (! mutex->mutex) {
125                 errno = ENOMEM;
126                 return -1;
127         }
128         return pthread_mutex_init((pthread_mutex_t *)mutex->mutex, NULL);
129 }
130
131 /*
132   mutex destroy function for thread model
133 */
134 static int thread_mutex_destroy(smb_mutex_t *mutex, const char *name)
135 {
136         return pthread_mutex_destroy((pthread_mutex_t *)mutex->mutex);
137 }
138
139 static void mutex_start_timer(struct timeval *tp1)
140 {
141         gettimeofday(tp1,NULL);
142 }
143
144 static double mutex_end_timer(struct timeval tp1)
145 {
146         struct timeval tp2;
147         gettimeofday(&tp2,NULL);
148         return((tp2.tv_sec - tp1.tv_sec) + 
149                (tp2.tv_usec - tp1.tv_usec)*1.0e-6);
150 }
151
152 /*
153   mutex lock function for thread model
154 */
155 static int thread_mutex_lock(smb_mutex_t *mutexP, const char *name)
156 {
157         pthread_mutex_t *mutex = (pthread_mutex_t *)mutexP->mutex;
158         int rc;
159         double t;
160         struct timeval tp1;
161         /* Test below is ONLY for debugging */
162         if ((rc = pthread_mutex_trylock(mutex))) {
163                 if (rc == EBUSY) {
164                         mutex_start_timer(&tp1);
165                         printf("mutex lock: thread %d, lock %s not available\n", 
166                                 (uint32_t)pthread_self(), name);
167                         print_suspicious_usage("mutex_lock", name);
168                         pthread_mutex_lock(mutex);
169                         t = mutex_end_timer(tp1);
170                         printf("mutex lock: thread %d, lock %s now available, waited %g seconds\n", 
171                                 (uint32_t)pthread_self(), name, t);
172                         return 0;
173                 }
174                 printf("mutex lock: thread %d, lock %s failed rc=%d\n", 
175                                 (uint32_t)pthread_self(), name, rc);
176                 SMB_ASSERT(errno == 0); /* force error */
177         }
178         return 0;
179 }
180
181 /* 
182    mutex unlock for thread model
183 */
184 static int thread_mutex_unlock(smb_mutex_t *mutex, const char *name)
185 {
186         return pthread_mutex_unlock((pthread_mutex_t *)mutex->mutex);
187 }
188
189 /*****************************************************************
190  Read/write lock routines.
191 *****************************************************************/  
192 /*
193   rwlock init function for thread model
194 */
195 static int thread_rwlock_init(smb_rwlock_t *rwlock, const char *name)
196 {
197         pthread_rwlock_t m = PTHREAD_RWLOCK_INITIALIZER;
198         rwlock->rwlock = memdup(&m, sizeof(m));
199         if (! rwlock->rwlock) {
200                 errno = ENOMEM;
201                 return -1;
202         }
203         return pthread_rwlock_init((pthread_rwlock_t *)rwlock->rwlock, NULL);
204 }
205
206 /*
207   rwlock destroy function for thread model
208 */
209 static int thread_rwlock_destroy(smb_rwlock_t *rwlock, const char *name)
210 {
211         return pthread_rwlock_destroy((pthread_rwlock_t *)rwlock->rwlock);
212 }
213
214 /*
215   rwlock lock for read function for thread model
216 */
217 static int thread_rwlock_lock_read(smb_rwlock_t *rwlockP, const char *name)
218 {
219         pthread_rwlock_t *rwlock = (pthread_rwlock_t *)rwlockP->rwlock;
220         int rc;
221         double t;
222         struct timeval tp1;
223         /* Test below is ONLY for debugging */
224         if ((rc = pthread_rwlock_tryrdlock(rwlock))) {
225                 if (rc == EBUSY) {
226                         mutex_start_timer(&tp1);
227                         printf("rwlock lock_read: thread %d, lock %s not available\n", 
228                                 (uint32_t)pthread_self(), name);
229                         print_suspicious_usage("rwlock_lock_read", name);
230                         pthread_rwlock_rdlock(rwlock);
231                         t = mutex_end_timer(tp1);
232                         printf("rwlock lock_read: thread %d, lock %s now available, waited %g seconds\n", 
233                                 (uint32_t)pthread_self(), name, t);
234                         return 0;
235                 }
236                 printf("rwlock lock_read: thread %d, lock %s failed rc=%d\n", 
237                                 (uint32_t)pthread_self(), name, rc);
238                 SMB_ASSERT(errno == 0); /* force error */
239         }
240         return 0;
241 }
242
243 /*
244   rwlock lock for write function for thread model
245 */
246 static int thread_rwlock_lock_write(smb_rwlock_t *rwlockP, const char *name)
247 {
248         pthread_rwlock_t *rwlock = (pthread_rwlock_t *)rwlockP->rwlock;
249         int rc;
250         double t;
251         struct timeval tp1;
252         /* Test below is ONLY for debugging */
253         if ((rc = pthread_rwlock_trywrlock(rwlock))) {
254                 if (rc == EBUSY) {
255                         mutex_start_timer(&tp1);
256                         printf("rwlock lock_write: thread %d, lock %s not available\n", 
257                                 (uint32_t)pthread_self(), name);
258                         print_suspicious_usage("rwlock_lock_write", name);
259                         pthread_rwlock_wrlock(rwlock);
260                         t = mutex_end_timer(tp1);
261                         printf("rwlock lock_write: thread %d, lock %s now available, waited %g seconds\n", 
262                                 (uint32_t)pthread_self(), name, t);
263                         return 0;
264                 }
265                 printf("rwlock lock_write: thread %d, lock %s failed rc=%d\n", 
266                                 (uint32_t)pthread_self(), name, rc);
267                 SMB_ASSERT(errno == 0); /* force error */
268         }
269         return 0;
270 }
271
272
273 /* 
274    rwlock unlock for thread model
275 */
276 static int thread_rwlock_unlock(smb_rwlock_t *rwlock, const char *name)
277 {
278         return pthread_rwlock_unlock((pthread_rwlock_t *)rwlock->rwlock);
279 }
280
281 /*****************************************************************
282  Log suspicious usage (primarily for possible thread-unsafe behavior.
283 *****************************************************************/  
284 static void thread_log_suspicious_usage(const char* from, const char* info)
285 {
286         DEBUG(1,("log_suspicious_usage: from %s info='%s'\n", from, info));
287 #ifdef HAVE_BACKTRACE
288         {
289                 void *addresses[10];
290                 int num_addresses = backtrace(addresses, 8);
291                 char **bt_symbols = backtrace_symbols(addresses, num_addresses);
292                 int i;
293
294                 if (bt_symbols) {
295                         for (i=0; i<num_addresses; i++) {
296                                 DEBUG(1,("log_suspicious_usage: %s%s\n", DEBUGTAB(1), bt_symbols[i]));
297                         }
298                         free(bt_symbols);
299                 }
300         }
301 #endif
302 }
303
304 /*****************************************************************
305  Log suspicious usage to stdout (primarily for possible thread-unsafe behavior.
306  Used in mutex code where DEBUG calls would cause recursion.
307 *****************************************************************/  
308 static void thread_print_suspicious_usage(const char* from, const char* info)
309 {
310         printf("log_suspicious_usage: from %s info='%s'\n", from, info);
311 #ifdef HAVE_BACKTRACE
312         {
313                 void *addresses[10];
314                 int num_addresses = backtrace(addresses, 8);
315                 char **bt_symbols = backtrace_symbols(addresses, num_addresses);
316                 int i;
317
318                 if (bt_symbols) {
319                         for (i=0; i<num_addresses; i++) {
320                                 printf("log_suspicious_usage: %s%s\n", DEBUGTAB(1), bt_symbols[i]);
321                         }
322                         free(bt_symbols);
323                 }
324         }
325 #endif
326 }
327
328 static uint32_t thread_get_task_id(void)
329 {
330         return (uint32_t)pthread_self();
331 }
332
333 static void thread_log_task_id(int fd)
334 {
335         char *s;
336         
337         asprintf(&s, "thread %u: ", (uint32_t)pthread_self());
338         write(fd, s, strlen(s));
339         free(s);
340 }
341 /****************************************************************************
342 catch serious errors
343 ****************************************************************************/
344 static void thread_sig_fault(int sig)
345 {
346         DEBUG(0,("===============================================================\n"));
347         DEBUG(0,("TERMINAL ERROR: Recursive signal %d in thread %lu (%s)\n",sig,(unsigned long int)pthread_self(),SAMBA_VERSION_STRING));
348         DEBUG(0,("===============================================================\n"));
349         exit(1); /* kill the whole server for now */
350 }
351
352 /*******************************************************************
353 setup our recursive fault handlers
354 ********************************************************************/
355 static void thread_fault_setup(void)
356 {
357 #ifdef SIGSEGV
358         CatchSignal(SIGSEGV,SIGNAL_CAST thread_sig_fault);
359 #endif
360 #ifdef SIGBUS
361         CatchSignal(SIGBUS,SIGNAL_CAST thread_sig_fault);
362 #endif
363 #ifdef SIGABRT
364         CatchSignal(SIGABRT,SIGNAL_CAST thread_sig_fault);
365 #endif
366 }
367
368 /*******************************************************************
369 report a fault in a thread
370 ********************************************************************/
371 static void thread_fault_handler(int sig)
372 {
373         static int counter;
374         
375         /* try to catch recursive faults */
376         thread_fault_setup();
377         
378         counter++;      /* count number of faults that have occurred */
379
380         DEBUG(0,("===============================================================\n"));
381         DEBUG(0,("INTERNAL ERROR: Signal %d in thread %lu (%s)\n",sig,(unsigned long int)pthread_self(),SAMBA_VERSION_STRING));
382         DEBUG(0,("Please read the file BUGS.txt in the distribution\n"));
383         DEBUG(0,("===============================================================\n"));
384 #ifdef HAVE_BACKTRACE
385         {
386                 void *addresses[10];
387                 int num_addresses = backtrace(addresses, 8);
388                 char **bt_symbols = backtrace_symbols(addresses, num_addresses);
389                 int i;
390
391                 if (bt_symbols) {
392                         for (i=0; i<num_addresses; i++) {
393                                 DEBUG(1,("fault_report: %s%s\n", DEBUGTAB(1), bt_symbols[i]));
394                         }
395                         free(bt_symbols);
396                 }
397         }
398 #endif
399         pthread_exit(NULL); /* terminate failing thread only */
400 }
401
402 /*
403   called when the process model is selected
404 */
405 static void thread_model_startup(void)
406 {
407         struct mutex_ops m_ops;
408         struct debug_ops d_ops;
409
410         ZERO_STRUCT(m_ops);
411         ZERO_STRUCT(d_ops);
412
413         smbd_process_init();
414
415         /* register mutex/rwlock handlers */
416         m_ops.mutex_init = thread_mutex_init;
417         m_ops.mutex_lock = thread_mutex_lock;
418         m_ops.mutex_unlock = thread_mutex_unlock;
419         m_ops.mutex_destroy = thread_mutex_destroy;
420         
421         m_ops.rwlock_init = thread_rwlock_init;
422         m_ops.rwlock_lock_write = thread_rwlock_lock_write;
423         m_ops.rwlock_lock_read = thread_rwlock_lock_read;
424         m_ops.rwlock_unlock = thread_rwlock_unlock;
425         m_ops.rwlock_destroy = thread_rwlock_destroy;
426
427         register_mutex_handlers("thread", &m_ops);
428
429         register_fault_handler("thread", thread_fault_handler);
430
431         d_ops.log_suspicious_usage = thread_log_suspicious_usage;
432         d_ops.print_suspicious_usage = thread_print_suspicious_usage;
433         d_ops.get_task_id = thread_get_task_id;
434         d_ops.log_task_id = thread_log_task_id;
435
436         register_debug_handlers("thread", &d_ops);      
437 }
438
439 static void thread_exit_server(struct server_context *srv_ctx, const char *reason)
440 {
441         DEBUG(1,("thread_exit_server: reason[%s]\n",reason));
442 }
443
444 /*
445   initialise the thread process model, registering ourselves with the model subsystem
446  */
447 NTSTATUS process_model_thread_init(void)
448 {
449         NTSTATUS ret;
450         struct model_ops ops;
451
452         ZERO_STRUCT(ops);
453
454         /* fill in our name */
455         ops.name = "thread";
456
457         /* fill in all the operations */
458         ops.model_startup = thread_model_startup;
459         ops.accept_connection = thread_accept_connection;
460         ops.terminate_connection = thread_terminate_connection;
461         ops.exit_server = thread_exit_server;
462         ops.get_id = thread_get_id;
463
464         /* register ourselves with the PROCESS_MODEL subsystem. */
465         ret = register_backend("process_model", &ops);
466         if (!NT_STATUS_IS_OK(ret)) {
467                 DEBUG(0,("Failed to register process_model 'thread'!\n"));
468                 return ret;
469         }
470
471         return ret;
472 }