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