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