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