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