xref: /freebsd/sys/net/if.c (revision cacdd70cc751fb68dec4b86c5e5b8c969b6e26ef)
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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)if.c	8.5 (Berkeley) 1/9/95
30  * $FreeBSD$
31  */
32 
33 #include "opt_compat.h"
34 #include "opt_inet6.h"
35 #include "opt_inet.h"
36 #include "opt_mac.h"
37 #include "opt_carp.h"
38 
39 #include <sys/param.h>
40 #include <sys/types.h>
41 #include <sys/conf.h>
42 #include <sys/malloc.h>
43 #include <sys/sbuf.h>
44 #include <sys/bus.h>
45 #include <sys/mbuf.h>
46 #include <sys/systm.h>
47 #include <sys/priv.h>
48 #include <sys/proc.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/protosw.h>
52 #include <sys/kernel.h>
53 #include <sys/sockio.h>
54 #include <sys/syslog.h>
55 #include <sys/sysctl.h>
56 #include <sys/taskqueue.h>
57 #include <sys/domain.h>
58 #include <sys/jail.h>
59 #include <machine/stdarg.h>
60 
61 #include <net/if.h>
62 #include <net/if_clone.h>
63 #include <net/if_dl.h>
64 #include <net/if_types.h>
65 #include <net/if_var.h>
66 #include <net/radix.h>
67 #include <net/route.h>
68 
69 #if defined(INET) || defined(INET6)
70 /*XXX*/
71 #include <netinet/in.h>
72 #include <netinet/in_var.h>
73 #ifdef INET6
74 #include <netinet6/in6_var.h>
75 #include <netinet6/in6_ifattach.h>
76 #endif
77 #endif
78 #ifdef INET
79 #include <netinet/if_ether.h>
80 #endif
81 #ifdef DEV_CARP
82 #include <netinet/ip_carp.h>
83 #endif
84 
85 #include <security/mac/mac_framework.h>
86 
87 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
88 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
89 
90 /* Log link state change events */
91 static int log_link_state_change = 1;
92 
93 SYSCTL_INT(_net_link, OID_AUTO, log_link_state_change, CTLFLAG_RW,
94 	&log_link_state_change, 0,
95 	"log interface link state change events");
96 
97 void	(*bstp_linkstate_p)(struct ifnet *ifp, int state);
98 void	(*ng_ether_link_state_p)(struct ifnet *ifp, int state);
99 void	(*lagg_linkstate_p)(struct ifnet *ifp, int state);
100 
101 struct mbuf *(*tbr_dequeue_ptr)(struct ifaltq *, int) = NULL;
102 
103 /*
104  * XXX: Style; these should be sorted alphabetically, and unprototyped
105  * static functions should be prototyped. Currently they are sorted by
106  * declaration order.
107  */
108 static void	if_attachdomain(void *);
109 static void	if_attachdomain1(struct ifnet *);
110 static int	ifconf(u_long, caddr_t);
111 static void	if_freemulti(struct ifmultiaddr *);
112 static void	if_grow(void);
113 static void	if_init(void *);
114 static void	if_qflush(struct ifaltq *);
115 static void	if_route(struct ifnet *, int flag, int fam);
116 static int	if_setflag(struct ifnet *, int, int, int *, int);
117 static void	if_slowtimo(void *);
118 static void	if_unroute(struct ifnet *, int flag, int fam);
119 static void	link_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
120 static int	if_rtdel(struct radix_node *, void *);
121 static int	ifhwioctl(u_long, struct ifnet *, caddr_t, struct thread *);
122 static int	if_delmulti_locked(struct ifnet *, struct ifmultiaddr *, int);
123 static void	if_start_deferred(void *context, int pending);
124 static void	do_link_state_change(void *, int);
125 static int	if_getgroup(struct ifgroupreq *, struct ifnet *);
126 static int	if_getgroupmembers(struct ifgroupreq *);
127 #ifdef INET6
128 /*
129  * XXX: declare here to avoid to include many inet6 related files..
130  * should be more generalized?
131  */
132 extern void	nd6_setmtu(struct ifnet *);
133 #endif
134 
135 int	if_index = 0;
136 int	ifqmaxlen = IFQ_MAXLEN;
137 struct	ifnethead ifnet;	/* depend on static init XXX */
138 struct	ifgrouphead ifg_head;
139 struct	mtx ifnet_lock;
140 static	if_com_alloc_t *if_com_alloc[256];
141 static	if_com_free_t *if_com_free[256];
142 
143 static int	if_indexlim = 8;
144 static struct	knlist ifklist;
145 
146 /*
147  * Table of ifnet/cdev by index.  Locked with ifnet_lock.
148  */
149 static struct ifindex_entry *ifindex_table = NULL;
150 
151 static void	filt_netdetach(struct knote *kn);
152 static int	filt_netdev(struct knote *kn, long hint);
153 
154 static struct filterops netdev_filtops =
155     { 1, NULL, filt_netdetach, filt_netdev };
156 
157 /*
158  * System initialization
159  */
160 SYSINIT(interfaces, SI_SUB_INIT_IF, SI_ORDER_FIRST, if_init, NULL);
161 SYSINIT(interface_check, SI_SUB_PROTO_IF, SI_ORDER_FIRST, if_slowtimo, NULL);
162 
163 MALLOC_DEFINE(M_IFNET, "ifnet", "interface internals");
164 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
165 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
166 
167 struct ifnet *
168 ifnet_byindex(u_short idx)
169 {
170 	struct ifnet *ifp;
171 
172 	IFNET_RLOCK();
173 	ifp = ifindex_table[idx].ife_ifnet;
174 	IFNET_RUNLOCK();
175 	return (ifp);
176 }
177 
178 static void
179 ifnet_setbyindex(u_short idx, struct ifnet *ifp)
180 {
181 
182 	IFNET_WLOCK_ASSERT();
183 
184 	ifindex_table[idx].ife_ifnet = ifp;
185 }
186 
187 struct ifaddr *
188 ifaddr_byindex(u_short idx)
189 {
190 	struct ifaddr *ifa;
191 
192 	IFNET_RLOCK();
193 	ifa = ifnet_byindex(idx)->if_addr;
194 	IFNET_RUNLOCK();
195 	return (ifa);
196 }
197 
198 struct cdev *
199 ifdev_byindex(u_short idx)
200 {
201 	struct cdev *cdev;
202 
203 	IFNET_RLOCK();
204 	cdev = ifindex_table[idx].ife_dev;
205 	IFNET_RUNLOCK();
206 	return (cdev);
207 }
208 
209 static void
210 ifdev_setbyindex(u_short idx, struct cdev *cdev)
211 {
212 
213 	IFNET_WLOCK();
214 	ifindex_table[idx].ife_dev = cdev;
215 	IFNET_WUNLOCK();
216 }
217 
218 static d_open_t		netopen;
219 static d_close_t	netclose;
220 static d_ioctl_t	netioctl;
221 static d_kqfilter_t	netkqfilter;
222 
223 static struct cdevsw net_cdevsw = {
224 	.d_version =	D_VERSION,
225 	.d_flags =	D_NEEDGIANT,
226 	.d_open =	netopen,
227 	.d_close =	netclose,
228 	.d_ioctl =	netioctl,
229 	.d_name =	"net",
230 	.d_kqfilter =	netkqfilter,
231 };
232 
233 static int
234 netopen(struct cdev *dev, int flag, int mode, struct thread *td)
235 {
236 	return (0);
237 }
238 
239 static int
240 netclose(struct cdev *dev, int flags, int fmt, struct thread *td)
241 {
242 	return (0);
243 }
244 
245 static int
246 netioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
247 {
248 	struct ifnet *ifp;
249 	int error, idx;
250 
251 	/* only support interface specific ioctls */
252 	if (IOCGROUP(cmd) != 'i')
253 		return (EOPNOTSUPP);
254 	idx = minor(dev);
255 	if (idx == 0) {
256 		/*
257 		 * special network device, not interface.
258 		 */
259 		if (cmd == SIOCGIFCONF)
260 			return (ifconf(cmd, data));	/* XXX remove cmd */
261 #ifdef __amd64__
262 		if (cmd == SIOCGIFCONF32)
263 			return (ifconf(cmd, data));	/* XXX remove cmd */
264 #endif
265 		return (EOPNOTSUPP);
266 	}
267 
268 	ifp = ifnet_byindex(idx);
269 	if (ifp == NULL)
270 		return (ENXIO);
271 
272 	error = ifhwioctl(cmd, ifp, data, td);
273 	if (error == ENOIOCTL)
274 		error = EOPNOTSUPP;
275 	return (error);
276 }
277 
278 static int
279 netkqfilter(struct cdev *dev, struct knote *kn)
280 {
281 	struct knlist *klist;
282 	struct ifnet *ifp;
283 	int idx;
284 
285 	switch (kn->kn_filter) {
286 	case EVFILT_NETDEV:
287 		kn->kn_fop = &netdev_filtops;
288 		break;
289 	default:
290 		return (EINVAL);
291 	}
292 
293 	idx = minor(dev);
294 	if (idx == 0) {
295 		klist = &ifklist;
296 	} else {
297 		ifp = ifnet_byindex(idx);
298 		if (ifp == NULL)
299 			return (1);
300 		klist = &ifp->if_klist;
301 	}
302 
303 	kn->kn_hook = (caddr_t)klist;
304 
305 	knlist_add(klist, kn, 0);
306 
307 	return (0);
308 }
309 
310 static void
311 filt_netdetach(struct knote *kn)
312 {
313 	struct knlist *klist = (struct knlist *)kn->kn_hook;
314 
315 	knlist_remove(klist, kn, 0);
316 }
317 
318 static int
319 filt_netdev(struct knote *kn, long hint)
320 {
321 	struct knlist *klist = (struct knlist *)kn->kn_hook;
322 
323 	/*
324 	 * Currently NOTE_EXIT is abused to indicate device detach.
325 	 */
326 	if (hint == NOTE_EXIT) {
327 		kn->kn_data = NOTE_LINKINV;
328 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
329 		knlist_remove_inevent(klist, kn);
330 		return (1);
331 	}
332 	if (hint != 0)
333 		kn->kn_data = hint;			/* current status */
334 	if (kn->kn_sfflags & hint)
335 		kn->kn_fflags |= hint;
336 	return (kn->kn_fflags != 0);
337 }
338 
339 /*
340  * Network interface utility routines.
341  *
342  * Routines with ifa_ifwith* names take sockaddr *'s as
343  * parameters.
344  */
345 
346 /* ARGSUSED*/
347 static void
348 if_init(void *dummy __unused)
349 {
350 
351 	IFNET_LOCK_INIT();
352 	TAILQ_INIT(&ifnet);
353 	TAILQ_INIT(&ifg_head);
354 	knlist_init(&ifklist, NULL, NULL, NULL, NULL);
355 	if_grow();				/* create initial table */
356 	ifdev_setbyindex(0, make_dev(&net_cdevsw, 0, UID_ROOT, GID_WHEEL,
357 	    0600, "network"));
358 	if_clone_init();
359 }
360 
361 static void
362 if_grow(void)
363 {
364 	u_int n;
365 	struct ifindex_entry *e;
366 
367 	if_indexlim <<= 1;
368 	n = if_indexlim * sizeof(*e);
369 	e = malloc(n, M_IFNET, M_WAITOK | M_ZERO);
370 	if (ifindex_table != NULL) {
371 		memcpy((caddr_t)e, (caddr_t)ifindex_table, n/2);
372 		free((caddr_t)ifindex_table, M_IFNET);
373 	}
374 	ifindex_table = e;
375 }
376 
377 /*
378  * Allocate a struct ifnet and an index for an interface.  A layer 2
379  * common structure will also be allocated if an allocation routine is
380  * registered for the passed type.
381  */
382 struct ifnet*
383 if_alloc(u_char type)
384 {
385 	struct ifnet *ifp;
386 
387 	ifp = malloc(sizeof(struct ifnet), M_IFNET, M_WAITOK|M_ZERO);
388 
389 	/*
390 	 * Try to find an empty slot below if_index.  If we fail, take
391 	 * the next slot.
392 	 *
393 	 * XXX: should be locked!
394 	 */
395 	for (ifp->if_index = 1; ifp->if_index <= if_index; ifp->if_index++) {
396 		if (ifnet_byindex(ifp->if_index) == NULL)
397 			break;
398 	}
399 	/* Catch if_index overflow. */
400 	if (ifp->if_index < 1) {
401 		free(ifp, M_IFNET);
402 		return (NULL);
403 	}
404 	if (ifp->if_index > if_index)
405 		if_index = ifp->if_index;
406 	if (if_index >= if_indexlim)
407 		if_grow();
408 
409 	ifp->if_type = type;
410 
411 	if (if_com_alloc[type] != NULL) {
412 		ifp->if_l2com = if_com_alloc[type](type, ifp);
413 		if (ifp->if_l2com == NULL) {
414 			free(ifp, M_IFNET);
415 			return (NULL);
416 		}
417 	}
418 	IFNET_WLOCK();
419 	ifnet_setbyindex(ifp->if_index, ifp);
420 	IFNET_WUNLOCK();
421 	IF_ADDR_LOCK_INIT(ifp);
422 
423 	return (ifp);
424 }
425 
426 /*
427  * Free the struct ifnet, the associated index, and the layer 2 common
428  * structure if needed.  All the work is done in if_free_type().
429  *
430  * Do not add code to this function!  Add it to if_free_type().
431  */
432 void
433 if_free(struct ifnet *ifp)
434 {
435 
436 	if_free_type(ifp, ifp->if_type);
437 }
438 
439 /*
440  * Do the actual work of freeing a struct ifnet, associated index, and
441  * layer 2 common structure.  This version should only be called by
442  * intefaces that switch their type after calling if_alloc().
443  */
444 void
445 if_free_type(struct ifnet *ifp, u_char type)
446 {
447 
448 	if (ifp != ifnet_byindex(ifp->if_index)) {
449 		if_printf(ifp, "%s: value was not if_alloced, skipping\n",
450 		    __func__);
451 		return;
452 	}
453 
454 	IFNET_WLOCK();
455 	ifnet_setbyindex(ifp->if_index, NULL);
456 
457 	/* XXX: should be locked with if_findindex() */
458 	while (if_index > 0 && ifnet_byindex(if_index) == NULL)
459 		if_index--;
460 	IFNET_WUNLOCK();
461 
462 	if (if_com_free[type] != NULL)
463 		if_com_free[type](ifp->if_l2com, type);
464 
465 	IF_ADDR_LOCK_DESTROY(ifp);
466 	free(ifp, M_IFNET);
467 };
468 
469 /*
470  * Perform generic interface initalization tasks and attach the interface
471  * to the list of "active" interfaces.
472  *
473  * XXX:
474  *  - The decision to return void and thus require this function to
475  *    succeed is questionable.
476  *  - We do more initialization here then is probably a good idea.
477  *    Some of this should probably move to if_alloc().
478  *  - We should probably do more sanity checking.  For instance we don't
479  *    do anything to insure if_xname is unique or non-empty.
480  */
481 void
482 if_attach(struct ifnet *ifp)
483 {
484 	unsigned socksize, ifasize;
485 	int namelen, masklen;
486 	struct sockaddr_dl *sdl;
487 	struct ifaddr *ifa;
488 
489 	if (ifp->if_index == 0 || ifp != ifnet_byindex(ifp->if_index))
490 		panic ("%s: BUG: if_attach called without if_alloc'd input()\n",
491 		    ifp->if_xname);
492 
493 	TASK_INIT(&ifp->if_starttask, 0, if_start_deferred, ifp);
494 	TASK_INIT(&ifp->if_linktask, 0, do_link_state_change, ifp);
495 	IF_AFDATA_LOCK_INIT(ifp);
496 	ifp->if_afdata_initialized = 0;
497 
498 	TAILQ_INIT(&ifp->if_addrhead);
499 	TAILQ_INIT(&ifp->if_prefixhead);
500 	TAILQ_INIT(&ifp->if_multiaddrs);
501 	TAILQ_INIT(&ifp->if_groups);
502 
503 	if_addgroup(ifp, IFG_ALL);
504 
505 	knlist_init(&ifp->if_klist, NULL, NULL, NULL, NULL);
506 	getmicrotime(&ifp->if_lastchange);
507 	ifp->if_data.ifi_epoch = time_uptime;
508 	ifp->if_data.ifi_datalen = sizeof(struct if_data);
509 
510 #ifdef MAC
511 	mac_ifnet_init(ifp);
512 	mac_ifnet_create(ifp);
513 #endif
514 
515 	ifdev_setbyindex(ifp->if_index, make_dev(&net_cdevsw,
516 	    unit2minor(ifp->if_index), UID_ROOT, GID_WHEEL, 0600, "%s/%s",
517 	    net_cdevsw.d_name, ifp->if_xname));
518 	make_dev_alias(ifdev_byindex(ifp->if_index), "%s%d",
519 	    net_cdevsw.d_name, ifp->if_index);
520 
521 	mtx_init(&ifp->if_snd.ifq_mtx, ifp->if_xname, "if send queue", MTX_DEF);
522 
523 	/*
524 	 * create a Link Level name for this device
525 	 */
526 	namelen = strlen(ifp->if_xname);
527 	/*
528 	 * Always save enough space for any possiable name so we can do
529 	 * a rename in place later.
530 	 */
531 	masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + IFNAMSIZ;
532 	socksize = masklen + ifp->if_addrlen;
533 	if (socksize < sizeof(*sdl))
534 		socksize = sizeof(*sdl);
535 	socksize = roundup2(socksize, sizeof(long));
536 	ifasize = sizeof(*ifa) + 2 * socksize;
537 	ifa = malloc(ifasize, M_IFADDR, M_WAITOK | M_ZERO);
538 	IFA_LOCK_INIT(ifa);
539 	sdl = (struct sockaddr_dl *)(ifa + 1);
540 	sdl->sdl_len = socksize;
541 	sdl->sdl_family = AF_LINK;
542 	bcopy(ifp->if_xname, sdl->sdl_data, namelen);
543 	sdl->sdl_nlen = namelen;
544 	sdl->sdl_index = ifp->if_index;
545 	sdl->sdl_type = ifp->if_type;
546 	ifp->if_addr = ifa;
547 	ifa->ifa_ifp = ifp;
548 	ifa->ifa_rtrequest = link_rtrequest;
549 	ifa->ifa_addr = (struct sockaddr *)sdl;
550 	sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
551 	ifa->ifa_netmask = (struct sockaddr *)sdl;
552 	sdl->sdl_len = masklen;
553 	while (namelen != 0)
554 		sdl->sdl_data[--namelen] = 0xff;
555 	ifa->ifa_refcnt = 1;
556 	TAILQ_INSERT_HEAD(&ifp->if_addrhead, ifa, ifa_link);
557 	ifp->if_broadcastaddr = NULL; /* reliably crash if used uninitialized */
558 
559 	/*
560 	 * XXX: why do we warn about this? We're correcting it and most
561 	 * drivers just set the value the way we do.
562 	 */
563 	if (ifp->if_snd.ifq_maxlen == 0) {
564 		if_printf(ifp, "XXX: driver didn't set ifq_maxlen\n");
565 		ifp->if_snd.ifq_maxlen = ifqmaxlen;
566 	}
567 	ifp->if_snd.altq_type = 0;
568 	ifp->if_snd.altq_disc = NULL;
569 	ifp->if_snd.altq_flags &= ALTQF_CANTCHANGE;
570 	ifp->if_snd.altq_tbr  = NULL;
571 	ifp->if_snd.altq_ifp  = ifp;
572 
573 	IFNET_WLOCK();
574 	TAILQ_INSERT_TAIL(&ifnet, ifp, if_link);
575 	IFNET_WUNLOCK();
576 
577 	if (domain_init_status >= 2)
578 		if_attachdomain1(ifp);
579 
580 	EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
581 	devctl_notify("IFNET", ifp->if_xname, "ATTACH", NULL);
582 
583 	/* Announce the interface. */
584 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
585 
586 	if (ifp->if_watchdog != NULL)
587 		if_printf(ifp,
588 		    "WARNING: using obsoleted if_watchdog interface\n");
589 	if (ifp->if_flags & IFF_NEEDSGIANT)
590 		if_printf(ifp,
591 		    "WARNING: using obsoleted IFF_NEEDSGIANT flag\n");
592 }
593 
594 static void
595 if_attachdomain(void *dummy)
596 {
597 	struct ifnet *ifp;
598 	int s;
599 
600 	s = splnet();
601 	TAILQ_FOREACH(ifp, &ifnet, if_link)
602 		if_attachdomain1(ifp);
603 	splx(s);
604 }
605 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_SECOND,
606     if_attachdomain, NULL);
607 
608 static void
609 if_attachdomain1(struct ifnet *ifp)
610 {
611 	struct domain *dp;
612 	int s;
613 
614 	s = splnet();
615 
616 	/*
617 	 * Since dp->dom_ifattach calls malloc() with M_WAITOK, we
618 	 * cannot lock ifp->if_afdata initialization, entirely.
619 	 */
620 	if (IF_AFDATA_TRYLOCK(ifp) == 0) {
621 		splx(s);
622 		return;
623 	}
624 	if (ifp->if_afdata_initialized >= domain_init_status) {
625 		IF_AFDATA_UNLOCK(ifp);
626 		splx(s);
627 		printf("if_attachdomain called more than once on %s\n",
628 		    ifp->if_xname);
629 		return;
630 	}
631 	ifp->if_afdata_initialized = domain_init_status;
632 	IF_AFDATA_UNLOCK(ifp);
633 
634 	/* address family dependent data region */
635 	bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
636 	for (dp = domains; dp; dp = dp->dom_next) {
637 		if (dp->dom_ifattach)
638 			ifp->if_afdata[dp->dom_family] =
639 			    (*dp->dom_ifattach)(ifp);
640 	}
641 
642 	splx(s);
643 }
644 
645 /*
646  * Remove any unicast or broadcast network addresses from an interface.
647  */
648 void
649 if_purgeaddrs(struct ifnet *ifp)
650 {
651 	struct ifaddr *ifa, *next;
652 
653 	TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, next) {
654 		if (ifa->ifa_addr->sa_family == AF_LINK)
655 			continue;
656 #ifdef INET
657 		/* XXX: Ugly!! ad hoc just for INET */
658 		if (ifa->ifa_addr->sa_family == AF_INET) {
659 			struct ifaliasreq ifr;
660 
661 			bzero(&ifr, sizeof(ifr));
662 			ifr.ifra_addr = *ifa->ifa_addr;
663 			if (ifa->ifa_dstaddr)
664 				ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
665 			if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
666 			    NULL) == 0)
667 				continue;
668 		}
669 #endif /* INET */
670 #ifdef INET6
671 		if (ifa->ifa_addr->sa_family == AF_INET6) {
672 			in6_purgeaddr(ifa);
673 			/* ifp_addrhead is already updated */
674 			continue;
675 		}
676 #endif /* INET6 */
677 		TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
678 		IFAFREE(ifa);
679 	}
680 }
681 
682 /*
683  * Remove any multicast network addresses from an interface.
684  */
685 void
686 if_purgemaddrs(struct ifnet *ifp)
687 {
688 	struct ifmultiaddr *ifma;
689 	struct ifmultiaddr *next;
690 
691 	IF_ADDR_LOCK(ifp);
692 	TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
693 		if_delmulti_locked(ifp, ifma, 1);
694 	IF_ADDR_UNLOCK(ifp);
695 }
696 
697 /*
698  * Detach an interface, removing it from the
699  * list of "active" interfaces.
700  *
701  * XXXRW: There are some significant questions about event ordering, and
702  * how to prevent things from starting to use the interface during detach.
703  */
704 void
705 if_detach(struct ifnet *ifp)
706 {
707 	struct ifaddr *ifa;
708 	struct radix_node_head	*rnh;
709 	int s;
710 	int i;
711 	struct domain *dp;
712  	struct ifnet *iter;
713  	int found = 0;
714 
715 	IFNET_WLOCK();
716 	TAILQ_FOREACH(iter, &ifnet, if_link)
717 		if (iter == ifp) {
718 			TAILQ_REMOVE(&ifnet, ifp, if_link);
719 			found = 1;
720 			break;
721 		}
722 	IFNET_WUNLOCK();
723 	if (!found)
724 		return;
725 
726 	/*
727 	 * Remove/wait for pending events.
728 	 */
729 	taskqueue_drain(taskqueue_swi, &ifp->if_linktask);
730 
731 	/*
732 	 * Remove routes and flush queues.
733 	 */
734 	s = splnet();
735 	if_down(ifp);
736 #ifdef ALTQ
737 	if (ALTQ_IS_ENABLED(&ifp->if_snd))
738 		altq_disable(&ifp->if_snd);
739 	if (ALTQ_IS_ATTACHED(&ifp->if_snd))
740 		altq_detach(&ifp->if_snd);
741 #endif
742 
743 	if_purgeaddrs(ifp);
744 
745 #ifdef INET
746 	in_ifdetach(ifp);
747 #endif
748 
749 #ifdef INET6
750 	/*
751 	 * Remove all IPv6 kernel structs related to ifp.  This should be done
752 	 * before removing routing entries below, since IPv6 interface direct
753 	 * routes are expected to be removed by the IPv6-specific kernel API.
754 	 * Otherwise, the kernel will detect some inconsistency and bark it.
755 	 */
756 	in6_ifdetach(ifp);
757 #endif
758 	if_purgemaddrs(ifp);
759 
760 	/*
761 	 * Remove link ifaddr pointer and maybe decrement if_index.
762 	 * Clean up all addresses.
763 	 */
764 	ifp->if_addr = NULL;
765 	destroy_dev(ifdev_byindex(ifp->if_index));
766 	ifdev_setbyindex(ifp->if_index, NULL);
767 
768 	/* We can now free link ifaddr. */
769 	if (!TAILQ_EMPTY(&ifp->if_addrhead)) {
770 		ifa = TAILQ_FIRST(&ifp->if_addrhead);
771 		TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
772 		IFAFREE(ifa);
773 	}
774 
775 	/*
776 	 * Delete all remaining routes using this interface
777 	 * Unfortuneatly the only way to do this is to slog through
778 	 * the entire routing table looking for routes which point
779 	 * to this interface...oh well...
780 	 */
781 	for (i = 1; i <= AF_MAX; i++) {
782 	    int j;
783 	    for (j = 0; j < rt_numfibs; j++) {
784 		if ((rnh = rt_tables[j][i]) == NULL)
785 			continue;
786 		RADIX_NODE_HEAD_LOCK(rnh);
787 		(void) rnh->rnh_walktree(rnh, if_rtdel, ifp);
788 		RADIX_NODE_HEAD_UNLOCK(rnh);
789 	    }
790 	}
791 
792 	/* Announce that the interface is gone. */
793 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
794 	EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
795 	devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
796 
797 	IF_AFDATA_LOCK(ifp);
798 	for (dp = domains; dp; dp = dp->dom_next) {
799 		if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
800 			(*dp->dom_ifdetach)(ifp,
801 			    ifp->if_afdata[dp->dom_family]);
802 	}
803 	IF_AFDATA_UNLOCK(ifp);
804 
805 #ifdef MAC
806 	mac_ifnet_destroy(ifp);
807 #endif /* MAC */
808 	KNOTE_UNLOCKED(&ifp->if_klist, NOTE_EXIT);
809 	knlist_clear(&ifp->if_klist, 0);
810 	knlist_destroy(&ifp->if_klist);
811 	mtx_destroy(&ifp->if_snd.ifq_mtx);
812 	IF_AFDATA_DESTROY(ifp);
813 	splx(s);
814 }
815 
816 /*
817  * Add a group to an interface
818  */
819 int
820 if_addgroup(struct ifnet *ifp, const char *groupname)
821 {
822 	struct ifg_list		*ifgl;
823 	struct ifg_group	*ifg = NULL;
824 	struct ifg_member	*ifgm;
825 
826 	if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
827 	    groupname[strlen(groupname) - 1] <= '9')
828 		return (EINVAL);
829 
830 	IFNET_WLOCK();
831 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
832 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname)) {
833 			IFNET_WUNLOCK();
834 			return (EEXIST);
835 		}
836 
837 	if ((ifgl = (struct ifg_list *)malloc(sizeof(struct ifg_list), M_TEMP,
838 	    M_NOWAIT)) == NULL) {
839 	    	IFNET_WUNLOCK();
840 		return (ENOMEM);
841 	}
842 
843 	if ((ifgm = (struct ifg_member *)malloc(sizeof(struct ifg_member),
844 	    M_TEMP, M_NOWAIT)) == NULL) {
845 		free(ifgl, M_TEMP);
846 		IFNET_WUNLOCK();
847 		return (ENOMEM);
848 	}
849 
850 	TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
851 		if (!strcmp(ifg->ifg_group, groupname))
852 			break;
853 
854 	if (ifg == NULL) {
855 		if ((ifg = (struct ifg_group *)malloc(sizeof(struct ifg_group),
856 		    M_TEMP, M_NOWAIT)) == NULL) {
857 			free(ifgl, M_TEMP);
858 			free(ifgm, M_TEMP);
859 			IFNET_WUNLOCK();
860 			return (ENOMEM);
861 		}
862 		strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
863 		ifg->ifg_refcnt = 0;
864 		TAILQ_INIT(&ifg->ifg_members);
865 		EVENTHANDLER_INVOKE(group_attach_event, ifg);
866 		TAILQ_INSERT_TAIL(&ifg_head, ifg, ifg_next);
867 	}
868 
869 	ifg->ifg_refcnt++;
870 	ifgl->ifgl_group = ifg;
871 	ifgm->ifgm_ifp = ifp;
872 
873 	IF_ADDR_LOCK(ifp);
874 	TAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
875 	TAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
876 	IF_ADDR_UNLOCK(ifp);
877 
878 	IFNET_WUNLOCK();
879 
880 	EVENTHANDLER_INVOKE(group_change_event, groupname);
881 
882 	return (0);
883 }
884 
885 /*
886  * Remove a group from an interface
887  */
888 int
889 if_delgroup(struct ifnet *ifp, const char *groupname)
890 {
891 	struct ifg_list		*ifgl;
892 	struct ifg_member	*ifgm;
893 
894 	IFNET_WLOCK();
895 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
896 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
897 			break;
898 	if (ifgl == NULL) {
899 		IFNET_WUNLOCK();
900 		return (ENOENT);
901 	}
902 
903 	IF_ADDR_LOCK(ifp);
904 	TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
905 	IF_ADDR_UNLOCK(ifp);
906 
907 	TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
908 		if (ifgm->ifgm_ifp == ifp)
909 			break;
910 
911 	if (ifgm != NULL) {
912 		TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifgm_next);
913 		free(ifgm, M_TEMP);
914 	}
915 
916 	if (--ifgl->ifgl_group->ifg_refcnt == 0) {
917 		TAILQ_REMOVE(&ifg_head, ifgl->ifgl_group, ifg_next);
918 		EVENTHANDLER_INVOKE(group_detach_event, ifgl->ifgl_group);
919 		free(ifgl->ifgl_group, M_TEMP);
920 	}
921 	IFNET_WUNLOCK();
922 
923 	free(ifgl, M_TEMP);
924 
925 	EVENTHANDLER_INVOKE(group_change_event, groupname);
926 
927 	return (0);
928 }
929 
930 /*
931  * Stores all groups from an interface in memory pointed
932  * to by data
933  */
934 static int
935 if_getgroup(struct ifgroupreq *data, struct ifnet *ifp)
936 {
937 	int			 len, error;
938 	struct ifg_list		*ifgl;
939 	struct ifg_req		 ifgrq, *ifgp;
940 	struct ifgroupreq	*ifgr = data;
941 
942 	if (ifgr->ifgr_len == 0) {
943 		IF_ADDR_LOCK(ifp);
944 		TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
945 			ifgr->ifgr_len += sizeof(struct ifg_req);
946 		IF_ADDR_UNLOCK(ifp);
947 		return (0);
948 	}
949 
950 	len = ifgr->ifgr_len;
951 	ifgp = ifgr->ifgr_groups;
952 	/* XXX: wire */
953 	IF_ADDR_LOCK(ifp);
954 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
955 		if (len < sizeof(ifgrq)) {
956 			IF_ADDR_UNLOCK(ifp);
957 			return (EINVAL);
958 		}
959 		bzero(&ifgrq, sizeof ifgrq);
960 		strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
961 		    sizeof(ifgrq.ifgrq_group));
962 		if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
963 		    	IF_ADDR_UNLOCK(ifp);
964 			return (error);
965 		}
966 		len -= sizeof(ifgrq);
967 		ifgp++;
968 	}
969 	IF_ADDR_UNLOCK(ifp);
970 
971 	return (0);
972 }
973 
974 /*
975  * Stores all members of a group in memory pointed to by data
976  */
977 static int
978 if_getgroupmembers(struct ifgroupreq *data)
979 {
980 	struct ifgroupreq	*ifgr = data;
981 	struct ifg_group	*ifg;
982 	struct ifg_member	*ifgm;
983 	struct ifg_req		 ifgrq, *ifgp;
984 	int			 len, error;
985 
986 	IFNET_RLOCK();
987 	TAILQ_FOREACH(ifg, &ifg_head, ifg_next)
988 		if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
989 			break;
990 	if (ifg == NULL) {
991 		IFNET_RUNLOCK();
992 		return (ENOENT);
993 	}
994 
995 	if (ifgr->ifgr_len == 0) {
996 		TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
997 			ifgr->ifgr_len += sizeof(ifgrq);
998 		IFNET_RUNLOCK();
999 		return (0);
1000 	}
1001 
1002 	len = ifgr->ifgr_len;
1003 	ifgp = ifgr->ifgr_groups;
1004 	TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1005 		if (len < sizeof(ifgrq)) {
1006 			IFNET_RUNLOCK();
1007 			return (EINVAL);
1008 		}
1009 		bzero(&ifgrq, sizeof ifgrq);
1010 		strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1011 		    sizeof(ifgrq.ifgrq_member));
1012 		if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1013 			IFNET_RUNLOCK();
1014 			return (error);
1015 		}
1016 		len -= sizeof(ifgrq);
1017 		ifgp++;
1018 	}
1019 	IFNET_RUNLOCK();
1020 
1021 	return (0);
1022 }
1023 
1024 /*
1025  * Delete Routes for a Network Interface
1026  *
1027  * Called for each routing entry via the rnh->rnh_walktree() call above
1028  * to delete all route entries referencing a detaching network interface.
1029  *
1030  * Arguments:
1031  *	rn	pointer to node in the routing table
1032  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
1033  *
1034  * Returns:
1035  *	0	successful
1036  *	errno	failed - reason indicated
1037  *
1038  */
1039 static int
1040 if_rtdel(struct radix_node *rn, void *arg)
1041 {
1042 	struct rtentry	*rt = (struct rtentry *)rn;
1043 	struct ifnet	*ifp = arg;
1044 	int		err;
1045 
1046 	if (rt->rt_ifp == ifp) {
1047 
1048 		/*
1049 		 * Protect (sorta) against walktree recursion problems
1050 		 * with cloned routes
1051 		 */
1052 		if ((rt->rt_flags & RTF_UP) == 0)
1053 			return (0);
1054 
1055 		err = rtrequest_fib(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1056 				rt_mask(rt), rt->rt_flags,
1057 				(struct rtentry **) NULL, rt->rt_fibnum);
1058 		if (err) {
1059 			log(LOG_WARNING, "if_rtdel: error %d\n", err);
1060 		}
1061 	}
1062 
1063 	return (0);
1064 }
1065 
1066 /*
1067  * XXX: Because sockaddr_dl has deeper structure than the sockaddr
1068  * structs used to represent other address families, it is necessary
1069  * to perform a different comparison.
1070  */
1071 
1072 #define	sa_equal(a1, a2)	\
1073 	(bcmp((a1), (a2), ((a1))->sa_len) == 0)
1074 
1075 #define	sa_dl_equal(a1, a2)	\
1076 	((((struct sockaddr_dl *)(a1))->sdl_len ==			\
1077 	 ((struct sockaddr_dl *)(a2))->sdl_len) &&			\
1078 	 (bcmp(LLADDR((struct sockaddr_dl *)(a1)),			\
1079 	       LLADDR((struct sockaddr_dl *)(a2)),			\
1080 	       ((struct sockaddr_dl *)(a1))->sdl_alen) == 0))
1081 
1082 /*
1083  * Locate an interface based on a complete address.
1084  */
1085 /*ARGSUSED*/
1086 struct ifaddr *
1087 ifa_ifwithaddr(struct sockaddr *addr)
1088 {
1089 	struct ifnet *ifp;
1090 	struct ifaddr *ifa;
1091 
1092 	IFNET_RLOCK();
1093 	TAILQ_FOREACH(ifp, &ifnet, if_link)
1094 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1095 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1096 				continue;
1097 			if (sa_equal(addr, ifa->ifa_addr))
1098 				goto done;
1099 			/* IP6 doesn't have broadcast */
1100 			if ((ifp->if_flags & IFF_BROADCAST) &&
1101 			    ifa->ifa_broadaddr &&
1102 			    ifa->ifa_broadaddr->sa_len != 0 &&
1103 			    sa_equal(ifa->ifa_broadaddr, addr))
1104 				goto done;
1105 		}
1106 	ifa = NULL;
1107 done:
1108 	IFNET_RUNLOCK();
1109 	return (ifa);
1110 }
1111 
1112 /*
1113  * Locate an interface based on the broadcast address.
1114  */
1115 /* ARGSUSED */
1116 struct ifaddr *
1117 ifa_ifwithbroadaddr(struct sockaddr *addr)
1118 {
1119 	struct ifnet *ifp;
1120 	struct ifaddr *ifa;
1121 
1122 	IFNET_RLOCK();
1123 	TAILQ_FOREACH(ifp, &ifnet, if_link)
1124 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1125 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1126 				continue;
1127 			if ((ifp->if_flags & IFF_BROADCAST) &&
1128 			    ifa->ifa_broadaddr &&
1129 			    ifa->ifa_broadaddr->sa_len != 0 &&
1130 			    sa_equal(ifa->ifa_broadaddr, addr))
1131 				goto done;
1132 		}
1133 	ifa = NULL;
1134 done:
1135 	IFNET_RUNLOCK();
1136 	return (ifa);
1137 }
1138 
1139 /*
1140  * Locate the point to point interface with a given destination address.
1141  */
1142 /*ARGSUSED*/
1143 struct ifaddr *
1144 ifa_ifwithdstaddr(struct sockaddr *addr)
1145 {
1146 	struct ifnet *ifp;
1147 	struct ifaddr *ifa;
1148 
1149 	IFNET_RLOCK();
1150 	TAILQ_FOREACH(ifp, &ifnet, if_link) {
1151 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1152 			continue;
1153 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1154 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1155 				continue;
1156 			if (ifa->ifa_dstaddr &&
1157 			    sa_equal(addr, ifa->ifa_dstaddr))
1158 				goto done;
1159 		}
1160 	}
1161 	ifa = NULL;
1162 done:
1163 	IFNET_RUNLOCK();
1164 	return (ifa);
1165 }
1166 
1167 /*
1168  * Find an interface on a specific network.  If many, choice
1169  * is most specific found.
1170  */
1171 struct ifaddr *
1172 ifa_ifwithnet(struct sockaddr *addr)
1173 {
1174 	struct ifnet *ifp;
1175 	struct ifaddr *ifa;
1176 	struct ifaddr *ifa_maybe = (struct ifaddr *) 0;
1177 	u_int af = addr->sa_family;
1178 	char *addr_data = addr->sa_data, *cplim;
1179 
1180 	/*
1181 	 * AF_LINK addresses can be looked up directly by their index number,
1182 	 * so do that if we can.
1183 	 */
1184 	if (af == AF_LINK) {
1185 	    struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
1186 	    if (sdl->sdl_index && sdl->sdl_index <= if_index)
1187 		return (ifaddr_byindex(sdl->sdl_index));
1188 	}
1189 
1190 	/*
1191 	 * Scan though each interface, looking for ones that have
1192 	 * addresses in this address family.
1193 	 */
1194 	IFNET_RLOCK();
1195 	TAILQ_FOREACH(ifp, &ifnet, if_link) {
1196 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1197 			char *cp, *cp2, *cp3;
1198 
1199 			if (ifa->ifa_addr->sa_family != af)
1200 next:				continue;
1201 			if (af == AF_INET && ifp->if_flags & IFF_POINTOPOINT) {
1202 				/*
1203 				 * This is a bit broken as it doesn't
1204 				 * take into account that the remote end may
1205 				 * be a single node in the network we are
1206 				 * looking for.
1207 				 * The trouble is that we don't know the
1208 				 * netmask for the remote end.
1209 				 */
1210 				if (ifa->ifa_dstaddr != 0 &&
1211 				    sa_equal(addr, ifa->ifa_dstaddr))
1212 					goto done;
1213 			} else {
1214 				/*
1215 				 * if we have a special address handler,
1216 				 * then use it instead of the generic one.
1217 				 */
1218 				if (ifa->ifa_claim_addr) {
1219 					if ((*ifa->ifa_claim_addr)(ifa, addr))
1220 						goto done;
1221 					continue;
1222 				}
1223 
1224 				/*
1225 				 * Scan all the bits in the ifa's address.
1226 				 * If a bit dissagrees with what we are
1227 				 * looking for, mask it with the netmask
1228 				 * to see if it really matters.
1229 				 * (A byte at a time)
1230 				 */
1231 				if (ifa->ifa_netmask == 0)
1232 					continue;
1233 				cp = addr_data;
1234 				cp2 = ifa->ifa_addr->sa_data;
1235 				cp3 = ifa->ifa_netmask->sa_data;
1236 				cplim = ifa->ifa_netmask->sa_len
1237 					+ (char *)ifa->ifa_netmask;
1238 				while (cp3 < cplim)
1239 					if ((*cp++ ^ *cp2++) & *cp3++)
1240 						goto next; /* next address! */
1241 				/*
1242 				 * If the netmask of what we just found
1243 				 * is more specific than what we had before
1244 				 * (if we had one) then remember the new one
1245 				 * before continuing to search
1246 				 * for an even better one.
1247 				 */
1248 				if (ifa_maybe == 0 ||
1249 				    rn_refines((caddr_t)ifa->ifa_netmask,
1250 				    (caddr_t)ifa_maybe->ifa_netmask))
1251 					ifa_maybe = ifa;
1252 			}
1253 		}
1254 	}
1255 	ifa = ifa_maybe;
1256 done:
1257 	IFNET_RUNLOCK();
1258 	return (ifa);
1259 }
1260 
1261 /*
1262  * Find an interface address specific to an interface best matching
1263  * a given address.
1264  */
1265 struct ifaddr *
1266 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1267 {
1268 	struct ifaddr *ifa;
1269 	char *cp, *cp2, *cp3;
1270 	char *cplim;
1271 	struct ifaddr *ifa_maybe = 0;
1272 	u_int af = addr->sa_family;
1273 
1274 	if (af >= AF_MAX)
1275 		return (0);
1276 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1277 		if (ifa->ifa_addr->sa_family != af)
1278 			continue;
1279 		if (ifa_maybe == 0)
1280 			ifa_maybe = ifa;
1281 		if (ifa->ifa_netmask == 0) {
1282 			if (sa_equal(addr, ifa->ifa_addr) ||
1283 			    (ifa->ifa_dstaddr &&
1284 			    sa_equal(addr, ifa->ifa_dstaddr)))
1285 				goto done;
1286 			continue;
1287 		}
1288 		if (ifp->if_flags & IFF_POINTOPOINT) {
1289 			if (sa_equal(addr, ifa->ifa_dstaddr))
1290 				goto done;
1291 		} else {
1292 			cp = addr->sa_data;
1293 			cp2 = ifa->ifa_addr->sa_data;
1294 			cp3 = ifa->ifa_netmask->sa_data;
1295 			cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1296 			for (; cp3 < cplim; cp3++)
1297 				if ((*cp++ ^ *cp2++) & *cp3)
1298 					break;
1299 			if (cp3 == cplim)
1300 				goto done;
1301 		}
1302 	}
1303 	ifa = ifa_maybe;
1304 done:
1305 	return (ifa);
1306 }
1307 
1308 #include <net/route.h>
1309 
1310 /*
1311  * Default action when installing a route with a Link Level gateway.
1312  * Lookup an appropriate real ifa to point to.
1313  * This should be moved to /sys/net/link.c eventually.
1314  */
1315 static void
1316 link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info)
1317 {
1318 	struct ifaddr *ifa, *oifa;
1319 	struct sockaddr *dst;
1320 	struct ifnet *ifp;
1321 
1322 	RT_LOCK_ASSERT(rt);
1323 
1324 	if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == 0) ||
1325 	    ((ifp = ifa->ifa_ifp) == 0) || ((dst = rt_key(rt)) == 0))
1326 		return;
1327 	ifa = ifaof_ifpforaddr(dst, ifp);
1328 	if (ifa) {
1329 		IFAREF(ifa);		/* XXX */
1330 		oifa = rt->rt_ifa;
1331 		rt->rt_ifa = ifa;
1332 		IFAFREE(oifa);
1333 		if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1334 			ifa->ifa_rtrequest(cmd, rt, info);
1335 	}
1336 }
1337 
1338 /*
1339  * Mark an interface down and notify protocols of
1340  * the transition.
1341  * NOTE: must be called at splnet or eqivalent.
1342  */
1343 static void
1344 if_unroute(struct ifnet *ifp, int flag, int fam)
1345 {
1346 	struct ifaddr *ifa;
1347 
1348 	KASSERT(flag == IFF_UP, ("if_unroute: flag != IFF_UP"));
1349 
1350 	ifp->if_flags &= ~flag;
1351 	getmicrotime(&ifp->if_lastchange);
1352 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1353 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1354 			pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1355 	if_qflush(&ifp->if_snd);
1356 #ifdef DEV_CARP
1357 	if (ifp->if_carp)
1358 		carp_carpdev_state(ifp->if_carp);
1359 #endif
1360 	rt_ifmsg(ifp);
1361 }
1362 
1363 /*
1364  * Mark an interface up and notify protocols of
1365  * the transition.
1366  * NOTE: must be called at splnet or eqivalent.
1367  */
1368 static void
1369 if_route(struct ifnet *ifp, int flag, int fam)
1370 {
1371 	struct ifaddr *ifa;
1372 
1373 	KASSERT(flag == IFF_UP, ("if_route: flag != IFF_UP"));
1374 
1375 	ifp->if_flags |= flag;
1376 	getmicrotime(&ifp->if_lastchange);
1377 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1378 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1379 			pfctlinput(PRC_IFUP, ifa->ifa_addr);
1380 #ifdef DEV_CARP
1381 	if (ifp->if_carp)
1382 		carp_carpdev_state(ifp->if_carp);
1383 #endif
1384 	rt_ifmsg(ifp);
1385 #ifdef INET6
1386 	in6_if_up(ifp);
1387 #endif
1388 }
1389 
1390 void	(*vlan_link_state_p)(struct ifnet *, int);	/* XXX: private from if_vlan */
1391 void	(*vlan_trunk_cap_p)(struct ifnet *);		/* XXX: private from if_vlan */
1392 
1393 /*
1394  * Handle a change in the interface link state. To avoid LORs
1395  * between driver lock and upper layer locks, as well as possible
1396  * recursions, we post event to taskqueue, and all job
1397  * is done in static do_link_state_change().
1398  */
1399 void
1400 if_link_state_change(struct ifnet *ifp, int link_state)
1401 {
1402 	/* Return if state hasn't changed. */
1403 	if (ifp->if_link_state == link_state)
1404 		return;
1405 
1406 	ifp->if_link_state = link_state;
1407 
1408 	taskqueue_enqueue(taskqueue_swi, &ifp->if_linktask);
1409 }
1410 
1411 static void
1412 do_link_state_change(void *arg, int pending)
1413 {
1414 	struct ifnet *ifp = (struct ifnet *)arg;
1415 	int link_state = ifp->if_link_state;
1416 	int link;
1417 
1418 	/* Notify that the link state has changed. */
1419 	rt_ifmsg(ifp);
1420 	if (link_state == LINK_STATE_UP)
1421 		link = NOTE_LINKUP;
1422 	else if (link_state == LINK_STATE_DOWN)
1423 		link = NOTE_LINKDOWN;
1424 	else
1425 		link = NOTE_LINKINV;
1426 	KNOTE_UNLOCKED(&ifp->if_klist, link);
1427 	if (ifp->if_vlantrunk != NULL)
1428 		(*vlan_link_state_p)(ifp, link);
1429 
1430 	if ((ifp->if_type == IFT_ETHER || ifp->if_type == IFT_L2VLAN) &&
1431 	    IFP2AC(ifp)->ac_netgraph != NULL)
1432 		(*ng_ether_link_state_p)(ifp, link_state);
1433 #ifdef DEV_CARP
1434 	if (ifp->if_carp)
1435 		carp_carpdev_state(ifp->if_carp);
1436 #endif
1437 	if (ifp->if_bridge) {
1438 		KASSERT(bstp_linkstate_p != NULL,("if_bridge bstp not loaded!"));
1439 		(*bstp_linkstate_p)(ifp, link_state);
1440 	}
1441 	if (ifp->if_lagg) {
1442 		KASSERT(lagg_linkstate_p != NULL,("if_lagg not loaded!"));
1443 		(*lagg_linkstate_p)(ifp, link_state);
1444 	}
1445 
1446 	devctl_notify("IFNET", ifp->if_xname,
1447 	    (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN", NULL);
1448 	if (pending > 1)
1449 		if_printf(ifp, "%d link states coalesced\n", pending);
1450 	if (log_link_state_change)
1451 		log(LOG_NOTICE, "%s: link state changed to %s\n", ifp->if_xname,
1452 		    (link_state == LINK_STATE_UP) ? "UP" : "DOWN" );
1453 }
1454 
1455 /*
1456  * Mark an interface down and notify protocols of
1457  * the transition.
1458  * NOTE: must be called at splnet or eqivalent.
1459  */
1460 void
1461 if_down(struct ifnet *ifp)
1462 {
1463 
1464 	if_unroute(ifp, IFF_UP, AF_UNSPEC);
1465 }
1466 
1467 /*
1468  * Mark an interface up and notify protocols of
1469  * the transition.
1470  * NOTE: must be called at splnet or eqivalent.
1471  */
1472 void
1473 if_up(struct ifnet *ifp)
1474 {
1475 
1476 	if_route(ifp, IFF_UP, AF_UNSPEC);
1477 }
1478 
1479 /*
1480  * Flush an interface queue.
1481  */
1482 static void
1483 if_qflush(struct ifaltq *ifq)
1484 {
1485 	struct mbuf *m, *n;
1486 
1487 	IFQ_LOCK(ifq);
1488 #ifdef ALTQ
1489 	if (ALTQ_IS_ENABLED(ifq))
1490 		ALTQ_PURGE(ifq);
1491 #endif
1492 	n = ifq->ifq_head;
1493 	while ((m = n) != 0) {
1494 		n = m->m_act;
1495 		m_freem(m);
1496 	}
1497 	ifq->ifq_head = 0;
1498 	ifq->ifq_tail = 0;
1499 	ifq->ifq_len = 0;
1500 	IFQ_UNLOCK(ifq);
1501 }
1502 
1503 /*
1504  * Handle interface watchdog timer routines.  Called
1505  * from softclock, we decrement timers (if set) and
1506  * call the appropriate interface routine on expiration.
1507  *
1508  * XXXRW: Note that because timeouts run with Giant, if_watchdog() is called
1509  * holding Giant.  If we switch to an MPSAFE callout, we likely need to grab
1510  * Giant before entering if_watchdog() on an IFF_NEEDSGIANT interface.
1511  */
1512 static void
1513 if_slowtimo(void *arg)
1514 {
1515 	struct ifnet *ifp;
1516 	int s = splimp();
1517 
1518 	IFNET_RLOCK();
1519 	TAILQ_FOREACH(ifp, &ifnet, if_link) {
1520 		if (ifp->if_timer == 0 || --ifp->if_timer)
1521 			continue;
1522 		if (ifp->if_watchdog)
1523 			(*ifp->if_watchdog)(ifp);
1524 	}
1525 	IFNET_RUNLOCK();
1526 	splx(s);
1527 	timeout(if_slowtimo, (void *)0, hz / IFNET_SLOWHZ);
1528 }
1529 
1530 /*
1531  * Map interface name to
1532  * interface structure pointer.
1533  */
1534 struct ifnet *
1535 ifunit(const char *name)
1536 {
1537 	struct ifnet *ifp;
1538 
1539 	IFNET_RLOCK();
1540 	TAILQ_FOREACH(ifp, &ifnet, if_link) {
1541 		if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0)
1542 			break;
1543 	}
1544 	IFNET_RUNLOCK();
1545 	return (ifp);
1546 }
1547 
1548 /*
1549  * Hardware specific interface ioctls.
1550  */
1551 static int
1552 ifhwioctl(u_long cmd, struct ifnet *ifp, caddr_t data, struct thread *td)
1553 {
1554 	struct ifreq *ifr;
1555 	struct ifstat *ifs;
1556 	int error = 0;
1557 	int new_flags, temp_flags;
1558 	size_t namelen, onamelen;
1559 	char new_name[IFNAMSIZ];
1560 	struct ifaddr *ifa;
1561 	struct sockaddr_dl *sdl;
1562 
1563 	ifr = (struct ifreq *)data;
1564 	switch (cmd) {
1565 	case SIOCGIFINDEX:
1566 		ifr->ifr_index = ifp->if_index;
1567 		break;
1568 
1569 	case SIOCGIFFLAGS:
1570 		temp_flags = ifp->if_flags | ifp->if_drv_flags;
1571 		ifr->ifr_flags = temp_flags & 0xffff;
1572 		ifr->ifr_flagshigh = temp_flags >> 16;
1573 		break;
1574 
1575 	case SIOCGIFCAP:
1576 		ifr->ifr_reqcap = ifp->if_capabilities;
1577 		ifr->ifr_curcap = ifp->if_capenable;
1578 		break;
1579 
1580 #ifdef MAC
1581 	case SIOCGIFMAC:
1582 		error = mac_ifnet_ioctl_get(td->td_ucred, ifr, ifp);
1583 		break;
1584 #endif
1585 
1586 	case SIOCGIFMETRIC:
1587 		ifr->ifr_metric = ifp->if_metric;
1588 		break;
1589 
1590 	case SIOCGIFMTU:
1591 		ifr->ifr_mtu = ifp->if_mtu;
1592 		break;
1593 
1594 	case SIOCGIFPHYS:
1595 		ifr->ifr_phys = ifp->if_physical;
1596 		break;
1597 
1598 	case SIOCSIFFLAGS:
1599 		error = priv_check(td, PRIV_NET_SETIFFLAGS);
1600 		if (error)
1601 			return (error);
1602 		/*
1603 		 * Currently, no driver owned flags pass the IFF_CANTCHANGE
1604 		 * check, so we don't need special handling here yet.
1605 		 */
1606 		new_flags = (ifr->ifr_flags & 0xffff) |
1607 		    (ifr->ifr_flagshigh << 16);
1608 		if (ifp->if_flags & IFF_SMART) {
1609 			/* Smart drivers twiddle their own routes */
1610 		} else if (ifp->if_flags & IFF_UP &&
1611 		    (new_flags & IFF_UP) == 0) {
1612 			int s = splimp();
1613 			if_down(ifp);
1614 			splx(s);
1615 		} else if (new_flags & IFF_UP &&
1616 		    (ifp->if_flags & IFF_UP) == 0) {
1617 			int s = splimp();
1618 			if_up(ifp);
1619 			splx(s);
1620 		}
1621 		/* See if permanently promiscuous mode bit is about to flip */
1622 		if ((ifp->if_flags ^ new_flags) & IFF_PPROMISC) {
1623 			if (new_flags & IFF_PPROMISC)
1624 				ifp->if_flags |= IFF_PROMISC;
1625 			else if (ifp->if_pcount == 0)
1626 				ifp->if_flags &= ~IFF_PROMISC;
1627 			log(LOG_INFO, "%s: permanently promiscuous mode %s\n",
1628 			    ifp->if_xname,
1629 			    (new_flags & IFF_PPROMISC) ? "enabled" : "disabled");
1630 		}
1631 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
1632 			(new_flags &~ IFF_CANTCHANGE);
1633 		if (ifp->if_ioctl) {
1634 			IFF_LOCKGIANT(ifp);
1635 			(void) (*ifp->if_ioctl)(ifp, cmd, data);
1636 			IFF_UNLOCKGIANT(ifp);
1637 		}
1638 		getmicrotime(&ifp->if_lastchange);
1639 		break;
1640 
1641 	case SIOCSIFCAP:
1642 		error = priv_check(td, PRIV_NET_SETIFCAP);
1643 		if (error)
1644 			return (error);
1645 		if (ifp->if_ioctl == NULL)
1646 			return (EOPNOTSUPP);
1647 		if (ifr->ifr_reqcap & ~ifp->if_capabilities)
1648 			return (EINVAL);
1649 		IFF_LOCKGIANT(ifp);
1650 		error = (*ifp->if_ioctl)(ifp, cmd, data);
1651 		IFF_UNLOCKGIANT(ifp);
1652 		if (error == 0)
1653 			getmicrotime(&ifp->if_lastchange);
1654 		break;
1655 
1656 #ifdef MAC
1657 	case SIOCSIFMAC:
1658 		error = mac_ifnet_ioctl_set(td->td_ucred, ifr, ifp);
1659 		break;
1660 #endif
1661 
1662 	case SIOCSIFNAME:
1663 		error = priv_check(td, PRIV_NET_SETIFNAME);
1664 		if (error)
1665 			return (error);
1666 		error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
1667 		if (error != 0)
1668 			return (error);
1669 		if (new_name[0] == '\0')
1670 			return (EINVAL);
1671 		if (ifunit(new_name) != NULL)
1672 			return (EEXIST);
1673 
1674 		/* Announce the departure of the interface. */
1675 		rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1676 		EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
1677 
1678 		log(LOG_INFO, "%s: changing name to '%s'\n",
1679 		    ifp->if_xname, new_name);
1680 
1681 		strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
1682 		ifa = ifp->if_addr;
1683 		IFA_LOCK(ifa);
1684 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1685 		namelen = strlen(new_name);
1686 		onamelen = sdl->sdl_nlen;
1687 		/*
1688 		 * Move the address if needed.  This is safe because we
1689 		 * allocate space for a name of length IFNAMSIZ when we
1690 		 * create this in if_attach().
1691 		 */
1692 		if (namelen != onamelen) {
1693 			bcopy(sdl->sdl_data + onamelen,
1694 			    sdl->sdl_data + namelen, sdl->sdl_alen);
1695 		}
1696 		bcopy(new_name, sdl->sdl_data, namelen);
1697 		sdl->sdl_nlen = namelen;
1698 		sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
1699 		bzero(sdl->sdl_data, onamelen);
1700 		while (namelen != 0)
1701 			sdl->sdl_data[--namelen] = 0xff;
1702 		IFA_UNLOCK(ifa);
1703 
1704 		EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
1705 		/* Announce the return of the interface. */
1706 		rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
1707 		break;
1708 
1709 	case SIOCSIFMETRIC:
1710 		error = priv_check(td, PRIV_NET_SETIFMETRIC);
1711 		if (error)
1712 			return (error);
1713 		ifp->if_metric = ifr->ifr_metric;
1714 		getmicrotime(&ifp->if_lastchange);
1715 		break;
1716 
1717 	case SIOCSIFPHYS:
1718 		error = priv_check(td, PRIV_NET_SETIFPHYS);
1719 		if (error)
1720 			return (error);
1721 		if (ifp->if_ioctl == NULL)
1722 			return (EOPNOTSUPP);
1723 		IFF_LOCKGIANT(ifp);
1724 		error = (*ifp->if_ioctl)(ifp, cmd, data);
1725 		IFF_UNLOCKGIANT(ifp);
1726 		if (error == 0)
1727 			getmicrotime(&ifp->if_lastchange);
1728 		break;
1729 
1730 	case SIOCSIFMTU:
1731 	{
1732 		u_long oldmtu = ifp->if_mtu;
1733 
1734 		error = priv_check(td, PRIV_NET_SETIFMTU);
1735 		if (error)
1736 			return (error);
1737 		if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
1738 			return (EINVAL);
1739 		if (ifp->if_ioctl == NULL)
1740 			return (EOPNOTSUPP);
1741 		IFF_LOCKGIANT(ifp);
1742 		error = (*ifp->if_ioctl)(ifp, cmd, data);
1743 		IFF_UNLOCKGIANT(ifp);
1744 		if (error == 0) {
1745 			getmicrotime(&ifp->if_lastchange);
1746 			rt_ifmsg(ifp);
1747 		}
1748 		/*
1749 		 * If the link MTU changed, do network layer specific procedure.
1750 		 */
1751 		if (ifp->if_mtu != oldmtu) {
1752 #ifdef INET6
1753 			nd6_setmtu(ifp);
1754 #endif
1755 		}
1756 		break;
1757 	}
1758 
1759 	case SIOCADDMULTI:
1760 	case SIOCDELMULTI:
1761 		if (cmd == SIOCADDMULTI)
1762 			error = priv_check(td, PRIV_NET_ADDMULTI);
1763 		else
1764 			error = priv_check(td, PRIV_NET_DELMULTI);
1765 		if (error)
1766 			return (error);
1767 
1768 		/* Don't allow group membership on non-multicast interfaces. */
1769 		if ((ifp->if_flags & IFF_MULTICAST) == 0)
1770 			return (EOPNOTSUPP);
1771 
1772 		/* Don't let users screw up protocols' entries. */
1773 		if (ifr->ifr_addr.sa_family != AF_LINK)
1774 			return (EINVAL);
1775 
1776 		if (cmd == SIOCADDMULTI) {
1777 			struct ifmultiaddr *ifma;
1778 
1779 			/*
1780 			 * Userland is only permitted to join groups once
1781 			 * via the if_addmulti() KPI, because it cannot hold
1782 			 * struct ifmultiaddr * between calls. It may also
1783 			 * lose a race while we check if the membership
1784 			 * already exists.
1785 			 */
1786 			IF_ADDR_LOCK(ifp);
1787 			ifma = if_findmulti(ifp, &ifr->ifr_addr);
1788 			IF_ADDR_UNLOCK(ifp);
1789 			if (ifma != NULL)
1790 				error = EADDRINUSE;
1791 			else
1792 				error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
1793 		} else {
1794 			error = if_delmulti(ifp, &ifr->ifr_addr);
1795 		}
1796 		if (error == 0)
1797 			getmicrotime(&ifp->if_lastchange);
1798 		break;
1799 
1800 	case SIOCSIFPHYADDR:
1801 	case SIOCDIFPHYADDR:
1802 #ifdef INET6
1803 	case SIOCSIFPHYADDR_IN6:
1804 #endif
1805 	case SIOCSLIFPHYADDR:
1806 	case SIOCSIFMEDIA:
1807 	case SIOCSIFGENERIC:
1808 		error = priv_check(td, PRIV_NET_HWIOCTL);
1809 		if (error)
1810 			return (error);
1811 		if (ifp->if_ioctl == NULL)
1812 			return (EOPNOTSUPP);
1813 		IFF_LOCKGIANT(ifp);
1814 		error = (*ifp->if_ioctl)(ifp, cmd, data);
1815 		IFF_UNLOCKGIANT(ifp);
1816 		if (error == 0)
1817 			getmicrotime(&ifp->if_lastchange);
1818 		break;
1819 
1820 	case SIOCGIFSTATUS:
1821 		ifs = (struct ifstat *)data;
1822 		ifs->ascii[0] = '\0';
1823 
1824 	case SIOCGIFPSRCADDR:
1825 	case SIOCGIFPDSTADDR:
1826 	case SIOCGLIFPHYADDR:
1827 	case SIOCGIFMEDIA:
1828 	case SIOCGIFGENERIC:
1829 		if (ifp->if_ioctl == NULL)
1830 			return (EOPNOTSUPP);
1831 		IFF_LOCKGIANT(ifp);
1832 		error = (*ifp->if_ioctl)(ifp, cmd, data);
1833 		IFF_UNLOCKGIANT(ifp);
1834 		break;
1835 
1836 	case SIOCSIFLLADDR:
1837 		error = priv_check(td, PRIV_NET_SETLLADDR);
1838 		if (error)
1839 			return (error);
1840 		error = if_setlladdr(ifp,
1841 		    ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
1842 		break;
1843 
1844 	case SIOCAIFGROUP:
1845 	{
1846 		struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
1847 
1848 		error = priv_check(td, PRIV_NET_ADDIFGROUP);
1849 		if (error)
1850 			return (error);
1851 		if ((error = if_addgroup(ifp, ifgr->ifgr_group)))
1852 			return (error);
1853 		break;
1854 	}
1855 
1856 	case SIOCGIFGROUP:
1857 		if ((error = if_getgroup((struct ifgroupreq *)ifr, ifp)))
1858 			return (error);
1859 		break;
1860 
1861 	case SIOCDIFGROUP:
1862 	{
1863 		struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
1864 
1865 		error = priv_check(td, PRIV_NET_DELIFGROUP);
1866 		if (error)
1867 			return (error);
1868 		if ((error = if_delgroup(ifp, ifgr->ifgr_group)))
1869 			return (error);
1870 		break;
1871 	}
1872 
1873 	default:
1874 		error = ENOIOCTL;
1875 		break;
1876 	}
1877 	return (error);
1878 }
1879 
1880 /*
1881  * Interface ioctls.
1882  */
1883 int
1884 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct thread *td)
1885 {
1886 	struct ifnet *ifp;
1887 	struct ifreq *ifr;
1888 	int error;
1889 	int oif_flags;
1890 
1891 	switch (cmd) {
1892 	case SIOCGIFCONF:
1893 	case OSIOCGIFCONF:
1894 #ifdef __amd64__
1895 	case SIOCGIFCONF32:
1896 #endif
1897 		return (ifconf(cmd, data));
1898 	}
1899 	ifr = (struct ifreq *)data;
1900 
1901 	switch (cmd) {
1902 	case SIOCIFCREATE:
1903 	case SIOCIFCREATE2:
1904 		error = priv_check(td, PRIV_NET_IFCREATE);
1905 		if (error)
1906 			return (error);
1907 		return (if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name),
1908 			cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL));
1909 	case SIOCIFDESTROY:
1910 		error = priv_check(td, PRIV_NET_IFDESTROY);
1911 		if (error)
1912 			return (error);
1913 		return if_clone_destroy(ifr->ifr_name);
1914 
1915 	case SIOCIFGCLONERS:
1916 		return (if_clone_list((struct if_clonereq *)data));
1917 	case SIOCGIFGMEMB:
1918 		return (if_getgroupmembers((struct ifgroupreq *)data));
1919 	}
1920 
1921 	ifp = ifunit(ifr->ifr_name);
1922 	if (ifp == 0)
1923 		return (ENXIO);
1924 
1925 	error = ifhwioctl(cmd, ifp, data, td);
1926 	if (error != ENOIOCTL)
1927 		return (error);
1928 
1929 	oif_flags = ifp->if_flags;
1930 	if (so->so_proto == 0)
1931 		return (EOPNOTSUPP);
1932 #ifndef COMPAT_43
1933 	error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
1934 								 data,
1935 								 ifp, td));
1936 #else
1937 	{
1938 		int ocmd = cmd;
1939 
1940 		switch (cmd) {
1941 
1942 		case SIOCSIFDSTADDR:
1943 		case SIOCSIFADDR:
1944 		case SIOCSIFBRDADDR:
1945 		case SIOCSIFNETMASK:
1946 #if BYTE_ORDER != BIG_ENDIAN
1947 			if (ifr->ifr_addr.sa_family == 0 &&
1948 			    ifr->ifr_addr.sa_len < 16) {
1949 				ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
1950 				ifr->ifr_addr.sa_len = 16;
1951 			}
1952 #else
1953 			if (ifr->ifr_addr.sa_len == 0)
1954 				ifr->ifr_addr.sa_len = 16;
1955 #endif
1956 			break;
1957 
1958 		case OSIOCGIFADDR:
1959 			cmd = SIOCGIFADDR;
1960 			break;
1961 
1962 		case OSIOCGIFDSTADDR:
1963 			cmd = SIOCGIFDSTADDR;
1964 			break;
1965 
1966 		case OSIOCGIFBRDADDR:
1967 			cmd = SIOCGIFBRDADDR;
1968 			break;
1969 
1970 		case OSIOCGIFNETMASK:
1971 			cmd = SIOCGIFNETMASK;
1972 		}
1973 		error =  ((*so->so_proto->pr_usrreqs->pru_control)(so,
1974 								   cmd,
1975 								   data,
1976 								   ifp, td));
1977 		switch (ocmd) {
1978 
1979 		case OSIOCGIFADDR:
1980 		case OSIOCGIFDSTADDR:
1981 		case OSIOCGIFBRDADDR:
1982 		case OSIOCGIFNETMASK:
1983 			*(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
1984 
1985 		}
1986 	}
1987 #endif /* COMPAT_43 */
1988 
1989 	if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
1990 #ifdef INET6
1991 		DELAY(100);/* XXX: temporary workaround for fxp issue*/
1992 		if (ifp->if_flags & IFF_UP) {
1993 			int s = splimp();
1994 			in6_if_up(ifp);
1995 			splx(s);
1996 		}
1997 #endif
1998 	}
1999 	return (error);
2000 }
2001 
2002 /*
2003  * The code common to handling reference counted flags,
2004  * e.g., in ifpromisc() and if_allmulti().
2005  * The "pflag" argument can specify a permanent mode flag to check,
2006  * such as IFF_PPROMISC for promiscuous mode; should be 0 if none.
2007  *
2008  * Only to be used on stack-owned flags, not driver-owned flags.
2009  */
2010 static int
2011 if_setflag(struct ifnet *ifp, int flag, int pflag, int *refcount, int onswitch)
2012 {
2013 	struct ifreq ifr;
2014 	int error;
2015 	int oldflags, oldcount;
2016 
2017 	/* Sanity checks to catch programming errors */
2018 	KASSERT((flag & (IFF_DRV_OACTIVE|IFF_DRV_RUNNING)) == 0,
2019 	    ("%s: setting driver-owned flag %d", __func__, flag));
2020 
2021 	if (onswitch)
2022 		KASSERT(*refcount >= 0,
2023 		    ("%s: increment negative refcount %d for flag %d",
2024 		    __func__, *refcount, flag));
2025 	else
2026 		KASSERT(*refcount > 0,
2027 		    ("%s: decrement non-positive refcount %d for flag %d",
2028 		    __func__, *refcount, flag));
2029 
2030 	/* In case this mode is permanent, just touch refcount */
2031 	if (ifp->if_flags & pflag) {
2032 		*refcount += onswitch ? 1 : -1;
2033 		return (0);
2034 	}
2035 
2036 	/* Save ifnet parameters for if_ioctl() may fail */
2037 	oldcount = *refcount;
2038 	oldflags = ifp->if_flags;
2039 
2040 	/*
2041 	 * See if we aren't the only and touching refcount is enough.
2042 	 * Actually toggle interface flag if we are the first or last.
2043 	 */
2044 	if (onswitch) {
2045 		if ((*refcount)++)
2046 			return (0);
2047 		ifp->if_flags |= flag;
2048 	} else {
2049 		if (--(*refcount))
2050 			return (0);
2051 		ifp->if_flags &= ~flag;
2052 	}
2053 
2054 	/* Call down the driver since we've changed interface flags */
2055 	if (ifp->if_ioctl == NULL) {
2056 		error = EOPNOTSUPP;
2057 		goto recover;
2058 	}
2059 	ifr.ifr_flags = ifp->if_flags & 0xffff;
2060 	ifr.ifr_flagshigh = ifp->if_flags >> 16;
2061 	IFF_LOCKGIANT(ifp);
2062 	error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2063 	IFF_UNLOCKGIANT(ifp);
2064 	if (error)
2065 		goto recover;
2066 	/* Notify userland that interface flags have changed */
2067 	rt_ifmsg(ifp);
2068 	return (0);
2069 
2070 recover:
2071 	/* Recover after driver error */
2072 	*refcount = oldcount;
2073 	ifp->if_flags = oldflags;
2074 	return (error);
2075 }
2076 
2077 /*
2078  * Set/clear promiscuous mode on interface ifp based on the truth value
2079  * of pswitch.  The calls are reference counted so that only the first
2080  * "on" request actually has an effect, as does the final "off" request.
2081  * Results are undefined if the "off" and "on" requests are not matched.
2082  */
2083 int
2084 ifpromisc(struct ifnet *ifp, int pswitch)
2085 {
2086 	int error;
2087 	int oldflags = ifp->if_flags;
2088 
2089 	error = if_setflag(ifp, IFF_PROMISC, IFF_PPROMISC,
2090 			   &ifp->if_pcount, pswitch);
2091 	/* If promiscuous mode status has changed, log a message */
2092 	if (error == 0 && ((ifp->if_flags ^ oldflags) & IFF_PROMISC))
2093 		log(LOG_INFO, "%s: promiscuous mode %s\n",
2094 		    ifp->if_xname,
2095 		    (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
2096 	return (error);
2097 }
2098 
2099 /*
2100  * Return interface configuration
2101  * of system.  List may be used
2102  * in later ioctl's (above) to get
2103  * other information.
2104  */
2105 /*ARGSUSED*/
2106 static int
2107 ifconf(u_long cmd, caddr_t data)
2108 {
2109 	struct ifconf *ifc = (struct ifconf *)data;
2110 #ifdef __amd64__
2111 	struct ifconf32 *ifc32 = (struct ifconf32 *)data;
2112 	struct ifconf ifc_swab;
2113 #endif
2114 	struct ifnet *ifp;
2115 	struct ifaddr *ifa;
2116 	struct ifreq ifr;
2117 	struct sbuf *sb;
2118 	int error, full = 0, valid_len, max_len;
2119 
2120 #ifdef __amd64__
2121 	if (cmd == SIOCGIFCONF32) {
2122 		ifc_swab.ifc_len = ifc32->ifc_len;
2123 		ifc_swab.ifc_buf = (caddr_t)(uintptr_t)ifc32->ifc_buf;
2124 		ifc = &ifc_swab;
2125 	}
2126 #endif
2127 	/* Limit initial buffer size to MAXPHYS to avoid DoS from userspace. */
2128 	max_len = MAXPHYS - 1;
2129 
2130 	/* Prevent hostile input from being able to crash the system */
2131 	if (ifc->ifc_len <= 0)
2132 		return (EINVAL);
2133 
2134 again:
2135 	if (ifc->ifc_len <= max_len) {
2136 		max_len = ifc->ifc_len;
2137 		full = 1;
2138 	}
2139 	sb = sbuf_new(NULL, NULL, max_len + 1, SBUF_FIXEDLEN);
2140 	max_len = 0;
2141 	valid_len = 0;
2142 
2143 	IFNET_RLOCK();		/* could sleep XXX */
2144 	TAILQ_FOREACH(ifp, &ifnet, if_link) {
2145 		int addrs;
2146 
2147 		/*
2148 		 * Zero the ifr_name buffer to make sure we don't
2149 		 * disclose the contents of the stack.
2150 		 */
2151 		memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
2152 
2153 		if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
2154 		    >= sizeof(ifr.ifr_name)) {
2155 			sbuf_delete(sb);
2156 			IFNET_RUNLOCK();
2157 			return (ENAMETOOLONG);
2158 		}
2159 
2160 		addrs = 0;
2161 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2162 			struct sockaddr *sa = ifa->ifa_addr;
2163 
2164 			if (jailed(curthread->td_ucred) &&
2165 			    prison_if(curthread->td_ucred, sa))
2166 				continue;
2167 			addrs++;
2168 #ifdef COMPAT_43
2169 			if (cmd == OSIOCGIFCONF) {
2170 				struct osockaddr *osa =
2171 					 (struct osockaddr *)&ifr.ifr_addr;
2172 				ifr.ifr_addr = *sa;
2173 				osa->sa_family = sa->sa_family;
2174 				sbuf_bcat(sb, &ifr, sizeof(ifr));
2175 				max_len += sizeof(ifr);
2176 			} else
2177 #endif
2178 			if (sa->sa_len <= sizeof(*sa)) {
2179 				ifr.ifr_addr = *sa;
2180 				sbuf_bcat(sb, &ifr, sizeof(ifr));
2181 				max_len += sizeof(ifr);
2182 			} else {
2183 				sbuf_bcat(sb, &ifr,
2184 				    offsetof(struct ifreq, ifr_addr));
2185 				max_len += offsetof(struct ifreq, ifr_addr);
2186 				sbuf_bcat(sb, sa, sa->sa_len);
2187 				max_len += sa->sa_len;
2188 			}
2189 
2190 			if (!sbuf_overflowed(sb))
2191 				valid_len = sbuf_len(sb);
2192 		}
2193 		if (addrs == 0) {
2194 			bzero((caddr_t)&ifr.ifr_addr, sizeof(ifr.ifr_addr));
2195 			sbuf_bcat(sb, &ifr, sizeof(ifr));
2196 			max_len += sizeof(ifr);
2197 
2198 			if (!sbuf_overflowed(sb))
2199 				valid_len = sbuf_len(sb);
2200 		}
2201 	}
2202 	IFNET_RUNLOCK();
2203 
2204 	/*
2205 	 * If we didn't allocate enough space (uncommon), try again.  If
2206 	 * we have already allocated as much space as we are allowed,
2207 	 * return what we've got.
2208 	 */
2209 	if (valid_len != max_len && !full) {
2210 		sbuf_delete(sb);
2211 		goto again;
2212 	}
2213 
2214 	ifc->ifc_len = valid_len;
2215 #ifdef __amd64__
2216 	if (cmd == SIOCGIFCONF32)
2217 		ifc32->ifc_len = valid_len;
2218 #endif
2219 	sbuf_finish(sb);
2220 	error = copyout(sbuf_data(sb), ifc->ifc_req, ifc->ifc_len);
2221 	sbuf_delete(sb);
2222 	return (error);
2223 }
2224 
2225 /*
2226  * Just like ifpromisc(), but for all-multicast-reception mode.
2227  */
2228 int
2229 if_allmulti(struct ifnet *ifp, int onswitch)
2230 {
2231 
2232 	return (if_setflag(ifp, IFF_ALLMULTI, 0, &ifp->if_amcount, onswitch));
2233 }
2234 
2235 struct ifmultiaddr *
2236 if_findmulti(struct ifnet *ifp, struct sockaddr *sa)
2237 {
2238 	struct ifmultiaddr *ifma;
2239 
2240 	IF_ADDR_LOCK_ASSERT(ifp);
2241 
2242 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2243 		if (sa->sa_family == AF_LINK) {
2244 			if (sa_dl_equal(ifma->ifma_addr, sa))
2245 				break;
2246 		} else {
2247 			if (sa_equal(ifma->ifma_addr, sa))
2248 				break;
2249 		}
2250 	}
2251 
2252 	return ifma;
2253 }
2254 
2255 /*
2256  * Allocate a new ifmultiaddr and initialize based on passed arguments.  We
2257  * make copies of passed sockaddrs.  The ifmultiaddr will not be added to
2258  * the ifnet multicast address list here, so the caller must do that and
2259  * other setup work (such as notifying the device driver).  The reference
2260  * count is initialized to 1.
2261  */
2262 static struct ifmultiaddr *
2263 if_allocmulti(struct ifnet *ifp, struct sockaddr *sa, struct sockaddr *llsa,
2264     int mflags)
2265 {
2266 	struct ifmultiaddr *ifma;
2267 	struct sockaddr *dupsa;
2268 
2269 	MALLOC(ifma, struct ifmultiaddr *, sizeof *ifma, M_IFMADDR, mflags |
2270 	    M_ZERO);
2271 	if (ifma == NULL)
2272 		return (NULL);
2273 
2274 	MALLOC(dupsa, struct sockaddr *, sa->sa_len, M_IFMADDR, mflags);
2275 	if (dupsa == NULL) {
2276 		FREE(ifma, M_IFMADDR);
2277 		return (NULL);
2278 	}
2279 	bcopy(sa, dupsa, sa->sa_len);
2280 	ifma->ifma_addr = dupsa;
2281 
2282 	ifma->ifma_ifp = ifp;
2283 	ifma->ifma_refcount = 1;
2284 	ifma->ifma_protospec = NULL;
2285 
2286 	if (llsa == NULL) {
2287 		ifma->ifma_lladdr = NULL;
2288 		return (ifma);
2289 	}
2290 
2291 	MALLOC(dupsa, struct sockaddr *, llsa->sa_len, M_IFMADDR, mflags);
2292 	if (dupsa == NULL) {
2293 		FREE(ifma->ifma_addr, M_IFMADDR);
2294 		FREE(ifma, M_IFMADDR);
2295 		return (NULL);
2296 	}
2297 	bcopy(llsa, dupsa, llsa->sa_len);
2298 	ifma->ifma_lladdr = dupsa;
2299 
2300 	return (ifma);
2301 }
2302 
2303 /*
2304  * if_freemulti: free ifmultiaddr structure and possibly attached related
2305  * addresses.  The caller is responsible for implementing reference
2306  * counting, notifying the driver, handling routing messages, and releasing
2307  * any dependent link layer state.
2308  */
2309 static void
2310 if_freemulti(struct ifmultiaddr *ifma)
2311 {
2312 
2313 	KASSERT(ifma->ifma_refcount == 0, ("if_freemulti: refcount %d",
2314 	    ifma->ifma_refcount));
2315 	KASSERT(ifma->ifma_protospec == NULL,
2316 	    ("if_freemulti: protospec not NULL"));
2317 
2318 	if (ifma->ifma_lladdr != NULL)
2319 		FREE(ifma->ifma_lladdr, M_IFMADDR);
2320 	FREE(ifma->ifma_addr, M_IFMADDR);
2321 	FREE(ifma, M_IFMADDR);
2322 }
2323 
2324 /*
2325  * Register an additional multicast address with a network interface.
2326  *
2327  * - If the address is already present, bump the reference count on the
2328  *   address and return.
2329  * - If the address is not link-layer, look up a link layer address.
2330  * - Allocate address structures for one or both addresses, and attach to the
2331  *   multicast address list on the interface.  If automatically adding a link
2332  *   layer address, the protocol address will own a reference to the link
2333  *   layer address, to be freed when it is freed.
2334  * - Notify the network device driver of an addition to the multicast address
2335  *   list.
2336  *
2337  * 'sa' points to caller-owned memory with the desired multicast address.
2338  *
2339  * 'retifma' will be used to return a pointer to the resulting multicast
2340  * address reference, if desired.
2341  */
2342 int
2343 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
2344     struct ifmultiaddr **retifma)
2345 {
2346 	struct ifmultiaddr *ifma, *ll_ifma;
2347 	struct sockaddr *llsa;
2348 	int error;
2349 
2350 	/*
2351 	 * If the address is already present, return a new reference to it;
2352 	 * otherwise, allocate storage and set up a new address.
2353 	 */
2354 	IF_ADDR_LOCK(ifp);
2355 	ifma = if_findmulti(ifp, sa);
2356 	if (ifma != NULL) {
2357 		ifma->ifma_refcount++;
2358 		if (retifma != NULL)
2359 			*retifma = ifma;
2360 		IF_ADDR_UNLOCK(ifp);
2361 		return (0);
2362 	}
2363 
2364 	/*
2365 	 * The address isn't already present; resolve the protocol address
2366 	 * into a link layer address, and then look that up, bump its
2367 	 * refcount or allocate an ifma for that also.  If 'llsa' was
2368 	 * returned, we will need to free it later.
2369 	 */
2370 	llsa = NULL;
2371 	ll_ifma = NULL;
2372 	if (ifp->if_resolvemulti != NULL) {
2373 		error = ifp->if_resolvemulti(ifp, &llsa, sa);
2374 		if (error)
2375 			goto unlock_out;
2376 	}
2377 
2378 	/*
2379 	 * Allocate the new address.  Don't hook it up yet, as we may also
2380 	 * need to allocate a link layer multicast address.
2381 	 */
2382 	ifma = if_allocmulti(ifp, sa, llsa, M_NOWAIT);
2383 	if (ifma == NULL) {
2384 		error = ENOMEM;
2385 		goto free_llsa_out;
2386 	}
2387 
2388 	/*
2389 	 * If a link layer address is found, we'll need to see if it's
2390 	 * already present in the address list, or allocate is as well.
2391 	 * When this block finishes, the link layer address will be on the
2392 	 * list.
2393 	 */
2394 	if (llsa != NULL) {
2395 		ll_ifma = if_findmulti(ifp, llsa);
2396 		if (ll_ifma == NULL) {
2397 			ll_ifma = if_allocmulti(ifp, llsa, NULL, M_NOWAIT);
2398 			if (ll_ifma == NULL) {
2399 				--ifma->ifma_refcount;
2400 				if_freemulti(ifma);
2401 				error = ENOMEM;
2402 				goto free_llsa_out;
2403 			}
2404 			TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ll_ifma,
2405 			    ifma_link);
2406 		} else
2407 			ll_ifma->ifma_refcount++;
2408 		ifma->ifma_llifma = ll_ifma;
2409 	}
2410 
2411 	/*
2412 	 * We now have a new multicast address, ifma, and possibly a new or
2413 	 * referenced link layer address.  Add the primary address to the
2414 	 * ifnet address list.
2415 	 */
2416 	TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2417 
2418 	if (retifma != NULL)
2419 		*retifma = ifma;
2420 
2421 	/*
2422 	 * Must generate the message while holding the lock so that 'ifma'
2423 	 * pointer is still valid.
2424 	 */
2425 	rt_newmaddrmsg(RTM_NEWMADDR, ifma);
2426 	IF_ADDR_UNLOCK(ifp);
2427 
2428 	/*
2429 	 * We are certain we have added something, so call down to the
2430 	 * interface to let them know about it.
2431 	 */
2432 	if (ifp->if_ioctl != NULL) {
2433 		IFF_LOCKGIANT(ifp);
2434 		(void) (*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
2435 		IFF_UNLOCKGIANT(ifp);
2436 	}
2437 
2438 	if (llsa != NULL)
2439 		FREE(llsa, M_IFMADDR);
2440 
2441 	return (0);
2442 
2443 free_llsa_out:
2444 	if (llsa != NULL)
2445 		FREE(llsa, M_IFMADDR);
2446 
2447 unlock_out:
2448 	IF_ADDR_UNLOCK(ifp);
2449 	return (error);
2450 }
2451 
2452 /*
2453  * Delete a multicast group membership by network-layer group address.
2454  *
2455  * Returns ENOENT if the entry could not be found. If ifp no longer
2456  * exists, results are undefined. This entry point should only be used
2457  * from subsystems which do appropriate locking to hold ifp for the
2458  * duration of the call.
2459  * Network-layer protocol domains must use if_delmulti_ifma().
2460  */
2461 int
2462 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
2463 {
2464 	struct ifmultiaddr *ifma;
2465 	int lastref;
2466 #ifdef INVARIANTS
2467 	struct ifnet *oifp;
2468 
2469 	IFNET_RLOCK();
2470 	TAILQ_FOREACH(oifp, &ifnet, if_link)
2471 		if (ifp == oifp)
2472 			break;
2473 	if (ifp != oifp)
2474 		ifp = NULL;
2475 	IFNET_RUNLOCK();
2476 
2477 	KASSERT(ifp != NULL, ("%s: ifnet went away", __func__));
2478 #endif
2479 	if (ifp == NULL)
2480 		return (ENOENT);
2481 
2482 	IF_ADDR_LOCK(ifp);
2483 	lastref = 0;
2484 	ifma = if_findmulti(ifp, sa);
2485 	if (ifma != NULL)
2486 		lastref = if_delmulti_locked(ifp, ifma, 0);
2487 	IF_ADDR_UNLOCK(ifp);
2488 
2489 	if (ifma == NULL)
2490 		return (ENOENT);
2491 
2492 	if (lastref && ifp->if_ioctl != NULL) {
2493 		IFF_LOCKGIANT(ifp);
2494 		(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
2495 		IFF_UNLOCKGIANT(ifp);
2496 	}
2497 
2498 	return (0);
2499 }
2500 
2501 /*
2502  * Delete a multicast group membership by group membership pointer.
2503  * Network-layer protocol domains must use this routine.
2504  *
2505  * It is safe to call this routine if the ifp disappeared. Callers should
2506  * hold IFF_LOCKGIANT() to avoid a LOR in case the hardware needs to be
2507  * reconfigured.
2508  */
2509 void
2510 if_delmulti_ifma(struct ifmultiaddr *ifma)
2511 {
2512 	struct ifnet *ifp;
2513 	int lastref;
2514 
2515 	ifp = ifma->ifma_ifp;
2516 #ifdef DIAGNOSTIC
2517 	if (ifp == NULL) {
2518 		printf("%s: ifma_ifp seems to be detached\n", __func__);
2519 	} else {
2520 		struct ifnet *oifp;
2521 
2522 		IFNET_RLOCK();
2523 		TAILQ_FOREACH(oifp, &ifnet, if_link)
2524 			if (ifp == oifp)
2525 				break;
2526 		if (ifp != oifp) {
2527 			printf("%s: ifnet %p disappeared\n", __func__, ifp);
2528 			ifp = NULL;
2529 		}
2530 		IFNET_RUNLOCK();
2531 	}
2532 #endif
2533 	/*
2534 	 * If and only if the ifnet instance exists: Acquire the address lock.
2535 	 */
2536 	if (ifp != NULL)
2537 		IF_ADDR_LOCK(ifp);
2538 
2539 	lastref = if_delmulti_locked(ifp, ifma, 0);
2540 
2541 	if (ifp != NULL) {
2542 		/*
2543 		 * If and only if the ifnet instance exists:
2544 		 *  Release the address lock.
2545 		 *  If the group was left: update the hardware hash filter.
2546 		 */
2547 		IF_ADDR_UNLOCK(ifp);
2548 		if (lastref && ifp->if_ioctl != NULL) {
2549 			IFF_LOCKGIANT(ifp);
2550 			(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
2551 			IFF_UNLOCKGIANT(ifp);
2552 		}
2553 	}
2554 }
2555 
2556 /*
2557  * Perform deletion of network-layer and/or link-layer multicast address.
2558  *
2559  * Return 0 if the reference count was decremented.
2560  * Return 1 if the final reference was released, indicating that the
2561  * hardware hash filter should be reprogrammed.
2562  */
2563 static int
2564 if_delmulti_locked(struct ifnet *ifp, struct ifmultiaddr *ifma, int detaching)
2565 {
2566 	struct ifmultiaddr *ll_ifma;
2567 
2568 	if (ifp != NULL && ifma->ifma_ifp != NULL) {
2569 		KASSERT(ifma->ifma_ifp == ifp,
2570 		    ("%s: inconsistent ifp %p", __func__, ifp));
2571 		IF_ADDR_LOCK_ASSERT(ifp);
2572 	}
2573 
2574 	ifp = ifma->ifma_ifp;
2575 
2576 	/*
2577 	 * If the ifnet is detaching, null out references to ifnet,
2578 	 * so that upper protocol layers will notice, and not attempt
2579 	 * to obtain locks for an ifnet which no longer exists. The
2580 	 * routing socket announcement must happen before the ifnet
2581 	 * instance is detached from the system.
2582 	 */
2583 	if (detaching) {
2584 #ifdef DIAGNOSTIC
2585 		printf("%s: detaching ifnet instance %p\n", __func__, ifp);
2586 #endif
2587 		/*
2588 		 * ifp may already be nulled out if we are being reentered
2589 		 * to delete the ll_ifma.
2590 		 */
2591 		if (ifp != NULL) {
2592 			rt_newmaddrmsg(RTM_DELMADDR, ifma);
2593 			ifma->ifma_ifp = NULL;
2594 		}
2595 	}
2596 
2597 	if (--ifma->ifma_refcount > 0)
2598 		return 0;
2599 
2600 	/*
2601 	 * If this ifma is a network-layer ifma, a link-layer ifma may
2602 	 * have been associated with it. Release it first if so.
2603 	 */
2604 	ll_ifma = ifma->ifma_llifma;
2605 	if (ll_ifma != NULL) {
2606 		KASSERT(ifma->ifma_lladdr != NULL,
2607 		    ("%s: llifma w/o lladdr", __func__));
2608 		if (detaching)
2609 			ll_ifma->ifma_ifp = NULL;	/* XXX */
2610 		if (--ll_ifma->ifma_refcount == 0) {
2611 			if (ifp != NULL) {
2612 				TAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma,
2613 				    ifma_link);
2614 			}
2615 			if_freemulti(ll_ifma);
2616 		}
2617 	}
2618 
2619 	if (ifp != NULL)
2620 		TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
2621 
2622 	if_freemulti(ifma);
2623 
2624 	/*
2625 	 * The last reference to this instance of struct ifmultiaddr
2626 	 * was released; the hardware should be notified of this change.
2627 	 */
2628 	return 1;
2629 }
2630 
2631 /*
2632  * Set the link layer address on an interface.
2633  *
2634  * At this time we only support certain types of interfaces,
2635  * and we don't allow the length of the address to change.
2636  */
2637 int
2638 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
2639 {
2640 	struct sockaddr_dl *sdl;
2641 	struct ifaddr *ifa;
2642 	struct ifreq ifr;
2643 
2644 	ifa = ifp->if_addr;
2645 	if (ifa == NULL)
2646 		return (EINVAL);
2647 	sdl = (struct sockaddr_dl *)ifa->ifa_addr;
2648 	if (sdl == NULL)
2649 		return (EINVAL);
2650 	if (len != sdl->sdl_alen)	/* don't allow length to change */
2651 		return (EINVAL);
2652 	switch (ifp->if_type) {
2653 	case IFT_ETHER:
2654 	case IFT_FDDI:
2655 	case IFT_XETHER:
2656 	case IFT_ISO88025:
2657 	case IFT_L2VLAN:
2658 	case IFT_BRIDGE:
2659 	case IFT_ARCNET:
2660 	case IFT_IEEE8023ADLAG:
2661 		bcopy(lladdr, LLADDR(sdl), len);
2662 		break;
2663 	default:
2664 		return (ENODEV);
2665 	}
2666 	/*
2667 	 * If the interface is already up, we need
2668 	 * to re-init it in order to reprogram its
2669 	 * address filter.
2670 	 */
2671 	if ((ifp->if_flags & IFF_UP) != 0) {
2672 		if (ifp->if_ioctl) {
2673 			IFF_LOCKGIANT(ifp);
2674 			ifp->if_flags &= ~IFF_UP;
2675 			ifr.ifr_flags = ifp->if_flags & 0xffff;
2676 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
2677 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2678 			ifp->if_flags |= IFF_UP;
2679 			ifr.ifr_flags = ifp->if_flags & 0xffff;
2680 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
2681 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2682 			IFF_UNLOCKGIANT(ifp);
2683 		}
2684 #ifdef INET
2685 		/*
2686 		 * Also send gratuitous ARPs to notify other nodes about
2687 		 * the address change.
2688 		 */
2689 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2690 			if (ifa->ifa_addr->sa_family == AF_INET)
2691 				arp_ifinit(ifp, ifa);
2692 		}
2693 #endif
2694 	}
2695 	return (0);
2696 }
2697 
2698 /*
2699  * The name argument must be a pointer to storage which will last as
2700  * long as the interface does.  For physical devices, the result of
2701  * device_get_name(dev) is a good choice and for pseudo-devices a
2702  * static string works well.
2703  */
2704 void
2705 if_initname(struct ifnet *ifp, const char *name, int unit)
2706 {
2707 	ifp->if_dname = name;
2708 	ifp->if_dunit = unit;
2709 	if (unit != IF_DUNIT_NONE)
2710 		snprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
2711 	else
2712 		strlcpy(ifp->if_xname, name, IFNAMSIZ);
2713 }
2714 
2715 int
2716 if_printf(struct ifnet *ifp, const char * fmt, ...)
2717 {
2718 	va_list ap;
2719 	int retval;
2720 
2721 	retval = printf("%s: ", ifp->if_xname);
2722 	va_start(ap, fmt);
2723 	retval += vprintf(fmt, ap);
2724 	va_end(ap);
2725 	return (retval);
2726 }
2727 
2728 /*
2729  * When an interface is marked IFF_NEEDSGIANT, its if_start() routine cannot
2730  * be called without Giant.  However, we often can't acquire the Giant lock
2731  * at those points; instead, we run it via a task queue that holds Giant via
2732  * if_start_deferred.
2733  *
2734  * XXXRW: We need to make sure that the ifnet isn't fully detached until any
2735  * outstanding if_start_deferred() tasks that will run after the free.  This
2736  * probably means waiting in if_detach().
2737  */
2738 void
2739 if_start(struct ifnet *ifp)
2740 {
2741 
2742 	if (ifp->if_flags & IFF_NEEDSGIANT) {
2743 		if (mtx_owned(&Giant))
2744 			(*(ifp)->if_start)(ifp);
2745 		else
2746 			taskqueue_enqueue(taskqueue_swi_giant,
2747 			    &ifp->if_starttask);
2748 	} else
2749 		(*(ifp)->if_start)(ifp);
2750 }
2751 
2752 static void
2753 if_start_deferred(void *context, int pending)
2754 {
2755 	struct ifnet *ifp;
2756 
2757 	GIANT_REQUIRED;
2758 
2759 	ifp = context;
2760 	(ifp->if_start)(ifp);
2761 }
2762 
2763 int
2764 if_handoff(struct ifqueue *ifq, struct mbuf *m, struct ifnet *ifp, int adjust)
2765 {
2766 	int active = 0;
2767 
2768 	IF_LOCK(ifq);
2769 	if (_IF_QFULL(ifq)) {
2770 		_IF_DROP(ifq);
2771 		IF_UNLOCK(ifq);
2772 		m_freem(m);
2773 		return (0);
2774 	}
2775 	if (ifp != NULL) {
2776 		ifp->if_obytes += m->m_pkthdr.len + adjust;
2777 		if (m->m_flags & (M_BCAST|M_MCAST))
2778 			ifp->if_omcasts++;
2779 		active = ifp->if_drv_flags & IFF_DRV_OACTIVE;
2780 	}
2781 	_IF_ENQUEUE(ifq, m);
2782 	IF_UNLOCK(ifq);
2783 	if (ifp != NULL && !active)
2784 		if_start(ifp);
2785 	return (1);
2786 }
2787 
2788 void
2789 if_register_com_alloc(u_char type,
2790     if_com_alloc_t *a, if_com_free_t *f)
2791 {
2792 
2793 	KASSERT(if_com_alloc[type] == NULL,
2794 	    ("if_register_com_alloc: %d already registered", type));
2795 	KASSERT(if_com_free[type] == NULL,
2796 	    ("if_register_com_alloc: %d free already registered", type));
2797 
2798 	if_com_alloc[type] = a;
2799 	if_com_free[type] = f;
2800 }
2801 
2802 void
2803 if_deregister_com_alloc(u_char type)
2804 {
2805 
2806 	KASSERT(if_com_alloc[type] != NULL,
2807 	    ("if_deregister_com_alloc: %d not registered", type));
2808 	KASSERT(if_com_free[type] != NULL,
2809 	    ("if_deregister_com_alloc: %d free not registered", type));
2810 	if_com_alloc[type] = NULL;
2811 	if_com_free[type] = NULL;
2812 }
2813