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