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