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