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