Initial OpenBSD support. Most of user space builds. No kernel module yet.
[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 #ifdef AFS_USERSPACE_IP_ADDR    
347     i = rxi_Findcbi(pp->host);
348     if (i == -1) {
349        pp->timeout.sec = 3;
350        /* pp->timeout.usec = 0; */
351        pp->ifMTU = RX_REMOTE_PACKET_SIZE;
352     } else {
353        pp->timeout.sec = 2;
354        /* pp->timeout.usec = 0; */
355        pp->ifMTU = MIN(RX_MAX_PACKET_SIZE, rx_MyMaxSendSize);
356     }
357     if (i != -1) {
358         mtu = ntohl(afs_cb_interface.mtu[i]);
359         /* Diminish the packet size to one based on the MTU given by
360          * the interface. */
361         if (mtu > (RX_IPUDP_SIZE + RX_HEADER_SIZE)) {
362             rxmtu = mtu - RX_IPUDP_SIZE;
363             if (rxmtu < pp->ifMTU) pp->ifMTU = rxmtu;
364         }
365     }
366     else {   /* couldn't find the interface, so assume the worst */
367       pp->ifMTU = RX_REMOTE_PACKET_SIZE;
368     }
369 #else /* AFS_USERSPACE_IP_ADDR */
370     struct in_ifaddr *ifad = (struct in_ifaddr *) 0;
371     struct ifnet *ifn;
372
373     /* At some time we need to iterate through rxi_FindIfnet() to find the
374      * global maximum.
375      */
376     ifn = rxi_FindIfnet(pp->host, &ifad);
377     if (ifn == NULL) {  /* not local */
378         pp->timeout.sec = 3;
379         /* pp->timeout.usec = 0; */
380         pp->ifMTU = RX_REMOTE_PACKET_SIZE;
381     } else {
382         pp->timeout.sec = 2;
383         /* pp->timeout.usec = 0; */
384         pp->ifMTU = MIN(RX_MAX_PACKET_SIZE, rx_MyMaxSendSize);
385     }
386     if (ifn) {
387 #ifdef IFF_POINTOPOINT
388         if (ifn->if_flags & IFF_POINTOPOINT) {
389             /* wish we knew the bit rate and the chunk size, sigh. */
390             pp->timeout.sec = 4;
391             pp->ifMTU = RX_PP_PACKET_SIZE;
392         }
393 #endif /* IFF_POINTOPOINT */
394         /* Diminish the packet size to one based on the MTU given by
395          * the interface. */
396         if (ifn->if_mtu > (RX_IPUDP_SIZE + RX_HEADER_SIZE)) {
397             rxmtu = ifn->if_mtu - RX_IPUDP_SIZE;
398             if (rxmtu < pp->ifMTU) pp->ifMTU = rxmtu;
399         }
400     }
401     else {   /* couldn't find the interface, so assume the worst */
402       pp->ifMTU = RX_REMOTE_PACKET_SIZE;
403     }
404 #endif/* else AFS_USERSPACE_IP_ADDR */
405 #else /* ADAPT_MTU */
406     pp->rateFlag = 2;   /* start timing after two full packets */
407     pp->timeout.sec = 2;
408     pp->ifMTU = OLD_MAX_PACKET_SIZE;
409 #endif /* else ADAPT_MTU */
410     pp->ifMTU = rxi_AdjustIfMTU(pp->ifMTU);
411     pp->maxMTU = OLD_MAX_PACKET_SIZE;  /* for compatibility with old guys */
412     pp->natMTU = MIN(pp->ifMTU, OLD_MAX_PACKET_SIZE); 
413     pp->ifDgramPackets = MIN(rxi_nDgramPackets,
414                              rxi_AdjustDgramPackets(RX_MAX_FRAGS, pp->ifMTU));
415     pp->maxDgramPackets = 1;
416
417     /* Initialize slow start parameters */
418     pp->MTU = MIN(pp->natMTU, pp->maxMTU);
419     pp->cwind = 1;
420     pp->nDgramPackets = 1;
421     pp->congestSeq = 0;
422 }
423
424
425 /* The following code is common to several system types, but not all. The
426  * separate ones are found in the system specific subdirectories.
427  */
428
429
430 #if ! defined(AFS_AIX_ENV) && ! defined(AFS_SUN5_ENV) && ! defined(UKERNEL) && ! defined(AFS_LINUX20_ENV) && !defined (AFS_DARWIN_ENV) && !defined (AFS_XBSD_ENV)
431 /* Routine called during the afsd "-shutdown" process to put things back to
432  * the initial state.
433  */
434 static struct protosw parent_proto;     /* udp proto switch */
435
436 void shutdown_rxkernel(void)
437 {
438     register struct protosw *tpro, *last;
439     last = inetdomain.dom_protoswNPROTOSW;
440     for (tpro = inetdomain.dom_protosw; tpro < last; tpro++)
441         if (tpro->pr_protocol == IPPROTO_UDP) {
442             /* restore original udp protocol switch */
443             memcpy((void *)tpro, (void *)&parent_proto, sizeof(parent_proto));
444             memset((void *)&parent_proto, 0, sizeof(parent_proto));
445             rxk_initDone = 0;
446             rxk_shutdownPorts();
447             return;
448         }    
449     printf("shutdown_rxkernel: no udp proto");
450 }
451 #endif /* !AIX && !SUN && !NCR  && !UKERNEL */
452
453 #if !defined(AFS_SUN5_ENV) && !defined(AFS_SGI62_ENV)
454 /* Determine what the network interfaces are for this machine. */
455
456 #define ADDRSPERSITE 16
457 static afs_uint32 myNetAddrs[ADDRSPERSITE];
458 static int myNetMTUs[ADDRSPERSITE];
459 static int myNetFlags[ADDRSPERSITE];
460 static int numMyNetAddrs = 0;
461
462 #ifdef AFS_USERSPACE_IP_ADDR    
463 int rxi_GetcbiInfo()
464 {
465    int     i, j, different = 0;
466    int     rxmtu, maxmtu;
467    afs_uint32 ifinaddr;
468    afs_uint32 addrs[ADDRSPERSITE];
469    int     mtus[ADDRSPERSITE];
470
471    memset((void *)addrs, 0, sizeof(addrs));
472    memset((void *)mtus, 0, sizeof(mtus));
473
474    for (i=0; i<afs_cb_interface.numberOfInterfaces; i++) {
475       rxmtu    = (ntohl(afs_cb_interface.mtu[i]) - RX_IPUDP_SIZE);
476       ifinaddr = ntohl(afs_cb_interface.addr_in[i]);
477       if (myNetAddrs[i] != ifinaddr) different++;
478
479       mtus[i]    = rxmtu;
480       rxmtu      = rxi_AdjustIfMTU(rxmtu);
481       maxmtu     = rxmtu * rxi_nRecvFrags + ((rxi_nRecvFrags-1) * UDP_HDR_SIZE);
482       maxmtu     = rxi_AdjustMaxMTU(rxmtu, maxmtu);
483       addrs[i++] = ifinaddr;
484       if ( ( ifinaddr != 0x7f000001 ) && (maxmtu > rx_maxReceiveSize) ) {
485          rx_maxReceiveSize = MIN( RX_MAX_PACKET_SIZE, maxmtu);
486          rx_maxReceiveSize = MIN( rx_maxReceiveSize, rx_maxReceiveSizeUser);
487       }
488    }
489
490    rx_maxJumboRecvSize = RX_HEADER_SIZE +
491                          ( rxi_nDgramPackets    * RX_JUMBOBUFFERSIZE) +
492                          ((rxi_nDgramPackets-1) * RX_JUMBOHEADERSIZE);
493    rx_maxJumboRecvSize = MAX(rx_maxJumboRecvSize, rx_maxReceiveSize);
494
495    if (different) {
496       for (j=0; j<i; j++) {
497          myNetMTUs[j]  = mtus[j];
498          myNetAddrs[j] = addrs[j];
499       }
500    }
501    return different;
502 }
503
504
505 /* Returns the afs_cb_interface inxex which best matches address.
506  * If none is found, we return -1.
507  */
508 afs_int32 rxi_Findcbi(addr)
509      afs_uint32 addr;
510 {
511    int j;
512    afs_uint32 myAddr, thisAddr, netMask, subnetMask;
513    afs_int32 rvalue = -1;
514    int match_value = 0;
515
516   if (numMyNetAddrs == 0)
517     (void) rxi_GetcbiInfo();
518
519    myAddr = ntohl(addr);
520
521    if      ( IN_CLASSA(myAddr) ) netMask = IN_CLASSA_NET;
522    else if ( IN_CLASSB(myAddr) ) netMask = IN_CLASSB_NET;
523    else if ( IN_CLASSC(myAddr) ) netMask = IN_CLASSC_NET;
524    else                          netMask = 0;
525
526    for (j=0; j<afs_cb_interface.numberOfInterfaces; j++) {
527       thisAddr   = ntohl(afs_cb_interface.addr_in[j]);
528       subnetMask = ntohl(afs_cb_interface.subnetmask[j]);
529       if ((myAddr & netMask) == (thisAddr & netMask)) {
530          if ((myAddr & subnetMask) == (thisAddr & subnetMask)) {
531             if (myAddr == thisAddr) {
532                match_value = 4;
533                rvalue = j;
534                break;
535             }
536             if (match_value < 3) {
537                match_value = 3;
538                rvalue = j;
539             }
540          } else {
541             if (match_value < 2) {
542                match_value = 2;
543                rvalue = j;
544             }
545          }
546       }
547    }
548
549  done:
550    return(rvalue);
551 }
552
553 #else /* AFS_USERSPACE_IP_ADDR */
554
555 #if !defined(AFS_AIX41_ENV) && !defined(AFS_DUX40_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
556 #define IFADDR2SA(f) (&((f)->ifa_addr))
557 #else /* AFS_AIX41_ENV */
558 #define IFADDR2SA(f) ((f)->ifa_addr)
559 #endif
560
561 int rxi_GetIFInfo()
562 {
563     int i = 0;
564     int different = 0;
565
566     register struct ifnet *ifn;
567     register int rxmtu, maxmtu;
568     afs_uint32 addrs[ADDRSPERSITE];
569     int mtus[ADDRSPERSITE];
570     struct ifaddr *ifad;  /* ifnet points to a if_addrlist of ifaddrs */
571     afs_uint32 ifinaddr;
572
573     memset(addrs, 0, sizeof(addrs));
574     memset(mtus, 0, sizeof(mtus));
575
576 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
577     TAILQ_FOREACH(ifn, &ifnet, if_link) {
578       if (i >= ADDRSPERSITE) break;
579 #else 
580     for (ifn = ifnet; ifn != NULL && i < ADDRSPERSITE; ifn = ifn->if_next) {
581 #endif
582       rxmtu = (ifn->if_mtu - RX_IPUDP_SIZE);
583 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
584       TAILQ_FOREACH(ifad, &ifn->if_addrhead, ifa_link) {
585       if (i >= ADDRSPERSITE) break;
586 #else
587       for (ifad = ifn->if_addrlist; ifad != NULL && i < ADDRSPERSITE;
588            ifad = ifad->ifa_next){
589 #endif
590         if (IFADDR2SA(ifad)->sa_family == AF_INET) {
591           ifinaddr = ntohl(((struct sockaddr_in *) IFADDR2SA(ifad))->sin_addr.s_addr);
592           if (myNetAddrs[i] != ifinaddr) { 
593             different++;
594           }
595           mtus[i] = rxmtu;
596           rxmtu = rxi_AdjustIfMTU(rxmtu);
597           maxmtu = rxmtu * rxi_nRecvFrags + ((rxi_nRecvFrags-1) * UDP_HDR_SIZE);
598           maxmtu = rxi_AdjustMaxMTU(rxmtu, maxmtu);
599           addrs[i++] = ifinaddr;
600           if ( ( ifinaddr != 0x7f000001 ) &&
601               (maxmtu > rx_maxReceiveSize) ) {
602             rx_maxReceiveSize = MIN( RX_MAX_PACKET_SIZE, maxmtu);
603             rx_maxReceiveSize = MIN( rx_maxReceiveSize, rx_maxReceiveSizeUser);
604           }
605         }
606       }
607     }
608
609     rx_maxJumboRecvSize = RX_HEADER_SIZE
610                           + rxi_nDgramPackets * RX_JUMBOBUFFERSIZE
611                           + (rxi_nDgramPackets-1) * RX_JUMBOHEADERSIZE;
612     rx_maxJumboRecvSize = MAX(rx_maxJumboRecvSize, rx_maxReceiveSize);
613
614     if (different) {
615       int j;
616       for (j=0; j< i; j++) {
617         myNetMTUs[j] = mtus[j];
618         myNetAddrs[j] = addrs[j];
619       }
620     }
621    return different;
622 }
623
624 /* Returns ifnet which best matches address */
625 struct ifnet *
626 rxi_FindIfnet(addr, pifad) 
627      afs_uint32 addr;
628      struct in_ifaddr **pifad;
629 {
630   afs_uint32 ppaddr;
631   int match_value = 0;
632   extern struct in_ifaddr *in_ifaddr;
633   struct in_ifaddr *ifa;
634   struct sockaddr_in *sin;
635   
636   if (numMyNetAddrs == 0)
637     (void) rxi_GetIFInfo();
638
639   ppaddr = ntohl(addr);
640
641   /* if we're given an address, skip everything until we find it */
642   if (!*pifad)
643 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
644     *pifad = TAILQ_FIRST(&in_ifaddrhead);
645 #else 
646     *pifad = in_ifaddr;
647 #endif
648   else {
649     if (((ppaddr & (*pifad)->ia_subnetmask) == (*pifad)->ia_subnet))
650       match_value = 2; /* don't find matching nets, just subnets */
651 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
652     *pifad = TAILQ_NEXT(*pifad, ia_link);
653 #else   
654     *pifad = (*pifad)->ia_next;
655 #endif
656   }
657     
658 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
659   for (ifa = *pifad; ifa; ifa = TAILQ_NEXT(ifa, ia_link) ) {
660 #else
661   for (ifa = *pifad; ifa; ifa = ifa->ia_next ) {
662 #endif
663     if ((ppaddr & ifa->ia_netmask) == ifa->ia_net) {
664       if ((ppaddr & ifa->ia_subnetmask) == ifa->ia_subnet) {
665         sin=IA_SIN(ifa);
666         if ( sin->sin_addr.s_addr == ppaddr) {   /* ie, ME!!!  */
667           match_value = 4;
668           *pifad = ifa;
669           goto done;
670         }
671         if (match_value < 3) {
672           *pifad = ifa;
673           match_value = 3;
674         }
675       }
676       else {
677         if (match_value < 2) {
678           *pifad = ifa;
679           match_value = 2;
680         }
681       }
682     } /* if net matches */
683   } /* for all in_ifaddrs */
684
685  done:
686   return (*pifad ?  (*pifad)->ia_ifp : NULL );
687 }
688 #endif /* else AFS_USERSPACE_IP_ADDR */
689 #endif /* !SUN5 && !SGI62 */
690
691
692 /* rxk_NewSocket, rxk_FreeSocket and osi_NetSend are from the now defunct
693  * afs_osinet.c. One could argue that rxi_NewSocket could go into the
694  * system specific subdirectories for all systems. But for the moment,
695  * most of it is simple to follow common code.
696  */
697 #if !defined(UKERNEL)
698 #if !defined(AFS_SUN5_ENV) && !defined(AFS_LINUX20_ENV)
699 /* rxk_NewSocket creates a new socket on the specified port. The port is
700  * in network byte order.
701  */
702 struct osi_socket *rxk_NewSocket(short aport)
703 {
704     register afs_int32 code;
705     struct socket *newSocket;
706     register struct mbuf *nam;
707     struct sockaddr_in myaddr;
708     int wow;
709 #ifdef AFS_HPUX110_ENV
710     /* prototype copied from kernel source file streams/str_proto.h */
711     extern MBLKP allocb_wait(int, int);
712     MBLKP bindnam;
713     int addrsize = sizeof(struct sockaddr_in);
714 #endif
715 #ifdef AFS_SGI65_ENV
716     bhv_desc_t bhv;
717 #endif
718
719     AFS_STATCNT(osi_NewSocket);
720 #if (defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)) && defined(KERNEL_FUNNEL)
721     thread_funnel_switch(KERNEL_FUNNEL, NETWORK_FUNNEL);
722 #endif
723 #if     defined(AFS_HPUX102_ENV)
724 #if     defined(AFS_HPUX110_ENV)
725     /* blocking socket */
726     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, 0, 0);
727 #else      /* AFS_HPUX110_ENV */
728     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, 0, SS_NOWAIT);
729 #endif     /* else AFS_HPUX110_ENV */
730 #else
731 #ifdef AFS_SGI65_ENV
732     code = socreate(AF_INET, &newSocket, SOCK_DGRAM,IPPROTO_UDP);
733 #elif defined(AFS_XBSD_ENV)
734     code = socreate(AF_INET, &newSocket, SOCK_DGRAM,IPPROTO_UDP, curproc);
735 #else
736     code = socreate(AF_INET, &newSocket, SOCK_DGRAM, 0);
737 #endif /* AFS_SGI65_ENV */
738 #endif /* AFS_HPUX102_ENV */
739     if (code) goto bad;
740
741     myaddr.sin_family = AF_INET;
742     myaddr.sin_port = aport;
743     myaddr.sin_addr.s_addr = 0;
744
745 #ifdef AFS_HPUX110_ENV
746     bindnam = allocb_wait((addrsize+SO_MSGOFFSET+1), BPRI_MED);
747     if (!bindnam) {
748        setuerror(ENOBUFS);
749        goto bad;
750     }
751     memcpy((caddr_t)bindnam->b_rptr+SO_MSGOFFSET, (caddr_t)&myaddr, addrsize);
752     bindnam->b_wptr = bindnam->b_rptr + (addrsize+SO_MSGOFFSET+1);
753
754     code = sobind(newSocket, bindnam, addrsize);
755     if (code) {
756        soclose(newSocket);
757        m_freem(nam);
758        goto bad;
759     }
760
761     freeb(bindnam);
762 #else /* AFS_HPUX110_ENV */
763     code = soreserve(newSocket, 50000, 50000);
764     if (code) {
765         code = soreserve(newSocket, 32766, 32766);
766         if (code)
767             osi_Panic("osi_NewSocket: last attempt to reserve 32K failed!\n");
768     }
769 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
770     myaddr.sin_len = sizeof(myaddr);
771 #if defined(AFS_XBSD_ENV)
772     code = sobind(newSocket, (struct sockaddr *)&myaddr, curproc);
773 #else
774     code = sobind(newSocket, (struct sockaddr *)&myaddr);
775 #endif
776     if (code) {
777         printf("sobind fails\n");
778         soclose(newSocket);
779         goto bad;
780     }
781 #else
782 #ifdef  AFS_OSF_ENV
783     nam = m_getclr(M_WAIT, MT_SONAME);
784 #else   /* AFS_OSF_ENV */
785     nam = m_get(M_WAIT, MT_SONAME);
786 #endif
787     if (nam == NULL) {
788 #if !defined(AFS_SUN5_ENV) && !defined(AFS_OSF_ENV) && !defined(AFS_SGI64_ENV) && !defined(AFS_XBSD_ENV)
789         setuerror(ENOBUFS);
790 #endif
791         goto bad;
792     }
793     nam->m_len = sizeof(myaddr);
794 #ifdef  AFS_OSF_ENV
795     myaddr.sin_len = nam->m_len;
796 #endif  /* AFS_OSF_ENV */
797     memcpy(mtod(nam, caddr_t), &myaddr, sizeof(myaddr));
798 #ifdef AFS_SGI65_ENV
799     BHV_PDATA(&bhv) = (void*)newSocket;
800     code = sobind(&bhv, nam);
801     m_freem(nam);
802 #elif defined(AFS_XBSD_ENV)
803     code = sobind(newSocket, nam, curproc);
804 #else
805     code = sobind(newSocket, nam);
806 #endif
807     if (code) {
808         soclose(newSocket);
809 #ifndef AFS_SGI65_ENV
810         m_freem(nam);
811 #endif
812         goto bad;
813     }
814 #endif /* else AFS_DARWIN_ENV */
815 #endif /* else AFS_HPUX110_ENV */
816
817 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
818     thread_funnel_switch(NETWORK_FUNNEL, KERNEL_FUNNEL);
819 #endif
820     return (struct osi_socket *) newSocket;
821
822 bad:
823 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
824     thread_funnel_switch(NETWORK_FUNNEL, KERNEL_FUNNEL);
825 #endif
826     return (struct osi_socket *) 0;
827 }
828
829
830 /* free socket allocated by rxk_NewSocket */
831 int rxk_FreeSocket(asocket)
832     register struct socket *asocket;
833 {
834     AFS_STATCNT(osi_FreeSocket);
835 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
836     thread_funnel_switch(KERNEL_FUNNEL, NETWORK_FUNNEL);
837 #endif
838     soclose(asocket);
839 #if defined(AFS_DARWIN_ENV) && defined(KERNEL_FUNNEL)
840     thread_funnel_switch(NETWORK_FUNNEL, KERNEL_FUNNEL);
841 #endif
842     return 0;
843 }
844 #endif /* !SUN5 && !LINUX20 */
845
846 #if defined(RXK_LISTENER_ENV) || defined(AFS_SUN5_ENV)
847 /*
848  * Run RX event daemon every second (5 times faster than rest of systems)
849  */
850 afs_rxevent_daemon() 
851 {
852     int s, code;
853     struct clock temp;
854     SPLVAR;
855
856     while (1) {
857 #ifdef RX_ENABLE_LOCKS
858         AFS_GUNLOCK();
859 #endif /* RX_ENABLE_LOCKS */
860         NETPRI;
861         AFS_RXGLOCK();
862         rxevent_RaiseEvents(&temp);
863         AFS_RXGUNLOCK();
864         USERPRI;
865 #ifdef RX_ENABLE_LOCKS
866         AFS_GLOCK();
867 #endif /* RX_ENABLE_LOCKS */
868         afs_osi_Wait(500, (char *)0, 0);
869         if (afs_termState == AFSOP_STOP_RXEVENT )
870         {
871 #ifdef RXK_LISTENER_ENV
872                 afs_termState = AFSOP_STOP_RXK_LISTENER;
873 #else
874                 afs_termState = AFSOP_STOP_COMPLETE;
875 #endif
876                 afs_osi_Wakeup(&afs_termState);
877                 return;
878         }
879     }
880 }
881 #endif
882
883 #ifdef RXK_LISTENER_ENV 
884
885 /* rxk_ReadPacket returns 1 if valid packet, 0 on error. */
886 int rxk_ReadPacket(osi_socket so, struct rx_packet *p, int *host, int *port)
887 {
888     int code;
889     struct sockaddr_in from;
890     int nbytes;
891     afs_int32 rlen;
892     register afs_int32 tlen;
893     afs_int32 savelen;            /* was using rlen but had aliasing problems */
894     rx_computelen(p, tlen);
895     rx_SetDataSize(p, tlen);  /* this is the size of the user data area */
896
897     tlen += RX_HEADER_SIZE;   /* now this is the size of the entire packet */
898     rlen = rx_maxJumboRecvSize; /* this is what I am advertising.  Only check
899                                  * it once in order to avoid races.  */
900     tlen = rlen - tlen;
901     if (tlen > 0) {
902       tlen = rxi_AllocDataBuf(p, tlen, RX_PACKET_CLASS_RECV_CBUF);
903       if (tlen >0) {
904         tlen = rlen - tlen;
905       }
906       else tlen = rlen;
907     }
908     else tlen = rlen;
909
910    /* add some padding to the last iovec, it's just to make sure that the 
911     * read doesn't return more data than we expect, and is done to get around
912     * our problems caused by the lack of a length field in the rx header. */
913     savelen = p->wirevec[p->niovecs-1].iov_len;
914     p->wirevec[p->niovecs-1].iov_len = savelen + RX_EXTRABUFFERSIZE;
915
916     nbytes = tlen + sizeof(afs_int32);
917     code = osi_NetReceive(rx_socket, &from, p->wirevec, p->niovecs,
918                             &nbytes);
919
920    /* restore the vec to its correct state */
921     p->wirevec[p->niovecs-1].iov_len = savelen;
922
923     if (!code) {
924         p->length = nbytes - RX_HEADER_SIZE;;
925         if ((nbytes > tlen) || (p->length & 0x8000)) {  /* Bogus packet */
926             if (nbytes > 0)
927                 rxi_MorePackets(rx_initSendWindow);
928             else {
929                 MUTEX_ENTER(&rx_stats_mutex);
930                 rx_stats.bogusPacketOnRead++;
931                 rx_stats.bogusHost = from.sin_addr.s_addr;
932                 MUTEX_EXIT(&rx_stats_mutex);
933                 dpf(("B: bogus packet from [%x,%d] nb=%d", from.sin_addr.s_addr,
934                      from.sin_port,nbytes));
935             }
936             return  -1;
937         }
938         else {
939             /* Extract packet header. */
940             rxi_DecodePacketHeader(p);
941       
942             *host = from.sin_addr.s_addr;
943             *port = from.sin_port;
944             if (p->header.type > 0 && p->header.type < RX_N_PACKET_TYPES) {
945                 MUTEX_ENTER(&rx_stats_mutex);
946                 rx_stats.packetsRead[p->header.type-1]++;
947                 MUTEX_EXIT(&rx_stats_mutex);
948             }
949
950             /* Free any empty packet buffers at the end of this packet */
951             rxi_TrimDataBufs(p, 1);
952
953             return  0;
954         }
955     }
956     else
957         return code;
958 }
959
960 /* rxk_Listener() 
961  *
962  * Listen for packets on socket. This thread is typically started after
963  * rx_Init has called rxi_StartListener(), but nevertheless, ensures that
964  * the start state is set before proceeding.
965  *
966  * Note that this thread is outside the AFS global lock for much of
967  * it's existence.
968  *
969  * In many OS's, the socket receive code sleeps interruptibly. That's not what
970  * we want here. So we need to either block all signals (including SIGKILL
971  * and SIGSTOP) or reset the thread's signal state to unsignalled when the
972  * OS's socket receive routine returns as a result of a signal.
973  */
974 int rxk_ListenerPid; /* Used to signal process to wakeup at shutdown */
975
976 #ifdef AFS_SUN5_ENV
977 /*
978  * Run the listener as a kernel process.
979  */
980 void rxk_Listener(void)
981 {
982     extern id_t syscid;
983     void rxk_ListenerProc(void);
984     if (newproc(rxk_ListenerProc, syscid, 59))
985         osi_Panic("rxk_Listener: failed to fork listener process!\n");
986 }
987
988 void rxk_ListenerProc(void)
989 #else /* AFS_SUN5_ENV */
990 void rxk_Listener(void)
991 #endif /* AFS_SUN5_ENV */
992 {
993     struct rx_packet *rxp = NULL;
994     int code;
995     int host, port;
996
997 #ifdef AFS_LINUX20_ENV
998     rxk_ListenerPid = current->pid;
999 #endif
1000 #ifdef AFS_SUN5_ENV
1001     rxk_ListenerPid = ttoproc(curthread)->p_pidp->pid_id;
1002 #endif /* AFS_SUN5_ENV */
1003 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
1004     rxk_ListenerPid = current_proc()->p_pid;
1005 #endif
1006 #if defined(RX_ENABLE_LOCKS) && !defined(AFS_SUN5_ENV)
1007     AFS_GUNLOCK();
1008 #endif /* RX_ENABLE_LOCKS && !AFS_SUN5_ENV */
1009
1010     while (afs_termState != AFSOP_STOP_RXK_LISTENER) {
1011         if (rxp) {
1012             rxi_RestoreDataBufs(rxp);
1013         }
1014         else {
1015             rxp = rxi_AllocPacket(RX_PACKET_CLASS_RECEIVE);
1016             if (!rxp)
1017                 osi_Panic("rxk_Listener: No more Rx buffers!\n");
1018         }
1019         if (!(code = rxk_ReadPacket(rx_socket, rxp, &host, &port))) {
1020             AFS_RXGLOCK();
1021             rxp = rxi_ReceivePacket(rxp, rx_socket, host, port);
1022             AFS_RXGUNLOCK();
1023         }
1024         if (afs_termState == AFSOP_STOP_RXK_LISTENER)
1025             break;
1026
1027     }
1028
1029 #ifdef RX_ENABLE_LOCKS
1030     AFS_GLOCK();
1031 #endif /* RX_ENABLE_LOCKS */
1032     if (afs_termState == AFSOP_STOP_RXK_LISTENER) {
1033         afs_termState = AFSOP_STOP_COMPLETE;
1034         afs_osi_Wakeup(&afs_termState);
1035     }
1036     rxk_ListenerPid = 0;
1037 #ifdef AFS_LINUX24_ENV
1038     afs_osi_Wakeup(&rxk_ListenerPid);
1039 #endif
1040 #ifdef AFS_SUN5_ENV
1041     AFS_GUNLOCK();
1042 #endif /* AFS_SUN5_ENV */
1043 }
1044
1045 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_SUN5_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
1046 /* The manner of stopping the rx listener thread may vary. Most unix's should
1047  * be able to call soclose.
1048  */
1049 void osi_StopListener(void)
1050 {
1051     soclose(rx_socket);
1052 }
1053 #endif
1054 #endif /* RXK_LISTENER_ENV */
1055
1056 #endif /* !NCR && !UKERNEL */