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