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