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