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