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