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