b5cc1daa1ea31cdde9bc13462240383d5958d089
[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 RCSID
22     ("$Header$");
23
24 #include <sys/types.h>
25 #include <errno.h>
26 #include <signal.h>
27 #ifndef AFS_NT40_ENV
28 # include <sys/socket.h>
29 # include <sys/file.h>
30 # include <netdb.h>
31 # include <netinet/in.h>
32 # include <net/if.h>
33 # include <sys/ioctl.h>
34 # include <sys/time.h>
35 #endif
36 #include <sys/stat.h>
37 #include <rx/rx.h>
38 #include <rx/rx_globals.h>
39 #include <assert.h>
40 #include <rx/rx_pthread.h>
41 #include <rx/rx_clock.h>
42
43 /*
44  * Number of times the event handling thread was signalled because a new
45  * event was scheduled earlier than the lastest event.
46  *
47  * Protected by event_handler_mutex
48  */
49 static long rx_pthread_n_event_wakeups;
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 pthread_cond_t rx_event_handler_cond;
68 pthread_mutex_t event_handler_mutex;
69 pthread_cond_t rx_listener_cond;
70 pthread_mutex_t listener_mutex;
71 static int listeners_started = 0;
72 pthread_mutex_t rx_clock_mutex;
73 struct clock rxi_clockNow;
74
75 /*
76  * Delay the current thread the specified number of seconds.
77  */
78 void
79 rxi_Delay(int sec)
80 {
81     sleep(sec);
82 }
83
84 /*
85  * Called from rx_Init()
86  */
87 void
88 rxi_InitializeThreadSupport(void)
89 {
90         /* listeners_started must only be reset if
91          * the listener thread terminates */
92         /* listeners_started = 0; */
93     clock_GetTime(&rxi_clockNow);
94 }
95
96 static void *
97 server_entry(void *argp)
98 {
99     void (*server_proc) () = (void (*)())argp;
100     server_proc();
101     dpf(("rx_pthread.c: server_entry: Server proc returned unexpectedly\n"));
102     exit(1);
103     return (void *)0;
104 }
105
106 /*
107  * Start an Rx server process.
108  */
109 void
110 rxi_StartServerProc(void (*proc) (void), int stacksize)
111 {
112     pthread_t thread;
113     pthread_attr_t tattr;
114     AFS_SIGSET_DECL;
115
116     if (pthread_attr_init(&tattr) != 0) {
117         dpf(("Unable to Create Rx server thread (pthread_attr_init)\n"));
118         exit(1);
119     }
120
121     if (pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) != 0) {
122         dpf
123             (("Unable to Create Rx server thread (pthread_attr_setdetachstate)\n"));
124         exit(1);
125     }
126
127     /*
128      * NOTE: We are ignoring the stack size parameter, for now.
129      */
130     AFS_SIGSET_CLEAR();
131     if (pthread_create(&thread, &tattr, server_entry, (void *)proc) != 0) {
132         dpf(("Unable to Create Rx server thread\n"));
133         exit(1);
134     }
135     AFS_SIGSET_RESTORE();
136 }
137
138 /*
139  * The event handling process.
140  */
141 static void *
142 event_handler(void *argp)
143 {
144     struct clock rx_pthread_last_event_wait_time = { 0, 0 };
145     unsigned long rx_pthread_n_event_expired = 0;
146     unsigned long rx_pthread_n_event_waits = 0;
147     long rx_pthread_n_event_woken = 0;
148     struct timespec rx_pthread_next_event_time = { 0, 0 };
149
150     assert(pthread_mutex_lock(&event_handler_mutex) == 0);
151
152     for (;;) {
153         struct clock cv;
154         struct clock next;
155
156         assert(pthread_mutex_unlock(&event_handler_mutex) == 0);
157
158         next.sec = 30;          /* Time to sleep if there are no events scheduled */
159         next.usec = 0;
160         clock_GetTime(&cv);
161         rxevent_RaiseEvents(&next);
162
163         assert(pthread_mutex_lock(&event_handler_mutex) == 0);
164         if (rx_pthread_event_rescheduled) {
165             rx_pthread_event_rescheduled = 0;
166             continue;
167         }
168
169         clock_Add(&cv, &next);
170         rx_pthread_next_event_time.tv_sec = cv.sec;
171         rx_pthread_next_event_time.tv_nsec = cv.usec * 1000;
172         rx_pthread_n_event_waits++;
173         if (pthread_cond_timedwait
174             (&rx_event_handler_cond, &event_handler_mutex,
175              &rx_pthread_next_event_time) == -1) {
176 #ifdef notdef
177             assert(errno == EAGAIN);
178 #endif
179             rx_pthread_n_event_expired++;
180         } else {
181             rx_pthread_n_event_woken++;
182         }
183         rx_pthread_event_rescheduled = 0;
184     }
185 }
186
187
188 /*
189  * This routine will get called by the event package whenever a new,
190  * earlier than others, event is posted. */
191 void
192 rxi_ReScheduleEvents(void)
193 {
194     assert(pthread_mutex_lock(&event_handler_mutex) == 0);
195     pthread_cond_signal(&rx_event_handler_cond);
196     rx_pthread_event_rescheduled = 1;
197     assert(pthread_mutex_unlock(&event_handler_mutex) == 0);
198 }
199
200
201 /* Loop to listen on a socket. Return setting *newcallp if this
202  * thread should become a server thread.  */
203 static void
204 rxi_ListenerProc(int sock, int *tnop, struct rx_call **newcallp)
205 {
206     struct sockaddr_storage saddr;
207     int slen;
208     register struct rx_packet *p = (struct rx_packet *)0;
209
210     assert(pthread_mutex_lock(&listener_mutex) == 0);
211     while (!listeners_started) {
212         assert(pthread_cond_wait(&rx_listener_cond, &listener_mutex) == 0);
213     }
214     assert(pthread_mutex_unlock(&listener_mutex) == 0);
215
216     for (;;) {
217         /*
218          * Grab a new packet only if necessary (otherwise re-use the old one)
219          */
220         if (p) {
221             rxi_RestoreDataBufs(p);
222         } else {
223             if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_RECEIVE))) {
224                 /* Could this happen with multiple socket listeners? */
225                 dpf(("rxi_Listener: no packets!"));     /* Shouldn't happen */
226                 exit(1);
227             }
228         }
229
230         slen = sizeof(saddr);
231         if (rxi_ReadPacket(sock, p, &saddr, &slen)) {
232             clock_NewTime();
233             p = rxi_ReceivePacket(p, sock, &saddr, slen, tnop, newcallp);
234             if (newcallp && *newcallp) {
235                 if (p)
236                     rxi_FreePacket(p);
237                 return;
238             }
239         }
240     }
241     /* NOTREACHED */
242 }
243
244 /* This is the listener process request loop. The listener process loop
245  * becomes a server thread when rxi_ListenerProc returns, and stays
246  * server thread until rxi_ServerProc returns. */
247 static void *
248 rx_ListenerProc(void *argp)
249 {
250     int threadID;
251     int sock = (int)argp;
252     struct rx_call *newcall;
253
254     while (1) {
255         newcall = NULL;
256         threadID = -1;
257         rxi_ListenerProc(sock, &threadID, &newcall);
258         /* assert(threadID != -1); */
259         /* assert(newcall != NULL); */
260         sock = OSI_NULLSOCKET;
261         assert(pthread_setspecific(rx_thread_id_key, (void *)threadID) == 0);
262         rxi_ServerProc(threadID, newcall, &sock);
263         /* assert(sock != OSI_NULLSOCKET); */
264     }
265     /* not reached */
266 }
267
268 /* This is the server process request loop. The server process loop
269  * becomes a listener thread when rxi_ServerProc returns, and stays
270  * listener thread until rxi_ListenerProc returns. */
271 void
272 rx_ServerProc(void)
273 {
274     int sock;
275     int threadID;
276     struct rx_call *newcall = NULL;
277
278     rxi_MorePackets(rx_maxReceiveWindow + 2);   /* alloc more packets */
279     MUTEX_ENTER(&rx_stats_mutex);
280     rxi_dataQuota += rx_initSendWindow; /* Reserve some pkts for hard times */
281     /* threadID is used for making decisions in GetCall.  Get it by bumping
282      * number of threads handling incoming calls */
283     /* Unique thread ID: used for scheduling purposes *and* as index into
284      * the host hold table (fileserver). 
285      * The previously used rxi_availProcs is unsuitable as it
286      * will already go up and down as packets arrive while the server
287      * threads are still initialising! The recently introduced
288      * rxi_pthread_hinum does not necessarily lead to a server
289      * thread with id 0, which is not allowed to hop through the
290      * incoming call queue.
291      * So either introduce yet another counter or flag the FCFS
292      * thread... chose the latter.
293      */
294     threadID = ++rxi_pthread_hinum;
295     if (rxi_fcfs_thread_num == 0 && rxi_fcfs_thread_num != threadID)
296         rxi_fcfs_thread_num = threadID;
297     ++rxi_availProcs;
298     MUTEX_EXIT(&rx_stats_mutex);
299
300     while (1) {
301         sock = OSI_NULLSOCKET;
302         assert(pthread_setspecific(rx_thread_id_key, (void *)threadID) == 0);
303         rxi_ServerProc(threadID, newcall, &sock);
304         /* assert(sock != OSI_NULLSOCKET); */
305         newcall = NULL;
306         rxi_ListenerProc(sock, &threadID, &newcall);
307         /* assert(threadID != -1); */
308         /* assert(newcall != NULL); */
309     }
310     /* not reached */
311 }
312
313 /*
314  * Historically used to start the listener process. We now have multiple
315  * listener processes (one for each socket); these are started by GetUdpSocket.
316  *
317  * The event handling process *is* started here (the old listener used
318  * to also handle events). The listener threads can't actually start 
319  * listening until rxi_StartListener is called because most of R may not
320  * be initialized when rxi_Listen is called.
321  */
322 void
323 rxi_StartListener(void)
324 {
325     pthread_attr_t tattr;
326     AFS_SIGSET_DECL;
327
328         if (listeners_started)
329                 return;
330
331     if (pthread_attr_init(&tattr) != 0) {
332         dpf
333             (("Unable to create Rx event handling thread (pthread_attr_init)\n"));
334         exit(1);
335     }
336
337     if (pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) != 0) {
338         dpf
339             (("Unable to create Rx event handling thread (pthread_attr_setdetachstate)\n"));
340         exit(1);
341     }
342
343     AFS_SIGSET_CLEAR();
344     if (pthread_create(&event_handler_thread, &tattr, event_handler, NULL) !=
345         0) {
346         dpf(("Unable to create Rx event handling thread\n"));
347         exit(1);
348     }
349     MUTEX_ENTER(&rx_stats_mutex);
350     ++rxi_pthread_hinum;
351     MUTEX_EXIT(&rx_stats_mutex);
352     AFS_SIGSET_RESTORE();
353
354     assert(pthread_mutex_lock(&listener_mutex) == 0);
355     assert(pthread_cond_broadcast(&rx_listener_cond) == 0);
356     listeners_started = 1;
357     assert(pthread_mutex_unlock(&listener_mutex) == 0);
358
359 }
360
361 /*
362  * Listen on the specified socket.
363  */
364 int
365 rxi_Listen(osi_socket sock)
366 {
367     pthread_t thread;
368     pthread_attr_t tattr;
369     AFS_SIGSET_DECL;
370
371     if (pthread_attr_init(&tattr) != 0) {
372         dpf
373             (("Unable to create socket listener thread (pthread_attr_init)\n"));
374         exit(1);
375     }
376
377     if (pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) != 0) {
378         dpf
379             (("Unable to create socket listener thread (pthread_attr_setdetachstate)\n"));
380         exit(1);
381     }
382
383     AFS_SIGSET_CLEAR();
384     if (pthread_create(&thread, &tattr, rx_ListenerProc, (void *)sock) != 0) {
385         dpf(("Unable to create socket listener thread\n"));
386         exit(1);
387     }
388     MUTEX_ENTER(&rx_stats_mutex);
389     ++rxi_pthread_hinum;
390     MUTEX_EXIT(&rx_stats_mutex);
391     AFS_SIGSET_RESTORE();
392     return 0;
393 }
394
395
396 /*
397  * Recvmsg.
398  *
399  */
400 int
401 rxi_Recvmsg(osi_socket socket, struct msghdr *msg_p, int flags)
402 {
403     int ret;
404     ret = recvmsg(socket, msg_p, flags);
405     return ret;
406 }
407
408 /*
409  * Sendmsg.
410  */
411 int
412 rxi_Sendmsg(osi_socket socket, struct msghdr *msg_p, int flags)
413 {
414     int ret;
415     ret = sendmsg(socket, msg_p, flags);
416 #ifdef AFS_LINUX22_ENV
417     /* linux unfortunately returns ECONNREFUSED if the target port
418      * is no longer in use */
419     /* and EAGAIN if a UDP checksum is incorrect */
420     if (ret == -1 && errno != ECONNREFUSED && errno != EAGAIN) {
421 #else
422     if (ret == -1) {
423 #endif
424         dpf(("rxi_sendmsg failed, error %d\n", errno));
425         fflush(stdout);
426         return -1;
427     }
428     return 0;
429 }
430
431 struct rx_ts_info_t * rx_ts_info_init() {
432     register struct rx_ts_info_t * rx_ts_info;
433     rx_ts_info = (rx_ts_info_t *) malloc(sizeof(rx_ts_info_t));
434     assert(rx_ts_info != NULL && pthread_setspecific(rx_ts_info_key, rx_ts_info) == 0);
435     memset(rx_ts_info, 0, sizeof(rx_ts_info_t));
436 #ifdef RX_ENABLE_TSFPQ
437     queue_Init(&rx_ts_info->_FPQ);
438
439     MUTEX_ENTER(&rx_stats_mutex);
440     rx_TSFPQMaxProcs++;
441     RX_TS_FPQ_COMPUTE_LIMITS;
442     MUTEX_EXIT(&rx_stats_mutex);
443 #endif /* RX_ENABLE_TSFPQ */
444     return rx_ts_info;
445 }