xref: /freebsd/sys/net/if.c (revision 48c779cdecb5f803e5fe5d761987e976ca9609db)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1986, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)if.c	8.5 (Berkeley) 1/9/95
32  * $FreeBSD$
33  */
34 
35 #include "opt_inet6.h"
36 #include "opt_inet.h"
37 
38 #include <sys/param.h>
39 #include <sys/conf.h>
40 #include <sys/eventhandler.h>
41 #include <sys/malloc.h>
42 #include <sys/domainset.h>
43 #include <sys/sbuf.h>
44 #include <sys/bus.h>
45 #include <sys/epoch.h>
46 #include <sys/mbuf.h>
47 #include <sys/systm.h>
48 #include <sys/priv.h>
49 #include <sys/proc.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/protosw.h>
53 #include <sys/kernel.h>
54 #include <sys/lock.h>
55 #include <sys/refcount.h>
56 #include <sys/module.h>
57 #include <sys/rwlock.h>
58 #include <sys/sockio.h>
59 #include <sys/syslog.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysent.h>
62 #include <sys/taskqueue.h>
63 #include <sys/domain.h>
64 #include <sys/jail.h>
65 #include <sys/priv.h>
66 
67 #include <machine/stdarg.h>
68 #include <vm/uma.h>
69 
70 #include <net/bpf.h>
71 #include <net/ethernet.h>
72 #include <net/if.h>
73 #include <net/if_arp.h>
74 #include <net/if_clone.h>
75 #include <net/if_dl.h>
76 #include <net/if_types.h>
77 #include <net/if_var.h>
78 #include <net/if_media.h>
79 #include <net/if_vlan_var.h>
80 #include <net/radix.h>
81 #include <net/route.h>
82 #include <net/vnet.h>
83 
84 #if defined(INET) || defined(INET6)
85 #include <net/ethernet.h>
86 #include <netinet/in.h>
87 #include <netinet/in_var.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_carp.h>
90 #ifdef INET
91 #include <net/debugnet.h>
92 #include <netinet/if_ether.h>
93 #endif /* INET */
94 #ifdef INET6
95 #include <netinet6/in6_var.h>
96 #include <netinet6/in6_ifattach.h>
97 #endif /* INET6 */
98 #endif /* INET || INET6 */
99 
100 #include <security/mac/mac_framework.h>
101 
102 /*
103  * Consumers of struct ifreq such as tcpdump assume no pad between ifr_name
104  * and ifr_ifru when it is used in SIOCGIFCONF.
105  */
106 _Static_assert(sizeof(((struct ifreq *)0)->ifr_name) ==
107     offsetof(struct ifreq, ifr_ifru), "gap between ifr_name and ifr_ifru");
108 
109 __read_mostly epoch_t net_epoch_preempt;
110 __read_mostly epoch_t net_epoch;
111 #ifdef COMPAT_FREEBSD32
112 #include <sys/mount.h>
113 #include <compat/freebsd32/freebsd32.h>
114 
115 struct ifreq_buffer32 {
116 	uint32_t	length;		/* (size_t) */
117 	uint32_t	buffer;		/* (void *) */
118 };
119 
120 /*
121  * Interface request structure used for socket
122  * ioctl's.  All interface ioctl's must have parameter
123  * definitions which begin with ifr_name.  The
124  * remainder may be interface specific.
125  */
126 struct ifreq32 {
127 	char	ifr_name[IFNAMSIZ];		/* if name, e.g. "en0" */
128 	union {
129 		struct sockaddr	ifru_addr;
130 		struct sockaddr	ifru_dstaddr;
131 		struct sockaddr	ifru_broadaddr;
132 		struct ifreq_buffer32 ifru_buffer;
133 		short		ifru_flags[2];
134 		short		ifru_index;
135 		int		ifru_jid;
136 		int		ifru_metric;
137 		int		ifru_mtu;
138 		int		ifru_phys;
139 		int		ifru_media;
140 		uint32_t	ifru_data;
141 		int		ifru_cap[2];
142 		u_int		ifru_fib;
143 		u_char		ifru_vlan_pcp;
144 	} ifr_ifru;
145 };
146 CTASSERT(sizeof(struct ifreq) == sizeof(struct ifreq32));
147 CTASSERT(__offsetof(struct ifreq, ifr_ifru) ==
148     __offsetof(struct ifreq32, ifr_ifru));
149 
150 struct ifgroupreq32 {
151 	char	ifgr_name[IFNAMSIZ];
152 	u_int	ifgr_len;
153 	union {
154 		char		ifgru_group[IFNAMSIZ];
155 		uint32_t	ifgru_groups;
156 	} ifgr_ifgru;
157 };
158 
159 struct ifmediareq32 {
160 	char		ifm_name[IFNAMSIZ];
161 	int		ifm_current;
162 	int		ifm_mask;
163 	int		ifm_status;
164 	int		ifm_active;
165 	int		ifm_count;
166 	uint32_t	ifm_ulist;	/* (int *) */
167 };
168 #define	SIOCGIFMEDIA32	_IOC_NEWTYPE(SIOCGIFMEDIA, struct ifmediareq32)
169 #define	SIOCGIFXMEDIA32	_IOC_NEWTYPE(SIOCGIFXMEDIA, struct ifmediareq32)
170 
171 #define	_CASE_IOC_IFGROUPREQ_32(cmd)				\
172     _IOC_NEWTYPE((cmd), struct ifgroupreq32): case
173 #else /* !COMPAT_FREEBSD32 */
174 #define _CASE_IOC_IFGROUPREQ_32(cmd)
175 #endif /* !COMPAT_FREEBSD32 */
176 
177 #define CASE_IOC_IFGROUPREQ(cmd)	\
178     _CASE_IOC_IFGROUPREQ_32(cmd)	\
179     (cmd)
180 
181 union ifreq_union {
182 	struct ifreq	ifr;
183 #ifdef COMPAT_FREEBSD32
184 	struct ifreq32	ifr32;
185 #endif
186 };
187 
188 union ifgroupreq_union {
189 	struct ifgroupreq ifgr;
190 #ifdef COMPAT_FREEBSD32
191 	struct ifgroupreq32 ifgr32;
192 #endif
193 };
194 
195 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW, 0, "Link layers");
196 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW, 0, "Generic link-management");
197 
198 SYSCTL_INT(_net_link, OID_AUTO, ifqmaxlen, CTLFLAG_RDTUN,
199     &ifqmaxlen, 0, "max send queue size");
200 
201 /* Log link state change events */
202 static int log_link_state_change = 1;
203 
204 SYSCTL_INT(_net_link, OID_AUTO, log_link_state_change, CTLFLAG_RW,
205 	&log_link_state_change, 0,
206 	"log interface link state change events");
207 
208 /* Log promiscuous mode change events */
209 static int log_promisc_mode_change = 1;
210 
211 SYSCTL_INT(_net_link, OID_AUTO, log_promisc_mode_change, CTLFLAG_RDTUN,
212 	&log_promisc_mode_change, 1,
213 	"log promiscuous mode change events");
214 
215 /* Interface description */
216 static unsigned int ifdescr_maxlen = 1024;
217 SYSCTL_UINT(_net, OID_AUTO, ifdescr_maxlen, CTLFLAG_RW,
218 	&ifdescr_maxlen, 0,
219 	"administrative maximum length for interface description");
220 
221 static MALLOC_DEFINE(M_IFDESCR, "ifdescr", "ifnet descriptions");
222 
223 /* global sx for non-critical path ifdescr */
224 static struct sx ifdescr_sx;
225 SX_SYSINIT(ifdescr_sx, &ifdescr_sx, "ifnet descr");
226 
227 void	(*ng_ether_link_state_p)(struct ifnet *ifp, int state);
228 void	(*lagg_linkstate_p)(struct ifnet *ifp, int state);
229 /* These are external hooks for CARP. */
230 void	(*carp_linkstate_p)(struct ifnet *ifp);
231 void	(*carp_demote_adj_p)(int, char *);
232 int	(*carp_master_p)(struct ifaddr *);
233 #if defined(INET) || defined(INET6)
234 int	(*carp_forus_p)(struct ifnet *ifp, u_char *dhost);
235 int	(*carp_output_p)(struct ifnet *ifp, struct mbuf *m,
236     const struct sockaddr *sa);
237 int	(*carp_ioctl_p)(struct ifreq *, u_long, struct thread *);
238 int	(*carp_attach_p)(struct ifaddr *, int);
239 void	(*carp_detach_p)(struct ifaddr *, bool);
240 #endif
241 #ifdef INET
242 int	(*carp_iamatch_p)(struct ifaddr *, uint8_t **);
243 #endif
244 #ifdef INET6
245 struct ifaddr *(*carp_iamatch6_p)(struct ifnet *ifp, struct in6_addr *taddr6);
246 caddr_t	(*carp_macmatch6_p)(struct ifnet *ifp, struct mbuf *m,
247     const struct in6_addr *taddr);
248 #endif
249 
250 struct mbuf *(*tbr_dequeue_ptr)(struct ifaltq *, int) = NULL;
251 
252 /*
253  * XXX: Style; these should be sorted alphabetically, and unprototyped
254  * static functions should be prototyped. Currently they are sorted by
255  * declaration order.
256  */
257 static void	if_attachdomain(void *);
258 static void	if_attachdomain1(struct ifnet *);
259 static int	ifconf(u_long, caddr_t);
260 static void	*if_grow(void);
261 static void	if_input_default(struct ifnet *, struct mbuf *);
262 static int	if_requestencap_default(struct ifnet *, struct if_encap_req *);
263 static void	if_route(struct ifnet *, int flag, int fam);
264 static int	if_setflag(struct ifnet *, int, int, int *, int);
265 static int	if_transmit(struct ifnet *ifp, struct mbuf *m);
266 static void	if_unroute(struct ifnet *, int flag, int fam);
267 static int	if_delmulti_locked(struct ifnet *, struct ifmultiaddr *, int);
268 static void	do_link_state_change(void *, int);
269 static int	if_getgroup(struct ifgroupreq *, struct ifnet *);
270 static int	if_getgroupmembers(struct ifgroupreq *);
271 static void	if_delgroups(struct ifnet *);
272 static void	if_attach_internal(struct ifnet *, int, struct if_clone *);
273 static int	if_detach_internal(struct ifnet *, int, struct if_clone **);
274 static void	if_siocaddmulti(void *, int);
275 #ifdef VIMAGE
276 static void	if_vmove(struct ifnet *, struct vnet *);
277 #endif
278 
279 #ifdef INET6
280 /*
281  * XXX: declare here to avoid to include many inet6 related files..
282  * should be more generalized?
283  */
284 extern void	nd6_setmtu(struct ifnet *);
285 #endif
286 
287 /* ipsec helper hooks */
288 VNET_DEFINE(struct hhook_head *, ipsec_hhh_in[HHOOK_IPSEC_COUNT]);
289 VNET_DEFINE(struct hhook_head *, ipsec_hhh_out[HHOOK_IPSEC_COUNT]);
290 
291 VNET_DEFINE(int, if_index);
292 int	ifqmaxlen = IFQ_MAXLEN;
293 VNET_DEFINE(struct ifnethead, ifnet);	/* depend on static init XXX */
294 VNET_DEFINE(struct ifgrouphead, ifg_head);
295 
296 VNET_DEFINE_STATIC(int, if_indexlim) = 8;
297 
298 /* Table of ifnet by index. */
299 VNET_DEFINE(struct ifnet **, ifindex_table);
300 
301 #define	V_if_indexlim		VNET(if_indexlim)
302 #define	V_ifindex_table		VNET(ifindex_table)
303 
304 /*
305  * The global network interface list (V_ifnet) and related state (such as
306  * if_index, if_indexlim, and ifindex_table) are protected by an sxlock and
307  * an rwlock.  Either may be acquired shared to stablize the list, but both
308  * must be acquired writable to modify the list.  This model allows us to
309  * both stablize the interface list during interrupt thread processing, but
310  * also to stablize it over long-running ioctls, without introducing priority
311  * inversions and deadlocks.
312  */
313 struct rwlock ifnet_rwlock;
314 RW_SYSINIT_FLAGS(ifnet_rw, &ifnet_rwlock, "ifnet_rw", RW_RECURSE);
315 struct sx ifnet_sxlock;
316 SX_SYSINIT_FLAGS(ifnet_sx, &ifnet_sxlock, "ifnet_sx", SX_RECURSE);
317 
318 /*
319  * The allocation of network interfaces is a rather non-atomic affair; we
320  * need to select an index before we are ready to expose the interface for
321  * use, so will use this pointer value to indicate reservation.
322  */
323 #define	IFNET_HOLD	(void *)(uintptr_t)(-1)
324 
325 static	if_com_alloc_t *if_com_alloc[256];
326 static	if_com_free_t *if_com_free[256];
327 
328 static MALLOC_DEFINE(M_IFNET, "ifnet", "interface internals");
329 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
330 MALLOC_DEFINE(M_IFMADDR, "ether_multi", "link-level multicast address");
331 
332 struct ifnet *
333 ifnet_byindex(u_short idx)
334 {
335 	struct ifnet *ifp;
336 
337 	if (__predict_false(idx > V_if_index))
338 		return (NULL);
339 
340 	ifp = *(struct ifnet * const volatile *)(V_ifindex_table + idx);
341 	return (__predict_false(ifp == IFNET_HOLD) ? NULL : ifp);
342 }
343 
344 struct ifnet *
345 ifnet_byindex_ref(u_short idx)
346 {
347 	struct ifnet *ifp;
348 
349 	NET_EPOCH_ASSERT();
350 
351 	ifp = ifnet_byindex(idx);
352 	if (ifp == NULL || (ifp->if_flags & IFF_DYING))
353 		return (NULL);
354 	if_ref(ifp);
355 	return (ifp);
356 }
357 
358 /*
359  * Allocate an ifindex array entry; return 0 on success or an error on
360  * failure.
361  */
362 static u_short
363 ifindex_alloc(void **old)
364 {
365 	u_short idx;
366 
367 	IFNET_WLOCK_ASSERT();
368 	/*
369 	 * Try to find an empty slot below V_if_index.  If we fail, take the
370 	 * next slot.
371 	 */
372 	for (idx = 1; idx <= V_if_index; idx++) {
373 		if (V_ifindex_table[idx] == NULL)
374 			break;
375 	}
376 
377 	/* Catch if_index overflow. */
378 	if (idx >= V_if_indexlim) {
379 		*old = if_grow();
380 		return (USHRT_MAX);
381 	}
382 	if (idx > V_if_index)
383 		V_if_index = idx;
384 	return (idx);
385 }
386 
387 static void
388 ifindex_free_locked(u_short idx)
389 {
390 
391 	IFNET_WLOCK_ASSERT();
392 
393 	V_ifindex_table[idx] = NULL;
394 	while (V_if_index > 0 &&
395 	    V_ifindex_table[V_if_index] == NULL)
396 		V_if_index--;
397 }
398 
399 static void
400 ifindex_free(u_short idx)
401 {
402 
403 	IFNET_WLOCK();
404 	ifindex_free_locked(idx);
405 	IFNET_WUNLOCK();
406 }
407 
408 static void
409 ifnet_setbyindex(u_short idx, struct ifnet *ifp)
410 {
411 
412 	V_ifindex_table[idx] = ifp;
413 }
414 
415 struct ifaddr *
416 ifaddr_byindex(u_short idx)
417 {
418 	struct ifnet *ifp;
419 	struct ifaddr *ifa = NULL;
420 
421 	NET_EPOCH_ASSERT();
422 
423 	ifp = ifnet_byindex(idx);
424 	if (ifp != NULL && (ifa = ifp->if_addr) != NULL)
425 		ifa_ref(ifa);
426 	return (ifa);
427 }
428 
429 /*
430  * Network interface utility routines.
431  *
432  * Routines with ifa_ifwith* names take sockaddr *'s as
433  * parameters.
434  */
435 
436 static void
437 vnet_if_init(const void *unused __unused)
438 {
439 	void *old;
440 
441 	CK_STAILQ_INIT(&V_ifnet);
442 	CK_STAILQ_INIT(&V_ifg_head);
443 	IFNET_WLOCK();
444 	old = if_grow();				/* create initial table */
445 	IFNET_WUNLOCK();
446 	epoch_wait_preempt(net_epoch_preempt);
447 	free(old, M_IFNET);
448 	vnet_if_clone_init();
449 }
450 VNET_SYSINIT(vnet_if_init, SI_SUB_INIT_IF, SI_ORDER_SECOND, vnet_if_init,
451     NULL);
452 
453 #ifdef VIMAGE
454 static void
455 vnet_if_uninit(const void *unused __unused)
456 {
457 
458 	VNET_ASSERT(CK_STAILQ_EMPTY(&V_ifnet), ("%s:%d tailq &V_ifnet=%p "
459 	    "not empty", __func__, __LINE__, &V_ifnet));
460 	VNET_ASSERT(CK_STAILQ_EMPTY(&V_ifg_head), ("%s:%d tailq &V_ifg_head=%p "
461 	    "not empty", __func__, __LINE__, &V_ifg_head));
462 
463 	free((caddr_t)V_ifindex_table, M_IFNET);
464 }
465 VNET_SYSUNINIT(vnet_if_uninit, SI_SUB_INIT_IF, SI_ORDER_FIRST,
466     vnet_if_uninit, NULL);
467 
468 static void
469 vnet_if_return(const void *unused __unused)
470 {
471 	struct ifnet *ifp, *nifp;
472 
473 	/* Return all inherited interfaces to their parent vnets. */
474 	CK_STAILQ_FOREACH_SAFE(ifp, &V_ifnet, if_link, nifp) {
475 		if (ifp->if_home_vnet != ifp->if_vnet)
476 			if_vmove(ifp, ifp->if_home_vnet);
477 	}
478 }
479 VNET_SYSUNINIT(vnet_if_return, SI_SUB_VNET_DONE, SI_ORDER_ANY,
480     vnet_if_return, NULL);
481 #endif
482 
483 
484 static void *
485 if_grow(void)
486 {
487 	int oldlim;
488 	u_int n;
489 	struct ifnet **e;
490 	void *old;
491 
492 	old = NULL;
493 	IFNET_WLOCK_ASSERT();
494 	oldlim = V_if_indexlim;
495 	IFNET_WUNLOCK();
496 	n = (oldlim << 1) * sizeof(*e);
497 	e = malloc(n, M_IFNET, M_WAITOK | M_ZERO);
498 	IFNET_WLOCK();
499 	if (V_if_indexlim != oldlim) {
500 		free(e, M_IFNET);
501 		return (NULL);
502 	}
503 	if (V_ifindex_table != NULL) {
504 		memcpy((caddr_t)e, (caddr_t)V_ifindex_table, n/2);
505 		old = V_ifindex_table;
506 	}
507 	V_if_indexlim <<= 1;
508 	V_ifindex_table = e;
509 	return (old);
510 }
511 
512 /*
513  * Allocate a struct ifnet and an index for an interface.  A layer 2
514  * common structure will also be allocated if an allocation routine is
515  * registered for the passed type.
516  */
517 struct ifnet *
518 if_alloc_domain(u_char type, int numa_domain)
519 {
520 	struct ifnet *ifp;
521 	u_short idx;
522 	void *old;
523 
524 	KASSERT(numa_domain <= IF_NODOM, ("numa_domain too large"));
525 	if (numa_domain == IF_NODOM)
526 		ifp = malloc(sizeof(struct ifnet), M_IFNET,
527 		    M_WAITOK | M_ZERO);
528 	else
529 		ifp = malloc_domainset(sizeof(struct ifnet), M_IFNET,
530 		    DOMAINSET_PREF(numa_domain), M_WAITOK | M_ZERO);
531  restart:
532 	IFNET_WLOCK();
533 	idx = ifindex_alloc(&old);
534 	if (__predict_false(idx == USHRT_MAX)) {
535 		IFNET_WUNLOCK();
536 		epoch_wait_preempt(net_epoch_preempt);
537 		free(old, M_IFNET);
538 		goto restart;
539 	}
540 	ifnet_setbyindex(idx, IFNET_HOLD);
541 	IFNET_WUNLOCK();
542 	ifp->if_index = idx;
543 	ifp->if_type = type;
544 	ifp->if_alloctype = type;
545 	ifp->if_numa_domain = numa_domain;
546 #ifdef VIMAGE
547 	ifp->if_vnet = curvnet;
548 #endif
549 	if (if_com_alloc[type] != NULL) {
550 		ifp->if_l2com = if_com_alloc[type](type, ifp);
551 		if (ifp->if_l2com == NULL) {
552 			free(ifp, M_IFNET);
553 			ifindex_free(idx);
554 			return (NULL);
555 		}
556 	}
557 
558 	IF_ADDR_LOCK_INIT(ifp);
559 	TASK_INIT(&ifp->if_linktask, 0, do_link_state_change, ifp);
560 	TASK_INIT(&ifp->if_addmultitask, 0, if_siocaddmulti, ifp);
561 	ifp->if_afdata_initialized = 0;
562 	IF_AFDATA_LOCK_INIT(ifp);
563 	CK_STAILQ_INIT(&ifp->if_addrhead);
564 	CK_STAILQ_INIT(&ifp->if_multiaddrs);
565 	CK_STAILQ_INIT(&ifp->if_groups);
566 #ifdef MAC
567 	mac_ifnet_init(ifp);
568 #endif
569 	ifq_init(&ifp->if_snd, ifp);
570 
571 	refcount_init(&ifp->if_refcount, 1);	/* Index reference. */
572 	for (int i = 0; i < IFCOUNTERS; i++)
573 		ifp->if_counters[i] = counter_u64_alloc(M_WAITOK);
574 	ifp->if_get_counter = if_get_counter_default;
575 	ifp->if_pcp = IFNET_PCP_NONE;
576 	ifnet_setbyindex(ifp->if_index, ifp);
577 	return (ifp);
578 }
579 
580 struct ifnet *
581 if_alloc_dev(u_char type, device_t dev)
582 {
583 	int numa_domain;
584 
585 	if (dev == NULL || bus_get_domain(dev, &numa_domain) != 0)
586 		return (if_alloc_domain(type, IF_NODOM));
587 	return (if_alloc_domain(type, numa_domain));
588 }
589 
590 struct ifnet *
591 if_alloc(u_char type)
592 {
593 
594 	return (if_alloc_domain(type, IF_NODOM));
595 }
596 /*
597  * Do the actual work of freeing a struct ifnet, and layer 2 common
598  * structure.  This call is made when the last reference to an
599  * interface is released.
600  */
601 static void
602 if_free_internal(struct ifnet *ifp)
603 {
604 
605 	KASSERT((ifp->if_flags & IFF_DYING),
606 	    ("if_free_internal: interface not dying"));
607 
608 	if (if_com_free[ifp->if_alloctype] != NULL)
609 		if_com_free[ifp->if_alloctype](ifp->if_l2com,
610 		    ifp->if_alloctype);
611 
612 #ifdef MAC
613 	mac_ifnet_destroy(ifp);
614 #endif /* MAC */
615 	IF_AFDATA_DESTROY(ifp);
616 	IF_ADDR_LOCK_DESTROY(ifp);
617 	ifq_delete(&ifp->if_snd);
618 
619 	for (int i = 0; i < IFCOUNTERS; i++)
620 		counter_u64_free(ifp->if_counters[i]);
621 
622 	free(ifp->if_description, M_IFDESCR);
623 	free(ifp->if_hw_addr, M_IFADDR);
624 	if (ifp->if_numa_domain == IF_NODOM)
625 		free(ifp, M_IFNET);
626 	else
627 		free_domain(ifp, M_IFNET);
628 }
629 
630 static void
631 if_destroy(epoch_context_t ctx)
632 {
633 	struct ifnet *ifp;
634 
635 	ifp = __containerof(ctx, struct ifnet, if_epoch_ctx);
636 	if_free_internal(ifp);
637 }
638 
639 /*
640  * Deregister an interface and free the associated storage.
641  */
642 void
643 if_free(struct ifnet *ifp)
644 {
645 
646 	ifp->if_flags |= IFF_DYING;			/* XXX: Locking */
647 
648 	CURVNET_SET_QUIET(ifp->if_vnet);
649 	IFNET_WLOCK();
650 	KASSERT(ifp == ifnet_byindex(ifp->if_index),
651 	    ("%s: freeing unallocated ifnet", ifp->if_xname));
652 
653 	ifindex_free_locked(ifp->if_index);
654 	IFNET_WUNLOCK();
655 
656 	if (refcount_release(&ifp->if_refcount))
657 		epoch_call(net_epoch_preempt, &ifp->if_epoch_ctx, if_destroy);
658 	CURVNET_RESTORE();
659 }
660 
661 /*
662  * Interfaces to keep an ifnet type-stable despite the possibility of the
663  * driver calling if_free().  If there are additional references, we defer
664  * freeing the underlying data structure.
665  */
666 void
667 if_ref(struct ifnet *ifp)
668 {
669 
670 	/* We don't assert the ifnet list lock here, but arguably should. */
671 	refcount_acquire(&ifp->if_refcount);
672 }
673 
674 void
675 if_rele(struct ifnet *ifp)
676 {
677 
678 	if (!refcount_release(&ifp->if_refcount))
679 		return;
680 	epoch_call(net_epoch_preempt, &ifp->if_epoch_ctx, if_destroy);
681 }
682 
683 void
684 ifq_init(struct ifaltq *ifq, struct ifnet *ifp)
685 {
686 
687 	mtx_init(&ifq->ifq_mtx, ifp->if_xname, "if send queue", MTX_DEF);
688 
689 	if (ifq->ifq_maxlen == 0)
690 		ifq->ifq_maxlen = ifqmaxlen;
691 
692 	ifq->altq_type = 0;
693 	ifq->altq_disc = NULL;
694 	ifq->altq_flags &= ALTQF_CANTCHANGE;
695 	ifq->altq_tbr  = NULL;
696 	ifq->altq_ifp  = ifp;
697 }
698 
699 void
700 ifq_delete(struct ifaltq *ifq)
701 {
702 	mtx_destroy(&ifq->ifq_mtx);
703 }
704 
705 /*
706  * Perform generic interface initialization tasks and attach the interface
707  * to the list of "active" interfaces.  If vmove flag is set on entry
708  * to if_attach_internal(), perform only a limited subset of initialization
709  * tasks, given that we are moving from one vnet to another an ifnet which
710  * has already been fully initialized.
711  *
712  * Note that if_detach_internal() removes group membership unconditionally
713  * even when vmove flag is set, and if_attach_internal() adds only IFG_ALL.
714  * Thus, when if_vmove() is applied to a cloned interface, group membership
715  * is lost while a cloned one always joins a group whose name is
716  * ifc->ifc_name.  To recover this after if_detach_internal() and
717  * if_attach_internal(), the cloner should be specified to
718  * if_attach_internal() via ifc.  If it is non-NULL, if_attach_internal()
719  * attempts to join a group whose name is ifc->ifc_name.
720  *
721  * XXX:
722  *  - The decision to return void and thus require this function to
723  *    succeed is questionable.
724  *  - We should probably do more sanity checking.  For instance we don't
725  *    do anything to insure if_xname is unique or non-empty.
726  */
727 void
728 if_attach(struct ifnet *ifp)
729 {
730 
731 	if_attach_internal(ifp, 0, NULL);
732 }
733 
734 /*
735  * Compute the least common TSO limit.
736  */
737 void
738 if_hw_tsomax_common(if_t ifp, struct ifnet_hw_tsomax *pmax)
739 {
740 	/*
741 	 * 1) If there is no limit currently, take the limit from
742 	 * the network adapter.
743 	 *
744 	 * 2) If the network adapter has a limit below the current
745 	 * limit, apply it.
746 	 */
747 	if (pmax->tsomaxbytes == 0 || (ifp->if_hw_tsomax != 0 &&
748 	    ifp->if_hw_tsomax < pmax->tsomaxbytes)) {
749 		pmax->tsomaxbytes = ifp->if_hw_tsomax;
750 	}
751 	if (pmax->tsomaxsegcount == 0 || (ifp->if_hw_tsomaxsegcount != 0 &&
752 	    ifp->if_hw_tsomaxsegcount < pmax->tsomaxsegcount)) {
753 		pmax->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
754 	}
755 	if (pmax->tsomaxsegsize == 0 || (ifp->if_hw_tsomaxsegsize != 0 &&
756 	    ifp->if_hw_tsomaxsegsize < pmax->tsomaxsegsize)) {
757 		pmax->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
758 	}
759 }
760 
761 /*
762  * Update TSO limit of a network adapter.
763  *
764  * Returns zero if no change. Else non-zero.
765  */
766 int
767 if_hw_tsomax_update(if_t ifp, struct ifnet_hw_tsomax *pmax)
768 {
769 	int retval = 0;
770 	if (ifp->if_hw_tsomax != pmax->tsomaxbytes) {
771 		ifp->if_hw_tsomax = pmax->tsomaxbytes;
772 		retval++;
773 	}
774 	if (ifp->if_hw_tsomaxsegsize != pmax->tsomaxsegsize) {
775 		ifp->if_hw_tsomaxsegsize = pmax->tsomaxsegsize;
776 		retval++;
777 	}
778 	if (ifp->if_hw_tsomaxsegcount != pmax->tsomaxsegcount) {
779 		ifp->if_hw_tsomaxsegcount = pmax->tsomaxsegcount;
780 		retval++;
781 	}
782 	return (retval);
783 }
784 
785 static void
786 if_attach_internal(struct ifnet *ifp, int vmove, struct if_clone *ifc)
787 {
788 	unsigned socksize, ifasize;
789 	int namelen, masklen;
790 	struct sockaddr_dl *sdl;
791 	struct ifaddr *ifa;
792 
793 	if (ifp->if_index == 0 || ifp != ifnet_byindex(ifp->if_index))
794 		panic ("%s: BUG: if_attach called without if_alloc'd input()\n",
795 		    ifp->if_xname);
796 
797 #ifdef VIMAGE
798 	ifp->if_vnet = curvnet;
799 	if (ifp->if_home_vnet == NULL)
800 		ifp->if_home_vnet = curvnet;
801 #endif
802 
803 	if_addgroup(ifp, IFG_ALL);
804 
805 	/* Restore group membership for cloned interfaces. */
806 	if (vmove && ifc != NULL)
807 		if_clone_addgroup(ifp, ifc);
808 
809 	getmicrotime(&ifp->if_lastchange);
810 	ifp->if_epoch = time_uptime;
811 
812 	KASSERT((ifp->if_transmit == NULL && ifp->if_qflush == NULL) ||
813 	    (ifp->if_transmit != NULL && ifp->if_qflush != NULL),
814 	    ("transmit and qflush must both either be set or both be NULL"));
815 	if (ifp->if_transmit == NULL) {
816 		ifp->if_transmit = if_transmit;
817 		ifp->if_qflush = if_qflush;
818 	}
819 	if (ifp->if_input == NULL)
820 		ifp->if_input = if_input_default;
821 
822 	if (ifp->if_requestencap == NULL)
823 		ifp->if_requestencap = if_requestencap_default;
824 
825 	if (!vmove) {
826 #ifdef MAC
827 		mac_ifnet_create(ifp);
828 #endif
829 
830 		/*
831 		 * Create a Link Level name for this device.
832 		 */
833 		namelen = strlen(ifp->if_xname);
834 		/*
835 		 * Always save enough space for any possiable name so we
836 		 * can do a rename in place later.
837 		 */
838 		masklen = offsetof(struct sockaddr_dl, sdl_data[0]) + IFNAMSIZ;
839 		socksize = masklen + ifp->if_addrlen;
840 		if (socksize < sizeof(*sdl))
841 			socksize = sizeof(*sdl);
842 		socksize = roundup2(socksize, sizeof(long));
843 		ifasize = sizeof(*ifa) + 2 * socksize;
844 		ifa = ifa_alloc(ifasize, M_WAITOK);
845 		sdl = (struct sockaddr_dl *)(ifa + 1);
846 		sdl->sdl_len = socksize;
847 		sdl->sdl_family = AF_LINK;
848 		bcopy(ifp->if_xname, sdl->sdl_data, namelen);
849 		sdl->sdl_nlen = namelen;
850 		sdl->sdl_index = ifp->if_index;
851 		sdl->sdl_type = ifp->if_type;
852 		ifp->if_addr = ifa;
853 		ifa->ifa_ifp = ifp;
854 		ifa->ifa_addr = (struct sockaddr *)sdl;
855 		sdl = (struct sockaddr_dl *)(socksize + (caddr_t)sdl);
856 		ifa->ifa_netmask = (struct sockaddr *)sdl;
857 		sdl->sdl_len = masklen;
858 		while (namelen != 0)
859 			sdl->sdl_data[--namelen] = 0xff;
860 		CK_STAILQ_INSERT_HEAD(&ifp->if_addrhead, ifa, ifa_link);
861 		/* Reliably crash if used uninitialized. */
862 		ifp->if_broadcastaddr = NULL;
863 
864 		if (ifp->if_type == IFT_ETHER) {
865 			ifp->if_hw_addr = malloc(ifp->if_addrlen, M_IFADDR,
866 			    M_WAITOK | M_ZERO);
867 		}
868 
869 #if defined(INET) || defined(INET6)
870 		/* Use defaults for TSO, if nothing is set */
871 		if (ifp->if_hw_tsomax == 0 &&
872 		    ifp->if_hw_tsomaxsegcount == 0 &&
873 		    ifp->if_hw_tsomaxsegsize == 0) {
874 			/*
875 			 * The TSO defaults needs to be such that an
876 			 * NFS mbuf list of 35 mbufs totalling just
877 			 * below 64K works and that a chain of mbufs
878 			 * can be defragged into at most 32 segments:
879 			 */
880 			ifp->if_hw_tsomax = min(IP_MAXPACKET, (32 * MCLBYTES) -
881 			    (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN));
882 			ifp->if_hw_tsomaxsegcount = 35;
883 			ifp->if_hw_tsomaxsegsize = 2048;	/* 2K */
884 
885 			/* XXX some drivers set IFCAP_TSO after ethernet attach */
886 			if (ifp->if_capabilities & IFCAP_TSO) {
887 				if_printf(ifp, "Using defaults for TSO: %u/%u/%u\n",
888 				    ifp->if_hw_tsomax,
889 				    ifp->if_hw_tsomaxsegcount,
890 				    ifp->if_hw_tsomaxsegsize);
891 			}
892 		}
893 #endif
894 	}
895 #ifdef VIMAGE
896 	else {
897 		/*
898 		 * Update the interface index in the link layer address
899 		 * of the interface.
900 		 */
901 		for (ifa = ifp->if_addr; ifa != NULL;
902 		    ifa = CK_STAILQ_NEXT(ifa, ifa_link)) {
903 			if (ifa->ifa_addr->sa_family == AF_LINK) {
904 				sdl = (struct sockaddr_dl *)ifa->ifa_addr;
905 				sdl->sdl_index = ifp->if_index;
906 			}
907 		}
908 	}
909 #endif
910 
911 	IFNET_WLOCK();
912 	CK_STAILQ_INSERT_TAIL(&V_ifnet, ifp, if_link);
913 #ifdef VIMAGE
914 	curvnet->vnet_ifcnt++;
915 #endif
916 	IFNET_WUNLOCK();
917 
918 	if (domain_init_status >= 2)
919 		if_attachdomain1(ifp);
920 
921 	EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
922 	if (IS_DEFAULT_VNET(curvnet))
923 		devctl_notify("IFNET", ifp->if_xname, "ATTACH", NULL);
924 
925 	/* Announce the interface. */
926 	rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
927 }
928 
929 static void
930 if_epochalloc(void *dummy __unused)
931 {
932 
933 	net_epoch_preempt = epoch_alloc("Net preemptible", EPOCH_PREEMPT);
934 	net_epoch = epoch_alloc("Net", 0);
935 }
936 SYSINIT(ifepochalloc, SI_SUB_TASKQ + 1, SI_ORDER_ANY,
937     if_epochalloc, NULL);
938 
939 static void
940 if_attachdomain(void *dummy)
941 {
942 	struct ifnet *ifp;
943 
944 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link)
945 		if_attachdomain1(ifp);
946 }
947 SYSINIT(domainifattach, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_SECOND,
948     if_attachdomain, NULL);
949 
950 static void
951 if_attachdomain1(struct ifnet *ifp)
952 {
953 	struct domain *dp;
954 
955 	/*
956 	 * Since dp->dom_ifattach calls malloc() with M_WAITOK, we
957 	 * cannot lock ifp->if_afdata initialization, entirely.
958 	 */
959 	IF_AFDATA_LOCK(ifp);
960 	if (ifp->if_afdata_initialized >= domain_init_status) {
961 		IF_AFDATA_UNLOCK(ifp);
962 		log(LOG_WARNING, "%s called more than once on %s\n",
963 		    __func__, ifp->if_xname);
964 		return;
965 	}
966 	ifp->if_afdata_initialized = domain_init_status;
967 	IF_AFDATA_UNLOCK(ifp);
968 
969 	/* address family dependent data region */
970 	bzero(ifp->if_afdata, sizeof(ifp->if_afdata));
971 	for (dp = domains; dp; dp = dp->dom_next) {
972 		if (dp->dom_ifattach)
973 			ifp->if_afdata[dp->dom_family] =
974 			    (*dp->dom_ifattach)(ifp);
975 	}
976 }
977 
978 /*
979  * Remove any unicast or broadcast network addresses from an interface.
980  */
981 void
982 if_purgeaddrs(struct ifnet *ifp)
983 {
984 	struct ifaddr *ifa;
985 
986 	while (1) {
987 		struct epoch_tracker et;
988 
989 		NET_EPOCH_ENTER(et);
990 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
991 			if (ifa->ifa_addr->sa_family != AF_LINK)
992 				break;
993 		}
994 		NET_EPOCH_EXIT(et);
995 
996 		if (ifa == NULL)
997 			break;
998 #ifdef INET
999 		/* XXX: Ugly!! ad hoc just for INET */
1000 		if (ifa->ifa_addr->sa_family == AF_INET) {
1001 			struct ifaliasreq ifr;
1002 
1003 			bzero(&ifr, sizeof(ifr));
1004 			ifr.ifra_addr = *ifa->ifa_addr;
1005 			if (ifa->ifa_dstaddr)
1006 				ifr.ifra_broadaddr = *ifa->ifa_dstaddr;
1007 			if (in_control(NULL, SIOCDIFADDR, (caddr_t)&ifr, ifp,
1008 			    NULL) == 0)
1009 				continue;
1010 		}
1011 #endif /* INET */
1012 #ifdef INET6
1013 		if (ifa->ifa_addr->sa_family == AF_INET6) {
1014 			in6_purgeaddr(ifa);
1015 			/* ifp_addrhead is already updated */
1016 			continue;
1017 		}
1018 #endif /* INET6 */
1019 		IF_ADDR_WLOCK(ifp);
1020 		CK_STAILQ_REMOVE(&ifp->if_addrhead, ifa, ifaddr, ifa_link);
1021 		IF_ADDR_WUNLOCK(ifp);
1022 		ifa_free(ifa);
1023 	}
1024 }
1025 
1026 /*
1027  * Remove any multicast network addresses from an interface when an ifnet
1028  * is going away.
1029  */
1030 static void
1031 if_purgemaddrs(struct ifnet *ifp)
1032 {
1033 	struct ifmultiaddr *ifma;
1034 
1035 	IF_ADDR_WLOCK(ifp);
1036 	while (!CK_STAILQ_EMPTY(&ifp->if_multiaddrs)) {
1037 		ifma = CK_STAILQ_FIRST(&ifp->if_multiaddrs);
1038 		CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifmultiaddr, ifma_link);
1039 		if_delmulti_locked(ifp, ifma, 1);
1040 	}
1041 	IF_ADDR_WUNLOCK(ifp);
1042 }
1043 
1044 /*
1045  * Detach an interface, removing it from the list of "active" interfaces.
1046  * If vmove flag is set on entry to if_detach_internal(), perform only a
1047  * limited subset of cleanup tasks, given that we are moving an ifnet from
1048  * one vnet to another, where it must be fully operational.
1049  *
1050  * XXXRW: There are some significant questions about event ordering, and
1051  * how to prevent things from starting to use the interface during detach.
1052  */
1053 void
1054 if_detach(struct ifnet *ifp)
1055 {
1056 
1057 	CURVNET_SET_QUIET(ifp->if_vnet);
1058 	if_detach_internal(ifp, 0, NULL);
1059 	CURVNET_RESTORE();
1060 }
1061 
1062 /*
1063  * The vmove flag, if set, indicates that we are called from a callpath
1064  * that is moving an interface to a different vnet instance.
1065  *
1066  * The shutdown flag, if set, indicates that we are called in the
1067  * process of shutting down a vnet instance.  Currently only the
1068  * vnet_if_return SYSUNINIT function sets it.  Note: we can be called
1069  * on a vnet instance shutdown without this flag being set, e.g., when
1070  * the cloned interfaces are destoyed as first thing of teardown.
1071  */
1072 static int
1073 if_detach_internal(struct ifnet *ifp, int vmove, struct if_clone **ifcp)
1074 {
1075 	struct ifaddr *ifa;
1076 	int i;
1077 	struct domain *dp;
1078  	struct ifnet *iter;
1079  	int found = 0;
1080 #ifdef VIMAGE
1081 	bool shutdown;
1082 
1083 	shutdown = ifp->if_vnet->vnet_shutdown;
1084 #endif
1085 	IFNET_WLOCK();
1086 	CK_STAILQ_FOREACH(iter, &V_ifnet, if_link)
1087 		if (iter == ifp) {
1088 			CK_STAILQ_REMOVE(&V_ifnet, ifp, ifnet, if_link);
1089 			if (!vmove)
1090 				ifp->if_flags |= IFF_DYING;
1091 			found = 1;
1092 			break;
1093 		}
1094 	IFNET_WUNLOCK();
1095 	if (!found) {
1096 		/*
1097 		 * While we would want to panic here, we cannot
1098 		 * guarantee that the interface is indeed still on
1099 		 * the list given we don't hold locks all the way.
1100 		 */
1101 		return (ENOENT);
1102 #if 0
1103 		if (vmove)
1104 			panic("%s: ifp=%p not on the ifnet tailq %p",
1105 			    __func__, ifp, &V_ifnet);
1106 		else
1107 			return; /* XXX this should panic as well? */
1108 #endif
1109 	}
1110 
1111 	/*
1112 	 * At this point we know the interface still was on the ifnet list
1113 	 * and we removed it so we are in a stable state.
1114 	 */
1115 #ifdef VIMAGE
1116 	curvnet->vnet_ifcnt--;
1117 #endif
1118 	epoch_wait_preempt(net_epoch_preempt);
1119 
1120 	/*
1121 	 * Ensure all pending EPOCH(9) callbacks have been executed. This
1122 	 * fixes issues about late destruction of multicast options
1123 	 * which lead to leave group calls, which in turn access the
1124 	 * belonging ifnet structure:
1125 	 */
1126 	epoch_drain_callbacks(net_epoch_preempt);
1127 
1128 	/*
1129 	 * In any case (destroy or vmove) detach us from the groups
1130 	 * and remove/wait for pending events on the taskq.
1131 	 * XXX-BZ in theory an interface could still enqueue a taskq change?
1132 	 */
1133 	if_delgroups(ifp);
1134 
1135 	taskqueue_drain(taskqueue_swi, &ifp->if_linktask);
1136 	taskqueue_drain(taskqueue_swi, &ifp->if_addmultitask);
1137 
1138 	/*
1139 	 * Check if this is a cloned interface or not. Must do even if
1140 	 * shutting down as a if_vmove_reclaim() would move the ifp and
1141 	 * the if_clone_addgroup() will have a corrupted string overwise
1142 	 * from a gibberish pointer.
1143 	 */
1144 	if (vmove && ifcp != NULL)
1145 		*ifcp = if_clone_findifc(ifp);
1146 
1147 	if_down(ifp);
1148 
1149 #ifdef VIMAGE
1150 	/*
1151 	 * On VNET shutdown abort here as the stack teardown will do all
1152 	 * the work top-down for us.
1153 	 */
1154 	if (shutdown) {
1155 		/* Give interface users the chance to clean up. */
1156 		EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
1157 
1158 		/*
1159 		 * In case of a vmove we are done here without error.
1160 		 * If we would signal an error it would lead to the same
1161 		 * abort as if we did not find the ifnet anymore.
1162 		 * if_detach() calls us in void context and does not care
1163 		 * about an early abort notification, so life is splendid :)
1164 		 */
1165 		goto finish_vnet_shutdown;
1166 	}
1167 #endif
1168 
1169 	/*
1170 	 * At this point we are not tearing down a VNET and are either
1171 	 * going to destroy or vmove the interface and have to cleanup
1172 	 * accordingly.
1173 	 */
1174 
1175 	/*
1176 	 * Remove routes and flush queues.
1177 	 */
1178 #ifdef ALTQ
1179 	if (ALTQ_IS_ENABLED(&ifp->if_snd))
1180 		altq_disable(&ifp->if_snd);
1181 	if (ALTQ_IS_ATTACHED(&ifp->if_snd))
1182 		altq_detach(&ifp->if_snd);
1183 #endif
1184 
1185 	if_purgeaddrs(ifp);
1186 
1187 #ifdef INET
1188 	in_ifdetach(ifp);
1189 #endif
1190 
1191 #ifdef INET6
1192 	/*
1193 	 * Remove all IPv6 kernel structs related to ifp.  This should be done
1194 	 * before removing routing entries below, since IPv6 interface direct
1195 	 * routes are expected to be removed by the IPv6-specific kernel API.
1196 	 * Otherwise, the kernel will detect some inconsistency and bark it.
1197 	 */
1198 	in6_ifdetach(ifp);
1199 #endif
1200 	if_purgemaddrs(ifp);
1201 
1202 	/* Announce that the interface is gone. */
1203 	rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
1204 	EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
1205 	if (IS_DEFAULT_VNET(curvnet))
1206 		devctl_notify("IFNET", ifp->if_xname, "DETACH", NULL);
1207 
1208 	if (!vmove) {
1209 		/*
1210 		 * Prevent further calls into the device driver via ifnet.
1211 		 */
1212 		if_dead(ifp);
1213 
1214 		/*
1215 		 * Clean up all addresses.
1216 		 */
1217 		IF_ADDR_WLOCK(ifp);
1218 		if (!CK_STAILQ_EMPTY(&ifp->if_addrhead)) {
1219 			ifa = CK_STAILQ_FIRST(&ifp->if_addrhead);
1220 			CK_STAILQ_REMOVE(&ifp->if_addrhead, ifa, ifaddr, ifa_link);
1221 			IF_ADDR_WUNLOCK(ifp);
1222 			ifa_free(ifa);
1223 		} else
1224 			IF_ADDR_WUNLOCK(ifp);
1225 	}
1226 
1227 	rt_flushifroutes(ifp);
1228 
1229 #ifdef VIMAGE
1230 finish_vnet_shutdown:
1231 #endif
1232 	/*
1233 	 * We cannot hold the lock over dom_ifdetach calls as they might
1234 	 * sleep, for example trying to drain a callout, thus open up the
1235 	 * theoretical race with re-attaching.
1236 	 */
1237 	IF_AFDATA_LOCK(ifp);
1238 	i = ifp->if_afdata_initialized;
1239 	ifp->if_afdata_initialized = 0;
1240 	IF_AFDATA_UNLOCK(ifp);
1241 	for (dp = domains; i > 0 && dp; dp = dp->dom_next) {
1242 		if (dp->dom_ifdetach && ifp->if_afdata[dp->dom_family]) {
1243 			(*dp->dom_ifdetach)(ifp,
1244 			    ifp->if_afdata[dp->dom_family]);
1245 			ifp->if_afdata[dp->dom_family] = NULL;
1246 		}
1247 	}
1248 
1249 	return (0);
1250 }
1251 
1252 #ifdef VIMAGE
1253 /*
1254  * if_vmove() performs a limited version of if_detach() in current
1255  * vnet and if_attach()es the ifnet to the vnet specified as 2nd arg.
1256  * An attempt is made to shrink if_index in current vnet, find an
1257  * unused if_index in target vnet and calls if_grow() if necessary,
1258  * and finally find an unused if_xname for the target vnet.
1259  */
1260 static void
1261 if_vmove(struct ifnet *ifp, struct vnet *new_vnet)
1262 {
1263 	struct if_clone *ifc;
1264 	u_int bif_dlt, bif_hdrlen;
1265 	void *old;
1266 	int rc;
1267 
1268  	/*
1269 	 * if_detach_internal() will call the eventhandler to notify
1270 	 * interface departure.  That will detach if_bpf.  We need to
1271 	 * safe the dlt and hdrlen so we can re-attach it later.
1272 	 */
1273 	bpf_get_bp_params(ifp->if_bpf, &bif_dlt, &bif_hdrlen);
1274 
1275 	/*
1276 	 * Detach from current vnet, but preserve LLADDR info, do not
1277 	 * mark as dead etc. so that the ifnet can be reattached later.
1278 	 * If we cannot find it, we lost the race to someone else.
1279 	 */
1280 	rc = if_detach_internal(ifp, 1, &ifc);
1281 	if (rc != 0)
1282 		return;
1283 
1284 	/*
1285 	 * Unlink the ifnet from ifindex_table[] in current vnet, and shrink
1286 	 * the if_index for that vnet if possible.
1287 	 *
1288 	 * NOTE: IFNET_WLOCK/IFNET_WUNLOCK() are assumed to be unvirtualized,
1289 	 * or we'd lock on one vnet and unlock on another.
1290 	 */
1291 	IFNET_WLOCK();
1292 	ifindex_free_locked(ifp->if_index);
1293 	IFNET_WUNLOCK();
1294 
1295 	/*
1296 	 * Perform interface-specific reassignment tasks, if provided by
1297 	 * the driver.
1298 	 */
1299 	if (ifp->if_reassign != NULL)
1300 		ifp->if_reassign(ifp, new_vnet, NULL);
1301 
1302 	/*
1303 	 * Switch to the context of the target vnet.
1304 	 */
1305 	CURVNET_SET_QUIET(new_vnet);
1306  restart:
1307 	IFNET_WLOCK();
1308 	ifp->if_index = ifindex_alloc(&old);
1309 	if (__predict_false(ifp->if_index == USHRT_MAX)) {
1310 		IFNET_WUNLOCK();
1311 		epoch_wait_preempt(net_epoch_preempt);
1312 		free(old, M_IFNET);
1313 		goto restart;
1314 	}
1315 	ifnet_setbyindex(ifp->if_index, ifp);
1316 	IFNET_WUNLOCK();
1317 
1318 	if_attach_internal(ifp, 1, ifc);
1319 
1320 	if (ifp->if_bpf == NULL)
1321 		bpfattach(ifp, bif_dlt, bif_hdrlen);
1322 
1323 	CURVNET_RESTORE();
1324 }
1325 
1326 /*
1327  * Move an ifnet to or from another child prison/vnet, specified by the jail id.
1328  */
1329 static int
1330 if_vmove_loan(struct thread *td, struct ifnet *ifp, char *ifname, int jid)
1331 {
1332 	struct prison *pr;
1333 	struct ifnet *difp;
1334 
1335 	/* Try to find the prison within our visibility. */
1336 	sx_slock(&allprison_lock);
1337 	pr = prison_find_child(td->td_ucred->cr_prison, jid);
1338 	sx_sunlock(&allprison_lock);
1339 	if (pr == NULL)
1340 		return (ENXIO);
1341 	prison_hold_locked(pr);
1342 	mtx_unlock(&pr->pr_mtx);
1343 
1344 	/* Do not try to move the iface from and to the same prison. */
1345 	if (pr->pr_vnet == ifp->if_vnet) {
1346 		prison_free(pr);
1347 		return (EEXIST);
1348 	}
1349 
1350 	/* Make sure the named iface does not exists in the dst. prison/vnet. */
1351 	/* XXX Lock interfaces to avoid races. */
1352 	CURVNET_SET_QUIET(pr->pr_vnet);
1353 	difp = ifunit(ifname);
1354 	if (difp != NULL) {
1355 		CURVNET_RESTORE();
1356 		prison_free(pr);
1357 		return (EEXIST);
1358 	}
1359 
1360 	/* Make sure the VNET is stable. */
1361 	if (ifp->if_vnet->vnet_shutdown) {
1362 		CURVNET_RESTORE();
1363 		prison_free(pr);
1364 		return (EBUSY);
1365 	}
1366 	CURVNET_RESTORE();
1367 
1368 	/* Move the interface into the child jail/vnet. */
1369 	if_vmove(ifp, pr->pr_vnet);
1370 
1371 	/* Report the new if_xname back to the userland. */
1372 	sprintf(ifname, "%s", ifp->if_xname);
1373 
1374 	prison_free(pr);
1375 	return (0);
1376 }
1377 
1378 static int
1379 if_vmove_reclaim(struct thread *td, char *ifname, int jid)
1380 {
1381 	struct prison *pr;
1382 	struct vnet *vnet_dst;
1383 	struct ifnet *ifp;
1384 
1385 	/* Try to find the prison within our visibility. */
1386 	sx_slock(&allprison_lock);
1387 	pr = prison_find_child(td->td_ucred->cr_prison, jid);
1388 	sx_sunlock(&allprison_lock);
1389 	if (pr == NULL)
1390 		return (ENXIO);
1391 	prison_hold_locked(pr);
1392 	mtx_unlock(&pr->pr_mtx);
1393 
1394 	/* Make sure the named iface exists in the source prison/vnet. */
1395 	CURVNET_SET(pr->pr_vnet);
1396 	ifp = ifunit(ifname);		/* XXX Lock to avoid races. */
1397 	if (ifp == NULL) {
1398 		CURVNET_RESTORE();
1399 		prison_free(pr);
1400 		return (ENXIO);
1401 	}
1402 
1403 	/* Do not try to move the iface from and to the same prison. */
1404 	vnet_dst = TD_TO_VNET(td);
1405 	if (vnet_dst == ifp->if_vnet) {
1406 		CURVNET_RESTORE();
1407 		prison_free(pr);
1408 		return (EEXIST);
1409 	}
1410 
1411 	/* Make sure the VNET is stable. */
1412 	if (ifp->if_vnet->vnet_shutdown) {
1413 		CURVNET_RESTORE();
1414 		prison_free(pr);
1415 		return (EBUSY);
1416 	}
1417 
1418 	/* Get interface back from child jail/vnet. */
1419 	if_vmove(ifp, vnet_dst);
1420 	CURVNET_RESTORE();
1421 
1422 	/* Report the new if_xname back to the userland. */
1423 	sprintf(ifname, "%s", ifp->if_xname);
1424 
1425 	prison_free(pr);
1426 	return (0);
1427 }
1428 #endif /* VIMAGE */
1429 
1430 /*
1431  * Add a group to an interface
1432  */
1433 int
1434 if_addgroup(struct ifnet *ifp, const char *groupname)
1435 {
1436 	struct ifg_list		*ifgl;
1437 	struct ifg_group	*ifg = NULL;
1438 	struct ifg_member	*ifgm;
1439 	int 			 new = 0;
1440 
1441 	if (groupname[0] && groupname[strlen(groupname) - 1] >= '0' &&
1442 	    groupname[strlen(groupname) - 1] <= '9')
1443 		return (EINVAL);
1444 
1445 	IFNET_WLOCK();
1446 	CK_STAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1447 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname)) {
1448 			IFNET_WUNLOCK();
1449 			return (EEXIST);
1450 		}
1451 
1452 	if ((ifgl = (struct ifg_list *)malloc(sizeof(struct ifg_list), M_TEMP,
1453 	    M_NOWAIT)) == NULL) {
1454 	    	IFNET_WUNLOCK();
1455 		return (ENOMEM);
1456 	}
1457 
1458 	if ((ifgm = (struct ifg_member *)malloc(sizeof(struct ifg_member),
1459 	    M_TEMP, M_NOWAIT)) == NULL) {
1460 		free(ifgl, M_TEMP);
1461 		IFNET_WUNLOCK();
1462 		return (ENOMEM);
1463 	}
1464 
1465 	CK_STAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1466 		if (!strcmp(ifg->ifg_group, groupname))
1467 			break;
1468 
1469 	if (ifg == NULL) {
1470 		if ((ifg = (struct ifg_group *)malloc(sizeof(struct ifg_group),
1471 		    M_TEMP, M_NOWAIT)) == NULL) {
1472 			free(ifgl, M_TEMP);
1473 			free(ifgm, M_TEMP);
1474 			IFNET_WUNLOCK();
1475 			return (ENOMEM);
1476 		}
1477 		strlcpy(ifg->ifg_group, groupname, sizeof(ifg->ifg_group));
1478 		ifg->ifg_refcnt = 0;
1479 		CK_STAILQ_INIT(&ifg->ifg_members);
1480 		CK_STAILQ_INSERT_TAIL(&V_ifg_head, ifg, ifg_next);
1481 		new = 1;
1482 	}
1483 
1484 	ifg->ifg_refcnt++;
1485 	ifgl->ifgl_group = ifg;
1486 	ifgm->ifgm_ifp = ifp;
1487 
1488 	IF_ADDR_WLOCK(ifp);
1489 	CK_STAILQ_INSERT_TAIL(&ifg->ifg_members, ifgm, ifgm_next);
1490 	CK_STAILQ_INSERT_TAIL(&ifp->if_groups, ifgl, ifgl_next);
1491 	IF_ADDR_WUNLOCK(ifp);
1492 
1493 	IFNET_WUNLOCK();
1494 
1495 	if (new)
1496 		EVENTHANDLER_INVOKE(group_attach_event, ifg);
1497 	EVENTHANDLER_INVOKE(group_change_event, groupname);
1498 
1499 	return (0);
1500 }
1501 
1502 /*
1503  * Remove a group from an interface
1504  */
1505 int
1506 if_delgroup(struct ifnet *ifp, const char *groupname)
1507 {
1508 	struct ifg_list		*ifgl;
1509 	struct ifg_member	*ifgm;
1510 	int freeifgl;
1511 
1512 	IFNET_WLOCK();
1513 	CK_STAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1514 		if (!strcmp(ifgl->ifgl_group->ifg_group, groupname))
1515 			break;
1516 	if (ifgl == NULL) {
1517 		IFNET_WUNLOCK();
1518 		return (ENOENT);
1519 	}
1520 
1521 	freeifgl = 0;
1522 	IF_ADDR_WLOCK(ifp);
1523 	CK_STAILQ_REMOVE(&ifp->if_groups, ifgl, ifg_list, ifgl_next);
1524 	IF_ADDR_WUNLOCK(ifp);
1525 
1526 	CK_STAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1527 		if (ifgm->ifgm_ifp == ifp)
1528 			break;
1529 
1530 	if (ifgm != NULL)
1531 		CK_STAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifg_member, ifgm_next);
1532 
1533 	if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1534 		CK_STAILQ_REMOVE(&V_ifg_head, ifgl->ifgl_group, ifg_group, ifg_next);
1535 		freeifgl = 1;
1536 	}
1537 	IFNET_WUNLOCK();
1538 
1539 	epoch_wait_preempt(net_epoch_preempt);
1540 	if (freeifgl) {
1541 		EVENTHANDLER_INVOKE(group_detach_event, ifgl->ifgl_group);
1542 		free(ifgl->ifgl_group, M_TEMP);
1543 	}
1544 	free(ifgm, M_TEMP);
1545 	free(ifgl, M_TEMP);
1546 
1547 	EVENTHANDLER_INVOKE(group_change_event, groupname);
1548 
1549 	return (0);
1550 }
1551 
1552 /*
1553  * Remove an interface from all groups
1554  */
1555 static void
1556 if_delgroups(struct ifnet *ifp)
1557 {
1558 	struct ifg_list		*ifgl;
1559 	struct ifg_member	*ifgm;
1560 	char groupname[IFNAMSIZ];
1561 	int ifglfree;
1562 
1563 	IFNET_WLOCK();
1564 	while (!CK_STAILQ_EMPTY(&ifp->if_groups)) {
1565 		ifgl = CK_STAILQ_FIRST(&ifp->if_groups);
1566 
1567 		strlcpy(groupname, ifgl->ifgl_group->ifg_group, IFNAMSIZ);
1568 
1569 		IF_ADDR_WLOCK(ifp);
1570 		CK_STAILQ_REMOVE(&ifp->if_groups, ifgl, ifg_list, ifgl_next);
1571 		IF_ADDR_WUNLOCK(ifp);
1572 
1573 		CK_STAILQ_FOREACH(ifgm, &ifgl->ifgl_group->ifg_members, ifgm_next)
1574 			if (ifgm->ifgm_ifp == ifp)
1575 				break;
1576 
1577 		if (ifgm != NULL)
1578 			CK_STAILQ_REMOVE(&ifgl->ifgl_group->ifg_members, ifgm, ifg_member,
1579 			    ifgm_next);
1580 		ifglfree = 0;
1581 		if (--ifgl->ifgl_group->ifg_refcnt == 0) {
1582 			CK_STAILQ_REMOVE(&V_ifg_head, ifgl->ifgl_group, ifg_group, ifg_next);
1583 			ifglfree = 1;
1584 		}
1585 
1586 		IFNET_WUNLOCK();
1587 		epoch_wait_preempt(net_epoch_preempt);
1588 		free(ifgm, M_TEMP);
1589 		if (ifglfree) {
1590 			EVENTHANDLER_INVOKE(group_detach_event,
1591 								ifgl->ifgl_group);
1592 			free(ifgl->ifgl_group, M_TEMP);
1593 		}
1594 		EVENTHANDLER_INVOKE(group_change_event, groupname);
1595 
1596 		IFNET_WLOCK();
1597 	}
1598 	IFNET_WUNLOCK();
1599 }
1600 
1601 static char *
1602 ifgr_group_get(void *ifgrp)
1603 {
1604 	union ifgroupreq_union *ifgrup;
1605 
1606 	ifgrup = ifgrp;
1607 #ifdef COMPAT_FREEBSD32
1608 	if (SV_CURPROC_FLAG(SV_ILP32))
1609 		return (&ifgrup->ifgr32.ifgr_ifgru.ifgru_group[0]);
1610 #endif
1611 	return (&ifgrup->ifgr.ifgr_ifgru.ifgru_group[0]);
1612 }
1613 
1614 static struct ifg_req *
1615 ifgr_groups_get(void *ifgrp)
1616 {
1617 	union ifgroupreq_union *ifgrup;
1618 
1619 	ifgrup = ifgrp;
1620 #ifdef COMPAT_FREEBSD32
1621 	if (SV_CURPROC_FLAG(SV_ILP32))
1622 		return ((struct ifg_req *)(uintptr_t)
1623 		    ifgrup->ifgr32.ifgr_ifgru.ifgru_groups);
1624 #endif
1625 	return (ifgrup->ifgr.ifgr_ifgru.ifgru_groups);
1626 }
1627 
1628 /*
1629  * Stores all groups from an interface in memory pointed to by ifgr.
1630  */
1631 static int
1632 if_getgroup(struct ifgroupreq *ifgr, struct ifnet *ifp)
1633 {
1634 	int			 len, error;
1635 	struct ifg_list		*ifgl;
1636 	struct ifg_req		 ifgrq, *ifgp;
1637 
1638 	NET_EPOCH_ASSERT();
1639 
1640 	if (ifgr->ifgr_len == 0) {
1641 		CK_STAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next)
1642 			ifgr->ifgr_len += sizeof(struct ifg_req);
1643 		return (0);
1644 	}
1645 
1646 	len = ifgr->ifgr_len;
1647 	ifgp = ifgr_groups_get(ifgr);
1648 	/* XXX: wire */
1649 	CK_STAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
1650 		if (len < sizeof(ifgrq))
1651 			return (EINVAL);
1652 		bzero(&ifgrq, sizeof ifgrq);
1653 		strlcpy(ifgrq.ifgrq_group, ifgl->ifgl_group->ifg_group,
1654 		    sizeof(ifgrq.ifgrq_group));
1655 		if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req))))
1656 			return (error);
1657 		len -= sizeof(ifgrq);
1658 		ifgp++;
1659 	}
1660 
1661 	return (0);
1662 }
1663 
1664 /*
1665  * Stores all members of a group in memory pointed to by igfr
1666  */
1667 static int
1668 if_getgroupmembers(struct ifgroupreq *ifgr)
1669 {
1670 	struct ifg_group	*ifg;
1671 	struct ifg_member	*ifgm;
1672 	struct ifg_req		 ifgrq, *ifgp;
1673 	int			 len, error;
1674 
1675 	IFNET_RLOCK();
1676 	CK_STAILQ_FOREACH(ifg, &V_ifg_head, ifg_next)
1677 		if (!strcmp(ifg->ifg_group, ifgr->ifgr_name))
1678 			break;
1679 	if (ifg == NULL) {
1680 		IFNET_RUNLOCK();
1681 		return (ENOENT);
1682 	}
1683 
1684 	if (ifgr->ifgr_len == 0) {
1685 		CK_STAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next)
1686 			ifgr->ifgr_len += sizeof(ifgrq);
1687 		IFNET_RUNLOCK();
1688 		return (0);
1689 	}
1690 
1691 	len = ifgr->ifgr_len;
1692 	ifgp = ifgr_groups_get(ifgr);
1693 	CK_STAILQ_FOREACH(ifgm, &ifg->ifg_members, ifgm_next) {
1694 		if (len < sizeof(ifgrq)) {
1695 			IFNET_RUNLOCK();
1696 			return (EINVAL);
1697 		}
1698 		bzero(&ifgrq, sizeof ifgrq);
1699 		strlcpy(ifgrq.ifgrq_member, ifgm->ifgm_ifp->if_xname,
1700 		    sizeof(ifgrq.ifgrq_member));
1701 		if ((error = copyout(&ifgrq, ifgp, sizeof(struct ifg_req)))) {
1702 			IFNET_RUNLOCK();
1703 			return (error);
1704 		}
1705 		len -= sizeof(ifgrq);
1706 		ifgp++;
1707 	}
1708 	IFNET_RUNLOCK();
1709 
1710 	return (0);
1711 }
1712 
1713 /*
1714  * Return counter values from counter(9)s stored in ifnet.
1715  */
1716 uint64_t
1717 if_get_counter_default(struct ifnet *ifp, ift_counter cnt)
1718 {
1719 
1720 	KASSERT(cnt < IFCOUNTERS, ("%s: invalid cnt %d", __func__, cnt));
1721 
1722 	return (counter_u64_fetch(ifp->if_counters[cnt]));
1723 }
1724 
1725 /*
1726  * Increase an ifnet counter. Usually used for counters shared
1727  * between the stack and a driver, but function supports them all.
1728  */
1729 void
1730 if_inc_counter(struct ifnet *ifp, ift_counter cnt, int64_t inc)
1731 {
1732 
1733 	KASSERT(cnt < IFCOUNTERS, ("%s: invalid cnt %d", __func__, cnt));
1734 
1735 	counter_u64_add(ifp->if_counters[cnt], inc);
1736 }
1737 
1738 /*
1739  * Copy data from ifnet to userland API structure if_data.
1740  */
1741 void
1742 if_data_copy(struct ifnet *ifp, struct if_data *ifd)
1743 {
1744 
1745 	ifd->ifi_type = ifp->if_type;
1746 	ifd->ifi_physical = 0;
1747 	ifd->ifi_addrlen = ifp->if_addrlen;
1748 	ifd->ifi_hdrlen = ifp->if_hdrlen;
1749 	ifd->ifi_link_state = ifp->if_link_state;
1750 	ifd->ifi_vhid = 0;
1751 	ifd->ifi_datalen = sizeof(struct if_data);
1752 	ifd->ifi_mtu = ifp->if_mtu;
1753 	ifd->ifi_metric = ifp->if_metric;
1754 	ifd->ifi_baudrate = ifp->if_baudrate;
1755 	ifd->ifi_hwassist = ifp->if_hwassist;
1756 	ifd->ifi_epoch = ifp->if_epoch;
1757 	ifd->ifi_lastchange = ifp->if_lastchange;
1758 
1759 	ifd->ifi_ipackets = ifp->if_get_counter(ifp, IFCOUNTER_IPACKETS);
1760 	ifd->ifi_ierrors = ifp->if_get_counter(ifp, IFCOUNTER_IERRORS);
1761 	ifd->ifi_opackets = ifp->if_get_counter(ifp, IFCOUNTER_OPACKETS);
1762 	ifd->ifi_oerrors = ifp->if_get_counter(ifp, IFCOUNTER_OERRORS);
1763 	ifd->ifi_collisions = ifp->if_get_counter(ifp, IFCOUNTER_COLLISIONS);
1764 	ifd->ifi_ibytes = ifp->if_get_counter(ifp, IFCOUNTER_IBYTES);
1765 	ifd->ifi_obytes = ifp->if_get_counter(ifp, IFCOUNTER_OBYTES);
1766 	ifd->ifi_imcasts = ifp->if_get_counter(ifp, IFCOUNTER_IMCASTS);
1767 	ifd->ifi_omcasts = ifp->if_get_counter(ifp, IFCOUNTER_OMCASTS);
1768 	ifd->ifi_iqdrops = ifp->if_get_counter(ifp, IFCOUNTER_IQDROPS);
1769 	ifd->ifi_oqdrops = ifp->if_get_counter(ifp, IFCOUNTER_OQDROPS);
1770 	ifd->ifi_noproto = ifp->if_get_counter(ifp, IFCOUNTER_NOPROTO);
1771 }
1772 
1773 /*
1774  * Initialization, destruction and refcounting functions for ifaddrs.
1775  */
1776 struct ifaddr *
1777 ifa_alloc(size_t size, int flags)
1778 {
1779 	struct ifaddr *ifa;
1780 
1781 	KASSERT(size >= sizeof(struct ifaddr),
1782 	    ("%s: invalid size %zu", __func__, size));
1783 
1784 	ifa = malloc(size, M_IFADDR, M_ZERO | flags);
1785 	if (ifa == NULL)
1786 		return (NULL);
1787 
1788 	if ((ifa->ifa_opackets = counter_u64_alloc(flags)) == NULL)
1789 		goto fail;
1790 	if ((ifa->ifa_ipackets = counter_u64_alloc(flags)) == NULL)
1791 		goto fail;
1792 	if ((ifa->ifa_obytes = counter_u64_alloc(flags)) == NULL)
1793 		goto fail;
1794 	if ((ifa->ifa_ibytes = counter_u64_alloc(flags)) == NULL)
1795 		goto fail;
1796 
1797 	refcount_init(&ifa->ifa_refcnt, 1);
1798 
1799 	return (ifa);
1800 
1801 fail:
1802 	/* free(NULL) is okay */
1803 	counter_u64_free(ifa->ifa_opackets);
1804 	counter_u64_free(ifa->ifa_ipackets);
1805 	counter_u64_free(ifa->ifa_obytes);
1806 	counter_u64_free(ifa->ifa_ibytes);
1807 	free(ifa, M_IFADDR);
1808 
1809 	return (NULL);
1810 }
1811 
1812 void
1813 ifa_ref(struct ifaddr *ifa)
1814 {
1815 
1816 	refcount_acquire(&ifa->ifa_refcnt);
1817 }
1818 
1819 static void
1820 ifa_destroy(epoch_context_t ctx)
1821 {
1822 	struct ifaddr *ifa;
1823 
1824 	ifa = __containerof(ctx, struct ifaddr, ifa_epoch_ctx);
1825 	counter_u64_free(ifa->ifa_opackets);
1826 	counter_u64_free(ifa->ifa_ipackets);
1827 	counter_u64_free(ifa->ifa_obytes);
1828 	counter_u64_free(ifa->ifa_ibytes);
1829 	free(ifa, M_IFADDR);
1830 }
1831 
1832 void
1833 ifa_free(struct ifaddr *ifa)
1834 {
1835 
1836 	if (refcount_release(&ifa->ifa_refcnt))
1837 		epoch_call(net_epoch_preempt, &ifa->ifa_epoch_ctx, ifa_destroy);
1838 }
1839 
1840 
1841 static int
1842 ifa_maintain_loopback_route(int cmd, const char *otype, struct ifaddr *ifa,
1843     struct sockaddr *ia)
1844 {
1845 	struct epoch_tracker et;
1846 	int error;
1847 	struct rt_addrinfo info;
1848 	struct sockaddr_dl null_sdl;
1849 	struct ifnet *ifp;
1850 
1851 	ifp = ifa->ifa_ifp;
1852 
1853 	bzero(&info, sizeof(info));
1854 	if (cmd != RTM_DELETE)
1855 		info.rti_ifp = V_loif;
1856 	if (cmd == RTM_ADD) {
1857 		/* explicitly specify (loopback) ifa */
1858 		if (info.rti_ifp != NULL) {
1859 			NET_EPOCH_ENTER(et);
1860 			info.rti_ifa = ifaof_ifpforaddr(ifa->ifa_addr, info.rti_ifp);
1861 			if (info.rti_ifa != NULL)
1862 				ifa_ref(info.rti_ifa);
1863 			NET_EPOCH_EXIT(et);
1864 		}
1865 	}
1866 	info.rti_flags = ifa->ifa_flags | RTF_HOST | RTF_STATIC | RTF_PINNED;
1867 	info.rti_info[RTAX_DST] = ia;
1868 	info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&null_sdl;
1869 	link_init_sdl(ifp, (struct sockaddr *)&null_sdl, ifp->if_type);
1870 
1871 	error = rtrequest1_fib(cmd, &info, NULL, ifp->if_fib);
1872 
1873 	if (error != 0 &&
1874 	    !(cmd == RTM_ADD && error == EEXIST) &&
1875 	    !(cmd == RTM_DELETE && error == ENOENT))
1876 		if_printf(ifp, "%s failed: %d\n", otype, error);
1877 
1878 	return (error);
1879 }
1880 
1881 int
1882 ifa_add_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1883 {
1884 
1885 	return (ifa_maintain_loopback_route(RTM_ADD, "insertion", ifa, ia));
1886 }
1887 
1888 int
1889 ifa_del_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1890 {
1891 
1892 	return (ifa_maintain_loopback_route(RTM_DELETE, "deletion", ifa, ia));
1893 }
1894 
1895 int
1896 ifa_switch_loopback_route(struct ifaddr *ifa, struct sockaddr *ia)
1897 {
1898 
1899 	return (ifa_maintain_loopback_route(RTM_CHANGE, "switch", ifa, ia));
1900 }
1901 
1902 /*
1903  * XXX: Because sockaddr_dl has deeper structure than the sockaddr
1904  * structs used to represent other address families, it is necessary
1905  * to perform a different comparison.
1906  */
1907 
1908 #define	sa_dl_equal(a1, a2)	\
1909 	((((const struct sockaddr_dl *)(a1))->sdl_len ==		\
1910 	 ((const struct sockaddr_dl *)(a2))->sdl_len) &&		\
1911 	 (bcmp(CLLADDR((const struct sockaddr_dl *)(a1)),		\
1912 	       CLLADDR((const struct sockaddr_dl *)(a2)),		\
1913 	       ((const struct sockaddr_dl *)(a1))->sdl_alen) == 0))
1914 
1915 /*
1916  * Locate an interface based on a complete address.
1917  */
1918 /*ARGSUSED*/
1919 struct ifaddr *
1920 ifa_ifwithaddr(const struct sockaddr *addr)
1921 {
1922 	struct ifnet *ifp;
1923 	struct ifaddr *ifa;
1924 
1925 	NET_EPOCH_ASSERT();
1926 
1927 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1928 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1929 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1930 				continue;
1931 			if (sa_equal(addr, ifa->ifa_addr)) {
1932 				goto done;
1933 			}
1934 			/* IP6 doesn't have broadcast */
1935 			if ((ifp->if_flags & IFF_BROADCAST) &&
1936 			    ifa->ifa_broadaddr &&
1937 			    ifa->ifa_broadaddr->sa_len != 0 &&
1938 			    sa_equal(ifa->ifa_broadaddr, addr)) {
1939 				goto done;
1940 			}
1941 		}
1942 	}
1943 	ifa = NULL;
1944 done:
1945 	return (ifa);
1946 }
1947 
1948 int
1949 ifa_ifwithaddr_check(const struct sockaddr *addr)
1950 {
1951 	struct epoch_tracker et;
1952 	int rc;
1953 
1954 	NET_EPOCH_ENTER(et);
1955 	rc = (ifa_ifwithaddr(addr) != NULL);
1956 	NET_EPOCH_EXIT(et);
1957 	return (rc);
1958 }
1959 
1960 /*
1961  * Locate an interface based on the broadcast address.
1962  */
1963 /* ARGSUSED */
1964 struct ifaddr *
1965 ifa_ifwithbroadaddr(const struct sockaddr *addr, int fibnum)
1966 {
1967 	struct ifnet *ifp;
1968 	struct ifaddr *ifa;
1969 
1970 	MPASS(in_epoch(net_epoch_preempt));
1971 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1972 		if ((fibnum != RT_ALL_FIBS) && (ifp->if_fib != fibnum))
1973 			continue;
1974 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1975 			if (ifa->ifa_addr->sa_family != addr->sa_family)
1976 				continue;
1977 			if ((ifp->if_flags & IFF_BROADCAST) &&
1978 			    ifa->ifa_broadaddr &&
1979 			    ifa->ifa_broadaddr->sa_len != 0 &&
1980 			    sa_equal(ifa->ifa_broadaddr, addr)) {
1981 				goto done;
1982 			}
1983 		}
1984 	}
1985 	ifa = NULL;
1986 done:
1987 	return (ifa);
1988 }
1989 
1990 /*
1991  * Locate the point to point interface with a given destination address.
1992  */
1993 /*ARGSUSED*/
1994 struct ifaddr *
1995 ifa_ifwithdstaddr(const struct sockaddr *addr, int fibnum)
1996 {
1997 	struct ifnet *ifp;
1998 	struct ifaddr *ifa;
1999 
2000 	MPASS(in_epoch(net_epoch_preempt));
2001 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2002 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
2003 			continue;
2004 		if ((fibnum != RT_ALL_FIBS) && (ifp->if_fib != fibnum))
2005 			continue;
2006 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2007 			if (ifa->ifa_addr->sa_family != addr->sa_family)
2008 				continue;
2009 			if (ifa->ifa_dstaddr != NULL &&
2010 			    sa_equal(addr, ifa->ifa_dstaddr)) {
2011 				goto done;
2012 			}
2013 		}
2014 	}
2015 	ifa = NULL;
2016 done:
2017 	return (ifa);
2018 }
2019 
2020 /*
2021  * Find an interface on a specific network.  If many, choice
2022  * is most specific found.
2023  */
2024 struct ifaddr *
2025 ifa_ifwithnet(const struct sockaddr *addr, int ignore_ptp, int fibnum)
2026 {
2027 	struct ifnet *ifp;
2028 	struct ifaddr *ifa;
2029 	struct ifaddr *ifa_maybe = NULL;
2030 	u_int af = addr->sa_family;
2031 	const char *addr_data = addr->sa_data, *cplim;
2032 
2033 	MPASS(in_epoch(net_epoch_preempt));
2034 	/*
2035 	 * AF_LINK addresses can be looked up directly by their index number,
2036 	 * so do that if we can.
2037 	 */
2038 	if (af == AF_LINK) {
2039 	    const struct sockaddr_dl *sdl = (const struct sockaddr_dl *)addr;
2040 	    if (sdl->sdl_index && sdl->sdl_index <= V_if_index)
2041 		return (ifaddr_byindex(sdl->sdl_index));
2042 	}
2043 
2044 	/*
2045 	 * Scan though each interface, looking for ones that have addresses
2046 	 * in this address family and the requested fib.
2047 	 */
2048 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2049 		if ((fibnum != RT_ALL_FIBS) && (ifp->if_fib != fibnum))
2050 			continue;
2051 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2052 			const char *cp, *cp2, *cp3;
2053 
2054 			if (ifa->ifa_addr->sa_family != af)
2055 next:				continue;
2056 			if (af == AF_INET &&
2057 			    ifp->if_flags & IFF_POINTOPOINT && !ignore_ptp) {
2058 				/*
2059 				 * This is a bit broken as it doesn't
2060 				 * take into account that the remote end may
2061 				 * be a single node in the network we are
2062 				 * looking for.
2063 				 * The trouble is that we don't know the
2064 				 * netmask for the remote end.
2065 				 */
2066 				if (ifa->ifa_dstaddr != NULL &&
2067 				    sa_equal(addr, ifa->ifa_dstaddr)) {
2068 					goto done;
2069 				}
2070 			} else {
2071 				/*
2072 				 * Scan all the bits in the ifa's address.
2073 				 * If a bit dissagrees with what we are
2074 				 * looking for, mask it with the netmask
2075 				 * to see if it really matters.
2076 				 * (A byte at a time)
2077 				 */
2078 				if (ifa->ifa_netmask == 0)
2079 					continue;
2080 				cp = addr_data;
2081 				cp2 = ifa->ifa_addr->sa_data;
2082 				cp3 = ifa->ifa_netmask->sa_data;
2083 				cplim = ifa->ifa_netmask->sa_len
2084 					+ (char *)ifa->ifa_netmask;
2085 				while (cp3 < cplim)
2086 					if ((*cp++ ^ *cp2++) & *cp3++)
2087 						goto next; /* next address! */
2088 				/*
2089 				 * If the netmask of what we just found
2090 				 * is more specific than what we had before
2091 				 * (if we had one), or if the virtual status
2092 				 * of new prefix is better than of the old one,
2093 				 * then remember the new one before continuing
2094 				 * to search for an even better one.
2095 				 */
2096 				if (ifa_maybe == NULL ||
2097 				    ifa_preferred(ifa_maybe, ifa) ||
2098 				    rn_refines((caddr_t)ifa->ifa_netmask,
2099 				    (caddr_t)ifa_maybe->ifa_netmask)) {
2100 					ifa_maybe = ifa;
2101 				}
2102 			}
2103 		}
2104 	}
2105 	ifa = ifa_maybe;
2106 	ifa_maybe = NULL;
2107 done:
2108 	return (ifa);
2109 }
2110 
2111 /*
2112  * Find an interface address specific to an interface best matching
2113  * a given address.
2114  */
2115 struct ifaddr *
2116 ifaof_ifpforaddr(const struct sockaddr *addr, struct ifnet *ifp)
2117 {
2118 	struct ifaddr *ifa;
2119 	const char *cp, *cp2, *cp3;
2120 	char *cplim;
2121 	struct ifaddr *ifa_maybe = NULL;
2122 	u_int af = addr->sa_family;
2123 
2124 	if (af >= AF_MAX)
2125 		return (NULL);
2126 
2127 	MPASS(in_epoch(net_epoch_preempt));
2128 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2129 		if (ifa->ifa_addr->sa_family != af)
2130 			continue;
2131 		if (ifa_maybe == NULL)
2132 			ifa_maybe = ifa;
2133 		if (ifa->ifa_netmask == 0) {
2134 			if (sa_equal(addr, ifa->ifa_addr) ||
2135 			    (ifa->ifa_dstaddr &&
2136 			    sa_equal(addr, ifa->ifa_dstaddr)))
2137 				goto done;
2138 			continue;
2139 		}
2140 		if (ifp->if_flags & IFF_POINTOPOINT) {
2141 			if (sa_equal(addr, ifa->ifa_dstaddr))
2142 				goto done;
2143 		} else {
2144 			cp = addr->sa_data;
2145 			cp2 = ifa->ifa_addr->sa_data;
2146 			cp3 = ifa->ifa_netmask->sa_data;
2147 			cplim = ifa->ifa_netmask->sa_len + (char *)ifa->ifa_netmask;
2148 			for (; cp3 < cplim; cp3++)
2149 				if ((*cp++ ^ *cp2++) & *cp3)
2150 					break;
2151 			if (cp3 == cplim)
2152 				goto done;
2153 		}
2154 	}
2155 	ifa = ifa_maybe;
2156 done:
2157 	return (ifa);
2158 }
2159 
2160 /*
2161  * See whether new ifa is better than current one:
2162  * 1) A non-virtual one is preferred over virtual.
2163  * 2) A virtual in master state preferred over any other state.
2164  *
2165  * Used in several address selecting functions.
2166  */
2167 int
2168 ifa_preferred(struct ifaddr *cur, struct ifaddr *next)
2169 {
2170 
2171 	return (cur->ifa_carp && (!next->ifa_carp ||
2172 	    ((*carp_master_p)(next) && !(*carp_master_p)(cur))));
2173 }
2174 
2175 struct sockaddr_dl *
2176 link_alloc_sdl(size_t size, int flags)
2177 {
2178 
2179 	return (malloc(size, M_TEMP, flags));
2180 }
2181 
2182 void
2183 link_free_sdl(struct sockaddr *sa)
2184 {
2185 	free(sa, M_TEMP);
2186 }
2187 
2188 /*
2189  * Fills in given sdl with interface basic info.
2190  * Returns pointer to filled sdl.
2191  */
2192 struct sockaddr_dl *
2193 link_init_sdl(struct ifnet *ifp, struct sockaddr *paddr, u_char iftype)
2194 {
2195 	struct sockaddr_dl *sdl;
2196 
2197 	sdl = (struct sockaddr_dl *)paddr;
2198 	memset(sdl, 0, sizeof(struct sockaddr_dl));
2199 	sdl->sdl_len = sizeof(struct sockaddr_dl);
2200 	sdl->sdl_family = AF_LINK;
2201 	sdl->sdl_index = ifp->if_index;
2202 	sdl->sdl_type = iftype;
2203 
2204 	return (sdl);
2205 }
2206 
2207 /*
2208  * Mark an interface down and notify protocols of
2209  * the transition.
2210  */
2211 static void
2212 if_unroute(struct ifnet *ifp, int flag, int fam)
2213 {
2214 	struct ifaddr *ifa;
2215 
2216 	KASSERT(flag == IFF_UP, ("if_unroute: flag != IFF_UP"));
2217 
2218 	ifp->if_flags &= ~flag;
2219 	getmicrotime(&ifp->if_lastchange);
2220 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
2221 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
2222 			pfctlinput(PRC_IFDOWN, ifa->ifa_addr);
2223 	ifp->if_qflush(ifp);
2224 
2225 	if (ifp->if_carp)
2226 		(*carp_linkstate_p)(ifp);
2227 	rt_ifmsg(ifp);
2228 }
2229 
2230 /*
2231  * Mark an interface up and notify protocols of
2232  * the transition.
2233  */
2234 static void
2235 if_route(struct ifnet *ifp, int flag, int fam)
2236 {
2237 	struct ifaddr *ifa;
2238 
2239 	KASSERT(flag == IFF_UP, ("if_route: flag != IFF_UP"));
2240 
2241 	ifp->if_flags |= flag;
2242 	getmicrotime(&ifp->if_lastchange);
2243 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
2244 		if (fam == PF_UNSPEC || (fam == ifa->ifa_addr->sa_family))
2245 			pfctlinput(PRC_IFUP, ifa->ifa_addr);
2246 	if (ifp->if_carp)
2247 		(*carp_linkstate_p)(ifp);
2248 	rt_ifmsg(ifp);
2249 #ifdef INET6
2250 	in6_if_up(ifp);
2251 #endif
2252 }
2253 
2254 void	(*vlan_link_state_p)(struct ifnet *);	/* XXX: private from if_vlan */
2255 void	(*vlan_trunk_cap_p)(struct ifnet *);		/* XXX: private from if_vlan */
2256 struct ifnet *(*vlan_trunkdev_p)(struct ifnet *);
2257 struct	ifnet *(*vlan_devat_p)(struct ifnet *, uint16_t);
2258 int	(*vlan_tag_p)(struct ifnet *, uint16_t *);
2259 int	(*vlan_pcp_p)(struct ifnet *, uint16_t *);
2260 int	(*vlan_setcookie_p)(struct ifnet *, void *);
2261 void	*(*vlan_cookie_p)(struct ifnet *);
2262 
2263 /*
2264  * Handle a change in the interface link state. To avoid LORs
2265  * between driver lock and upper layer locks, as well as possible
2266  * recursions, we post event to taskqueue, and all job
2267  * is done in static do_link_state_change().
2268  */
2269 void
2270 if_link_state_change(struct ifnet *ifp, int link_state)
2271 {
2272 	/* Return if state hasn't changed. */
2273 	if (ifp->if_link_state == link_state)
2274 		return;
2275 
2276 	ifp->if_link_state = link_state;
2277 
2278 	/* XXXGL: reference ifp? */
2279 	taskqueue_enqueue(taskqueue_swi, &ifp->if_linktask);
2280 }
2281 
2282 static void
2283 do_link_state_change(void *arg, int pending)
2284 {
2285 	struct ifnet *ifp;
2286 	int link_state;
2287 
2288 	ifp = arg;
2289 	link_state = ifp->if_link_state;
2290 
2291 	CURVNET_SET(ifp->if_vnet);
2292 	rt_ifmsg(ifp);
2293 	if (ifp->if_vlantrunk != NULL)
2294 		(*vlan_link_state_p)(ifp);
2295 
2296 	if ((ifp->if_type == IFT_ETHER || ifp->if_type == IFT_L2VLAN) &&
2297 	    ifp->if_l2com != NULL)
2298 		(*ng_ether_link_state_p)(ifp, link_state);
2299 	if (ifp->if_carp)
2300 		(*carp_linkstate_p)(ifp);
2301 	if (ifp->if_bridge)
2302 		ifp->if_bridge_linkstate(ifp);
2303 	if (ifp->if_lagg)
2304 		(*lagg_linkstate_p)(ifp, link_state);
2305 
2306 	if (IS_DEFAULT_VNET(curvnet))
2307 		devctl_notify("IFNET", ifp->if_xname,
2308 		    (link_state == LINK_STATE_UP) ? "LINK_UP" : "LINK_DOWN",
2309 		    NULL);
2310 	if (pending > 1)
2311 		if_printf(ifp, "%d link states coalesced\n", pending);
2312 	if (log_link_state_change)
2313 		if_printf(ifp, "link state changed to %s\n",
2314 		    (link_state == LINK_STATE_UP) ? "UP" : "DOWN" );
2315 	EVENTHANDLER_INVOKE(ifnet_link_event, ifp, link_state);
2316 	CURVNET_RESTORE();
2317 }
2318 
2319 /*
2320  * Mark an interface down and notify protocols of
2321  * the transition.
2322  */
2323 void
2324 if_down(struct ifnet *ifp)
2325 {
2326 
2327 	EVENTHANDLER_INVOKE(ifnet_event, ifp, IFNET_EVENT_DOWN);
2328 	if_unroute(ifp, IFF_UP, AF_UNSPEC);
2329 }
2330 
2331 /*
2332  * Mark an interface up and notify protocols of
2333  * the transition.
2334  */
2335 void
2336 if_up(struct ifnet *ifp)
2337 {
2338 
2339 	if_route(ifp, IFF_UP, AF_UNSPEC);
2340 	EVENTHANDLER_INVOKE(ifnet_event, ifp, IFNET_EVENT_UP);
2341 }
2342 
2343 /*
2344  * Flush an interface queue.
2345  */
2346 void
2347 if_qflush(struct ifnet *ifp)
2348 {
2349 	struct mbuf *m, *n;
2350 	struct ifaltq *ifq;
2351 
2352 	ifq = &ifp->if_snd;
2353 	IFQ_LOCK(ifq);
2354 #ifdef ALTQ
2355 	if (ALTQ_IS_ENABLED(ifq))
2356 		ALTQ_PURGE(ifq);
2357 #endif
2358 	n = ifq->ifq_head;
2359 	while ((m = n) != NULL) {
2360 		n = m->m_nextpkt;
2361 		m_freem(m);
2362 	}
2363 	ifq->ifq_head = 0;
2364 	ifq->ifq_tail = 0;
2365 	ifq->ifq_len = 0;
2366 	IFQ_UNLOCK(ifq);
2367 }
2368 
2369 /*
2370  * Map interface name to interface structure pointer, with or without
2371  * returning a reference.
2372  */
2373 struct ifnet *
2374 ifunit_ref(const char *name)
2375 {
2376 	struct epoch_tracker et;
2377 	struct ifnet *ifp;
2378 
2379 	NET_EPOCH_ENTER(et);
2380 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2381 		if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0 &&
2382 		    !(ifp->if_flags & IFF_DYING))
2383 			break;
2384 	}
2385 	if (ifp != NULL)
2386 		if_ref(ifp);
2387 	NET_EPOCH_EXIT(et);
2388 	return (ifp);
2389 }
2390 
2391 struct ifnet *
2392 ifunit(const char *name)
2393 {
2394 	struct epoch_tracker et;
2395 	struct ifnet *ifp;
2396 
2397 	NET_EPOCH_ENTER(et);
2398 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2399 		if (strncmp(name, ifp->if_xname, IFNAMSIZ) == 0)
2400 			break;
2401 	}
2402 	NET_EPOCH_EXIT(et);
2403 	return (ifp);
2404 }
2405 
2406 static void *
2407 ifr_buffer_get_buffer(void *data)
2408 {
2409 	union ifreq_union *ifrup;
2410 
2411 	ifrup = data;
2412 #ifdef COMPAT_FREEBSD32
2413 	if (SV_CURPROC_FLAG(SV_ILP32))
2414 		return ((void *)(uintptr_t)
2415 		    ifrup->ifr32.ifr_ifru.ifru_buffer.buffer);
2416 #endif
2417 	return (ifrup->ifr.ifr_ifru.ifru_buffer.buffer);
2418 }
2419 
2420 static void
2421 ifr_buffer_set_buffer_null(void *data)
2422 {
2423 	union ifreq_union *ifrup;
2424 
2425 	ifrup = data;
2426 #ifdef COMPAT_FREEBSD32
2427 	if (SV_CURPROC_FLAG(SV_ILP32))
2428 		ifrup->ifr32.ifr_ifru.ifru_buffer.buffer = 0;
2429 	else
2430 #endif
2431 		ifrup->ifr.ifr_ifru.ifru_buffer.buffer = NULL;
2432 }
2433 
2434 static size_t
2435 ifr_buffer_get_length(void *data)
2436 {
2437 	union ifreq_union *ifrup;
2438 
2439 	ifrup = data;
2440 #ifdef COMPAT_FREEBSD32
2441 	if (SV_CURPROC_FLAG(SV_ILP32))
2442 		return (ifrup->ifr32.ifr_ifru.ifru_buffer.length);
2443 #endif
2444 	return (ifrup->ifr.ifr_ifru.ifru_buffer.length);
2445 }
2446 
2447 static void
2448 ifr_buffer_set_length(void *data, size_t len)
2449 {
2450 	union ifreq_union *ifrup;
2451 
2452 	ifrup = data;
2453 #ifdef COMPAT_FREEBSD32
2454 	if (SV_CURPROC_FLAG(SV_ILP32))
2455 		ifrup->ifr32.ifr_ifru.ifru_buffer.length = len;
2456 	else
2457 #endif
2458 		ifrup->ifr.ifr_ifru.ifru_buffer.length = len;
2459 }
2460 
2461 void *
2462 ifr_data_get_ptr(void *ifrp)
2463 {
2464 	union ifreq_union *ifrup;
2465 
2466 	ifrup = ifrp;
2467 #ifdef COMPAT_FREEBSD32
2468 	if (SV_CURPROC_FLAG(SV_ILP32))
2469 		return ((void *)(uintptr_t)
2470 		    ifrup->ifr32.ifr_ifru.ifru_data);
2471 #endif
2472 		return (ifrup->ifr.ifr_ifru.ifru_data);
2473 }
2474 
2475 /*
2476  * Hardware specific interface ioctls.
2477  */
2478 int
2479 ifhwioctl(u_long cmd, struct ifnet *ifp, caddr_t data, struct thread *td)
2480 {
2481 	struct ifreq *ifr;
2482 	int error = 0, do_ifup = 0;
2483 	int new_flags, temp_flags;
2484 	size_t namelen, onamelen;
2485 	size_t descrlen;
2486 	char *descrbuf, *odescrbuf;
2487 	char new_name[IFNAMSIZ];
2488 	struct ifaddr *ifa;
2489 	struct sockaddr_dl *sdl;
2490 
2491 	ifr = (struct ifreq *)data;
2492 	switch (cmd) {
2493 	case SIOCGIFINDEX:
2494 		ifr->ifr_index = ifp->if_index;
2495 		break;
2496 
2497 	case SIOCGIFFLAGS:
2498 		temp_flags = ifp->if_flags | ifp->if_drv_flags;
2499 		ifr->ifr_flags = temp_flags & 0xffff;
2500 		ifr->ifr_flagshigh = temp_flags >> 16;
2501 		break;
2502 
2503 	case SIOCGIFCAP:
2504 		ifr->ifr_reqcap = ifp->if_capabilities;
2505 		ifr->ifr_curcap = ifp->if_capenable;
2506 		break;
2507 
2508 #ifdef MAC
2509 	case SIOCGIFMAC:
2510 		error = mac_ifnet_ioctl_get(td->td_ucred, ifr, ifp);
2511 		break;
2512 #endif
2513 
2514 	case SIOCGIFMETRIC:
2515 		ifr->ifr_metric = ifp->if_metric;
2516 		break;
2517 
2518 	case SIOCGIFMTU:
2519 		ifr->ifr_mtu = ifp->if_mtu;
2520 		break;
2521 
2522 	case SIOCGIFPHYS:
2523 		/* XXXGL: did this ever worked? */
2524 		ifr->ifr_phys = 0;
2525 		break;
2526 
2527 	case SIOCGIFDESCR:
2528 		error = 0;
2529 		sx_slock(&ifdescr_sx);
2530 		if (ifp->if_description == NULL)
2531 			error = ENOMSG;
2532 		else {
2533 			/* space for terminating nul */
2534 			descrlen = strlen(ifp->if_description) + 1;
2535 			if (ifr_buffer_get_length(ifr) < descrlen)
2536 				ifr_buffer_set_buffer_null(ifr);
2537 			else
2538 				error = copyout(ifp->if_description,
2539 				    ifr_buffer_get_buffer(ifr), descrlen);
2540 			ifr_buffer_set_length(ifr, descrlen);
2541 		}
2542 		sx_sunlock(&ifdescr_sx);
2543 		break;
2544 
2545 	case SIOCSIFDESCR:
2546 		error = priv_check(td, PRIV_NET_SETIFDESCR);
2547 		if (error)
2548 			return (error);
2549 
2550 		/*
2551 		 * Copy only (length-1) bytes to make sure that
2552 		 * if_description is always nul terminated.  The
2553 		 * length parameter is supposed to count the
2554 		 * terminating nul in.
2555 		 */
2556 		if (ifr_buffer_get_length(ifr) > ifdescr_maxlen)
2557 			return (ENAMETOOLONG);
2558 		else if (ifr_buffer_get_length(ifr) == 0)
2559 			descrbuf = NULL;
2560 		else {
2561 			descrbuf = malloc(ifr_buffer_get_length(ifr),
2562 			    M_IFDESCR, M_WAITOK | M_ZERO);
2563 			error = copyin(ifr_buffer_get_buffer(ifr), descrbuf,
2564 			    ifr_buffer_get_length(ifr) - 1);
2565 			if (error) {
2566 				free(descrbuf, M_IFDESCR);
2567 				break;
2568 			}
2569 		}
2570 
2571 		sx_xlock(&ifdescr_sx);
2572 		odescrbuf = ifp->if_description;
2573 		ifp->if_description = descrbuf;
2574 		sx_xunlock(&ifdescr_sx);
2575 
2576 		getmicrotime(&ifp->if_lastchange);
2577 		free(odescrbuf, M_IFDESCR);
2578 		break;
2579 
2580 	case SIOCGIFFIB:
2581 		ifr->ifr_fib = ifp->if_fib;
2582 		break;
2583 
2584 	case SIOCSIFFIB:
2585 		error = priv_check(td, PRIV_NET_SETIFFIB);
2586 		if (error)
2587 			return (error);
2588 		if (ifr->ifr_fib >= rt_numfibs)
2589 			return (EINVAL);
2590 
2591 		ifp->if_fib = ifr->ifr_fib;
2592 		break;
2593 
2594 	case SIOCSIFFLAGS:
2595 		error = priv_check(td, PRIV_NET_SETIFFLAGS);
2596 		if (error)
2597 			return (error);
2598 		/*
2599 		 * Currently, no driver owned flags pass the IFF_CANTCHANGE
2600 		 * check, so we don't need special handling here yet.
2601 		 */
2602 		new_flags = (ifr->ifr_flags & 0xffff) |
2603 		    (ifr->ifr_flagshigh << 16);
2604 		if (ifp->if_flags & IFF_UP &&
2605 		    (new_flags & IFF_UP) == 0) {
2606 			if_down(ifp);
2607 		} else if (new_flags & IFF_UP &&
2608 		    (ifp->if_flags & IFF_UP) == 0) {
2609 			do_ifup = 1;
2610 		}
2611 		/* See if permanently promiscuous mode bit is about to flip */
2612 		if ((ifp->if_flags ^ new_flags) & IFF_PPROMISC) {
2613 			if (new_flags & IFF_PPROMISC)
2614 				ifp->if_flags |= IFF_PROMISC;
2615 			else if (ifp->if_pcount == 0)
2616 				ifp->if_flags &= ~IFF_PROMISC;
2617 			if (log_promisc_mode_change)
2618                                 if_printf(ifp, "permanently promiscuous mode %s\n",
2619                                     ((new_flags & IFF_PPROMISC) ?
2620                                      "enabled" : "disabled"));
2621 		}
2622 		ifp->if_flags = (ifp->if_flags & IFF_CANTCHANGE) |
2623 			(new_flags &~ IFF_CANTCHANGE);
2624 		if (ifp->if_ioctl) {
2625 			(void) (*ifp->if_ioctl)(ifp, cmd, data);
2626 		}
2627 		if (do_ifup)
2628 			if_up(ifp);
2629 		getmicrotime(&ifp->if_lastchange);
2630 		break;
2631 
2632 	case SIOCSIFCAP:
2633 		error = priv_check(td, PRIV_NET_SETIFCAP);
2634 		if (error)
2635 			return (error);
2636 		if (ifp->if_ioctl == NULL)
2637 			return (EOPNOTSUPP);
2638 		if (ifr->ifr_reqcap & ~ifp->if_capabilities)
2639 			return (EINVAL);
2640 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2641 		if (error == 0)
2642 			getmicrotime(&ifp->if_lastchange);
2643 		break;
2644 
2645 #ifdef MAC
2646 	case SIOCSIFMAC:
2647 		error = mac_ifnet_ioctl_set(td->td_ucred, ifr, ifp);
2648 		break;
2649 #endif
2650 
2651 	case SIOCSIFNAME:
2652 		error = priv_check(td, PRIV_NET_SETIFNAME);
2653 		if (error)
2654 			return (error);
2655 		error = copyinstr(ifr_data_get_ptr(ifr), new_name, IFNAMSIZ,
2656 		    NULL);
2657 		if (error != 0)
2658 			return (error);
2659 		if (new_name[0] == '\0')
2660 			return (EINVAL);
2661 		if (new_name[IFNAMSIZ-1] != '\0') {
2662 			new_name[IFNAMSIZ-1] = '\0';
2663 			if (strlen(new_name) == IFNAMSIZ-1)
2664 				return (EINVAL);
2665 		}
2666 		if (strcmp(new_name, ifp->if_xname) == 0)
2667 			break;
2668 		if (ifunit(new_name) != NULL)
2669 			return (EEXIST);
2670 
2671 		/*
2672 		 * XXX: Locking.  Nothing else seems to lock if_flags,
2673 		 * and there are numerous other races with the
2674 		 * ifunit() checks not being atomic with namespace
2675 		 * changes (renames, vmoves, if_attach, etc).
2676 		 */
2677 		ifp->if_flags |= IFF_RENAMING;
2678 
2679 		/* Announce the departure of the interface. */
2680 		rt_ifannouncemsg(ifp, IFAN_DEPARTURE);
2681 		EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
2682 
2683 		if_printf(ifp, "changing name to '%s'\n", new_name);
2684 
2685 		IF_ADDR_WLOCK(ifp);
2686 		strlcpy(ifp->if_xname, new_name, sizeof(ifp->if_xname));
2687 		ifa = ifp->if_addr;
2688 		sdl = (struct sockaddr_dl *)ifa->ifa_addr;
2689 		namelen = strlen(new_name);
2690 		onamelen = sdl->sdl_nlen;
2691 		/*
2692 		 * Move the address if needed.  This is safe because we
2693 		 * allocate space for a name of length IFNAMSIZ when we
2694 		 * create this in if_attach().
2695 		 */
2696 		if (namelen != onamelen) {
2697 			bcopy(sdl->sdl_data + onamelen,
2698 			    sdl->sdl_data + namelen, sdl->sdl_alen);
2699 		}
2700 		bcopy(new_name, sdl->sdl_data, namelen);
2701 		sdl->sdl_nlen = namelen;
2702 		sdl = (struct sockaddr_dl *)ifa->ifa_netmask;
2703 		bzero(sdl->sdl_data, onamelen);
2704 		while (namelen != 0)
2705 			sdl->sdl_data[--namelen] = 0xff;
2706 		IF_ADDR_WUNLOCK(ifp);
2707 
2708 		EVENTHANDLER_INVOKE(ifnet_arrival_event, ifp);
2709 		/* Announce the return of the interface. */
2710 		rt_ifannouncemsg(ifp, IFAN_ARRIVAL);
2711 
2712 		ifp->if_flags &= ~IFF_RENAMING;
2713 		break;
2714 
2715 #ifdef VIMAGE
2716 	case SIOCSIFVNET:
2717 		error = priv_check(td, PRIV_NET_SETIFVNET);
2718 		if (error)
2719 			return (error);
2720 		error = if_vmove_loan(td, ifp, ifr->ifr_name, ifr->ifr_jid);
2721 		break;
2722 #endif
2723 
2724 	case SIOCSIFMETRIC:
2725 		error = priv_check(td, PRIV_NET_SETIFMETRIC);
2726 		if (error)
2727 			return (error);
2728 		ifp->if_metric = ifr->ifr_metric;
2729 		getmicrotime(&ifp->if_lastchange);
2730 		break;
2731 
2732 	case SIOCSIFPHYS:
2733 		error = priv_check(td, PRIV_NET_SETIFPHYS);
2734 		if (error)
2735 			return (error);
2736 		if (ifp->if_ioctl == NULL)
2737 			return (EOPNOTSUPP);
2738 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2739 		if (error == 0)
2740 			getmicrotime(&ifp->if_lastchange);
2741 		break;
2742 
2743 	case SIOCSIFMTU:
2744 	{
2745 		u_long oldmtu = ifp->if_mtu;
2746 
2747 		error = priv_check(td, PRIV_NET_SETIFMTU);
2748 		if (error)
2749 			return (error);
2750 		if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU)
2751 			return (EINVAL);
2752 		if (ifp->if_ioctl == NULL)
2753 			return (EOPNOTSUPP);
2754 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2755 		if (error == 0) {
2756 			getmicrotime(&ifp->if_lastchange);
2757 			rt_ifmsg(ifp);
2758 #ifdef INET
2759 			DEBUGNET_NOTIFY_MTU(ifp);
2760 #endif
2761 		}
2762 		/*
2763 		 * If the link MTU changed, do network layer specific procedure.
2764 		 */
2765 		if (ifp->if_mtu != oldmtu) {
2766 #ifdef INET6
2767 			nd6_setmtu(ifp);
2768 #endif
2769 			rt_updatemtu(ifp);
2770 		}
2771 		break;
2772 	}
2773 
2774 	case SIOCADDMULTI:
2775 	case SIOCDELMULTI:
2776 		if (cmd == SIOCADDMULTI)
2777 			error = priv_check(td, PRIV_NET_ADDMULTI);
2778 		else
2779 			error = priv_check(td, PRIV_NET_DELMULTI);
2780 		if (error)
2781 			return (error);
2782 
2783 		/* Don't allow group membership on non-multicast interfaces. */
2784 		if ((ifp->if_flags & IFF_MULTICAST) == 0)
2785 			return (EOPNOTSUPP);
2786 
2787 		/* Don't let users screw up protocols' entries. */
2788 		if (ifr->ifr_addr.sa_family != AF_LINK)
2789 			return (EINVAL);
2790 
2791 		if (cmd == SIOCADDMULTI) {
2792 			struct epoch_tracker et;
2793 			struct ifmultiaddr *ifma;
2794 
2795 			/*
2796 			 * Userland is only permitted to join groups once
2797 			 * via the if_addmulti() KPI, because it cannot hold
2798 			 * struct ifmultiaddr * between calls. It may also
2799 			 * lose a race while we check if the membership
2800 			 * already exists.
2801 			 */
2802 			NET_EPOCH_ENTER(et);
2803 			ifma = if_findmulti(ifp, &ifr->ifr_addr);
2804 			NET_EPOCH_EXIT(et);
2805 			if (ifma != NULL)
2806 				error = EADDRINUSE;
2807 			else
2808 				error = if_addmulti(ifp, &ifr->ifr_addr, &ifma);
2809 		} else {
2810 			error = if_delmulti(ifp, &ifr->ifr_addr);
2811 		}
2812 		if (error == 0)
2813 			getmicrotime(&ifp->if_lastchange);
2814 		break;
2815 
2816 	case SIOCSIFPHYADDR:
2817 	case SIOCDIFPHYADDR:
2818 #ifdef INET6
2819 	case SIOCSIFPHYADDR_IN6:
2820 #endif
2821 	case SIOCSIFMEDIA:
2822 	case SIOCSIFGENERIC:
2823 		error = priv_check(td, PRIV_NET_HWIOCTL);
2824 		if (error)
2825 			return (error);
2826 		if (ifp->if_ioctl == NULL)
2827 			return (EOPNOTSUPP);
2828 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2829 		if (error == 0)
2830 			getmicrotime(&ifp->if_lastchange);
2831 		break;
2832 
2833 	case SIOCGIFSTATUS:
2834 	case SIOCGIFPSRCADDR:
2835 	case SIOCGIFPDSTADDR:
2836 	case SIOCGIFMEDIA:
2837 	case SIOCGIFXMEDIA:
2838 	case SIOCGIFGENERIC:
2839 	case SIOCGIFRSSKEY:
2840 	case SIOCGIFRSSHASH:
2841 	case SIOCGIFDOWNREASON:
2842 		if (ifp->if_ioctl == NULL)
2843 			return (EOPNOTSUPP);
2844 		error = (*ifp->if_ioctl)(ifp, cmd, data);
2845 		break;
2846 
2847 	case SIOCSIFLLADDR:
2848 		error = priv_check(td, PRIV_NET_SETLLADDR);
2849 		if (error)
2850 			return (error);
2851 		error = if_setlladdr(ifp,
2852 		    ifr->ifr_addr.sa_data, ifr->ifr_addr.sa_len);
2853 		break;
2854 
2855 	case SIOCGHWADDR:
2856 		error = if_gethwaddr(ifp, ifr);
2857 		break;
2858 
2859 	case CASE_IOC_IFGROUPREQ(SIOCAIFGROUP):
2860 		error = priv_check(td, PRIV_NET_ADDIFGROUP);
2861 		if (error)
2862 			return (error);
2863 		if ((error = if_addgroup(ifp,
2864 		    ifgr_group_get((struct ifgroupreq *)data))))
2865 			return (error);
2866 		break;
2867 
2868 	case CASE_IOC_IFGROUPREQ(SIOCGIFGROUP):
2869 	{
2870 		struct epoch_tracker et;
2871 
2872 		NET_EPOCH_ENTER(et);
2873 		error = if_getgroup((struct ifgroupreq *)data, ifp);
2874 		NET_EPOCH_EXIT(et);
2875 		break;
2876 	}
2877 
2878 	case CASE_IOC_IFGROUPREQ(SIOCDIFGROUP):
2879 		error = priv_check(td, PRIV_NET_DELIFGROUP);
2880 		if (error)
2881 			return (error);
2882 		if ((error = if_delgroup(ifp,
2883 		    ifgr_group_get((struct ifgroupreq *)data))))
2884 			return (error);
2885 		break;
2886 
2887 	default:
2888 		error = ENOIOCTL;
2889 		break;
2890 	}
2891 	return (error);
2892 }
2893 
2894 #ifdef COMPAT_FREEBSD32
2895 struct ifconf32 {
2896 	int32_t	ifc_len;
2897 	union {
2898 		uint32_t	ifcu_buf;
2899 		uint32_t	ifcu_req;
2900 	} ifc_ifcu;
2901 };
2902 #define	SIOCGIFCONF32	_IOWR('i', 36, struct ifconf32)
2903 #endif
2904 
2905 #ifdef COMPAT_FREEBSD32
2906 static void
2907 ifmr_init(struct ifmediareq *ifmr, caddr_t data)
2908 {
2909 	struct ifmediareq32 *ifmr32;
2910 
2911 	ifmr32 = (struct ifmediareq32 *)data;
2912 	memcpy(ifmr->ifm_name, ifmr32->ifm_name,
2913 	    sizeof(ifmr->ifm_name));
2914 	ifmr->ifm_current = ifmr32->ifm_current;
2915 	ifmr->ifm_mask = ifmr32->ifm_mask;
2916 	ifmr->ifm_status = ifmr32->ifm_status;
2917 	ifmr->ifm_active = ifmr32->ifm_active;
2918 	ifmr->ifm_count = ifmr32->ifm_count;
2919 	ifmr->ifm_ulist = (int *)(uintptr_t)ifmr32->ifm_ulist;
2920 }
2921 
2922 static void
2923 ifmr_update(const struct ifmediareq *ifmr, caddr_t data)
2924 {
2925 	struct ifmediareq32 *ifmr32;
2926 
2927 	ifmr32 = (struct ifmediareq32 *)data;
2928 	ifmr32->ifm_current = ifmr->ifm_current;
2929 	ifmr32->ifm_mask = ifmr->ifm_mask;
2930 	ifmr32->ifm_status = ifmr->ifm_status;
2931 	ifmr32->ifm_active = ifmr->ifm_active;
2932 	ifmr32->ifm_count = ifmr->ifm_count;
2933 }
2934 #endif
2935 
2936 /*
2937  * Interface ioctls.
2938  */
2939 int
2940 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct thread *td)
2941 {
2942 #ifdef COMPAT_FREEBSD32
2943 	caddr_t saved_data = NULL;
2944 	struct ifmediareq ifmr;
2945 	struct ifmediareq *ifmrp = NULL;
2946 #endif
2947 	struct ifnet *ifp;
2948 	struct ifreq *ifr;
2949 	int error;
2950 	int oif_flags;
2951 
2952 	CURVNET_SET(so->so_vnet);
2953 #ifdef VIMAGE
2954 	/* Make sure the VNET is stable. */
2955 	if (so->so_vnet->vnet_shutdown) {
2956 		CURVNET_RESTORE();
2957 		return (EBUSY);
2958 	}
2959 #endif
2960 
2961 	switch (cmd) {
2962 	case SIOCGIFCONF:
2963 		error = ifconf(cmd, data);
2964 		goto out_noref;
2965 
2966 #ifdef COMPAT_FREEBSD32
2967 	case SIOCGIFCONF32:
2968 		{
2969 			struct ifconf32 *ifc32;
2970 			struct ifconf ifc;
2971 
2972 			ifc32 = (struct ifconf32 *)data;
2973 			ifc.ifc_len = ifc32->ifc_len;
2974 			ifc.ifc_buf = PTRIN(ifc32->ifc_buf);
2975 
2976 			error = ifconf(SIOCGIFCONF, (void *)&ifc);
2977 			if (error == 0)
2978 				ifc32->ifc_len = ifc.ifc_len;
2979 			goto out_noref;
2980 		}
2981 #endif
2982 	}
2983 
2984 #ifdef COMPAT_FREEBSD32
2985 	switch (cmd) {
2986 	case SIOCGIFMEDIA32:
2987 	case SIOCGIFXMEDIA32:
2988 		ifmrp = &ifmr;
2989 		ifmr_init(ifmrp, data);
2990 		cmd = _IOC_NEWTYPE(cmd, struct ifmediareq);
2991 		saved_data = data;
2992 		data = (caddr_t)ifmrp;
2993 	}
2994 #endif
2995 
2996 	ifr = (struct ifreq *)data;
2997 	switch (cmd) {
2998 #ifdef VIMAGE
2999 	case SIOCSIFRVNET:
3000 		error = priv_check(td, PRIV_NET_SETIFVNET);
3001 		if (error == 0)
3002 			error = if_vmove_reclaim(td, ifr->ifr_name,
3003 			    ifr->ifr_jid);
3004 		goto out_noref;
3005 #endif
3006 	case SIOCIFCREATE:
3007 	case SIOCIFCREATE2:
3008 		error = priv_check(td, PRIV_NET_IFCREATE);
3009 		if (error == 0)
3010 			error = if_clone_create(ifr->ifr_name,
3011 			    sizeof(ifr->ifr_name), cmd == SIOCIFCREATE2 ?
3012 			    ifr_data_get_ptr(ifr) : NULL);
3013 		goto out_noref;
3014 	case SIOCIFDESTROY:
3015 		error = priv_check(td, PRIV_NET_IFDESTROY);
3016 		if (error == 0)
3017 			error = if_clone_destroy(ifr->ifr_name);
3018 		goto out_noref;
3019 
3020 	case SIOCIFGCLONERS:
3021 		error = if_clone_list((struct if_clonereq *)data);
3022 		goto out_noref;
3023 
3024 	case CASE_IOC_IFGROUPREQ(SIOCGIFGMEMB):
3025 		error = if_getgroupmembers((struct ifgroupreq *)data);
3026 		goto out_noref;
3027 
3028 #if defined(INET) || defined(INET6)
3029 	case SIOCSVH:
3030 	case SIOCGVH:
3031 		if (carp_ioctl_p == NULL)
3032 			error = EPROTONOSUPPORT;
3033 		else
3034 			error = (*carp_ioctl_p)(ifr, cmd, td);
3035 		goto out_noref;
3036 #endif
3037 	}
3038 
3039 	ifp = ifunit_ref(ifr->ifr_name);
3040 	if (ifp == NULL) {
3041 		error = ENXIO;
3042 		goto out_noref;
3043 	}
3044 
3045 	error = ifhwioctl(cmd, ifp, data, td);
3046 	if (error != ENOIOCTL)
3047 		goto out_ref;
3048 
3049 	oif_flags = ifp->if_flags;
3050 	if (so->so_proto == NULL) {
3051 		error = EOPNOTSUPP;
3052 		goto out_ref;
3053 	}
3054 
3055 	/*
3056 	 * Pass the request on to the socket control method, and if the
3057 	 * latter returns EOPNOTSUPP, directly to the interface.
3058 	 *
3059 	 * Make an exception for the legacy SIOCSIF* requests.  Drivers
3060 	 * trust SIOCSIFADDR et al to come from an already privileged
3061 	 * layer, and do not perform any credentials checks or input
3062 	 * validation.
3063 	 */
3064 	error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd, data,
3065 	    ifp, td));
3066 	if (error == EOPNOTSUPP && ifp != NULL && ifp->if_ioctl != NULL &&
3067 	    cmd != SIOCSIFADDR && cmd != SIOCSIFBRDADDR &&
3068 	    cmd != SIOCSIFDSTADDR && cmd != SIOCSIFNETMASK)
3069 		error = (*ifp->if_ioctl)(ifp, cmd, data);
3070 
3071 	if ((oif_flags ^ ifp->if_flags) & IFF_UP) {
3072 #ifdef INET6
3073 		if (ifp->if_flags & IFF_UP)
3074 			in6_if_up(ifp);
3075 #endif
3076 	}
3077 
3078 out_ref:
3079 	if_rele(ifp);
3080 out_noref:
3081 #ifdef COMPAT_FREEBSD32
3082 	if (ifmrp != NULL) {
3083 		KASSERT((cmd == SIOCGIFMEDIA || cmd == SIOCGIFXMEDIA),
3084 		    ("ifmrp non-NULL, but cmd is not an ifmedia req 0x%lx",
3085 		     cmd));
3086 		data = saved_data;
3087 		ifmr_update(ifmrp, data);
3088 	}
3089 #endif
3090 	CURVNET_RESTORE();
3091 	return (error);
3092 }
3093 
3094 /*
3095  * The code common to handling reference counted flags,
3096  * e.g., in ifpromisc() and if_allmulti().
3097  * The "pflag" argument can specify a permanent mode flag to check,
3098  * such as IFF_PPROMISC for promiscuous mode; should be 0 if none.
3099  *
3100  * Only to be used on stack-owned flags, not driver-owned flags.
3101  */
3102 static int
3103 if_setflag(struct ifnet *ifp, int flag, int pflag, int *refcount, int onswitch)
3104 {
3105 	struct ifreq ifr;
3106 	int error;
3107 	int oldflags, oldcount;
3108 
3109 	/* Sanity checks to catch programming errors */
3110 	KASSERT((flag & (IFF_DRV_OACTIVE|IFF_DRV_RUNNING)) == 0,
3111 	    ("%s: setting driver-owned flag %d", __func__, flag));
3112 
3113 	if (onswitch)
3114 		KASSERT(*refcount >= 0,
3115 		    ("%s: increment negative refcount %d for flag %d",
3116 		    __func__, *refcount, flag));
3117 	else
3118 		KASSERT(*refcount > 0,
3119 		    ("%s: decrement non-positive refcount %d for flag %d",
3120 		    __func__, *refcount, flag));
3121 
3122 	/* In case this mode is permanent, just touch refcount */
3123 	if (ifp->if_flags & pflag) {
3124 		*refcount += onswitch ? 1 : -1;
3125 		return (0);
3126 	}
3127 
3128 	/* Save ifnet parameters for if_ioctl() may fail */
3129 	oldcount = *refcount;
3130 	oldflags = ifp->if_flags;
3131 
3132 	/*
3133 	 * See if we aren't the only and touching refcount is enough.
3134 	 * Actually toggle interface flag if we are the first or last.
3135 	 */
3136 	if (onswitch) {
3137 		if ((*refcount)++)
3138 			return (0);
3139 		ifp->if_flags |= flag;
3140 	} else {
3141 		if (--(*refcount))
3142 			return (0);
3143 		ifp->if_flags &= ~flag;
3144 	}
3145 
3146 	/* Call down the driver since we've changed interface flags */
3147 	if (ifp->if_ioctl == NULL) {
3148 		error = EOPNOTSUPP;
3149 		goto recover;
3150 	}
3151 	ifr.ifr_flags = ifp->if_flags & 0xffff;
3152 	ifr.ifr_flagshigh = ifp->if_flags >> 16;
3153 	error = (*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3154 	if (error)
3155 		goto recover;
3156 	/* Notify userland that interface flags have changed */
3157 	rt_ifmsg(ifp);
3158 	return (0);
3159 
3160 recover:
3161 	/* Recover after driver error */
3162 	*refcount = oldcount;
3163 	ifp->if_flags = oldflags;
3164 	return (error);
3165 }
3166 
3167 /*
3168  * Set/clear promiscuous mode on interface ifp based on the truth value
3169  * of pswitch.  The calls are reference counted so that only the first
3170  * "on" request actually has an effect, as does the final "off" request.
3171  * Results are undefined if the "off" and "on" requests are not matched.
3172  */
3173 int
3174 ifpromisc(struct ifnet *ifp, int pswitch)
3175 {
3176 	int error;
3177 	int oldflags = ifp->if_flags;
3178 
3179 	error = if_setflag(ifp, IFF_PROMISC, IFF_PPROMISC,
3180 			   &ifp->if_pcount, pswitch);
3181 	/* If promiscuous mode status has changed, log a message */
3182 	if (error == 0 && ((ifp->if_flags ^ oldflags) & IFF_PROMISC) &&
3183             log_promisc_mode_change)
3184 		if_printf(ifp, "promiscuous mode %s\n",
3185 		    (ifp->if_flags & IFF_PROMISC) ? "enabled" : "disabled");
3186 	return (error);
3187 }
3188 
3189 /*
3190  * Return interface configuration
3191  * of system.  List may be used
3192  * in later ioctl's (above) to get
3193  * other information.
3194  */
3195 /*ARGSUSED*/
3196 static int
3197 ifconf(u_long cmd, caddr_t data)
3198 {
3199 	struct ifconf *ifc = (struct ifconf *)data;
3200 	struct ifnet *ifp;
3201 	struct ifaddr *ifa;
3202 	struct ifreq ifr;
3203 	struct sbuf *sb;
3204 	int error, full = 0, valid_len, max_len;
3205 
3206 	/* Limit initial buffer size to MAXPHYS to avoid DoS from userspace. */
3207 	max_len = MAXPHYS - 1;
3208 
3209 	/* Prevent hostile input from being able to crash the system */
3210 	if (ifc->ifc_len <= 0)
3211 		return (EINVAL);
3212 
3213 again:
3214 	if (ifc->ifc_len <= max_len) {
3215 		max_len = ifc->ifc_len;
3216 		full = 1;
3217 	}
3218 	sb = sbuf_new(NULL, NULL, max_len + 1, SBUF_FIXEDLEN);
3219 	max_len = 0;
3220 	valid_len = 0;
3221 
3222 	IFNET_RLOCK();
3223 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
3224 		struct epoch_tracker et;
3225 		int addrs;
3226 
3227 		/*
3228 		 * Zero the ifr to make sure we don't disclose the contents
3229 		 * of the stack.
3230 		 */
3231 		memset(&ifr, 0, sizeof(ifr));
3232 
3233 		if (strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name))
3234 		    >= sizeof(ifr.ifr_name)) {
3235 			sbuf_delete(sb);
3236 			IFNET_RUNLOCK();
3237 			return (ENAMETOOLONG);
3238 		}
3239 
3240 		addrs = 0;
3241 		NET_EPOCH_ENTER(et);
3242 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
3243 			struct sockaddr *sa = ifa->ifa_addr;
3244 
3245 			if (prison_if(curthread->td_ucred, sa) != 0)
3246 				continue;
3247 			addrs++;
3248 			if (sa->sa_len <= sizeof(*sa)) {
3249 				if (sa->sa_len < sizeof(*sa)) {
3250 					memset(&ifr.ifr_ifru.ifru_addr, 0,
3251 					    sizeof(ifr.ifr_ifru.ifru_addr));
3252 					memcpy(&ifr.ifr_ifru.ifru_addr, sa,
3253 					    sa->sa_len);
3254 				} else
3255 					ifr.ifr_ifru.ifru_addr = *sa;
3256 				sbuf_bcat(sb, &ifr, sizeof(ifr));
3257 				max_len += sizeof(ifr);
3258 			} else {
3259 				sbuf_bcat(sb, &ifr,
3260 				    offsetof(struct ifreq, ifr_addr));
3261 				max_len += offsetof(struct ifreq, ifr_addr);
3262 				sbuf_bcat(sb, sa, sa->sa_len);
3263 				max_len += sa->sa_len;
3264 			}
3265 
3266 			if (sbuf_error(sb) == 0)
3267 				valid_len = sbuf_len(sb);
3268 		}
3269 		NET_EPOCH_EXIT(et);
3270 		if (addrs == 0) {
3271 			sbuf_bcat(sb, &ifr, sizeof(ifr));
3272 			max_len += sizeof(ifr);
3273 
3274 			if (sbuf_error(sb) == 0)
3275 				valid_len = sbuf_len(sb);
3276 		}
3277 	}
3278 	IFNET_RUNLOCK();
3279 
3280 	/*
3281 	 * If we didn't allocate enough space (uncommon), try again.  If
3282 	 * we have already allocated as much space as we are allowed,
3283 	 * return what we've got.
3284 	 */
3285 	if (valid_len != max_len && !full) {
3286 		sbuf_delete(sb);
3287 		goto again;
3288 	}
3289 
3290 	ifc->ifc_len = valid_len;
3291 	sbuf_finish(sb);
3292 	error = copyout(sbuf_data(sb), ifc->ifc_req, ifc->ifc_len);
3293 	sbuf_delete(sb);
3294 	return (error);
3295 }
3296 
3297 /*
3298  * Just like ifpromisc(), but for all-multicast-reception mode.
3299  */
3300 int
3301 if_allmulti(struct ifnet *ifp, int onswitch)
3302 {
3303 
3304 	return (if_setflag(ifp, IFF_ALLMULTI, 0, &ifp->if_amcount, onswitch));
3305 }
3306 
3307 struct ifmultiaddr *
3308 if_findmulti(struct ifnet *ifp, const struct sockaddr *sa)
3309 {
3310 	struct ifmultiaddr *ifma;
3311 
3312 	IF_ADDR_LOCK_ASSERT(ifp);
3313 
3314 	CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3315 		if (sa->sa_family == AF_LINK) {
3316 			if (sa_dl_equal(ifma->ifma_addr, sa))
3317 				break;
3318 		} else {
3319 			if (sa_equal(ifma->ifma_addr, sa))
3320 				break;
3321 		}
3322 	}
3323 
3324 	return ifma;
3325 }
3326 
3327 /*
3328  * Allocate a new ifmultiaddr and initialize based on passed arguments.  We
3329  * make copies of passed sockaddrs.  The ifmultiaddr will not be added to
3330  * the ifnet multicast address list here, so the caller must do that and
3331  * other setup work (such as notifying the device driver).  The reference
3332  * count is initialized to 1.
3333  */
3334 static struct ifmultiaddr *
3335 if_allocmulti(struct ifnet *ifp, struct sockaddr *sa, struct sockaddr *llsa,
3336     int mflags)
3337 {
3338 	struct ifmultiaddr *ifma;
3339 	struct sockaddr *dupsa;
3340 
3341 	ifma = malloc(sizeof *ifma, M_IFMADDR, mflags |
3342 	    M_ZERO);
3343 	if (ifma == NULL)
3344 		return (NULL);
3345 
3346 	dupsa = malloc(sa->sa_len, M_IFMADDR, mflags);
3347 	if (dupsa == NULL) {
3348 		free(ifma, M_IFMADDR);
3349 		return (NULL);
3350 	}
3351 	bcopy(sa, dupsa, sa->sa_len);
3352 	ifma->ifma_addr = dupsa;
3353 
3354 	ifma->ifma_ifp = ifp;
3355 	ifma->ifma_refcount = 1;
3356 	ifma->ifma_protospec = NULL;
3357 
3358 	if (llsa == NULL) {
3359 		ifma->ifma_lladdr = NULL;
3360 		return (ifma);
3361 	}
3362 
3363 	dupsa = malloc(llsa->sa_len, M_IFMADDR, mflags);
3364 	if (dupsa == NULL) {
3365 		free(ifma->ifma_addr, M_IFMADDR);
3366 		free(ifma, M_IFMADDR);
3367 		return (NULL);
3368 	}
3369 	bcopy(llsa, dupsa, llsa->sa_len);
3370 	ifma->ifma_lladdr = dupsa;
3371 
3372 	return (ifma);
3373 }
3374 
3375 /*
3376  * if_freemulti: free ifmultiaddr structure and possibly attached related
3377  * addresses.  The caller is responsible for implementing reference
3378  * counting, notifying the driver, handling routing messages, and releasing
3379  * any dependent link layer state.
3380  */
3381 #ifdef MCAST_VERBOSE
3382 extern void kdb_backtrace(void);
3383 #endif
3384 static void
3385 if_freemulti_internal(struct ifmultiaddr *ifma)
3386 {
3387 
3388 	KASSERT(ifma->ifma_refcount == 0, ("if_freemulti: refcount %d",
3389 	    ifma->ifma_refcount));
3390 
3391 	if (ifma->ifma_lladdr != NULL)
3392 		free(ifma->ifma_lladdr, M_IFMADDR);
3393 #ifdef MCAST_VERBOSE
3394 	kdb_backtrace();
3395 	printf("%s freeing ifma: %p\n", __func__, ifma);
3396 #endif
3397 	free(ifma->ifma_addr, M_IFMADDR);
3398 	free(ifma, M_IFMADDR);
3399 }
3400 
3401 static void
3402 if_destroymulti(epoch_context_t ctx)
3403 {
3404 	struct ifmultiaddr *ifma;
3405 
3406 	ifma = __containerof(ctx, struct ifmultiaddr, ifma_epoch_ctx);
3407 	if_freemulti_internal(ifma);
3408 }
3409 
3410 void
3411 if_freemulti(struct ifmultiaddr *ifma)
3412 {
3413 	KASSERT(ifma->ifma_refcount == 0, ("if_freemulti_epoch: refcount %d",
3414 	    ifma->ifma_refcount));
3415 
3416 	epoch_call(net_epoch_preempt, &ifma->ifma_epoch_ctx, if_destroymulti);
3417 }
3418 
3419 
3420 /*
3421  * Register an additional multicast address with a network interface.
3422  *
3423  * - If the address is already present, bump the reference count on the
3424  *   address and return.
3425  * - If the address is not link-layer, look up a link layer address.
3426  * - Allocate address structures for one or both addresses, and attach to the
3427  *   multicast address list on the interface.  If automatically adding a link
3428  *   layer address, the protocol address will own a reference to the link
3429  *   layer address, to be freed when it is freed.
3430  * - Notify the network device driver of an addition to the multicast address
3431  *   list.
3432  *
3433  * 'sa' points to caller-owned memory with the desired multicast address.
3434  *
3435  * 'retifma' will be used to return a pointer to the resulting multicast
3436  * address reference, if desired.
3437  */
3438 int
3439 if_addmulti(struct ifnet *ifp, struct sockaddr *sa,
3440     struct ifmultiaddr **retifma)
3441 {
3442 	struct ifmultiaddr *ifma, *ll_ifma;
3443 	struct sockaddr *llsa;
3444 	struct sockaddr_dl sdl;
3445 	int error;
3446 
3447 #ifdef INET
3448 	IN_MULTI_LIST_UNLOCK_ASSERT();
3449 #endif
3450 #ifdef INET6
3451 	IN6_MULTI_LIST_UNLOCK_ASSERT();
3452 #endif
3453 	/*
3454 	 * If the address is already present, return a new reference to it;
3455 	 * otherwise, allocate storage and set up a new address.
3456 	 */
3457 	IF_ADDR_WLOCK(ifp);
3458 	ifma = if_findmulti(ifp, sa);
3459 	if (ifma != NULL) {
3460 		ifma->ifma_refcount++;
3461 		if (retifma != NULL)
3462 			*retifma = ifma;
3463 		IF_ADDR_WUNLOCK(ifp);
3464 		return (0);
3465 	}
3466 
3467 	/*
3468 	 * The address isn't already present; resolve the protocol address
3469 	 * into a link layer address, and then look that up, bump its
3470 	 * refcount or allocate an ifma for that also.
3471 	 * Most link layer resolving functions returns address data which
3472 	 * fits inside default sockaddr_dl structure. However callback
3473 	 * can allocate another sockaddr structure, in that case we need to
3474 	 * free it later.
3475 	 */
3476 	llsa = NULL;
3477 	ll_ifma = NULL;
3478 	if (ifp->if_resolvemulti != NULL) {
3479 		/* Provide called function with buffer size information */
3480 		sdl.sdl_len = sizeof(sdl);
3481 		llsa = (struct sockaddr *)&sdl;
3482 		error = ifp->if_resolvemulti(ifp, &llsa, sa);
3483 		if (error)
3484 			goto unlock_out;
3485 	}
3486 
3487 	/*
3488 	 * Allocate the new address.  Don't hook it up yet, as we may also
3489 	 * need to allocate a link layer multicast address.
3490 	 */
3491 	ifma = if_allocmulti(ifp, sa, llsa, M_NOWAIT);
3492 	if (ifma == NULL) {
3493 		error = ENOMEM;
3494 		goto free_llsa_out;
3495 	}
3496 
3497 	/*
3498 	 * If a link layer address is found, we'll need to see if it's
3499 	 * already present in the address list, or allocate is as well.
3500 	 * When this block finishes, the link layer address will be on the
3501 	 * list.
3502 	 */
3503 	if (llsa != NULL) {
3504 		ll_ifma = if_findmulti(ifp, llsa);
3505 		if (ll_ifma == NULL) {
3506 			ll_ifma = if_allocmulti(ifp, llsa, NULL, M_NOWAIT);
3507 			if (ll_ifma == NULL) {
3508 				--ifma->ifma_refcount;
3509 				if_freemulti(ifma);
3510 				error = ENOMEM;
3511 				goto free_llsa_out;
3512 			}
3513 			ll_ifma->ifma_flags |= IFMA_F_ENQUEUED;
3514 			CK_STAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ll_ifma,
3515 			    ifma_link);
3516 		} else
3517 			ll_ifma->ifma_refcount++;
3518 		ifma->ifma_llifma = ll_ifma;
3519 	}
3520 
3521 	/*
3522 	 * We now have a new multicast address, ifma, and possibly a new or
3523 	 * referenced link layer address.  Add the primary address to the
3524 	 * ifnet address list.
3525 	 */
3526 	ifma->ifma_flags |= IFMA_F_ENQUEUED;
3527 	CK_STAILQ_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
3528 
3529 	if (retifma != NULL)
3530 		*retifma = ifma;
3531 
3532 	/*
3533 	 * Must generate the message while holding the lock so that 'ifma'
3534 	 * pointer is still valid.
3535 	 */
3536 	rt_newmaddrmsg(RTM_NEWMADDR, ifma);
3537 	IF_ADDR_WUNLOCK(ifp);
3538 
3539 	/*
3540 	 * We are certain we have added something, so call down to the
3541 	 * interface to let them know about it.
3542 	 */
3543 	if (ifp->if_ioctl != NULL) {
3544 		if (THREAD_CAN_SLEEP())
3545 			(void )(*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
3546 		else
3547 			taskqueue_enqueue(taskqueue_swi, &ifp->if_addmultitask);
3548 	}
3549 
3550 	if ((llsa != NULL) && (llsa != (struct sockaddr *)&sdl))
3551 		link_free_sdl(llsa);
3552 
3553 	return (0);
3554 
3555 free_llsa_out:
3556 	if ((llsa != NULL) && (llsa != (struct sockaddr *)&sdl))
3557 		link_free_sdl(llsa);
3558 
3559 unlock_out:
3560 	IF_ADDR_WUNLOCK(ifp);
3561 	return (error);
3562 }
3563 
3564 static void
3565 if_siocaddmulti(void *arg, int pending)
3566 {
3567 	struct ifnet *ifp;
3568 
3569 	ifp = arg;
3570 #ifdef DIAGNOSTIC
3571 	if (pending > 1)
3572 		if_printf(ifp, "%d SIOCADDMULTI coalesced\n", pending);
3573 #endif
3574 	(void )(*ifp->if_ioctl)(ifp, SIOCADDMULTI, 0);
3575 }
3576 
3577 /*
3578  * Delete a multicast group membership by network-layer group address.
3579  *
3580  * Returns ENOENT if the entry could not be found. If ifp no longer
3581  * exists, results are undefined. This entry point should only be used
3582  * from subsystems which do appropriate locking to hold ifp for the
3583  * duration of the call.
3584  * Network-layer protocol domains must use if_delmulti_ifma().
3585  */
3586 int
3587 if_delmulti(struct ifnet *ifp, struct sockaddr *sa)
3588 {
3589 	struct ifmultiaddr *ifma;
3590 	int lastref;
3591 
3592 	KASSERT(ifp, ("%s: NULL ifp", __func__));
3593 
3594 	IF_ADDR_WLOCK(ifp);
3595 	lastref = 0;
3596 	ifma = if_findmulti(ifp, sa);
3597 	if (ifma != NULL)
3598 		lastref = if_delmulti_locked(ifp, ifma, 0);
3599 	IF_ADDR_WUNLOCK(ifp);
3600 
3601 	if (ifma == NULL)
3602 		return (ENOENT);
3603 
3604 	if (lastref && ifp->if_ioctl != NULL) {
3605 		(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3606 	}
3607 
3608 	return (0);
3609 }
3610 
3611 /*
3612  * Delete all multicast group membership for an interface.
3613  * Should be used to quickly flush all multicast filters.
3614  */
3615 void
3616 if_delallmulti(struct ifnet *ifp)
3617 {
3618 	struct ifmultiaddr *ifma;
3619 	struct ifmultiaddr *next;
3620 
3621 	IF_ADDR_WLOCK(ifp);
3622 	CK_STAILQ_FOREACH_SAFE(ifma, &ifp->if_multiaddrs, ifma_link, next)
3623 		if_delmulti_locked(ifp, ifma, 0);
3624 	IF_ADDR_WUNLOCK(ifp);
3625 }
3626 
3627 void
3628 if_delmulti_ifma(struct ifmultiaddr *ifma)
3629 {
3630 	if_delmulti_ifma_flags(ifma, 0);
3631 }
3632 
3633 /*
3634  * Delete a multicast group membership by group membership pointer.
3635  * Network-layer protocol domains must use this routine.
3636  *
3637  * It is safe to call this routine if the ifp disappeared.
3638  */
3639 void
3640 if_delmulti_ifma_flags(struct ifmultiaddr *ifma, int flags)
3641 {
3642 	struct ifnet *ifp;
3643 	int lastref;
3644 	MCDPRINTF("%s freeing ifma: %p\n", __func__, ifma);
3645 #ifdef INET
3646 	IN_MULTI_LIST_UNLOCK_ASSERT();
3647 #endif
3648 	ifp = ifma->ifma_ifp;
3649 #ifdef DIAGNOSTIC
3650 	if (ifp == NULL) {
3651 		printf("%s: ifma_ifp seems to be detached\n", __func__);
3652 	} else {
3653 		struct epoch_tracker et;
3654 		struct ifnet *oifp;
3655 
3656 		NET_EPOCH_ENTER(et);
3657 		CK_STAILQ_FOREACH(oifp, &V_ifnet, if_link)
3658 			if (ifp == oifp)
3659 				break;
3660 		NET_EPOCH_EXIT(et);
3661 		if (ifp != oifp)
3662 			ifp = NULL;
3663 	}
3664 #endif
3665 	/*
3666 	 * If and only if the ifnet instance exists: Acquire the address lock.
3667 	 */
3668 	if (ifp != NULL)
3669 		IF_ADDR_WLOCK(ifp);
3670 
3671 	lastref = if_delmulti_locked(ifp, ifma, flags);
3672 
3673 	if (ifp != NULL) {
3674 		/*
3675 		 * If and only if the ifnet instance exists:
3676 		 *  Release the address lock.
3677 		 *  If the group was left: update the hardware hash filter.
3678 		 */
3679 		IF_ADDR_WUNLOCK(ifp);
3680 		if (lastref && ifp->if_ioctl != NULL) {
3681 			(void)(*ifp->if_ioctl)(ifp, SIOCDELMULTI, 0);
3682 		}
3683 	}
3684 }
3685 
3686 /*
3687  * Perform deletion of network-layer and/or link-layer multicast address.
3688  *
3689  * Return 0 if the reference count was decremented.
3690  * Return 1 if the final reference was released, indicating that the
3691  * hardware hash filter should be reprogrammed.
3692  */
3693 static int
3694 if_delmulti_locked(struct ifnet *ifp, struct ifmultiaddr *ifma, int detaching)
3695 {
3696 	struct ifmultiaddr *ll_ifma;
3697 
3698 	if (ifp != NULL && ifma->ifma_ifp != NULL) {
3699 		KASSERT(ifma->ifma_ifp == ifp,
3700 		    ("%s: inconsistent ifp %p", __func__, ifp));
3701 		IF_ADDR_WLOCK_ASSERT(ifp);
3702 	}
3703 
3704 	ifp = ifma->ifma_ifp;
3705 	MCDPRINTF("%s freeing %p from %s \n", __func__, ifma, ifp ? ifp->if_xname : "");
3706 
3707 	/*
3708 	 * If the ifnet is detaching, null out references to ifnet,
3709 	 * so that upper protocol layers will notice, and not attempt
3710 	 * to obtain locks for an ifnet which no longer exists. The
3711 	 * routing socket announcement must happen before the ifnet
3712 	 * instance is detached from the system.
3713 	 */
3714 	if (detaching) {
3715 #ifdef DIAGNOSTIC
3716 		printf("%s: detaching ifnet instance %p\n", __func__, ifp);
3717 #endif
3718 		/*
3719 		 * ifp may already be nulled out if we are being reentered
3720 		 * to delete the ll_ifma.
3721 		 */
3722 		if (ifp != NULL) {
3723 			rt_newmaddrmsg(RTM_DELMADDR, ifma);
3724 			ifma->ifma_ifp = NULL;
3725 		}
3726 	}
3727 
3728 	if (--ifma->ifma_refcount > 0)
3729 		return 0;
3730 
3731 	if (ifp != NULL && detaching == 0 && (ifma->ifma_flags & IFMA_F_ENQUEUED)) {
3732 		CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ifma, ifmultiaddr, ifma_link);
3733 		ifma->ifma_flags &= ~IFMA_F_ENQUEUED;
3734 	}
3735 	/*
3736 	 * If this ifma is a network-layer ifma, a link-layer ifma may
3737 	 * have been associated with it. Release it first if so.
3738 	 */
3739 	ll_ifma = ifma->ifma_llifma;
3740 	if (ll_ifma != NULL) {
3741 		KASSERT(ifma->ifma_lladdr != NULL,
3742 		    ("%s: llifma w/o lladdr", __func__));
3743 		if (detaching)
3744 			ll_ifma->ifma_ifp = NULL;	/* XXX */
3745 		if (--ll_ifma->ifma_refcount == 0) {
3746 			if (ifp != NULL) {
3747 				if (ll_ifma->ifma_flags & IFMA_F_ENQUEUED) {
3748 					CK_STAILQ_REMOVE(&ifp->if_multiaddrs, ll_ifma, ifmultiaddr,
3749 						ifma_link);
3750 					ll_ifma->ifma_flags &= ~IFMA_F_ENQUEUED;
3751 				}
3752 			}
3753 			if_freemulti(ll_ifma);
3754 		}
3755 	}
3756 #ifdef INVARIANTS
3757 	if (ifp) {
3758 		struct ifmultiaddr *ifmatmp;
3759 
3760 		CK_STAILQ_FOREACH(ifmatmp, &ifp->if_multiaddrs, ifma_link)
3761 			MPASS(ifma != ifmatmp);
3762 	}
3763 #endif
3764 	if_freemulti(ifma);
3765 	/*
3766 	 * The last reference to this instance of struct ifmultiaddr
3767 	 * was released; the hardware should be notified of this change.
3768 	 */
3769 	return 1;
3770 }
3771 
3772 /*
3773  * Set the link layer address on an interface.
3774  *
3775  * At this time we only support certain types of interfaces,
3776  * and we don't allow the length of the address to change.
3777  *
3778  * Set noinline to be dtrace-friendly
3779  */
3780 __noinline int
3781 if_setlladdr(struct ifnet *ifp, const u_char *lladdr, int len)
3782 {
3783 	struct sockaddr_dl *sdl;
3784 	struct ifaddr *ifa;
3785 	struct ifreq ifr;
3786 
3787 	ifa = ifp->if_addr;
3788 	if (ifa == NULL)
3789 		return (EINVAL);
3790 
3791 	sdl = (struct sockaddr_dl *)ifa->ifa_addr;
3792 	if (sdl == NULL)
3793 		return (EINVAL);
3794 
3795 	if (len != sdl->sdl_alen)	/* don't allow length to change */
3796 		return (EINVAL);
3797 
3798 	switch (ifp->if_type) {
3799 	case IFT_ETHER:
3800 	case IFT_XETHER:
3801 	case IFT_L2VLAN:
3802 	case IFT_BRIDGE:
3803 	case IFT_IEEE8023ADLAG:
3804 		bcopy(lladdr, LLADDR(sdl), len);
3805 		break;
3806 	default:
3807 		return (ENODEV);
3808 	}
3809 
3810 	/*
3811 	 * If the interface is already up, we need
3812 	 * to re-init it in order to reprogram its
3813 	 * address filter.
3814 	 */
3815 	if ((ifp->if_flags & IFF_UP) != 0) {
3816 		if (ifp->if_ioctl) {
3817 			ifp->if_flags &= ~IFF_UP;
3818 			ifr.ifr_flags = ifp->if_flags & 0xffff;
3819 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
3820 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3821 			ifp->if_flags |= IFF_UP;
3822 			ifr.ifr_flags = ifp->if_flags & 0xffff;
3823 			ifr.ifr_flagshigh = ifp->if_flags >> 16;
3824 			(*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr);
3825 		}
3826 	}
3827 	EVENTHANDLER_INVOKE(iflladdr_event, ifp);
3828 
3829 	return (0);
3830 }
3831 
3832 /*
3833  * Compat function for handling basic encapsulation requests.
3834  * Not converted stacks (FDDI, IB, ..) supports traditional
3835  * output model: ARP (and other similar L2 protocols) are handled
3836  * inside output routine, arpresolve/nd6_resolve() returns MAC
3837  * address instead of full prepend.
3838  *
3839  * This function creates calculated header==MAC for IPv4/IPv6 and
3840  * returns EAFNOSUPPORT (which is then handled in ARP code) for other
3841  * address families.
3842  */
3843 static int
3844 if_requestencap_default(struct ifnet *ifp, struct if_encap_req *req)
3845 {
3846 
3847 	if (req->rtype != IFENCAP_LL)
3848 		return (EOPNOTSUPP);
3849 
3850 	if (req->bufsize < req->lladdr_len)
3851 		return (ENOMEM);
3852 
3853 	switch (req->family) {
3854 	case AF_INET:
3855 	case AF_INET6:
3856 		break;
3857 	default:
3858 		return (EAFNOSUPPORT);
3859 	}
3860 
3861 	/* Copy lladdr to storage as is */
3862 	memmove(req->buf, req->lladdr, req->lladdr_len);
3863 	req->bufsize = req->lladdr_len;
3864 	req->lladdr_off = 0;
3865 
3866 	return (0);
3867 }
3868 
3869 /*
3870  * Tunnel interfaces can nest, also they may cause infinite recursion
3871  * calls when misconfigured. We'll prevent this by detecting loops.
3872  * High nesting level may cause stack exhaustion. We'll prevent this
3873  * by introducing upper limit.
3874  *
3875  * Return 0, if tunnel nesting count is equal or less than limit.
3876  */
3877 int
3878 if_tunnel_check_nesting(struct ifnet *ifp, struct mbuf *m, uint32_t cookie,
3879     int limit)
3880 {
3881 	struct m_tag *mtag;
3882 	int count;
3883 
3884 	count = 1;
3885 	mtag = NULL;
3886 	while ((mtag = m_tag_locate(m, cookie, 0, mtag)) != NULL) {
3887 		if (*(struct ifnet **)(mtag + 1) == ifp) {
3888 			log(LOG_NOTICE, "%s: loop detected\n", if_name(ifp));
3889 			return (EIO);
3890 		}
3891 		count++;
3892 	}
3893 	if (count > limit) {
3894 		log(LOG_NOTICE,
3895 		    "%s: if_output recursively called too many times(%d)\n",
3896 		    if_name(ifp), count);
3897 		return (EIO);
3898 	}
3899 	mtag = m_tag_alloc(cookie, 0, sizeof(struct ifnet *), M_NOWAIT);
3900 	if (mtag == NULL)
3901 		return (ENOMEM);
3902 	*(struct ifnet **)(mtag + 1) = ifp;
3903 	m_tag_prepend(m, mtag);
3904 	return (0);
3905 }
3906 
3907 /*
3908  * Get the link layer address that was read from the hardware at attach.
3909  *
3910  * This is only set by Ethernet NICs (IFT_ETHER), but laggX interfaces re-type
3911  * their component interfaces as IFT_IEEE8023ADLAG.
3912  */
3913 int
3914 if_gethwaddr(struct ifnet *ifp, struct ifreq *ifr)
3915 {
3916 
3917 	if (ifp->if_hw_addr == NULL)
3918 		return (ENODEV);
3919 
3920 	switch (ifp->if_type) {
3921 	case IFT_ETHER:
3922 	case IFT_IEEE8023ADLAG:
3923 		bcopy(ifp->if_hw_addr, ifr->ifr_addr.sa_data, ifp->if_addrlen);
3924 		return (0);
3925 	default:
3926 		return (ENODEV);
3927 	}
3928 }
3929 
3930 /*
3931  * The name argument must be a pointer to storage which will last as
3932  * long as the interface does.  For physical devices, the result of
3933  * device_get_name(dev) is a good choice and for pseudo-devices a
3934  * static string works well.
3935  */
3936 void
3937 if_initname(struct ifnet *ifp, const char *name, int unit)
3938 {
3939 	ifp->if_dname = name;
3940 	ifp->if_dunit = unit;
3941 	if (unit != IF_DUNIT_NONE)
3942 		snprintf(ifp->if_xname, IFNAMSIZ, "%s%d", name, unit);
3943 	else
3944 		strlcpy(ifp->if_xname, name, IFNAMSIZ);
3945 }
3946 
3947 int
3948 if_printf(struct ifnet *ifp, const char *fmt, ...)
3949 {
3950 	char if_fmt[256];
3951 	va_list ap;
3952 
3953 	snprintf(if_fmt, sizeof(if_fmt), "%s: %s", ifp->if_xname, fmt);
3954 	va_start(ap, fmt);
3955 	vlog(LOG_INFO, if_fmt, ap);
3956 	va_end(ap);
3957 	return (0);
3958 }
3959 
3960 void
3961 if_start(struct ifnet *ifp)
3962 {
3963 
3964 	(*(ifp)->if_start)(ifp);
3965 }
3966 
3967 /*
3968  * Backwards compatibility interface for drivers
3969  * that have not implemented it
3970  */
3971 static int
3972 if_transmit(struct ifnet *ifp, struct mbuf *m)
3973 {
3974 	int error;
3975 
3976 	IFQ_HANDOFF(ifp, m, error);
3977 	return (error);
3978 }
3979 
3980 static void
3981 if_input_default(struct ifnet *ifp __unused, struct mbuf *m)
3982 {
3983 
3984 	m_freem(m);
3985 }
3986 
3987 int
3988 if_handoff(struct ifqueue *ifq, struct mbuf *m, struct ifnet *ifp, int adjust)
3989 {
3990 	int active = 0;
3991 
3992 	IF_LOCK(ifq);
3993 	if (_IF_QFULL(ifq)) {
3994 		IF_UNLOCK(ifq);
3995 		if_inc_counter(ifp, IFCOUNTER_OQDROPS, 1);
3996 		m_freem(m);
3997 		return (0);
3998 	}
3999 	if (ifp != NULL) {
4000 		if_inc_counter(ifp, IFCOUNTER_OBYTES, m->m_pkthdr.len + adjust);
4001 		if (m->m_flags & (M_BCAST|M_MCAST))
4002 			if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
4003 		active = ifp->if_drv_flags & IFF_DRV_OACTIVE;
4004 	}
4005 	_IF_ENQUEUE(ifq, m);
4006 	IF_UNLOCK(ifq);
4007 	if (ifp != NULL && !active)
4008 		(*(ifp)->if_start)(ifp);
4009 	return (1);
4010 }
4011 
4012 void
4013 if_register_com_alloc(u_char type,
4014     if_com_alloc_t *a, if_com_free_t *f)
4015 {
4016 
4017 	KASSERT(if_com_alloc[type] == NULL,
4018 	    ("if_register_com_alloc: %d already registered", type));
4019 	KASSERT(if_com_free[type] == NULL,
4020 	    ("if_register_com_alloc: %d free already registered", type));
4021 
4022 	if_com_alloc[type] = a;
4023 	if_com_free[type] = f;
4024 }
4025 
4026 void
4027 if_deregister_com_alloc(u_char type)
4028 {
4029 
4030 	KASSERT(if_com_alloc[type] != NULL,
4031 	    ("if_deregister_com_alloc: %d not registered", type));
4032 	KASSERT(if_com_free[type] != NULL,
4033 	    ("if_deregister_com_alloc: %d free not registered", type));
4034 	if_com_alloc[type] = NULL;
4035 	if_com_free[type] = NULL;
4036 }
4037 
4038 /* API for driver access to network stack owned ifnet.*/
4039 uint64_t
4040 if_setbaudrate(struct ifnet *ifp, uint64_t baudrate)
4041 {
4042 	uint64_t oldbrate;
4043 
4044 	oldbrate = ifp->if_baudrate;
4045 	ifp->if_baudrate = baudrate;
4046 	return (oldbrate);
4047 }
4048 
4049 uint64_t
4050 if_getbaudrate(if_t ifp)
4051 {
4052 
4053 	return (((struct ifnet *)ifp)->if_baudrate);
4054 }
4055 
4056 int
4057 if_setcapabilities(if_t ifp, int capabilities)
4058 {
4059 	((struct ifnet *)ifp)->if_capabilities = capabilities;
4060 	return (0);
4061 }
4062 
4063 int
4064 if_setcapabilitiesbit(if_t ifp, int setbit, int clearbit)
4065 {
4066 	((struct ifnet *)ifp)->if_capabilities |= setbit;
4067 	((struct ifnet *)ifp)->if_capabilities &= ~clearbit;
4068 
4069 	return (0);
4070 }
4071 
4072 int
4073 if_getcapabilities(if_t ifp)
4074 {
4075 	return ((struct ifnet *)ifp)->if_capabilities;
4076 }
4077 
4078 int
4079 if_setcapenable(if_t ifp, int capabilities)
4080 {
4081 	((struct ifnet *)ifp)->if_capenable = capabilities;
4082 	return (0);
4083 }
4084 
4085 int
4086 if_setcapenablebit(if_t ifp, int setcap, int clearcap)
4087 {
4088 	if(setcap)
4089 		((struct ifnet *)ifp)->if_capenable |= setcap;
4090 	if(clearcap)
4091 		((struct ifnet *)ifp)->if_capenable &= ~clearcap;
4092 
4093 	return (0);
4094 }
4095 
4096 const char *
4097 if_getdname(if_t ifp)
4098 {
4099 	return ((struct ifnet *)ifp)->if_dname;
4100 }
4101 
4102 int
4103 if_togglecapenable(if_t ifp, int togglecap)
4104 {
4105 	((struct ifnet *)ifp)->if_capenable ^= togglecap;
4106 	return (0);
4107 }
4108 
4109 int
4110 if_getcapenable(if_t ifp)
4111 {
4112 	return ((struct ifnet *)ifp)->if_capenable;
4113 }
4114 
4115 /*
4116  * This is largely undesirable because it ties ifnet to a device, but does
4117  * provide flexiblity for an embedded product vendor. Should be used with
4118  * the understanding that it violates the interface boundaries, and should be
4119  * a last resort only.
4120  */
4121 int
4122 if_setdev(if_t ifp, void *dev)
4123 {
4124 	return (0);
4125 }
4126 
4127 int
4128 if_setdrvflagbits(if_t ifp, int set_flags, int clear_flags)
4129 {
4130 	((struct ifnet *)ifp)->if_drv_flags |= set_flags;
4131 	((struct ifnet *)ifp)->if_drv_flags &= ~clear_flags;
4132 
4133 	return (0);
4134 }
4135 
4136 int
4137 if_getdrvflags(if_t ifp)
4138 {
4139 	return ((struct ifnet *)ifp)->if_drv_flags;
4140 }
4141 
4142 int
4143 if_setdrvflags(if_t ifp, int flags)
4144 {
4145 	((struct ifnet *)ifp)->if_drv_flags = flags;
4146 	return (0);
4147 }
4148 
4149 
4150 int
4151 if_setflags(if_t ifp, int flags)
4152 {
4153 	((struct ifnet *)ifp)->if_flags = flags;
4154 	return (0);
4155 }
4156 
4157 int
4158 if_setflagbits(if_t ifp, int set, int clear)
4159 {
4160 	((struct ifnet *)ifp)->if_flags |= set;
4161 	((struct ifnet *)ifp)->if_flags &= ~clear;
4162 
4163 	return (0);
4164 }
4165 
4166 int
4167 if_getflags(if_t ifp)
4168 {
4169 	return ((struct ifnet *)ifp)->if_flags;
4170 }
4171 
4172 int
4173 if_clearhwassist(if_t ifp)
4174 {
4175 	((struct ifnet *)ifp)->if_hwassist = 0;
4176 	return (0);
4177 }
4178 
4179 int
4180 if_sethwassistbits(if_t ifp, int toset, int toclear)
4181 {
4182 	((struct ifnet *)ifp)->if_hwassist |= toset;
4183 	((struct ifnet *)ifp)->if_hwassist &= ~toclear;
4184 
4185 	return (0);
4186 }
4187 
4188 int
4189 if_sethwassist(if_t ifp, int hwassist_bit)
4190 {
4191 	((struct ifnet *)ifp)->if_hwassist = hwassist_bit;
4192 	return (0);
4193 }
4194 
4195 int
4196 if_gethwassist(if_t ifp)
4197 {
4198 	return ((struct ifnet *)ifp)->if_hwassist;
4199 }
4200 
4201 int
4202 if_setmtu(if_t ifp, int mtu)
4203 {
4204 	((struct ifnet *)ifp)->if_mtu = mtu;
4205 	return (0);
4206 }
4207 
4208 int
4209 if_getmtu(if_t ifp)
4210 {
4211 	return ((struct ifnet *)ifp)->if_mtu;
4212 }
4213 
4214 int
4215 if_getmtu_family(if_t ifp, int family)
4216 {
4217 	struct domain *dp;
4218 
4219 	for (dp = domains; dp; dp = dp->dom_next) {
4220 		if (dp->dom_family == family && dp->dom_ifmtu != NULL)
4221 			return (dp->dom_ifmtu((struct ifnet *)ifp));
4222 	}
4223 
4224 	return (((struct ifnet *)ifp)->if_mtu);
4225 }
4226 
4227 /*
4228  * Methods for drivers to access interface unicast and multicast
4229  * link level addresses.  Driver shall not know 'struct ifaddr' neither
4230  * 'struct ifmultiaddr'.
4231  */
4232 u_int
4233 if_lladdr_count(if_t ifp)
4234 {
4235 	struct epoch_tracker et;
4236 	struct ifaddr *ifa;
4237 	u_int count;
4238 
4239 	count = 0;
4240 	NET_EPOCH_ENTER(et);
4241 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link)
4242 		if (ifa->ifa_addr->sa_family == AF_LINK)
4243 			count++;
4244 	NET_EPOCH_EXIT(et);
4245 
4246 	return (count);
4247 }
4248 
4249 u_int
4250 if_foreach_lladdr(if_t ifp, iflladdr_cb_t cb, void *cb_arg)
4251 {
4252 	struct epoch_tracker et;
4253 	struct ifaddr *ifa;
4254 	u_int count;
4255 
4256 	MPASS(cb);
4257 
4258 	count = 0;
4259 	NET_EPOCH_ENTER(et);
4260 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
4261 		if (ifa->ifa_addr->sa_family != AF_LINK)
4262 			continue;
4263 		count += (*cb)(cb_arg, (struct sockaddr_dl *)ifa->ifa_addr,
4264 		    count);
4265 	}
4266 	NET_EPOCH_EXIT(et);
4267 
4268 	return (count);
4269 }
4270 
4271 u_int
4272 if_llmaddr_count(if_t ifp)
4273 {
4274 	struct epoch_tracker et;
4275 	struct ifmultiaddr *ifma;
4276 	int count;
4277 
4278 	count = 0;
4279 	NET_EPOCH_ENTER(et);
4280 	CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link)
4281 		if (ifma->ifma_addr->sa_family == AF_LINK)
4282 			count++;
4283 	NET_EPOCH_EXIT(et);
4284 
4285 	return (count);
4286 }
4287 
4288 u_int
4289 if_foreach_llmaddr(if_t ifp, iflladdr_cb_t cb, void *cb_arg)
4290 {
4291 	struct epoch_tracker et;
4292 	struct ifmultiaddr *ifma;
4293 	u_int count;
4294 
4295 	MPASS(cb);
4296 
4297 	count = 0;
4298 	NET_EPOCH_ENTER(et);
4299 	CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
4300 		if (ifma->ifma_addr->sa_family != AF_LINK)
4301 			continue;
4302 		count += (*cb)(cb_arg, (struct sockaddr_dl *)ifma->ifma_addr,
4303 		    count);
4304 	}
4305 	NET_EPOCH_EXIT(et);
4306 
4307 	return (count);
4308 }
4309 
4310 int
4311 if_setsoftc(if_t ifp, void *softc)
4312 {
4313 	((struct ifnet *)ifp)->if_softc = softc;
4314 	return (0);
4315 }
4316 
4317 void *
4318 if_getsoftc(if_t ifp)
4319 {
4320 	return ((struct ifnet *)ifp)->if_softc;
4321 }
4322 
4323 void
4324 if_setrcvif(struct mbuf *m, if_t ifp)
4325 {
4326 
4327 	MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
4328 	m->m_pkthdr.rcvif = (struct ifnet *)ifp;
4329 }
4330 
4331 void
4332 if_setvtag(struct mbuf *m, uint16_t tag)
4333 {
4334 	m->m_pkthdr.ether_vtag = tag;
4335 }
4336 
4337 uint16_t
4338 if_getvtag(struct mbuf *m)
4339 {
4340 
4341 	return (m->m_pkthdr.ether_vtag);
4342 }
4343 
4344 int
4345 if_sendq_empty(if_t ifp)
4346 {
4347 	return IFQ_DRV_IS_EMPTY(&((struct ifnet *)ifp)->if_snd);
4348 }
4349 
4350 struct ifaddr *
4351 if_getifaddr(if_t ifp)
4352 {
4353 	return ((struct ifnet *)ifp)->if_addr;
4354 }
4355 
4356 int
4357 if_getamcount(if_t ifp)
4358 {
4359 	return ((struct ifnet *)ifp)->if_amcount;
4360 }
4361 
4362 
4363 int
4364 if_setsendqready(if_t ifp)
4365 {
4366 	IFQ_SET_READY(&((struct ifnet *)ifp)->if_snd);
4367 	return (0);
4368 }
4369 
4370 int
4371 if_setsendqlen(if_t ifp, int tx_desc_count)
4372 {
4373 	IFQ_SET_MAXLEN(&((struct ifnet *)ifp)->if_snd, tx_desc_count);
4374 	((struct ifnet *)ifp)->if_snd.ifq_drv_maxlen = tx_desc_count;
4375 
4376 	return (0);
4377 }
4378 
4379 int
4380 if_vlantrunkinuse(if_t ifp)
4381 {
4382 	return ((struct ifnet *)ifp)->if_vlantrunk != NULL?1:0;
4383 }
4384 
4385 int
4386 if_input(if_t ifp, struct mbuf* sendmp)
4387 {
4388 	(*((struct ifnet *)ifp)->if_input)((struct ifnet *)ifp, sendmp);
4389 	return (0);
4390 
4391 }
4392 
4393 struct mbuf *
4394 if_dequeue(if_t ifp)
4395 {
4396 	struct mbuf *m;
4397 	IFQ_DRV_DEQUEUE(&((struct ifnet *)ifp)->if_snd, m);
4398 
4399 	return (m);
4400 }
4401 
4402 int
4403 if_sendq_prepend(if_t ifp, struct mbuf *m)
4404 {
4405 	IFQ_DRV_PREPEND(&((struct ifnet *)ifp)->if_snd, m);
4406 	return (0);
4407 }
4408 
4409 int
4410 if_setifheaderlen(if_t ifp, int len)
4411 {
4412 	((struct ifnet *)ifp)->if_hdrlen = len;
4413 	return (0);
4414 }
4415 
4416 caddr_t
4417 if_getlladdr(if_t ifp)
4418 {
4419 	return (IF_LLADDR((struct ifnet *)ifp));
4420 }
4421 
4422 void *
4423 if_gethandle(u_char type)
4424 {
4425 	return (if_alloc(type));
4426 }
4427 
4428 void
4429 if_bpfmtap(if_t ifh, struct mbuf *m)
4430 {
4431 	struct ifnet *ifp = (struct ifnet *)ifh;
4432 
4433 	BPF_MTAP(ifp, m);
4434 }
4435 
4436 void
4437 if_etherbpfmtap(if_t ifh, struct mbuf *m)
4438 {
4439 	struct ifnet *ifp = (struct ifnet *)ifh;
4440 
4441 	ETHER_BPF_MTAP(ifp, m);
4442 }
4443 
4444 void
4445 if_vlancap(if_t ifh)
4446 {
4447 	struct ifnet *ifp = (struct ifnet *)ifh;
4448 	VLAN_CAPABILITIES(ifp);
4449 }
4450 
4451 int
4452 if_sethwtsomax(if_t ifp, u_int if_hw_tsomax)
4453 {
4454 
4455 	((struct ifnet *)ifp)->if_hw_tsomax = if_hw_tsomax;
4456         return (0);
4457 }
4458 
4459 int
4460 if_sethwtsomaxsegcount(if_t ifp, u_int if_hw_tsomaxsegcount)
4461 {
4462 
4463 	((struct ifnet *)ifp)->if_hw_tsomaxsegcount = if_hw_tsomaxsegcount;
4464         return (0);
4465 }
4466 
4467 int
4468 if_sethwtsomaxsegsize(if_t ifp, u_int if_hw_tsomaxsegsize)
4469 {
4470 
4471 	((struct ifnet *)ifp)->if_hw_tsomaxsegsize = if_hw_tsomaxsegsize;
4472         return (0);
4473 }
4474 
4475 u_int
4476 if_gethwtsomax(if_t ifp)
4477 {
4478 
4479 	return (((struct ifnet *)ifp)->if_hw_tsomax);
4480 }
4481 
4482 u_int
4483 if_gethwtsomaxsegcount(if_t ifp)
4484 {
4485 
4486 	return (((struct ifnet *)ifp)->if_hw_tsomaxsegcount);
4487 }
4488 
4489 u_int
4490 if_gethwtsomaxsegsize(if_t ifp)
4491 {
4492 
4493 	return (((struct ifnet *)ifp)->if_hw_tsomaxsegsize);
4494 }
4495 
4496 void
4497 if_setinitfn(if_t ifp, void (*init_fn)(void *))
4498 {
4499 	((struct ifnet *)ifp)->if_init = init_fn;
4500 }
4501 
4502 void
4503 if_setioctlfn(if_t ifp, int (*ioctl_fn)(if_t, u_long, caddr_t))
4504 {
4505 	((struct ifnet *)ifp)->if_ioctl = (void *)ioctl_fn;
4506 }
4507 
4508 void
4509 if_setstartfn(if_t ifp, void (*start_fn)(if_t))
4510 {
4511 	((struct ifnet *)ifp)->if_start = (void *)start_fn;
4512 }
4513 
4514 void
4515 if_settransmitfn(if_t ifp, if_transmit_fn_t start_fn)
4516 {
4517 	((struct ifnet *)ifp)->if_transmit = start_fn;
4518 }
4519 
4520 void if_setqflushfn(if_t ifp, if_qflush_fn_t flush_fn)
4521 {
4522 	((struct ifnet *)ifp)->if_qflush = flush_fn;
4523 
4524 }
4525 
4526 void
4527 if_setgetcounterfn(if_t ifp, if_get_counter_t fn)
4528 {
4529 
4530 	ifp->if_get_counter = fn;
4531 }
4532 
4533 /* Revisit these - These are inline functions originally. */
4534 int
4535 drbr_inuse_drv(if_t ifh, struct buf_ring *br)
4536 {
4537 	return drbr_inuse(ifh, br);
4538 }
4539 
4540 struct mbuf*
4541 drbr_dequeue_drv(if_t ifh, struct buf_ring *br)
4542 {
4543 	return drbr_dequeue(ifh, br);
4544 }
4545 
4546 int
4547 drbr_needs_enqueue_drv(if_t ifh, struct buf_ring *br)
4548 {
4549 	return drbr_needs_enqueue(ifh, br);
4550 }
4551 
4552 int
4553 drbr_enqueue_drv(if_t ifh, struct buf_ring *br, struct mbuf *m)
4554 {
4555 	return drbr_enqueue(ifh, br, m);
4556 
4557 }
4558