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