xref: /freebsd/sys/net/if.c (revision 5521ff5a4d1929056e7ffc982fac3341ca54df7c)
1 /*
2  * Copyright (c) 1980, 1986, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)if.c	8.3 (Berkeley) 1/4/94
34  * $FreeBSD$
35  */
36 
37 #include "opt_compat.h"
38 #include "opt_inet6.h"
39 #include "opt_inet.h"
40 
41 #include <sys/param.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/systm.h>
45 #include <sys/proc.h>
46 #include <sys/socket.h>
47 #include <sys/socketvar.h>
48 #include <sys/protosw.h>
49 #include <sys/kernel.h>
50 #include <sys/sockio.h>
51 #include <sys/syslog.h>
52 #include <sys/sysctl.h>
53 #include <sys/jail.h>
54 
55 #include <net/if.h>
56 #include <net/if_arp.h>
57 #include <net/if_dl.h>
58 #include <net/if_types.h>
59 #include <net/if_var.h>
60 #include <net/radix.h>
61 #include <net/route.h>
62 
63 #if defined(INET) || defined(INET6)
64 /*XXX*/
65 #include <netinet/in.h>
66 #include <netinet/in_var.h>
67 #ifdef INET6
68 #include <netinet6/in6_var.h>
69 #include <netinet6/in6_ifattach.h>
70 #endif
71 #endif
72 
73 /*
74  * System initialization
75  */
76 
77 static int ifconf __P((u_long, caddr_t));
78 static void ifinit __P((void *));
79 static void if_qflush __P((struct ifqueue *));
80 static void if_slowtimo __P((void *));
81 static void link_rtrequest __P((int, struct rtentry *, struct sockaddr *));
82 static int  if_rtdel __P((struct radix_node *, void *));
83 
84 SYSINIT(interfaces, SI_SUB_PROTO_IF, SI_ORDER_FIRST, ifinit, NULL)
85 
86 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
87 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
88 
89 int	ifqmaxlen = IFQ_MAXLEN;
90 struct	ifnethead ifnet;	/* depend on static init XXX */
91 
92 #ifdef INET6
93 /*
94  * XXX: declare here to avoid to include many inet6 related files..
95  * should be more generalized?
96  */
97 extern void	nd6_setmtu __P((struct ifnet *));
98 #endif
99 
100 struct if_clone *if_clone_lookup __P((const char *, int *));
101 int if_clone_list __P((struct if_clonereq *));
102 
103 LIST_HEAD(, if_clone) if_cloners = LIST_HEAD_INITIALIZER(if_cloners);
104 int if_cloners_count;
105 
106 /*
107  * Network interface utility routines.
108  *
109  * Routines with ifa_ifwith* names take sockaddr *'s as
110  * parameters.
111  */
112 /* ARGSUSED*/
113 void
114 ifinit(dummy)
115 	void *dummy;
116 {
117 	struct ifnet *ifp;
118 	int s;
119 
120 	s = splimp();
121 	TAILQ_FOREACH(ifp, &ifnet, if_link) {
122 		if (ifp->if_snd.ifq_maxlen == 0) {
123 			printf("%s%d XXX: driver didn't set ifq_maxlen\n",
124 			    ifp->if_name, ifp->if_unit);
125 			ifp->if_snd.ifq_maxlen = ifqmaxlen;
126 		}
127 		if (!mtx_initialized(&ifp->if_snd.ifq_mtx)) {
128 			printf("%s%d XXX: driver didn't initialize queue mtx\n",
129 			    ifp->if_name, ifp->if_unit);
130 			mtx_init(&ifp->if_snd.ifq_mtx, "unknown", MTX_DEF);
131 		}
132 	}
133 	splx(s);
134 	if_slowtimo(0);
135 }
136 
137 int if_index = 0;
138 struct ifaddr **ifnet_addrs;
139 struct ifnet **ifindex2ifnet = NULL;
140 
141 
142 /*
143  * Attach an interface to the
144  * list of "active" interfaces.
145  */
146 void
147 if_attach(ifp)
148 	struct ifnet *ifp;
149 {
150 	unsigned socksize, ifasize;
151 	int namelen, masklen;
152 	char workbuf[64];
153 	register struct sockaddr_dl *sdl;
154 	register struct ifaddr *ifa;
155 	static int if_indexlim = 8;
156 	static int inited;
157 
158 	if (!inited) {
159 		TAILQ_INIT(&ifnet);
160 		inited = 1;
161 	}
162 
163 	TAILQ_INSERT_TAIL(&ifnet, ifp, if_link);
164 	ifp->if_index = ++if_index;
165 	/*
166 	 * XXX -
167 	 * The old code would work if the interface passed a pre-existing
168 	 * chain of ifaddrs to this code.  We don't trust our callers to
169 	 * properly initialize the tailq, however, so we no longer allow
170 	 * this unlikely case.
171 	 */
172 	TAILQ_INIT(&ifp->if_addrhead);
173 	TAILQ_INIT(&ifp->if_prefixhead);
174 	TAILQ_INIT(&ifp->if_multiaddrs);
175 	getmicrotime(&ifp->if_lastchange);
176 	if (ifnet_addrs == 0 || if_index >= if_indexlim) {
177 		unsigned n = (if_indexlim <<= 1) * sizeof(ifa);
178 		caddr_t q = malloc(n, M_IFADDR, M_WAITOK | M_ZERO);
179 		if (ifnet_addrs) {
180 			bcopy((caddr_t)ifnet_addrs, (caddr_t)q, n/2);
181 			free((caddr_t)ifnet_addrs, M_IFADDR);
182 		}
183 		ifnet_addrs = (struct ifaddr **)q;
184 
185 		/* grow ifindex2ifnet */
186 		n = if_indexlim * sizeof(struct ifnet *);
187 		q = malloc(n, M_IFADDR, M_WAITOK | M_ZERO);
188 		if (ifindex2ifnet) {
189 			bcopy((caddr_t)ifindex2ifnet, q, n/2);
190 			free((caddr_t)ifindex2ifnet, M_IFADDR);
191 		}
192 		ifindex2ifnet = (struct ifnet **)q;
193 	}
194 
195 	ifindex2ifnet[if_index] = ifp;
196 
197 	mtx_init(&ifp->if_snd.ifq_mtx, ifp->if_name, MTX_DEF);
198 
199 	/*
200 	 * create a Link Level name for this device
201 	 */
202 	namelen = snprintf(workbuf, sizeof(workbuf),
203 	    "%s%d", ifp->if_name, ifp->if_unit);
204 #define _offsetof(t, m) ((int)((caddr_t)&((t *)0)->m))
205 	masklen = _offsetof(struct sockaddr_dl, sdl_data[0]) + namelen;
206 	socksize = masklen + ifp->if_addrlen;
207 #define ROUNDUP(a) (1 + (((a) - 1) | (sizeof(long) - 1)))
208 	if (socksize < sizeof(*sdl))
209 		socksize = sizeof(*sdl);
210 	socksize = ROUNDUP(socksize);
211 	ifasize = sizeof(*ifa) + 2 * socksize;
212 	ifa = (struct ifaddr *)malloc(ifasize, M_IFADDR, M_WAITOK | M_ZERO);
213 	if (ifa) {
214 		sdl = (struct sockaddr_dl *)(ifa + 1);
215 		sdl->sdl_len = socksize;
216 		sdl->sdl_family = AF_LINK;
217 		bcopy(workbuf, sdl->sdl_data, namelen);
218 		sdl->sdl_nlen = namelen;
219 		sdl->sdl_index = ifp->if_index;
220 		sdl->sdl_type = ifp->if_type;
221 		ifnet_addrs[if_index - 1] = ifa;
222 		ifa->ifa_ifp = ifp;
223 		ifa->ifa_rtrequest = link_rtrequest;
224 		ifa->ifa_addr = (struct sockaddr *)sdl;
225 		sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
226 		ifa->ifa_netmask = (struct sockaddr *)sdl;
227 		sdl->sdl_len = masklen;
228 		while (namelen != 0)
229 			sdl->sdl_data[--namelen] = 0xff;
230 		TAILQ_INSERT_HEAD(&ifp->if_addrhead, ifa, ifa_link);
231 	}
232 }
233 
234 /*
235  * Detach an interface, removing it from the
236  * list of "active" interfaces.
237  */
238 void
239 if_detach(ifp)
240 	struct ifnet *ifp;
241 {
242 	struct ifaddr *ifa;
243 	struct radix_node_head	*rnh;
244 	int s;
245 	int i;
246 
247 	/*
248 	 * Remove routes and flush queues.
249 	 */
250 	s = splnet();
251 	if_down(ifp);
252 
253 	/*
254 	 * Remove address from ifnet_addrs[] and maybe decrement if_index.
255 	 * Clean up all addresses.
256 	 */
257 	ifnet_addrs[ifp->if_index - 1] = 0;
258 	while (if_index > 0 && ifnet_addrs[if_index - 1] == 0)
259 		if_index--;
260 
261 	for (ifa = TAILQ_FIRST(&ifp->if_addrhead); ifa;
262 	     ifa = TAILQ_FIRST(&ifp->if_addrhead)) {
263 #ifdef INET
264 		/* XXX: Ugly!! ad hoc just for INET */
265 		if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) {
266 			struct ifaliasreq ifr;
267 
268 			bzero(&ifr, sizeof(ifr));
269 			ifr.ifra_addr = *ifa->ifa_addr;
270 			if (ifa->ifa_dstaddr)
271 				ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
272 			if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
273 			    NULL) == 0)
274 				continue;
275 		}
276 #endif /* INET */
277 #ifdef INET6
278 		if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET6) {
279 			in6_purgeaddr(ifa);
280 			/* ifp_addrhead is already updated */
281 			continue;
282 		}
283 #endif /* INET6 */
284 		TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
285 		IFAFREE(ifa);
286 	}
287 
288 #ifdef INET6
289 	/*
290 	 * Remove all IPv6 kernel structs related to ifp.  This should be done
291 	 * before removing routing entries below, since IPv6 interface direct
292 	 * routes are expected to be removed by the IPv6-specific kernel API.
293 	 * Otherwise, the kernel will detect some inconsistency and bark it.
294 	 */
295 	in6_ifdetach(ifp);
296 #endif
297 
298 	/*
299 	 * Delete all remaining routes using this interface
300 	 * Unfortuneatly the only way to do this is to slog through
301 	 * the entire routing table looking for routes which point
302 	 * to this interface...oh well...
303 	 */
304 	for (i = 1; i <= AF_MAX; i++) {
305 		if ((rnh = rt_tables[i]) == NULL)
306 			continue;
307 		(void) rnh->rnh_walktree(rnh, if_rtdel, ifp);
308 	}
309 
310 	TAILQ_REMOVE(&ifnet, ifp, if_link);
311 	mtx_destroy(&ifp->if_snd.ifq_mtx);
312 	splx(s);
313 }
314 
315 /*
316  * Delete Routes for a Network Interface
317  *
318  * Called for each routing entry via the rnh->rnh_walktree() call above
319  * to delete all route entries referencing a detaching network interface.
320  *
321  * Arguments:
322  *	rn	pointer to node in the routing table
323  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
324  *
325  * Returns:
326  *	0	successful
327  *	errno	failed - reason indicated
328  *
329  */
330 static int
331 if_rtdel(rn, arg)
332 	struct radix_node	*rn;
333 	void			*arg;
334 {
335 	struct rtentry	*rt = (struct rtentry *)rn;
336 	struct ifnet	*ifp = arg;
337 	int		err;
338 
339 	if (rt->rt_ifp == ifp) {
340 
341 		/*
342 		 * Protect (sorta) against walktree recursion problems
343 		 * with cloned routes
344 		 */
345 		if ((rt->rt_flags & RTF_UP) == 0)
346 			return (0);
347 
348 		err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
349 				rt_mask(rt), rt->rt_flags,
350 				(struct rtentry **) NULL);
351 		if (err) {
352 			log(LOG_WARNING, "if_rtdel: error %d\n", err);
353 		}
354 	}
355 
356 	return (0);
357 }
358 
359 /*
360  * Create a clone network interface.
361  */
362 int
363 if_clone_create(name, len)
364 	char *name;
365 	int len;
366 {
367 	struct if_clone *ifc;
368 	char *dp;
369 	int wildcard;
370 	int unit;
371 	int err;
372 
373 	ifc = if_clone_lookup(name, &unit);
374 	if (ifc == NULL)
375 		return (EINVAL);
376 
377 	if (ifunit(name) != NULL)
378 		return (EEXIST);
379 
380 	wildcard = (unit < 0);
381 
382 	err = (*ifc->ifc_create)(ifc, &unit);
383 	if (err != 0)
384 		return (err);
385 
386 	/* In the wildcard case, we need to update the name. */
387 	if (wildcard) {
388 		for (dp = name; *dp != '\0'; dp++);
389 		if (snprintf(dp, len - (dp-name), "%d", unit) >
390 		    len - (dp-name) - 1) {
391 			/*
392 			 * This can only be a programmer error and
393 			 * there's no straightforward way to recover if
394 			 * it happens.
395 			 */
396 			panic("if_clone_create(): interface name too long");
397 		}
398 
399 	}
400 
401 	return (0);
402 }
403 
404 /*
405  * Destroy a clone network interface.
406  */
407 int
408 if_clone_destroy(name)
409 	const char *name;
410 {
411 	struct if_clone *ifc;
412 	struct ifnet *ifp;
413 
414 	ifc = if_clone_lookup(name, NULL);
415 	if (ifc == NULL)
416 		return (EINVAL);
417 
418 	ifp = ifunit(name);
419 	if (ifp == NULL)
420 		return (ENXIO);
421 
422 	if (ifc->ifc_destroy == NULL)
423 		return (EOPNOTSUPP);
424 
425 	(*ifc->ifc_destroy)(ifp);
426 	return (0);
427 }
428 
429 /*
430  * Look up a network interface cloner.
431  */
432 struct if_clone *
433 if_clone_lookup(name, unitp)
434 	const char *name;
435 	int *unitp;
436 {
437 	struct if_clone *ifc;
438 	const char *cp;
439 	int i;
440 
441 	for (ifc = LIST_FIRST(&if_cloners); ifc != NULL;) {
442 		for (cp = name, i = 0; i < ifc->ifc_namelen; i++, cp++) {
443 			if (ifc->ifc_name[i] != *cp)
444 				goto next_ifc;
445 		}
446 		goto found_name;
447  next_ifc:
448 		ifc = LIST_NEXT(ifc, ifc_list);
449 	}
450 
451 	/* No match. */
452 	return ((struct if_clone *)NULL);
453 
454  found_name:
455 	if (*cp == '\0') {
456 		i = -1;
457 	} else {
458 		for (i = 0; *cp != '\0'; cp++) {
459 			if (*cp < '0' || *cp > '9') {
460 				/* Bogus unit number. */
461 				return (NULL);
462 			}
463 			i = (i * 10) + (*cp - '0');
464 		}
465 	}
466 
467 	if (unitp != NULL)
468 		*unitp = i;
469 	return (ifc);
470 }
471 
472 /*
473  * Register a network interface cloner.
474  */
475 void
476 if_clone_attach(ifc)
477 	struct if_clone *ifc;
478 {
479 
480 	LIST_INSERT_HEAD(&if_cloners, ifc, ifc_list);
481 	if_cloners_count++;
482 }
483 
484 /*
485  * Unregister a network interface cloner.
486  */
487 void
488 if_clone_detach(ifc)
489 	struct if_clone *ifc;
490 {
491 
492 	LIST_REMOVE(ifc, ifc_list);
493 	if_cloners_count--;
494 }
495 
496 /*
497  * Provide list of interface cloners to userspace.
498  */
499 int
500 if_clone_list(ifcr)
501 	struct if_clonereq *ifcr;
502 {
503 	char outbuf[IFNAMSIZ], *dst;
504 	struct if_clone *ifc;
505 	int count, error = 0;
506 
507 	ifcr->ifcr_total = if_cloners_count;
508 	if ((dst = ifcr->ifcr_buffer) == NULL) {
509 		/* Just asking how many there are. */
510 		return (0);
511 	}
512 
513 	if (ifcr->ifcr_count < 0)
514 		return (EINVAL);
515 
516 	count = (if_cloners_count < ifcr->ifcr_count) ?
517 	    if_cloners_count : ifcr->ifcr_count;
518 
519 	for (ifc = LIST_FIRST(&if_cloners); ifc != NULL && count != 0;
520 	     ifc = LIST_NEXT(ifc, ifc_list), count--, dst += IFNAMSIZ) {
521 		strncpy(outbuf, ifc->ifc_name, IFNAMSIZ);
522 		outbuf[IFNAMSIZ - 1] = '\0';	/* sanity */
523 		error = copyout(outbuf, dst, IFNAMSIZ);
524 		if (error)
525 			break;
526 	}
527 
528 	return (error);
529 }
530 
531 /*
532  * Locate an interface based on a complete address.
533  */
534 /*ARGSUSED*/
535 struct ifaddr *
536 ifa_ifwithaddr(addr)
537 	register struct sockaddr *addr;
538 {
539 	register struct ifnet *ifp;
540 	register struct ifaddr *ifa;
541 
542 #define	equal(a1, a2) \
543   (bcmp((caddr_t)(a1), (caddr_t)(a2), ((struct sockaddr *)(a1))->sa_len) == 0)
544 	TAILQ_FOREACH(ifp, &ifnet, if_link)
545 	    TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
546 		if (ifa->ifa_addr->sa_family != addr->sa_family)
547 			continue;
548 		if (equal(addr, ifa->ifa_addr))
549 			return (ifa);
550 		if ((ifp->if_flags & IFF_BROADCAST) && ifa->ifa_broadaddr &&
551 		    /* IP6 doesn't have broadcast */
552 		    ifa->ifa_broadaddr->sa_len != 0 &&
553 		    equal(ifa->ifa_broadaddr, addr))
554 			return (ifa);
555 	}
556 	return ((struct ifaddr *)0);
557 }
558 /*
559  * Locate the point to point interface with a given destination address.
560  */
561 /*ARGSUSED*/
562 struct ifaddr *
563 ifa_ifwithdstaddr(addr)
564 	register struct sockaddr *addr;
565 {
566 	register struct ifnet *ifp;
567 	register struct ifaddr *ifa;
568 
569 	TAILQ_FOREACH(ifp, &ifnet, if_link)
570 	    if (ifp->if_flags & IFF_POINTOPOINT)
571 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
572 			if (ifa->ifa_addr->sa_family != addr->sa_family)
573 				continue;
574 			if (ifa->ifa_dstaddr && equal(addr, ifa->ifa_dstaddr))
575 				return (ifa);
576 	}
577 	return ((struct ifaddr *)0);
578 }
579 
580 /*
581  * Find an interface on a specific network.  If many, choice
582  * is most specific found.
583  */
584 struct ifaddr *
585 ifa_ifwithnet(addr)
586 	struct sockaddr *addr;
587 {
588 	register struct ifnet *ifp;
589 	register struct ifaddr *ifa;
590 	struct ifaddr *ifa_maybe = (struct ifaddr *) 0;
591 	u_int af = addr->sa_family;
592 	char *addr_data = addr->sa_data, *cplim;
593 
594 	/*
595 	 * AF_LINK addresses can be looked up directly by their index number,
596 	 * so do that if we can.
597 	 */
598 	if (af == AF_LINK) {
599 	    register struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
600 	    if (sdl->sdl_index && sdl->sdl_index <= if_index)
601 		return (ifnet_addrs[sdl->sdl_index - 1]);
602 	}
603 
604 	/*
605 	 * Scan though each interface, looking for ones that have
606 	 * addresses in this address family.
607 	 */
608 	TAILQ_FOREACH(ifp, &ifnet, if_link) {
609 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
610 			register char *cp, *cp2, *cp3;
611 
612 			if (ifa->ifa_addr->sa_family != af)
613 next:				continue;
614 			if (
615 #ifdef INET6 /* XXX: for maching gif tunnel dst as routing entry gateway */
616 			    addr->sa_family != AF_INET6 &&
617 #endif
618 			    ifp->if_flags & IFF_POINTOPOINT) {
619 				/*
620 				 * This is a bit broken as it doesn't
621 				 * take into account that the remote end may
622 				 * be a single node in the network we are
623 				 * looking for.
624 				 * The trouble is that we don't know the
625 				 * netmask for the remote end.
626 				 */
627 				if (ifa->ifa_dstaddr != 0
628 				    && equal(addr, ifa->ifa_dstaddr))
629  					return (ifa);
630 			} else {
631 				/*
632 				 * if we have a special address handler,
633 				 * then use it instead of the generic one.
634 				 */
635 	          		if (ifa->ifa_claim_addr) {
636 					if ((*ifa->ifa_claim_addr)(ifa, addr)) {
637 						return (ifa);
638 					} else {
639 						continue;
640 					}
641 				}
642 
643 				/*
644 				 * Scan all the bits in the ifa's address.
645 				 * If a bit dissagrees with what we are
646 				 * looking for, mask it with the netmask
647 				 * to see if it really matters.
648 				 * (A byte at a time)
649 				 */
650 				if (ifa->ifa_netmask == 0)
651 					continue;
652 				cp = addr_data;
653 				cp2 = ifa->ifa_addr->sa_data;
654 				cp3 = ifa->ifa_netmask->sa_data;
655 				cplim = ifa->ifa_netmask->sa_len
656 					+ (char *)ifa->ifa_netmask;
657 				while (cp3 < cplim)
658 					if ((*cp++ ^ *cp2++) & *cp3++)
659 						goto next; /* next address! */
660 				/*
661 				 * If the netmask of what we just found
662 				 * is more specific than what we had before
663 				 * (if we had one) then remember the new one
664 				 * before continuing to search
665 				 * for an even better one.
666 				 */
667 				if (ifa_maybe == 0 ||
668 				    rn_refines((caddr_t)ifa->ifa_netmask,
669 				    (caddr_t)ifa_maybe->ifa_netmask))
670 					ifa_maybe = ifa;
671 			}
672 		}
673 	}
674 	return (ifa_maybe);
675 }
676 
677 /*
678  * Find an interface address specific to an interface best matching
679  * a given address.
680  */
681 struct ifaddr *
682 ifaof_ifpforaddr(addr, ifp)
683 	struct sockaddr *addr;
684 	register struct ifnet *ifp;
685 {
686 	register struct ifaddr *ifa;
687 	register char *cp, *cp2, *cp3;
688 	register char *cplim;
689 	struct ifaddr *ifa_maybe = 0;
690 	u_int af = addr->sa_family;
691 
692 	if (af >= AF_MAX)
693 		return (0);
694 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
695 		if (ifa->ifa_addr->sa_family != af)
696 			continue;
697 		if (ifa_maybe == 0)
698 			ifa_maybe = ifa;
699 		if (ifa->ifa_netmask == 0) {
700 			if (equal(addr, ifa->ifa_addr) ||
701 			    (ifa->ifa_dstaddr && equal(addr, ifa->ifa_dstaddr)))
702 				return (ifa);
703 			continue;
704 		}
705 		if (ifp->if_flags & IFF_POINTOPOINT) {
706 			if (equal(addr, ifa->ifa_dstaddr))
707 				return (ifa);
708 		} else {
709 			cp = addr->sa_data;
710 			cp2 = ifa->ifa_addr->sa_data;
711 			cp3 = ifa->ifa_netmask->sa_data;
712 			cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
713 			for (; cp3 < cplim; cp3++)
714 				if ((*cp++ ^ *cp2++) & *cp3)
715 					break;
716 			if (cp3 == cplim)
717 				return (ifa);
718 		}
719 	}
720 	return (ifa_maybe);
721 }
722 
723 #include <net/route.h>
724 
725 /*
726  * Default action when installing a route with a Link Level gateway.
727  * Lookup an appropriate real ifa to point to.
728  * This should be moved to /sys/net/link.c eventually.
729  */
730 static void
731 link_rtrequest(cmd, rt, sa)
732 	int cmd;
733 	register struct rtentry *rt;
734 	struct sockaddr *sa;
735 {
736 	register struct ifaddr *ifa;
737 	struct sockaddr *dst;
738 	struct ifnet *ifp;
739 
740 	if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == 0) ||
741 	    ((ifp = ifa->ifa_ifp) == 0) || ((dst = rt_key(rt)) == 0))
742 		return;
743 	ifa = ifaof_ifpforaddr(dst, ifp);
744 	if (ifa) {
745 		IFAFREE(rt->rt_ifa);
746 		rt->rt_ifa = ifa;
747 		ifa->ifa_refcnt++;
748 		if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
749 			ifa->ifa_rtrequest(cmd, rt, sa);
750 	}
751 }
752 
753 /*
754  * Mark an interface down and notify protocols of
755  * the transition.
756  * NOTE: must be called at splnet or eqivalent.
757  */
758 void
759 if_unroute(ifp, flag, fam)
760 	register struct ifnet *ifp;
761 	int flag, fam;
762 {
763 	register struct ifaddr *ifa;
764 
765 	ifp->if_flags &= ~flag;
766 	getmicrotime(&ifp->if_lastchange);
767 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
768 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
769 			pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
770 	if_qflush(&ifp->if_snd);
771 	rt_ifmsg(ifp);
772 }
773 
774 /*
775  * Mark an interface up and notify protocols of
776  * the transition.
777  * NOTE: must be called at splnet or eqivalent.
778  */
779 void
780 if_route(ifp, flag, fam)
781 	register struct ifnet *ifp;
782 	int flag, fam;
783 {
784 	register struct ifaddr *ifa;
785 
786 	ifp->if_flags |= flag;
787 	getmicrotime(&ifp->if_lastchange);
788 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
789 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
790 			pfctlinput(PRC_IFUP, ifa->ifa_addr);
791 	rt_ifmsg(ifp);
792 #ifdef INET6
793 	in6_if_up(ifp);
794 #endif
795 }
796 
797 /*
798  * Mark an interface down and notify protocols of
799  * the transition.
800  * NOTE: must be called at splnet or eqivalent.
801  */
802 void
803 if_down(ifp)
804 	register struct ifnet *ifp;
805 {
806 
807 	if_unroute(ifp, IFF_UP, AF_UNSPEC);
808 }
809 
810 /*
811  * Mark an interface up and notify protocols of
812  * the transition.
813  * NOTE: must be called at splnet or eqivalent.
814  */
815 void
816 if_up(ifp)
817 	register struct ifnet *ifp;
818 {
819 
820 	if_route(ifp, IFF_UP, AF_UNSPEC);
821 }
822 
823 /*
824  * Flush an interface queue.
825  */
826 static void
827 if_qflush(ifq)
828 	register struct ifqueue *ifq;
829 {
830 	register struct mbuf *m, *n;
831 
832 	n = ifq->ifq_head;
833 	while ((m = n) != 0) {
834 		n = m->m_act;
835 		m_freem(m);
836 	}
837 	ifq->ifq_head = 0;
838 	ifq->ifq_tail = 0;
839 	ifq->ifq_len = 0;
840 }
841 
842 /*
843  * Handle interface watchdog timer routines.  Called
844  * from softclock, we decrement timers (if set) and
845  * call the appropriate interface routine on expiration.
846  */
847 static void
848 if_slowtimo(arg)
849 	void *arg;
850 {
851 	register struct ifnet *ifp;
852 	int s = splimp();
853 
854 	TAILQ_FOREACH(ifp, &ifnet, if_link) {
855 		if (ifp->if_timer == 0 || --ifp->if_timer)
856 			continue;
857 		if (ifp->if_watchdog)
858 			(*ifp->if_watchdog)(ifp);
859 	}
860 	splx(s);
861 	timeout(if_slowtimo, (void *)0, hz / IFNET_SLOWHZ);
862 }
863 
864 /*
865  * Map interface name to
866  * interface structure pointer.
867  */
868 struct ifnet *
869 ifunit(const char *name)
870 {
871 	char namebuf[IFNAMSIZ + 1];
872 	const char *cp;
873 	struct ifnet *ifp;
874 	int unit;
875 	unsigned len, m;
876 	char c;
877 
878 	len = strlen(name);
879 	if (len < 2 || len > IFNAMSIZ)
880 		return NULL;
881 	cp = name + len - 1;
882 	c = *cp;
883 	if (c < '0' || c > '9')
884 		return NULL;		/* trailing garbage */
885 	unit = 0;
886 	m = 1;
887 	do {
888 		if (cp == name)
889 			return NULL;	/* no interface name */
890 		unit += (c - '0') * m;
891 		if (unit > 1000000)
892 			return NULL;	/* number is unreasonable */
893 		m *= 10;
894 		c = *--cp;
895 	} while (c >= '0' && c <= '9');
896 	len = cp - name + 1;
897 	bcopy(name, namebuf, len);
898 	namebuf[len] = '\0';
899 	/*
900 	 * Now search all the interfaces for this name/number
901 	 */
902 	TAILQ_FOREACH(ifp, &ifnet, if_link) {
903 		if (strcmp(ifp->if_name, namebuf))
904 			continue;
905 		if (unit == ifp->if_unit)
906 			break;
907 	}
908 	return (ifp);
909 }
910 
911 
912 /*
913  * Map interface name in a sockaddr_dl to
914  * interface structure pointer.
915  */
916 struct ifnet *
917 if_withname(sa)
918 	struct sockaddr *sa;
919 {
920 	char ifname[IFNAMSIZ+1];
921 	struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
922 
923 	if ( (sa->sa_family != AF_LINK) || (sdl->sdl_nlen == 0) ||
924 	     (sdl->sdl_nlen > IFNAMSIZ) )
925 		return NULL;
926 
927 	/*
928 	 * ifunit wants a null-terminated name.  It may not be null-terminated
929 	 * in the sockaddr.  We don't want to change the caller's sockaddr,
930 	 * and there might not be room to put the trailing null anyway, so we
931 	 * make a local copy that we know we can null terminate safely.
932 	 */
933 
934 	bcopy(sdl->sdl_data, ifname, sdl->sdl_nlen);
935 	ifname[sdl->sdl_nlen] = '\0';
936 	return ifunit(ifname);
937 }
938 
939 
940 /*
941  * Interface ioctls.
942  */
943 int
944 ifioctl(so, cmd, data, p)
945 	struct socket *so;
946 	u_long cmd;
947 	caddr_t data;
948 	struct proc *p;
949 {
950 	register struct ifnet *ifp;
951 	register struct ifreq *ifr;
952 	struct ifstat *ifs;
953 	int error;
954 	short oif_flags;
955 
956 	switch (cmd) {
957 
958 	case SIOCGIFCONF:
959 	case OSIOCGIFCONF:
960 		return (ifconf(cmd, data));
961 	}
962 	ifr = (struct ifreq *)data;
963 
964 	switch (cmd) {
965 	case SIOCIFCREATE:
966 	case SIOCIFDESTROY:
967 		if ((error = suser(p)) != 0)
968 			return (error);
969 		return ((cmd == SIOCIFCREATE) ?
970 			if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name)) :
971 			if_clone_destroy(ifr->ifr_name));
972 
973 	case SIOCIFGCLONERS:
974 		return (if_clone_list((struct if_clonereq *)data));
975 	}
976 
977 	ifp = ifunit(ifr->ifr_name);
978 	if (ifp == 0)
979 		return (ENXIO);
980 	switch (cmd) {
981 
982 	case SIOCGIFFLAGS:
983 		ifr->ifr_flags = ifp->if_flags;
984 		break;
985 
986 	case SIOCGIFMETRIC:
987 		ifr->ifr_metric = ifp->if_metric;
988 		break;
989 
990 	case SIOCGIFMTU:
991 		ifr->ifr_mtu = ifp->if_mtu;
992 		break;
993 
994 	case SIOCGIFPHYS:
995 		ifr->ifr_phys = ifp->if_physical;
996 		break;
997 
998 	case SIOCSIFFLAGS:
999 		error = suser(p);
1000 		if (error)
1001 			return (error);
1002 		ifr->ifr_prevflags = ifp->if_flags;
1003 		if (ifp->if_flags & IFF_SMART) {
1004 			/* Smart drivers twiddle their own routes */
1005 		} else if (ifp->if_flags & IFF_UP &&
1006 		    (ifr->ifr_flags & IFF_UP) == 0) {
1007 			int s = splimp();
1008 			if_down(ifp);
1009 			splx(s);
1010 		} else if (ifr->ifr_flags & IFF_UP &&
1011 		    (ifp->if_flags & IFF_UP) == 0) {
1012 			int s = splimp();
1013 			if_up(ifp);
1014 			splx(s);
1015 		}
1016 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1017 			(ifr->ifr_flags &~ IFF_CANTCHANGE);
1018 		if (ifp->if_ioctl)
1019 			(void) (*ifp->if_ioctl)(ifp, cmd, data);
1020 		getmicrotime(&ifp->if_lastchange);
1021 		break;
1022 
1023 	case SIOCSIFMETRIC:
1024 		error = suser(p);
1025 		if (error)
1026 			return (error);
1027 		ifp->if_metric = ifr->ifr_metric;
1028 		getmicrotime(&ifp->if_lastchange);
1029 		break;
1030 
1031 	case SIOCSIFPHYS:
1032 		error = suser(p);
1033 		if (error)
1034 			return error;
1035 		if (!ifp->if_ioctl)
1036 		        return EOPNOTSUPP;
1037 		error = (*ifp->if_ioctl)(ifp, cmd, data);
1038 		if (error == 0)
1039 			getmicrotime(&ifp->if_lastchange);
1040 		return(error);
1041 
1042 	case SIOCSIFMTU:
1043 	{
1044 		u_long oldmtu = ifp->if_mtu;
1045 
1046 		error = suser(p);
1047 		if (error)
1048 			return (error);
1049 		if (ifp->if_ioctl == NULL)
1050 			return (EOPNOTSUPP);
1051 		if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
1052 			return (EINVAL);
1053 		error = (*ifp->if_ioctl)(ifp, cmd, data);
1054 		if (error == 0) {
1055 			getmicrotime(&ifp->if_lastchange);
1056 			rt_ifmsg(ifp);
1057 		}
1058 		/*
1059 		 * If the link MTU changed, do network layer specific procedure.
1060 		 */
1061 		if (ifp->if_mtu != oldmtu) {
1062 #ifdef INET6
1063 			nd6_setmtu(ifp);
1064 #endif
1065 		}
1066 		return (error);
1067 	}
1068 
1069 	case SIOCADDMULTI:
1070 	case SIOCDELMULTI:
1071 		error = suser(p);
1072 		if (error)
1073 			return (error);
1074 
1075 		/* Don't allow group membership on non-multicast interfaces. */
1076 		if ((ifp->if_flags & IFF_MULTICAST) == 0)
1077 			return EOPNOTSUPP;
1078 
1079 		/* Don't let users screw up protocols' entries. */
1080 		if (ifr->ifr_addr.sa_family != AF_LINK)
1081 			return EINVAL;
1082 
1083 		if (cmd == SIOCADDMULTI) {
1084 			struct ifmultiaddr *ifma;
1085 			error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
1086 		} else {
1087 			error = if_delmulti(ifp, &ifr->ifr_addr);
1088 		}
1089 		if (error == 0)
1090 			getmicrotime(&ifp->if_lastchange);
1091 		return error;
1092 
1093 	case SIOCSIFPHYADDR:
1094 	case SIOCDIFPHYADDR:
1095 #ifdef INET6
1096 	case SIOCSIFPHYADDR_IN6:
1097 #endif
1098 	case SIOCSLIFPHYADDR:
1099         case SIOCSIFMEDIA:
1100 	case SIOCSIFGENERIC:
1101 		error = suser(p);
1102 		if (error)
1103 			return (error);
1104 		if (ifp->if_ioctl == 0)
1105 			return (EOPNOTSUPP);
1106 		error = (*ifp->if_ioctl)(ifp, cmd, data);
1107 		if (error == 0)
1108 			getmicrotime(&ifp->if_lastchange);
1109 		return error;
1110 
1111 	case SIOCGIFSTATUS:
1112 		ifs = (struct ifstat *)data;
1113 		ifs->ascii[0] = '\0';
1114 
1115 	case SIOCGIFPSRCADDR:
1116 	case SIOCGIFPDSTADDR:
1117 	case SIOCGLIFPHYADDR:
1118 	case SIOCGIFMEDIA:
1119 	case SIOCGIFGENERIC:
1120 		if (ifp->if_ioctl == 0)
1121 			return (EOPNOTSUPP);
1122 		return ((*ifp->if_ioctl)(ifp, cmd, data));
1123 
1124 	case SIOCSIFLLADDR:
1125 		error = suser(p);
1126 		if (error)
1127 			return (error);
1128 		return if_setlladdr(ifp,
1129 		    ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
1130 
1131 	default:
1132 		oif_flags = ifp->if_flags;
1133 		if (so->so_proto == 0)
1134 			return (EOPNOTSUPP);
1135 #ifndef COMPAT_43
1136 		error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
1137 								 data,
1138 								 ifp, p));
1139 #else
1140 	    {
1141 		int ocmd = cmd;
1142 
1143 		switch (cmd) {
1144 
1145 		case SIOCSIFDSTADDR:
1146 		case SIOCSIFADDR:
1147 		case SIOCSIFBRDADDR:
1148 		case SIOCSIFNETMASK:
1149 #if BYTE_ORDER != BIG_ENDIAN
1150 			if (ifr->ifr_addr.sa_family == 0 &&
1151 			    ifr->ifr_addr.sa_len < 16) {
1152 				ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
1153 				ifr->ifr_addr.sa_len = 16;
1154 			}
1155 #else
1156 			if (ifr->ifr_addr.sa_len == 0)
1157 				ifr->ifr_addr.sa_len = 16;
1158 #endif
1159 			break;
1160 
1161 		case OSIOCGIFADDR:
1162 			cmd = SIOCGIFADDR;
1163 			break;
1164 
1165 		case OSIOCGIFDSTADDR:
1166 			cmd = SIOCGIFDSTADDR;
1167 			break;
1168 
1169 		case OSIOCGIFBRDADDR:
1170 			cmd = SIOCGIFBRDADDR;
1171 			break;
1172 
1173 		case OSIOCGIFNETMASK:
1174 			cmd = SIOCGIFNETMASK;
1175 		}
1176 		error =  ((*so->so_proto->pr_usrreqs->pru_control)(so,
1177 								   cmd,
1178 								   data,
1179 								   ifp, p));
1180 		switch (ocmd) {
1181 
1182 		case OSIOCGIFADDR:
1183 		case OSIOCGIFDSTADDR:
1184 		case OSIOCGIFBRDADDR:
1185 		case OSIOCGIFNETMASK:
1186 			*(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
1187 
1188 		}
1189 	    }
1190 #endif /* COMPAT_43 */
1191 
1192 		if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
1193 #ifdef INET6
1194 			DELAY(100);/* XXX: temporal workaround for fxp issue*/
1195 			if (ifp->if_flags & IFF_UP) {
1196 				int s = splimp();
1197 				in6_if_up(ifp);
1198 				splx(s);
1199 			}
1200 #endif
1201 		}
1202 		return (error);
1203 
1204 	}
1205 	return (0);
1206 }
1207 
1208 /*
1209  * Set/clear promiscuous mode on interface ifp based on the truth value
1210  * of pswitch.  The calls are reference counted so that only the first
1211  * "on" request actually has an effect, as does the final "off" request.
1212  * Results are undefined if the "off" and "on" requests are not matched.
1213  */
1214 int
1215 ifpromisc(ifp, pswitch)
1216 	struct ifnet *ifp;
1217 	int pswitch;
1218 {
1219 	struct ifreq ifr;
1220 	int error;
1221 	int oldflags, oldpcount;
1222 
1223 	oldpcount = ifp->if_pcount;
1224 	oldflags = ifp->if_flags;
1225 	if (pswitch) {
1226 		/*
1227 		 * If the device is not configured up, we cannot put it in
1228 		 * promiscuous mode.
1229 		 */
1230 		if ((ifp->if_flags & IFF_UP) == 0)
1231 			return (ENETDOWN);
1232 		if (ifp->if_pcount++ != 0)
1233 			return (0);
1234 		ifp->if_flags |= IFF_PROMISC;
1235 	} else {
1236 		if (--ifp->if_pcount > 0)
1237 			return (0);
1238 		ifp->if_flags &= ~IFF_PROMISC;
1239 	}
1240 	ifr.ifr_flags = ifp->if_flags;
1241 	error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
1242 	if (error == 0) {
1243 		log(LOG_INFO, "%s%d: promiscuous mode %s\n",
1244 		    ifp->if_name, ifp->if_unit,
1245 		    (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
1246 		rt_ifmsg(ifp);
1247 	} else {
1248 		ifp->if_pcount = oldpcount;
1249 		ifp->if_flags = oldflags;
1250 	}
1251 	return error;
1252 }
1253 
1254 /*
1255  * Return interface configuration
1256  * of system.  List may be used
1257  * in later ioctl's (above) to get
1258  * other information.
1259  */
1260 /*ARGSUSED*/
1261 static int
1262 ifconf(cmd, data)
1263 	u_long cmd;
1264 	caddr_t data;
1265 {
1266 	register struct ifconf *ifc = (struct ifconf *)data;
1267 	register struct ifnet *ifp = TAILQ_FIRST(&ifnet);
1268 	register struct ifaddr *ifa;
1269 	struct ifreq ifr, *ifrp;
1270 	int space = ifc->ifc_len, error = 0;
1271 
1272 	ifrp = ifc->ifc_req;
1273 	for (; space > sizeof (ifr) && ifp; ifp = TAILQ_NEXT(ifp, if_link)) {
1274 		char workbuf[64];
1275 		int ifnlen, addrs;
1276 
1277 		ifnlen = snprintf(workbuf, sizeof(workbuf),
1278 		    "%s%d", ifp->if_name, ifp->if_unit);
1279 		if(ifnlen + 1 > sizeof ifr.ifr_name) {
1280 			error = ENAMETOOLONG;
1281 			break;
1282 		} else {
1283 			strcpy(ifr.ifr_name, workbuf);
1284 		}
1285 
1286 		addrs = 0;
1287 		ifa = TAILQ_FIRST(&ifp->if_addrhead);
1288 		for ( ; space > sizeof (ifr) && ifa;
1289 		    ifa = TAILQ_NEXT(ifa, ifa_link)) {
1290 			register struct sockaddr *sa = ifa->ifa_addr;
1291 			if (jailed(curproc->p_ucred) &&
1292 			    prison_if(curproc->p_ucred, sa))
1293 				continue;
1294 			addrs++;
1295 #ifdef COMPAT_43
1296 			if (cmd == OSIOCGIFCONF) {
1297 				struct osockaddr *osa =
1298 					 (struct osockaddr *)&ifr.ifr_addr;
1299 				ifr.ifr_addr = *sa;
1300 				osa->sa_family = sa->sa_family;
1301 				error = copyout((caddr_t)&ifr, (caddr_t)ifrp,
1302 						sizeof (ifr));
1303 				ifrp++;
1304 			} else
1305 #endif
1306 			if (sa->sa_len <= sizeof(*sa)) {
1307 				ifr.ifr_addr = *sa;
1308 				error = copyout((caddr_t)&ifr, (caddr_t)ifrp,
1309 						sizeof (ifr));
1310 				ifrp++;
1311 			} else {
1312 				if (space < sizeof (ifr) + sa->sa_len -
1313 					    sizeof(*sa))
1314 					break;
1315 				space -= sa->sa_len - sizeof(*sa);
1316 				error = copyout((caddr_t)&ifr, (caddr_t)ifrp,
1317 						sizeof (ifr.ifr_name));
1318 				if (error == 0)
1319 				    error = copyout((caddr_t)sa,
1320 				      (caddr_t)&ifrp->ifr_addr, sa->sa_len);
1321 				ifrp = (struct ifreq *)
1322 					(sa->sa_len + (caddr_t)&ifrp->ifr_addr);
1323 			}
1324 			if (error)
1325 				break;
1326 			space -= sizeof (ifr);
1327 		}
1328 		if (error)
1329 			break;
1330 		if (!addrs) {
1331 			bzero((caddr_t)&ifr.ifr_addr, sizeof(ifr.ifr_addr));
1332 			error = copyout((caddr_t)&ifr, (caddr_t)ifrp,
1333 			    sizeof (ifr));
1334 			if (error)
1335 				break;
1336 			space -= sizeof (ifr);
1337 			ifrp++;
1338 		}
1339 	}
1340 	ifc->ifc_len -= space;
1341 	return (error);
1342 }
1343 
1344 /*
1345  * Just like if_promisc(), but for all-multicast-reception mode.
1346  */
1347 int
1348 if_allmulti(ifp, onswitch)
1349 	struct ifnet *ifp;
1350 	int onswitch;
1351 {
1352 	int error = 0;
1353 	int s = splimp();
1354 
1355 	if (onswitch) {
1356 		if (ifp->if_amcount++ == 0) {
1357 			ifp->if_flags |= IFF_ALLMULTI;
1358 			error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, 0);
1359 		}
1360 	} else {
1361 		if (ifp->if_amcount > 1) {
1362 			ifp->if_amcount--;
1363 		} else {
1364 			ifp->if_amcount = 0;
1365 			ifp->if_flags &= ~IFF_ALLMULTI;
1366 			error = ifp->if_ioctl(ifp, SIOCSIFFLAGS, 0);
1367 		}
1368 	}
1369 	splx(s);
1370 
1371 	if (error == 0)
1372 		rt_ifmsg(ifp);
1373 	return error;
1374 }
1375 
1376 /*
1377  * Add a multicast listenership to the interface in question.
1378  * The link layer provides a routine which converts
1379  */
1380 int
1381 if_addmulti(ifp, sa, retifma)
1382 	struct ifnet *ifp;	/* interface to manipulate */
1383 	struct sockaddr *sa;	/* address to add */
1384 	struct ifmultiaddr **retifma;
1385 {
1386 	struct sockaddr *llsa, *dupsa;
1387 	int error, s;
1388 	struct ifmultiaddr *ifma;
1389 
1390 	/*
1391 	 * If the matching multicast address already exists
1392 	 * then don't add a new one, just add a reference
1393 	 */
1394 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1395 		if (equal(sa, ifma->ifma_addr)) {
1396 			ifma->ifma_refcount++;
1397 			if (retifma)
1398 				*retifma = ifma;
1399 			return 0;
1400 		}
1401 	}
1402 
1403 	/*
1404 	 * Give the link layer a chance to accept/reject it, and also
1405 	 * find out which AF_LINK address this maps to, if it isn't one
1406 	 * already.
1407 	 */
1408 	if (ifp->if_resolvemulti) {
1409 		error = ifp->if_resolvemulti(ifp, &llsa, sa);
1410 		if (error) return error;
1411 	} else {
1412 		llsa = 0;
1413 	}
1414 
1415 	MALLOC(ifma, struct ifmultiaddr *, sizeof *ifma, M_IFMADDR, M_WAITOK);
1416 	MALLOC(dupsa, struct sockaddr *, sa->sa_len, M_IFMADDR, M_WAITOK);
1417 	bcopy(sa, dupsa, sa->sa_len);
1418 
1419 	ifma->ifma_addr = dupsa;
1420 	ifma->ifma_lladdr = llsa;
1421 	ifma->ifma_ifp = ifp;
1422 	ifma->ifma_refcount = 1;
1423 	ifma->ifma_protospec = 0;
1424 	rt_newmaddrmsg(RTM_NEWMADDR, ifma);
1425 
1426 	/*
1427 	 * Some network interfaces can scan the address list at
1428 	 * interrupt time; lock them out.
1429 	 */
1430 	s = splimp();
1431 	TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
1432 	splx(s);
1433 	*retifma = ifma;
1434 
1435 	if (llsa != 0) {
1436 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1437 			if (equal(ifma->ifma_addr, llsa))
1438 				break;
1439 		}
1440 		if (ifma) {
1441 			ifma->ifma_refcount++;
1442 		} else {
1443 			MALLOC(ifma, struct ifmultiaddr *, sizeof *ifma,
1444 			       M_IFMADDR, M_WAITOK);
1445 			MALLOC(dupsa, struct sockaddr *, llsa->sa_len,
1446 			       M_IFMADDR, M_WAITOK);
1447 			bcopy(llsa, dupsa, llsa->sa_len);
1448 			ifma->ifma_addr = dupsa;
1449 			ifma->ifma_ifp = ifp;
1450 			ifma->ifma_refcount = 1;
1451 			s = splimp();
1452 			TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
1453 			splx(s);
1454 		}
1455 	}
1456 	/*
1457 	 * We are certain we have added something, so call down to the
1458 	 * interface to let them know about it.
1459 	 */
1460 	s = splimp();
1461 	ifp->if_ioctl(ifp, SIOCADDMULTI, 0);
1462 	splx(s);
1463 
1464 	return 0;
1465 }
1466 
1467 /*
1468  * Remove a reference to a multicast address on this interface.  Yell
1469  * if the request does not match an existing membership.
1470  */
1471 int
1472 if_delmulti(ifp, sa)
1473 	struct ifnet *ifp;
1474 	struct sockaddr *sa;
1475 {
1476 	struct ifmultiaddr *ifma;
1477 	int s;
1478 
1479 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
1480 		if (equal(sa, ifma->ifma_addr))
1481 			break;
1482 	if (ifma == 0)
1483 		return ENOENT;
1484 
1485 	if (ifma->ifma_refcount > 1) {
1486 		ifma->ifma_refcount--;
1487 		return 0;
1488 	}
1489 
1490 	rt_newmaddrmsg(RTM_DELMADDR, ifma);
1491 	sa = ifma->ifma_lladdr;
1492 	s = splimp();
1493 	TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
1494 	/*
1495 	 * Make sure the interface driver is notified
1496 	 * in the case of a link layer mcast group being left.
1497 	 */
1498 	if (ifma->ifma_addr->sa_family == AF_LINK && sa == 0)
1499 		ifp->if_ioctl(ifp, SIOCDELMULTI, 0);
1500 	splx(s);
1501 	free(ifma->ifma_addr, M_IFMADDR);
1502 	free(ifma, M_IFMADDR);
1503 	if (sa == 0)
1504 		return 0;
1505 
1506 	/*
1507 	 * Now look for the link-layer address which corresponds to
1508 	 * this network address.  It had been squirreled away in
1509 	 * ifma->ifma_lladdr for this purpose (so we don't have
1510 	 * to call ifp->if_resolvemulti() again), and we saved that
1511 	 * value in sa above.  If some nasty deleted the
1512 	 * link-layer address out from underneath us, we can deal because
1513 	 * the address we stored was is not the same as the one which was
1514 	 * in the record for the link-layer address.  (So we don't complain
1515 	 * in that case.)
1516 	 */
1517 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
1518 		if (equal(sa, ifma->ifma_addr))
1519 			break;
1520 	if (ifma == 0)
1521 		return 0;
1522 
1523 	if (ifma->ifma_refcount > 1) {
1524 		ifma->ifma_refcount--;
1525 		return 0;
1526 	}
1527 
1528 	s = splimp();
1529 	TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
1530 	ifp->if_ioctl(ifp, SIOCDELMULTI, 0);
1531 	splx(s);
1532 	free(ifma->ifma_addr, M_IFMADDR);
1533 	free(sa, M_IFMADDR);
1534 	free(ifma, M_IFMADDR);
1535 
1536 	return 0;
1537 }
1538 
1539 /*
1540  * Set the link layer address on an interface.
1541  *
1542  * At this time we only support certain types of interfaces,
1543  * and we don't allow the length of the address to change.
1544  */
1545 int
1546 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
1547 {
1548 	struct sockaddr_dl *sdl;
1549 	struct ifaddr *ifa;
1550 
1551 	ifa = ifnet_addrs[ifp->if_index - 1];
1552 	if (ifa == NULL)
1553 		return (EINVAL);
1554 	sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1555 	if (sdl == NULL)
1556 		return (EINVAL);
1557 	if (len != sdl->sdl_alen)	/* don't allow length to change */
1558 		return (EINVAL);
1559 	switch (ifp->if_type) {
1560 	case IFT_ETHER:			/* these types use struct arpcom */
1561 	case IFT_FDDI:
1562 	case IFT_XETHER:
1563 	case IFT_ISO88025:
1564 	case IFT_L2VLAN:
1565 		bcopy(lladdr, ((struct arpcom *)ifp->if_softc)->ac_enaddr, len);
1566 		bcopy(lladdr, LLADDR(sdl), len);
1567 		break;
1568 	default:
1569 		return (ENODEV);
1570 	}
1571 	/*
1572 	 * If the interface is already up, we need
1573 	 * to re-init it in order to reprogram its
1574 	 * address filter.
1575 	 */
1576 	if ((ifp->if_flags & IFF_UP) != 0) {
1577 		ifp->if_flags &= ~IFF_UP;
1578 		(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, NULL);
1579 		ifp->if_flags |= IFF_UP;
1580 		(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, NULL);
1581 	}
1582 	return (0);
1583 }
1584 
1585 struct ifmultiaddr *
1586 ifmaof_ifpforaddr(sa, ifp)
1587 	struct sockaddr *sa;
1588 	struct ifnet *ifp;
1589 {
1590 	struct ifmultiaddr *ifma;
1591 
1592 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
1593 		if (equal(ifma->ifma_addr, sa))
1594 			break;
1595 
1596 	return ifma;
1597 }
1598 
1599 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
1600 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
1601