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