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