f0b2e8e9831255c551e911b511afee1ffdacabcd
[openafs.git] / src / rx / rx_kcommon.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  * rx_kcommon.c - Common kernel RX code for all system types.
12  */
13
14 #include <afsconfig.h>
15 #include "afs/param.h"
16
17 RCSID
18     ("$Header$");
19
20 #include "rx/rx_kcommon.h"
21
22 #ifdef AFS_HPUX110_ENV
23 #include "h/tihdr.h"
24 #include <xti.h>
25 #endif
26 #include "afsint.h"
27
28 #ifndef RXK_LISTENER_ENV
29 int (*rxk_PacketArrivalProc) (register struct rx_packet * ahandle, register struct sockaddr_in * afrom, char *arock, afs_int32 asize);  /* set to packet allocation procedure */
30 int (*rxk_GetPacketProc) (char **ahandle, int asize);
31 #endif
32
33 struct osi_socket *rxk_NewSocketHost(afs_uint32 ahost, short aport);
34 extern struct interfaceAddr afs_cb_interface;
35
36 rxk_ports_t rxk_ports;
37 rxk_portRocks_t rxk_portRocks;
38
39 int rxk_initDone = 0;
40
41 #if !defined(AFS_SUN5_ENV) && !defined(AFS_SGI62_ENV)
42 #define ADDRSPERSITE 16
43 static afs_uint32 myNetAddrs[ADDRSPERSITE];
44 static int myNetMTUs[ADDRSPERSITE];
45 static int numMyNetAddrs = 0;
46 #endif
47
48 /* add a port to the monitored list, port # is in network order */
49 static int
50 rxk_AddPort(u_short aport, char *arock)
51 {
52     int i;
53     unsigned short *tsp, ts;
54     int zslot;
55
56     zslot = -1;                 /* look for an empty slot simultaneously */
57     for (i = 0, tsp = rxk_ports; i < MAXRXPORTS; i++, tsp++) {
58         if (((ts = *tsp) == 0) && (zslot == -1))
59             zslot = i;
60         if (ts == aport) {
61             return 0;
62         }
63     }
64     /* otherwise allocate a new port slot */
65     if (zslot < 0)
66         return E2BIG;           /* all full */
67     rxk_ports[zslot] = aport;
68     rxk_portRocks[zslot] = arock;
69     return 0;
70 }
71
72 /* remove as port from the monitored list, port # is in network order */
73 int
74 rxk_DelPort(u_short aport)
75 {
76     register int i;
77     register unsigned short *tsp;
78
79     for (i = 0, tsp = rxk_ports; i < MAXRXPORTS; i++, tsp++) {
80         if (*tsp == aport) {
81             /* found it, adjust ref count and free the port reference if all gone */
82             *tsp = 0;
83             return 0;
84         }
85     }
86     /* otherwise port not found */
87     return ENOENT;
88 }
89
90 void
91 rxk_shutdownPorts(void)
92 {
93     int i;
94     for (i = 0; i < MAXRXPORTS; i++) {
95         if (rxk_ports[i]) {
96             rxk_ports[i] = 0;
97 #if ! defined(AFS_SUN5_ENV) && ! defined(UKERNEL) && ! defined(RXK_LISTENER_ENV)
98             soclose((struct socket *)rxk_portRocks[i]);
99 #endif
100             rxk_portRocks[i] = NULL;
101         }
102     }
103 }
104
105 osi_socket
106 rxi_GetHostUDPSocket(u_int host, u_short port)
107 {
108     struct osi_socket *sockp;
109     sockp = (struct osi_socket *)rxk_NewSocketHost(host, port);
110     if (sockp == (struct osi_socket *)0)
111         return OSI_NULLSOCKET;
112     rxk_AddPort(port, (char *)sockp);
113     return (osi_socket) sockp;
114 }
115
116 osi_socket
117 rxi_GetUDPSocket(u_short port)
118 {
119     return rxi_GetHostUDPSocket(htonl(INADDR_ANY), port);
120 }
121
122 void
123 osi_Panic(msg, a1, a2, a3)
124      char *msg;
125 {
126     if (!msg)
127         msg = "Unknown AFS panic";
128
129     printf(msg, a1, a2, a3);
130 #ifdef AFS_LINUX20_ENV
131     *((char *)0xffffffff) = 42;
132 #else
133     panic(msg);
134 #endif
135 }
136
137 /*
138  * osi_utoa() - write the NUL-terminated ASCII decimal form of the given
139  * unsigned long value into the given buffer.  Returns 0 on success,
140  * and a value less than 0 on failure.  The contents of the buffer is
141  * defined only on success.
142  */
143
144 int
145 osi_utoa(char *buf, size_t len, unsigned long val)
146 {
147     long k;                     /* index of first byte of string value */
148
149     /* we definitely need room for at least one digit and NUL */
150
151     if (len < 2) {
152         return -1;
153     }
154
155     /* compute the string form from the high end of the buffer */
156
157     buf[len - 1] = '\0';
158     for (k = len - 2; k >= 0; k--) {
159         buf[k] = val % 10 + '0';
160         val /= 10;
161
162         if (val == 0)
163             break;
164     }
165
166     /* did we finish converting val to string form? */
167
168     if (val != 0) {
169         return -2;
170     }
171
172     /* this should never happen */
173
174     if (k < 0) {
175         return -3;
176     }
177
178     /* this should never happen */
179
180     if (k >= len) {
181         return -4;
182     }
183
184     /* if necessary, relocate string to beginning of buf[] */
185
186     if (k > 0) {
187
188         /*
189          * We need to achieve the effect of calling
190          *
191          * memmove(buf, &buf[k], len - k);
192          *
193          * However, since memmove() is not available in all
194          * kernels, we explicitly do an appropriate copy.
195          */
196
197         char *dst = buf;
198         char *src = buf + k;
199
200         while ((*dst++ = *src++) != '\0')
201             continue;
202     }
203
204     return 0;
205 }
206
207 /*
208  * osi_AssertFailK() -- used by the osi_Assert() macro.
209  *
210  * It essentially does
211  *
212  * osi_Panic("assertion failed: %s, file: %s, line: %d", expr, file, line);
213  *
214  * Since the kernel version of osi_Panic() only passes its first
215  * argument to the native panic(), we construct a single string and hand
216  * that to osi_Panic().
217  */
218 void
219 osi_AssertFailK(const char *expr, const char *file, int line)
220 {
221     static const char msg0[] = "assertion failed: ";
222     static const char msg1[] = ", file: ";
223     static const char msg2[] = ", line: ";
224     static const char msg3[] = "\n";
225
226     /*
227      * These buffers add up to 1K, which is a pleasantly nice round
228      * value, but probably not vital.
229      */
230     char buf[1008];
231     char linebuf[16];
232
233     /* check line number conversion */
234
235     if (osi_utoa(linebuf, sizeof linebuf, line) < 0) {
236         osi_Panic("osi_AssertFailK: error in osi_utoa()\n");
237     }
238
239     /* okay, panic */
240
241 #define ADDBUF(BUF, STR)                                        \
242         if (strlen(BUF) + strlen((char *)(STR)) + 1 <= sizeof BUF) {    \
243                 strcat(BUF, (char *)(STR));                             \
244         }
245
246     buf[0] = '\0';
247     ADDBUF(buf, msg0);
248     ADDBUF(buf, expr);
249     ADDBUF(buf, msg1);
250     ADDBUF(buf, file);
251     ADDBUF(buf, msg2);
252     ADDBUF(buf, linebuf);
253     ADDBUF(buf, msg3);
254
255 #undef ADDBUF
256
257     osi_Panic(buf);
258 }
259
260 #ifndef UKERNEL
261 /* This is the server process request loop. Kernel server
262  * processes never become listener threads */
263 void
264 rx_ServerProc(void)
265 {
266     int threadID;
267
268     rxi_MorePackets(rx_maxReceiveWindow + 2);   /* alloc more packets */
269     rxi_dataQuota += rx_initSendWindow; /* Reserve some pkts for hard times */
270     /* threadID is used for making decisions in GetCall.  Get it by bumping
271      * number of threads handling incoming calls */
272     threadID = rxi_availProcs++;
273
274 #ifdef RX_ENABLE_LOCKS
275     AFS_GUNLOCK();
276 #endif /* RX_ENABLE_LOCKS */
277     rxi_ServerProc(threadID, NULL, NULL);
278 #ifdef RX_ENABLE_LOCKS
279     AFS_GLOCK();
280 #endif /* RX_ENABLE_LOCKS */
281 }
282 #endif /* !UKERNEL */
283
284 #ifndef RXK_LISTENER_ENV
285 /* asize includes the Rx header */
286 static int
287 MyPacketProc(char **ahandle, int asize)
288 {
289     register struct rx_packet *tp;
290
291     /* If this is larger than we expected, increase rx_maxReceiveDataSize */
292     /* If we can't scrounge enough cbufs, then we have to drop the packet,
293      * but we should set a flag so we magic up some more at our leisure.
294      */
295
296     if ((asize >= 0) && (asize <= RX_MAX_PACKET_SIZE)) {
297         tp = rxi_AllocPacket(RX_PACKET_CLASS_RECEIVE);
298         if (tp && (tp->length + RX_HEADER_SIZE) < asize) {
299             if (0 <
300                 rxi_AllocDataBuf(tp, asize - (tp->length + RX_HEADER_SIZE),
301                                  RX_PACKET_CLASS_RECV_CBUF)) {
302                 rxi_FreePacket(tp);
303                 tp = NULL;
304                 MUTEX_ENTER(&rx_stats_mutex);
305                 rx_stats.noPacketBuffersOnRead++;
306                 MUTEX_EXIT(&rx_stats_mutex);
307             }
308         }
309     } else {
310         /*
311          * XXX if packet is too long for our buffer,
312          * should do this at a higher layer and let other
313          * end know we're losing.
314          */
315         MUTEX_ENTER(&rx_stats_mutex);
316         rx_stats.bogusPacketOnRead++;
317         MUTEX_EXIT(&rx_stats_mutex);
318         /* I DON"T LIKE THIS PRINTF -- PRINTFS MAKE THINGS VERY VERY SLOOWWW */
319         printf("rx: packet dropped: bad ulen=%d\n", asize);
320         tp = NULL;
321     }
322
323     if (!tp)
324         return -1;
325     /* otherwise we have a packet, set appropriate values */
326     *ahandle = (char *)tp;
327     return 0;
328 }
329
330 static int
331 MyArrivalProc(register struct rx_packet *ahandle,
332               register struct sockaddr_in *afrom, char *arock,
333               afs_int32 asize)
334 {
335     /* handle basic rx packet */
336     ahandle->length = asize - RX_HEADER_SIZE;
337     rxi_DecodePacketHeader(ahandle);
338     ahandle =
339         rxi_ReceivePacket(ahandle, (struct socket *)arock,
340                           afrom->sin_addr.s_addr, afrom->sin_port, NULL,
341                           NULL);
342
343     /* free the packet if it has been returned */
344     if (ahandle)
345         rxi_FreePacket(ahandle);
346     return 0;
347 }
348 #endif /* !RXK_LISTENER_ENV */
349
350 void
351 rxi_StartListener(void)
352 {
353     /* if kernel, give name of appropriate procedures */
354 #ifndef RXK_LISTENER_ENV
355     rxk_GetPacketProc = MyPacketProc;
356     rxk_PacketArrivalProc = MyArrivalProc;
357     rxk_init();
358 #endif
359 }
360
361 /* Called from rxi_FindPeer, when initializing a clear rx_peer structure,
362   to get interesting information. */
363 void
364 rxi_InitPeerParams(register struct rx_peer *pp)
365 {
366     u_short rxmtu;
367     afs_int32 i, mtu;
368
369 #ifdef  ADAPT_MTU
370 #ifndef AFS_SUN5_ENV
371 #ifdef AFS_USERSPACE_IP_ADDR
372     i = rxi_Findcbi(pp->host);
373     if (i == -1) {
374         pp->timeout.sec = 3;
375         /* pp->timeout.usec = 0; */
376         pp->ifMTU = RX_REMOTE_PACKET_SIZE;
377     } else {
378         pp->timeout.sec = 2;
379         /* pp->timeout.usec = 0; */
380         pp->ifMTU = MIN(RX_MAX_PACKET_SIZE, rx_MyMaxSendSize);
381     }
382     if (i != -1) {
383         mtu = ntohl(afs_cb_interface.mtu[i]);
384         /* Diminish the packet size to one based on the MTU given by
385          * the interface. */
386         if (mtu > (RX_IPUDP_SIZE + RX_HEADER_SIZE)) {
387             rxmtu = mtu - RX_IPUDP_SIZE;
388             if (rxmtu < pp->ifMTU)
389                 pp->ifMTU = rxmtu;
390         }
391     } else {                    /* couldn't find the interface, so assume the worst */
392         pp->ifMTU = RX_REMOTE_PACKET_SIZE;
393     }
394 #else /* AFS_USERSPACE_IP_ADDR */
395     struct ifnet *ifn;
396
397 #if !defined(AFS_SGI62_ENV)
398     if (numMyNetAddrs == 0)
399         (void)rxi_GetIFInfo();
400 #endif
401
402     ifn = rxi_FindIfnet(pp->host, NULL);
403     if (ifn) {
404         pp->timeout.sec = 2;
405         /* pp->timeout.usec = 0; */
406         pp->ifMTU = MIN(RX_MAX_PACKET_SIZE, rx_MyMaxSendSize);
407 #ifdef IFF_POINTOPOINT
408         if (ifn->if_flags & IFF_POINTOPOINT) {
409             /* wish we knew the bit rate and the chunk size, sigh. */
410             pp->timeout.sec = 4;
411             pp->ifMTU = RX_PP_PACKET_SIZE;
412         }
413 #endif /* IFF_POINTOPOINT */
414         /* Diminish the packet size to one based on the MTU given by
415          * the interface. */
416         if (ifn->if_mtu > (RX_IPUDP_SIZE + RX_HEADER_SIZE)) {
417             rxmtu = ifn->if_mtu - RX_IPUDP_SIZE;
418             if (rxmtu < pp->ifMTU)
419                 pp->ifMTU = rxmtu;
420         }
421     } else {                    /* couldn't find the interface, so assume the worst */
422         pp->timeout.sec = 3;
423         /* pp->timeout.usec = 0; */
424         pp->ifMTU = RX_REMOTE_PACKET_SIZE;
425     }
426 #endif /* else AFS_USERSPACE_IP_ADDR */
427 #else /* AFS_SUN5_ENV */
428     mtu = rxi_FindIfMTU(pp->host);
429
430     if (mtu <= 0) {
431         pp->timeout.sec = 3;
432         /* pp->timeout.usec = 0; */
433         pp->ifMTU = RX_REMOTE_PACKET_SIZE;
434     } else {
435         pp->timeout.sec = 2;
436         /* pp->timeout.usec = 0; */
437         pp->ifMTU = MIN(RX_MAX_PACKET_SIZE, rx_MyMaxSendSize);
438     }
439
440     if (mtu > 0) {
441         /* Diminish the packet size to one based on the MTU given by
442          * the interface. */
443         if (mtu > (RX_IPUDP_SIZE + RX_HEADER_SIZE)) {
444             rxmtu = mtu - RX_IPUDP_SIZE;
445             if (rxmtu < pp->ifMTU)
446                 pp->ifMTU = rxmtu;
447         }
448     } else {                    /* couldn't find the interface, so assume the worst */
449         pp->ifMTU = RX_REMOTE_PACKET_SIZE;
450     }
451 #endif /* AFS_SUN5_ENV */
452 #else /* ADAPT_MTU */
453     pp->rateFlag = 2;           /* start timing after two full packets */
454     pp->timeout.sec = 2;
455     pp->ifMTU = OLD_MAX_PACKET_SIZE;
456 #endif /* else ADAPT_MTU */
457     pp->ifMTU = rxi_AdjustIfMTU(pp->ifMTU);
458     pp->maxMTU = OLD_MAX_PACKET_SIZE;   /* for compatibility with old guys */
459     pp->natMTU = MIN(pp->ifMTU, OLD_MAX_PACKET_SIZE);
460     pp->ifDgramPackets =
461         MIN(rxi_nDgramPackets,
462             rxi_AdjustDgramPackets(RX_MAX_FRAGS, pp->ifMTU));
463     pp->maxDgramPackets = 1;
464
465     /* Initialize slow start parameters */
466     pp->MTU = MIN(pp->natMTU, pp->maxMTU);
467     pp->cwind = 1;
468     pp->nDgramPackets = 1;
469     pp->congestSeq = 0;
470 }
471
472
473 /* The following code is common to several system types, but not all. The
474  * separate ones are found in the system specific subdirectories.
475  */
476
477
478 #if ! defined(AFS_AIX_ENV) && ! defined(AFS_SUN5_ENV) && ! defined(UKERNEL) && ! defined(AFS_LINUX20_ENV) && !defined (AFS_DARWIN_ENV) && !defined (AFS_XBSD_ENV)
479 /* Routine called during the afsd "-shutdown" process to put things back to
480  * the initial state.
481  */
482 static struct protosw parent_proto;     /* udp proto switch */
483
484 void
485 shutdown_rxkernel(void)
486 {
487     register struct protosw *tpro, *last;
488     last = inetdomain.dom_protoswNPROTOSW;
489     for (tpro = inetdomain.dom_protosw; tpro < last; tpro++)
490         if (tpro->pr_protocol == IPPROTO_UDP) {
491             /* restore original udp protocol switch */
492             memcpy((void *)tpro, (void *)&parent_proto, sizeof(parent_proto));
493             memset((void *)&parent_proto, 0, sizeof(parent_proto));
494             rxk_initDone = 0;
495             rxk_shutdownPorts();
496             return;
497         }
498     printf("shutdown_rxkernel: no udp proto");
499 }
500 #endif /* !AIX && !SUN && !NCR  && !UKERNEL */
501
502 #if !defined(AFS_SUN5_ENV) && !defined(AFS_SGI62_ENV)
503 /* Determine what the network interfaces are for this machine. */
504
505 #ifdef AFS_USERSPACE_IP_ADDR
506 int
507 rxi_GetcbiInfo(void)
508 {
509     int i, j, different = 0;
510     int rxmtu, maxmtu;
511     afs_uint32 ifinaddr;
512     afs_uint32 addrs[ADDRSPERSITE];
513     int mtus[ADDRSPERSITE];
514
515     memset((void *)addrs, 0, sizeof(addrs));
516     memset((void *)mtus, 0, sizeof(mtus));
517
518     for (i = 0; i < afs_cb_interface.numberOfInterfaces; i++) {
519         if (!afs_cb_interface.mtu[i])
520             afs_cb_interface.mtu[i] = htonl(1500);
521         rxmtu = (ntohl(afs_cb_interface.mtu[i]) - RX_IPUDP_SIZE);
522         ifinaddr = ntohl(afs_cb_interface.addr_in[i]);
523         if (myNetAddrs[i] != ifinaddr)
524             different++;
525
526         mtus[i] = rxmtu;
527         rxmtu = rxi_AdjustIfMTU(rxmtu);
528         maxmtu =
529             rxmtu * rxi_nRecvFrags + ((rxi_nRecvFrags - 1) * UDP_HDR_SIZE);
530         maxmtu = rxi_AdjustMaxMTU(rxmtu, maxmtu);
531         addrs[i++] = ifinaddr;
532         if ((ifinaddr != 0x7f000001) && (maxmtu > rx_maxReceiveSize)) {
533             rx_maxReceiveSize = MIN(RX_MAX_PACKET_SIZE, maxmtu);
534             rx_maxReceiveSize = MIN(rx_maxReceiveSize, rx_maxReceiveSizeUser);
535         }
536     }
537
538     rx_maxJumboRecvSize =
539         RX_HEADER_SIZE + (rxi_nDgramPackets * RX_JUMBOBUFFERSIZE) +
540         ((rxi_nDgramPackets - 1) * RX_JUMBOHEADERSIZE);
541     rx_maxJumboRecvSize = MAX(rx_maxJumboRecvSize, rx_maxReceiveSize);
542
543     if (different) {
544         for (j = 0; j < i; j++) {
545             myNetMTUs[j] = mtus[j];
546             myNetAddrs[j] = addrs[j];
547         }
548     }
549     return different;
550 }
551
552
553 /* Returns the afs_cb_interface inxex which best matches address.
554  * If none is found, we return -1.
555  */
556 afs_int32
557 rxi_Findcbi(afs_uint32 addr)
558 {
559     int j;
560     afs_uint32 myAddr, thisAddr, netMask, subnetMask;
561     afs_int32 rvalue = -1;
562     int match_value = 0;
563
564     if (numMyNetAddrs == 0)
565         (void)rxi_GetcbiInfo();
566
567     myAddr = ntohl(addr);
568
569     if (IN_CLASSA(myAddr))
570         netMask = IN_CLASSA_NET;
571     else if (IN_CLASSB(myAddr))
572         netMask = IN_CLASSB_NET;
573     else if (IN_CLASSC(myAddr))
574         netMask = IN_CLASSC_NET;
575     else
576         netMask = 0;
577
578     for (j = 0; j < afs_cb_interface.numberOfInterfaces; j++) {
579         thisAddr = ntohl(afs_cb_interface.addr_in[j]);
580         subnetMask = ntohl(afs_cb_interface.subnetmask[j]);
581         if ((myAddr & netMask) == (thisAddr & netMask)) {
582             if ((myAddr & subnetMask) == (thisAddr & subnetMask)) {
583                 if (myAddr == thisAddr) {
584                     match_value = 4;
585                     rvalue = j;
586                     break;
587                 }
588                 if (match_value < 3) {
589                     match_value = 3;
590                     rvalue = j;
591                 }
592             } else {
593                 if (match_value < 2) {
594                     match_value = 2;
595                     rvalue = j;
596                 }
597             }
598         }
599     }
600
601     return (rvalue);
602 }
603
604 #else /* AFS_USERSPACE_IP_ADDR */
605
606 #if !defined(AFS_AIX41_ENV) && !defined(AFS_DUX40_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
607 #define IFADDR2SA(f) (&((f)->ifa_addr))
608 #else /* AFS_AIX41_ENV */
609 #define IFADDR2SA(f) ((f)->ifa_addr)
610 #endif
611
612 int
613 rxi_GetIFInfo(void)
614 {
615     int i = 0;
616     int different = 0;
617
618     register struct ifnet *ifn;
619     register int rxmtu, maxmtu;
620     afs_uint32 addrs[ADDRSPERSITE];
621     int mtus[ADDRSPERSITE];
622     struct ifaddr *ifad;        /* ifnet points to a if_addrlist of ifaddrs */
623     afs_uint32 ifinaddr;
624
625     memset(addrs, 0, sizeof(addrs));
626     memset(mtus, 0, sizeof(mtus));
627
628 #if defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
629     TAILQ_FOREACH(ifn, &ifnet, if_link) {
630         if (i >= ADDRSPERSITE)
631             break;
632 #elif defined(AFS_OBSD_ENV)
633     for (ifn = ifnet.tqh_first; i < ADDRSPERSITE && ifn != NULL;
634          ifn = ifn->if_list.tqe_next) {
635 #else
636     for (ifn = ifnet; ifn != NULL && i < ADDRSPERSITE; ifn = ifn->if_next) {
637 #endif
638         rxmtu = (ifn->if_mtu - RX_IPUDP_SIZE);
639 #if defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
640         TAILQ_FOREACH(ifad, &ifn->if_addrhead, ifa_link) {
641             if (i >= ADDRSPERSITE)
642                 break;
643 #elif defined(AFS_OBSD_ENV)
644         for (ifad = ifn->if_addrlist.tqh_first;
645              ifad != NULL && i < ADDRSPERSITE;
646              ifad = ifad->ifa_list.tqe_next) {
647 #else
648         for (ifad = ifn->if_addrlist; ifad != NULL && i < ADDRSPERSITE;
649              ifad = ifad->ifa_next) {
650 #endif
651             if (IFADDR2SA(ifad)->sa_family == AF_INET) {
652                 ifinaddr =
653                     ntohl(((struct sockaddr_in *)IFADDR2SA(ifad))->sin_addr.
654                           s_addr);
655                 if (myNetAddrs[i] != ifinaddr) {
656                     different++;
657                 }
658                 mtus[i] = rxmtu;
659                 rxmtu = rxi_AdjustIfMTU(rxmtu);
660                 maxmtu =
661                     rxmtu * rxi_nRecvFrags +
662                     ((rxi_nRecvFrags - 1) * UDP_HDR_SIZE);
663                 maxmtu = rxi_AdjustMaxMTU(rxmtu, maxmtu);
664                 addrs[i++] = ifinaddr;
665                 if ((ifinaddr != 0x7f000001) && (maxmtu > rx_maxReceiveSize)) {
666                     rx_maxReceiveSize = MIN(RX_MAX_PACKET_SIZE, maxmtu);
667                     rx_maxReceiveSize =
668                         MIN(rx_maxReceiveSize, rx_maxReceiveSizeUser);
669                 }
670             }
671         }
672     }
673
674     rx_maxJumboRecvSize =
675         RX_HEADER_SIZE + rxi_nDgramPackets * RX_JUMBOBUFFERSIZE +
676         (rxi_nDgramPackets - 1) * RX_JUMBOHEADERSIZE;
677     rx_maxJumboRecvSize = MAX(rx_maxJumboRecvSize, rx_maxReceiveSize);
678
679     if (different) {
680         int j;
681         for (j = 0; j < i; j++) {
682             myNetMTUs[j] = mtus[j];
683             myNetAddrs[j] = addrs[j];
684         }
685     }
686     return different;
687 }
688
689 #if defined(AFS_DARWIN60_ENV) || defined(AFS_XBSD_ENV)
690 /* Returns ifnet which best matches address */
691 struct ifnet *
692 rxi_FindIfnet(afs_uint32 addr, afs_uint32 * maskp)
693 {
694     struct sockaddr_in s;
695     struct ifaddr *ifad;
696
697     s.sin_family = AF_INET;
698     s.sin_addr.s_addr = addr;
699     ifad = ifa_ifwithnet((struct sockaddr *)&s);
700
701     if (ifad && maskp)
702         *maskp = ((struct sockaddr_in *)ifad->ifa_netmask)->sin_addr.s_addr;
703     return (ifad ? ifad->ifa_ifp : NULL);
704 }
705
706 #else /* DARWIN60 || XBSD */
707
708 /* Returns ifnet which best matches address */
709 struct ifnet *
710 rxi_FindIfnet(afs_uint32 addr, afs_uint32 * maskp)
711 {
712     int match_value = 0;
713     extern struct in_ifaddr *in_ifaddr;
714     struct in_ifaddr *ifa, *ifad = NULL;
715
716     addr = ntohl(addr);
717
718 #if defined(AFS_DARWIN_ENV)
719     for (ifa = TAILQ_FIRST(&in_ifaddrhead); ifa;
720          ifa = TAILQ_NEXT(ifa, ia_link)) {
721 #else
722     for (ifa = in_ifaddr; ifa; ifa = ifa->ia_next) {
723 #endif
724         if ((addr & ifa->ia_netmask) == ifa->ia_net) {
725             if ((addr & ifa->ia_subnetmask) == ifa->ia_subnet) {
726                 if (IA_SIN(ifa)->sin_addr.s_addr == addr) {     /* ie, ME!!!  */
727                     match_value = 4;
728                     ifad = ifa;
729                     goto done;
730                 }
731                 if (match_value < 3) {
732                     ifad = ifa;
733                     match_value = 3;
734                 }
735             } else {
736                 if (match_value < 2) {
737                     ifad = ifa;
738                     match_value = 2;
739                 }
740             }
741         }                       /* if net matches */
742     }                           /* for all in_ifaddrs */
743
744   done:
745     if (ifad && maskp)
746         *maskp = ifad->ia_subnetmask;
747     return (ifad ? ifad->ia_ifp : NULL);
748 }
749 #endif /* else DARWIN60 || XBSD */
750 #endif /* else AFS_USERSPACE_IP_ADDR */
751 #endif /* !SUN5 && !SGI62 */
752
753
754 /* rxk_NewSocket, rxk_FreeSocket and osi_NetSend are from the now defunct
755  * afs_osinet.c. One could argue that rxi_NewSocket could go into the
756  * system specific subdirectories for all systems. But for the moment,
757  * most of it is simple to follow common code.
758  */
759 #if !defined(UKERNEL)
760 #if !defined(AFS_SUN5_ENV) && !defined(AFS_LINUX20_ENV)
761 /* rxk_NewSocket creates a new socket on the specified port. The port is
762  * in network byte order.
763  */
764 struct osi_socket *
765 rxk_NewSocketHost(afs_uint32 ahost, short aport)
766 {
767     register afs_int32 code;
768     struct socket *newSocket;
769 #if (!defined(AFS_HPUX1122_ENV) && !defined(AFS_FBSD50_ENV))
770     struct mbuf *nam;
771 #endif
772     struct sockaddr_in myaddr;
773 #ifdef AFS_HPUX110_ENV
774     /* prototype copied from kernel source file streams/str_proto.h */
775     extern MBLKP allocb_wait(int, int);
776     MBLKP bindnam;
777     int addrsize = sizeof(struct sockaddr_in);
778     struct file *fp;
779     extern struct fileops socketops;
780 #endif
781 #ifdef AFS_SGI65_ENV
782     bhv_desc_t bhv;
783 #endif
784
785     AFS_STATCNT(osi_NewSocket);
786 #if (defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)) && defined(KERNEL_FUNNEL)
787     thread_funnel_switch(KERNEL_FUNNEL, NETWORK_FUNNEL);
788 #endif
789     AFS_ASSERT_GLOCK();
790     AFS_GUNLOCK();
791 #if     defined(AFS_HPUX102_ENV)
792 #if     defined(AFS_HPUX110_ENV)
793     /* we need a file associated with the socket so sosend in NetSend 
794      * will not fail */
795     /* blocking socket */
796     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, 0, 0);
797     fp = falloc();
798     if (!fp)
799         goto bad;
800     fp->f_flag = FREAD | FWRITE;
801     fp->f_type = DTYPE_SOCKET;
802     fp->f_ops = &socketops;
803
804     fp->f_data = (void *)newSocket;
805     newSocket->so_fp = (void *)fp;
806
807 #else /* AFS_HPUX110_ENV */
808     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, 0, SS_NOWAIT);
809 #endif /* else AFS_HPUX110_ENV */
810 #elif defined(AFS_SGI65_ENV) || defined(AFS_OBSD_ENV)
811     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, IPPROTO_UDP);
812 #elif defined(AFS_FBSD50_ENV)
813     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, IPPROTO_UDP,
814                     afs_osi_credp, curthread);
815 #elif defined(AFS_FBSD40_ENV)
816     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, IPPROTO_UDP, curproc);
817 #else
818     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, 0);
819 #endif /* AFS_HPUX102_ENV */
820     if (code)
821         goto bad;
822
823     memset(&myaddr, 0, sizeof myaddr);
824     myaddr.sin_family = AF_INET;
825     myaddr.sin_port = aport;
826     myaddr.sin_addr.s_addr = ahost;
827 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
828     myaddr.sin_len = sizeof(myaddr);
829 #endif
830
831 #ifdef AFS_HPUX110_ENV
832     bindnam = allocb_wait((addrsize + SO_MSGOFFSET + 1), BPRI_MED);
833     if (!bindnam) {
834         setuerror(ENOBUFS);
835         goto bad;
836     }
837     memcpy((caddr_t) bindnam->b_rptr + SO_MSGOFFSET, (caddr_t) & myaddr,
838            addrsize);
839     bindnam->b_wptr = bindnam->b_rptr + (addrsize + SO_MSGOFFSET + 1);
840
841     code = sobind(newSocket, bindnam, addrsize);
842     if (code) {
843         soclose(newSocket);
844 #if !defined(AFS_HPUX1122_ENV)
845         m_freem(nam);
846 #endif
847         goto bad;
848     }
849
850     freeb(bindnam);
851 #else /* AFS_HPUX110_ENV */
852     code = soreserve(newSocket, 50000, 50000);
853     if (code) {
854         code = soreserve(newSocket, 32766, 32766);
855         if (code)
856             osi_Panic("osi_NewSocket: last attempt to reserve 32K failed!\n");
857     }
858 #if defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
859 #if defined(AFS_FBSD50_ENV)
860     code = sobind(newSocket, (struct sockaddr *)&myaddr, curthread);
861 #elif defined(AFS_FBSD40_ENV)
862     code = sobind(newSocket, (struct sockaddr *)&myaddr, curproc);
863 #else
864     code = sobind(newSocket, (struct sockaddr *)&myaddr);
865 #endif
866     if (code) {
867         printf("sobind fails (%d)\n", (int)code);
868         soclose(newSocket);
869         AFS_GLOCK();
870         goto bad;
871     }
872 #else /* defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV) */
873 #ifdef  AFS_OSF_ENV
874     nam = m_getclr(M_WAIT, MT_SONAME);
875 #else /* AFS_OSF_ENV */
876     nam = m_get(M_WAIT, MT_SONAME);
877 #endif
878     if (nam == NULL) {
879 #if defined(KERNEL_HAVE_UERROR)
880         setuerror(ENOBUFS);
881 #endif
882         goto bad;
883     }
884     nam->m_len = sizeof(myaddr);
885     memcpy(mtod(nam, caddr_t), &myaddr, sizeof(myaddr));
886 #ifdef AFS_SGI65_ENV
887     BHV_PDATA(&bhv) = (void *)newSocket;
888     code = sobind(&bhv, nam);
889     m_freem(nam);
890 #else
891     code = sobind(newSocket, nam);
892 #endif
893     if (code) {
894         printf("sobind fails (%d)\n", (int)code);
895         soclose(newSocket);
896 #ifndef AFS_SGI65_ENV
897         m_freem(nam);
898 #endif
899         goto bad;
900     }
901 #endif /* else AFS_DARWIN_ENV */
902 #endif /* else AFS_HPUX110_ENV */
903
904     AFS_GLOCK();
905 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
906     thread_funnel_switch(NETWORK_FUNNEL, KERNEL_FUNNEL);
907 #endif
908     return (struct osi_socket *)newSocket;
909
910   bad:
911     AFS_GLOCK();
912 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
913     thread_funnel_switch(NETWORK_FUNNEL, KERNEL_FUNNEL);
914 #endif
915     return (struct osi_socket *)0;
916 }
917
918 struct osi_socket *
919 rxk_NewSocket(short aport)
920 {
921     return rxk_NewSocketHost(0, aport);
922 }
923
924 /* free socket allocated by rxk_NewSocket */
925 int
926 rxk_FreeSocket(register struct socket *asocket)
927 {
928     AFS_STATCNT(osi_FreeSocket);
929 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
930     thread_funnel_switch(KERNEL_FUNNEL, NETWORK_FUNNEL);
931 #endif
932 #ifdef AFS_HPUX110_ENV
933     if (asocket->so_fp) {
934         struct file *fp = asocket->so_fp;
935 #if !defined(AFS_HPUX1123_ENV)
936         /* 11.23 still has falloc, but not FPENTRYFREE ! 
937          * so for now if we shutdown, we will waist a file 
938          * structure */
939         FPENTRYFREE(fp);
940         asocket->so_fp = NULL;
941 #endif
942     }
943 #endif /* AFS_HPUX110_ENV */
944     soclose(asocket);
945 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
946     thread_funnel_switch(NETWORK_FUNNEL, KERNEL_FUNNEL);
947 #endif
948     return 0;
949 }
950 #endif /* !SUN5 && !LINUX20 */
951
952 #if defined(RXK_LISTENER_ENV) || defined(AFS_SUN5_ENV)
953 /*
954  * Run RX event daemon every second (5 times faster than rest of systems)
955  */
956 void
957 afs_rxevent_daemon(void)
958 {
959     struct clock temp;
960     SPLVAR;
961
962     while (1) {
963 #ifdef RX_ENABLE_LOCKS
964         AFS_GUNLOCK();
965 #endif /* RX_ENABLE_LOCKS */
966         NETPRI;
967         AFS_RXGLOCK();
968         rxevent_RaiseEvents(&temp);
969         AFS_RXGUNLOCK();
970         USERPRI;
971 #ifdef RX_ENABLE_LOCKS
972         AFS_GLOCK();
973 #endif /* RX_ENABLE_LOCKS */
974 #ifdef RX_KERNEL_TRACE
975         afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
976                    "before afs_osi_Wait()");
977 #endif
978         afs_osi_Wait(500, NULL, 0);
979 #ifdef RX_KERNEL_TRACE
980         afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
981                    "after afs_osi_Wait()");
982 #endif
983         if (afs_termState == AFSOP_STOP_RXEVENT) {
984 #ifdef RXK_LISTENER_ENV
985             afs_termState = AFSOP_STOP_RXK_LISTENER;
986 #else
987             afs_termState = AFSOP_STOP_COMPLETE;
988 #endif
989             osi_rxWakeup(&afs_termState);
990             return;
991         }
992     }
993 }
994 #endif
995
996 #ifdef RXK_LISTENER_ENV
997
998 /* rxk_ReadPacket returns 1 if valid packet, 0 on error. */
999 int
1000 rxk_ReadPacket(osi_socket so, struct rx_packet *p, int *host, int *port)
1001 {
1002     int code;
1003     struct sockaddr_in from;
1004     int nbytes;
1005     afs_int32 rlen;
1006     register afs_int32 tlen;
1007     afs_int32 savelen;          /* was using rlen but had aliasing problems */
1008     rx_computelen(p, tlen);
1009     rx_SetDataSize(p, tlen);    /* this is the size of the user data area */
1010
1011     tlen += RX_HEADER_SIZE;     /* now this is the size of the entire packet */
1012     rlen = rx_maxJumboRecvSize; /* this is what I am advertising.  Only check
1013                                  * it once in order to avoid races.  */
1014     tlen = rlen - tlen;
1015     if (tlen > 0) {
1016         tlen = rxi_AllocDataBuf(p, tlen, RX_PACKET_CLASS_RECV_CBUF);
1017         if (tlen > 0) {
1018             tlen = rlen - tlen;
1019         } else
1020             tlen = rlen;
1021     } else
1022         tlen = rlen;
1023
1024     /* add some padding to the last iovec, it's just to make sure that the 
1025      * read doesn't return more data than we expect, and is done to get around
1026      * our problems caused by the lack of a length field in the rx header. */
1027     savelen = p->wirevec[p->niovecs - 1].iov_len;
1028     p->wirevec[p->niovecs - 1].iov_len = savelen + RX_EXTRABUFFERSIZE;
1029
1030     nbytes = tlen + sizeof(afs_int32);
1031 #ifdef RX_KERNEL_TRACE
1032     if (ICL_SETACTIVE(afs_iclSetp)) {
1033         AFS_GLOCK();
1034         afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1035                    "before osi_NetRecive()");
1036         AFS_GUNLOCK();
1037     }
1038 #endif
1039     code = osi_NetReceive(rx_socket, &from, p->wirevec, p->niovecs, &nbytes);
1040
1041 #ifdef RX_KERNEL_TRACE
1042     if (ICL_SETACTIVE(afs_iclSetp)) {
1043         AFS_GLOCK();
1044         afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1045                    "after osi_NetRecive()");
1046         AFS_GUNLOCK();
1047     }
1048 #endif
1049     /* restore the vec to its correct state */
1050     p->wirevec[p->niovecs - 1].iov_len = savelen;
1051
1052     if (!code) {
1053         p->length = nbytes - RX_HEADER_SIZE;;
1054         if ((nbytes > tlen) || (p->length & 0x8000)) {  /* Bogus packet */
1055             if (nbytes > 0)
1056                 rxi_MorePackets(rx_initSendWindow);
1057             else {
1058                 MUTEX_ENTER(&rx_stats_mutex);
1059                 rx_stats.bogusPacketOnRead++;
1060                 rx_stats.bogusHost = from.sin_addr.s_addr;
1061                 MUTEX_EXIT(&rx_stats_mutex);
1062                 dpf(("B: bogus packet from [%x,%d] nb=%d",
1063                      from.sin_addr.s_addr, from.sin_port, nbytes));
1064             }
1065             return -1;
1066         } else {
1067             /* Extract packet header. */
1068             rxi_DecodePacketHeader(p);
1069
1070             *host = from.sin_addr.s_addr;
1071             *port = from.sin_port;
1072             if (p->header.type > 0 && p->header.type < RX_N_PACKET_TYPES) {
1073                 MUTEX_ENTER(&rx_stats_mutex);
1074                 rx_stats.packetsRead[p->header.type - 1]++;
1075                 MUTEX_EXIT(&rx_stats_mutex);
1076             }
1077
1078             /* Free any empty packet buffers at the end of this packet */
1079             rxi_TrimDataBufs(p, 1);
1080
1081             return 0;
1082         }
1083     } else
1084         return code;
1085 }
1086
1087 /* rxk_Listener() 
1088  *
1089  * Listen for packets on socket. This thread is typically started after
1090  * rx_Init has called rxi_StartListener(), but nevertheless, ensures that
1091  * the start state is set before proceeding.
1092  *
1093  * Note that this thread is outside the AFS global lock for much of
1094  * it's existence.
1095  *
1096  * In many OS's, the socket receive code sleeps interruptibly. That's not what
1097  * we want here. So we need to either block all signals (including SIGKILL
1098  * and SIGSTOP) or reset the thread's signal state to unsignalled when the
1099  * OS's socket receive routine returns as a result of a signal.
1100  */
1101 int rxk_ListenerPid;            /* Used to signal process to wakeup at shutdown */
1102
1103 #ifdef AFS_SUN5_ENV
1104 /*
1105  * Run the listener as a kernel thread.
1106  */
1107 void
1108 rxk_Listener(void)
1109 {
1110     extern id_t syscid;
1111     void rxk_ListenerProc(void);
1112     if (thread_create
1113         (NULL, DEFAULTSTKSZ, rxk_ListenerProc, 0, 0, &p0, TS_RUN,
1114          minclsyspri) == NULL)
1115         osi_Panic("rxk_Listener: failed to start listener thread!\n");
1116 }
1117
1118 void
1119 rxk_ListenerProc(void)
1120 #else /* AFS_SUN5_ENV */
1121 void
1122 rxk_Listener(void)
1123 #endif                          /* AFS_SUN5_ENV */
1124 {
1125     struct rx_packet *rxp = NULL;
1126     int code;
1127     int host, port;
1128
1129 #ifdef AFS_LINUX20_ENV
1130     rxk_ListenerPid = current->pid;
1131 #endif
1132 #ifdef AFS_SUN5_ENV
1133     rxk_ListenerPid = 1;        /* No PID, just a flag that we're alive */
1134 #endif /* AFS_SUN5_ENV */
1135 #ifdef AFS_XBSD_ENV
1136     rxk_ListenerPid = curproc->p_pid;
1137 #endif /* AFS_FBSD_ENV */
1138 #if defined(AFS_DARWIN_ENV)
1139     rxk_ListenerPid = current_proc()->p_pid;
1140 #endif
1141 #if defined(RX_ENABLE_LOCKS) && !defined(AFS_SUN5_ENV)
1142     AFS_GUNLOCK();
1143 #endif /* RX_ENABLE_LOCKS && !AFS_SUN5_ENV */
1144
1145     while (afs_termState != AFSOP_STOP_RXK_LISTENER) {
1146         if (rxp) {
1147             rxi_RestoreDataBufs(rxp);
1148         } else {
1149             rxp = rxi_AllocPacket(RX_PACKET_CLASS_RECEIVE);
1150             if (!rxp)
1151                 osi_Panic("rxk_Listener: No more Rx buffers!\n");
1152         }
1153         if (!(code = rxk_ReadPacket(rx_socket, rxp, &host, &port))) {
1154             AFS_RXGLOCK();
1155             rxp = rxi_ReceivePacket(rxp, rx_socket, host, port, 0, 0);
1156             AFS_RXGUNLOCK();
1157         }
1158     }
1159
1160 #ifdef RX_ENABLE_LOCKS
1161     AFS_GLOCK();
1162 #endif /* RX_ENABLE_LOCKS */
1163     if (afs_termState == AFSOP_STOP_RXK_LISTENER) {
1164         afs_termState = AFSOP_STOP_COMPLETE;
1165         osi_rxWakeup(&afs_termState);
1166     }
1167     rxk_ListenerPid = 0;
1168 #if defined(AFS_LINUX22_ENV) || defined(AFS_SUN5_ENV)
1169     osi_rxWakeup(&rxk_ListenerPid);
1170 #endif
1171 #ifdef AFS_SUN5_ENV
1172     AFS_GUNLOCK();
1173 #endif /* AFS_SUN5_ENV */
1174 }
1175
1176 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_SUN5_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
1177 /* The manner of stopping the rx listener thread may vary. Most unix's should
1178  * be able to call soclose.
1179  */
1180 void
1181 osi_StopListener(void)
1182 {
1183     soclose(rx_socket);
1184 }
1185 #endif
1186 #endif /* RXK_LISTENER_ENV */
1187
1188 #endif /* !NCR && !UKERNEL */