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