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