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