2 * Copyright 2000, International Business Machines Corporation and others.
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
10 /* rx_user.c contains routines specific to the user space UNIX implementation of rx */
12 /* This controls the size of an fd_set; it must be defined early before
13 * the system headers define that type and the macros that operate on it.
14 * Its value should be as large as the maximum file descriptor limit we
15 * are likely to run into on any platform. Right now, that is 65536
16 * which is the default hard fd limit on Solaris 9 */
18 #define FD_SETSIZE 65536
21 #include <afsconfig.h>
22 #include <afs/param.h>
25 # include <sys/types.h> /* fd_set on older platforms */
29 # include <winsock2.h>
31 # include <unistd.h> /* select() prototype */
32 # include <sys/time.h> /* struct timeval, select() prototype */
34 # include <sys/select.h> /* fd_set on newer platforms */
36 # include <sys/socket.h>
37 # include <sys/file.h>
39 # include <sys/stat.h>
40 # include <netinet/in.h>
42 # include <sys/ioctl.h>
43 # include <sys/time.h>
47 # include "rx_globals.h"
50 #define MAXTHREADNAMELENGTH 64
52 int debugSelectFailure; /* # of times select failed */
55 * Sleep on the unique wait channel provided.
60 LWP_WaitProcess(addr);
64 * Wakeup any threads on the channel provided.
65 * They may be woken up spuriously, and must check any conditions.
68 rxi_Wakeup(void *addr)
70 LWP_NoYieldSignal(addr);
73 PROCESS rx_listenerPid = 0; /* LWP process id of socket listener process */
74 static void* rx_ListenerProc(void *dummy);
77 * Delay the current thread the specified number of seconds.
85 static int quitListening = 0;
87 /* This routine will kill the listener thread, if it exists. */
89 rxi_StopListener(void)
92 rxi_ReScheduleEvents();
95 /* This routine will get called by the event package whenever a new,
96 earlier than others, event is posted. If the Listener process
97 is blocked in selects, this will unblock it. It also can be called
98 to force a new trip through the rxi_Listener select loop when the set
99 of file descriptors it should be listening to changes... */
101 rxi_ReScheduleEvents(void)
104 IOMGR_Cancel(rx_listenerPid);
108 rxi_InitializeThreadSupport(void)
112 LWP_InitializeProcessSupport(LWP_NORMAL_PRIORITY, &junk);
114 FD_ZERO(&rx_selectMask);
118 rxi_StartServerProc(void *(*proc) (void *), int stacksize)
121 static int number = 0;
124 sprintf(name, "srv_%d", ++number);
125 LWP_CreateProcess(proc, stacksize, RX_PROCESS_PRIORITY, NULL,
126 "rx_ServerProc", &scratchPid);
128 (*registerProgram) (scratchPid, name);
132 rxi_StartListener(void)
134 /* Priority of listener should be high, so it can keep conns alive */
135 #define RX_LIST_STACK 24000
136 LWP_CreateProcess(rx_ListenerProc, RX_LIST_STACK, LWP_MAX_PRIORITY,
137 NULL, "rx_Listener", &rx_listenerPid);
139 (*registerProgram) (rx_listenerPid, "listener");
142 /* The main loop which listens to the net for datagrams, and handles timeouts
143 and retransmissions, etc. It also is responsible for scheduling the
144 execution of pending events (in conjunction with event.c).
146 Note interaction of nextPollTime and lastPollWorked. The idea is that if rx is not
147 keeping up with the incoming stream of packets (because there are threads that
148 are interfering with its running sufficiently often), rx does a polling select
149 before doing a real IOMGR_Select system call. Doing a real select means that
150 we don't have to let other processes run before processing more packets.
152 So, our algorithm is that if the last poll on the file descriptor found useful data, or
153 we're at the time nextPollTime (which is advanced so that it occurs every 3 or 4 seconds),
154 then we try the polling select before the IOMGR_Select. If we eventually catch up
155 (which we can tell by the polling select returning no input packets ready), then we
156 don't do a polling select again until several seconds later (via nextPollTime mechanism).
160 rxi_ListenerProc(fd_set * rfds, int *tnop, struct rx_call **newcallp)
164 struct rx_packet *p = (struct rx_packet *)0;
167 afs_int32 nextPollTime; /* time to next poll FD before sleeping */
168 int lastPollWorked, doingPoll; /* true iff last poll was useful */
169 struct timeval tv, *tvp;
175 char name[MAXTHREADNAMELENGTH] = "srv_0";
180 code = LWP_CurrentProcess(&pid);
182 fprintf(stderr, "rxi_Listener: Can't get my pid.\n");
185 rx_listenerPid = pid;
187 (*swapNameProgram) (pid, "listener", &name[0]);
190 /* Grab a new packet only if necessary (otherwise re-use the old one) */
192 rxi_RestoreDataBufs(p);
194 if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_RECEIVE)))
195 osi_Panic("rxi_ListenerProc: no packets!"); /* Shouldn't happen */
197 /* Wait for the next event time or a packet to arrive. */
198 /* event_RaiseEvents schedules any events whose time has come and
199 * then atomically computes the time to the next event, guaranteeing
200 * that this is positive. If there is no next event, it returns 0 */
202 if (!rxevent_RaiseEvents(&cv))
205 /* It's important to copy cv to tv, because the 4.3 documentation
206 * for select threatens that *tv may be updated after a select, in
207 * future editions of the system, to indicate how much of the time
208 * period has elapsed. So we shouldn't rely on tv not being altered. */
209 tv.tv_sec = cv.sec; /* Time to next event */
210 tv.tv_usec = cv.usec;
215 *rfds = rx_selectMask;
217 if (lastPollWorked || nextPollTime < clock_Sec()) {
218 /* we're catching up, or haven't tried to for a few seconds */
220 nextPollTime = clock_Sec() + 4; /* try again in 4 seconds no matter what */
221 tv.tv_sec = tv.tv_usec = 0; /* make sure we poll */
223 code = select((int)(rx_maxSocketNumber + 1), rfds, 0, 0, tvp);
226 code = IOMGR_Select((int)(rx_maxSocketNumber + 1), rfds, 0, 0, tvp);
228 lastPollWorked = 0; /* default is that it didn't find anything */
232 LWP_DestroyProcess(pid);
238 * If it was a timer interrupt then we can assume that
239 * the time has advanced by roughly the value of the
240 * previous timeout, and that there is now at least
246 /* select or IOMGR_Select returned failure */
247 debugSelectFailure++; /* update debugging counter */
252 * IOMGR_Cancel is invoked whenever a new event is
253 * posted that is earlier than any existing events.
254 * So we re-evaluate the time, and then go back to
261 /* Packets have arrived, presumably:
262 * If it wasn't a timer interrupt, then no event should have
263 * timed out yet (well some event may have, but only just...), so
264 * we don't bother looking to see if any have timed out, but just
265 * go directly to reading the data packets
271 for (i = 0; p && i < rfds->fd_count; i++) {
272 socket = rfds->fd_array[i];
273 if (rxi_ReadPacket(socket, p, &host, &port)) {
275 p = rxi_ReceivePacket(p, socket, host, port, tnop,
277 if (newcallp && *newcallp) {
281 if (swapNameProgram) {
282 (*swapNameProgram) (rx_listenerPid, name, 0);
290 for (socket = rx_minSocketNumber;
291 p && socket <= rx_maxSocketNumber; socket++) {
292 if (!FD_ISSET(socket, rfds))
294 if (rxi_ReadPacket(socket, p, &host, &port)) {
295 p = rxi_ReceivePacket(p, socket, host, port, tnop,
297 if (newcallp && *newcallp) {
301 if (swapNameProgram) {
302 (*swapNameProgram) (rx_listenerPid, name, 0);
316 /* This is the listener process request loop. The listener process loop
317 * becomes a server thread when rxi_ListenerProc returns, and stays
318 * server thread until rxi_ServerProc returns. */
320 rx_ListenerProc(void *dummy)
324 struct rx_call *newcall;
327 if (!(rfds = IOMGR_AllocFDSet())) {
328 osi_Panic("rx_ListenerProc: no fd_sets!\n");
334 rxi_ListenerProc(rfds, &threadID, &newcall);
335 /* assert(threadID != -1); */
336 /* assert(newcall != NULL); */
337 sock = OSI_NULLSOCKET;
338 rxi_ServerProc(threadID, newcall, &sock);
339 /* assert(sock != OSI_NULLSOCKET); */
345 /* This is the server process request loop. The server process loop
346 * becomes a listener thread when rxi_ServerProc returns, and stays
347 * listener thread until rxi_ListenerProc returns. */
349 rx_ServerProc(void * unused)
353 struct rx_call *newcall = NULL;
356 if (!(rfds = IOMGR_AllocFDSet())) {
357 osi_Panic("rxi_ListenerProc: no fd_sets!\n");
360 rxi_MorePackets(rx_maxReceiveWindow + 2); /* alloc more packets */
361 rxi_dataQuota += rx_initSendWindow; /* Reserve some pkts for hard times */
362 /* threadID is used for making decisions in GetCall. Get it by bumping
363 * number of threads handling incoming calls */
364 threadID = rxi_availProcs++;
367 sock = OSI_NULLSOCKET;
368 rxi_ServerProc(threadID, newcall, &sock);
369 /* assert(sock != OSI_NULLSOCKET); */
371 rxi_ListenerProc(rfds, &threadID, &newcall);
372 /* assert(threadID != -1); */
373 /* assert(newcall != NULL); */
380 * Called from GetUDPSocket.
381 * Called from a single thread at startup.
382 * Returns 0 on success; -1 on failure.
385 rxi_Listen(osi_socket sock)
389 * Put the socket into non-blocking mode so that rx_Listener
390 * can do a polling read before entering select
392 if (fcntl(sock, F_SETFL, FNDELAY) == -1) {
394 (osi_Msg "rxi_Listen: unable to set non-blocking mode on socket\n");
398 if (sock > FD_SETSIZE - 1) {
399 (osi_Msg "rxi_Listen: socket descriptor > (FD_SETSIZE-1) = %d\n",
405 FD_SET(sock, &rx_selectMask);
406 if (sock > rx_maxSocketNumber)
407 rx_maxSocketNumber = sock;
408 if (sock < rx_minSocketNumber)
409 rx_minSocketNumber = sock;
417 rxi_Recvmsg(osi_socket socket, struct msghdr *msg_p, int flags)
419 #if defined(HAVE_LINUX_ERRQUEUE_H) && defined(ADAPT_PMTU)
420 while((rxi_HandleSocketError(socket)) > 0)
423 return recvmsg(socket, msg_p, flags);
427 * Simulate a blocking sendmsg on the non-blocking socket.
428 * It's non blocking because it was set that way for recvmsg.
431 rxi_Sendmsg(osi_socket socket, struct msghdr *msg_p, int flags)
433 fd_set *sfds = (fd_set *) 0;
434 while (sendmsg(socket, msg_p, flags) == -1) {
436 rx_stats.sendSelects++;
439 if (!(sfds = IOMGR_AllocFDSet())) {
440 (osi_Msg "rx failed to alloc fd_set: ");
441 perror("rx_sendmsg");
444 FD_SET(socket, sfds);
446 #if defined(HAVE_LINUX_ERRQUEUE_H) && defined(ADAPT_PMTU)
447 while((rxi_HandleSocketError(socket)) > 0)
451 if (WSAGetLastError())
452 #elif defined(AFS_LINUX22_ENV)
453 /* linux unfortunately returns ECONNREFUSED if the target port
454 * is no longer in use */
455 /* and EAGAIN if a UDP checksum is incorrect */
456 if (errno != EWOULDBLOCK && errno != ENOBUFS && errno != ECONNREFUSED
459 if (errno != EWOULDBLOCK && errno != ENOBUFS)
462 (osi_Msg "rx failed to send packet: ");
463 perror("rx_sendmsg");
468 if (WSAGetLastError() > 0)
469 return -WSAGetLastError();
473 while ((err = select(socket + 1, 0, sfds, 0, 0)) != 1) {
474 if (err >= 0 || errno != EINTR)
475 osi_Panic("rxi_sendmsg: select error %d.%d", err, errno);
479 IOMGR_FreeFDSet(sfds);