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