openafs-string-header-cleanup-20071030
[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 #include <string.h>
28 #ifndef AFS_NT40_ENV
29 # include <sys/socket.h>
30 # include <sys/file.h>
31 # include <netdb.h>
32 # include <netinet/in.h>
33 # include <net/if.h>
34 # include <sys/ioctl.h>
35 # include <sys/time.h>
36 #endif
37 #include <sys/stat.h>
38 #include <rx/rx.h>
39 #include <rx/rx_globals.h>
40 #include <assert.h>
41 #include <rx/rx_pthread.h>
42 #include <rx/rx_clock.h>
43
44 /*
45  * Number of times the event handling thread was signalled because a new
46  * event was scheduled earlier than the lastest event.
47  *
48  * Protected by event_handler_mutex
49  */
50 static long rx_pthread_n_event_wakeups;
51
52 /* Set rx_pthread_event_rescheduled if event_handler should just try
53  * again instead of sleeping.
54  *
55  * Protected by event_handler_mutex
56  */
57 static int rx_pthread_event_rescheduled = 0;
58
59 static void *rx_ListenerProc(void *);
60
61 /*
62  * We supply an event handling thread for Rx's event processing.
63  * The condition variable is used to wakeup the thread whenever a new
64  * event is scheduled earlier than the previous earliest event.
65  * This thread is also responsible for keeping time.
66  */
67 static pthread_t event_handler_thread;
68 pthread_cond_t rx_event_handler_cond;
69 pthread_mutex_t event_handler_mutex;
70 pthread_cond_t rx_listener_cond;
71 pthread_mutex_t listener_mutex;
72 static int listeners_started = 0;
73 pthread_mutex_t rx_clock_mutex;
74 struct clock rxi_clockNow;
75
76 /*
77  * Delay the current thread the specified number of seconds.
78  */
79 void
80 rxi_Delay(int sec)
81 {
82     sleep(sec);
83 }
84
85 /*
86  * Called from rx_Init()
87  */
88 void
89 rxi_InitializeThreadSupport(void)
90 {
91         /* listeners_started must only be reset if
92          * the listener thread terminates */
93         /* listeners_started = 0; */
94     clock_GetTime(&rxi_clockNow);
95 }
96
97 static void *
98 server_entry(void *argp)
99 {
100     void (*server_proc) () = (void (*)())argp;
101     server_proc();
102     dpf(("rx_pthread.c: server_entry: Server proc returned unexpectedly\n"));
103     exit(1);
104     return (void *)0;
105 }
106
107 /*
108  * Start an Rx server process.
109  */
110 void
111 rxi_StartServerProc(void (*proc) (void), int stacksize)
112 {
113     pthread_t thread;
114     pthread_attr_t tattr;
115     AFS_SIGSET_DECL;
116
117     if (pthread_attr_init(&tattr) != 0) {
118         dpf(("Unable to Create Rx server thread (pthread_attr_init)\n"));
119         exit(1);
120     }
121
122     if (pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) != 0) {
123         dpf
124             (("Unable to Create Rx server thread (pthread_attr_setdetachstate)\n"));
125         exit(1);
126     }
127
128     /*
129      * NOTE: We are ignoring the stack size parameter, for now.
130      */
131     AFS_SIGSET_CLEAR();
132     if (pthread_create(&thread, &tattr, server_entry, (void *)proc) != 0) {
133         dpf(("Unable to Create Rx server thread\n"));
134         exit(1);
135     }
136     AFS_SIGSET_RESTORE();
137 }
138
139 /*
140  * The event handling process.
141  */
142 static void *
143 event_handler(void *argp)
144 {
145     struct clock rx_pthread_last_event_wait_time = { 0, 0 };
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     struct timespec rx_pthread_next_event_time = { 0, 0 };
150
151     assert(pthread_mutex_lock(&event_handler_mutex) == 0);
152
153     for (;;) {
154         struct clock cv;
155         struct clock next;
156
157         assert(pthread_mutex_unlock(&event_handler_mutex) == 0);
158
159         next.sec = 30;          /* Time to sleep if there are no events scheduled */
160         next.usec = 0;
161         clock_GetTime(&cv);
162         rxevent_RaiseEvents(&next);
163
164         assert(pthread_mutex_lock(&event_handler_mutex) == 0);
165         if (rx_pthread_event_rescheduled) {
166             rx_pthread_event_rescheduled = 0;
167             continue;
168         }
169
170         clock_Add(&cv, &next);
171         rx_pthread_next_event_time.tv_sec = cv.sec;
172         rx_pthread_next_event_time.tv_nsec = cv.usec * 1000;
173         rx_pthread_n_event_waits++;
174         if (pthread_cond_timedwait
175             (&rx_event_handler_cond, &event_handler_mutex,
176              &rx_pthread_next_event_time) == -1) {
177 #ifdef notdef
178             assert(errno == EAGAIN);
179 #endif
180             rx_pthread_n_event_expired++;
181         } else {
182             rx_pthread_n_event_woken++;
183         }
184         rx_pthread_event_rescheduled = 0;
185     }
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     assert(pthread_mutex_lock(&event_handler_mutex) == 0);
196     pthread_cond_signal(&rx_event_handler_cond);
197     rx_pthread_event_rescheduled = 1;
198     assert(pthread_mutex_unlock(&event_handler_mutex) == 0);
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(int sock, int *tnop, struct rx_call **newcallp)
206 {
207     unsigned int host;
208     u_short port;
209     register struct rx_packet *p = (struct rx_packet *)0;
210
211     assert(pthread_mutex_lock(&listener_mutex) == 0);
212     while (!listeners_started) {
213         assert(pthread_cond_wait(&rx_listener_cond, &listener_mutex) == 0);
214     }
215     assert(pthread_mutex_unlock(&listener_mutex) == 0);
216
217     for (;;) {
218         /*
219          * Grab a new packet only if necessary (otherwise re-use the old one)
220          */
221         if (p) {
222             rxi_RestoreDataBufs(p);
223         } else {
224             if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_RECEIVE))) {
225                 /* Could this happen with multiple socket listeners? */
226                 dpf(("rxi_Listener: no packets!"));     /* Shouldn't happen */
227                 exit(1);
228             }
229         }
230
231         if (rxi_ReadPacket(sock, p, &host, &port)) {
232             clock_NewTime();
233             p = rxi_ReceivePacket(p, sock, host, port, 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 }