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