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