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