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