RX: Avoid timing out non-kernel busy channels
[openafs.git] / src / rx / rx_pthread.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11  * An implementation of the rx socket listener for pthreads (not using select).
12  * This assumes that multiple read system calls may be extant at any given
13  * time. Also implements the pthread-specific event handling for rx.
14  *
15  * rx_pthread.c is used for the thread safe RX package.
16  */
17
18 #include <afsconfig.h>
19 #include <afs/param.h>
20
21 #ifndef KERNEL
22 # include <roken.h>
23 #endif /* KERNEL */
24
25 #include <sys/types.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <string.h>
29 #ifdef HAVE_STDINT_H
30 # include <stdint.h>
31 #endif
32 #ifndef AFS_NT40_ENV
33 # include <sys/socket.h>
34 # include <sys/file.h>
35 # include <netdb.h>
36 # include <netinet/in.h>
37 # include <net/if.h>
38 # include <sys/ioctl.h>
39 # include <sys/time.h>
40 # include <unistd.h>
41 # include <assert.h>
42 #endif
43 #include <sys/stat.h>
44
45 #include "rx.h"
46 #include "rx_globals.h"
47 #include "rx_pthread.h"
48 #include "rx_clock.h"
49 #include "rx_atomic.h"
50
51 /* Set rx_pthread_event_rescheduled if event_handler should just try
52  * again instead of sleeping.
53  *
54  * Protected by event_handler_mutex
55  */
56 static int rx_pthread_event_rescheduled = 0;
57
58 static void *rx_ListenerProc(void *);
59
60 /*
61  * We supply an event handling thread for Rx's event processing.
62  * The condition variable is used to wakeup the thread whenever a new
63  * event is scheduled earlier than the previous earliest event.
64  * This thread is also responsible for keeping time.
65  */
66 static pthread_t event_handler_thread;
67 afs_kcondvar_t rx_event_handler_cond;
68 afs_kmutex_t event_handler_mutex;
69 afs_kcondvar_t rx_listener_cond;
70 afs_kmutex_t listener_mutex;
71 static int listeners_started = 0;
72 afs_kmutex_t rx_clock_mutex;
73 struct clock rxi_clockNow;
74
75 static rx_atomic_t threadHiNum;
76
77 int
78 rx_NewThreadId(void) {
79     return rx_atomic_inc_and_read(&threadHiNum);
80 }
81
82 /*
83  * Delay the current thread the specified number of seconds.
84  */
85 void
86 rxi_Delay(int sec)
87 {
88     sleep(sec);
89 }
90
91 /*
92  * Called from rx_Init()
93  */
94 void
95 rxi_InitializeThreadSupport(void)
96 {
97         /* listeners_started must only be reset if
98          * the listener thread terminates */
99         /* listeners_started = 0; */
100     clock_GetTime(&rxi_clockNow);
101 }
102
103 static void *
104 server_entry(void *argp)
105 {
106     void (*server_proc) (void *) = (void (*)(void *))argp;
107     server_proc(NULL);
108     dpf(("rx_pthread.c: server_entry: Server proc returned unexpectedly\n"));
109     return (void *) -1; /* reused as return value, see pthread(3) */
110 }
111
112 /*
113  * Start an Rx server process.
114  */
115 void
116 rxi_StartServerProc(void *(*proc) (void *), int stacksize)
117 {
118     pthread_t thread;
119     pthread_attr_t tattr;
120     AFS_SIGSET_DECL;
121
122     if (pthread_attr_init(&tattr) != 0) {
123         osi_Panic("Unable to Create Rx server thread (pthread_attr_init)\n");
124     }
125
126     if (pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) != 0) {
127         osi_Panic("Unable to Create Rx server thread (pthread_attr_setdetachstate)\n");
128     }
129
130     /*
131      * NOTE: We are ignoring the stack size parameter, for now.
132      */
133     AFS_SIGSET_CLEAR();
134     if (pthread_create(&thread, &tattr, server_entry, (void *)proc) != 0) {
135         osi_Panic("Unable to Create Rx server thread\n");
136     }
137     AFS_SIGSET_RESTORE();
138 }
139
140 /*
141  * The event handling process.
142  */
143 static void *
144 event_handler(void *argp)
145 {
146     unsigned long rx_pthread_n_event_expired = 0;
147     unsigned long rx_pthread_n_event_waits = 0;
148     long rx_pthread_n_event_woken = 0;
149     unsigned long rx_pthread_n_event_error = 0;
150     struct timespec rx_pthread_next_event_time = { 0, 0 };
151     int error;
152
153     MUTEX_ENTER(&event_handler_mutex);
154
155     for (;;) {
156         struct clock cv;
157         struct clock next;
158
159         MUTEX_EXIT(&event_handler_mutex);
160
161         next.sec = 30;          /* Time to sleep if there are no events scheduled */
162         next.usec = 0;
163         clock_GetTime(&cv);
164         rxevent_RaiseEvents(&next);
165
166         MUTEX_ENTER(&event_handler_mutex);
167         if (rx_pthread_event_rescheduled) {
168             rx_pthread_event_rescheduled = 0;
169             continue;
170         }
171
172         clock_Add(&cv, &next);
173         rx_pthread_next_event_time.tv_sec = cv.sec;
174         rx_pthread_next_event_time.tv_nsec = cv.usec * 1000;
175         rx_pthread_n_event_waits++;
176         error = CV_TIMEDWAIT(&rx_event_handler_cond, &event_handler_mutex, &rx_pthread_next_event_time);
177         if (error == 0) {
178             rx_pthread_n_event_woken++;
179         }
180 #ifdef AFS_NT40_ENV
181         else if (error == ETIMEDOUT) {
182             rx_pthread_n_event_expired++;
183         } else {
184             rx_pthread_n_event_error++;
185         }
186 #else
187         else if (errno == ETIMEDOUT) {
188             rx_pthread_n_event_expired++;
189         } else {
190             rx_pthread_n_event_error++;
191         }
192 #endif
193         rx_pthread_event_rescheduled = 0;
194     }
195     return NULL;
196 }
197
198
199 /*
200  * This routine will get called by the event package whenever a new,
201  * earlier than others, event is posted. */
202 void
203 rxi_ReScheduleEvents(void)
204 {
205     MUTEX_ENTER(&event_handler_mutex);
206     CV_SIGNAL(&rx_event_handler_cond);
207     rx_pthread_event_rescheduled = 1;
208     MUTEX_EXIT(&event_handler_mutex);
209 }
210
211
212 /* Loop to listen on a socket. Return setting *newcallp if this
213  * thread should become a server thread.  */
214 static void
215 rxi_ListenerProc(osi_socket sock, int *tnop, struct rx_call **newcallp)
216 {
217     unsigned int host;
218     u_short port;
219     struct rx_packet *p = (struct rx_packet *)0;
220
221     MUTEX_ENTER(&listener_mutex);
222     while (!listeners_started) {
223         CV_WAIT(&rx_listener_cond, &listener_mutex);
224     }
225     MUTEX_EXIT(&listener_mutex);
226
227     for (;;) {
228         /* See if a check for additional packets was issued */
229         rx_CheckPackets();
230
231         /*
232          * Grab a new packet only if necessary (otherwise re-use the old one)
233          */
234         if (p) {
235             rxi_RestoreDataBufs(p);
236         } else {
237             if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_RECEIVE))) {
238                 /* Could this happen with multiple socket listeners? */
239                 osi_Panic("rxi_Listener: no packets!"); /* Shouldn't happen */
240             }
241         }
242
243         if (rxi_ReadPacket(sock, p, &host, &port)) {
244             clock_NewTime();
245             p = rxi_ReceivePacket(p, sock, host, port, tnop, newcallp);
246             if (newcallp && *newcallp) {
247                 if (p)
248                     rxi_FreePacket(p);
249                 return;
250             }
251         }
252     }
253     /* NOTREACHED */
254 }
255
256 /* This is the listener process request loop. The listener process loop
257  * becomes a server thread when rxi_ListenerProc returns, and stays
258  * server thread until rxi_ServerProc returns. */
259 static void *
260 rx_ListenerProc(void *argp)
261 {
262     int threadID;
263     osi_socket sock = (osi_socket)(intptr_t)argp;
264     struct rx_call *newcall;
265
266     while (1) {
267         newcall = NULL;
268         threadID = -1;
269         rxi_ListenerProc(sock, &threadID, &newcall);
270         /* osi_Assert(threadID != -1); */
271         /* osi_Assert(newcall != NULL); */
272         sock = OSI_NULLSOCKET;
273         osi_Assert(pthread_setspecific(rx_thread_id_key, (void *)(intptr_t)threadID) == 0);
274         rxi_ServerProc(threadID, newcall, &sock);
275         /* osi_Assert(sock != OSI_NULLSOCKET); */
276     }
277     /* not reached */
278     return NULL;
279 }
280
281 /* This is the server process request loop. The server process loop
282  * becomes a listener thread when rxi_ServerProc returns, and stays
283  * listener thread until rxi_ListenerProc returns. */
284 void *
285 rx_ServerProc(void * dummy)
286 {
287     osi_socket sock;
288     int threadID;
289     struct rx_call *newcall = NULL;
290
291     rxi_MorePackets(rx_maxReceiveWindow + 2);   /* alloc more packets */
292     MUTEX_ENTER(&rx_quota_mutex);
293     rxi_dataQuota += rx_initSendWindow; /* Reserve some pkts for hard times */
294     /* threadID is used for making decisions in GetCall.  Get it by bumping
295      * number of threads handling incoming calls */
296     /* Unique thread ID: used for scheduling purposes *and* as index into
297      * the host hold table (fileserver).
298      * The previously used rxi_availProcs is unsuitable as it
299      * will already go up and down as packets arrive while the server
300      * threads are still initialising! The recently introduced
301      * rxi_pthread_hinum does not necessarily lead to a server
302      * thread with id 0, which is not allowed to hop through the
303      * incoming call queue.
304      * So either introduce yet another counter or flag the FCFS
305      * thread... chose the latter.
306      */
307     MUTEX_ENTER(&rx_pthread_mutex);
308     threadID = rx_NewThreadId();
309     if (rxi_fcfs_thread_num == 0 && rxi_fcfs_thread_num != threadID)
310         rxi_fcfs_thread_num = threadID;
311     MUTEX_EXIT(&rx_pthread_mutex);
312     ++rxi_availProcs;
313     MUTEX_EXIT(&rx_quota_mutex);
314
315     while (1) {
316         sock = OSI_NULLSOCKET;
317         osi_Assert(pthread_setspecific(rx_thread_id_key, (void *)(intptr_t)threadID) == 0);
318         rxi_ServerProc(threadID, newcall, &sock);
319         /* osi_Assert(sock != OSI_NULLSOCKET); */
320         newcall = NULL;
321         rxi_ListenerProc(sock, &threadID, &newcall);
322         /* osi_Assert(threadID != -1); */
323         /* osi_Assert(newcall != NULL); */
324     }
325     /* not reached */
326     return NULL;
327 }
328
329 /*
330  * Historically used to start the listener process. We now have multiple
331  * listener processes (one for each socket); these are started by GetUdpSocket.
332  *
333  * The event handling process *is* started here (the old listener used
334  * to also handle events). The listener threads can't actually start
335  * listening until rxi_StartListener is called because most of R may not
336  * be initialized when rxi_Listen is called.
337  */
338 void
339 rxi_StartListener(void)
340 {
341     pthread_attr_t tattr;
342     AFS_SIGSET_DECL;
343
344         if (listeners_started)
345                 return;
346
347     if (pthread_attr_init(&tattr) != 0) {
348         osi_Panic("Unable to create Rx event handling thread (pthread_attr_init)\n");
349     }
350
351     if (pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) != 0) {
352         osi_Panic("Unable to create Rx event handling thread (pthread_attr_setdetachstate)\n");
353     }
354
355     AFS_SIGSET_CLEAR();
356     if (pthread_create(&event_handler_thread, &tattr, event_handler, NULL) !=
357         0) {
358         osi_Panic("Unable to create Rx event handling thread\n");
359     }
360     rx_NewThreadId();
361     AFS_SIGSET_RESTORE();
362
363     MUTEX_ENTER(&listener_mutex);
364     CV_BROADCAST(&rx_listener_cond);
365     listeners_started = 1;
366     MUTEX_EXIT(&listener_mutex);
367
368 }
369
370 /*
371  * Listen on the specified socket.
372  */
373 int
374 rxi_Listen(osi_socket sock)
375 {
376     pthread_t thread;
377     pthread_attr_t tattr;
378     AFS_SIGSET_DECL;
379
380     if (pthread_attr_init(&tattr) != 0) {
381         osi_Panic("Unable to create socket listener thread (pthread_attr_init)\n");
382     }
383
384     if (pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) != 0) {
385         osi_Panic("Unable to create socket listener thread (pthread_attr_setdetachstate)\n");
386     }
387
388     AFS_SIGSET_CLEAR();
389     if (pthread_create(&thread, &tattr, rx_ListenerProc, (void *)(intptr_t)sock) != 0) {
390         osi_Panic("Unable to create socket listener thread\n");
391     }
392     rx_NewThreadId();
393     AFS_SIGSET_RESTORE();
394     return 0;
395 }
396
397
398 /*
399  * Recvmsg.
400  *
401  */
402 int
403 rxi_Recvmsg(osi_socket socket, struct msghdr *msg_p, int flags)
404 {
405     int ret;
406 #if defined(HAVE_LINUX_ERRQUEUE_H) && defined(ADAPT_PMTU)
407     while((rxi_HandleSocketError(socket)) > 0)
408       ;
409 #endif
410     ret = recvmsg(socket, msg_p, flags);
411     return ret;
412 }
413
414 /*
415  * Sendmsg.
416  */
417 int
418 rxi_Sendmsg(osi_socket socket, struct msghdr *msg_p, int flags)
419 {
420     int ret;
421     ret = sendmsg(socket, msg_p, flags);
422 #ifdef AFS_LINUX22_ENV
423     /* linux unfortunately returns ECONNREFUSED if the target port
424      * is no longer in use */
425     /* and EAGAIN if a UDP checksum is incorrect */
426     if (ret == -1 && errno != ECONNREFUSED && errno != EAGAIN) {
427 #else
428     if (ret == -1) {
429 #endif
430         dpf(("rxi_sendmsg failed, error %d\n", errno));
431         fflush(stdout);
432 #ifndef AFS_NT40_ENV
433         if (errno > 0)
434           return -errno;
435 #else
436             if (WSAGetLastError() > 0)
437               return -WSAGetLastError();
438 #endif
439         return -1;
440     }
441     return 0;
442 }
443
444 struct rx_ts_info_t * rx_ts_info_init(void) {
445     struct rx_ts_info_t * rx_ts_info;
446     rx_ts_info = (rx_ts_info_t *) malloc(sizeof(rx_ts_info_t));
447     osi_Assert(rx_ts_info != NULL && pthread_setspecific(rx_ts_info_key, rx_ts_info) == 0);
448     memset(rx_ts_info, 0, sizeof(rx_ts_info_t));
449 #ifdef RX_ENABLE_TSFPQ
450     queue_Init(&rx_ts_info->_FPQ);
451
452     MUTEX_ENTER(&rx_packets_mutex);
453     rx_TSFPQMaxProcs++;
454     RX_TS_FPQ_COMPUTE_LIMITS;
455     MUTEX_EXIT(&rx_packets_mutex);
456 #endif /* RX_ENABLE_TSFPQ */
457     return rx_ts_info;
458 }