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