r3314: added a option "socket:testnonblock" to the generic socket code. If
[bbaumbach/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         NTSTATUS status;
53         struct socket_context *sock;
54         int rc;
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         status = socket_accept(server_socket->socket, &sock);
62         if (!NT_STATUS_IS_OK(status)) {
63                 DEBUG(0,("accept_connection_single: accept: %s\n",
64                          nt_errstr(status)));
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         ev = event_context_init(server_socket);
76         if (!ev) {
77                 DEBUG(0,("thread_accept_connection: failed to create event_context!\n"));
78                 socket_destroy(sock);
79                 return; 
80         }
81
82         conn = server_setup_connection(ev, server_socket, sock, t, pthread_self());
83         if (!conn) {
84                 DEBUG(0,("server_setup_connection(ev, server_socket, sock, t) failed\n"));
85                 event_context_destroy(ev);
86                 socket_destroy(sock);
87                 return;
88         }
89
90         talloc_steal(conn, ev);
91         talloc_steal(conn, sock);
92
93         /* TODO: is this MUTEX_LOCK in the right place here?
94          *       --metze
95          */
96         MUTEX_LOCK_BY_ID(MUTEX_SMBD);
97         DLIST_ADD(server_socket->connection_list,conn);
98         MUTEX_UNLOCK_BY_ID(MUTEX_SMBD);
99         
100         pthread_attr_init(&thread_attr);
101         pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
102         rc = pthread_create(&thread_id, &thread_attr, thread_connection_fn, ev);
103         pthread_attr_destroy(&thread_attr);
104         if (rc == 0) {
105                 DEBUG(4,("accept_connection_thread: created thread_id=%lu for fd=%d\n", 
106                         (unsigned long int)thread_id, socket_get_fd(sock)));
107         } else {
108                 DEBUG(0,("accept_connection_thread: thread create failed for fd=%d, rc=%d\n", socket_get_fd(sock), rc));
109                 event_context_destroy(ev);
110                 socket_destroy(sock);
111                 return;
112         }
113 }
114
115 /* called when a SMB connection goes down */
116 static void thread_terminate_connection(struct server_connection *conn, const char *reason) 
117 {
118         DEBUG(0,("thread_terminate_connection: reason[%s]\n",reason));
119
120         if (conn) {
121                 talloc_free(conn);
122         }
123
124         /* terminate this thread */
125         pthread_exit(NULL);  /* thread cleanup routine will do actual cleanup */
126 }
127
128 /*
129   mutex init function for thread model
130 */
131 static int thread_mutex_init(smb_mutex_t *mutex, const char *name)
132 {
133         pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
134         mutex->mutex = memdup(&m, sizeof(m));
135         if (! mutex->mutex) {
136                 errno = ENOMEM;
137                 return -1;
138         }
139         return pthread_mutex_init((pthread_mutex_t *)mutex->mutex, NULL);
140 }
141
142 /*
143   mutex destroy function for thread model
144 */
145 static int thread_mutex_destroy(smb_mutex_t *mutex, const char *name)
146 {
147         return pthread_mutex_destroy((pthread_mutex_t *)mutex->mutex);
148 }
149
150 static void mutex_start_timer(struct timeval *tp1)
151 {
152         gettimeofday(tp1,NULL);
153 }
154
155 static double mutex_end_timer(struct timeval tp1)
156 {
157         struct timeval tp2;
158         gettimeofday(&tp2,NULL);
159         return((tp2.tv_sec - tp1.tv_sec) + 
160                (tp2.tv_usec - tp1.tv_usec)*1.0e-6);
161 }
162
163 /*
164   mutex lock function for thread model
165 */
166 static int thread_mutex_lock(smb_mutex_t *mutexP, const char *name)
167 {
168         pthread_mutex_t *mutex = (pthread_mutex_t *)mutexP->mutex;
169         int rc;
170         double t;
171         struct timeval tp1;
172         /* Test below is ONLY for debugging */
173         if ((rc = pthread_mutex_trylock(mutex))) {
174                 if (rc == EBUSY) {
175                         mutex_start_timer(&tp1);
176                         printf("mutex lock: thread %d, lock %s not available\n", 
177                                 (uint32_t)pthread_self(), name);
178                         print_suspicious_usage("mutex_lock", name);
179                         pthread_mutex_lock(mutex);
180                         t = mutex_end_timer(tp1);
181                         printf("mutex lock: thread %d, lock %s now available, waited %g seconds\n", 
182                                 (uint32_t)pthread_self(), name, t);
183                         return 0;
184                 }
185                 printf("mutex lock: thread %d, lock %s failed rc=%d\n", 
186                                 (uint32_t)pthread_self(), name, rc);
187                 SMB_ASSERT(errno == 0); /* force error */
188         }
189         return 0;
190 }
191
192 /* 
193    mutex unlock for thread model
194 */
195 static int thread_mutex_unlock(smb_mutex_t *mutex, const char *name)
196 {
197         return pthread_mutex_unlock((pthread_mutex_t *)mutex->mutex);
198 }
199
200 /*****************************************************************
201  Read/write lock routines.
202 *****************************************************************/  
203 /*
204   rwlock init function for thread model
205 */
206 static int thread_rwlock_init(smb_rwlock_t *rwlock, const char *name)
207 {
208         pthread_rwlock_t m = PTHREAD_RWLOCK_INITIALIZER;
209         rwlock->rwlock = memdup(&m, sizeof(m));
210         if (! rwlock->rwlock) {
211                 errno = ENOMEM;
212                 return -1;
213         }
214         return pthread_rwlock_init((pthread_rwlock_t *)rwlock->rwlock, NULL);
215 }
216
217 /*
218   rwlock destroy function for thread model
219 */
220 static int thread_rwlock_destroy(smb_rwlock_t *rwlock, const char *name)
221 {
222         return pthread_rwlock_destroy((pthread_rwlock_t *)rwlock->rwlock);
223 }
224
225 /*
226   rwlock lock for read function for thread model
227 */
228 static int thread_rwlock_lock_read(smb_rwlock_t *rwlockP, const char *name)
229 {
230         pthread_rwlock_t *rwlock = (pthread_rwlock_t *)rwlockP->rwlock;
231         int rc;
232         double t;
233         struct timeval tp1;
234         /* Test below is ONLY for debugging */
235         if ((rc = pthread_rwlock_tryrdlock(rwlock))) {
236                 if (rc == EBUSY) {
237                         mutex_start_timer(&tp1);
238                         printf("rwlock lock_read: thread %d, lock %s not available\n", 
239                                 (uint32_t)pthread_self(), name);
240                         print_suspicious_usage("rwlock_lock_read", name);
241                         pthread_rwlock_rdlock(rwlock);
242                         t = mutex_end_timer(tp1);
243                         printf("rwlock lock_read: thread %d, lock %s now available, waited %g seconds\n", 
244                                 (uint32_t)pthread_self(), name, t);
245                         return 0;
246                 }
247                 printf("rwlock lock_read: thread %d, lock %s failed rc=%d\n", 
248                                 (uint32_t)pthread_self(), name, rc);
249                 SMB_ASSERT(errno == 0); /* force error */
250         }
251         return 0;
252 }
253
254 /*
255   rwlock lock for write function for thread model
256 */
257 static int thread_rwlock_lock_write(smb_rwlock_t *rwlockP, const char *name)
258 {
259         pthread_rwlock_t *rwlock = (pthread_rwlock_t *)rwlockP->rwlock;
260         int rc;
261         double t;
262         struct timeval tp1;
263         /* Test below is ONLY for debugging */
264         if ((rc = pthread_rwlock_trywrlock(rwlock))) {
265                 if (rc == EBUSY) {
266                         mutex_start_timer(&tp1);
267                         printf("rwlock lock_write: thread %d, lock %s not available\n", 
268                                 (uint32_t)pthread_self(), name);
269                         print_suspicious_usage("rwlock_lock_write", name);
270                         pthread_rwlock_wrlock(rwlock);
271                         t = mutex_end_timer(tp1);
272                         printf("rwlock lock_write: thread %d, lock %s now available, waited %g seconds\n", 
273                                 (uint32_t)pthread_self(), name, t);
274                         return 0;
275                 }
276                 printf("rwlock lock_write: thread %d, lock %s failed rc=%d\n", 
277                                 (uint32_t)pthread_self(), name, rc);
278                 SMB_ASSERT(errno == 0); /* force error */
279         }
280         return 0;
281 }
282
283
284 /* 
285    rwlock unlock for thread model
286 */
287 static int thread_rwlock_unlock(smb_rwlock_t *rwlock, const char *name)
288 {
289         return pthread_rwlock_unlock((pthread_rwlock_t *)rwlock->rwlock);
290 }
291
292 /*****************************************************************
293  Log suspicious usage (primarily for possible thread-unsafe behavior.
294 *****************************************************************/  
295 static void thread_log_suspicious_usage(const char* from, const char* info)
296 {
297         DEBUG(1,("log_suspicious_usage: from %s info='%s'\n", from, info));
298 #ifdef HAVE_BACKTRACE
299         {
300                 void *addresses[10];
301                 int num_addresses = backtrace(addresses, 8);
302                 char **bt_symbols = backtrace_symbols(addresses, num_addresses);
303                 int i;
304
305                 if (bt_symbols) {
306                         for (i=0; i<num_addresses; i++) {
307                                 DEBUG(1,("log_suspicious_usage: %s%s\n", DEBUGTAB(1), bt_symbols[i]));
308                         }
309                         free(bt_symbols);
310                 }
311         }
312 #endif
313 }
314
315 /*****************************************************************
316  Log suspicious usage to stdout (primarily for possible thread-unsafe behavior.
317  Used in mutex code where DEBUG calls would cause recursion.
318 *****************************************************************/  
319 static void thread_print_suspicious_usage(const char* from, const char* info)
320 {
321         printf("log_suspicious_usage: from %s info='%s'\n", from, info);
322 #ifdef HAVE_BACKTRACE
323         {
324                 void *addresses[10];
325                 int num_addresses = backtrace(addresses, 8);
326                 char **bt_symbols = backtrace_symbols(addresses, num_addresses);
327                 int i;
328
329                 if (bt_symbols) {
330                         for (i=0; i<num_addresses; i++) {
331                                 printf("log_suspicious_usage: %s%s\n", DEBUGTAB(1), bt_symbols[i]);
332                         }
333                         free(bt_symbols);
334                 }
335         }
336 #endif
337 }
338
339 static uint32_t thread_get_task_id(void)
340 {
341         return (uint32_t)pthread_self();
342 }
343
344 static void thread_log_task_id(int fd)
345 {
346         char *s;
347         
348         asprintf(&s, "thread %u: ", (uint32_t)pthread_self());
349         write(fd, s, strlen(s));
350         free(s);
351 }
352 /****************************************************************************
353 catch serious errors
354 ****************************************************************************/
355 static void thread_sig_fault(int sig)
356 {
357         DEBUG(0,("===============================================================\n"));
358         DEBUG(0,("TERMINAL ERROR: Recursive signal %d in thread %lu (%s)\n",sig,(unsigned long int)pthread_self(),SAMBA_VERSION_STRING));
359         DEBUG(0,("===============================================================\n"));
360         exit(1); /* kill the whole server for now */
361 }
362
363 /*******************************************************************
364 setup our recursive fault handlers
365 ********************************************************************/
366 static void thread_fault_setup(void)
367 {
368 #ifdef SIGSEGV
369         CatchSignal(SIGSEGV,SIGNAL_CAST thread_sig_fault);
370 #endif
371 #ifdef SIGBUS
372         CatchSignal(SIGBUS,SIGNAL_CAST thread_sig_fault);
373 #endif
374 #ifdef SIGABRT
375         CatchSignal(SIGABRT,SIGNAL_CAST thread_sig_fault);
376 #endif
377 }
378
379 /*******************************************************************
380 report a fault in a thread
381 ********************************************************************/
382 static void thread_fault_handler(int sig)
383 {
384         static int counter;
385         
386         /* try to catch recursive faults */
387         thread_fault_setup();
388         
389         counter++;      /* count number of faults that have occurred */
390
391         DEBUG(0,("===============================================================\n"));
392         DEBUG(0,("INTERNAL ERROR: Signal %d in thread %lu (%s)\n",sig,(unsigned long int)pthread_self(),SAMBA_VERSION_STRING));
393         DEBUG(0,("Please read the file BUGS.txt in the distribution\n"));
394         DEBUG(0,("===============================================================\n"));
395 #ifdef HAVE_BACKTRACE
396         {
397                 void *addresses[10];
398                 int num_addresses = backtrace(addresses, 8);
399                 char **bt_symbols = backtrace_symbols(addresses, num_addresses);
400                 int i;
401
402                 if (bt_symbols) {
403                         for (i=0; i<num_addresses; i++) {
404                                 DEBUG(1,("fault_report: %s%s\n", DEBUGTAB(1), bt_symbols[i]));
405                         }
406                         free(bt_symbols);
407                 }
408         }
409 #endif
410         pthread_exit(NULL); /* terminate failing thread only */
411 }
412
413 /*
414   called when the process model is selected
415 */
416 static void thread_model_startup(void)
417 {
418         struct mutex_ops m_ops;
419         struct debug_ops d_ops;
420
421         ZERO_STRUCT(m_ops);
422         ZERO_STRUCT(d_ops);
423
424         smbd_process_init();
425
426         /* register mutex/rwlock handlers */
427         m_ops.mutex_init = thread_mutex_init;
428         m_ops.mutex_lock = thread_mutex_lock;
429         m_ops.mutex_unlock = thread_mutex_unlock;
430         m_ops.mutex_destroy = thread_mutex_destroy;
431         
432         m_ops.rwlock_init = thread_rwlock_init;
433         m_ops.rwlock_lock_write = thread_rwlock_lock_write;
434         m_ops.rwlock_lock_read = thread_rwlock_lock_read;
435         m_ops.rwlock_unlock = thread_rwlock_unlock;
436         m_ops.rwlock_destroy = thread_rwlock_destroy;
437
438         register_mutex_handlers("thread", &m_ops);
439
440         register_fault_handler("thread", thread_fault_handler);
441
442         d_ops.log_suspicious_usage = thread_log_suspicious_usage;
443         d_ops.print_suspicious_usage = thread_print_suspicious_usage;
444         d_ops.get_task_id = thread_get_task_id;
445         d_ops.log_task_id = thread_log_task_id;
446
447         register_debug_handlers("thread", &d_ops);      
448 }
449
450 static void thread_exit_server(struct server_context *srv_ctx, const char *reason)
451 {
452         DEBUG(1,("thread_exit_server: reason[%s]\n",reason));
453 }
454
455 /*
456   initialise the thread process model, registering ourselves with the model subsystem
457  */
458 NTSTATUS process_model_thread_init(void)
459 {
460         NTSTATUS ret;
461         struct model_ops ops;
462
463         ZERO_STRUCT(ops);
464
465         /* fill in our name */
466         ops.name = "thread";
467
468         /* fill in all the operations */
469         ops.model_startup = thread_model_startup;
470         ops.accept_connection = thread_accept_connection;
471         ops.terminate_connection = thread_terminate_connection;
472         ops.exit_server = thread_exit_server;
473         ops.get_id = thread_get_id;
474
475         /* register ourselves with the PROCESS_MODEL subsystem. */
476         ret = register_backend("process_model", &ops);
477         if (!NT_STATUS_IS_OK(ret)) {
478                 DEBUG(0,("Failed to register process_model 'thread'!\n"));
479                 return ret;
480         }
481
482         return ret;
483 }