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