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