xref: /freebsd/sys/net/if.c (revision 5a0bba9007c527b18db7f9b64f06b486cda4fe9d)
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 
37 #include <sys/param.h>
38 #include <sys/types.h>
39 #include <sys/conf.h>
40 #include <sys/malloc.h>
41 #include <sys/sbuf.h>
42 #include <sys/bus.h>
43 #include <sys/mbuf.h>
44 #include <sys/systm.h>
45 #include <sys/priv.h>
46 #include <sys/proc.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/protosw.h>
50 #include <sys/kernel.h>
51 #include <sys/lock.h>
52 #include <sys/refcount.h>
53 #include <sys/module.h>
54 #include <sys/rwlock.h>
55 #include <sys/sockio.h>
56 #include <sys/syslog.h>
57 #include <sys/sysctl.h>
58 #include <sys/taskqueue.h>
59 #include <sys/domain.h>
60 #include <sys/jail.h>
61 #include <machine/stdarg.h>
62 #include <vm/uma.h>
63 
64 #include <net/if.h>
65 #include <net/if_arp.h>
66 #include <net/if_clone.h>
67 #include <net/if_dl.h>
68 #include <net/if_types.h>
69 #include <net/if_var.h>
70 #include <net/radix.h>
71 #include <net/route.h>
72 #include <net/vnet.h>
73 
74 #if defined(INET) || defined(INET6)
75 /*XXX*/
76 #include <netinet/in.h>
77 #include <netinet/in_var.h>
78 #include <netinet/ip_carp.h>
79 #ifdef INET6
80 #include <netinet6/in6_var.h>
81 #include <netinet6/in6_ifattach.h>
82 #endif
83 #endif
84 #ifdef INET
85 #include <netinet/if_ether.h>
86 #endif
87 
88 #include <security/mac/mac_framework.h>
89 
90 #ifdef COMPAT_FREEBSD32
91 #include <sys/mount.h>
92 #include <compat/freebsd32/freebsd32.h>
93 #endif
94 
95 struct ifindex_entry {
96 	struct  ifnet *ife_ifnet;
97 };
98 
99 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
100 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
101 
102 TUNABLE_INT("net.link.ifqmaxlen", &ifqmaxlen);
103 SYSCTL_INT(_net_link, OID_AUTO, ifqmaxlen, CTLFLAG_RDTUN,
104     &ifqmaxlen, 0, "max send queue size");
105 
106 /* Log link state change events */
107 static int log_link_state_change = 1;
108 
109 SYSCTL_INT(_net_link, OID_AUTO, log_link_state_change, CTLFLAG_RW,
110 	&log_link_state_change, 0,
111 	"log interface link state change events");
112 
113 /* Interface description */
114 static unsigned int ifdescr_maxlen = 1024;
115 SYSCTL_UINT(_net, OID_AUTO, ifdescr_maxlen, CTLFLAG_RW,
116 	&ifdescr_maxlen, 0,
117 	"administrative maximum length for interface description");
118 
119 MALLOC_DEFINE(M_IFDESCR, "ifdescr", "ifnet descriptions");
120 
121 /* global sx for non-critical path ifdescr */
122 static struct sx ifdescr_sx;
123 SX_SYSINIT(ifdescr_sx, &ifdescr_sx, "ifnet descr");
124 
125 void	(*bstp_linkstate_p)(struct ifnet *ifp, int state);
126 void	(*ng_ether_link_state_p)(struct ifnet *ifp, int state);
127 void	(*lagg_linkstate_p)(struct ifnet *ifp, int state);
128 /* These are external hooks for CARP. */
129 void	(*carp_linkstate_p)(struct ifnet *ifp);
130 #if defined(INET) || defined(INET6)
131 struct ifnet *(*carp_forus_p)(struct ifnet *ifp, u_char *dhost);
132 int	(*carp_output_p)(struct ifnet *ifp, struct mbuf *m,
133     struct sockaddr *sa, struct rtentry *rt);
134 #endif
135 #ifdef INET
136 int (*carp_iamatch_p)(struct ifnet *, struct in_ifaddr *, struct in_addr *,
137     u_int8_t **);
138 #endif
139 #ifdef INET6
140 struct ifaddr *(*carp_iamatch6_p)(struct ifnet *ifp, struct in6_addr *taddr6);
141 caddr_t (*carp_macmatch6_p)(struct ifnet *ifp, struct mbuf *m,
142     const struct in6_addr *taddr);
143 #endif
144 
145 struct mbuf *(*tbr_dequeue_ptr)(struct ifaltq *, int) = NULL;
146 
147 /*
148  * XXX: Style; these should be sorted alphabetically, and unprototyped
149  * static functions should be prototyped. Currently they are sorted by
150  * declaration order.
151  */
152 static void	if_attachdomain(void *);
153 static void	if_attachdomain1(struct ifnet *);
154 static int	ifconf(u_long, caddr_t);
155 static void	if_freemulti(struct ifmultiaddr *);
156 static void	if_init(void *);
157 static void	if_grow(void);
158 static void	if_route(struct ifnet *, int flag, int fam);
159 static int	if_setflag(struct ifnet *, int, int, int *, int);
160 static int	if_transmit(struct ifnet *ifp, struct mbuf *m);
161 static void	if_unroute(struct ifnet *, int flag, int fam);
162 static void	link_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
163 static int	if_rtdel(struct radix_node *, void *);
164 static int	ifhwioctl(u_long, struct ifnet *, caddr_t, struct thread *);
165 static int	if_delmulti_locked(struct ifnet *, struct ifmultiaddr *, int);
166 static void	do_link_state_change(void *, int);
167 static int	if_getgroup(struct ifgroupreq *, struct ifnet *);
168 static int	if_getgroupmembers(struct ifgroupreq *);
169 static void	if_delgroups(struct ifnet *);
170 static void	if_attach_internal(struct ifnet *, int);
171 static void	if_detach_internal(struct ifnet *, int);
172 
173 #ifdef INET6
174 /*
175  * XXX: declare here to avoid to include many inet6 related files..
176  * should be more generalized?
177  */
178 extern void	nd6_setmtu(struct ifnet *);
179 #endif
180 
181 VNET_DEFINE(int, if_index);
182 int	ifqmaxlen = IFQ_MAXLEN;
183 VNET_DEFINE(struct ifnethead, ifnet);	/* depend on static init XXX */
184 VNET_DEFINE(struct ifgrouphead, ifg_head);
185 
186 static VNET_DEFINE(int, if_indexlim) = 8;
187 
188 /* Table of ifnet by index. */
189 VNET_DEFINE(struct ifindex_entry *, ifindex_table);
190 
191 #define	V_if_indexlim		VNET(if_indexlim)
192 #define	V_ifindex_table		VNET(ifindex_table)
193 
194 /*
195  * The global network interface list (V_ifnet) and related state (such as
196  * if_index, if_indexlim, and ifindex_table) are protected by an sxlock and
197  * an rwlock.  Either may be acquired shared to stablize the list, but both
198  * must be acquired writable to modify the list.  This model allows us to
199  * both stablize the interface list during interrupt thread processing, but
200  * also to stablize it over long-running ioctls, without introducing priority
201  * inversions and deadlocks.
202  */
203 struct rwlock ifnet_rwlock;
204 struct sx ifnet_sxlock;
205 
206 /*
207  * The allocation of network interfaces is a rather non-atomic affair; we
208  * need to select an index before we are ready to expose the interface for
209  * use, so will use this pointer value to indicate reservation.
210  */
211 #define	IFNET_HOLD	(void *)(uintptr_t)(-1)
212 
213 static	if_com_alloc_t *if_com_alloc[256];
214 static	if_com_free_t *if_com_free[256];
215 
216 MALLOC_DEFINE(M_IFNET, "ifnet", "interface internals");
217 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
218 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
219 
220 struct ifnet *
221 ifnet_byindex_locked(u_short idx)
222 {
223 
224 	if (idx > V_if_index)
225 		return (NULL);
226 	if (V_ifindex_table[idx].ife_ifnet == IFNET_HOLD)
227 		return (NULL);
228 	return (V_ifindex_table[idx].ife_ifnet);
229 }
230 
231 struct ifnet *
232 ifnet_byindex(u_short idx)
233 {
234 	struct ifnet *ifp;
235 
236 	IFNET_RLOCK_NOSLEEP();
237 	ifp = ifnet_byindex_locked(idx);
238 	IFNET_RUNLOCK_NOSLEEP();
239 	return (ifp);
240 }
241 
242 struct ifnet *
243 ifnet_byindex_ref(u_short idx)
244 {
245 	struct ifnet *ifp;
246 
247 	IFNET_RLOCK_NOSLEEP();
248 	ifp = ifnet_byindex_locked(idx);
249 	if (ifp == NULL || (ifp->if_flags & IFF_DYING)) {
250 		IFNET_RUNLOCK_NOSLEEP();
251 		return (NULL);
252 	}
253 	if_ref(ifp);
254 	IFNET_RUNLOCK_NOSLEEP();
255 	return (ifp);
256 }
257 
258 /*
259  * Allocate an ifindex array entry; return 0 on success or an error on
260  * failure.
261  */
262 static int
263 ifindex_alloc_locked(u_short *idxp)
264 {
265 	u_short idx;
266 
267 	IFNET_WLOCK_ASSERT();
268 
269 retry:
270 	/*
271 	 * Try to find an empty slot below V_if_index.  If we fail, take the
272 	 * next slot.
273 	 */
274 	for (idx = 1; idx <= V_if_index; idx++) {
275 		if (V_ifindex_table[idx].ife_ifnet == NULL)
276 			break;
277 	}
278 
279 	/* Catch if_index overflow. */
280 	if (idx < 1)
281 		return (ENOSPC);
282 	if (idx >= V_if_indexlim) {
283 		if_grow();
284 		goto retry;
285 	}
286 	if (idx > V_if_index)
287 		V_if_index = idx;
288 	*idxp = idx;
289 	return (0);
290 }
291 
292 static void
293 ifindex_free_locked(u_short idx)
294 {
295 
296 	IFNET_WLOCK_ASSERT();
297 
298 	V_ifindex_table[idx].ife_ifnet = NULL;
299 	while (V_if_index > 0 &&
300 	    V_ifindex_table[V_if_index].ife_ifnet == NULL)
301 		V_if_index--;
302 }
303 
304 static void
305 ifindex_free(u_short idx)
306 {
307 
308 	IFNET_WLOCK();
309 	ifindex_free_locked(idx);
310 	IFNET_WUNLOCK();
311 }
312 
313 static void
314 ifnet_setbyindex_locked(u_short idx, struct ifnet *ifp)
315 {
316 
317 	IFNET_WLOCK_ASSERT();
318 
319 	V_ifindex_table[idx].ife_ifnet = ifp;
320 }
321 
322 static void
323 ifnet_setbyindex(u_short idx, struct ifnet *ifp)
324 {
325 
326 	IFNET_WLOCK();
327 	ifnet_setbyindex_locked(idx, ifp);
328 	IFNET_WUNLOCK();
329 }
330 
331 struct ifaddr *
332 ifaddr_byindex(u_short idx)
333 {
334 	struct ifaddr *ifa;
335 
336 	IFNET_RLOCK_NOSLEEP();
337 	ifa = ifnet_byindex_locked(idx)->if_addr;
338 	if (ifa != NULL)
339 		ifa_ref(ifa);
340 	IFNET_RUNLOCK_NOSLEEP();
341 	return (ifa);
342 }
343 
344 /*
345  * Network interface utility routines.
346  *
347  * Routines with ifa_ifwith* names take sockaddr *'s as
348  * parameters.
349  */
350 
351 static void
352 vnet_if_init(const void *unused __unused)
353 {
354 
355 	TAILQ_INIT(&V_ifnet);
356 	TAILQ_INIT(&V_ifg_head);
357 	IFNET_WLOCK();
358 	if_grow();				/* create initial table */
359 	IFNET_WUNLOCK();
360 	vnet_if_clone_init();
361 }
362 VNET_SYSINIT(vnet_if_init, SI_SUB_INIT_IF, SI_ORDER_SECOND, vnet_if_init,
363     NULL);
364 
365 /* ARGSUSED*/
366 static void
367 if_init(void *dummy __unused)
368 {
369 
370 	IFNET_LOCK_INIT();
371 	if_clone_init();
372 }
373 SYSINIT(interfaces, SI_SUB_INIT_IF, SI_ORDER_FIRST, if_init, NULL);
374 
375 
376 #ifdef VIMAGE
377 static void
378 vnet_if_uninit(const void *unused __unused)
379 {
380 
381 	VNET_ASSERT(TAILQ_EMPTY(&V_ifnet));
382 	VNET_ASSERT(TAILQ_EMPTY(&V_ifg_head));
383 
384 	free((caddr_t)V_ifindex_table, M_IFNET);
385 }
386 VNET_SYSUNINIT(vnet_if_uninit, SI_SUB_INIT_IF, SI_ORDER_FIRST,
387     vnet_if_uninit, NULL);
388 #endif
389 
390 static void
391 if_grow(void)
392 {
393 	int oldlim;
394 	u_int n;
395 	struct ifindex_entry *e;
396 
397 	IFNET_WLOCK_ASSERT();
398 	oldlim = V_if_indexlim;
399 	IFNET_WUNLOCK();
400 	n = (oldlim << 1) * sizeof(*e);
401 	e = malloc(n, M_IFNET, M_WAITOK | M_ZERO);
402 	IFNET_WLOCK();
403 	if (V_if_indexlim != oldlim) {
404 		free(e, M_IFNET);
405 		return;
406 	}
407 	if (V_ifindex_table != NULL) {
408 		memcpy((caddr_t)e, (caddr_t)V_ifindex_table, n/2);
409 		free((caddr_t)V_ifindex_table, M_IFNET);
410 	}
411 	V_if_indexlim <<= 1;
412 	V_ifindex_table = e;
413 }
414 
415 /*
416  * Allocate a struct ifnet and an index for an interface.  A layer 2
417  * common structure will also be allocated if an allocation routine is
418  * registered for the passed type.
419  */
420 struct ifnet *
421 if_alloc(u_char type)
422 {
423 	struct ifnet *ifp;
424 	u_short idx;
425 
426 	ifp = malloc(sizeof(struct ifnet), M_IFNET, M_WAITOK|M_ZERO);
427 	IFNET_WLOCK();
428 	if (ifindex_alloc_locked(&idx) != 0) {
429 		IFNET_WUNLOCK();
430 		free(ifp, M_IFNET);
431 		return (NULL);
432 	}
433 	ifnet_setbyindex_locked(idx, IFNET_HOLD);
434 	IFNET_WUNLOCK();
435 	ifp->if_index = idx;
436 	ifp->if_type = type;
437 	ifp->if_alloctype = type;
438 	if (if_com_alloc[type] != NULL) {
439 		ifp->if_l2com = if_com_alloc[type](type, ifp);
440 		if (ifp->if_l2com == NULL) {
441 			free(ifp, M_IFNET);
442 			ifindex_free(idx);
443 			return (NULL);
444 		}
445 	}
446 
447 	IF_ADDR_LOCK_INIT(ifp);
448 	TASK_INIT(&ifp->if_linktask, 0, do_link_state_change, ifp);
449 	ifp->if_afdata_initialized = 0;
450 	IF_AFDATA_LOCK_INIT(ifp);
451 	TAILQ_INIT(&ifp->if_addrhead);
452 	TAILQ_INIT(&ifp->if_prefixhead);
453 	TAILQ_INIT(&ifp->if_multiaddrs);
454 	TAILQ_INIT(&ifp->if_groups);
455 #ifdef MAC
456 	mac_ifnet_init(ifp);
457 #endif
458 	ifq_init(&ifp->if_snd, ifp);
459 
460 	refcount_init(&ifp->if_refcount, 1);	/* Index reference. */
461 	ifnet_setbyindex(ifp->if_index, ifp);
462 	return (ifp);
463 }
464 
465 /*
466  * Do the actual work of freeing a struct ifnet, associated index, and layer
467  * 2 common structure.  This call is made when the last reference to an
468  * interface is released.
469  */
470 static void
471 if_free_internal(struct ifnet *ifp)
472 {
473 
474 	KASSERT((ifp->if_flags & IFF_DYING),
475 	    ("if_free_internal: interface not dying"));
476 
477 	IFNET_WLOCK();
478 	KASSERT(ifp == ifnet_byindex_locked(ifp->if_index),
479 	    ("%s: freeing unallocated ifnet", ifp->if_xname));
480 
481 	ifindex_free_locked(ifp->if_index);
482 	IFNET_WUNLOCK();
483 
484 	if (if_com_free[ifp->if_alloctype] != NULL)
485 		if_com_free[ifp->if_alloctype](ifp->if_l2com,
486 		    ifp->if_alloctype);
487 
488 #ifdef MAC
489 	mac_ifnet_destroy(ifp);
490 #endif /* MAC */
491 	if (ifp->if_description != NULL)
492 		free(ifp->if_description, M_IFDESCR);
493 	IF_AFDATA_DESTROY(ifp);
494 	IF_ADDR_LOCK_DESTROY(ifp);
495 	ifq_delete(&ifp->if_snd);
496 	free(ifp, M_IFNET);
497 }
498 
499 /*
500  * This version should only be called by intefaces that switch their type
501  * after calling if_alloc().  if_free_type() will go away again now that we
502  * have if_alloctype to cache the original allocation type.  For now, assert
503  * that they match, since we require that in practice.
504  */
505 void
506 if_free_type(struct ifnet *ifp, u_char type)
507 {
508 
509 	KASSERT(ifp->if_alloctype == type,
510 	    ("if_free_type: type (%d) != alloctype (%d)", type,
511 	    ifp->if_alloctype));
512 
513 	ifp->if_flags |= IFF_DYING;			/* XXX: Locking */
514 	if (!refcount_release(&ifp->if_refcount))
515 		return;
516 	if_free_internal(ifp);
517 }
518 
519 /*
520  * This is the normal version of if_free(), used by device drivers to free a
521  * detached network interface.  The contents of if_free_type() will move into
522  * here when if_free_type() goes away.
523  */
524 void
525 if_free(struct ifnet *ifp)
526 {
527 
528 	if_free_type(ifp, ifp->if_alloctype);
529 }
530 
531 /*
532  * Interfaces to keep an ifnet type-stable despite the possibility of the
533  * driver calling if_free().  If there are additional references, we defer
534  * freeing the underlying data structure.
535  */
536 void
537 if_ref(struct ifnet *ifp)
538 {
539 
540 	/* We don't assert the ifnet list lock here, but arguably should. */
541 	refcount_acquire(&ifp->if_refcount);
542 }
543 
544 void
545 if_rele(struct ifnet *ifp)
546 {
547 
548 	if (!refcount_release(&ifp->if_refcount))
549 		return;
550 	if_free_internal(ifp);
551 }
552 
553 void
554 ifq_init(struct ifaltq *ifq, struct ifnet *ifp)
555 {
556 
557 	mtx_init(&ifq->ifq_mtx, ifp->if_xname, "if send queue", MTX_DEF);
558 
559 	if (ifq->ifq_maxlen == 0)
560 		ifq->ifq_maxlen = ifqmaxlen;
561 
562 	ifq->altq_type = 0;
563 	ifq->altq_disc = NULL;
564 	ifq->altq_flags &= ALTQF_CANTCHANGE;
565 	ifq->altq_tbr  = NULL;
566 	ifq->altq_ifp  = ifp;
567 }
568 
569 void
570 ifq_delete(struct ifaltq *ifq)
571 {
572 	mtx_destroy(&ifq->ifq_mtx);
573 }
574 
575 /*
576  * Perform generic interface initalization tasks and attach the interface
577  * to the list of "active" interfaces.  If vmove flag is set on entry
578  * to if_attach_internal(), perform only a limited subset of initialization
579  * tasks, given that we are moving from one vnet to another an ifnet which
580  * has already been fully initialized.
581  *
582  * XXX:
583  *  - The decision to return void and thus require this function to
584  *    succeed is questionable.
585  *  - We should probably do more sanity checking.  For instance we don't
586  *    do anything to insure if_xname is unique or non-empty.
587  */
588 void
589 if_attach(struct ifnet *ifp)
590 {
591 
592 	if_attach_internal(ifp, 0);
593 }
594 
595 static void
596 if_attach_internal(struct ifnet *ifp, int vmove)
597 {
598 	unsigned socksize, ifasize;
599 	int namelen, masklen;
600 	struct sockaddr_dl *sdl;
601 	struct ifaddr *ifa;
602 
603 	if (ifp->if_index == 0 || ifp != ifnet_byindex(ifp->if_index))
604 		panic ("%s: BUG: if_attach called without if_alloc'd input()\n",
605 		    ifp->if_xname);
606 
607 #ifdef VIMAGE
608 	ifp->if_vnet = curvnet;
609 	if (ifp->if_home_vnet == NULL)
610 		ifp->if_home_vnet = curvnet;
611 #endif
612 
613 	if_addgroup(ifp, IFG_ALL);
614 
615 	getmicrotime(&ifp->if_lastchange);
616 	ifp->if_data.ifi_epoch = time_uptime;
617 	ifp->if_data.ifi_datalen = sizeof(struct if_data);
618 
619 	KASSERT((ifp->if_transmit == NULL && ifp->if_qflush == NULL) ||
620 	    (ifp->if_transmit != NULL && ifp->if_qflush != NULL),
621 	    ("transmit and qflush must both either be set or both be NULL"));
622 	if (ifp->if_transmit == NULL) {
623 		ifp->if_transmit = if_transmit;
624 		ifp->if_qflush = if_qflush;
625 	}
626 
627 	if (!vmove) {
628 #ifdef MAC
629 		mac_ifnet_create(ifp);
630 #endif
631 
632 		/*
633 		 * Create a Link Level name for this device.
634 		 */
635 		namelen = strlen(ifp->if_xname);
636 		/*
637 		 * Always save enough space for any possiable name so we
638 		 * can do a rename in place later.
639 		 */
640 		masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + IFNAMSIZ;
641 		socksize = masklen + ifp->if_addrlen;
642 		if (socksize < sizeof(*sdl))
643 			socksize = sizeof(*sdl);
644 		socksize = roundup2(socksize, sizeof(long));
645 		ifasize = sizeof(*ifa) + 2 * socksize;
646 		ifa = malloc(ifasize, M_IFADDR, M_WAITOK | M_ZERO);
647 		ifa_init(ifa);
648 		sdl = (struct sockaddr_dl *)(ifa + 1);
649 		sdl->sdl_len = socksize;
650 		sdl->sdl_family = AF_LINK;
651 		bcopy(ifp->if_xname, sdl->sdl_data, namelen);
652 		sdl->sdl_nlen = namelen;
653 		sdl->sdl_index = ifp->if_index;
654 		sdl->sdl_type = ifp->if_type;
655 		ifp->if_addr = ifa;
656 		ifa->ifa_ifp = ifp;
657 		ifa->ifa_rtrequest = link_rtrequest;
658 		ifa->ifa_addr = (struct sockaddr *)sdl;
659 		sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
660 		ifa->ifa_netmask = (struct sockaddr *)sdl;
661 		sdl->sdl_len = masklen;
662 		while (namelen != 0)
663 			sdl->sdl_data[--namelen] = 0xff;
664 		TAILQ_INSERT_HEAD(&ifp->if_addrhead, ifa, ifa_link);
665 		/* Reliably crash if used uninitialized. */
666 		ifp->if_broadcastaddr = NULL;
667 	}
668 #ifdef VIMAGE
669 	else {
670 		/*
671 		 * Update the interface index in the link layer address
672 		 * of the interface.
673 		 */
674 		for (ifa = ifp->if_addr; ifa != NULL;
675 		    ifa = TAILQ_NEXT(ifa, ifa_link)) {
676 			if (ifa->ifa_addr->sa_family == AF_LINK) {
677 				sdl = (struct sockaddr_dl *)ifa->ifa_addr;
678 				sdl->sdl_index = ifp->if_index;
679 			}
680 		}
681 	}
682 #endif
683 
684 	IFNET_WLOCK();
685 	TAILQ_INSERT_TAIL(&V_ifnet, ifp, if_link);
686 #ifdef VIMAGE
687 	curvnet->vnet_ifcnt++;
688 #endif
689 	IFNET_WUNLOCK();
690 
691 	if (domain_init_status >= 2)
692 		if_attachdomain1(ifp);
693 
694 	EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
695 	if (IS_DEFAULT_VNET(curvnet))
696 		devctl_notify("IFNET", ifp->if_xname, "ATTACH", NULL);
697 
698 	/* Announce the interface. */
699 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
700 }
701 
702 static void
703 if_attachdomain(void *dummy)
704 {
705 	struct ifnet *ifp;
706 	int s;
707 
708 	s = splnet();
709 	TAILQ_FOREACH(ifp, &V_ifnet, if_link)
710 		if_attachdomain1(ifp);
711 	splx(s);
712 }
713 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_SECOND,
714     if_attachdomain, NULL);
715 
716 static void
717 if_attachdomain1(struct ifnet *ifp)
718 {
719 	struct domain *dp;
720 	int s;
721 
722 	s = splnet();
723 
724 	/*
725 	 * Since dp->dom_ifattach calls malloc() with M_WAITOK, we
726 	 * cannot lock ifp->if_afdata initialization, entirely.
727 	 */
728 	if (IF_AFDATA_TRYLOCK(ifp) == 0) {
729 		splx(s);
730 		return;
731 	}
732 	if (ifp->if_afdata_initialized >= domain_init_status) {
733 		IF_AFDATA_UNLOCK(ifp);
734 		splx(s);
735 		printf("if_attachdomain called more than once on %s\n",
736 		    ifp->if_xname);
737 		return;
738 	}
739 	ifp->if_afdata_initialized = domain_init_status;
740 	IF_AFDATA_UNLOCK(ifp);
741 
742 	/* address family dependent data region */
743 	bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
744 	for (dp = domains; dp; dp = dp->dom_next) {
745 		if (dp->dom_ifattach)
746 			ifp->if_afdata[dp->dom_family] =
747 			    (*dp->dom_ifattach)(ifp);
748 	}
749 
750 	splx(s);
751 }
752 
753 /*
754  * Remove any unicast or broadcast network addresses from an interface.
755  */
756 void
757 if_purgeaddrs(struct ifnet *ifp)
758 {
759 	struct ifaddr *ifa, *next;
760 
761 	TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, next) {
762 		if (ifa->ifa_addr->sa_family == AF_LINK)
763 			continue;
764 #ifdef INET
765 		/* XXX: Ugly!! ad hoc just for INET */
766 		if (ifa->ifa_addr->sa_family == AF_INET) {
767 			struct ifaliasreq ifr;
768 
769 			bzero(&ifr, sizeof(ifr));
770 			ifr.ifra_addr = *ifa->ifa_addr;
771 			if (ifa->ifa_dstaddr)
772 				ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
773 			if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
774 			    NULL) == 0)
775 				continue;
776 		}
777 #endif /* INET */
778 #ifdef INET6
779 		if (ifa->ifa_addr->sa_family == AF_INET6) {
780 			in6_purgeaddr(ifa);
781 			/* ifp_addrhead is already updated */
782 			continue;
783 		}
784 #endif /* INET6 */
785 		TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
786 		ifa_free(ifa);
787 	}
788 }
789 
790 /*
791  * Remove any multicast network addresses from an interface when an ifnet
792  * is going away.
793  */
794 static void
795 if_purgemaddrs(struct ifnet *ifp)
796 {
797 	struct ifmultiaddr *ifma;
798 	struct ifmultiaddr *next;
799 
800 	IF_ADDR_LOCK(ifp);
801 	TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
802 		if_delmulti_locked(ifp, ifma, 1);
803 	IF_ADDR_UNLOCK(ifp);
804 }
805 
806 /*
807  * Detach an interface, removing it from the list of "active" interfaces.
808  * If vmove flag is set on entry to if_detach_internal(), perform only a
809  * limited subset of cleanup tasks, given that we are moving an ifnet from
810  * one vnet to another, where it must be fully operational.
811  *
812  * XXXRW: There are some significant questions about event ordering, and
813  * how to prevent things from starting to use the interface during detach.
814  */
815 void
816 if_detach(struct ifnet *ifp)
817 {
818 
819 	if_detach_internal(ifp, 0);
820 }
821 
822 static void
823 if_detach_internal(struct ifnet *ifp, int vmove)
824 {
825 	struct ifaddr *ifa;
826 	struct radix_node_head	*rnh;
827 	int i, j;
828 	struct domain *dp;
829  	struct ifnet *iter;
830  	int found = 0;
831 
832 	IFNET_WLOCK();
833 	TAILQ_FOREACH(iter, &V_ifnet, if_link)
834 		if (iter == ifp) {
835 			TAILQ_REMOVE(&V_ifnet, ifp, if_link);
836 			found = 1;
837 			break;
838 		}
839 #ifdef VIMAGE
840 	if (found)
841 		curvnet->vnet_ifcnt--;
842 #endif
843 	IFNET_WUNLOCK();
844 	if (!found) {
845 		if (vmove)
846 			panic("%s: ifp=%p not on the ifnet tailq %p",
847 			    __func__, ifp, &V_ifnet);
848 		else
849 			return; /* XXX this should panic as well? */
850 	}
851 
852 	/*
853 	 * Remove/wait for pending events.
854 	 */
855 	taskqueue_drain(taskqueue_swi, &ifp->if_linktask);
856 
857 	/*
858 	 * Remove routes and flush queues.
859 	 */
860 	if_down(ifp);
861 #ifdef ALTQ
862 	if (ALTQ_IS_ENABLED(&ifp->if_snd))
863 		altq_disable(&ifp->if_snd);
864 	if (ALTQ_IS_ATTACHED(&ifp->if_snd))
865 		altq_detach(&ifp->if_snd);
866 #endif
867 
868 	if_purgeaddrs(ifp);
869 
870 #ifdef INET
871 	in_ifdetach(ifp);
872 #endif
873 
874 #ifdef INET6
875 	/*
876 	 * Remove all IPv6 kernel structs related to ifp.  This should be done
877 	 * before removing routing entries below, since IPv6 interface direct
878 	 * routes are expected to be removed by the IPv6-specific kernel API.
879 	 * Otherwise, the kernel will detect some inconsistency and bark it.
880 	 */
881 	in6_ifdetach(ifp);
882 #endif
883 	if_purgemaddrs(ifp);
884 
885 	if (!vmove) {
886 		/*
887 		 * Prevent further calls into the device driver via ifnet.
888 		 */
889 		if_dead(ifp);
890 
891 		/*
892 		 * Remove link ifaddr pointer and maybe decrement if_index.
893 		 * Clean up all addresses.
894 		 */
895 		ifp->if_addr = NULL;
896 
897 		/* We can now free link ifaddr. */
898 		if (!TAILQ_EMPTY(&ifp->if_addrhead)) {
899 			ifa = TAILQ_FIRST(&ifp->if_addrhead);
900 			TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
901 			ifa_free(ifa);
902 		}
903 	}
904 
905 	/*
906 	 * Delete all remaining routes using this interface
907 	 * Unfortuneatly the only way to do this is to slog through
908 	 * the entire routing table looking for routes which point
909 	 * to this interface...oh well...
910 	 */
911 	for (i = 1; i <= AF_MAX; i++) {
912 		for (j = 0; j < rt_numfibs; j++) {
913 			rnh = rt_tables_get_rnh(j, i);
914 			if (rnh == NULL)
915 				continue;
916 			RADIX_NODE_HEAD_LOCK(rnh);
917 			(void) rnh->rnh_walktree(rnh, if_rtdel, ifp);
918 			RADIX_NODE_HEAD_UNLOCK(rnh);
919 		}
920 	}
921 
922 	/* Announce that the interface is gone. */
923 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
924 	EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
925 	if (IS_DEFAULT_VNET(curvnet))
926 		devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
927 	if_delgroups(ifp);
928 
929 	/*
930 	 * We cannot hold the lock over dom_ifdetach calls as they might
931 	 * sleep, for example trying to drain a callout, thus open up the
932 	 * theoretical race with re-attaching.
933 	 */
934 	IF_AFDATA_LOCK(ifp);
935 	i = ifp->if_afdata_initialized;
936 	ifp->if_afdata_initialized = 0;
937 	IF_AFDATA_UNLOCK(ifp);
938 	for (dp = domains; i > 0 && dp; dp = dp->dom_next) {
939 		if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family])
940 			(*dp->dom_ifdetach)(ifp,
941 			    ifp->if_afdata[dp->dom_family]);
942 	}
943 }
944 
945 #ifdef VIMAGE
946 /*
947  * if_vmove() performs a limited version of if_detach() in current
948  * vnet and if_attach()es the ifnet to the vnet specified as 2nd arg.
949  * An attempt is made to shrink if_index in current vnet, find an
950  * unused if_index in target vnet and calls if_grow() if necessary,
951  * and finally find an unused if_xname for the target vnet.
952  */
953 void
954 if_vmove(struct ifnet *ifp, struct vnet *new_vnet)
955 {
956 	u_short idx;
957 
958 	/*
959 	 * Detach from current vnet, but preserve LLADDR info, do not
960 	 * mark as dead etc. so that the ifnet can be reattached later.
961 	 */
962 	if_detach_internal(ifp, 1);
963 
964 	/*
965 	 * Unlink the ifnet from ifindex_table[] in current vnet, and shrink
966 	 * the if_index for that vnet if possible.
967 	 *
968 	 * NOTE: IFNET_WLOCK/IFNET_WUNLOCK() are assumed to be unvirtualized,
969 	 * or we'd lock on one vnet and unlock on another.
970 	 */
971 	IFNET_WLOCK();
972 	ifindex_free_locked(ifp->if_index);
973 	IFNET_WUNLOCK();
974 
975 	/*
976 	 * Perform interface-specific reassignment tasks, if provided by
977 	 * the driver.
978 	 */
979 	if (ifp->if_reassign != NULL)
980 		ifp->if_reassign(ifp, new_vnet, NULL);
981 
982 	/*
983 	 * Switch to the context of the target vnet.
984 	 */
985 	CURVNET_SET_QUIET(new_vnet);
986 
987 	IFNET_WLOCK();
988 	if (ifindex_alloc_locked(&idx) != 0) {
989 		IFNET_WUNLOCK();
990 		panic("if_index overflow");
991 	}
992 	ifp->if_index = idx;
993 	ifnet_setbyindex_locked(ifp->if_index, ifp);
994 	IFNET_WUNLOCK();
995 
996 	if_attach_internal(ifp, 1);
997 
998 	CURVNET_RESTORE();
999 }
1000 
1001 /*
1002  * Move an ifnet to or from another child prison/vnet, specified by the jail id.
1003  */
1004 static int
1005 if_vmove_loan(struct thread *td, struct ifnet *ifp, char *ifname, int jid)
1006 {
1007 	struct prison *pr;
1008 	struct ifnet *difp;
1009 
1010 	/* Try to find the prison within our visibility. */
1011 	sx_slock(&allprison_lock);
1012 	pr = prison_find_child(td->td_ucred->cr_prison, jid);
1013 	sx_sunlock(&allprison_lock);
1014 	if (pr == NULL)
1015 		return (ENXIO);
1016 	prison_hold_locked(pr);
1017 	mtx_unlock(&pr->pr_mtx);
1018 
1019 	/* Do not try to move the iface from and to the same prison. */
1020 	if (pr->pr_vnet == ifp->if_vnet) {
1021 		prison_free(pr);
1022 		return (EEXIST);
1023 	}
1024 
1025 	/* Make sure the named iface does not exists in the dst. prison/vnet. */
1026 	/* XXX Lock interfaces to avoid races. */
1027 	CURVNET_SET_QUIET(pr->pr_vnet);
1028 	difp = ifunit(ifname);
1029 	CURVNET_RESTORE();
1030 	if (difp != NULL) {
1031 		prison_free(pr);
1032 		return (EEXIST);
1033 	}
1034 
1035 	/* Move the interface into the child jail/vnet. */
1036 	if_vmove(ifp, pr->pr_vnet);
1037 
1038 	/* Report the new if_xname back to the userland. */
1039 	sprintf(ifname, "%s", ifp->if_xname);
1040 
1041 	prison_free(pr);
1042 	return (0);
1043 }
1044 
1045 static int
1046 if_vmove_reclaim(struct thread *td, char *ifname, int jid)
1047 {
1048 	struct prison *pr;
1049 	struct vnet *vnet_dst;
1050 	struct ifnet *ifp;
1051 
1052 	/* Try to find the prison within our visibility. */
1053 	sx_slock(&allprison_lock);
1054 	pr = prison_find_child(td->td_ucred->cr_prison, jid);
1055 	sx_sunlock(&allprison_lock);
1056 	if (pr == NULL)
1057 		return (ENXIO);
1058 	prison_hold_locked(pr);
1059 	mtx_unlock(&pr->pr_mtx);
1060 
1061 	/* Make sure the named iface exists in the source prison/vnet. */
1062 	CURVNET_SET(pr->pr_vnet);
1063 	ifp = ifunit(ifname);		/* XXX Lock to avoid races. */
1064 	if (ifp == NULL) {
1065 		CURVNET_RESTORE();
1066 		prison_free(pr);
1067 		return (ENXIO);
1068 	}
1069 
1070 	/* Do not try to move the iface from and to the same prison. */
1071 	vnet_dst = TD_TO_VNET(td);
1072 	if (vnet_dst == ifp->if_vnet) {
1073 		CURVNET_RESTORE();
1074 		prison_free(pr);
1075 		return (EEXIST);
1076 	}
1077 
1078 	/* Get interface back from child jail/vnet. */
1079 	if_vmove(ifp, vnet_dst);
1080 	CURVNET_RESTORE();
1081 
1082 	/* Report the new if_xname back to the userland. */
1083 	sprintf(ifname, "%s", ifp->if_xname);
1084 
1085 	prison_free(pr);
1086 	return (0);
1087 }
1088 #endif /* VIMAGE */
1089 
1090 /*
1091  * Add a group to an interface
1092  */
1093 int
1094 if_addgroup(struct ifnet *ifp, const char *groupname)
1095 {
1096 	struct ifg_list		*ifgl;
1097 	struct ifg_group	*ifg = NULL;
1098 	struct ifg_member	*ifgm;
1099 
1100 	if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
1101 	    groupname[strlen(groupname) - 1] <= '9')
1102 		return (EINVAL);
1103 
1104 	IFNET_WLOCK();
1105 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1106 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname)) {
1107 			IFNET_WUNLOCK();
1108 			return (EEXIST);
1109 		}
1110 
1111 	if ((ifgl = (struct ifg_list *)malloc(sizeof(struct ifg_list), M_TEMP,
1112 	    M_NOWAIT)) == NULL) {
1113 	    	IFNET_WUNLOCK();
1114 		return (ENOMEM);
1115 	}
1116 
1117 	if ((ifgm = (struct ifg_member *)malloc(sizeof(struct ifg_member),
1118 	    M_TEMP, M_NOWAIT)) == NULL) {
1119 		free(ifgl, M_TEMP);
1120 		IFNET_WUNLOCK();
1121 		return (ENOMEM);
1122 	}
1123 
1124 	TAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1125 		if (!strcmp(ifg->ifg_group, groupname))
1126 			break;
1127 
1128 	if (ifg == NULL) {
1129 		if ((ifg = (struct ifg_group *)malloc(sizeof(struct ifg_group),
1130 		    M_TEMP, M_NOWAIT)) == NULL) {
1131 			free(ifgl, M_TEMP);
1132 			free(ifgm, M_TEMP);
1133 			IFNET_WUNLOCK();
1134 			return (ENOMEM);
1135 		}
1136 		strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
1137 		ifg->ifg_refcnt = 0;
1138 		TAILQ_INIT(&ifg->ifg_members);
1139 		EVENTHANDLER_INVOKE(group_attach_event, ifg);
1140 		TAILQ_INSERT_TAIL(&V_ifg_head, ifg, ifg_next);
1141 	}
1142 
1143 	ifg->ifg_refcnt++;
1144 	ifgl->ifgl_group = ifg;
1145 	ifgm->ifgm_ifp = ifp;
1146 
1147 	IF_ADDR_LOCK(ifp);
1148 	TAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
1149 	TAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
1150 	IF_ADDR_UNLOCK(ifp);
1151 
1152 	IFNET_WUNLOCK();
1153 
1154 	EVENTHANDLER_INVOKE(group_change_event, groupname);
1155 
1156 	return (0);
1157 }
1158 
1159 /*
1160  * Remove a group from an interface
1161  */
1162 int
1163 if_delgroup(struct ifnet *ifp, const char *groupname)
1164 {
1165 	struct ifg_list		*ifgl;
1166 	struct ifg_member	*ifgm;
1167 
1168 	IFNET_WLOCK();
1169 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1170 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
1171 			break;
1172 	if (ifgl == NULL) {
1173 		IFNET_WUNLOCK();
1174 		return (ENOENT);
1175 	}
1176 
1177 	IF_ADDR_LOCK(ifp);
1178 	TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
1179 	IF_ADDR_UNLOCK(ifp);
1180 
1181 	TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1182 		if (ifgm->ifgm_ifp == ifp)
1183 			break;
1184 
1185 	if (ifgm != NULL) {
1186 		TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifgm_next);
1187 		free(ifgm, M_TEMP);
1188 	}
1189 
1190 	if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1191 		TAILQ_REMOVE(&V_ifg_head, ifgl->ifgl_group, ifg_next);
1192 		EVENTHANDLER_INVOKE(group_detach_event, ifgl->ifgl_group);
1193 		free(ifgl->ifgl_group, M_TEMP);
1194 	}
1195 	IFNET_WUNLOCK();
1196 
1197 	free(ifgl, M_TEMP);
1198 
1199 	EVENTHANDLER_INVOKE(group_change_event, groupname);
1200 
1201 	return (0);
1202 }
1203 
1204 /*
1205  * Remove an interface from all groups
1206  */
1207 static void
1208 if_delgroups(struct ifnet *ifp)
1209 {
1210 	struct ifg_list		*ifgl;
1211 	struct ifg_member	*ifgm;
1212 	char groupname[IFNAMSIZ];
1213 
1214 	IFNET_WLOCK();
1215 	while (!TAILQ_EMPTY(&ifp->if_groups)) {
1216 		ifgl = TAILQ_FIRST(&ifp->if_groups);
1217 
1218 		strlcpy(groupname, ifgl->ifgl_group->ifg_group, IFNAMSIZ);
1219 
1220 		IF_ADDR_LOCK(ifp);
1221 		TAILQ_REMOVE(&ifp->if_groups, ifgl, ifgl_next);
1222 		IF_ADDR_UNLOCK(ifp);
1223 
1224 		TAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1225 			if (ifgm->ifgm_ifp == ifp)
1226 				break;
1227 
1228 		if (ifgm != NULL) {
1229 			TAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm,
1230 			    ifgm_next);
1231 			free(ifgm, M_TEMP);
1232 		}
1233 
1234 		if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1235 			TAILQ_REMOVE(&V_ifg_head, ifgl->ifgl_group, ifg_next);
1236 			EVENTHANDLER_INVOKE(group_detach_event,
1237 			    ifgl->ifgl_group);
1238 			free(ifgl->ifgl_group, M_TEMP);
1239 		}
1240 		IFNET_WUNLOCK();
1241 
1242 		free(ifgl, M_TEMP);
1243 
1244 		EVENTHANDLER_INVOKE(group_change_event, groupname);
1245 
1246 		IFNET_WLOCK();
1247 	}
1248 	IFNET_WUNLOCK();
1249 }
1250 
1251 /*
1252  * Stores all groups from an interface in memory pointed
1253  * to by data
1254  */
1255 static int
1256 if_getgroup(struct ifgroupreq *data, struct ifnet *ifp)
1257 {
1258 	int			 len, error;
1259 	struct ifg_list		*ifgl;
1260 	struct ifg_req		 ifgrq, *ifgp;
1261 	struct ifgroupreq	*ifgr = data;
1262 
1263 	if (ifgr->ifgr_len == 0) {
1264 		IF_ADDR_LOCK(ifp);
1265 		TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1266 			ifgr->ifgr_len += sizeof(struct ifg_req);
1267 		IF_ADDR_UNLOCK(ifp);
1268 		return (0);
1269 	}
1270 
1271 	len = ifgr->ifgr_len;
1272 	ifgp = ifgr->ifgr_groups;
1273 	/* XXX: wire */
1274 	IF_ADDR_LOCK(ifp);
1275 	TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
1276 		if (len < sizeof(ifgrq)) {
1277 			IF_ADDR_UNLOCK(ifp);
1278 			return (EINVAL);
1279 		}
1280 		bzero(&ifgrq, sizeof ifgrq);
1281 		strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
1282 		    sizeof(ifgrq.ifgrq_group));
1283 		if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1284 		    	IF_ADDR_UNLOCK(ifp);
1285 			return (error);
1286 		}
1287 		len -= sizeof(ifgrq);
1288 		ifgp++;
1289 	}
1290 	IF_ADDR_UNLOCK(ifp);
1291 
1292 	return (0);
1293 }
1294 
1295 /*
1296  * Stores all members of a group in memory pointed to by data
1297  */
1298 static int
1299 if_getgroupmembers(struct ifgroupreq *data)
1300 {
1301 	struct ifgroupreq	*ifgr = data;
1302 	struct ifg_group	*ifg;
1303 	struct ifg_member	*ifgm;
1304 	struct ifg_req		 ifgrq, *ifgp;
1305 	int			 len, error;
1306 
1307 	IFNET_RLOCK();
1308 	TAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1309 		if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
1310 			break;
1311 	if (ifg == NULL) {
1312 		IFNET_RUNLOCK();
1313 		return (ENOENT);
1314 	}
1315 
1316 	if (ifgr->ifgr_len == 0) {
1317 		TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
1318 			ifgr->ifgr_len += sizeof(ifgrq);
1319 		IFNET_RUNLOCK();
1320 		return (0);
1321 	}
1322 
1323 	len = ifgr->ifgr_len;
1324 	ifgp = ifgr->ifgr_groups;
1325 	TAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1326 		if (len < sizeof(ifgrq)) {
1327 			IFNET_RUNLOCK();
1328 			return (EINVAL);
1329 		}
1330 		bzero(&ifgrq, sizeof ifgrq);
1331 		strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1332 		    sizeof(ifgrq.ifgrq_member));
1333 		if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1334 			IFNET_RUNLOCK();
1335 			return (error);
1336 		}
1337 		len -= sizeof(ifgrq);
1338 		ifgp++;
1339 	}
1340 	IFNET_RUNLOCK();
1341 
1342 	return (0);
1343 }
1344 
1345 /*
1346  * Delete Routes for a Network Interface
1347  *
1348  * Called for each routing entry via the rnh->rnh_walktree() call above
1349  * to delete all route entries referencing a detaching network interface.
1350  *
1351  * Arguments:
1352  *	rn	pointer to node in the routing table
1353  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
1354  *
1355  * Returns:
1356  *	0	successful
1357  *	errno	failed - reason indicated
1358  *
1359  */
1360 static int
1361 if_rtdel(struct radix_node *rn, void *arg)
1362 {
1363 	struct rtentry	*rt = (struct rtentry *)rn;
1364 	struct ifnet	*ifp = arg;
1365 	int		err;
1366 
1367 	if (rt->rt_ifp == ifp) {
1368 
1369 		/*
1370 		 * Protect (sorta) against walktree recursion problems
1371 		 * with cloned routes
1372 		 */
1373 		if ((rt->rt_flags & RTF_UP) == 0)
1374 			return (0);
1375 
1376 		err = rtrequest_fib(RTM_DELETE, rt_key(rt), rt->rt_gateway,
1377 				rt_mask(rt), rt->rt_flags|RTF_RNH_LOCKED,
1378 				(struct rtentry **) NULL, rt->rt_fibnum);
1379 		if (err) {
1380 			log(LOG_WARNING, "if_rtdel: error %d\n", err);
1381 		}
1382 	}
1383 
1384 	return (0);
1385 }
1386 
1387 /*
1388  * Wrapper functions for struct ifnet address list locking macros.  These are
1389  * used by kernel modules to avoid encoding programming interface or binary
1390  * interface assumptions that may be violated when kernel-internal locking
1391  * approaches change.
1392  */
1393 void
1394 if_addr_rlock(struct ifnet *ifp)
1395 {
1396 
1397 	IF_ADDR_LOCK(ifp);
1398 }
1399 
1400 void
1401 if_addr_runlock(struct ifnet *ifp)
1402 {
1403 
1404 	IF_ADDR_UNLOCK(ifp);
1405 }
1406 
1407 void
1408 if_maddr_rlock(struct ifnet *ifp)
1409 {
1410 
1411 	IF_ADDR_LOCK(ifp);
1412 }
1413 
1414 void
1415 if_maddr_runlock(struct ifnet *ifp)
1416 {
1417 
1418 	IF_ADDR_UNLOCK(ifp);
1419 }
1420 
1421 /*
1422  * Reference count functions for ifaddrs.
1423  */
1424 void
1425 ifa_init(struct ifaddr *ifa)
1426 {
1427 
1428 	mtx_init(&ifa->ifa_mtx, "ifaddr", NULL, MTX_DEF);
1429 	refcount_init(&ifa->ifa_refcnt, 1);
1430 }
1431 
1432 void
1433 ifa_ref(struct ifaddr *ifa)
1434 {
1435 
1436 	refcount_acquire(&ifa->ifa_refcnt);
1437 }
1438 
1439 void
1440 ifa_free(struct ifaddr *ifa)
1441 {
1442 
1443 	if (refcount_release(&ifa->ifa_refcnt)) {
1444 		mtx_destroy(&ifa->ifa_mtx);
1445 		free(ifa, M_IFADDR);
1446 	}
1447 }
1448 
1449 int
1450 ifa_add_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1451 {
1452 	int error = 0;
1453 	struct rtentry *rt = NULL;
1454 	struct rt_addrinfo info;
1455 	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1456 
1457 	bzero(&info, sizeof(info));
1458 	info.rti_ifp = V_loif;
1459 	info.rti_flags = ifa->ifa_flags | RTF_HOST | RTF_STATIC;
1460 	info.rti_info[RTAX_DST] = ia;
1461 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&null_sdl;
1462 	error = rtrequest1_fib(RTM_ADD, &info, &rt, 0);
1463 
1464 	if (error == 0 && rt != NULL) {
1465 		RT_LOCK(rt);
1466 		((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
1467 			ifa->ifa_ifp->if_type;
1468 		((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
1469 			ifa->ifa_ifp->if_index;
1470 		RT_REMREF(rt);
1471 		RT_UNLOCK(rt);
1472 	} else if (error != 0)
1473 		log(LOG_INFO, "ifa_add_loopback_route: insertion failed\n");
1474 
1475 	return (error);
1476 }
1477 
1478 int
1479 ifa_del_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1480 {
1481 	int error = 0;
1482 	struct rt_addrinfo info;
1483 	struct sockaddr_dl null_sdl;
1484 
1485 	bzero(&null_sdl, sizeof(null_sdl));
1486 	null_sdl.sdl_len = sizeof(null_sdl);
1487 	null_sdl.sdl_family = AF_LINK;
1488 	null_sdl.sdl_type = ifa->ifa_ifp->if_type;
1489 	null_sdl.sdl_index = ifa->ifa_ifp->if_index;
1490 	bzero(&info, sizeof(info));
1491 	info.rti_flags = ifa->ifa_flags | RTF_HOST | RTF_STATIC;
1492 	info.rti_info[RTAX_DST] = ia;
1493 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&null_sdl;
1494 	error = rtrequest1_fib(RTM_DELETE, &info, NULL, 0);
1495 
1496 	if (error != 0)
1497 		log(LOG_INFO, "ifa_del_loopback_route: deletion failed\n");
1498 
1499 	return (error);
1500 }
1501 
1502 /*
1503  * XXX: Because sockaddr_dl has deeper structure than the sockaddr
1504  * structs used to represent other address families, it is necessary
1505  * to perform a different comparison.
1506  */
1507 
1508 #define	sa_equal(a1, a2)	\
1509 	(bcmp((a1), (a2), ((a1))->sa_len) == 0)
1510 
1511 #define	sa_dl_equal(a1, a2)	\
1512 	((((struct sockaddr_dl *)(a1))->sdl_len ==			\
1513 	 ((struct sockaddr_dl *)(a2))->sdl_len) &&			\
1514 	 (bcmp(LLADDR((struct sockaddr_dl *)(a1)),			\
1515 	       LLADDR((struct sockaddr_dl *)(a2)),			\
1516 	       ((struct sockaddr_dl *)(a1))->sdl_alen) == 0))
1517 
1518 /*
1519  * Locate an interface based on a complete address.
1520  */
1521 /*ARGSUSED*/
1522 static struct ifaddr *
1523 ifa_ifwithaddr_internal(struct sockaddr *addr, int getref)
1524 {
1525 	struct ifnet *ifp;
1526 	struct ifaddr *ifa;
1527 
1528 	IFNET_RLOCK_NOSLEEP();
1529 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1530 		IF_ADDR_LOCK(ifp);
1531 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1532 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1533 				continue;
1534 			if (sa_equal(addr, ifa->ifa_addr)) {
1535 				if (getref)
1536 					ifa_ref(ifa);
1537 				IF_ADDR_UNLOCK(ifp);
1538 				goto done;
1539 			}
1540 			/* IP6 doesn't have broadcast */
1541 			if ((ifp->if_flags & IFF_BROADCAST) &&
1542 			    ifa->ifa_broadaddr &&
1543 			    ifa->ifa_broadaddr->sa_len != 0 &&
1544 			    sa_equal(ifa->ifa_broadaddr, addr)) {
1545 				if (getref)
1546 					ifa_ref(ifa);
1547 				IF_ADDR_UNLOCK(ifp);
1548 				goto done;
1549 			}
1550 		}
1551 		IF_ADDR_UNLOCK(ifp);
1552 	}
1553 	ifa = NULL;
1554 done:
1555 	IFNET_RUNLOCK_NOSLEEP();
1556 	return (ifa);
1557 }
1558 
1559 struct ifaddr *
1560 ifa_ifwithaddr(struct sockaddr *addr)
1561 {
1562 
1563 	return (ifa_ifwithaddr_internal(addr, 1));
1564 }
1565 
1566 int
1567 ifa_ifwithaddr_check(struct sockaddr *addr)
1568 {
1569 
1570 	return (ifa_ifwithaddr_internal(addr, 0) != NULL);
1571 }
1572 
1573 /*
1574  * Locate an interface based on the broadcast address.
1575  */
1576 /* ARGSUSED */
1577 struct ifaddr *
1578 ifa_ifwithbroadaddr(struct sockaddr *addr)
1579 {
1580 	struct ifnet *ifp;
1581 	struct ifaddr *ifa;
1582 
1583 	IFNET_RLOCK_NOSLEEP();
1584 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1585 		IF_ADDR_LOCK(ifp);
1586 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1587 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1588 				continue;
1589 			if ((ifp->if_flags & IFF_BROADCAST) &&
1590 			    ifa->ifa_broadaddr &&
1591 			    ifa->ifa_broadaddr->sa_len != 0 &&
1592 			    sa_equal(ifa->ifa_broadaddr, addr)) {
1593 				ifa_ref(ifa);
1594 				IF_ADDR_UNLOCK(ifp);
1595 				goto done;
1596 			}
1597 		}
1598 		IF_ADDR_UNLOCK(ifp);
1599 	}
1600 	ifa = NULL;
1601 done:
1602 	IFNET_RUNLOCK_NOSLEEP();
1603 	return (ifa);
1604 }
1605 
1606 /*
1607  * Locate the point to point interface with a given destination address.
1608  */
1609 /*ARGSUSED*/
1610 struct ifaddr *
1611 ifa_ifwithdstaddr(struct sockaddr *addr)
1612 {
1613 	struct ifnet *ifp;
1614 	struct ifaddr *ifa;
1615 
1616 	IFNET_RLOCK_NOSLEEP();
1617 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1618 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1619 			continue;
1620 		IF_ADDR_LOCK(ifp);
1621 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1622 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1623 				continue;
1624 			if (ifa->ifa_dstaddr != NULL &&
1625 			    sa_equal(addr, ifa->ifa_dstaddr)) {
1626 				ifa_ref(ifa);
1627 				IF_ADDR_UNLOCK(ifp);
1628 				goto done;
1629 			}
1630 		}
1631 		IF_ADDR_UNLOCK(ifp);
1632 	}
1633 	ifa = NULL;
1634 done:
1635 	IFNET_RUNLOCK_NOSLEEP();
1636 	return (ifa);
1637 }
1638 
1639 /*
1640  * Find an interface on a specific network.  If many, choice
1641  * is most specific found.
1642  */
1643 struct ifaddr *
1644 ifa_ifwithnet(struct sockaddr *addr, int ignore_ptp)
1645 {
1646 	struct ifnet *ifp;
1647 	struct ifaddr *ifa;
1648 	struct ifaddr *ifa_maybe = NULL;
1649 	u_int af = addr->sa_family;
1650 	char *addr_data = addr->sa_data, *cplim;
1651 
1652 	/*
1653 	 * AF_LINK addresses can be looked up directly by their index number,
1654 	 * so do that if we can.
1655 	 */
1656 	if (af == AF_LINK) {
1657 	    struct sockaddr_dl *sdl = (struct sockaddr_dl *)addr;
1658 	    if (sdl->sdl_index && sdl->sdl_index <= V_if_index)
1659 		return (ifaddr_byindex(sdl->sdl_index));
1660 	}
1661 
1662 	/*
1663 	 * Scan though each interface, looking for ones that have addresses
1664 	 * in this address family.  Maintain a reference on ifa_maybe once
1665 	 * we find one, as we release the IF_ADDR_LOCK() that kept it stable
1666 	 * when we move onto the next interface.
1667 	 */
1668 	IFNET_RLOCK_NOSLEEP();
1669 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1670 		IF_ADDR_LOCK(ifp);
1671 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1672 			char *cp, *cp2, *cp3;
1673 
1674 			if (ifa->ifa_addr->sa_family != af)
1675 next:				continue;
1676 			if (af == AF_INET &&
1677 			    ifp->if_flags & IFF_POINTOPOINT && !ignore_ptp) {
1678 				/*
1679 				 * This is a bit broken as it doesn't
1680 				 * take into account that the remote end may
1681 				 * be a single node in the network we are
1682 				 * looking for.
1683 				 * The trouble is that we don't know the
1684 				 * netmask for the remote end.
1685 				 */
1686 				if (ifa->ifa_dstaddr != NULL &&
1687 				    sa_equal(addr, ifa->ifa_dstaddr)) {
1688 					ifa_ref(ifa);
1689 					IF_ADDR_UNLOCK(ifp);
1690 					goto done;
1691 				}
1692 			} else {
1693 				/*
1694 				 * if we have a special address handler,
1695 				 * then use it instead of the generic one.
1696 				 */
1697 				if (ifa->ifa_claim_addr) {
1698 					if ((*ifa->ifa_claim_addr)(ifa, addr)) {
1699 						ifa_ref(ifa);
1700 						IF_ADDR_UNLOCK(ifp);
1701 						goto done;
1702 					}
1703 					continue;
1704 				}
1705 
1706 				/*
1707 				 * Scan all the bits in the ifa's address.
1708 				 * If a bit dissagrees with what we are
1709 				 * looking for, mask it with the netmask
1710 				 * to see if it really matters.
1711 				 * (A byte at a time)
1712 				 */
1713 				if (ifa->ifa_netmask == 0)
1714 					continue;
1715 				cp = addr_data;
1716 				cp2 = ifa->ifa_addr->sa_data;
1717 				cp3 = ifa->ifa_netmask->sa_data;
1718 				cplim = ifa->ifa_netmask->sa_len
1719 					+ (char *)ifa->ifa_netmask;
1720 				while (cp3 < cplim)
1721 					if ((*cp++ ^ *cp2++) & *cp3++)
1722 						goto next; /* next address! */
1723 				/*
1724 				 * If the netmask of what we just found
1725 				 * is more specific than what we had before
1726 				 * (if we had one) then remember the new one
1727 				 * before continuing to search
1728 				 * for an even better one.
1729 				 */
1730 				if (ifa_maybe == NULL ||
1731 				    rn_refines((caddr_t)ifa->ifa_netmask,
1732 				    (caddr_t)ifa_maybe->ifa_netmask)) {
1733 					if (ifa_maybe != NULL)
1734 						ifa_free(ifa_maybe);
1735 					ifa_maybe = ifa;
1736 					ifa_ref(ifa_maybe);
1737 				}
1738 			}
1739 		}
1740 		IF_ADDR_UNLOCK(ifp);
1741 	}
1742 	ifa = ifa_maybe;
1743 	ifa_maybe = NULL;
1744 done:
1745 	IFNET_RUNLOCK_NOSLEEP();
1746 	if (ifa_maybe != NULL)
1747 		ifa_free(ifa_maybe);
1748 	return (ifa);
1749 }
1750 
1751 /*
1752  * Find an interface address specific to an interface best matching
1753  * a given address.
1754  */
1755 struct ifaddr *
1756 ifaof_ifpforaddr(struct sockaddr *addr, struct ifnet *ifp)
1757 {
1758 	struct ifaddr *ifa;
1759 	char *cp, *cp2, *cp3;
1760 	char *cplim;
1761 	struct ifaddr *ifa_maybe = NULL;
1762 	u_int af = addr->sa_family;
1763 
1764 	if (af >= AF_MAX)
1765 		return (NULL);
1766 	IF_ADDR_LOCK(ifp);
1767 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1768 		if (ifa->ifa_addr->sa_family != af)
1769 			continue;
1770 		if (ifa_maybe == NULL)
1771 			ifa_maybe = ifa;
1772 		if (ifa->ifa_netmask == 0) {
1773 			if (sa_equal(addr, ifa->ifa_addr) ||
1774 			    (ifa->ifa_dstaddr &&
1775 			    sa_equal(addr, ifa->ifa_dstaddr)))
1776 				goto done;
1777 			continue;
1778 		}
1779 		if (ifp->if_flags & IFF_POINTOPOINT) {
1780 			if (sa_equal(addr, ifa->ifa_dstaddr))
1781 				goto done;
1782 		} else {
1783 			cp = addr->sa_data;
1784 			cp2 = ifa->ifa_addr->sa_data;
1785 			cp3 = ifa->ifa_netmask->sa_data;
1786 			cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
1787 			for (; cp3 < cplim; cp3++)
1788 				if ((*cp++ ^ *cp2++) & *cp3)
1789 					break;
1790 			if (cp3 == cplim)
1791 				goto done;
1792 		}
1793 	}
1794 	ifa = ifa_maybe;
1795 done:
1796 	if (ifa != NULL)
1797 		ifa_ref(ifa);
1798 	IF_ADDR_UNLOCK(ifp);
1799 	return (ifa);
1800 }
1801 
1802 #include <net/if_llatbl.h>
1803 
1804 /*
1805  * Default action when installing a route with a Link Level gateway.
1806  * Lookup an appropriate real ifa to point to.
1807  * This should be moved to /sys/net/link.c eventually.
1808  */
1809 static void
1810 link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info)
1811 {
1812 	struct ifaddr *ifa, *oifa;
1813 	struct sockaddr *dst;
1814 	struct ifnet *ifp;
1815 
1816 	RT_LOCK_ASSERT(rt);
1817 
1818 	if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == 0) ||
1819 	    ((ifp = ifa->ifa_ifp) == 0) || ((dst = rt_key(rt)) == 0))
1820 		return;
1821 	ifa = ifaof_ifpforaddr(dst, ifp);
1822 	if (ifa) {
1823 		oifa = rt->rt_ifa;
1824 		rt->rt_ifa = ifa;
1825 		ifa_free(oifa);
1826 		if (ifa->ifa_rtrequest && ifa->ifa_rtrequest != link_rtrequest)
1827 			ifa->ifa_rtrequest(cmd, rt, info);
1828 	}
1829 }
1830 
1831 /*
1832  * Mark an interface down and notify protocols of
1833  * the transition.
1834  * NOTE: must be called at splnet or eqivalent.
1835  */
1836 static void
1837 if_unroute(struct ifnet *ifp, int flag, int fam)
1838 {
1839 	struct ifaddr *ifa;
1840 
1841 	KASSERT(flag == IFF_UP, ("if_unroute: flag != IFF_UP"));
1842 
1843 	ifp->if_flags &= ~flag;
1844 	getmicrotime(&ifp->if_lastchange);
1845 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1846 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1847 			pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
1848 	ifp->if_qflush(ifp);
1849 
1850 	if (ifp->if_carp)
1851 		(*carp_linkstate_p)(ifp);
1852 	rt_ifmsg(ifp);
1853 }
1854 
1855 /*
1856  * Mark an interface up and notify protocols of
1857  * the transition.
1858  * NOTE: must be called at splnet or eqivalent.
1859  */
1860 static void
1861 if_route(struct ifnet *ifp, int flag, int fam)
1862 {
1863 	struct ifaddr *ifa;
1864 
1865 	KASSERT(flag == IFF_UP, ("if_route: flag != IFF_UP"));
1866 
1867 	ifp->if_flags |= flag;
1868 	getmicrotime(&ifp->if_lastchange);
1869 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
1870 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
1871 			pfctlinput(PRC_IFUP, ifa->ifa_addr);
1872 	if (ifp->if_carp)
1873 		(*carp_linkstate_p)(ifp);
1874 	rt_ifmsg(ifp);
1875 #ifdef INET6
1876 	in6_if_up(ifp);
1877 #endif
1878 }
1879 
1880 void	(*vlan_link_state_p)(struct ifnet *);	/* XXX: private from if_vlan */
1881 void	(*vlan_trunk_cap_p)(struct ifnet *);		/* XXX: private from if_vlan */
1882 
1883 /*
1884  * Handle a change in the interface link state. To avoid LORs
1885  * between driver lock and upper layer locks, as well as possible
1886  * recursions, we post event to taskqueue, and all job
1887  * is done in static do_link_state_change().
1888  */
1889 void
1890 if_link_state_change(struct ifnet *ifp, int link_state)
1891 {
1892 	/* Return if state hasn't changed. */
1893 	if (ifp->if_link_state == link_state)
1894 		return;
1895 
1896 	ifp->if_link_state = link_state;
1897 
1898 	taskqueue_enqueue(taskqueue_swi, &ifp->if_linktask);
1899 }
1900 
1901 static void
1902 do_link_state_change(void *arg, int pending)
1903 {
1904 	struct ifnet *ifp = (struct ifnet *)arg;
1905 	int link_state = ifp->if_link_state;
1906 	CURVNET_SET(ifp->if_vnet);
1907 
1908 	/* Notify that the link state has changed. */
1909 	rt_ifmsg(ifp);
1910 	if (ifp->if_vlantrunk != NULL)
1911 		(*vlan_link_state_p)(ifp);
1912 
1913 	if ((ifp->if_type == IFT_ETHER || ifp->if_type == IFT_L2VLAN) &&
1914 	    IFP2AC(ifp)->ac_netgraph != NULL)
1915 		(*ng_ether_link_state_p)(ifp, link_state);
1916 	if (ifp->if_carp)
1917 		(*carp_linkstate_p)(ifp);
1918 	if (ifp->if_bridge) {
1919 		KASSERT(bstp_linkstate_p != NULL,("if_bridge bstp not loaded!"));
1920 		(*bstp_linkstate_p)(ifp, link_state);
1921 	}
1922 	if (ifp->if_lagg) {
1923 		KASSERT(lagg_linkstate_p != NULL,("if_lagg not loaded!"));
1924 		(*lagg_linkstate_p)(ifp, link_state);
1925 	}
1926 
1927 	if (IS_DEFAULT_VNET(curvnet))
1928 		devctl_notify("IFNET", ifp->if_xname,
1929 		    (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN",
1930 		    NULL);
1931 	if (pending > 1)
1932 		if_printf(ifp, "%d link states coalesced\n", pending);
1933 	if (log_link_state_change)
1934 		log(LOG_NOTICE, "%s: link state changed to %s\n", ifp->if_xname,
1935 		    (link_state == LINK_STATE_UP) ? "UP" : "DOWN" );
1936 	CURVNET_RESTORE();
1937 }
1938 
1939 /*
1940  * Mark an interface down and notify protocols of
1941  * the transition.
1942  * NOTE: must be called at splnet or eqivalent.
1943  */
1944 void
1945 if_down(struct ifnet *ifp)
1946 {
1947 
1948 	if_unroute(ifp, IFF_UP, AF_UNSPEC);
1949 }
1950 
1951 /*
1952  * Mark an interface up and notify protocols of
1953  * the transition.
1954  * NOTE: must be called at splnet or eqivalent.
1955  */
1956 void
1957 if_up(struct ifnet *ifp)
1958 {
1959 
1960 	if_route(ifp, IFF_UP, AF_UNSPEC);
1961 }
1962 
1963 /*
1964  * Flush an interface queue.
1965  */
1966 void
1967 if_qflush(struct ifnet *ifp)
1968 {
1969 	struct mbuf *m, *n;
1970 	struct ifaltq *ifq;
1971 
1972 	ifq = &ifp->if_snd;
1973 	IFQ_LOCK(ifq);
1974 #ifdef ALTQ
1975 	if (ALTQ_IS_ENABLED(ifq))
1976 		ALTQ_PURGE(ifq);
1977 #endif
1978 	n = ifq->ifq_head;
1979 	while ((m = n) != 0) {
1980 		n = m->m_act;
1981 		m_freem(m);
1982 	}
1983 	ifq->ifq_head = 0;
1984 	ifq->ifq_tail = 0;
1985 	ifq->ifq_len = 0;
1986 	IFQ_UNLOCK(ifq);
1987 }
1988 
1989 /*
1990  * Map interface name to interface structure pointer, with or without
1991  * returning a reference.
1992  */
1993 struct ifnet *
1994 ifunit_ref(const char *name)
1995 {
1996 	struct ifnet *ifp;
1997 
1998 	IFNET_RLOCK_NOSLEEP();
1999 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2000 		if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0 &&
2001 		    !(ifp->if_flags & IFF_DYING))
2002 			break;
2003 	}
2004 	if (ifp != NULL)
2005 		if_ref(ifp);
2006 	IFNET_RUNLOCK_NOSLEEP();
2007 	return (ifp);
2008 }
2009 
2010 struct ifnet *
2011 ifunit(const char *name)
2012 {
2013 	struct ifnet *ifp;
2014 
2015 	IFNET_RLOCK_NOSLEEP();
2016 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2017 		if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0)
2018 			break;
2019 	}
2020 	IFNET_RUNLOCK_NOSLEEP();
2021 	return (ifp);
2022 }
2023 
2024 /*
2025  * Hardware specific interface ioctls.
2026  */
2027 static int
2028 ifhwioctl(u_long cmd, struct ifnet *ifp, caddr_t data, struct thread *td)
2029 {
2030 	struct ifreq *ifr;
2031 	struct ifstat *ifs;
2032 	int error = 0;
2033 	int new_flags, temp_flags;
2034 	size_t namelen, onamelen;
2035 	size_t descrlen;
2036 	char *descrbuf, *odescrbuf;
2037 	char new_name[IFNAMSIZ];
2038 	struct ifaddr *ifa;
2039 	struct sockaddr_dl *sdl;
2040 
2041 	ifr = (struct ifreq *)data;
2042 	switch (cmd) {
2043 	case SIOCGIFINDEX:
2044 		ifr->ifr_index = ifp->if_index;
2045 		break;
2046 
2047 	case SIOCGIFFLAGS:
2048 		temp_flags = ifp->if_flags | ifp->if_drv_flags;
2049 		ifr->ifr_flags = temp_flags & 0xffff;
2050 		ifr->ifr_flagshigh = temp_flags >> 16;
2051 		break;
2052 
2053 	case SIOCGIFCAP:
2054 		ifr->ifr_reqcap = ifp->if_capabilities;
2055 		ifr->ifr_curcap = ifp->if_capenable;
2056 		break;
2057 
2058 #ifdef MAC
2059 	case SIOCGIFMAC:
2060 		error = mac_ifnet_ioctl_get(td->td_ucred, ifr, ifp);
2061 		break;
2062 #endif
2063 
2064 	case SIOCGIFMETRIC:
2065 		ifr->ifr_metric = ifp->if_metric;
2066 		break;
2067 
2068 	case SIOCGIFMTU:
2069 		ifr->ifr_mtu = ifp->if_mtu;
2070 		break;
2071 
2072 	case SIOCGIFPHYS:
2073 		ifr->ifr_phys = ifp->if_physical;
2074 		break;
2075 
2076 	case SIOCGIFDESCR:
2077 		error = 0;
2078 		sx_slock(&ifdescr_sx);
2079 		if (ifp->if_description == NULL)
2080 			error = ENOMSG;
2081 		else {
2082 			/* space for terminating nul */
2083 			descrlen = strlen(ifp->if_description) + 1;
2084 			if (ifr->ifr_buffer.length < descrlen)
2085 				ifr->ifr_buffer.buffer = NULL;
2086 			else
2087 				error = copyout(ifp->if_description,
2088 				    ifr->ifr_buffer.buffer, descrlen);
2089 			ifr->ifr_buffer.length = descrlen;
2090 		}
2091 		sx_sunlock(&ifdescr_sx);
2092 		break;
2093 
2094 	case SIOCSIFDESCR:
2095 		error = priv_check(td, PRIV_NET_SETIFDESCR);
2096 		if (error)
2097 			return (error);
2098 
2099 		/*
2100 		 * Copy only (length-1) bytes to make sure that
2101 		 * if_description is always nul terminated.  The
2102 		 * length parameter is supposed to count the
2103 		 * terminating nul in.
2104 		 */
2105 		if (ifr->ifr_buffer.length > ifdescr_maxlen)
2106 			return (ENAMETOOLONG);
2107 		else if (ifr->ifr_buffer.length == 0)
2108 			descrbuf = NULL;
2109 		else {
2110 			descrbuf = malloc(ifr->ifr_buffer.length, M_IFDESCR,
2111 			    M_WAITOK | M_ZERO);
2112 			error = copyin(ifr->ifr_buffer.buffer, descrbuf,
2113 			    ifr->ifr_buffer.length - 1);
2114 			if (error) {
2115 				free(descrbuf, M_IFDESCR);
2116 				break;
2117 			}
2118 		}
2119 
2120 		sx_xlock(&ifdescr_sx);
2121 		odescrbuf = ifp->if_description;
2122 		ifp->if_description = descrbuf;
2123 		sx_xunlock(&ifdescr_sx);
2124 
2125 		getmicrotime(&ifp->if_lastchange);
2126 		free(odescrbuf, M_IFDESCR);
2127 		break;
2128 
2129 	case SIOCSIFFLAGS:
2130 		error = priv_check(td, PRIV_NET_SETIFFLAGS);
2131 		if (error)
2132 			return (error);
2133 		/*
2134 		 * Currently, no driver owned flags pass the IFF_CANTCHANGE
2135 		 * check, so we don't need special handling here yet.
2136 		 */
2137 		new_flags = (ifr->ifr_flags & 0xffff) |
2138 		    (ifr->ifr_flagshigh << 16);
2139 		if (ifp->if_flags & IFF_SMART) {
2140 			/* Smart drivers twiddle their own routes */
2141 		} else if (ifp->if_flags & IFF_UP &&
2142 		    (new_flags & IFF_UP) == 0) {
2143 			int s = splimp();
2144 			if_down(ifp);
2145 			splx(s);
2146 		} else if (new_flags & IFF_UP &&
2147 		    (ifp->if_flags & IFF_UP) == 0) {
2148 			int s = splimp();
2149 			if_up(ifp);
2150 			splx(s);
2151 		}
2152 		/* See if permanently promiscuous mode bit is about to flip */
2153 		if ((ifp->if_flags ^ new_flags) & IFF_PPROMISC) {
2154 			if (new_flags & IFF_PPROMISC)
2155 				ifp->if_flags |= IFF_PROMISC;
2156 			else if (ifp->if_pcount == 0)
2157 				ifp->if_flags &= ~IFF_PROMISC;
2158 			log(LOG_INFO, "%s: permanently promiscuous mode %s\n",
2159 			    ifp->if_xname,
2160 			    (new_flags & IFF_PPROMISC) ? "enabled" : "disabled");
2161 		}
2162 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
2163 			(new_flags &~ IFF_CANTCHANGE);
2164 		if (ifp->if_ioctl) {
2165 			(void) (*ifp->if_ioctl)(ifp, cmd, data);
2166 		}
2167 		getmicrotime(&ifp->if_lastchange);
2168 		break;
2169 
2170 	case SIOCSIFCAP:
2171 		error = priv_check(td, PRIV_NET_SETIFCAP);
2172 		if (error)
2173 			return (error);
2174 		if (ifp->if_ioctl == NULL)
2175 			return (EOPNOTSUPP);
2176 		if (ifr->ifr_reqcap & ~ifp->if_capabilities)
2177 			return (EINVAL);
2178 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2179 		if (error == 0)
2180 			getmicrotime(&ifp->if_lastchange);
2181 		break;
2182 
2183 #ifdef MAC
2184 	case SIOCSIFMAC:
2185 		error = mac_ifnet_ioctl_set(td->td_ucred, ifr, ifp);
2186 		break;
2187 #endif
2188 
2189 	case SIOCSIFNAME:
2190 		error = priv_check(td, PRIV_NET_SETIFNAME);
2191 		if (error)
2192 			return (error);
2193 		error = copyinstr(ifr->ifr_data, new_name, IFNAMSIZ, NULL);
2194 		if (error != 0)
2195 			return (error);
2196 		if (new_name[0] == '\0')
2197 			return (EINVAL);
2198 		if (ifunit(new_name) != NULL)
2199 			return (EEXIST);
2200 
2201 		/*
2202 		 * XXX: Locking.  Nothing else seems to lock if_flags,
2203 		 * and there are numerous other races with the
2204 		 * ifunit() checks not being atomic with namespace
2205 		 * changes (renames, vmoves, if_attach, etc).
2206 		 */
2207 		ifp->if_flags |= IFF_RENAMING;
2208 
2209 		/* Announce the departure of the interface. */
2210 		rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
2211 		EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
2212 
2213 		log(LOG_INFO, "%s: changing name to '%s'\n",
2214 		    ifp->if_xname, new_name);
2215 
2216 		strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
2217 		ifa = ifp->if_addr;
2218 		IFA_LOCK(ifa);
2219 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
2220 		namelen = strlen(new_name);
2221 		onamelen = sdl->sdl_nlen;
2222 		/*
2223 		 * Move the address if needed.  This is safe because we
2224 		 * allocate space for a name of length IFNAMSIZ when we
2225 		 * create this in if_attach().
2226 		 */
2227 		if (namelen != onamelen) {
2228 			bcopy(sdl->sdl_data + onamelen,
2229 			    sdl->sdl_data + namelen, sdl->sdl_alen);
2230 		}
2231 		bcopy(new_name, sdl->sdl_data, namelen);
2232 		sdl->sdl_nlen = namelen;
2233 		sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
2234 		bzero(sdl->sdl_data, onamelen);
2235 		while (namelen != 0)
2236 			sdl->sdl_data[--namelen] = 0xff;
2237 		IFA_UNLOCK(ifa);
2238 
2239 		EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
2240 		/* Announce the return of the interface. */
2241 		rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
2242 
2243 		ifp->if_flags &= ~IFF_RENAMING;
2244 		break;
2245 
2246 #ifdef VIMAGE
2247 	case SIOCSIFVNET:
2248 		error = priv_check(td, PRIV_NET_SETIFVNET);
2249 		if (error)
2250 			return (error);
2251 		error = if_vmove_loan(td, ifp, ifr->ifr_name, ifr->ifr_jid);
2252 		break;
2253 #endif
2254 
2255 	case SIOCSIFMETRIC:
2256 		error = priv_check(td, PRIV_NET_SETIFMETRIC);
2257 		if (error)
2258 			return (error);
2259 		ifp->if_metric = ifr->ifr_metric;
2260 		getmicrotime(&ifp->if_lastchange);
2261 		break;
2262 
2263 	case SIOCSIFPHYS:
2264 		error = priv_check(td, PRIV_NET_SETIFPHYS);
2265 		if (error)
2266 			return (error);
2267 		if (ifp->if_ioctl == NULL)
2268 			return (EOPNOTSUPP);
2269 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2270 		if (error == 0)
2271 			getmicrotime(&ifp->if_lastchange);
2272 		break;
2273 
2274 	case SIOCSIFMTU:
2275 	{
2276 		u_long oldmtu = ifp->if_mtu;
2277 
2278 		error = priv_check(td, PRIV_NET_SETIFMTU);
2279 		if (error)
2280 			return (error);
2281 		if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
2282 			return (EINVAL);
2283 		if (ifp->if_ioctl == NULL)
2284 			return (EOPNOTSUPP);
2285 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2286 		if (error == 0) {
2287 			getmicrotime(&ifp->if_lastchange);
2288 			rt_ifmsg(ifp);
2289 		}
2290 		/*
2291 		 * If the link MTU changed, do network layer specific procedure.
2292 		 */
2293 		if (ifp->if_mtu != oldmtu) {
2294 #ifdef INET6
2295 			nd6_setmtu(ifp);
2296 #endif
2297 		}
2298 		break;
2299 	}
2300 
2301 	case SIOCADDMULTI:
2302 	case SIOCDELMULTI:
2303 		if (cmd == SIOCADDMULTI)
2304 			error = priv_check(td, PRIV_NET_ADDMULTI);
2305 		else
2306 			error = priv_check(td, PRIV_NET_DELMULTI);
2307 		if (error)
2308 			return (error);
2309 
2310 		/* Don't allow group membership on non-multicast interfaces. */
2311 		if ((ifp->if_flags & IFF_MULTICAST) == 0)
2312 			return (EOPNOTSUPP);
2313 
2314 		/* Don't let users screw up protocols' entries. */
2315 		if (ifr->ifr_addr.sa_family != AF_LINK)
2316 			return (EINVAL);
2317 
2318 		if (cmd == SIOCADDMULTI) {
2319 			struct ifmultiaddr *ifma;
2320 
2321 			/*
2322 			 * Userland is only permitted to join groups once
2323 			 * via the if_addmulti() KPI, because it cannot hold
2324 			 * struct ifmultiaddr * between calls. It may also
2325 			 * lose a race while we check if the membership
2326 			 * already exists.
2327 			 */
2328 			IF_ADDR_LOCK(ifp);
2329 			ifma = if_findmulti(ifp, &ifr->ifr_addr);
2330 			IF_ADDR_UNLOCK(ifp);
2331 			if (ifma != NULL)
2332 				error = EADDRINUSE;
2333 			else
2334 				error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
2335 		} else {
2336 			error = if_delmulti(ifp, &ifr->ifr_addr);
2337 		}
2338 		if (error == 0)
2339 			getmicrotime(&ifp->if_lastchange);
2340 		break;
2341 
2342 	case SIOCSIFPHYADDR:
2343 	case SIOCDIFPHYADDR:
2344 #ifdef INET6
2345 	case SIOCSIFPHYADDR_IN6:
2346 #endif
2347 	case SIOCSLIFPHYADDR:
2348 	case SIOCSIFMEDIA:
2349 	case SIOCSIFGENERIC:
2350 		error = priv_check(td, PRIV_NET_HWIOCTL);
2351 		if (error)
2352 			return (error);
2353 		if (ifp->if_ioctl == NULL)
2354 			return (EOPNOTSUPP);
2355 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2356 		if (error == 0)
2357 			getmicrotime(&ifp->if_lastchange);
2358 		break;
2359 
2360 	case SIOCGIFSTATUS:
2361 		ifs = (struct ifstat *)data;
2362 		ifs->ascii[0] = '\0';
2363 
2364 	case SIOCGIFPSRCADDR:
2365 	case SIOCGIFPDSTADDR:
2366 	case SIOCGLIFPHYADDR:
2367 	case SIOCGIFMEDIA:
2368 	case SIOCGIFGENERIC:
2369 		if (ifp->if_ioctl == NULL)
2370 			return (EOPNOTSUPP);
2371 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2372 		break;
2373 
2374 	case SIOCSIFLLADDR:
2375 		error = priv_check(td, PRIV_NET_SETLLADDR);
2376 		if (error)
2377 			return (error);
2378 		error = if_setlladdr(ifp,
2379 		    ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
2380 		EVENTHANDLER_INVOKE(iflladdr_event, ifp);
2381 		break;
2382 
2383 	case SIOCAIFGROUP:
2384 	{
2385 		struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
2386 
2387 		error = priv_check(td, PRIV_NET_ADDIFGROUP);
2388 		if (error)
2389 			return (error);
2390 		if ((error = if_addgroup(ifp, ifgr->ifgr_group)))
2391 			return (error);
2392 		break;
2393 	}
2394 
2395 	case SIOCGIFGROUP:
2396 		if ((error = if_getgroup((struct ifgroupreq *)ifr, ifp)))
2397 			return (error);
2398 		break;
2399 
2400 	case SIOCDIFGROUP:
2401 	{
2402 		struct ifgroupreq *ifgr = (struct ifgroupreq *)ifr;
2403 
2404 		error = priv_check(td, PRIV_NET_DELIFGROUP);
2405 		if (error)
2406 			return (error);
2407 		if ((error = if_delgroup(ifp, ifgr->ifgr_group)))
2408 			return (error);
2409 		break;
2410 	}
2411 
2412 	default:
2413 		error = ENOIOCTL;
2414 		break;
2415 	}
2416 	return (error);
2417 }
2418 
2419 #ifdef COMPAT_FREEBSD32
2420 struct ifconf32 {
2421 	int32_t	ifc_len;
2422 	union {
2423 		uint32_t	ifcu_buf;
2424 		uint32_t	ifcu_req;
2425 	} ifc_ifcu;
2426 };
2427 #define	SIOCGIFCONF32	_IOWR('i', 36, struct ifconf32)
2428 #endif
2429 
2430 /*
2431  * Interface ioctls.
2432  */
2433 int
2434 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct thread *td)
2435 {
2436 	struct ifnet *ifp;
2437 	struct ifreq *ifr;
2438 	int error;
2439 	int oif_flags;
2440 
2441 	switch (cmd) {
2442 	case SIOCGIFCONF:
2443 	case OSIOCGIFCONF:
2444 		return (ifconf(cmd, data));
2445 
2446 #ifdef COMPAT_FREEBSD32
2447 	case SIOCGIFCONF32:
2448 		{
2449 			struct ifconf32 *ifc32;
2450 			struct ifconf ifc;
2451 
2452 			ifc32 = (struct ifconf32 *)data;
2453 			ifc.ifc_len = ifc32->ifc_len;
2454 			ifc.ifc_buf = PTRIN(ifc32->ifc_buf);
2455 
2456 			return (ifconf(SIOCGIFCONF, (void *)&ifc));
2457 		}
2458 #endif
2459 	}
2460 	ifr = (struct ifreq *)data;
2461 
2462 	switch (cmd) {
2463 #ifdef VIMAGE
2464 	case SIOCSIFRVNET:
2465 		error = priv_check(td, PRIV_NET_SETIFVNET);
2466 		if (error)
2467 			return (error);
2468 		return (if_vmove_reclaim(td, ifr->ifr_name, ifr->ifr_jid));
2469 #endif
2470 	case SIOCIFCREATE:
2471 	case SIOCIFCREATE2:
2472 		error = priv_check(td, PRIV_NET_IFCREATE);
2473 		if (error)
2474 			return (error);
2475 		return (if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name),
2476 			cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL));
2477 	case SIOCIFDESTROY:
2478 		error = priv_check(td, PRIV_NET_IFDESTROY);
2479 		if (error)
2480 			return (error);
2481 		return if_clone_destroy(ifr->ifr_name);
2482 
2483 	case SIOCIFGCLONERS:
2484 		return (if_clone_list((struct if_clonereq *)data));
2485 	case SIOCGIFGMEMB:
2486 		return (if_getgroupmembers((struct ifgroupreq *)data));
2487 	}
2488 
2489 	ifp = ifunit_ref(ifr->ifr_name);
2490 	if (ifp == NULL)
2491 		return (ENXIO);
2492 
2493 	error = ifhwioctl(cmd, ifp, data, td);
2494 	if (error != ENOIOCTL) {
2495 		if_rele(ifp);
2496 		return (error);
2497 	}
2498 
2499 	oif_flags = ifp->if_flags;
2500 	if (so->so_proto == NULL) {
2501 		if_rele(ifp);
2502 		return (EOPNOTSUPP);
2503 	}
2504 #ifndef COMPAT_43
2505 	error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
2506 								 data,
2507 								 ifp, td));
2508 	if (error == EOPNOTSUPP && ifp != NULL && ifp->if_ioctl != NULL)
2509 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2510 #else
2511 	{
2512 		u_long ocmd = cmd;
2513 
2514 		switch (cmd) {
2515 
2516 		case SIOCSIFDSTADDR:
2517 		case SIOCSIFADDR:
2518 		case SIOCSIFBRDADDR:
2519 		case SIOCSIFNETMASK:
2520 #if BYTE_ORDER != BIG_ENDIAN
2521 			if (ifr->ifr_addr.sa_family == 0 &&
2522 			    ifr->ifr_addr.sa_len < 16) {
2523 				ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
2524 				ifr->ifr_addr.sa_len = 16;
2525 			}
2526 #else
2527 			if (ifr->ifr_addr.sa_len == 0)
2528 				ifr->ifr_addr.sa_len = 16;
2529 #endif
2530 			break;
2531 
2532 		case OSIOCGIFADDR:
2533 			cmd = SIOCGIFADDR;
2534 			break;
2535 
2536 		case OSIOCGIFDSTADDR:
2537 			cmd = SIOCGIFDSTADDR;
2538 			break;
2539 
2540 		case OSIOCGIFBRDADDR:
2541 			cmd = SIOCGIFBRDADDR;
2542 			break;
2543 
2544 		case OSIOCGIFNETMASK:
2545 			cmd = SIOCGIFNETMASK;
2546 		}
2547 		error =  ((*so->so_proto->pr_usrreqs->pru_control)(so,
2548 								   cmd,
2549 								   data,
2550 								   ifp, td));
2551 		if (error == EOPNOTSUPP && ifp != NULL &&
2552 		    ifp->if_ioctl != NULL)
2553 			error = (*ifp->if_ioctl)(ifp, cmd, data);
2554 		switch (ocmd) {
2555 
2556 		case OSIOCGIFADDR:
2557 		case OSIOCGIFDSTADDR:
2558 		case OSIOCGIFBRDADDR:
2559 		case OSIOCGIFNETMASK:
2560 			*(u_short *)&ifr->ifr_addr = ifr->ifr_addr.sa_family;
2561 
2562 		}
2563 	}
2564 #endif /* COMPAT_43 */
2565 
2566 	if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
2567 #ifdef INET6
2568 		if (ifp->if_flags & IFF_UP) {
2569 			int s = splimp();
2570 			in6_if_up(ifp);
2571 			splx(s);
2572 		}
2573 #endif
2574 	}
2575 	if_rele(ifp);
2576 	return (error);
2577 }
2578 
2579 /*
2580  * The code common to handling reference counted flags,
2581  * e.g., in ifpromisc() and if_allmulti().
2582  * The "pflag" argument can specify a permanent mode flag to check,
2583  * such as IFF_PPROMISC for promiscuous mode; should be 0 if none.
2584  *
2585  * Only to be used on stack-owned flags, not driver-owned flags.
2586  */
2587 static int
2588 if_setflag(struct ifnet *ifp, int flag, int pflag, int *refcount, int onswitch)
2589 {
2590 	struct ifreq ifr;
2591 	int error;
2592 	int oldflags, oldcount;
2593 
2594 	/* Sanity checks to catch programming errors */
2595 	KASSERT((flag & (IFF_DRV_OACTIVE|IFF_DRV_RUNNING)) == 0,
2596 	    ("%s: setting driver-owned flag %d", __func__, flag));
2597 
2598 	if (onswitch)
2599 		KASSERT(*refcount >= 0,
2600 		    ("%s: increment negative refcount %d for flag %d",
2601 		    __func__, *refcount, flag));
2602 	else
2603 		KASSERT(*refcount > 0,
2604 		    ("%s: decrement non-positive refcount %d for flag %d",
2605 		    __func__, *refcount, flag));
2606 
2607 	/* In case this mode is permanent, just touch refcount */
2608 	if (ifp->if_flags & pflag) {
2609 		*refcount += onswitch ? 1 : -1;
2610 		return (0);
2611 	}
2612 
2613 	/* Save ifnet parameters for if_ioctl() may fail */
2614 	oldcount = *refcount;
2615 	oldflags = ifp->if_flags;
2616 
2617 	/*
2618 	 * See if we aren't the only and touching refcount is enough.
2619 	 * Actually toggle interface flag if we are the first or last.
2620 	 */
2621 	if (onswitch) {
2622 		if ((*refcount)++)
2623 			return (0);
2624 		ifp->if_flags |= flag;
2625 	} else {
2626 		if (--(*refcount))
2627 			return (0);
2628 		ifp->if_flags &= ~flag;
2629 	}
2630 
2631 	/* Call down the driver since we've changed interface flags */
2632 	if (ifp->if_ioctl == NULL) {
2633 		error = EOPNOTSUPP;
2634 		goto recover;
2635 	}
2636 	ifr.ifr_flags = ifp->if_flags & 0xffff;
2637 	ifr.ifr_flagshigh = ifp->if_flags >> 16;
2638 	error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
2639 	if (error)
2640 		goto recover;
2641 	/* Notify userland that interface flags have changed */
2642 	rt_ifmsg(ifp);
2643 	return (0);
2644 
2645 recover:
2646 	/* Recover after driver error */
2647 	*refcount = oldcount;
2648 	ifp->if_flags = oldflags;
2649 	return (error);
2650 }
2651 
2652 /*
2653  * Set/clear promiscuous mode on interface ifp based on the truth value
2654  * of pswitch.  The calls are reference counted so that only the first
2655  * "on" request actually has an effect, as does the final "off" request.
2656  * Results are undefined if the "off" and "on" requests are not matched.
2657  */
2658 int
2659 ifpromisc(struct ifnet *ifp, int pswitch)
2660 {
2661 	int error;
2662 	int oldflags = ifp->if_flags;
2663 
2664 	error = if_setflag(ifp, IFF_PROMISC, IFF_PPROMISC,
2665 			   &ifp->if_pcount, pswitch);
2666 	/* If promiscuous mode status has changed, log a message */
2667 	if (error == 0 && ((ifp->if_flags ^ oldflags) & IFF_PROMISC))
2668 		log(LOG_INFO, "%s: promiscuous mode %s\n",
2669 		    ifp->if_xname,
2670 		    (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
2671 	return (error);
2672 }
2673 
2674 /*
2675  * Return interface configuration
2676  * of system.  List may be used
2677  * in later ioctl's (above) to get
2678  * other information.
2679  */
2680 /*ARGSUSED*/
2681 static int
2682 ifconf(u_long cmd, caddr_t data)
2683 {
2684 	struct ifconf *ifc = (struct ifconf *)data;
2685 	struct ifnet *ifp;
2686 	struct ifaddr *ifa;
2687 	struct ifreq ifr;
2688 	struct sbuf *sb;
2689 	int error, full = 0, valid_len, max_len;
2690 
2691 	/* Limit initial buffer size to MAXPHYS to avoid DoS from userspace. */
2692 	max_len = MAXPHYS - 1;
2693 
2694 	/* Prevent hostile input from being able to crash the system */
2695 	if (ifc->ifc_len <= 0)
2696 		return (EINVAL);
2697 
2698 again:
2699 	if (ifc->ifc_len <= max_len) {
2700 		max_len = ifc->ifc_len;
2701 		full = 1;
2702 	}
2703 	sb = sbuf_new(NULL, NULL, max_len + 1, SBUF_FIXEDLEN);
2704 	max_len = 0;
2705 	valid_len = 0;
2706 
2707 	IFNET_RLOCK();
2708 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2709 		int addrs;
2710 
2711 		/*
2712 		 * Zero the ifr_name buffer to make sure we don't
2713 		 * disclose the contents of the stack.
2714 		 */
2715 		memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
2716 
2717 		if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
2718 		    >= sizeof(ifr.ifr_name)) {
2719 			sbuf_delete(sb);
2720 			IFNET_RUNLOCK();
2721 			return (ENAMETOOLONG);
2722 		}
2723 
2724 		addrs = 0;
2725 		IF_ADDR_LOCK(ifp);
2726 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2727 			struct sockaddr *sa = ifa->ifa_addr;
2728 
2729 			if (prison_if(curthread->td_ucred, sa) != 0)
2730 				continue;
2731 			addrs++;
2732 #ifdef COMPAT_43
2733 			if (cmd == OSIOCGIFCONF) {
2734 				struct osockaddr *osa =
2735 					 (struct osockaddr *)&ifr.ifr_addr;
2736 				ifr.ifr_addr = *sa;
2737 				osa->sa_family = sa->sa_family;
2738 				sbuf_bcat(sb, &ifr, sizeof(ifr));
2739 				max_len += sizeof(ifr);
2740 			} else
2741 #endif
2742 			if (sa->sa_len <= sizeof(*sa)) {
2743 				ifr.ifr_addr = *sa;
2744 				sbuf_bcat(sb, &ifr, sizeof(ifr));
2745 				max_len += sizeof(ifr);
2746 			} else {
2747 				sbuf_bcat(sb, &ifr,
2748 				    offsetof(struct ifreq, ifr_addr));
2749 				max_len += offsetof(struct ifreq, ifr_addr);
2750 				sbuf_bcat(sb, sa, sa->sa_len);
2751 				max_len += sa->sa_len;
2752 			}
2753 
2754 			if (sbuf_error(sb) == 0)
2755 				valid_len = sbuf_len(sb);
2756 		}
2757 		IF_ADDR_UNLOCK(ifp);
2758 		if (addrs == 0) {
2759 			bzero((caddr_t)&ifr.ifr_addr, sizeof(ifr.ifr_addr));
2760 			sbuf_bcat(sb, &ifr, sizeof(ifr));
2761 			max_len += sizeof(ifr);
2762 
2763 			if (sbuf_error(sb) == 0)
2764 				valid_len = sbuf_len(sb);
2765 		}
2766 	}
2767 	IFNET_RUNLOCK();
2768 
2769 	/*
2770 	 * If we didn't allocate enough space (uncommon), try again.  If
2771 	 * we have already allocated as much space as we are allowed,
2772 	 * return what we've got.
2773 	 */
2774 	if (valid_len != max_len && !full) {
2775 		sbuf_delete(sb);
2776 		goto again;
2777 	}
2778 
2779 	ifc->ifc_len = valid_len;
2780 	sbuf_finish(sb);
2781 	error = copyout(sbuf_data(sb), ifc->ifc_req, ifc->ifc_len);
2782 	sbuf_delete(sb);
2783 	return (error);
2784 }
2785 
2786 /*
2787  * Just like ifpromisc(), but for all-multicast-reception mode.
2788  */
2789 int
2790 if_allmulti(struct ifnet *ifp, int onswitch)
2791 {
2792 
2793 	return (if_setflag(ifp, IFF_ALLMULTI, 0, &ifp->if_amcount, onswitch));
2794 }
2795 
2796 struct ifmultiaddr *
2797 if_findmulti(struct ifnet *ifp, struct sockaddr *sa)
2798 {
2799 	struct ifmultiaddr *ifma;
2800 
2801 	IF_ADDR_LOCK_ASSERT(ifp);
2802 
2803 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2804 		if (sa->sa_family == AF_LINK) {
2805 			if (sa_dl_equal(ifma->ifma_addr, sa))
2806 				break;
2807 		} else {
2808 			if (sa_equal(ifma->ifma_addr, sa))
2809 				break;
2810 		}
2811 	}
2812 
2813 	return ifma;
2814 }
2815 
2816 /*
2817  * Allocate a new ifmultiaddr and initialize based on passed arguments.  We
2818  * make copies of passed sockaddrs.  The ifmultiaddr will not be added to
2819  * the ifnet multicast address list here, so the caller must do that and
2820  * other setup work (such as notifying the device driver).  The reference
2821  * count is initialized to 1.
2822  */
2823 static struct ifmultiaddr *
2824 if_allocmulti(struct ifnet *ifp, struct sockaddr *sa, struct sockaddr *llsa,
2825     int mflags)
2826 {
2827 	struct ifmultiaddr *ifma;
2828 	struct sockaddr *dupsa;
2829 
2830 	ifma = malloc(sizeof *ifma, M_IFMADDR, mflags |
2831 	    M_ZERO);
2832 	if (ifma == NULL)
2833 		return (NULL);
2834 
2835 	dupsa = malloc(sa->sa_len, M_IFMADDR, mflags);
2836 	if (dupsa == NULL) {
2837 		free(ifma, M_IFMADDR);
2838 		return (NULL);
2839 	}
2840 	bcopy(sa, dupsa, sa->sa_len);
2841 	ifma->ifma_addr = dupsa;
2842 
2843 	ifma->ifma_ifp = ifp;
2844 	ifma->ifma_refcount = 1;
2845 	ifma->ifma_protospec = NULL;
2846 
2847 	if (llsa == NULL) {
2848 		ifma->ifma_lladdr = NULL;
2849 		return (ifma);
2850 	}
2851 
2852 	dupsa = malloc(llsa->sa_len, M_IFMADDR, mflags);
2853 	if (dupsa == NULL) {
2854 		free(ifma->ifma_addr, M_IFMADDR);
2855 		free(ifma, M_IFMADDR);
2856 		return (NULL);
2857 	}
2858 	bcopy(llsa, dupsa, llsa->sa_len);
2859 	ifma->ifma_lladdr = dupsa;
2860 
2861 	return (ifma);
2862 }
2863 
2864 /*
2865  * if_freemulti: free ifmultiaddr structure and possibly attached related
2866  * addresses.  The caller is responsible for implementing reference
2867  * counting, notifying the driver, handling routing messages, and releasing
2868  * any dependent link layer state.
2869  */
2870 static void
2871 if_freemulti(struct ifmultiaddr *ifma)
2872 {
2873 
2874 	KASSERT(ifma->ifma_refcount == 0, ("if_freemulti: refcount %d",
2875 	    ifma->ifma_refcount));
2876 	KASSERT(ifma->ifma_protospec == NULL,
2877 	    ("if_freemulti: protospec not NULL"));
2878 
2879 	if (ifma->ifma_lladdr != NULL)
2880 		free(ifma->ifma_lladdr, M_IFMADDR);
2881 	free(ifma->ifma_addr, M_IFMADDR);
2882 	free(ifma, M_IFMADDR);
2883 }
2884 
2885 /*
2886  * Register an additional multicast address with a network interface.
2887  *
2888  * - If the address is already present, bump the reference count on the
2889  *   address and return.
2890  * - If the address is not link-layer, look up a link layer address.
2891  * - Allocate address structures for one or both addresses, and attach to the
2892  *   multicast address list on the interface.  If automatically adding a link
2893  *   layer address, the protocol address will own a reference to the link
2894  *   layer address, to be freed when it is freed.
2895  * - Notify the network device driver of an addition to the multicast address
2896  *   list.
2897  *
2898  * 'sa' points to caller-owned memory with the desired multicast address.
2899  *
2900  * 'retifma' will be used to return a pointer to the resulting multicast
2901  * address reference, if desired.
2902  */
2903 int
2904 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
2905     struct ifmultiaddr **retifma)
2906 {
2907 	struct ifmultiaddr *ifma, *ll_ifma;
2908 	struct sockaddr *llsa;
2909 	int error;
2910 
2911 	/*
2912 	 * If the address is already present, return a new reference to it;
2913 	 * otherwise, allocate storage and set up a new address.
2914 	 */
2915 	IF_ADDR_LOCK(ifp);
2916 	ifma = if_findmulti(ifp, sa);
2917 	if (ifma != NULL) {
2918 		ifma->ifma_refcount++;
2919 		if (retifma != NULL)
2920 			*retifma = ifma;
2921 		IF_ADDR_UNLOCK(ifp);
2922 		return (0);
2923 	}
2924 
2925 	/*
2926 	 * The address isn't already present; resolve the protocol address
2927 	 * into a link layer address, and then look that up, bump its
2928 	 * refcount or allocate an ifma for that also.  If 'llsa' was
2929 	 * returned, we will need to free it later.
2930 	 */
2931 	llsa = NULL;
2932 	ll_ifma = NULL;
2933 	if (ifp->if_resolvemulti != NULL) {
2934 		error = ifp->if_resolvemulti(ifp, &llsa, sa);
2935 		if (error)
2936 			goto unlock_out;
2937 	}
2938 
2939 	/*
2940 	 * Allocate the new address.  Don't hook it up yet, as we may also
2941 	 * need to allocate a link layer multicast address.
2942 	 */
2943 	ifma = if_allocmulti(ifp, sa, llsa, M_NOWAIT);
2944 	if (ifma == NULL) {
2945 		error = ENOMEM;
2946 		goto free_llsa_out;
2947 	}
2948 
2949 	/*
2950 	 * If a link layer address is found, we'll need to see if it's
2951 	 * already present in the address list, or allocate is as well.
2952 	 * When this block finishes, the link layer address will be on the
2953 	 * list.
2954 	 */
2955 	if (llsa != NULL) {
2956 		ll_ifma = if_findmulti(ifp, llsa);
2957 		if (ll_ifma == NULL) {
2958 			ll_ifma = if_allocmulti(ifp, llsa, NULL, M_NOWAIT);
2959 			if (ll_ifma == NULL) {
2960 				--ifma->ifma_refcount;
2961 				if_freemulti(ifma);
2962 				error = ENOMEM;
2963 				goto free_llsa_out;
2964 			}
2965 			TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ll_ifma,
2966 			    ifma_link);
2967 		} else
2968 			ll_ifma->ifma_refcount++;
2969 		ifma->ifma_llifma = ll_ifma;
2970 	}
2971 
2972 	/*
2973 	 * We now have a new multicast address, ifma, and possibly a new or
2974 	 * referenced link layer address.  Add the primary address to the
2975 	 * ifnet address list.
2976 	 */
2977 	TAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
2978 
2979 	if (retifma != NULL)
2980 		*retifma = ifma;
2981 
2982 	/*
2983 	 * Must generate the message while holding the lock so that 'ifma'
2984 	 * pointer is still valid.
2985 	 */
2986 	rt_newmaddrmsg(RTM_NEWMADDR, ifma);
2987 	IF_ADDR_UNLOCK(ifp);
2988 
2989 	/*
2990 	 * We are certain we have added something, so call down to the
2991 	 * interface to let them know about it.
2992 	 */
2993 	if (ifp->if_ioctl != NULL) {
2994 		(void) (*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
2995 	}
2996 
2997 	if (llsa != NULL)
2998 		free(llsa, M_IFMADDR);
2999 
3000 	return (0);
3001 
3002 free_llsa_out:
3003 	if (llsa != NULL)
3004 		free(llsa, M_IFMADDR);
3005 
3006 unlock_out:
3007 	IF_ADDR_UNLOCK(ifp);
3008 	return (error);
3009 }
3010 
3011 /*
3012  * Delete a multicast group membership by network-layer group address.
3013  *
3014  * Returns ENOENT if the entry could not be found. If ifp no longer
3015  * exists, results are undefined. This entry point should only be used
3016  * from subsystems which do appropriate locking to hold ifp for the
3017  * duration of the call.
3018  * Network-layer protocol domains must use if_delmulti_ifma().
3019  */
3020 int
3021 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
3022 {
3023 	struct ifmultiaddr *ifma;
3024 	int lastref;
3025 #ifdef INVARIANTS
3026 	struct ifnet *oifp;
3027 
3028 	IFNET_RLOCK_NOSLEEP();
3029 	TAILQ_FOREACH(oifp, &V_ifnet, if_link)
3030 		if (ifp == oifp)
3031 			break;
3032 	if (ifp != oifp)
3033 		ifp = NULL;
3034 	IFNET_RUNLOCK_NOSLEEP();
3035 
3036 	KASSERT(ifp != NULL, ("%s: ifnet went away", __func__));
3037 #endif
3038 	if (ifp == NULL)
3039 		return (ENOENT);
3040 
3041 	IF_ADDR_LOCK(ifp);
3042 	lastref = 0;
3043 	ifma = if_findmulti(ifp, sa);
3044 	if (ifma != NULL)
3045 		lastref = if_delmulti_locked(ifp, ifma, 0);
3046 	IF_ADDR_UNLOCK(ifp);
3047 
3048 	if (ifma == NULL)
3049 		return (ENOENT);
3050 
3051 	if (lastref && ifp->if_ioctl != NULL) {
3052 		(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3053 	}
3054 
3055 	return (0);
3056 }
3057 
3058 /*
3059  * Delete all multicast group membership for an interface.
3060  * Should be used to quickly flush all multicast filters.
3061  */
3062 void
3063 if_delallmulti(struct ifnet *ifp)
3064 {
3065 	struct ifmultiaddr *ifma;
3066 	struct ifmultiaddr *next;
3067 
3068 	IF_ADDR_LOCK(ifp);
3069 	TAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
3070 		if_delmulti_locked(ifp, ifma, 0);
3071 	IF_ADDR_UNLOCK(ifp);
3072 }
3073 
3074 /*
3075  * Delete a multicast group membership by group membership pointer.
3076  * Network-layer protocol domains must use this routine.
3077  *
3078  * It is safe to call this routine if the ifp disappeared.
3079  */
3080 void
3081 if_delmulti_ifma(struct ifmultiaddr *ifma)
3082 {
3083 	struct ifnet *ifp;
3084 	int lastref;
3085 
3086 	ifp = ifma->ifma_ifp;
3087 #ifdef DIAGNOSTIC
3088 	if (ifp == NULL) {
3089 		printf("%s: ifma_ifp seems to be detached\n", __func__);
3090 	} else {
3091 		struct ifnet *oifp;
3092 
3093 		IFNET_RLOCK_NOSLEEP();
3094 		TAILQ_FOREACH(oifp, &V_ifnet, if_link)
3095 			if (ifp == oifp)
3096 				break;
3097 		if (ifp != oifp) {
3098 			printf("%s: ifnet %p disappeared\n", __func__, ifp);
3099 			ifp = NULL;
3100 		}
3101 		IFNET_RUNLOCK_NOSLEEP();
3102 	}
3103 #endif
3104 	/*
3105 	 * If and only if the ifnet instance exists: Acquire the address lock.
3106 	 */
3107 	if (ifp != NULL)
3108 		IF_ADDR_LOCK(ifp);
3109 
3110 	lastref = if_delmulti_locked(ifp, ifma, 0);
3111 
3112 	if (ifp != NULL) {
3113 		/*
3114 		 * If and only if the ifnet instance exists:
3115 		 *  Release the address lock.
3116 		 *  If the group was left: update the hardware hash filter.
3117 		 */
3118 		IF_ADDR_UNLOCK(ifp);
3119 		if (lastref && ifp->if_ioctl != NULL) {
3120 			(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3121 		}
3122 	}
3123 }
3124 
3125 /*
3126  * Perform deletion of network-layer and/or link-layer multicast address.
3127  *
3128  * Return 0 if the reference count was decremented.
3129  * Return 1 if the final reference was released, indicating that the
3130  * hardware hash filter should be reprogrammed.
3131  */
3132 static int
3133 if_delmulti_locked(struct ifnet *ifp, struct ifmultiaddr *ifma, int detaching)
3134 {
3135 	struct ifmultiaddr *ll_ifma;
3136 
3137 	if (ifp != NULL && ifma->ifma_ifp != NULL) {
3138 		KASSERT(ifma->ifma_ifp == ifp,
3139 		    ("%s: inconsistent ifp %p", __func__, ifp));
3140 		IF_ADDR_LOCK_ASSERT(ifp);
3141 	}
3142 
3143 	ifp = ifma->ifma_ifp;
3144 
3145 	/*
3146 	 * If the ifnet is detaching, null out references to ifnet,
3147 	 * so that upper protocol layers will notice, and not attempt
3148 	 * to obtain locks for an ifnet which no longer exists. The
3149 	 * routing socket announcement must happen before the ifnet
3150 	 * instance is detached from the system.
3151 	 */
3152 	if (detaching) {
3153 #ifdef DIAGNOSTIC
3154 		printf("%s: detaching ifnet instance %p\n", __func__, ifp);
3155 #endif
3156 		/*
3157 		 * ifp may already be nulled out if we are being reentered
3158 		 * to delete the ll_ifma.
3159 		 */
3160 		if (ifp != NULL) {
3161 			rt_newmaddrmsg(RTM_DELMADDR, ifma);
3162 			ifma->ifma_ifp = NULL;
3163 		}
3164 	}
3165 
3166 	if (--ifma->ifma_refcount > 0)
3167 		return 0;
3168 
3169 	/*
3170 	 * If this ifma is a network-layer ifma, a link-layer ifma may
3171 	 * have been associated with it. Release it first if so.
3172 	 */
3173 	ll_ifma = ifma->ifma_llifma;
3174 	if (ll_ifma != NULL) {
3175 		KASSERT(ifma->ifma_lladdr != NULL,
3176 		    ("%s: llifma w/o lladdr", __func__));
3177 		if (detaching)
3178 			ll_ifma->ifma_ifp = NULL;	/* XXX */
3179 		if (--ll_ifma->ifma_refcount == 0) {
3180 			if (ifp != NULL) {
3181 				TAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma,
3182 				    ifma_link);
3183 			}
3184 			if_freemulti(ll_ifma);
3185 		}
3186 	}
3187 
3188 	if (ifp != NULL)
3189 		TAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifma_link);
3190 
3191 	if_freemulti(ifma);
3192 
3193 	/*
3194 	 * The last reference to this instance of struct ifmultiaddr
3195 	 * was released; the hardware should be notified of this change.
3196 	 */
3197 	return 1;
3198 }
3199 
3200 /*
3201  * Set the link layer address on an interface.
3202  *
3203  * At this time we only support certain types of interfaces,
3204  * and we don't allow the length of the address to change.
3205  */
3206 int
3207 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
3208 {
3209 	struct sockaddr_dl *sdl;
3210 	struct ifaddr *ifa;
3211 	struct ifreq ifr;
3212 
3213 	IF_ADDR_LOCK(ifp);
3214 	ifa = ifp->if_addr;
3215 	if (ifa == NULL) {
3216 		IF_ADDR_UNLOCK(ifp);
3217 		return (EINVAL);
3218 	}
3219 	ifa_ref(ifa);
3220 	IF_ADDR_UNLOCK(ifp);
3221 	sdl = (struct sockaddr_dl *)ifa->ifa_addr;
3222 	if (sdl == NULL) {
3223 		ifa_free(ifa);
3224 		return (EINVAL);
3225 	}
3226 	if (len != sdl->sdl_alen) {	/* don't allow length to change */
3227 		ifa_free(ifa);
3228 		return (EINVAL);
3229 	}
3230 	switch (ifp->if_type) {
3231 	case IFT_ETHER:
3232 	case IFT_FDDI:
3233 	case IFT_XETHER:
3234 	case IFT_ISO88025:
3235 	case IFT_L2VLAN:
3236 	case IFT_BRIDGE:
3237 	case IFT_ARCNET:
3238 	case IFT_IEEE8023ADLAG:
3239 	case IFT_IEEE80211:
3240 		bcopy(lladdr, LLADDR(sdl), len);
3241 		ifa_free(ifa);
3242 		break;
3243 	default:
3244 		ifa_free(ifa);
3245 		return (ENODEV);
3246 	}
3247 
3248 	/*
3249 	 * If the interface is already up, we need
3250 	 * to re-init it in order to reprogram its
3251 	 * address filter.
3252 	 */
3253 	if ((ifp->if_flags & IFF_UP) != 0) {
3254 		if (ifp->if_ioctl) {
3255 			ifp->if_flags &= ~IFF_UP;
3256 			ifr.ifr_flags = ifp->if_flags & 0xffff;
3257 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
3258 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3259 			ifp->if_flags |= IFF_UP;
3260 			ifr.ifr_flags = ifp->if_flags & 0xffff;
3261 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
3262 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3263 		}
3264 #ifdef INET
3265 		/*
3266 		 * Also send gratuitous ARPs to notify other nodes about
3267 		 * the address change.
3268 		 */
3269 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
3270 			if (ifa->ifa_addr->sa_family == AF_INET)
3271 				arp_ifinit(ifp, ifa);
3272 		}
3273 #endif
3274 	}
3275 	return (0);
3276 }
3277 
3278 /*
3279  * The name argument must be a pointer to storage which will last as
3280  * long as the interface does.  For physical devices, the result of
3281  * device_get_name(dev) is a good choice and for pseudo-devices a
3282  * static string works well.
3283  */
3284 void
3285 if_initname(struct ifnet *ifp, const char *name, int unit)
3286 {
3287 	ifp->if_dname = name;
3288 	ifp->if_dunit = unit;
3289 	if (unit != IF_DUNIT_NONE)
3290 		snprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
3291 	else
3292 		strlcpy(ifp->if_xname, name, IFNAMSIZ);
3293 }
3294 
3295 int
3296 if_printf(struct ifnet *ifp, const char * fmt, ...)
3297 {
3298 	va_list ap;
3299 	int retval;
3300 
3301 	retval = printf("%s: ", ifp->if_xname);
3302 	va_start(ap, fmt);
3303 	retval += vprintf(fmt, ap);
3304 	va_end(ap);
3305 	return (retval);
3306 }
3307 
3308 void
3309 if_start(struct ifnet *ifp)
3310 {
3311 
3312 	(*(ifp)->if_start)(ifp);
3313 }
3314 
3315 /*
3316  * Backwards compatibility interface for drivers
3317  * that have not implemented it
3318  */
3319 static int
3320 if_transmit(struct ifnet *ifp, struct mbuf *m)
3321 {
3322 	int error;
3323 
3324 	IFQ_HANDOFF(ifp, m, error);
3325 	return (error);
3326 }
3327 
3328 int
3329 if_handoff(struct ifqueue *ifq, struct mbuf *m, struct ifnet *ifp, int adjust)
3330 {
3331 	int active = 0;
3332 
3333 	IF_LOCK(ifq);
3334 	if (_IF_QFULL(ifq)) {
3335 		_IF_DROP(ifq);
3336 		IF_UNLOCK(ifq);
3337 		m_freem(m);
3338 		return (0);
3339 	}
3340 	if (ifp != NULL) {
3341 		ifp->if_obytes += m->m_pkthdr.len + adjust;
3342 		if (m->m_flags & (M_BCAST|M_MCAST))
3343 			ifp->if_omcasts++;
3344 		active = ifp->if_drv_flags & IFF_DRV_OACTIVE;
3345 	}
3346 	_IF_ENQUEUE(ifq, m);
3347 	IF_UNLOCK(ifq);
3348 	if (ifp != NULL && !active)
3349 		(*(ifp)->if_start)(ifp);
3350 	return (1);
3351 }
3352 
3353 void
3354 if_register_com_alloc(u_char type,
3355     if_com_alloc_t *a, if_com_free_t *f)
3356 {
3357 
3358 	KASSERT(if_com_alloc[type] == NULL,
3359 	    ("if_register_com_alloc: %d already registered", type));
3360 	KASSERT(if_com_free[type] == NULL,
3361 	    ("if_register_com_alloc: %d free already registered", type));
3362 
3363 	if_com_alloc[type] = a;
3364 	if_com_free[type] = f;
3365 }
3366 
3367 void
3368 if_deregister_com_alloc(u_char type)
3369 {
3370 
3371 	KASSERT(if_com_alloc[type] != NULL,
3372 	    ("if_deregister_com_alloc: %d not registered", type));
3373 	KASSERT(if_com_free[type] != NULL,
3374 	    ("if_deregister_com_alloc: %d free not registered", type));
3375 	if_com_alloc[type] = NULL;
3376 	if_com_free[type] = NULL;
3377 }
3378