6563ef8c1904c67f886138e5c947c8391d569a81
[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         rxmtu = (ntohl(afs_cb_interface.mtu[i]) - RX_IPUDP_SIZE);
514         ifinaddr = ntohl(afs_cb_interface.addr_in[i]);
515         if (myNetAddrs[i] != ifinaddr)
516             different++;
517
518         mtus[i] = rxmtu;
519         rxmtu = rxi_AdjustIfMTU(rxmtu);
520         maxmtu =
521             rxmtu * rxi_nRecvFrags + ((rxi_nRecvFrags - 1) * UDP_HDR_SIZE);
522         maxmtu = rxi_AdjustMaxMTU(rxmtu, maxmtu);
523         addrs[i++] = ifinaddr;
524         if ((ifinaddr != 0x7f000001) && (maxmtu > rx_maxReceiveSize)) {
525             rx_maxReceiveSize = MIN(RX_MAX_PACKET_SIZE, maxmtu);
526             rx_maxReceiveSize = MIN(rx_maxReceiveSize, rx_maxReceiveSizeUser);
527         }
528     }
529
530     rx_maxJumboRecvSize =
531         RX_HEADER_SIZE + (rxi_nDgramPackets * RX_JUMBOBUFFERSIZE) +
532         ((rxi_nDgramPackets - 1) * RX_JUMBOHEADERSIZE);
533     rx_maxJumboRecvSize = MAX(rx_maxJumboRecvSize, rx_maxReceiveSize);
534
535     if (different) {
536         for (j = 0; j < i; j++) {
537             myNetMTUs[j] = mtus[j];
538             myNetAddrs[j] = addrs[j];
539         }
540     }
541     return different;
542 }
543
544
545 /* Returns the afs_cb_interface inxex which best matches address.
546  * If none is found, we return -1.
547  */
548 afs_int32
549 rxi_Findcbi(afs_uint32 addr)
550 {
551     int j;
552     afs_uint32 myAddr, thisAddr, netMask, subnetMask;
553     afs_int32 rvalue = -1;
554     int match_value = 0;
555
556     if (numMyNetAddrs == 0)
557         (void)rxi_GetcbiInfo();
558
559     myAddr = ntohl(addr);
560
561     if (IN_CLASSA(myAddr))
562         netMask = IN_CLASSA_NET;
563     else if (IN_CLASSB(myAddr))
564         netMask = IN_CLASSB_NET;
565     else if (IN_CLASSC(myAddr))
566         netMask = IN_CLASSC_NET;
567     else
568         netMask = 0;
569
570     for (j = 0; j < afs_cb_interface.numberOfInterfaces; j++) {
571         thisAddr = ntohl(afs_cb_interface.addr_in[j]);
572         subnetMask = ntohl(afs_cb_interface.subnetmask[j]);
573         if ((myAddr & netMask) == (thisAddr & netMask)) {
574             if ((myAddr & subnetMask) == (thisAddr & subnetMask)) {
575                 if (myAddr == thisAddr) {
576                     match_value = 4;
577                     rvalue = j;
578                     break;
579                 }
580                 if (match_value < 3) {
581                     match_value = 3;
582                     rvalue = j;
583                 }
584             } else {
585                 if (match_value < 2) {
586                     match_value = 2;
587                     rvalue = j;
588                 }
589             }
590         }
591     }
592
593     return (rvalue);
594 }
595
596 #else /* AFS_USERSPACE_IP_ADDR */
597
598 #if !defined(AFS_AIX41_ENV) && !defined(AFS_DUX40_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
599 #define IFADDR2SA(f) (&((f)->ifa_addr))
600 #else /* AFS_AIX41_ENV */
601 #define IFADDR2SA(f) ((f)->ifa_addr)
602 #endif
603
604 int
605 rxi_GetIFInfo(void)
606 {
607     int i = 0;
608     int different = 0;
609
610     register struct ifnet *ifn;
611     register int rxmtu, maxmtu;
612     afs_uint32 addrs[ADDRSPERSITE];
613     int mtus[ADDRSPERSITE];
614     struct ifaddr *ifad;        /* ifnet points to a if_addrlist of ifaddrs */
615     afs_uint32 ifinaddr;
616
617     memset(addrs, 0, sizeof(addrs));
618     memset(mtus, 0, sizeof(mtus));
619
620 #if defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
621     TAILQ_FOREACH(ifn, &ifnet, if_link) {
622         if (i >= ADDRSPERSITE)
623             break;
624 #elif defined(AFS_OBSD_ENV)
625     for (ifn = ifnet.tqh_first; i < ADDRSPERSITE && ifn != NULL;
626          ifn = ifn->if_list.tqe_next) {
627 #else
628     for (ifn = ifnet; ifn != NULL && i < ADDRSPERSITE; ifn = ifn->if_next) {
629 #endif
630         rxmtu = (ifn->if_mtu - RX_IPUDP_SIZE);
631 #if defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
632         TAILQ_FOREACH(ifad, &ifn->if_addrhead, ifa_link) {
633             if (i >= ADDRSPERSITE)
634                 break;
635 #elif defined(AFS_OBSD_ENV)
636         for (ifad = ifn->if_addrlist.tqh_first;
637              ifad != NULL && i < ADDRSPERSITE;
638              ifad = ifad->ifa_list.tqe_next) {
639 #else
640         for (ifad = ifn->if_addrlist; ifad != NULL && i < ADDRSPERSITE;
641              ifad = ifad->ifa_next) {
642 #endif
643             if (IFADDR2SA(ifad)->sa_family == AF_INET) {
644                 ifinaddr =
645                     ntohl(((struct sockaddr_in *)IFADDR2SA(ifad))->sin_addr.
646                           s_addr);
647                 if (myNetAddrs[i] != ifinaddr) {
648                     different++;
649                 }
650                 mtus[i] = rxmtu;
651                 rxmtu = rxi_AdjustIfMTU(rxmtu);
652                 maxmtu =
653                     rxmtu * rxi_nRecvFrags +
654                     ((rxi_nRecvFrags - 1) * UDP_HDR_SIZE);
655                 maxmtu = rxi_AdjustMaxMTU(rxmtu, maxmtu);
656                 addrs[i++] = ifinaddr;
657                 if ((ifinaddr != 0x7f000001) && (maxmtu > rx_maxReceiveSize)) {
658                     rx_maxReceiveSize = MIN(RX_MAX_PACKET_SIZE, maxmtu);
659                     rx_maxReceiveSize =
660                         MIN(rx_maxReceiveSize, rx_maxReceiveSizeUser);
661                 }
662             }
663         }
664     }
665
666     rx_maxJumboRecvSize =
667         RX_HEADER_SIZE + rxi_nDgramPackets * RX_JUMBOBUFFERSIZE +
668         (rxi_nDgramPackets - 1) * RX_JUMBOHEADERSIZE;
669     rx_maxJumboRecvSize = MAX(rx_maxJumboRecvSize, rx_maxReceiveSize);
670
671     if (different) {
672         int j;
673         for (j = 0; j < i; j++) {
674             myNetMTUs[j] = mtus[j];
675             myNetAddrs[j] = addrs[j];
676         }
677     }
678     return different;
679 }
680
681 #if defined(AFS_DARWIN60_ENV) || defined(AFS_XBSD_ENV)
682 /* Returns ifnet which best matches address */
683 struct ifnet *
684 rxi_FindIfnet(afs_uint32 addr, afs_uint32 * maskp)
685 {
686     struct sockaddr_in s;
687     struct ifaddr *ifad;
688
689     s.sin_family = AF_INET;
690     s.sin_addr.s_addr = addr;
691     ifad = ifa_ifwithnet((struct sockaddr *)&s);
692
693     if (ifad && maskp)
694         *maskp = ((struct sockaddr_in *)ifad->ifa_netmask)->sin_addr.s_addr;
695     return (ifad ? ifad->ifa_ifp : NULL);
696 }
697
698 #else /* DARWIN60 || XBSD */
699
700 /* Returns ifnet which best matches address */
701 struct ifnet *
702 rxi_FindIfnet(afs_uint32 addr, afs_uint32 * maskp)
703 {
704     int match_value = 0;
705     extern struct in_ifaddr *in_ifaddr;
706     struct in_ifaddr *ifa, *ifad = NULL;
707
708     addr = ntohl(addr);
709
710 #if defined(AFS_DARWIN_ENV)
711     for (ifa = TAILQ_FIRST(&in_ifaddrhead); ifa;
712          ifa = TAILQ_NEXT(ifa, ia_link)) {
713 #else
714     for (ifa = in_ifaddr; ifa; ifa = ifa->ia_next) {
715 #endif
716         if ((addr & ifa->ia_netmask) == ifa->ia_net) {
717             if ((addr & ifa->ia_subnetmask) == ifa->ia_subnet) {
718                 if (IA_SIN(ifa)->sin_addr.s_addr == addr) {     /* ie, ME!!!  */
719                     match_value = 4;
720                     ifad = ifa;
721                     goto done;
722                 }
723                 if (match_value < 3) {
724                     ifad = ifa;
725                     match_value = 3;
726                 }
727             } else {
728                 if (match_value < 2) {
729                     ifad = ifa;
730                     match_value = 2;
731                 }
732             }
733         }                       /* if net matches */
734     }                           /* for all in_ifaddrs */
735
736   done:
737     if (ifad && maskp)
738         *maskp = ifad->ia_subnetmask;
739     return (ifad ? ifad->ia_ifp : NULL);
740 }
741 #endif /* else DARWIN60 || XBSD */
742 #endif /* else AFS_USERSPACE_IP_ADDR */
743 #endif /* !SUN5 && !SGI62 */
744
745
746 /* rxk_NewSocket, rxk_FreeSocket and osi_NetSend are from the now defunct
747  * afs_osinet.c. One could argue that rxi_NewSocket could go into the
748  * system specific subdirectories for all systems. But for the moment,
749  * most of it is simple to follow common code.
750  */
751 #if !defined(UKERNEL)
752 #if !defined(AFS_SUN5_ENV) && !defined(AFS_LINUX20_ENV)
753 /* rxk_NewSocket creates a new socket on the specified port. The port is
754  * in network byte order.
755  */
756 struct osi_socket *
757 rxk_NewSocket(short aport)
758 {
759     register afs_int32 code;
760     struct socket *newSocket;
761 #if (!defined(AFS_HPUX1122_ENV) && !defined(AFS_FBSD50_ENV))
762     struct mbuf *nam;
763 #endif
764     struct sockaddr_in myaddr;
765 #ifdef AFS_HPUX110_ENV
766     /* prototype copied from kernel source file streams/str_proto.h */
767     extern MBLKP allocb_wait(int, int);
768     MBLKP bindnam;
769     int addrsize = sizeof(struct sockaddr_in);
770 #endif
771 #ifdef AFS_SGI65_ENV
772     bhv_desc_t bhv;
773 #endif
774
775     AFS_STATCNT(osi_NewSocket);
776 #if (defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)) && defined(KERNEL_FUNNEL)
777     thread_funnel_switch(KERNEL_FUNNEL, NETWORK_FUNNEL);
778 #endif
779 #if     defined(AFS_HPUX102_ENV)
780 #if     defined(AFS_HPUX110_ENV)
781     /* blocking socket */
782     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, 0, 0);
783 #else /* AFS_HPUX110_ENV */
784     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, 0, SS_NOWAIT);
785 #endif /* else AFS_HPUX110_ENV */
786 #elif defined(AFS_SGI65_ENV) || defined(AFS_OBSD_ENV)
787     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, IPPROTO_UDP);
788 #elif defined(AFS_FBSD50_ENV)
789     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, IPPROTO_UDP,
790                     afs_osi_credp, curthread);
791 #elif defined(AFS_FBSD40_ENV)
792     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, IPPROTO_UDP, curproc);
793 #else
794     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, 0);
795 #endif /* AFS_HPUX102_ENV */
796     if (code)
797         goto bad;
798
799     myaddr.sin_family = AF_INET;
800     myaddr.sin_port = aport;
801     myaddr.sin_addr.s_addr = 0;
802 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
803     myaddr.sin_len = sizeof(myaddr);
804 #endif
805
806 #ifdef AFS_HPUX110_ENV
807     bindnam = allocb_wait((addrsize + SO_MSGOFFSET + 1), BPRI_MED);
808     if (!bindnam) {
809         setuerror(ENOBUFS);
810         goto bad;
811     }
812     memcpy((caddr_t) bindnam->b_rptr + SO_MSGOFFSET, (caddr_t) & myaddr,
813            addrsize);
814     bindnam->b_wptr = bindnam->b_rptr + (addrsize + SO_MSGOFFSET + 1);
815
816     code = sobind(newSocket, bindnam, addrsize);
817     if (code) {
818         soclose(newSocket);
819 #if !defined(AFS_HPUX1122_ENV)
820         m_freem(nam);
821 #endif
822         goto bad;
823     }
824
825     freeb(bindnam);
826 #else /* AFS_HPUX110_ENV */
827     code = soreserve(newSocket, 50000, 50000);
828     if (code) {
829         code = soreserve(newSocket, 32766, 32766);
830         if (code)
831             osi_Panic("osi_NewSocket: last attempt to reserve 32K failed!\n");
832     }
833 #if defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV)
834 #if defined(AFS_FBSD50_ENV)
835     code = sobind(newSocket, (struct sockaddr *)&myaddr, curthread);
836 #elif defined(AFS_FBSD40_ENV)
837     code = sobind(newSocket, (struct sockaddr *)&myaddr, curproc);
838 #else
839     code = sobind(newSocket, (struct sockaddr *)&myaddr);
840 #endif
841     if (code) {
842         printf("sobind fails (%d)\n", (int)code);
843         soclose(newSocket);
844         goto bad;
845     }
846 #else /* defined(AFS_DARWIN_ENV) || defined(AFS_FBSD_ENV) */
847 #ifdef  AFS_OSF_ENV
848     nam = m_getclr(M_WAIT, MT_SONAME);
849 #else /* AFS_OSF_ENV */
850     nam = m_get(M_WAIT, MT_SONAME);
851 #endif
852     if (nam == NULL) {
853 #if defined(KERNEL_HAVE_UERROR)
854         setuerror(ENOBUFS);
855 #endif
856         goto bad;
857     }
858     nam->m_len = sizeof(myaddr);
859     memcpy(mtod(nam, caddr_t), &myaddr, sizeof(myaddr));
860 #ifdef AFS_SGI65_ENV
861     BHV_PDATA(&bhv) = (void *)newSocket;
862     code = sobind(&bhv, nam);
863     m_freem(nam);
864 #else
865     code = sobind(newSocket, nam);
866 #endif
867     if (code) {
868         printf("sobind fails (%d)\n", (int)code);
869         soclose(newSocket);
870 #ifndef AFS_SGI65_ENV
871         m_freem(nam);
872 #endif
873         goto bad;
874     }
875 #endif /* else AFS_DARWIN_ENV */
876 #endif /* else AFS_HPUX110_ENV */
877
878 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
879     thread_funnel_switch(NETWORK_FUNNEL, KERNEL_FUNNEL);
880 #endif
881     return (struct osi_socket *)newSocket;
882
883   bad:
884 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
885     thread_funnel_switch(NETWORK_FUNNEL, KERNEL_FUNNEL);
886 #endif
887     return (struct osi_socket *)0;
888 }
889
890
891 /* free socket allocated by rxk_NewSocket */
892 int
893 rxk_FreeSocket(register struct socket *asocket)
894 {
895     AFS_STATCNT(osi_FreeSocket);
896 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
897     thread_funnel_switch(KERNEL_FUNNEL, NETWORK_FUNNEL);
898 #endif
899     soclose(asocket);
900 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
901     thread_funnel_switch(NETWORK_FUNNEL, KERNEL_FUNNEL);
902 #endif
903     return 0;
904 }
905 #endif /* !SUN5 && !LINUX20 */
906
907 #if defined(RXK_LISTENER_ENV) || defined(AFS_SUN5_ENV)
908 /*
909  * Run RX event daemon every second (5 times faster than rest of systems)
910  */
911 void
912 afs_rxevent_daemon(void)
913 {
914     struct clock temp;
915     SPLVAR;
916
917     while (1) {
918 #ifdef RX_ENABLE_LOCKS
919         AFS_GUNLOCK();
920 #endif /* RX_ENABLE_LOCKS */
921         NETPRI;
922         AFS_RXGLOCK();
923         rxevent_RaiseEvents(&temp);
924         AFS_RXGUNLOCK();
925         USERPRI;
926 #ifdef RX_ENABLE_LOCKS
927         AFS_GLOCK();
928 #endif /* RX_ENABLE_LOCKS */
929 #ifdef RX_KERNEL_TRACE
930         afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
931                    "before afs_osi_Wait()");
932 #endif
933         afs_osi_Wait(500, NULL, 0);
934 #ifdef RX_KERNEL_TRACE
935         afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
936                    "after afs_osi_Wait()");
937 #endif
938         if (afs_termState == AFSOP_STOP_RXEVENT) {
939 #ifdef RXK_LISTENER_ENV
940             afs_termState = AFSOP_STOP_RXK_LISTENER;
941 #else
942             afs_termState = AFSOP_STOP_COMPLETE;
943 #endif
944             osi_rxWakeup(&afs_termState);
945             return;
946         }
947     }
948 }
949 #endif
950
951 #ifdef RXK_LISTENER_ENV
952
953 /* rxk_ReadPacket returns 1 if valid packet, 0 on error. */
954 int
955 rxk_ReadPacket(osi_socket so, struct rx_packet *p, int *host, int *port)
956 {
957     int code;
958     struct sockaddr_in from;
959     int nbytes;
960     afs_int32 rlen;
961     register afs_int32 tlen;
962     afs_int32 savelen;          /* was using rlen but had aliasing problems */
963     rx_computelen(p, tlen);
964     rx_SetDataSize(p, tlen);    /* this is the size of the user data area */
965
966     tlen += RX_HEADER_SIZE;     /* now this is the size of the entire packet */
967     rlen = rx_maxJumboRecvSize; /* this is what I am advertising.  Only check
968                                  * it once in order to avoid races.  */
969     tlen = rlen - tlen;
970     if (tlen > 0) {
971         tlen = rxi_AllocDataBuf(p, tlen, RX_PACKET_CLASS_RECV_CBUF);
972         if (tlen > 0) {
973             tlen = rlen - tlen;
974         } else
975             tlen = rlen;
976     } else
977         tlen = rlen;
978
979     /* add some padding to the last iovec, it's just to make sure that the 
980      * read doesn't return more data than we expect, and is done to get around
981      * our problems caused by the lack of a length field in the rx header. */
982     savelen = p->wirevec[p->niovecs - 1].iov_len;
983     p->wirevec[p->niovecs - 1].iov_len = savelen + RX_EXTRABUFFERSIZE;
984
985     nbytes = tlen + sizeof(afs_int32);
986 #ifdef RX_KERNEL_TRACE
987     if (ICL_SETACTIVE(afs_iclSetp)) {
988         AFS_GLOCK();
989         afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
990                    "before osi_NetRecive()");
991         AFS_GUNLOCK();
992     }
993 #endif
994     code = osi_NetReceive(rx_socket, &from, p->wirevec, p->niovecs, &nbytes);
995
996 #ifdef RX_KERNEL_TRACE
997     if (ICL_SETACTIVE(afs_iclSetp)) {
998         AFS_GLOCK();
999         afs_Trace1(afs_iclSetp, CM_TRACE_TIMESTAMP, ICL_TYPE_STRING,
1000                    "after osi_NetRecive()");
1001         AFS_GUNLOCK();
1002     }
1003 #endif
1004     /* restore the vec to its correct state */
1005     p->wirevec[p->niovecs - 1].iov_len = savelen;
1006
1007     if (!code) {
1008         p->length = nbytes - RX_HEADER_SIZE;;
1009         if ((nbytes > tlen) || (p->length & 0x8000)) {  /* Bogus packet */
1010             if (nbytes > 0)
1011                 rxi_MorePackets(rx_initSendWindow);
1012             else {
1013                 MUTEX_ENTER(&rx_stats_mutex);
1014                 rx_stats.bogusPacketOnRead++;
1015                 rx_stats.bogusHost = from.sin_addr.s_addr;
1016                 MUTEX_EXIT(&rx_stats_mutex);
1017                 dpf(("B: bogus packet from [%x,%d] nb=%d",
1018                      from.sin_addr.s_addr, from.sin_port, nbytes));
1019             }
1020             return -1;
1021         } else {
1022             /* Extract packet header. */
1023             rxi_DecodePacketHeader(p);
1024
1025             *host = from.sin_addr.s_addr;
1026             *port = from.sin_port;
1027             if (p->header.type > 0 && p->header.type < RX_N_PACKET_TYPES) {
1028                 MUTEX_ENTER(&rx_stats_mutex);
1029                 rx_stats.packetsRead[p->header.type - 1]++;
1030                 MUTEX_EXIT(&rx_stats_mutex);
1031             }
1032
1033             /* Free any empty packet buffers at the end of this packet */
1034             rxi_TrimDataBufs(p, 1);
1035
1036             return 0;
1037         }
1038     } else
1039         return code;
1040 }
1041
1042 /* rxk_Listener() 
1043  *
1044  * Listen for packets on socket. This thread is typically started after
1045  * rx_Init has called rxi_StartListener(), but nevertheless, ensures that
1046  * the start state is set before proceeding.
1047  *
1048  * Note that this thread is outside the AFS global lock for much of
1049  * it's existence.
1050  *
1051  * In many OS's, the socket receive code sleeps interruptibly. That's not what
1052  * we want here. So we need to either block all signals (including SIGKILL
1053  * and SIGSTOP) or reset the thread's signal state to unsignalled when the
1054  * OS's socket receive routine returns as a result of a signal.
1055  */
1056 int rxk_ListenerPid;            /* Used to signal process to wakeup at shutdown */
1057
1058 #ifdef AFS_SUN5_ENV
1059 /*
1060  * Run the listener as a kernel thread.
1061  */
1062 void
1063 rxk_Listener(void)
1064 {
1065     extern id_t syscid;
1066     void rxk_ListenerProc(void);
1067     if (thread_create
1068         (NULL, DEFAULTSTKSZ, rxk_ListenerProc, 0, 0, &p0, TS_RUN,
1069          minclsyspri) == NULL)
1070         osi_Panic("rxk_Listener: failed to start listener thread!\n");
1071 }
1072
1073 void
1074 rxk_ListenerProc(void)
1075 #else /* AFS_SUN5_ENV */
1076 void
1077 rxk_Listener(void)
1078 #endif                          /* AFS_SUN5_ENV */
1079 {
1080     struct rx_packet *rxp = NULL;
1081     int code;
1082     int host, port;
1083
1084 #ifdef AFS_LINUX20_ENV
1085     rxk_ListenerPid = current->pid;
1086 #endif
1087 #ifdef AFS_SUN5_ENV
1088     rxk_ListenerPid = 1;        /* No PID, just a flag that we're alive */
1089 #endif /* AFS_SUN5_ENV */
1090 #ifdef AFS_XBSD_ENV
1091     rxk_ListenerPid = curproc->p_pid;
1092 #endif /* AFS_FBSD_ENV */
1093 #if defined(AFS_DARWIN_ENV)
1094     rxk_ListenerPid = current_proc()->p_pid;
1095 #endif
1096 #if defined(RX_ENABLE_LOCKS) && !defined(AFS_SUN5_ENV)
1097     AFS_GUNLOCK();
1098 #endif /* RX_ENABLE_LOCKS && !AFS_SUN5_ENV */
1099
1100     while (afs_termState != AFSOP_STOP_RXK_LISTENER) {
1101         if (rxp) {
1102             rxi_RestoreDataBufs(rxp);
1103         } else {
1104             rxp = rxi_AllocPacket(RX_PACKET_CLASS_RECEIVE);
1105             if (!rxp)
1106                 osi_Panic("rxk_Listener: No more Rx buffers!\n");
1107         }
1108         if (!(code = rxk_ReadPacket(rx_socket, rxp, &host, &port))) {
1109             AFS_RXGLOCK();
1110             rxp = rxi_ReceivePacket(rxp, rx_socket, host, port, 0, 0);
1111             AFS_RXGUNLOCK();
1112         }
1113     }
1114
1115 #ifdef RX_ENABLE_LOCKS
1116     AFS_GLOCK();
1117 #endif /* RX_ENABLE_LOCKS */
1118     if (afs_termState == AFSOP_STOP_RXK_LISTENER) {
1119         afs_termState = AFSOP_STOP_COMPLETE;
1120         osi_rxWakeup(&afs_termState);
1121     }
1122     rxk_ListenerPid = 0;
1123 #if defined(AFS_LINUX22_ENV) || defined(AFS_SUN5_ENV)
1124     osi_rxWakeup(&rxk_ListenerPid);
1125 #endif
1126 #ifdef AFS_SUN5_ENV
1127     AFS_GUNLOCK();
1128 #endif /* AFS_SUN5_ENV */
1129 }
1130
1131 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_SUN5_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
1132 /* The manner of stopping the rx listener thread may vary. Most unix's should
1133  * be able to call soclose.
1134  */
1135 void
1136 osi_StopListener(void)
1137 {
1138     soclose(rx_socket);
1139 }
1140 #endif
1141 #endif /* RXK_LISTENER_ENV */
1142
1143 #endif /* !NCR && !UKERNEL */