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