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