xref: /xnu-10002.1.13/bsd/net/if.c (revision 1031c584a5e37aff177559b9f69dbd3c8c3fd30a)
1 /*
2  * Copyright (c) 2000-2023 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * Copyright (c) 1980, 1986, 1993
30  *	The Regents of the University of California.  All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. All advertising materials mentioning features or use of this software
41  *    must display the following acknowledgement:
42  *	This product includes software developed by the University of
43  *	California, Berkeley and its contributors.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)if.c	8.3 (Berkeley) 1/4/94
61  * $FreeBSD: src/sys/net/if.c,v 1.85.2.9 2001/07/24 19:10:17 brooks Exp $
62  */
63 /*
64  * NOTICE: This file was modified by SPARTA, Inc. in 2006 to introduce
65  * support for mandatory and extensible security protections.  This notice
66  * is included in support of clause 2.2 (b) of the Apple Public License,
67  * Version 2.0.
68  */
69 
70 #include <kern/locks.h>
71 
72 #include <sys/param.h>
73 #include <sys/malloc.h>
74 #include <sys/mbuf.h>
75 #include <sys/systm.h>
76 #include <sys/proc.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/protosw.h>
80 #include <sys/kernel.h>
81 #include <sys/sockio.h>
82 #include <sys/syslog.h>
83 #include <sys/sysctl.h>
84 #include <sys/mcache.h>
85 #include <sys/kauth.h>
86 #include <sys/priv.h>
87 #include <kern/zalloc.h>
88 #include <mach/boolean.h>
89 
90 #include <machine/endian.h>
91 
92 #include <pexpert/pexpert.h>
93 
94 #include <net/if.h>
95 #include <net/if_arp.h>
96 #include <net/if_dl.h>
97 #include <net/if_types.h>
98 #include <net/if_var.h>
99 #include <net/if_media.h>
100 #include <net/if_ppp.h>
101 #include <net/ethernet.h>
102 #include <net/network_agent.h>
103 #include <net/pktsched/pktsched_netem.h>
104 #include <net/radix.h>
105 #include <net/route.h>
106 #include <net/dlil.h>
107 #include <net/nwk_wq.h>
108 
109 #include <sys/domain.h>
110 #include <libkern/OSAtomic.h>
111 
112 #if INET
113 #include <netinet/in.h>
114 #include <netinet/in_var.h>
115 #include <netinet/in_tclass.h>
116 #include <netinet/ip_var.h>
117 #include <netinet/ip.h>
118 #include <netinet/ip6.h>
119 #include <netinet/ip_var.h>
120 #include <netinet/tcp.h>
121 #include <netinet/tcp_var.h>
122 #include <netinet/udp.h>
123 #include <netinet/udp_var.h>
124 #include <netinet6/in6_var.h>
125 #include <netinet6/in6_ifattach.h>
126 #include <netinet6/ip6_var.h>
127 #include <netinet6/nd6.h>
128 #endif /* INET */
129 
130 #if SKYWALK
131 #include <skywalk/nexus/netif/nx_netif.h>
132 #endif /* SKYWALK */
133 
134 #include <os/log.h>
135 
136 #include <IOKit/IOBSD.h>
137 
138 /*
139  * System initialization
140  */
141 
142 extern char *proc_name_address(void *);
143 
144 /* Lock group and attribute for ifaddr lock */
145 LCK_ATTR_DECLARE(ifa_mtx_attr, 0, 0);
146 LCK_GRP_DECLARE(ifa_mtx_grp, "ifaddr");
147 
148 static int ifioctl_ifreq(struct socket *, u_long, struct ifreq *,
149     struct proc *);
150 static int ifioctl_ifconf(u_long, caddr_t);
151 static int ifioctl_ifclone(u_long, caddr_t);
152 static int ifioctl_iforder(u_long, caddr_t);
153 static int ifioctl_ifdesc(struct ifnet *, u_long, caddr_t, struct proc *);
154 static int ifioctl_linkparams(struct ifnet *, u_long, caddr_t, struct proc *);
155 static int ifioctl_qstats(struct ifnet *, u_long, caddr_t);
156 static int ifioctl_throttle(struct ifnet *, u_long, caddr_t, struct proc *);
157 static int ifioctl_netsignature(struct ifnet *, u_long, caddr_t);
158 static int ifconf(u_long cmd, user_addr_t ifrp, int * ret_space);
159 __private_extern__ void link_rtrequest(int, struct rtentry *, struct sockaddr *);
160 void if_rtproto_del(struct ifnet *ifp, int protocol);
161 
162 static int if_addmulti_common(struct ifnet *, const struct sockaddr *,
163     struct ifmultiaddr **, int);
164 static int if_delmulti_common(struct ifmultiaddr *, struct ifnet *,
165     const struct sockaddr *, int);
166 static struct ifnet *ifunit_common(const char *, boolean_t);
167 
168 static int if_rtmtu(struct radix_node *, void *);
169 static void if_rtmtu_update(struct ifnet *);
170 
171 static int if_clone_list(int, int *, user_addr_t);
172 
173 MALLOC_DEFINE(M_IFADDR, "ifaddr", "interface address");
174 
175 struct  ifnethead ifnet_head = TAILQ_HEAD_INITIALIZER(ifnet_head);
176 
177 /* ifnet_ordered_head and if_ordered_count are protected by the ifnet_head lock */
178 struct  ifnethead ifnet_ordered_head = TAILQ_HEAD_INITIALIZER(ifnet_ordered_head);
179 static  u_int32_t if_ordered_count = 0;
180 
181 static int      if_cloners_count;
182 LIST_HEAD(, if_clone) if_cloners = LIST_HEAD_INITIALIZER(if_cloners);
183 
184 static struct ifaddr *ifa_ifwithnet_common(const struct sockaddr *,
185     unsigned int);
186 static void if_attach_ifa_common(struct ifnet *, struct ifaddr *, int);
187 static void if_detach_ifa_common(struct ifnet *, struct ifaddr *, int);
188 
189 static void if_attach_ifma(struct ifnet *, struct ifmultiaddr *, int);
190 static int if_detach_ifma(struct ifnet *, struct ifmultiaddr *, int);
191 
192 static struct ifmultiaddr *ifma_alloc(zalloc_flags_t);
193 static void ifma_free(struct ifmultiaddr *);
194 static void ifma_trace(struct ifmultiaddr *, int);
195 
196 #if DEBUG
197 static TUNABLE(bool, ifma_debug, "ifma_debug", true); /* debugging (enabled) */
198 #else
199 static TUNABLE(bool, ifma_debug, "ifma_debug", false); /* debugging (disabled) */
200 #endif /* !DEBUG */
201 static struct zone *ifma_zone;          /* zone for ifmultiaddr */
202 
203 #define IFMA_TRACE_HIST_SIZE    32      /* size of trace history */
204 
205 /* For gdb */
206 __private_extern__ unsigned int ifma_trace_hist_size = IFMA_TRACE_HIST_SIZE;
207 
208 struct ifmultiaddr_dbg {
209 	struct ifmultiaddr      ifma;                   /* ifmultiaddr */
210 	u_int16_t               ifma_refhold_cnt;       /* # of ref */
211 	u_int16_t               ifma_refrele_cnt;       /* # of rele */
212 	/*
213 	 * Circular lists of IFA_ADDREF and IFA_REMREF callers.
214 	 */
215 	ctrace_t                ifma_refhold[IFMA_TRACE_HIST_SIZE];
216 	ctrace_t                ifma_refrele[IFMA_TRACE_HIST_SIZE];
217 	/*
218 	 * Trash list linkage
219 	 */
220 	TAILQ_ENTRY(ifmultiaddr_dbg) ifma_trash_link;
221 };
222 
223 /* List of trash ifmultiaddr entries protected by ifma_trash_lock */
224 static TAILQ_HEAD(, ifmultiaddr_dbg) ifma_trash_head;
225 static LCK_MTX_DECLARE_ATTR(ifma_trash_lock, &ifa_mtx_grp, &ifa_mtx_attr);
226 
227 #define IFMA_ZONE_MAX           64              /* maximum elements in zone */
228 #define IFMA_ZONE_NAME          "ifmultiaddr"   /* zone name */
229 
230 /*
231  * XXX: declare here to avoid to include many inet6 related files..
232  * should be more generalized?
233  */
234 extern void     nd6_setmtu(struct ifnet *);
235 
236 SYSCTL_NODE(_net, PF_LINK, link, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "Link layers");
237 SYSCTL_NODE(_net_link, 0, generic, CTLFLAG_RW | CTLFLAG_LOCKED, 0,
238     "Generic link-management");
239 
240 SYSCTL_DECL(_net_link_generic_system);
241 
242 static uint32_t if_verbose = 0;
243 SYSCTL_INT(_net_link_generic_system, OID_AUTO, if_verbose,
244     CTLFLAG_RW | CTLFLAG_LOCKED, &if_verbose, 0, "");
245 
246 #if (DEBUG || DEVELOPMENT)
247 static uint32_t default_tcp_kao_max = 0;
248 SYSCTL_INT(_net_link_generic_system, OID_AUTO, default_tcp_kao_max,
249     CTLFLAG_RW | CTLFLAG_LOCKED, &default_tcp_kao_max, 0, "");
250 #else
251 static const uint32_t default_tcp_kao_max = 0;
252 #endif /* (DEBUG || DEVELOPMENT) */
253 
254 u_int32_t companion_link_sock_buffer_limit = 0;
255 
256 static int
257 sysctl_set_companion_link_sock_buf_limit SYSCTL_HANDLER_ARGS
258 {
259 #pragma unused(arg1, arg2)
260 	int error, tmp = companion_link_sock_buffer_limit;
261 	error = sysctl_handle_int(oidp, &tmp, 0, req);
262 	if (tmp < 0) {
263 		return EINVAL;
264 	}
265 	if ((error = priv_check_cred(kauth_cred_get(),
266 	    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
267 		return error;
268 	}
269 
270 	u_int32_t new_limit = tmp;
271 	if (new_limit == companion_link_sock_buffer_limit) {
272 		return 0;
273 	}
274 
275 	bool recover = new_limit == 0 ? true : false;
276 	if (recover) {
277 		error = inp_recover_companion_link(&tcbinfo);
278 	} else {
279 		error = inp_limit_companion_link(&tcbinfo, new_limit);
280 	}
281 	if (!error) {
282 		companion_link_sock_buffer_limit = new_limit;
283 	}
284 	return error;
285 }
286 
287 SYSCTL_PROC(_net_link_generic_system, OID_AUTO, companion_sndbuf_limit,
288     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_ANYBODY,
289     &companion_link_sock_buffer_limit, 0, sysctl_set_companion_link_sock_buf_limit,
290     "I", "set sock send buffer limit of connections using companion links");
291 
292 
293 TUNABLE(bool, intcoproc_unrestricted, "intcoproc_unrestricted", false);
294 
295 SYSCTL_NODE(_net_link_generic_system, OID_AUTO, management,
296     CTLFLAG_RW | CTLFLAG_LOCKED, 0, "management interface");
297 
298 TUNABLE_WRITEABLE(int, if_management_verbose, "management_data_unrestricted", 0);
299 
300 SYSCTL_INT(_net_link_generic_system_management, OID_AUTO, verbose,
301     CTLFLAG_RW | CTLFLAG_LOCKED, &if_management_verbose, 0, "");
302 
303 /*
304  * boot-args to disable entitlement check for data transfer on management interface
305  */
306 TUNABLE_DEV_WRITEABLE(bool, management_data_unrestricted, "management_data_unrestricted", false);
307 
308 #if DEBUG || DEVELOPMENT
309 #define MANAGEMENT_CTLFLAG_ACCESS CTLFLAG_RW
310 #else
311 #define MANAGEMENT_CTLFLAG_ACCESS CTLFLAG_RD
312 #endif
313 
314 static int
315 sysctl_management_data_unrestricted SYSCTL_HANDLER_ARGS
316 {
317 #pragma unused(oidp, arg1, arg2)
318 	int val = management_data_unrestricted;
319 
320 	int error = sysctl_handle_int(oidp, &val, 0, req);
321 #if DEBUG || DEVELOPMENT
322 	if (error == 0 && req->newptr != USER_ADDR_NULL) {
323 		management_data_unrestricted = (val == 0) ? false : true;
324 		if (if_management_verbose > 0) {
325 			os_log(OS_LOG_DEFAULT,
326 			    "sysctl_management_data_unrestricted val %d -> management_data_unrestricted %d",
327 			    val, management_data_unrestricted);
328 		}
329 	}
330 #endif /* DEBUG || DEVELOPMENT */
331 	return error;
332 }
333 
334 SYSCTL_PROC(_net_link_generic_system_management, OID_AUTO, data_unrestricted,
335     CTLTYPE_INT | MANAGEMENT_CTLFLAG_ACCESS | CTLFLAG_LOCKED, 0, 0,
336     sysctl_management_data_unrestricted, "I", "");
337 
338 /*
339  * boot-args to disable entitlement restrictions to control management interfaces
340  */
341 TUNABLE_DEV_WRITEABLE(bool, management_control_unrestricted, "management_control_unrestricted", false);
342 
343 static int
344 sysctl_management_control_unrestricted SYSCTL_HANDLER_ARGS
345 {
346 #pragma unused(oidp, arg1, arg2)
347 	int val = management_control_unrestricted;
348 
349 	int error = sysctl_handle_int(oidp, &val, 0, req);
350 #if DEBUG || DEVELOPMENT
351 	if (error == 0 && req->newptr != USER_ADDR_NULL) {
352 		management_control_unrestricted = (val == 0) ? false : true;
353 		if (if_management_verbose > 0) {
354 			os_log(OS_LOG_DEFAULT,
355 			    "sysctl_management_control_unrestricted val %d -> management_control_unrestricted %d",
356 			    val, management_control_unrestricted);
357 		}
358 	}
359 #endif /* DEBUG || DEVELOPMENT */
360 	return error;
361 }
362 
363 SYSCTL_PROC(_net_link_generic_system_management, OID_AUTO, control_unrestricted,
364     CTLTYPE_INT | MANAGEMENT_CTLFLAG_ACCESS | CTLFLAG_LOCKED, 0, 0,
365     sysctl_management_control_unrestricted, "I", "");
366 
367 #undef MANAGEMENT_CTLFLAG_ACCESS
368 
369 /* The following is set as soon as IFNET_SUBFAMILY_MANAGEMENT is used */
370 bool if_management_interface_check_needed = false;
371 
372 /* Eventhandler context for interface events */
373 struct eventhandler_lists_ctxt ifnet_evhdlr_ctxt;
374 
375 void
ifa_init(void)376 ifa_init(void)
377 {
378 	size_t ifma_size = (ifma_debug == 0) ? sizeof(struct ifmultiaddr) :
379 	    sizeof(struct ifmultiaddr_dbg);
380 
381 	ifma_zone = zone_create(IFMA_ZONE_NAME, ifma_size, ZC_NONE);
382 	TAILQ_INIT(&ifma_trash_head);
383 }
384 
385 /*
386  * Network interface utility routines.
387  *
388  * Routines with ifa_ifwith* names take sockaddr *'s as
389  * parameters.
390  */
391 
392 int if_index;
393 struct ifaddr **ifnet_addrs;
394 struct ifnet **ifindex2ifnet;
395 
396 __private_extern__ void
if_attach_ifa(struct ifnet * ifp,struct ifaddr * ifa)397 if_attach_ifa(struct ifnet *ifp, struct ifaddr *ifa)
398 {
399 	if_attach_ifa_common(ifp, ifa, 0);
400 }
401 
402 __private_extern__ void
if_attach_link_ifa(struct ifnet * ifp,struct ifaddr * ifa)403 if_attach_link_ifa(struct ifnet *ifp, struct ifaddr *ifa)
404 {
405 	if_attach_ifa_common(ifp, ifa, 1);
406 }
407 
408 static void
if_attach_ifa_common(struct ifnet * ifp,struct ifaddr * ifa,int link)409 if_attach_ifa_common(struct ifnet *ifp, struct ifaddr *ifa, int link)
410 {
411 	ifnet_lock_assert(ifp, IFNET_LCK_ASSERT_EXCLUSIVE);
412 	IFA_LOCK_ASSERT_HELD(ifa);
413 
414 	if (ifa->ifa_ifp != ifp) {
415 		panic("%s: Mismatch ifa_ifp=%p != ifp=%p", __func__,
416 		    ifa->ifa_ifp, ifp);
417 		/* NOTREACHED */
418 	} else if (ifa->ifa_debug & IFD_ATTACHED) {
419 		panic("%s: Attempt to attach an already attached ifa=%p",
420 		    __func__, ifa);
421 		/* NOTREACHED */
422 	} else if (link && !(ifa->ifa_debug & IFD_LINK)) {
423 		panic("%s: Unexpected non-link address ifa=%p", __func__, ifa);
424 		/* NOTREACHED */
425 	} else if (!link && (ifa->ifa_debug & IFD_LINK)) {
426 		panic("%s: Unexpected link address ifa=%p", __func__, ifa);
427 		/* NOTREACHED */
428 	}
429 	IFA_ADDREF_LOCKED(ifa);
430 	ifa->ifa_debug |= IFD_ATTACHED;
431 
432 	if (link) {
433 		TAILQ_INSERT_HEAD(&ifp->if_addrhead, ifa, ifa_link);
434 	} else {
435 		TAILQ_INSERT_TAIL(&ifp->if_addrhead, ifa, ifa_link);
436 	}
437 
438 	if (ifa->ifa_attached != NULL) {
439 		(*ifa->ifa_attached)(ifa);
440 	}
441 
442 #if SKYWALK
443 	SK_NXS_MS_IF_ADDR_GENCNT_INC(ifp);
444 #endif /* SKYWALK */
445 }
446 
447 __private_extern__ void
if_detach_ifa(struct ifnet * ifp,struct ifaddr * ifa)448 if_detach_ifa(struct ifnet *ifp, struct ifaddr *ifa)
449 {
450 	if_detach_ifa_common(ifp, ifa, 0);
451 }
452 
453 __private_extern__ void
if_detach_link_ifa(struct ifnet * ifp,struct ifaddr * ifa)454 if_detach_link_ifa(struct ifnet *ifp, struct ifaddr *ifa)
455 {
456 	if_detach_ifa_common(ifp, ifa, 1);
457 }
458 
459 static void
if_detach_ifa_common(struct ifnet * ifp,struct ifaddr * ifa,int link)460 if_detach_ifa_common(struct ifnet *ifp, struct ifaddr *ifa, int link)
461 {
462 	ifnet_lock_assert(ifp, IFNET_LCK_ASSERT_EXCLUSIVE);
463 	IFA_LOCK_ASSERT_HELD(ifa);
464 
465 	if (link && !(ifa->ifa_debug & IFD_LINK)) {
466 		panic("%s: Unexpected non-link address ifa=%p", __func__, ifa);
467 		/* NOTREACHED */
468 	} else if (link && ifa != TAILQ_FIRST(&ifp->if_addrhead)) {
469 		panic("%s: Link address ifa=%p not first", __func__, ifa);
470 		/* NOTREACHED */
471 	} else if (!link && (ifa->ifa_debug & IFD_LINK)) {
472 		panic("%s: Unexpected link address ifa=%p", __func__, ifa);
473 		/* NOTREACHED */
474 	} else if (!(ifa->ifa_debug & IFD_ATTACHED)) {
475 		panic("%s: Attempt to detach an unattached address ifa=%p",
476 		    __func__, ifa);
477 		/* NOTREACHED */
478 	} else if (ifa->ifa_ifp != ifp) {
479 		panic("%s: Mismatch ifa_ifp=%p, ifp=%p", __func__,
480 		    ifa->ifa_ifp, ifp);
481 		/* NOTREACHED */
482 	} else if (ifa->ifa_debug & IFD_DEBUG) {
483 		struct ifaddr *ifa2;
484 		TAILQ_FOREACH(ifa2, &ifp->if_addrhead, ifa_link) {
485 			if (ifa2 == ifa) {
486 				break;
487 			}
488 		}
489 		if (ifa2 != ifa) {
490 			panic("%s: Attempt to detach a stray address ifa=%p",
491 			    __func__, ifa);
492 			/* NOTREACHED */
493 		}
494 	}
495 	TAILQ_REMOVE(&ifp->if_addrhead, ifa, ifa_link);
496 	/* This must not be the last reference to the ifaddr */
497 	if (IFA_REMREF_LOCKED(ifa) == NULL) {
498 		panic("%s: unexpected (missing) refcnt ifa=%p", __func__, ifa);
499 		/* NOTREACHED */
500 	}
501 	ifa->ifa_debug &= ~IFD_ATTACHED;
502 
503 	if (ifa->ifa_detached != NULL) {
504 		(*ifa->ifa_detached)(ifa);
505 	}
506 
507 #if SKYWALK
508 	SK_NXS_MS_IF_ADDR_GENCNT_INC(ifp);
509 #endif /* SKYWALK */
510 }
511 
512 #define INITIAL_IF_INDEXLIM     8
513 
514 /*
515  * Function: if_next_index
516  * Purpose:
517  *   Return the next available interface index.
518  *   Grow the ifnet_addrs[] and ifindex2ifnet[] arrays to accomodate the
519  *   added entry when necessary.
520  *
521  * Note:
522  *   ifnet_addrs[] is indexed by (if_index - 1), whereas
523  *   ifindex2ifnet[] is indexed by ifp->if_index.  That requires us to
524  *   always allocate one extra element to hold ifindex2ifnet[0], which
525  *   is unused.
526  */
527 int if_next_index(void);
528 
529 __private_extern__ int
if_next_index(void)530 if_next_index(void)
531 {
532 	static int      if_indexlim = 0;
533 	int             new_index;
534 
535 	/*
536 	 * Although we are returning an integer,
537 	 * ifnet's if_index is a uint16_t which means
538 	 * that's our upper bound.
539 	 */
540 	if (if_index >= UINT16_MAX) {
541 		return -1;
542 	}
543 	new_index = ++if_index;
544 	if (if_index > if_indexlim) {
545 		unsigned        n;
546 		int             new_if_indexlim;
547 		caddr_t         new_ifnet_addrs;
548 		caddr_t         new_ifindex2ifnet;
549 		caddr_t         old_ifnet_addrs;
550 		size_t          old_ifnet_size;
551 
552 		old_ifnet_addrs = (caddr_t)ifnet_addrs;
553 		old_ifnet_size = (size_t)(2 * if_indexlim + 1);
554 		if (ifnet_addrs == NULL) {
555 			new_if_indexlim = INITIAL_IF_INDEXLIM;
556 		} else {
557 			new_if_indexlim = if_indexlim << 1;
558 		}
559 
560 		/* allocate space for the larger arrays */
561 		n = (2 * new_if_indexlim + 1);
562 		new_ifnet_addrs = (caddr_t)kalloc_type(caddr_t, n, Z_WAITOK | Z_ZERO);
563 		if (new_ifnet_addrs == NULL) {
564 			--if_index;
565 			return -1;
566 		}
567 
568 		new_ifindex2ifnet = new_ifnet_addrs + new_if_indexlim * sizeof(caddr_t);
569 		if (ifnet_addrs != NULL) {
570 			/* copy the existing data */
571 			bcopy(ifnet_addrs, new_ifnet_addrs, if_indexlim * sizeof(caddr_t));
572 			bcopy(ifindex2ifnet, new_ifindex2ifnet, (if_indexlim + 1) * sizeof(caddr_t));
573 		}
574 
575 		/* switch to the new tables and size */
576 		ifnet_addrs = (struct ifaddr **)(void *)new_ifnet_addrs;
577 		ifindex2ifnet = (struct ifnet **)(void *)new_ifindex2ifnet;
578 		if_indexlim = new_if_indexlim;
579 
580 		/* release the old data */
581 		if (old_ifnet_addrs != NULL) {
582 			void *old_ifnet_addrs_p = (void *)old_ifnet_addrs;
583 			kfree_type(caddr_t, old_ifnet_size, old_ifnet_addrs_p);
584 		}
585 	}
586 	return new_index;
587 }
588 
589 /*
590  * Create a clone network interface.
591  */
592 static int
if_clone_create(char * name,int len,void * params)593 if_clone_create(char *name, int len, void *params)
594 {
595 	struct if_clone *ifc;
596 	struct ifnet *ifp;
597 	char *dp;
598 	int wildcard;
599 	u_int32_t bytoff, bitoff;
600 	u_int32_t unit;
601 	int err;
602 
603 	ifc = if_clone_lookup(name, &unit);
604 	if (ifc == NULL) {
605 		return EINVAL;
606 	}
607 
608 	if (ifunit(name) != NULL) {
609 		return EEXIST;
610 	}
611 
612 	bytoff = bitoff = 0;
613 	wildcard = (unit == UINT32_MAX);
614 	/*
615 	 * Find a free unit if none was given.
616 	 */
617 	lck_mtx_lock(&ifc->ifc_mutex);
618 again:
619 	if (wildcard) {
620 		while ((bytoff < ifc->ifc_bmlen) &&
621 		    (ifc->ifc_units[bytoff] == 0xff)) {
622 			bytoff++;
623 		}
624 		if (bytoff >= ifc->ifc_bmlen) {
625 			lck_mtx_lock(&ifc->ifc_mutex);
626 			return ENOSPC;
627 		}
628 		while ((ifc->ifc_units[bytoff] & (1 << bitoff)) != 0) {
629 			bitoff++;
630 		}
631 		unit = (bytoff << 3) + bitoff;
632 	}
633 
634 	if (unit > ifc->ifc_maxunit) {
635 		lck_mtx_unlock(&ifc->ifc_mutex);
636 		return ENXIO;
637 	}
638 
639 	err = (*ifc->ifc_create)(ifc, unit, params);
640 	if (err != 0) {
641 		if (wildcard && err == EBUSY) {
642 			bitoff++;
643 			goto again;
644 		}
645 		lck_mtx_unlock(&ifc->ifc_mutex);
646 		return err;
647 	}
648 
649 	if (!wildcard) {
650 		bytoff = unit >> 3;
651 		bitoff = unit - (bytoff << 3);
652 	}
653 
654 	/*
655 	 * Allocate the unit in the bitmap.
656 	 */
657 	KASSERT((ifc->ifc_units[bytoff] & (1 << bitoff)) == 0,
658 	    ("%s: bit is already set", __func__));
659 	ifc->ifc_units[bytoff] |= (1 << bitoff);
660 
661 	/* In the wildcard case, we need to update the name. */
662 	if (wildcard) {
663 		for (dp = name; *dp != '\0'; dp++) {
664 			;
665 		}
666 		if (snprintf(dp, len - (dp - name), "%d", unit) >
667 		    len - (dp - name) - 1) {
668 			/*
669 			 * This can only be a programmer error and
670 			 * there's no straightforward way to recover if
671 			 * it happens.
672 			 */
673 			panic("%s: interface name too long", __func__);
674 			/* NOTREACHED */
675 		}
676 	}
677 	lck_mtx_unlock(&ifc->ifc_mutex);
678 	ifp = ifunit(name);
679 	if (ifp != NULL) {
680 		if_set_eflags(ifp, IFEF_CLONE);
681 	}
682 	return 0;
683 }
684 
685 /*
686  * Destroy a clone network interface.
687  */
688 static int
if_clone_destroy(const char * name)689 if_clone_destroy(const char *name)
690 {
691 	struct if_clone *ifc = NULL;
692 	struct ifnet *ifp = NULL;
693 	int bytoff, bitoff;
694 	u_int32_t unit;
695 	int error = 0;
696 
697 	ifc = if_clone_lookup(name, &unit);
698 
699 	if (ifc == NULL) {
700 		error = EINVAL;
701 		goto done;
702 	}
703 
704 	if (unit < ifc->ifc_minifs) {
705 		error = EINVAL;
706 		goto done;
707 	}
708 
709 	ifp = ifunit_ref(name);
710 	if (ifp == NULL) {
711 		error = ENXIO;
712 		goto done;
713 	}
714 	if ((ifp->if_eflags & IFEF_CLONE) == 0) {
715 		error = EOPNOTSUPP;
716 		goto done;
717 	}
718 	if (ifc->ifc_destroy == NULL) {
719 		error = EOPNOTSUPP;
720 		goto done;
721 	}
722 
723 	lck_mtx_lock(&ifc->ifc_mutex);
724 	error = (*ifc->ifc_destroy)(ifp);
725 
726 	if (error) {
727 		lck_mtx_unlock(&ifc->ifc_mutex);
728 		goto done;
729 	}
730 
731 	/* Compute offset in the bitmap and deallocate the unit. */
732 	bytoff = unit >> 3;
733 	bitoff = unit - (bytoff << 3);
734 	KASSERT((ifc->ifc_units[bytoff] & (1 << bitoff)) != 0,
735 	    ("%s: bit is already cleared", __func__));
736 	ifc->ifc_units[bytoff] &= ~(1 << bitoff);
737 	lck_mtx_unlock(&ifc->ifc_mutex);
738 
739 done:
740 	if (ifp != NULL) {
741 		ifnet_decr_iorefcnt(ifp);
742 	}
743 	return error;
744 }
745 
746 /*
747  * Look up a network interface cloner.
748  */
749 
750 __private_extern__ struct if_clone *
if_clone_lookup(const char * name,u_int32_t * unitp)751 if_clone_lookup(const char *name, u_int32_t *unitp)
752 {
753 	struct if_clone *ifc;
754 	const char *cp;
755 	u_int32_t i;
756 
757 	LIST_FOREACH(ifc, &if_cloners, ifc_list) {
758 		if (strncmp(name, ifc->ifc_name, ifc->ifc_namelen) == 0) {
759 			cp = name + ifc->ifc_namelen;
760 			goto found_name;
761 		}
762 	}
763 
764 	/* No match. */
765 	return (struct if_clone *)NULL;
766 
767 found_name:
768 	if (*cp == '\0') {
769 		i = UINT32_MAX;
770 	} else {
771 		for (i = 0; *cp != '\0'; cp++) {
772 			if (*cp < '0' || *cp > '9') {
773 				/* Bogus unit number. */
774 				return NULL;
775 			}
776 			i = (i * 10) + (*cp - '0');
777 		}
778 	}
779 
780 	if (unitp != NULL) {
781 		*unitp = i;
782 	}
783 	return ifc;
784 }
785 
786 /*
787  * Register a network interface cloner.
788  */
789 int
if_clone_attach(struct if_clone * ifc)790 if_clone_attach(struct if_clone *ifc)
791 {
792 	int bytoff, bitoff;
793 	int err;
794 	int len, maxclone;
795 	u_int32_t unit;
796 
797 	KASSERT(ifc->ifc_minifs - 1 <= ifc->ifc_maxunit,
798 	    ("%s: %s requested more units then allowed (%d > %d)",
799 	    __func__, ifc->ifc_name, ifc->ifc_minifs,
800 	    ifc->ifc_maxunit + 1));
801 	/*
802 	 * Compute bitmap size and allocate it.
803 	 */
804 	maxclone = ifc->ifc_maxunit + 1;
805 	len = maxclone >> 3;
806 	if ((len << 3) < maxclone) {
807 		len++;
808 	}
809 	ifc->ifc_units = (unsigned char *)kalloc_data(len, Z_WAITOK | Z_ZERO);
810 	if (ifc->ifc_units == NULL) {
811 		return ENOBUFS;
812 	}
813 	ifc->ifc_bmlen = len;
814 	lck_mtx_init(&ifc->ifc_mutex, &ifnet_lock_group, &ifnet_lock_attr);
815 
816 	LIST_INSERT_HEAD(&if_cloners, ifc, ifc_list);
817 	if_cloners_count++;
818 
819 	for (unit = 0; unit < ifc->ifc_minifs; unit++) {
820 		err = (*ifc->ifc_create)(ifc, unit, NULL);
821 		KASSERT(err == 0,
822 		    ("%s: failed to create required interface %s%d",
823 		    __func__, ifc->ifc_name, unit));
824 
825 		/* Allocate the unit in the bitmap. */
826 		bytoff = unit >> 3;
827 		bitoff = unit - (bytoff << 3);
828 		ifc->ifc_units[bytoff] |= (1 << bitoff);
829 	}
830 
831 	return 0;
832 }
833 
834 /*
835  * Unregister a network interface cloner.
836  */
837 void
if_clone_detach(struct if_clone * ifc)838 if_clone_detach(struct if_clone *ifc)
839 {
840 	LIST_REMOVE(ifc, ifc_list);
841 	kfree_data(ifc->ifc_units, ifc->ifc_bmlen);
842 	lck_mtx_destroy(&ifc->ifc_mutex, &ifnet_lock_group);
843 	if_cloners_count--;
844 }
845 
846 /*
847  * Provide list of interface cloners to userspace.
848  */
849 static int
if_clone_list(int count,int * ret_total,user_addr_t dst)850 if_clone_list(int count, int *ret_total, user_addr_t dst)
851 {
852 	char outbuf[IFNAMSIZ];
853 	struct if_clone *ifc;
854 	int error = 0;
855 
856 	*ret_total = if_cloners_count;
857 	if (dst == USER_ADDR_NULL) {
858 		/* Just asking how many there are. */
859 		return 0;
860 	}
861 
862 	if (count < 0) {
863 		return EINVAL;
864 	}
865 
866 	count = (if_cloners_count < count) ? if_cloners_count : count;
867 
868 	for (ifc = LIST_FIRST(&if_cloners); ifc != NULL && count != 0;
869 	    ifc = LIST_NEXT(ifc, ifc_list), count--, dst += IFNAMSIZ) {
870 		bzero(outbuf, sizeof(outbuf));
871 		strlcpy(outbuf, ifc->ifc_name, IFNAMSIZ);
872 		error = copyout(outbuf, dst, IFNAMSIZ);
873 		if (error) {
874 			break;
875 		}
876 	}
877 
878 	return error;
879 }
880 
881 u_int32_t
if_functional_type(struct ifnet * ifp,bool exclude_delegate)882 if_functional_type(struct ifnet *ifp, bool exclude_delegate)
883 {
884 	u_int32_t ret = IFRTYPE_FUNCTIONAL_UNKNOWN;
885 
886 	if (ifp != NULL) {
887 		if (ifp->if_flags & IFF_LOOPBACK) {
888 			ret = IFRTYPE_FUNCTIONAL_LOOPBACK;
889 		} else if (IFNET_IS_COMPANION_LINK(ifp)) {
890 			ret = IFRTYPE_FUNCTIONAL_COMPANIONLINK;
891 		} else if ((exclude_delegate &&
892 		    (ifp->if_family == IFNET_FAMILY_ETHERNET &&
893 		    ifp->if_subfamily == IFNET_SUBFAMILY_WIFI)) ||
894 		    (!exclude_delegate && IFNET_IS_WIFI(ifp))) {
895 			if (ifp->if_eflags & IFEF_AWDL) {
896 				ret = IFRTYPE_FUNCTIONAL_WIFI_AWDL;
897 			} else {
898 				ret = IFRTYPE_FUNCTIONAL_WIFI_INFRA;
899 			}
900 		} else if ((exclude_delegate &&
901 		    (ifp->if_type == IFT_CELLULAR ||
902 		    (ifp->if_family == IFNET_FAMILY_ETHERNET &&
903 		    ifp->if_subfamily == IFNET_SUBFAMILY_SIMCELL))) ||
904 		    (!exclude_delegate && IFNET_IS_CELLULAR(ifp))) {
905 			ret = IFRTYPE_FUNCTIONAL_CELLULAR;
906 		} else if (IFNET_IS_INTCOPROC(ifp)) {
907 			ret = IFRTYPE_FUNCTIONAL_INTCOPROC;
908 		} else if (IFNET_IS_MANAGEMENT(ifp)) {
909 			ret = IFRTYPE_FUNCTIONAL_MANAGEMENT;
910 		} else if ((exclude_delegate &&
911 		    (ifp->if_family == IFNET_FAMILY_ETHERNET ||
912 		    ifp->if_family == IFNET_FAMILY_BOND ||
913 		    ifp->if_family == IFNET_FAMILY_VLAN ||
914 		    ifp->if_family == IFNET_FAMILY_FIREWIRE)) ||
915 		    (!exclude_delegate && IFNET_IS_WIRED(ifp))) {
916 			ret = IFRTYPE_FUNCTIONAL_WIRED;
917 		}
918 	}
919 
920 	return ret;
921 }
922 
923 /*
924  * Similar to ifa_ifwithaddr, except that this is IPv4 specific
925  * and that it matches only the local (not broadcast) address.
926  */
927 __private_extern__ struct in_ifaddr *
ifa_foraddr(unsigned int addr)928 ifa_foraddr(unsigned int addr)
929 {
930 	return ifa_foraddr_scoped(addr, IFSCOPE_NONE);
931 }
932 
933 /*
934  * Similar to ifa_foraddr, except with the added interface scope
935  * constraint (unless the caller passes in IFSCOPE_NONE in which
936  * case there is no scope restriction).
937  */
938 __private_extern__ struct in_ifaddr *
ifa_foraddr_scoped(unsigned int addr,unsigned int scope)939 ifa_foraddr_scoped(unsigned int addr, unsigned int scope)
940 {
941 	struct in_ifaddr *ia = NULL;
942 
943 	lck_rw_lock_shared(&in_ifaddr_rwlock);
944 	TAILQ_FOREACH(ia, INADDR_HASH(addr), ia_hash) {
945 		IFA_LOCK_SPIN(&ia->ia_ifa);
946 		if (ia->ia_addr.sin_addr.s_addr == addr &&
947 		    (scope == IFSCOPE_NONE || ia->ia_ifp->if_index == scope)) {
948 			IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for caller */
949 			IFA_UNLOCK(&ia->ia_ifa);
950 			break;
951 		}
952 		IFA_UNLOCK(&ia->ia_ifa);
953 	}
954 	lck_rw_done(&in_ifaddr_rwlock);
955 	return ia;
956 }
957 
958 /*
959  * Similar to ifa_foraddr, except that this for IPv6.
960  */
961 __private_extern__ struct in6_ifaddr *
ifa_foraddr6(struct in6_addr * addr6)962 ifa_foraddr6(struct in6_addr *addr6)
963 {
964 	return ifa_foraddr6_scoped(addr6, IFSCOPE_NONE);
965 }
966 
967 __private_extern__ struct in6_ifaddr *
ifa_foraddr6_scoped(struct in6_addr * addr6,unsigned int scope)968 ifa_foraddr6_scoped(struct in6_addr *addr6, unsigned int scope)
969 {
970 	struct in6_ifaddr *ia = NULL;
971 
972 	lck_rw_lock_shared(&in6_ifaddr_rwlock);
973 	TAILQ_FOREACH(ia, IN6ADDR_HASH(addr6), ia6_hash) {
974 		IFA_LOCK(&ia->ia_ifa);
975 		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr, addr6) &&
976 		    (scope == IFSCOPE_NONE || ia->ia_ifp->if_index == scope)) {
977 			IFA_ADDREF_LOCKED(&ia->ia_ifa); /* for caller */
978 			IFA_UNLOCK(&ia->ia_ifa);
979 			break;
980 		}
981 		IFA_UNLOCK(&ia->ia_ifa);
982 	}
983 	lck_rw_done(&in6_ifaddr_rwlock);
984 
985 	return ia;
986 }
987 
988 /*
989  * Return the first (primary) address of a given family on an interface.
990  */
991 __private_extern__ struct ifaddr *
ifa_ifpgetprimary(struct ifnet * ifp,int family)992 ifa_ifpgetprimary(struct ifnet *ifp, int family)
993 {
994 	struct ifaddr *ifa;
995 
996 	ifnet_lock_shared(ifp);
997 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
998 		IFA_LOCK_SPIN(ifa);
999 		if (ifa->ifa_addr->sa_family == family) {
1000 			IFA_ADDREF_LOCKED(ifa); /* for caller */
1001 			IFA_UNLOCK(ifa);
1002 			break;
1003 		}
1004 		IFA_UNLOCK(ifa);
1005 	}
1006 	ifnet_lock_done(ifp);
1007 
1008 	return ifa;
1009 }
1010 
1011 inline boolean_t
sa_equal(const struct sockaddr * sa1,const struct sockaddr * sa2)1012 sa_equal(const struct sockaddr *sa1, const struct sockaddr *sa2)
1013 {
1014 	if (!sa1 || !sa2) {
1015 		return FALSE;
1016 	}
1017 	if (sa1->sa_len != sa2->sa_len) {
1018 		return FALSE;
1019 	}
1020 
1021 	return bcmp(sa1, sa2, sa1->sa_len) == 0;
1022 }
1023 
1024 /*
1025  * Locate an interface based on a complete address.
1026  */
1027 struct ifaddr *
ifa_ifwithaddr_locked(const struct sockaddr * addr)1028 ifa_ifwithaddr_locked(const struct sockaddr *addr)
1029 {
1030 	struct ifnet *ifp;
1031 	struct ifaddr *ifa;
1032 	struct ifaddr *result = NULL;
1033 
1034 	for (ifp = ifnet_head.tqh_first; ifp && !result;
1035 	    ifp = ifp->if_link.tqe_next) {
1036 		ifnet_lock_shared(ifp);
1037 		for (ifa = ifp->if_addrhead.tqh_first; ifa;
1038 		    ifa = ifa->ifa_link.tqe_next) {
1039 			IFA_LOCK_SPIN(ifa);
1040 			if (ifa->ifa_addr->sa_family != addr->sa_family) {
1041 				IFA_UNLOCK(ifa);
1042 				continue;
1043 			}
1044 			if (sa_equal(addr, ifa->ifa_addr)) {
1045 				result = ifa;
1046 				IFA_ADDREF_LOCKED(ifa); /* for caller */
1047 				IFA_UNLOCK(ifa);
1048 				break;
1049 			}
1050 			if ((ifp->if_flags & IFF_BROADCAST) &&
1051 			    ifa->ifa_broadaddr != NULL &&
1052 			    /* IP6 doesn't have broadcast */
1053 			    ifa->ifa_broadaddr->sa_len != 0 &&
1054 			    sa_equal(ifa->ifa_broadaddr, addr)) {
1055 				result = ifa;
1056 				IFA_ADDREF_LOCKED(ifa); /* for caller */
1057 				IFA_UNLOCK(ifa);
1058 				break;
1059 			}
1060 			IFA_UNLOCK(ifa);
1061 		}
1062 		ifnet_lock_done(ifp);
1063 	}
1064 
1065 	return result;
1066 }
1067 
1068 struct ifaddr *
ifa_ifwithaddr(const struct sockaddr * addr)1069 ifa_ifwithaddr(const struct sockaddr *addr)
1070 {
1071 	struct ifaddr *result = NULL;
1072 
1073 	ifnet_head_lock_shared();
1074 
1075 	result = ifa_ifwithaddr_locked(addr);
1076 
1077 	ifnet_head_done();
1078 
1079 	return result;
1080 }
1081 /*
1082  * Locate the point to point interface with a given destination address.
1083  */
1084 /*ARGSUSED*/
1085 
1086 static struct ifaddr *
ifa_ifwithdstaddr_ifp(const struct sockaddr * addr,struct ifnet * ifp)1087 ifa_ifwithdstaddr_ifp(const struct sockaddr *addr, struct ifnet * ifp)
1088 {
1089 	struct ifaddr *ifa;
1090 	struct ifaddr *result = NULL;
1091 
1092 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1093 		ifnet_lock_shared(ifp);
1094 
1095 		for (ifa = ifp->if_addrhead.tqh_first; ifa;
1096 		    ifa = ifa->ifa_link.tqe_next) {
1097 			IFA_LOCK_SPIN(ifa);
1098 			if (ifa->ifa_addr->sa_family !=
1099 			    addr->sa_family) {
1100 				IFA_UNLOCK(ifa);
1101 				continue;
1102 			}
1103 			if (sa_equal(addr, ifa->ifa_dstaddr)) {
1104 				result = ifa;
1105 				IFA_ADDREF_LOCKED(ifa); /* for caller */
1106 				IFA_UNLOCK(ifa);
1107 				break;
1108 			}
1109 			IFA_UNLOCK(ifa);
1110 		}
1111 
1112 		ifnet_lock_done(ifp);
1113 	}
1114 	return result;
1115 }
1116 
1117 struct ifaddr *
ifa_ifwithdstaddr(const struct sockaddr * addr)1118 ifa_ifwithdstaddr(const struct sockaddr *addr)
1119 {
1120 	struct ifnet *ifp;
1121 	struct ifaddr *result = NULL;
1122 
1123 	ifnet_head_lock_shared();
1124 	for (ifp = ifnet_head.tqh_first; ifp && !result;
1125 	    ifp = ifp->if_link.tqe_next) {
1126 		result = ifa_ifwithdstaddr_ifp(addr, ifp);
1127 	}
1128 	ifnet_head_done();
1129 	return result;
1130 }
1131 
1132 struct ifaddr *
ifa_ifwithdstaddr_scoped(const struct sockaddr * addr,unsigned int ifscope)1133 ifa_ifwithdstaddr_scoped(const struct sockaddr *addr, unsigned int ifscope)
1134 {
1135 	struct ifnet *ifp;
1136 	struct ifaddr *result = NULL;
1137 
1138 	if (ifscope == IFSCOPE_NONE) {
1139 		return ifa_ifwithdstaddr(addr);
1140 	}
1141 	ifnet_head_lock_shared();
1142 	if (ifscope <= (unsigned int)if_index) {
1143 		ifp = ifindex2ifnet[ifscope];
1144 		if (ifp != NULL) {
1145 			result = ifa_ifwithdstaddr_ifp(addr, ifp);
1146 		}
1147 	}
1148 	ifnet_head_done();
1149 	return result;
1150 }
1151 
1152 /*
1153  * Locate the source address of an interface based on a complete address.
1154  */
1155 struct ifaddr *
ifa_ifwithaddr_scoped_locked(const struct sockaddr * addr,unsigned int ifscope)1156 ifa_ifwithaddr_scoped_locked(const struct sockaddr *addr, unsigned int ifscope)
1157 {
1158 	struct ifaddr *result = NULL;
1159 	struct ifnet *ifp;
1160 
1161 	if (ifscope == IFSCOPE_NONE) {
1162 		return ifa_ifwithaddr_locked(addr);
1163 	}
1164 
1165 	if (ifscope > (unsigned int)if_index) {
1166 		return NULL;
1167 	}
1168 
1169 	ifp = ifindex2ifnet[ifscope];
1170 	if (ifp != NULL) {
1171 		struct ifaddr *ifa = NULL;
1172 
1173 		/*
1174 		 * This is suboptimal; there should be a better way
1175 		 * to search for a given address of an interface
1176 		 * for any given address family.
1177 		 */
1178 		ifnet_lock_shared(ifp);
1179 		for (ifa = ifp->if_addrhead.tqh_first; ifa != NULL;
1180 		    ifa = ifa->ifa_link.tqe_next) {
1181 			IFA_LOCK_SPIN(ifa);
1182 			if (ifa->ifa_addr->sa_family != addr->sa_family) {
1183 				IFA_UNLOCK(ifa);
1184 				continue;
1185 			}
1186 			if (sa_equal(addr, ifa->ifa_addr)) {
1187 				result = ifa;
1188 				IFA_ADDREF_LOCKED(ifa); /* for caller */
1189 				IFA_UNLOCK(ifa);
1190 				break;
1191 			}
1192 			if ((ifp->if_flags & IFF_BROADCAST) &&
1193 			    ifa->ifa_broadaddr != NULL &&
1194 			    /* IP6 doesn't have broadcast */
1195 			    ifa->ifa_broadaddr->sa_len != 0 &&
1196 			    sa_equal(ifa->ifa_broadaddr, addr)) {
1197 				result = ifa;
1198 				IFA_ADDREF_LOCKED(ifa); /* for caller */
1199 				IFA_UNLOCK(ifa);
1200 				break;
1201 			}
1202 			IFA_UNLOCK(ifa);
1203 		}
1204 		ifnet_lock_done(ifp);
1205 	}
1206 
1207 	return result;
1208 }
1209 
1210 struct ifaddr *
ifa_ifwithaddr_scoped(const struct sockaddr * addr,unsigned int ifscope)1211 ifa_ifwithaddr_scoped(const struct sockaddr *addr, unsigned int ifscope)
1212 {
1213 	struct ifaddr *result = NULL;
1214 
1215 	ifnet_head_lock_shared();
1216 
1217 	result = ifa_ifwithaddr_scoped_locked(addr, ifscope);
1218 
1219 	ifnet_head_done();
1220 
1221 	return result;
1222 }
1223 
1224 struct ifaddr *
ifa_ifwithnet(const struct sockaddr * addr)1225 ifa_ifwithnet(const struct sockaddr *addr)
1226 {
1227 	return ifa_ifwithnet_common(addr, IFSCOPE_NONE);
1228 }
1229 
1230 struct ifaddr *
ifa_ifwithnet_scoped(const struct sockaddr * addr,unsigned int ifscope)1231 ifa_ifwithnet_scoped(const struct sockaddr *addr, unsigned int ifscope)
1232 {
1233 	return ifa_ifwithnet_common(addr, ifscope);
1234 }
1235 
1236 /*
1237  * Find an interface on a specific network.  If many, choice
1238  * is most specific found.
1239  */
1240 static struct ifaddr *
ifa_ifwithnet_common(const struct sockaddr * addr,unsigned int ifscope)1241 ifa_ifwithnet_common(const struct sockaddr *addr, unsigned int ifscope)
1242 {
1243 	struct ifnet *ifp;
1244 	struct ifaddr *ifa = NULL;
1245 	struct ifaddr *ifa_maybe = NULL;
1246 	u_int af = addr->sa_family;
1247 	const char *addr_data = addr->sa_data, *cplim;
1248 	const struct sockaddr_in6 *sock_addr = (const struct sockaddr_in6*)(const void*)addr;
1249 
1250 	if (af != AF_INET && af != AF_INET6) {
1251 		ifscope = IFSCOPE_NONE;
1252 	}
1253 
1254 	ifnet_head_lock_shared();
1255 	/*
1256 	 * AF_LINK addresses can be looked up directly by their index number,
1257 	 * so do that if we can.
1258 	 */
1259 	if (af == AF_LINK) {
1260 		const struct sockaddr_dl *sdl =
1261 		    (const struct sockaddr_dl *)(uintptr_t)(size_t)addr;
1262 		if (sdl->sdl_index && sdl->sdl_index <= if_index) {
1263 			ifa = ifnet_addrs[sdl->sdl_index - 1];
1264 			if (ifa != NULL) {
1265 				IFA_ADDREF(ifa);
1266 			}
1267 
1268 			ifnet_head_done();
1269 			return ifa;
1270 		}
1271 	}
1272 
1273 	if (!in6_embedded_scope && af == AF_INET6 &&
1274 	    IN6_IS_SCOPE_EMBED(&sock_addr->sin6_addr)) {
1275 		VERIFY(ifscope != IFSCOPE_NONE);
1276 	}
1277 
1278 	/*
1279 	 * Scan though each interface, looking for ones that have
1280 	 * addresses in this address family.
1281 	 */
1282 	for (ifp = ifnet_head.tqh_first; ifp; ifp = ifp->if_link.tqe_next) {
1283 		ifnet_lock_shared(ifp);
1284 		for (ifa = ifp->if_addrhead.tqh_first; ifa;
1285 		    ifa = ifa->ifa_link.tqe_next) {
1286 			const char *cp, *cp2, *cp3;
1287 
1288 			IFA_LOCK(ifa);
1289 			if (ifa->ifa_addr == NULL ||
1290 			    ifa->ifa_addr->sa_family != af) {
1291 next:
1292 				IFA_UNLOCK(ifa);
1293 				continue;
1294 			}
1295 			/*
1296 			 * If we're looking up with a scope,
1297 			 * find using a matching interface.
1298 			 */
1299 			if (ifscope != IFSCOPE_NONE &&
1300 			    ifp->if_index != ifscope) {
1301 				IFA_UNLOCK(ifa);
1302 				continue;
1303 			}
1304 
1305 			/*
1306 			 * Scan all the bits in the ifa's address.
1307 			 * If a bit dissagrees with what we are
1308 			 * looking for, mask it with the netmask
1309 			 * to see if it really matters.
1310 			 * (A byte at a time)
1311 			 */
1312 			if (ifa->ifa_netmask == 0) {
1313 				IFA_UNLOCK(ifa);
1314 				continue;
1315 			}
1316 			cp = addr_data;
1317 			cp2 = ifa->ifa_addr->sa_data;
1318 			cp3 = ifa->ifa_netmask->sa_data;
1319 			cplim = ifa->ifa_netmask->sa_len +
1320 			    (char *)ifa->ifa_netmask;
1321 			while (cp3 < cplim) {
1322 				if ((*cp++ ^ *cp2++) & *cp3++) {
1323 					goto next; /* next address! */
1324 				}
1325 			}
1326 			/*
1327 			 * If the netmask of what we just found
1328 			 * is more specific than what we had before
1329 			 * (if we had one) then remember the new one
1330 			 * before continuing to search
1331 			 * for an even better one.
1332 			 */
1333 			if (ifa_maybe == NULL ||
1334 			    rn_refines((caddr_t)ifa->ifa_netmask,
1335 			    (caddr_t)ifa_maybe->ifa_netmask)) {
1336 				IFA_ADDREF_LOCKED(ifa); /* ifa_maybe */
1337 				IFA_UNLOCK(ifa);
1338 				if (ifa_maybe != NULL) {
1339 					IFA_REMREF(ifa_maybe);
1340 				}
1341 				ifa_maybe = ifa;
1342 			} else {
1343 				IFA_UNLOCK(ifa);
1344 			}
1345 			IFA_LOCK_ASSERT_NOTHELD(ifa);
1346 		}
1347 		ifnet_lock_done(ifp);
1348 
1349 		if (ifa != NULL) {
1350 			break;
1351 		}
1352 	}
1353 	ifnet_head_done();
1354 
1355 	if (ifa == NULL) {
1356 		ifa = ifa_maybe;
1357 	} else if (ifa_maybe != NULL) {
1358 		IFA_REMREF(ifa_maybe);
1359 	}
1360 
1361 	return ifa;
1362 }
1363 
1364 /*
1365  * Find an interface address specific to an interface best matching
1366  * a given address applying same source address selection rules
1367  * as done in the kernel for implicit source address binding
1368  */
1369 struct ifaddr *
ifaof_ifpforaddr_select(const struct sockaddr * addr,struct ifnet * ifp)1370 ifaof_ifpforaddr_select(const struct sockaddr *addr, struct ifnet *ifp)
1371 {
1372 	u_int af = addr->sa_family;
1373 
1374 	if (af == AF_INET6) {
1375 		return in6_selectsrc_core_ifa(__DECONST(struct sockaddr_in6 *, addr), ifp, 0);
1376 	}
1377 
1378 	return ifaof_ifpforaddr(addr, ifp);
1379 }
1380 
1381 /*
1382  * Find an interface address specific to an interface best matching
1383  * a given address without regards to source address selection.
1384  *
1385  * This is appropriate for use-cases where we just want to update/init
1386  * some data structure like routing table entries.
1387  */
1388 struct ifaddr *
ifaof_ifpforaddr(const struct sockaddr * addr,struct ifnet * ifp)1389 ifaof_ifpforaddr(const struct sockaddr *addr, struct ifnet *ifp)
1390 {
1391 	struct ifaddr *ifa = NULL;
1392 	const char *cp, *cp2, *cp3;
1393 	char *cplim;
1394 	struct ifaddr *ifa_maybe = NULL;
1395 	struct ifaddr *better_ifa_maybe = NULL;
1396 	u_int af = addr->sa_family;
1397 
1398 	if (af >= AF_MAX) {
1399 		return NULL;
1400 	}
1401 
1402 	ifnet_lock_shared(ifp);
1403 	for (ifa = ifp->if_addrhead.tqh_first; ifa;
1404 	    ifa = ifa->ifa_link.tqe_next) {
1405 		IFA_LOCK(ifa);
1406 		if (ifa->ifa_addr->sa_family != af) {
1407 			IFA_UNLOCK(ifa);
1408 			continue;
1409 		}
1410 		if (ifa_maybe == NULL) {
1411 			IFA_ADDREF_LOCKED(ifa); /* for ifa_maybe */
1412 			ifa_maybe = ifa;
1413 		}
1414 		if (ifa->ifa_netmask == 0) {
1415 			if (sa_equal(addr, ifa->ifa_addr) ||
1416 			    sa_equal(addr, ifa->ifa_dstaddr)) {
1417 				IFA_ADDREF_LOCKED(ifa); /* for caller */
1418 				IFA_UNLOCK(ifa);
1419 				break;
1420 			}
1421 			IFA_UNLOCK(ifa);
1422 			continue;
1423 		}
1424 		if (ifp->if_flags & IFF_POINTOPOINT) {
1425 			if (sa_equal(addr, ifa->ifa_dstaddr)) {
1426 				IFA_ADDREF_LOCKED(ifa); /* for caller */
1427 				IFA_UNLOCK(ifa);
1428 				break;
1429 			}
1430 		} else {
1431 			if (sa_equal(addr, ifa->ifa_addr)) {
1432 				/* exact match */
1433 				IFA_ADDREF_LOCKED(ifa); /* for caller */
1434 				IFA_UNLOCK(ifa);
1435 				break;
1436 			}
1437 			cp = addr->sa_data;
1438 			cp2 = ifa->ifa_addr->sa_data;
1439 			cp3 = ifa->ifa_netmask->sa_data;
1440 			cplim = ifa->ifa_netmask->sa_len +
1441 			    (char *)ifa->ifa_netmask;
1442 			for (; cp3 < cplim; cp3++) {
1443 				if ((*cp++ ^ *cp2++) & *cp3) {
1444 					break;
1445 				}
1446 			}
1447 			if (cp3 == cplim) {
1448 				/* subnet match */
1449 				if (better_ifa_maybe == NULL) {
1450 					/* for better_ifa_maybe */
1451 					IFA_ADDREF_LOCKED(ifa);
1452 					better_ifa_maybe = ifa;
1453 				}
1454 			}
1455 		}
1456 		IFA_UNLOCK(ifa);
1457 	}
1458 
1459 	if (ifa == NULL) {
1460 		if (better_ifa_maybe != NULL) {
1461 			ifa = better_ifa_maybe;
1462 			better_ifa_maybe = NULL;
1463 		} else {
1464 			ifa = ifa_maybe;
1465 			ifa_maybe = NULL;
1466 		}
1467 	}
1468 
1469 	ifnet_lock_done(ifp);
1470 
1471 	if (better_ifa_maybe != NULL) {
1472 		IFA_REMREF(better_ifa_maybe);
1473 	}
1474 	if (ifa_maybe != NULL) {
1475 		IFA_REMREF(ifa_maybe);
1476 	}
1477 
1478 	return ifa;
1479 }
1480 
1481 #include <net/route.h>
1482 
1483 /*
1484  * Default action when installing a route with a Link Level gateway.
1485  * Lookup an appropriate real ifa to point to.
1486  * This should be moved to /sys/net/link.c eventually.
1487  */
1488 void
link_rtrequest(int cmd,struct rtentry * rt,struct sockaddr * sa)1489 link_rtrequest(int cmd, struct rtentry *rt, struct sockaddr *sa)
1490 {
1491 	struct ifaddr *ifa;
1492 	struct sockaddr *dst;
1493 	struct ifnet *ifp;
1494 	void (*ifa_rtrequest)(int, struct rtentry *, struct sockaddr *);
1495 
1496 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1497 	RT_LOCK_ASSERT_HELD(rt);
1498 
1499 	if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == 0) ||
1500 	    ((ifp = ifa->ifa_ifp) == 0) || ((dst = rt_key(rt)) == 0)) {
1501 		return;
1502 	}
1503 
1504 	/* Become a regular mutex, just in case */
1505 	RT_CONVERT_LOCK(rt);
1506 
1507 	ifa = ifaof_ifpforaddr(dst, ifp);
1508 	if (ifa) {
1509 		rtsetifa(rt, ifa);
1510 		IFA_LOCK_SPIN(ifa);
1511 		ifa_rtrequest = ifa->ifa_rtrequest;
1512 		IFA_UNLOCK(ifa);
1513 		if (ifa_rtrequest != NULL && ifa_rtrequest != link_rtrequest) {
1514 			ifa_rtrequest(cmd, rt, sa);
1515 		}
1516 		IFA_REMREF(ifa);
1517 	}
1518 }
1519 
1520 /*
1521  * if_updown will set the interface up or down. It will
1522  * prevent other up/down events from occurring until this
1523  * up/down event has completed.
1524  *
1525  * Caller must lock ifnet. This function will drop the
1526  * lock. This allows ifnet_set_flags to set the rest of
1527  * the flags after we change the up/down state without
1528  * dropping the interface lock between setting the
1529  * up/down state and updating the rest of the flags.
1530  */
1531 __private_extern__ void
if_updown(struct ifnet * ifp,int up)1532 if_updown(struct ifnet *ifp, int up)
1533 {
1534 	u_int32_t eflags;
1535 	int i;
1536 	struct ifaddr **ifa;
1537 	struct timespec tv;
1538 	struct ifclassq *ifq;
1539 
1540 	/* Wait until no one else is changing the up/down state */
1541 	while ((ifp->if_eflags & IFEF_UPDOWNCHANGE) != 0) {
1542 		tv.tv_sec = 0;
1543 		tv.tv_nsec = NSEC_PER_SEC / 10;
1544 		ifnet_lock_done(ifp);
1545 		msleep(&ifp->if_eflags, NULL, 0, "if_updown", &tv);
1546 		ifnet_lock_exclusive(ifp);
1547 	}
1548 
1549 	/* Verify that the interface isn't already in the right state */
1550 	if ((!up && (ifp->if_flags & IFF_UP) == 0) ||
1551 	    (up && (ifp->if_flags & IFF_UP) == IFF_UP)) {
1552 		return;
1553 	}
1554 
1555 	/* Indicate that the up/down state is changing */
1556 	eflags = if_set_eflags(ifp, IFEF_UPDOWNCHANGE);
1557 	ASSERT((eflags & IFEF_UPDOWNCHANGE) == 0);
1558 
1559 	/* Mark interface up or down */
1560 	if (up) {
1561 		ifp->if_flags |= IFF_UP;
1562 	} else {
1563 		ifp->if_flags &= ~IFF_UP;
1564 	}
1565 
1566 	if (!ifnet_is_attached(ifp, 1)) {
1567 		/*
1568 		 * The interface is not attached or is detaching, so
1569 		 * skip modifying any other state.
1570 		 */
1571 		os_log(OS_LOG_DEFAULT, "%s: %s is not attached",
1572 		    __func__, if_name(ifp));
1573 	} else {
1574 		/* Drop the lock to notify addresses and route */
1575 		ifnet_lock_done(ifp);
1576 
1577 		/* Inform all transmit queues about the new link state */
1578 		ifq = ifp->if_snd;
1579 		ASSERT(ifq != NULL);
1580 		IFCQ_LOCK(ifq);
1581 		if_qflush_snd(ifp, true);
1582 		ifnet_update_sndq(ifq,
1583 		    up ? CLASSQ_EV_LINK_UP : CLASSQ_EV_LINK_DOWN);
1584 		IFCQ_UNLOCK(ifq);
1585 
1586 		/* Inform protocols of changed interface state */
1587 		if (ifnet_get_address_list(ifp, &ifa) == 0) {
1588 			for (i = 0; ifa[i] != 0; i++) {
1589 				pfctlinput(up ? PRC_IFUP : PRC_IFDOWN,
1590 				    ifa[i]->ifa_addr);
1591 			}
1592 			ifnet_free_address_list(ifa);
1593 		}
1594 		rt_ifmsg(ifp);
1595 
1596 		ifnet_lock_exclusive(ifp);
1597 		ifnet_touch_lastchange(ifp);
1598 		ifnet_touch_lastupdown(ifp);
1599 		ifnet_decr_iorefcnt(ifp);
1600 	}
1601 	if_clear_eflags(ifp, IFEF_UPDOWNCHANGE);
1602 	wakeup(&ifp->if_eflags);
1603 }
1604 
1605 /*
1606  * Mark an interface down and notify protocols of
1607  * the transition.
1608  */
1609 void
if_down(struct ifnet * ifp)1610 if_down(
1611 	struct ifnet *ifp)
1612 {
1613 	ifnet_lock_exclusive(ifp);
1614 	if_updown(ifp, 0);
1615 	ifnet_lock_done(ifp);
1616 }
1617 
1618 /*
1619  * Mark an interface up and notify protocols of
1620  * the transition.
1621  */
1622 void
if_up(struct ifnet * ifp)1623 if_up(
1624 	struct ifnet *ifp)
1625 {
1626 	ifnet_lock_exclusive(ifp);
1627 	if_updown(ifp, 1);
1628 	ifnet_lock_done(ifp);
1629 }
1630 
1631 /*
1632  * Flush an interface queue.
1633  */
1634 void
if_qflush(struct ifnet * ifp,struct ifclassq * ifq,bool ifq_locked)1635 if_qflush(struct ifnet *ifp, struct ifclassq *ifq, bool ifq_locked)
1636 {
1637 	lck_mtx_lock(&ifp->if_ref_lock);
1638 	if ((ifp->if_refflags & IFRF_ATTACH_MASK) == 0) {
1639 		lck_mtx_unlock(&ifp->if_ref_lock);
1640 		return;
1641 	}
1642 	VERIFY(ifq != NULL);
1643 	ifclassq_retain(ifq);
1644 	lck_mtx_unlock(&ifp->if_ref_lock);
1645 
1646 	if (!ifq_locked) {
1647 		IFCQ_LOCK(ifq);
1648 	}
1649 
1650 	if (IFCQ_IS_ENABLED(ifq)) {
1651 		fq_if_request_classq(ifq, CLASSQRQ_PURGE, NULL);
1652 	}
1653 
1654 	VERIFY(IFCQ_IS_EMPTY(ifq));
1655 
1656 	if (!ifq_locked) {
1657 		IFCQ_UNLOCK(ifq);
1658 	}
1659 	ifclassq_release(&ifq);
1660 }
1661 
1662 void
if_qflush_snd(struct ifnet * ifp,bool ifq_locked)1663 if_qflush_snd(struct ifnet *ifp, bool ifq_locked)
1664 {
1665 	if_qflush(ifp, ifp->if_snd, ifq_locked);
1666 }
1667 
1668 void
if_qflush_sc(struct ifnet * ifp,mbuf_svc_class_t sc,u_int32_t flow,u_int32_t * packets,u_int32_t * bytes,int ifq_locked)1669 if_qflush_sc(struct ifnet *ifp, mbuf_svc_class_t sc, u_int32_t flow,
1670     u_int32_t *packets, u_int32_t *bytes, int ifq_locked)
1671 {
1672 	struct ifclassq *ifq;
1673 	u_int32_t cnt = 0, len = 0;
1674 
1675 	if ((ifp->if_refflags & IFRF_ATTACH_MASK) == 0) {
1676 		return;
1677 	}
1678 	ifq = ifp->if_snd;
1679 	VERIFY(ifq != NULL);
1680 	VERIFY(sc == MBUF_SC_UNSPEC || MBUF_VALID_SC(sc));
1681 	VERIFY(flow != 0);
1682 
1683 	if (!ifq_locked) {
1684 		IFCQ_LOCK(ifq);
1685 	}
1686 
1687 	if (IFCQ_IS_ENABLED(ifq)) {
1688 		cqrq_purge_sc_t req = { sc, flow, 0, 0 };
1689 
1690 		fq_if_request_classq(ifq, CLASSQRQ_PURGE_SC, &req);
1691 		cnt = req.packets;
1692 		len = req.bytes;
1693 	}
1694 
1695 	if (!ifq_locked) {
1696 		IFCQ_UNLOCK(ifq);
1697 	}
1698 
1699 	if (packets != NULL) {
1700 		*packets = cnt;
1701 	}
1702 	if (bytes != NULL) {
1703 		*bytes = len;
1704 	}
1705 }
1706 
1707 /*
1708  * Extracts interface unit number and name from string, returns -1 upon failure.
1709  * Upon success, returns extracted unit number, and interface name in dst.
1710  */
1711 int
ifunit_extract(const char * src,char * dst,size_t dstlen,int * unit)1712 ifunit_extract(const char *src, char *dst, size_t dstlen, int *unit)
1713 {
1714 	const char *cp;
1715 	size_t len, m;
1716 	char c;
1717 	int u;
1718 
1719 	if (src == NULL || dst == NULL || dstlen == 0 || unit == NULL) {
1720 		return -1;
1721 	}
1722 
1723 	len = strlen(src);
1724 	if (len < 2 || len > dstlen) {
1725 		return -1;
1726 	}
1727 	cp = src + len - 1;
1728 	c = *cp;
1729 	if (c < '0' || c > '9') {
1730 		return -1;            /* trailing garbage */
1731 	}
1732 	u = 0;
1733 	m = 1;
1734 	do {
1735 		if (cp == src) {
1736 			return -1;    /* no interface name */
1737 		}
1738 		u += (c - '0') * m;
1739 		if (u > 1000000) {
1740 			return -1;    /* number is unreasonable */
1741 		}
1742 		m *= 10;
1743 		c = *--cp;
1744 	} while (c >= '0' && c <= '9');
1745 	len = cp - src + 1;
1746 	bcopy(src, dst, len);
1747 	dst[len] = '\0';
1748 	*unit = u;
1749 
1750 	return 0;
1751 }
1752 
1753 /*
1754  * Map interface name to
1755  * interface structure pointer.
1756  */
1757 static struct ifnet *
ifunit_common(const char * name,boolean_t hold)1758 ifunit_common(const char *name, boolean_t hold)
1759 {
1760 	char namebuf[IFNAMSIZ + 1];
1761 	struct ifnet *ifp;
1762 	int unit;
1763 
1764 	if (ifunit_extract(name, namebuf, sizeof(namebuf), &unit) < 0) {
1765 		return NULL;
1766 	}
1767 
1768 	/* for safety, since we use strcmp() below */
1769 	namebuf[sizeof(namebuf) - 1] = '\0';
1770 
1771 	/*
1772 	 * Now search all the interfaces for this name/number
1773 	 */
1774 	ifnet_head_lock_shared();
1775 	TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
1776 		/*
1777 		 * Use strcmp() rather than strncmp() here,
1778 		 * since we want to match the entire string.
1779 		 */
1780 		if (strcmp(ifp->if_name, namebuf)) {
1781 			continue;
1782 		}
1783 		if (unit == ifp->if_unit) {
1784 			break;
1785 		}
1786 	}
1787 
1788 	/* if called from ifunit_ref() and ifnet is not attached, bail */
1789 	if (hold && ifp != NULL && !ifnet_is_attached(ifp, 1)) {
1790 		ifp = NULL;
1791 	}
1792 
1793 	ifnet_head_done();
1794 	return ifp;
1795 }
1796 
1797 struct ifnet *
ifunit(const char * name)1798 ifunit(const char *name)
1799 {
1800 	return ifunit_common(name, FALSE);
1801 }
1802 
1803 /*
1804  * Similar to ifunit(), except that we hold an I/O reference count on an
1805  * attached interface, which must later be released via ifnet_decr_iorefcnt().
1806  * Will return NULL unless interface exists and is fully attached.
1807  */
1808 struct ifnet *
ifunit_ref(const char * name)1809 ifunit_ref(const char *name)
1810 {
1811 	return ifunit_common(name, TRUE);
1812 }
1813 
1814 /*
1815  * Map interface name in a sockaddr_dl to
1816  * interface structure pointer.
1817  */
1818 struct ifnet *
if_withname(struct sockaddr * sa)1819 if_withname(struct sockaddr *sa)
1820 {
1821 	char ifname[IFNAMSIZ + 1];
1822 	struct sockaddr_dl *sdl = (struct sockaddr_dl *)(void *)sa;
1823 
1824 	if ((sa->sa_family != AF_LINK) || (sdl->sdl_nlen == 0) ||
1825 	    (sdl->sdl_nlen > IFNAMSIZ)) {
1826 		return NULL;
1827 	}
1828 
1829 	/*
1830 	 * ifunit wants a null-terminated name.  It may not be null-terminated
1831 	 * in the sockaddr.  We don't want to change the caller's sockaddr,
1832 	 * and there might not be room to put the trailing null anyway, so we
1833 	 * make a local copy that we know we can null terminate safely.
1834 	 */
1835 
1836 	bcopy(sdl->sdl_data, ifname, sdl->sdl_nlen);
1837 	ifname[sdl->sdl_nlen] = '\0';
1838 	return ifunit(ifname);
1839 }
1840 
1841 static __attribute__((noinline)) int
ifioctl_ifconf(u_long cmd,caddr_t data)1842 ifioctl_ifconf(u_long cmd, caddr_t data)
1843 {
1844 	int error = 0;
1845 
1846 	switch (cmd) {
1847 	case OSIOCGIFCONF32:                    /* struct ifconf32 */
1848 	case SIOCGIFCONF32: {                   /* struct ifconf32 */
1849 		struct ifconf32 ifc;
1850 		bcopy(data, &ifc, sizeof(ifc));
1851 		error = ifconf(cmd, CAST_USER_ADDR_T(ifc.ifc_req),
1852 		    &ifc.ifc_len);
1853 		bcopy(&ifc, data, sizeof(ifc));
1854 		break;
1855 	}
1856 
1857 	case SIOCGIFCONF64:                     /* struct ifconf64 */
1858 	case OSIOCGIFCONF64: {                  /* struct ifconf64 */
1859 		struct ifconf64 ifc;
1860 		bcopy(data, &ifc, sizeof(ifc));
1861 		error = ifconf(cmd, CAST_USER_ADDR_T(ifc.ifc_req), &ifc.ifc_len);
1862 		bcopy(&ifc, data, sizeof(ifc));
1863 		break;
1864 	}
1865 
1866 	default:
1867 		VERIFY(0);
1868 		/* NOTREACHED */
1869 	}
1870 
1871 	return error;
1872 }
1873 
1874 static __attribute__((noinline)) int
ifioctl_ifclone(u_long cmd,caddr_t data)1875 ifioctl_ifclone(u_long cmd, caddr_t data)
1876 {
1877 	int error = 0;
1878 
1879 	switch (cmd) {
1880 	case SIOCIFGCLONERS32: {                /* struct if_clonereq32 */
1881 		struct if_clonereq32 ifcr;
1882 		bcopy(data, &ifcr, sizeof(ifcr));
1883 		error = if_clone_list(ifcr.ifcr_count, &ifcr.ifcr_total,
1884 		    CAST_USER_ADDR_T(ifcr.ifcru_buffer));
1885 		bcopy(&ifcr, data, sizeof(ifcr));
1886 		break;
1887 	}
1888 
1889 	case SIOCIFGCLONERS64: {                /* struct if_clonereq64 */
1890 		struct if_clonereq64 ifcr;
1891 		bcopy(data, &ifcr, sizeof(ifcr));
1892 		error = if_clone_list(ifcr.ifcr_count, &ifcr.ifcr_total,
1893 		    CAST_USER_ADDR_T(ifcr.ifcru_buffer));
1894 		bcopy(&ifcr, data, sizeof(ifcr));
1895 		break;
1896 	}
1897 
1898 	default:
1899 		VERIFY(0);
1900 		/* NOTREACHED */
1901 	}
1902 
1903 	return error;
1904 }
1905 
1906 static __attribute__((noinline)) int
ifioctl_ifdesc(struct ifnet * ifp,u_long cmd,caddr_t data,struct proc * p)1907 ifioctl_ifdesc(struct ifnet *ifp, u_long cmd, caddr_t data, struct proc *p)
1908 {
1909 	struct if_descreq *ifdr = (struct if_descreq *)(void *)data;
1910 	u_int32_t ifdr_len;
1911 	int error = 0;
1912 
1913 	VERIFY(ifp != NULL);
1914 
1915 	switch (cmd) {
1916 	case SIOCSIFDESC: {                     /* struct if_descreq */
1917 		if ((error = proc_suser(p)) != 0) {
1918 			break;
1919 		}
1920 
1921 		ifnet_lock_exclusive(ifp);
1922 		bcopy(&ifdr->ifdr_len, &ifdr_len, sizeof(ifdr_len));
1923 		if (ifdr_len > sizeof(ifdr->ifdr_desc) ||
1924 		    ifdr_len > ifp->if_desc.ifd_maxlen) {
1925 			error = EINVAL;
1926 			ifnet_lock_done(ifp);
1927 			break;
1928 		}
1929 
1930 		bzero(ifp->if_desc.ifd_desc, ifp->if_desc.ifd_maxlen);
1931 		if ((ifp->if_desc.ifd_len = ifdr_len) > 0) {
1932 			bcopy(ifdr->ifdr_desc, ifp->if_desc.ifd_desc,
1933 			    MIN(ifdr_len, ifp->if_desc.ifd_maxlen));
1934 		}
1935 		ifnet_lock_done(ifp);
1936 		break;
1937 	}
1938 
1939 	case SIOCGIFDESC: {                     /* struct if_descreq */
1940 		ifnet_lock_shared(ifp);
1941 		ifdr_len = MIN(ifp->if_desc.ifd_len, sizeof(ifdr->ifdr_desc));
1942 		bcopy(&ifdr_len, &ifdr->ifdr_len, sizeof(ifdr_len));
1943 		bzero(&ifdr->ifdr_desc, sizeof(ifdr->ifdr_desc));
1944 		if (ifdr_len > 0) {
1945 			bcopy(ifp->if_desc.ifd_desc, ifdr->ifdr_desc, ifdr_len);
1946 		}
1947 		ifnet_lock_done(ifp);
1948 		break;
1949 	}
1950 
1951 	default:
1952 		VERIFY(0);
1953 		/* NOTREACHED */
1954 	}
1955 
1956 	return error;
1957 }
1958 
1959 static __attribute__((noinline)) int
ifioctl_linkparams(struct ifnet * ifp,u_long cmd,caddr_t data,struct proc * p)1960 ifioctl_linkparams(struct ifnet *ifp, u_long cmd, caddr_t data, struct proc *p)
1961 {
1962 	struct if_linkparamsreq *iflpr =
1963 	    (struct if_linkparamsreq *)(void *)data;
1964 	struct ifclassq *ifq;
1965 	int error = 0;
1966 
1967 	VERIFY(ifp != NULL);
1968 	ifq = ifp->if_snd;
1969 
1970 	ASSERT(ifq != NULL);
1971 	switch (cmd) {
1972 	case SIOCSIFLINKPARAMS: {               /* struct if_linkparamsreq */
1973 		struct tb_profile tb = { .rate = 0, .percent = 0, .depth = 0 };
1974 
1975 		if ((error = proc_suser(p)) != 0) {
1976 			break;
1977 		}
1978 
1979 #if SKYWALK
1980 		error = kern_nexus_set_netif_input_tbr_rate(ifp,
1981 		    iflpr->iflpr_input_tbr_rate);
1982 		if (error != 0) {
1983 			break;
1984 		}
1985 
1986 		/*
1987 		 * Input netem is done at flowswitch, which is the entry point
1988 		 * of all traffic, when skywalk is enabled.
1989 		 */
1990 		error = kern_nexus_set_if_netem_params(
1991 			kern_nexus_shared_controller(),
1992 			ifp->if_nx_flowswitch.if_fsw_instance,
1993 			&iflpr->iflpr_input_netem,
1994 			sizeof(iflpr->iflpr_input_netem));
1995 		if (error != 0) {
1996 			break;
1997 		}
1998 #endif /* SKYWALK */
1999 
2000 		char netem_name[32];
2001 		(void) snprintf(netem_name, sizeof(netem_name),
2002 		    "if_output_netem_%s", if_name(ifp));
2003 		error = netem_config(&ifp->if_output_netem, netem_name, ifp,
2004 		    &iflpr->iflpr_output_netem, (void *)ifp,
2005 		    ifnet_enqueue_netem, NETEM_MAX_BATCH_SIZE);
2006 		if (error != 0) {
2007 			break;
2008 		}
2009 
2010 		IFCQ_LOCK(ifq);
2011 		if (!IFCQ_IS_READY(ifq)) {
2012 			error = ENXIO;
2013 			IFCQ_UNLOCK(ifq);
2014 			break;
2015 		}
2016 		bcopy(&iflpr->iflpr_output_tbr_rate, &tb.rate,
2017 		    sizeof(tb.rate));
2018 		bcopy(&iflpr->iflpr_output_tbr_percent, &tb.percent,
2019 		    sizeof(tb.percent));
2020 		error = ifclassq_tbr_set(ifq, &tb, TRUE);
2021 		IFCQ_UNLOCK(ifq);
2022 		break;
2023 	}
2024 
2025 	case SIOCGIFLINKPARAMS: {               /* struct if_linkparamsreq */
2026 		u_int32_t sched_type = PKTSCHEDT_NONE, flags = 0;
2027 		u_int64_t tbr_bw = 0, tbr_pct = 0;
2028 
2029 		IFCQ_LOCK(ifq);
2030 
2031 		if (IFCQ_IS_ENABLED(ifq)) {
2032 			sched_type = ifq->ifcq_type;
2033 		}
2034 
2035 		bcopy(&sched_type, &iflpr->iflpr_output_sched,
2036 		    sizeof(iflpr->iflpr_output_sched));
2037 
2038 		if (IFCQ_TBR_IS_ENABLED(ifq)) {
2039 			tbr_bw = ifq->ifcq_tbr.tbr_rate_raw;
2040 			tbr_pct = ifq->ifcq_tbr.tbr_percent;
2041 		}
2042 		bcopy(&tbr_bw, &iflpr->iflpr_output_tbr_rate,
2043 		    sizeof(iflpr->iflpr_output_tbr_rate));
2044 		bcopy(&tbr_pct, &iflpr->iflpr_output_tbr_percent,
2045 		    sizeof(iflpr->iflpr_output_tbr_percent));
2046 		IFCQ_UNLOCK(ifq);
2047 
2048 		if (ifp->if_output_sched_model ==
2049 		    IFNET_SCHED_MODEL_DRIVER_MANAGED) {
2050 			flags |= IFLPRF_DRVMANAGED;
2051 		}
2052 		bcopy(&flags, &iflpr->iflpr_flags, sizeof(iflpr->iflpr_flags));
2053 		bcopy(&ifp->if_output_bw, &iflpr->iflpr_output_bw,
2054 		    sizeof(iflpr->iflpr_output_bw));
2055 		bcopy(&ifp->if_input_bw, &iflpr->iflpr_input_bw,
2056 		    sizeof(iflpr->iflpr_input_bw));
2057 		bcopy(&ifp->if_output_lt, &iflpr->iflpr_output_lt,
2058 		    sizeof(iflpr->iflpr_output_lt));
2059 		bcopy(&ifp->if_input_lt, &iflpr->iflpr_input_lt,
2060 		    sizeof(iflpr->iflpr_input_lt));
2061 
2062 #if SKYWALK
2063 		if (ifp->if_input_netem != NULL) {
2064 			netem_get_params(ifp->if_input_netem,
2065 			    &iflpr->iflpr_input_netem);
2066 		}
2067 #endif /* SKYWALK */
2068 		if (ifp->if_output_netem != NULL) {
2069 			netem_get_params(ifp->if_output_netem,
2070 			    &iflpr->iflpr_output_netem);
2071 		}
2072 
2073 		break;
2074 	}
2075 
2076 	default:
2077 		VERIFY(0);
2078 		/* NOTREACHED */
2079 	}
2080 
2081 	return error;
2082 }
2083 
2084 static __attribute__((noinline)) int
ifioctl_qstats(struct ifnet * ifp,u_long cmd,caddr_t data)2085 ifioctl_qstats(struct ifnet *ifp, u_long cmd, caddr_t data)
2086 {
2087 	struct if_qstatsreq *ifqr = (struct if_qstatsreq *)(void *)data;
2088 	u_int32_t ifqr_len, ifqr_slot;
2089 	uint32_t ifqr_grp_idx = 0;
2090 	int error = 0;
2091 
2092 	VERIFY(ifp != NULL);
2093 
2094 	switch (cmd) {
2095 	case SIOCGIFQUEUESTATS: {               /* struct if_qstatsreq */
2096 		bcopy(&ifqr->ifqr_slot, &ifqr_slot, sizeof(ifqr_slot));
2097 		bcopy(&ifqr->ifqr_grp_idx, &ifqr_grp_idx, sizeof(ifqr_grp_idx));
2098 		bcopy(&ifqr->ifqr_len, &ifqr_len, sizeof(ifqr_len));
2099 
2100 		if (ifqr_grp_idx > FQ_IF_MAX_GROUPS) {
2101 			return EINVAL;
2102 		}
2103 		error = ifclassq_getqstats(ifp->if_snd, (uint8_t)ifqr_grp_idx,
2104 		    ifqr_slot, ifqr->ifqr_buf, &ifqr_len);
2105 		if (error != 0) {
2106 			ifqr_len = 0;
2107 		}
2108 		bcopy(&ifqr_len, &ifqr->ifqr_len, sizeof(ifqr_len));
2109 		break;
2110 	}
2111 
2112 	default:
2113 		VERIFY(0);
2114 		/* NOTREACHED */
2115 	}
2116 
2117 	return error;
2118 }
2119 
2120 static __attribute__((noinline)) int
ifioctl_throttle(struct ifnet * ifp,u_long cmd,caddr_t data,struct proc * p)2121 ifioctl_throttle(struct ifnet *ifp, u_long cmd, caddr_t data, struct proc *p)
2122 {
2123 	struct if_throttlereq *ifthr = (struct if_throttlereq *)(void *)data;
2124 	u_int32_t ifthr_level;
2125 	int error = 0;
2126 
2127 	VERIFY(ifp != NULL);
2128 
2129 	switch (cmd) {
2130 	case SIOCSIFTHROTTLE: {                 /* struct if_throttlereq */
2131 		/*
2132 		 * XXX: Use priv_check_cred() instead of root check?
2133 		 */
2134 		if ((error = proc_suser(p)) != 0) {
2135 			break;
2136 		}
2137 
2138 		bcopy(&ifthr->ifthr_level, &ifthr_level, sizeof(ifthr_level));
2139 		error = ifnet_set_throttle(ifp, ifthr_level);
2140 		if (error == EALREADY) {
2141 			error = 0;
2142 		}
2143 		break;
2144 	}
2145 
2146 	case SIOCGIFTHROTTLE: {                 /* struct if_throttlereq */
2147 		if ((error = ifnet_get_throttle(ifp, &ifthr_level)) == 0) {
2148 			bcopy(&ifthr_level, &ifthr->ifthr_level,
2149 			    sizeof(ifthr_level));
2150 		}
2151 		break;
2152 	}
2153 
2154 	default:
2155 		VERIFY(0);
2156 		/* NOTREACHED */
2157 	}
2158 
2159 	return error;
2160 }
2161 
2162 static int
ifioctl_getnetagents(struct ifnet * ifp,u_int32_t * count,user_addr_t uuid_p)2163 ifioctl_getnetagents(struct ifnet *ifp, u_int32_t *count, user_addr_t uuid_p)
2164 {
2165 	int error = 0;
2166 	u_int32_t index = 0;
2167 	u_int32_t valid_netagent_count = 0;
2168 	*count = 0;
2169 
2170 	ifnet_lock_assert(ifp, IFNET_LCK_ASSERT_SHARED);
2171 
2172 	if (ifp->if_agentids != NULL) {
2173 		for (index = 0; index < ifp->if_agentcount; index++) {
2174 			uuid_t *netagent_uuid = &(ifp->if_agentids[index]);
2175 			if (!uuid_is_null(*netagent_uuid)) {
2176 				if (uuid_p != USER_ADDR_NULL) {
2177 					error = copyout(netagent_uuid,
2178 					    uuid_p + sizeof(uuid_t) * valid_netagent_count,
2179 					    sizeof(uuid_t));
2180 					if (error != 0) {
2181 						return error;
2182 					}
2183 				}
2184 				valid_netagent_count++;
2185 			}
2186 		}
2187 	}
2188 	*count = valid_netagent_count;
2189 
2190 	return 0;
2191 }
2192 
2193 #define IF_MAXAGENTS            64
2194 #define IF_AGENT_INCREMENT      8
2195 int
if_add_netagent_locked(struct ifnet * ifp,uuid_t new_agent_uuid)2196 if_add_netagent_locked(struct ifnet *ifp, uuid_t new_agent_uuid)
2197 {
2198 	VERIFY(ifp != NULL);
2199 
2200 	uuid_t *first_empty_slot = NULL;
2201 	u_int32_t index = 0;
2202 	bool already_added = FALSE;
2203 
2204 	if (ifp->if_agentids != NULL) {
2205 		for (index = 0; index < ifp->if_agentcount; index++) {
2206 			uuid_t *netagent_uuid = &(ifp->if_agentids[index]);
2207 			if (uuid_compare(*netagent_uuid, new_agent_uuid) == 0) {
2208 				/* Already present, ignore */
2209 				already_added = TRUE;
2210 				break;
2211 			}
2212 			if (first_empty_slot == NULL &&
2213 			    uuid_is_null(*netagent_uuid)) {
2214 				first_empty_slot = netagent_uuid;
2215 			}
2216 		}
2217 	}
2218 	if (already_added) {
2219 		/* Already added agent, don't return an error */
2220 		return 0;
2221 	}
2222 	if (first_empty_slot == NULL) {
2223 		if (ifp->if_agentcount >= IF_MAXAGENTS) {
2224 			/* No room for another netagent UUID, bail */
2225 			return ENOMEM;
2226 		} else {
2227 			/* Calculate new array size */
2228 			u_int32_t new_agent_count =
2229 			    MIN(ifp->if_agentcount + IF_AGENT_INCREMENT,
2230 			    IF_MAXAGENTS);
2231 
2232 			/* Reallocate array */
2233 			uuid_t *new_agent_array = krealloc_data(ifp->if_agentids,
2234 			    sizeof(uuid_t) * ifp->if_agentcount,
2235 			    sizeof(uuid_t) * new_agent_count,
2236 			    Z_WAITOK | Z_ZERO);
2237 			if (new_agent_array == NULL) {
2238 				return ENOMEM;
2239 			}
2240 
2241 			/* Save new array */
2242 			ifp->if_agentids = new_agent_array;
2243 
2244 			/* Set first empty slot */
2245 			first_empty_slot =
2246 			    &(ifp->if_agentids[ifp->if_agentcount]);
2247 
2248 			/* Save new array length */
2249 			ifp->if_agentcount = new_agent_count;
2250 		}
2251 	}
2252 	uuid_copy(*first_empty_slot, new_agent_uuid);
2253 	netagent_post_updated_interfaces(new_agent_uuid);
2254 	return 0;
2255 }
2256 
2257 int
if_add_netagent(struct ifnet * ifp,uuid_t new_agent_uuid)2258 if_add_netagent(struct ifnet *ifp, uuid_t new_agent_uuid)
2259 {
2260 	VERIFY(ifp != NULL);
2261 
2262 	ifnet_lock_exclusive(ifp);
2263 
2264 	int error = if_add_netagent_locked(ifp, new_agent_uuid);
2265 
2266 	ifnet_lock_done(ifp);
2267 
2268 	return error;
2269 }
2270 
2271 static int
if_delete_netagent_locked(struct ifnet * ifp,uuid_t remove_agent_uuid)2272 if_delete_netagent_locked(struct ifnet *ifp, uuid_t remove_agent_uuid)
2273 {
2274 	u_int32_t index = 0;
2275 	bool removed_agent_id = FALSE;
2276 
2277 	if (ifp->if_agentids != NULL) {
2278 		for (index = 0; index < ifp->if_agentcount; index++) {
2279 			uuid_t *netagent_uuid = &(ifp->if_agentids[index]);
2280 			if (uuid_compare(*netagent_uuid,
2281 			    remove_agent_uuid) == 0) {
2282 				uuid_clear(*netagent_uuid);
2283 				removed_agent_id = TRUE;
2284 				break;
2285 			}
2286 		}
2287 	}
2288 	if (removed_agent_id) {
2289 		netagent_post_updated_interfaces(remove_agent_uuid);
2290 	}
2291 
2292 	return 0;
2293 }
2294 
2295 int
if_delete_netagent(struct ifnet * ifp,uuid_t remove_agent_uuid)2296 if_delete_netagent(struct ifnet *ifp, uuid_t remove_agent_uuid)
2297 {
2298 	VERIFY(ifp != NULL);
2299 
2300 	ifnet_lock_exclusive(ifp);
2301 
2302 	int error = if_delete_netagent_locked(ifp, remove_agent_uuid);
2303 
2304 	ifnet_lock_done(ifp);
2305 
2306 	return error;
2307 }
2308 
2309 boolean_t
if_check_netagent(struct ifnet * ifp,uuid_t find_agent_uuid)2310 if_check_netagent(struct ifnet *ifp, uuid_t find_agent_uuid)
2311 {
2312 	boolean_t found = FALSE;
2313 
2314 	if (!ifp || uuid_is_null(find_agent_uuid)) {
2315 		return FALSE;
2316 	}
2317 
2318 	ifnet_lock_shared(ifp);
2319 
2320 	if (ifp->if_agentids != NULL) {
2321 		for (uint32_t index = 0; index < ifp->if_agentcount; index++) {
2322 			if (uuid_compare(ifp->if_agentids[index], find_agent_uuid) == 0) {
2323 				found = TRUE;
2324 				break;
2325 			}
2326 		}
2327 	}
2328 
2329 	ifnet_lock_done(ifp);
2330 
2331 	return found;
2332 }
2333 
2334 static __attribute__((noinline)) int
ifioctl_netagent(struct ifnet * ifp,u_long cmd,caddr_t data,struct proc * p)2335 ifioctl_netagent(struct ifnet *ifp, u_long cmd, caddr_t data, struct proc *p)
2336 {
2337 	struct if_agentidreq *ifar = (struct if_agentidreq *)(void *)data;
2338 	union {
2339 		struct if_agentidsreq32 s32;
2340 		struct if_agentidsreq64 s64;
2341 	} u;
2342 	int error = 0;
2343 
2344 	VERIFY(ifp != NULL);
2345 
2346 	/* Get an io ref count if the interface is attached */
2347 	if (!ifnet_is_attached(ifp, 1)) {
2348 		return EOPNOTSUPP;
2349 	}
2350 
2351 	if (cmd == SIOCAIFAGENTID ||
2352 	    cmd == SIOCDIFAGENTID) {
2353 		ifnet_lock_exclusive(ifp);
2354 	} else {
2355 		ifnet_lock_shared(ifp);
2356 	}
2357 
2358 	switch (cmd) {
2359 	case SIOCAIFAGENTID: {                  /* struct if_agentidreq */
2360 		// TODO: Use priv_check_cred() instead of root check
2361 		if ((error = proc_suser(p)) != 0) {
2362 			break;
2363 		}
2364 		error = if_add_netagent_locked(ifp, ifar->ifar_uuid);
2365 		break;
2366 	}
2367 	case SIOCDIFAGENTID: {                          /* struct if_agentidreq */
2368 		// TODO: Use priv_check_cred() instead of root check
2369 		if ((error = proc_suser(p)) != 0) {
2370 			break;
2371 		}
2372 		error = if_delete_netagent_locked(ifp, ifar->ifar_uuid);
2373 		break;
2374 	}
2375 	case SIOCGIFAGENTIDS32: {               /* struct if_agentidsreq32 */
2376 		bcopy(data, &u.s32, sizeof(u.s32));
2377 		error = ifioctl_getnetagents(ifp, &u.s32.ifar_count,
2378 		    u.s32.ifar_uuids);
2379 		if (error == 0) {
2380 			bcopy(&u.s32, data, sizeof(u.s32));
2381 		}
2382 		break;
2383 	}
2384 	case SIOCGIFAGENTIDS64: {               /* struct if_agentidsreq64 */
2385 		bcopy(data, &u.s64, sizeof(u.s64));
2386 		error = ifioctl_getnetagents(ifp, &u.s64.ifar_count,
2387 		    CAST_USER_ADDR_T(u.s64.ifar_uuids));
2388 		if (error == 0) {
2389 			bcopy(&u.s64, data, sizeof(u.s64));
2390 		}
2391 		break;
2392 	}
2393 	default:
2394 		VERIFY(0);
2395 		/* NOTREACHED */
2396 	}
2397 
2398 	ifnet_lock_done(ifp);
2399 	ifnet_decr_iorefcnt(ifp);
2400 
2401 	return error;
2402 }
2403 
2404 void
ifnet_clear_netagent(uuid_t netagent_uuid)2405 ifnet_clear_netagent(uuid_t netagent_uuid)
2406 {
2407 	struct ifnet *ifp = NULL;
2408 	u_int32_t index = 0;
2409 
2410 	ifnet_head_lock_shared();
2411 
2412 	TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
2413 		ifnet_lock_shared(ifp);
2414 		if (ifp->if_agentids != NULL) {
2415 			for (index = 0; index < ifp->if_agentcount; index++) {
2416 				uuid_t *ifp_netagent_uuid = &(ifp->if_agentids[index]);
2417 				if (uuid_compare(*ifp_netagent_uuid, netagent_uuid) == 0) {
2418 					uuid_clear(*ifp_netagent_uuid);
2419 				}
2420 			}
2421 		}
2422 		ifnet_lock_done(ifp);
2423 	}
2424 
2425 	ifnet_head_done();
2426 }
2427 
2428 void
ifnet_increment_generation(ifnet_t interface)2429 ifnet_increment_generation(ifnet_t interface)
2430 {
2431 	OSIncrementAtomic(&interface->if_generation);
2432 }
2433 
2434 u_int32_t
ifnet_get_generation(ifnet_t interface)2435 ifnet_get_generation(ifnet_t interface)
2436 {
2437 	return interface->if_generation;
2438 }
2439 
2440 void
ifnet_remove_from_ordered_list(struct ifnet * ifp)2441 ifnet_remove_from_ordered_list(struct ifnet *ifp)
2442 {
2443 	ifnet_head_assert_exclusive();
2444 
2445 	// Remove from list
2446 	TAILQ_REMOVE(&ifnet_ordered_head, ifp, if_ordered_link);
2447 	ifp->if_ordered_link.tqe_next = NULL;
2448 	ifp->if_ordered_link.tqe_prev = NULL;
2449 
2450 	// Update ordered count
2451 	VERIFY(if_ordered_count > 0);
2452 	if_ordered_count--;
2453 }
2454 
2455 static int
ifnet_reset_order(u_int32_t * ordered_indices,u_int32_t count)2456 ifnet_reset_order(u_int32_t *ordered_indices, u_int32_t count)
2457 {
2458 	struct ifnet *ifp = NULL;
2459 	int error = 0;
2460 
2461 	if (if_verbose != 0) {
2462 		os_log(OS_LOG_DEFAULT, "%s: count %u", __func__, count);
2463 	}
2464 
2465 	ifnet_head_lock_exclusive();
2466 	for (u_int32_t order_index = 0; order_index < count; order_index++) {
2467 		if (ordered_indices[order_index] == IFSCOPE_NONE ||
2468 		    ordered_indices[order_index] > (uint32_t)if_index) {
2469 			error = EINVAL;
2470 			ifnet_head_done();
2471 			return error;
2472 		}
2473 	}
2474 	// Flush current ordered list
2475 	for (ifp = TAILQ_FIRST(&ifnet_ordered_head); ifp != NULL;
2476 	    ifp = TAILQ_FIRST(&ifnet_ordered_head)) {
2477 		ifnet_lock_exclusive(ifp);
2478 		ifnet_remove_from_ordered_list(ifp);
2479 		ifnet_lock_done(ifp);
2480 	}
2481 
2482 	VERIFY(if_ordered_count == 0);
2483 
2484 	for (u_int32_t order_index = 0; order_index < count; order_index++) {
2485 		u_int32_t interface_index = ordered_indices[order_index];
2486 		ifp = ifindex2ifnet[interface_index];
2487 		if (ifp == NULL) {
2488 			continue;
2489 		}
2490 		ifnet_lock_exclusive(ifp);
2491 		TAILQ_INSERT_TAIL(&ifnet_ordered_head, ifp, if_ordered_link);
2492 		ifnet_lock_done(ifp);
2493 		if_ordered_count++;
2494 	}
2495 
2496 	ifnet_head_done();
2497 
2498 	necp_update_all_clients();
2499 
2500 	return error;
2501 }
2502 
2503 #if (DEBUG || DEVELOPMENT)
2504 static int
ifnet_get_ordered_indices(u_int32_t * ordered_indices,uint32_t * count)2505 ifnet_get_ordered_indices(u_int32_t *ordered_indices, uint32_t *count)
2506 {
2507 	struct ifnet *ifp = NULL;
2508 	int error = 0;
2509 	uint32_t order_index = 0;
2510 
2511 	ifnet_head_lock_exclusive();
2512 
2513 	if (*count < if_ordered_count) {
2514 		ifnet_head_done();
2515 		return ENOBUFS;
2516 	}
2517 
2518 	TAILQ_FOREACH(ifp, &ifnet_ordered_head, if_ordered_link) {
2519 		if (order_index >= if_ordered_count) {
2520 			break;
2521 		}
2522 		ordered_indices[order_index++] = ifp->if_index;
2523 	}
2524 	*count = order_index;
2525 	ifnet_head_done();
2526 
2527 	return error;
2528 }
2529 #endif /* (DEBUG || DEVELOPMENT) */
2530 
2531 int
if_set_qosmarking_mode(struct ifnet * ifp,u_int32_t mode)2532 if_set_qosmarking_mode(struct ifnet *ifp, u_int32_t mode)
2533 {
2534 	int error = 0;
2535 	u_int32_t old_mode = ifp->if_qosmarking_mode;
2536 
2537 	switch (mode) {
2538 	case IFRTYPE_QOSMARKING_MODE_NONE:
2539 		ifp->if_qosmarking_mode = IFRTYPE_QOSMARKING_MODE_NONE;
2540 		break;
2541 	case IFRTYPE_QOSMARKING_FASTLANE:
2542 	case IFRTYPE_QOSMARKING_RFC4594:
2543 		ifp->if_qosmarking_mode = mode;
2544 		break;
2545 #if (DEBUG || DEVELOPMENT)
2546 	case IFRTYPE_QOSMARKING_CUSTOM:
2547 		ifp->if_qosmarking_mode = mode;
2548 		break;
2549 #endif /* (DEBUG || DEVELOPMENT) */
2550 	default:
2551 		error = EINVAL;
2552 		break;
2553 	}
2554 	if (error == 0 && old_mode != ifp->if_qosmarking_mode) {
2555 		dlil_post_msg(ifp, KEV_DL_SUBCLASS, KEV_DL_QOS_MODE_CHANGED,
2556 		    NULL, 0, FALSE);
2557 	}
2558 	return error;
2559 }
2560 
2561 static __attribute__((noinline)) int
ifioctl_iforder(u_long cmd,caddr_t data)2562 ifioctl_iforder(u_long cmd, caddr_t data)
2563 {
2564 	int error = 0;
2565 	u_int32_t *ordered_indices = NULL;
2566 	size_t ordered_indices_length = 0;
2567 
2568 	if (data == NULL) {
2569 		return EINVAL;
2570 	}
2571 
2572 	switch (cmd) {
2573 	case SIOCSIFORDER: {            /* struct if_order */
2574 		struct if_order *ifo = (struct if_order *)(void *)data;
2575 
2576 		if (ifo->ifo_count > (u_int32_t)if_index) {
2577 			error = EINVAL;
2578 			break;
2579 		}
2580 
2581 		ordered_indices_length = ifo->ifo_count * sizeof(u_int32_t);
2582 		if (ordered_indices_length > 0) {
2583 			if (ifo->ifo_ordered_indices == USER_ADDR_NULL) {
2584 				error = EINVAL;
2585 				break;
2586 			}
2587 			ordered_indices = (u_int32_t *)kalloc_data(ordered_indices_length,
2588 			    Z_WAITOK);
2589 			if (ordered_indices == NULL) {
2590 				error = ENOMEM;
2591 				break;
2592 			}
2593 
2594 			error = copyin(CAST_USER_ADDR_T(ifo->ifo_ordered_indices),
2595 			    ordered_indices, ordered_indices_length);
2596 			if (error != 0) {
2597 				break;
2598 			}
2599 
2600 			/* ordered_indices should not contain duplicates */
2601 			bool found_duplicate = FALSE;
2602 			for (uint32_t i = 0; i < (ifo->ifo_count - 1) && !found_duplicate; i++) {
2603 				for (uint32_t j = i + 1; j < ifo->ifo_count && !found_duplicate; j++) {
2604 					if (ordered_indices[j] == ordered_indices[i]) {
2605 						error = EINVAL;
2606 						found_duplicate = TRUE;
2607 						break;
2608 					}
2609 				}
2610 			}
2611 			if (found_duplicate) {
2612 				break;
2613 			}
2614 
2615 			error = ifnet_reset_order(ordered_indices, ifo->ifo_count);
2616 		} else {
2617 			// Clear the list
2618 			error = ifnet_reset_order(NULL, 0);
2619 		}
2620 		break;
2621 	}
2622 
2623 	case SIOCGIFORDER: {
2624 #if (DEBUG || DEVELOPMENT)
2625 		struct if_order *ifo = (struct if_order *)(void *)data;
2626 		uint32_t count;
2627 
2628 		if (ifo->ifo_ordered_indices == 0) {
2629 			ifo->ifo_count = if_ordered_count;
2630 			break;
2631 		}
2632 
2633 		count = ifo->ifo_count;
2634 		if (count == 0) {
2635 			error = EINVAL;
2636 			break;
2637 		}
2638 
2639 		ordered_indices_length = count * sizeof(uint32_t);
2640 		ordered_indices = (uint32_t *)kalloc_data(ordered_indices_length,
2641 		    Z_WAITOK | Z_ZERO);
2642 		if (ordered_indices == NULL) {
2643 			error = ENOMEM;
2644 			break;
2645 		}
2646 
2647 		error = ifnet_get_ordered_indices(ordered_indices, &count);
2648 		if (error == 0) {
2649 			ifo->ifo_count = count;
2650 			error = copyout((caddr_t)ordered_indices,
2651 			    CAST_USER_ADDR_T(ifo->ifo_ordered_indices),
2652 			    count * sizeof(uint32_t));
2653 		}
2654 #else /* (DEBUG || DEVELOPMENT) */
2655 		error = EOPNOTSUPP;
2656 #endif /* (DEBUG || DEVELOPMENT) */
2657 
2658 		break;
2659 	}
2660 
2661 	default: {
2662 		VERIFY(0);
2663 		/* NOTREACHED */
2664 	}
2665 	}
2666 
2667 	if (ordered_indices != NULL) {
2668 		kfree_data(ordered_indices, ordered_indices_length);
2669 	}
2670 
2671 	return error;
2672 }
2673 
2674 static __attribute__((noinline)) int
ifioctl_networkid(struct ifnet * ifp,caddr_t data)2675 ifioctl_networkid(struct ifnet *ifp, caddr_t data)
2676 {
2677 	struct if_netidreq *ifnetidr = (struct if_netidreq *)(void *)data;
2678 	int error = 0;
2679 	int len = ifnetidr->ifnetid_len;
2680 
2681 	VERIFY(ifp != NULL);
2682 
2683 	if (len > sizeof(ifnetidr->ifnetid)) {
2684 		error = EINVAL;
2685 		goto end;
2686 	}
2687 
2688 	if (len == 0) {
2689 		bzero(&ifp->network_id, sizeof(ifp->network_id));
2690 	} else if (len > sizeof(ifp->network_id)) {
2691 		error = EINVAL;
2692 		goto end;
2693 	}
2694 
2695 	ifp->network_id_len = (uint8_t)len;
2696 	bcopy(data, ifp->network_id, len);
2697 end:
2698 	return error;
2699 }
2700 
2701 static __attribute__((noinline)) int
ifioctl_netsignature(struct ifnet * ifp,u_long cmd,caddr_t data)2702 ifioctl_netsignature(struct ifnet *ifp, u_long cmd, caddr_t data)
2703 {
2704 	struct if_nsreq *ifnsr = (struct if_nsreq *)(void *)data;
2705 	u_int16_t flags;
2706 	int error = 0;
2707 
2708 	VERIFY(ifp != NULL);
2709 
2710 	switch (cmd) {
2711 	case SIOCSIFNETSIGNATURE:               /* struct if_nsreq */
2712 		if (ifnsr->ifnsr_len > sizeof(ifnsr->ifnsr_data)) {
2713 			error = EINVAL;
2714 			break;
2715 		}
2716 		bcopy(&ifnsr->ifnsr_flags, &flags, sizeof(flags));
2717 		error = ifnet_set_netsignature(ifp, ifnsr->ifnsr_family,
2718 		    ifnsr->ifnsr_len, flags, ifnsr->ifnsr_data);
2719 		break;
2720 
2721 	case SIOCGIFNETSIGNATURE:               /* struct if_nsreq */
2722 		ifnsr->ifnsr_len = sizeof(ifnsr->ifnsr_data);
2723 		error = ifnet_get_netsignature(ifp, ifnsr->ifnsr_family,
2724 		    &ifnsr->ifnsr_len, &flags, ifnsr->ifnsr_data);
2725 		if (error == 0) {
2726 			bcopy(&flags, &ifnsr->ifnsr_flags, sizeof(flags));
2727 		} else {
2728 			ifnsr->ifnsr_len = 0;
2729 		}
2730 		break;
2731 
2732 	default:
2733 		VERIFY(0);
2734 		/* NOTREACHED */
2735 	}
2736 
2737 	return error;
2738 }
2739 
2740 static __attribute__((noinline)) int
ifioctl_nat64prefix(struct ifnet * ifp,u_long cmd,caddr_t data)2741 ifioctl_nat64prefix(struct ifnet *ifp, u_long cmd, caddr_t data)
2742 {
2743 	struct if_nat64req *ifnat64 = (struct if_nat64req *)(void *)data;
2744 	int error = 0;
2745 
2746 	VERIFY(ifp != NULL);
2747 
2748 	switch (cmd) {
2749 	case SIOCSIFNAT64PREFIX:                /* struct if_nat64req */
2750 		error = ifnet_set_nat64prefix(ifp, ifnat64->ifnat64_prefixes);
2751 		if (error != 0) {
2752 			ip6stat.ip6s_clat464_plat64_pfx_setfail++;
2753 		}
2754 		break;
2755 
2756 	case SIOCGIFNAT64PREFIX:                /* struct if_nat64req */
2757 		error = ifnet_get_nat64prefix(ifp, ifnat64->ifnat64_prefixes);
2758 		if (error != 0) {
2759 			ip6stat.ip6s_clat464_plat64_pfx_getfail++;
2760 		}
2761 		break;
2762 
2763 	default:
2764 		VERIFY(0);
2765 		/* NOTREACHED */
2766 	}
2767 
2768 	return error;
2769 }
2770 
2771 static __attribute__((noinline)) int
ifioctl_clat46addr(struct ifnet * ifp,u_long cmd,caddr_t data)2772 ifioctl_clat46addr(struct ifnet *ifp, u_long cmd, caddr_t data)
2773 {
2774 	struct if_clat46req *ifclat46 = (struct if_clat46req *)(void *)data;
2775 	struct in6_ifaddr *ia6_clat = NULL;
2776 	int error = 0;
2777 
2778 	VERIFY(ifp != NULL);
2779 
2780 	switch (cmd) {
2781 	case SIOCGIFCLAT46ADDR:
2782 		ia6_clat = in6ifa_ifpwithflag(ifp, IN6_IFF_CLAT46);
2783 		if (ia6_clat == NULL) {
2784 			error = ENOENT;
2785 			break;
2786 		}
2787 
2788 		bcopy(&ia6_clat->ia_addr.sin6_addr, &ifclat46->ifclat46_addr.v6_address,
2789 		    sizeof(ifclat46->ifclat46_addr.v6_address));
2790 		ifclat46->ifclat46_addr.v6_prefixlen = ia6_clat->ia_plen;
2791 		IFA_REMREF(&ia6_clat->ia_ifa);
2792 		break;
2793 	default:
2794 		VERIFY(0);
2795 		/* NOTREACHED */
2796 	}
2797 
2798 	return error;
2799 }
2800 
2801 #if SKYWALK
2802 static __attribute__((noinline)) int
ifioctl_nexus(struct ifnet * ifp,u_long cmd,caddr_t data)2803 ifioctl_nexus(struct ifnet *ifp, u_long cmd, caddr_t data)
2804 {
2805 	int error = 0;
2806 	struct if_nexusreq *ifnr = (struct if_nexusreq *)(void *)data;
2807 
2808 	switch (cmd) {
2809 	case SIOCGIFNEXUS:              /* struct if_nexusreq */
2810 		if (ifnr->ifnr_flags != 0) {
2811 			error = EINVAL;
2812 			break;
2813 		}
2814 		error = kern_nexus_get_netif_instance(ifp, ifnr->ifnr_netif);
2815 		if (error != 0) {
2816 			break;
2817 		}
2818 		kern_nexus_get_flowswitch_instance(ifp, ifnr->ifnr_flowswitch);
2819 		break;
2820 	default:
2821 		VERIFY(0);
2822 		/* NOTREACHED */
2823 	}
2824 
2825 	return error;
2826 }
2827 #endif /* SKYWALK */
2828 
2829 static int
ifioctl_get_protolist(struct ifnet * ifp,u_int32_t * ret_count,user_addr_t ifpl)2830 ifioctl_get_protolist(struct ifnet *ifp, u_int32_t * ret_count,
2831     user_addr_t ifpl)
2832 {
2833 	u_int32_t       actual_count;
2834 	u_int32_t       count;
2835 	int             error = 0;
2836 	u_int32_t       *list = NULL;
2837 
2838 	/* find out how many */
2839 	count = if_get_protolist(ifp, NULL, 0);
2840 	if (ifpl == USER_ADDR_NULL) {
2841 		goto done;
2842 	}
2843 
2844 	/* copy out how many there's space for */
2845 	if (*ret_count < count) {
2846 		count = *ret_count;
2847 	}
2848 	if (count == 0) {
2849 		goto done;
2850 	}
2851 	list = (u_int32_t *)kalloc_data(count * sizeof(*list), Z_WAITOK | Z_ZERO);
2852 	if (list == NULL) {
2853 		error = ENOMEM;
2854 		goto done;
2855 	}
2856 	actual_count = if_get_protolist(ifp, list, count);
2857 	if (actual_count < count) {
2858 		count = actual_count;
2859 	}
2860 	if (count != 0) {
2861 		error = copyout((caddr_t)list, ifpl, count * sizeof(*list));
2862 	}
2863 
2864 done:
2865 	if (list != NULL) {
2866 		if_free_protolist(list);
2867 	}
2868 	*ret_count = count;
2869 	return error;
2870 }
2871 
2872 static __attribute__((noinline)) int
ifioctl_protolist(struct ifnet * ifp,u_long cmd,caddr_t data)2873 ifioctl_protolist(struct ifnet *ifp, u_long cmd, caddr_t data)
2874 {
2875 	int error = 0;
2876 
2877 	switch (cmd) {
2878 	case SIOCGIFPROTOLIST32: {              /* struct if_protolistreq32 */
2879 		struct if_protolistreq32        ifpl;
2880 
2881 		bcopy(data, &ifpl, sizeof(ifpl));
2882 		if (ifpl.ifpl_reserved != 0) {
2883 			error = EINVAL;
2884 			break;
2885 		}
2886 		error = ifioctl_get_protolist(ifp, &ifpl.ifpl_count,
2887 		    CAST_USER_ADDR_T(ifpl.ifpl_list));
2888 		bcopy(&ifpl, data, sizeof(ifpl));
2889 		break;
2890 	}
2891 	case SIOCGIFPROTOLIST64: {              /* struct if_protolistreq64 */
2892 		struct if_protolistreq64        ifpl;
2893 
2894 		bcopy(data, &ifpl, sizeof(ifpl));
2895 		if (ifpl.ifpl_reserved != 0) {
2896 			error = EINVAL;
2897 			break;
2898 		}
2899 		error = ifioctl_get_protolist(ifp, &ifpl.ifpl_count,
2900 		    CAST_USER_ADDR_T(ifpl.ifpl_list));
2901 		bcopy(&ifpl, data, sizeof(ifpl));
2902 		break;
2903 	}
2904 	default:
2905 		VERIFY(0);
2906 		/* NOTREACHED */
2907 	}
2908 
2909 	return error;
2910 }
2911 
2912 /*
2913  * List the ioctl()s we can perform on restricted INTCOPROC interfaces.
2914  */
2915 static bool
ifioctl_restrict_intcoproc(unsigned long cmd,const char * ifname,struct ifnet * ifp,struct proc * p)2916 ifioctl_restrict_intcoproc(unsigned long cmd, const char *ifname,
2917     struct ifnet *ifp, struct proc *p)
2918 {
2919 	if (intcoproc_unrestricted) {
2920 		return false;
2921 	}
2922 	if (proc_pid(p) == 0) {
2923 		return false;
2924 	}
2925 	if (ifname) {
2926 		ifp = ifunit(ifname);
2927 	}
2928 	if (ifp == NULL) {
2929 		return false;
2930 	}
2931 	if (!IFNET_IS_INTCOPROC(ifp)) {
2932 		return false;
2933 	}
2934 	switch (cmd) {
2935 	case SIOCGIFBRDADDR:
2936 	case SIOCGIFCONF32:
2937 	case SIOCGIFCONF64:
2938 	case SIOCGIFFLAGS:
2939 	case SIOCGIFEFLAGS:
2940 	case SIOCGIFCAP:
2941 	case SIOCGIFMETRIC:
2942 	case SIOCGIFMTU:
2943 	case SIOCGIFPHYS:
2944 	case SIOCGIFTYPE:
2945 	case SIOCGIFFUNCTIONALTYPE:
2946 	case SIOCGIFPSRCADDR:
2947 	case SIOCGIFPDSTADDR:
2948 	case SIOCGIFGENERIC:
2949 	case SIOCGIFDEVMTU:
2950 	case SIOCGIFVLAN:
2951 	case SIOCGIFBOND:
2952 	case SIOCGIFWAKEFLAGS:
2953 	case SIOCGIFGETRTREFCNT:
2954 	case SIOCGIFOPPORTUNISTIC:
2955 	case SIOCGIFLINKQUALITYMETRIC:
2956 	case SIOCGIFLOG:
2957 	case SIOCGIFDELEGATE:
2958 	case SIOCGIFEXPENSIVE:
2959 	case SIOCGIFINTERFACESTATE:
2960 	case SIOCGIFPROBECONNECTIVITY:
2961 	case SIOCGIFTIMESTAMPENABLED:
2962 	case SIOCGECNMODE:
2963 	case SIOCGQOSMARKINGMODE:
2964 	case SIOCGQOSMARKINGENABLED:
2965 	case SIOCGIFLOWINTERNET:
2966 	case SIOCGIFSTATUS:
2967 	case SIOCGIFMEDIA32:
2968 	case SIOCGIFMEDIA64:
2969 	case SIOCGIFXMEDIA32:
2970 	case SIOCGIFXMEDIA64:
2971 	case SIOCGIFDESC:
2972 	case SIOCGIFLINKPARAMS:
2973 	case SIOCGIFQUEUESTATS:
2974 	case SIOCGIFTHROTTLE:
2975 	case SIOCGIFAGENTIDS32:
2976 	case SIOCGIFAGENTIDS64:
2977 	case SIOCGIFNETSIGNATURE:
2978 	case SIOCGIFINFO_IN6:
2979 	case SIOCGIFAFLAG_IN6:
2980 	case SIOCGNBRINFO_IN6:
2981 	case SIOCGIFALIFETIME_IN6:
2982 	case SIOCGIFNETMASK_IN6:
2983 #if SKYWALK
2984 	case SIOCGIFNEXUS:
2985 #endif /* SKYWALK */
2986 	case SIOCGIFPROTOLIST32:
2987 	case SIOCGIFPROTOLIST64:
2988 	case SIOCGIFXFLAGS:
2989 	case SIOCGIFNOTRAFFICSHAPING:
2990 	case SIOCGIFGENERATIONID:
2991 		return false;
2992 	default:
2993 #if (DEBUG || DEVELOPMENT)
2994 		printf("%s: cmd 0x%lx not allowed (pid %u)\n",
2995 		    __func__, cmd, proc_pid(p));
2996 #endif
2997 		return true;
2998 	}
2999 	return false;
3000 }
3001 
3002 static bool
ifioctl_restrict_management(unsigned long cmd,const char * ifname,struct ifnet * ifp,struct proc * p)3003 ifioctl_restrict_management(unsigned long cmd, const char *ifname,
3004     struct ifnet *ifp, struct proc *p)
3005 {
3006 	if (if_management_interface_check_needed == false) {
3007 		return false;
3008 	}
3009 	if (management_control_unrestricted) {
3010 		return false;
3011 	}
3012 	if (proc_pid(p) == 0) {
3013 		return false;
3014 	}
3015 	if (ifname) {
3016 		ifp = ifunit(ifname);
3017 	}
3018 	if (ifp == NULL) {
3019 		return false;
3020 	}
3021 	if (!IFNET_IS_MANAGEMENT(ifp)) {
3022 		return false;
3023 	}
3024 	switch (cmd) {
3025 	case SIOCGIFBRDADDR:
3026 	case SIOCGIFCONF32:
3027 	case SIOCGIFCONF64:
3028 	case SIOCGIFFLAGS:
3029 	case SIOCGIFEFLAGS:
3030 	case SIOCGIFCAP:
3031 	case SIOCGIFMETRIC:
3032 	case SIOCGIFMTU:
3033 	case SIOCGIFPHYS:
3034 	case SIOCGIFTYPE:
3035 	case SIOCGIFFUNCTIONALTYPE:
3036 	case SIOCGIFPSRCADDR:
3037 	case SIOCGIFPDSTADDR:
3038 	case SIOCGIFGENERIC:
3039 	case SIOCGIFDEVMTU:
3040 	case SIOCGIFVLAN:
3041 	case SIOCGIFBOND:
3042 	case SIOCGIFWAKEFLAGS:
3043 	case SIOCGIFGETRTREFCNT:
3044 	case SIOCGIFOPPORTUNISTIC:
3045 	case SIOCGIFLINKQUALITYMETRIC:
3046 	case SIOCGIFLOG:
3047 	case SIOCGIFDELEGATE:
3048 	case SIOCGIFEXPENSIVE:
3049 	case SIOCGIFINTERFACESTATE:
3050 	case SIOCGIFPROBECONNECTIVITY:
3051 	case SIOCGIFTIMESTAMPENABLED:
3052 	case SIOCGECNMODE:
3053 	case SIOCGQOSMARKINGMODE:
3054 	case SIOCGQOSMARKINGENABLED:
3055 	case SIOCGIFLOWINTERNET:
3056 	case SIOCGIFSTATUS:
3057 	case SIOCGIFMEDIA32:
3058 	case SIOCGIFMEDIA64:
3059 	case SIOCGIFXMEDIA32:
3060 	case SIOCGIFXMEDIA64:
3061 	case SIOCGIFDESC:
3062 	case SIOCGIFLINKPARAMS:
3063 	case SIOCGIFQUEUESTATS:
3064 	case SIOCGIFTHROTTLE:
3065 	case SIOCGIFAGENTIDS32:
3066 	case SIOCGIFAGENTIDS64:
3067 	case SIOCGIFNETSIGNATURE:
3068 	case SIOCGIFINFO_IN6:
3069 	case SIOCGIFAFLAG_IN6:
3070 	case SIOCGNBRINFO_IN6:
3071 	case SIOCGIFALIFETIME_IN6:
3072 	case SIOCGIFNETMASK_IN6:
3073 #if SKYWALK
3074 	case SIOCGIFNEXUS:
3075 #endif /* SKYWALK */
3076 	case SIOCGIFPROTOLIST32:
3077 	case SIOCGIFPROTOLIST64:
3078 	case SIOCGIFXFLAGS:
3079 	case SIOCGIFNOTRAFFICSHAPING:
3080 	case SIOCGIFGENERATIONID:
3081 		return false;
3082 	default:
3083 		if (!IOCurrentTaskHasEntitlement(MANAGEMENT_CONTROL_ENTITLEMENT)) {
3084 #if (DEBUG || DEVELOPMENT)
3085 			printf("ifioctl_restrict_management: cmd 0x%lx on %s not allowed for %s:%u\n",
3086 			    cmd, ifname, proc_name_address(p), proc_pid(p));
3087 #endif
3088 			return true;
3089 		}
3090 		return false;
3091 	}
3092 	return false;
3093 }
3094 
3095 /*
3096  * Given a media word, return one suitable for an application
3097  * using the original encoding.
3098  */
3099 static int
compat_media(int media)3100 compat_media(int media)
3101 {
3102 	if (IFM_TYPE(media) == IFM_ETHER && IFM_SUBTYPE(media) > IFM_OTHER) {
3103 		media &= ~IFM_TMASK;
3104 		media |= IFM_OTHER;
3105 	}
3106 	return media;
3107 }
3108 
3109 static int
compat_ifmu_ulist(struct ifnet * ifp,u_long cmd,void * data)3110 compat_ifmu_ulist(struct ifnet *ifp, u_long cmd, void *data)
3111 {
3112 	struct ifmediareq *ifmr = (struct ifmediareq *)data;
3113 	user_addr_t user_addr;
3114 	int i;
3115 	int *media_list = NULL;
3116 	int error = 0;
3117 	bool list_modified = false;
3118 
3119 	user_addr = (cmd == SIOCGIFMEDIA64) ?
3120 	    CAST_USER_ADDR_T(((struct ifmediareq64 *)ifmr)->ifmu_ulist) :
3121 	    CAST_USER_ADDR_T(((struct ifmediareq32 *)ifmr)->ifmu_ulist);
3122 	if (user_addr == USER_ADDR_NULL || ifmr->ifm_count == 0) {
3123 		return 0;
3124 	}
3125 	media_list = (int *)kalloc_data(ifmr->ifm_count * sizeof(int),
3126 	    Z_WAITOK | Z_ZERO);
3127 	if (media_list == NULL) {
3128 		os_log_error(OS_LOG_DEFAULT,
3129 		    "%s: %s kalloc_data() failed",
3130 		    __func__, ifp->if_xname);
3131 		error = ENOMEM;
3132 		goto done;
3133 	}
3134 	error = copyin(user_addr, media_list, ifmr->ifm_count * sizeof(int));
3135 	if (error != 0) {
3136 		os_log_error(OS_LOG_DEFAULT,
3137 		    "%s: %s copyin() error %d",
3138 		    __func__, ifp->if_xname, error);
3139 		goto done;
3140 	}
3141 	for (i = 0; i < ifmr->ifm_count; i++) {
3142 		int old_media, new_media;
3143 
3144 		old_media = media_list[i];
3145 
3146 		new_media = compat_media(old_media);
3147 		if (new_media == old_media) {
3148 			continue;
3149 		}
3150 		if (if_verbose != 0) {
3151 			os_log_info(OS_LOG_DEFAULT,
3152 			    "%s: %s converted extended media %08x to compat media %08x",
3153 			    __func__, ifp->if_xname, old_media, new_media);
3154 		}
3155 		media_list[i] = new_media;
3156 		list_modified = true;
3157 	}
3158 	if (list_modified) {
3159 		error = copyout(media_list, user_addr, ifmr->ifm_count * sizeof(int));
3160 		if (error != 0) {
3161 			os_log_error(OS_LOG_DEFAULT,
3162 			    "%s: %s copyout() error %d",
3163 			    __func__, ifp->if_xname, error);
3164 			goto done;
3165 		}
3166 	}
3167 done:
3168 	if (media_list != NULL) {
3169 		kfree_data(media_list, ifmr->ifm_count * sizeof(int));
3170 	}
3171 	return error;
3172 }
3173 
3174 static int
compat_ifmediareq(struct ifnet * ifp,u_long cmd,void * data)3175 compat_ifmediareq(struct ifnet *ifp, u_long cmd, void *data)
3176 {
3177 	struct ifmediareq *ifmr = (struct ifmediareq *)data;
3178 	int error;
3179 
3180 	ifmr->ifm_active = compat_media(ifmr->ifm_active);
3181 	ifmr->ifm_current = compat_media(ifmr->ifm_current);
3182 
3183 	error = compat_ifmu_ulist(ifp, cmd, data);
3184 
3185 	return error;
3186 }
3187 
3188 static int
ifioctl_get_media(struct ifnet * ifp,struct socket * so,u_long cmd,caddr_t data)3189 ifioctl_get_media(struct ifnet *ifp, struct socket *so, u_long cmd, caddr_t data)
3190 {
3191 	int error = 0;
3192 
3193 	/*
3194 	 * An ifnet must not implement SIOCGIFXMEDIA as it gets the extended
3195 	 *  media subtypes macros from <net/if_media.h>
3196 	 */
3197 	switch (cmd) {
3198 	case SIOCGIFMEDIA32:
3199 	case SIOCGIFXMEDIA32:
3200 		error = ifnet_ioctl(ifp, SOCK_DOM(so), SIOCGIFMEDIA32, data);
3201 		break;
3202 	case SIOCGIFMEDIA64:
3203 	case SIOCGIFXMEDIA64:
3204 		error = ifnet_ioctl(ifp, SOCK_DOM(so), SIOCGIFMEDIA64, data);
3205 		break;
3206 	}
3207 	if (if_verbose != 0 && error != 0) {
3208 		os_log(OS_LOG_DEFAULT, "%s: first ifnet_ioctl(%s, %08lx) error %d",
3209 		    __func__, ifp->if_xname, cmd, error);
3210 	}
3211 	if (error == 0 && (cmd == SIOCGIFMEDIA32 || cmd == SIOCGIFMEDIA64)) {
3212 		error = compat_ifmediareq(ifp, cmd, data);
3213 	}
3214 	return error;
3215 }
3216 /*
3217  * Interface ioctls.
3218  *
3219  * Most of the routines called to handle the ioctls would end up being
3220  * tail-call optimized, which unfortunately causes this routine to
3221  * consume too much stack space; this is the reason for the "noinline"
3222  * attribute used on those routines.
3223  */
3224 int
ifioctl(struct socket * so,u_long cmd,caddr_t data,struct proc * p)3225 ifioctl(struct socket *so, u_long cmd, caddr_t data, struct proc *p)
3226 {
3227 	char ifname[IFNAMSIZ + 1];
3228 	struct ifnet *ifp = NULL;
3229 	struct ifstat *ifs = NULL;
3230 	int error = 0;
3231 
3232 	bzero(ifname, sizeof(ifname));
3233 
3234 	/*
3235 	 * ioctls which don't require ifp, or ifreq ioctls
3236 	 */
3237 	switch (cmd) {
3238 	case OSIOCGIFCONF32:                    /* struct ifconf32 */
3239 	case SIOCGIFCONF32:                     /* struct ifconf32 */
3240 	case SIOCGIFCONF64:                     /* struct ifconf64 */
3241 	case OSIOCGIFCONF64:                    /* struct ifconf64 */
3242 		error = ifioctl_ifconf(cmd, data);
3243 		goto done;
3244 
3245 	case SIOCIFGCLONERS32:                  /* struct if_clonereq32 */
3246 	case SIOCIFGCLONERS64:                  /* struct if_clonereq64 */
3247 		error = ifioctl_ifclone(cmd, data);
3248 		goto done;
3249 
3250 	case SIOCGIFAGENTDATA32:                /* struct netagent_req32 */
3251 	case SIOCGIFAGENTDATA64:                /* struct netagent_req64 */
3252 	case SIOCGIFAGENTLIST32:                /* struct netagentlist_req32 */
3253 	case SIOCGIFAGENTLIST64:                /* struct netagentlist_req64 */
3254 		error = netagent_ioctl(cmd, data);
3255 		goto done;
3256 
3257 	case SIOCSIFORDER:                      /* struct if_order */
3258 	case SIOCGIFORDER:                      /* struct if_order */
3259 		error = ifioctl_iforder(cmd, data);
3260 		goto done;
3261 
3262 	case SIOCSIFDSTADDR:                    /* struct ifreq */
3263 	case SIOCSIFADDR:                       /* struct ifreq */
3264 	case SIOCSIFBRDADDR:                    /* struct ifreq */
3265 	case SIOCSIFNETMASK:                    /* struct ifreq */
3266 	case OSIOCGIFADDR:                      /* struct ifreq */
3267 	case OSIOCGIFDSTADDR:                   /* struct ifreq */
3268 	case OSIOCGIFBRDADDR:                   /* struct ifreq */
3269 	case OSIOCGIFNETMASK:                   /* struct ifreq */
3270 	case SIOCSIFKPI:                        /* struct ifreq */
3271 		if (so->so_proto == NULL) {
3272 			error = EOPNOTSUPP;
3273 			goto done;
3274 		}
3275 		OS_FALLTHROUGH;
3276 	case SIOCIFCREATE:                      /* struct ifreq */
3277 	case SIOCIFCREATE2:                     /* struct ifreq */
3278 	case SIOCIFDESTROY:                     /* struct ifreq */
3279 	case SIOCGIFFLAGS:                      /* struct ifreq */
3280 	case SIOCGIFEFLAGS:                     /* struct ifreq */
3281 	case SIOCGIFCAP:                        /* struct ifreq */
3282 	case SIOCGIFMETRIC:                     /* struct ifreq */
3283 	case SIOCGIFMTU:                        /* struct ifreq */
3284 	case SIOCGIFPHYS:                       /* struct ifreq */
3285 	case SIOCSIFFLAGS:                      /* struct ifreq */
3286 	case SIOCSIFCAP:                        /* struct ifreq */
3287 	case SIOCSIFMANAGEMENT:                 /* struct ifreq */
3288 	case SIOCSIFMETRIC:                     /* struct ifreq */
3289 	case SIOCSIFPHYS:                       /* struct ifreq */
3290 	case SIOCSIFMTU:                        /* struct ifreq */
3291 	case SIOCADDMULTI:                      /* struct ifreq */
3292 	case SIOCDELMULTI:                      /* struct ifreq */
3293 	case SIOCDIFPHYADDR:                    /* struct ifreq */
3294 	case SIOCSIFMEDIA:                      /* struct ifreq */
3295 	case SIOCSIFGENERIC:                    /* struct ifreq */
3296 	case SIOCSIFLLADDR:                     /* struct ifreq */
3297 	case SIOCSIFALTMTU:                     /* struct ifreq */
3298 	case SIOCSIFVLAN:                       /* struct ifreq */
3299 	case SIOCSIFBOND:                       /* struct ifreq */
3300 	case SIOCGIFLLADDR:                     /* struct ifreq */
3301 	case SIOCGIFTYPE:                       /* struct ifreq */
3302 	case SIOCGIFFUNCTIONALTYPE:             /* struct ifreq */
3303 	case SIOCGIFPSRCADDR:                   /* struct ifreq */
3304 	case SIOCGIFPDSTADDR:                   /* struct ifreq */
3305 	case SIOCGIFGENERIC:                    /* struct ifreq */
3306 	case SIOCGIFDEVMTU:                     /* struct ifreq */
3307 	case SIOCGIFVLAN:                       /* struct ifreq */
3308 	case SIOCGIFBOND:                       /* struct ifreq */
3309 	case SIOCGIFWAKEFLAGS:                  /* struct ifreq */
3310 	case SIOCGIFGETRTREFCNT:                /* struct ifreq */
3311 	case SIOCSIFOPPORTUNISTIC:              /* struct ifreq */
3312 	case SIOCGIFOPPORTUNISTIC:              /* struct ifreq */
3313 	case SIOCGIFLINKQUALITYMETRIC:          /* struct ifreq */
3314 	case SIOCSIFLINKQUALITYMETRIC:          /* struct ifreq */
3315 	case SIOCSIFLOG:                        /* struct ifreq */
3316 	case SIOCGIFLOG:                        /* struct ifreq */
3317 	case SIOCGIFDELEGATE:                   /* struct ifreq */
3318 	case SIOCGIFEXPENSIVE:                  /* struct ifreq */
3319 	case SIOCSIFEXPENSIVE:                  /* struct ifreq */
3320 	case SIOCSIF2KCL:                       /* struct ifreq */
3321 	case SIOCGIF2KCL:                       /* struct ifreq */
3322 	case SIOCSIFINTERFACESTATE:             /* struct ifreq */
3323 	case SIOCGIFINTERFACESTATE:             /* struct ifreq */
3324 	case SIOCSIFPROBECONNECTIVITY:          /* struct ifreq */
3325 	case SIOCGIFPROBECONNECTIVITY:          /* struct ifreq */
3326 	case SIOCGSTARTDELAY:                   /* struct ifreq */
3327 	case SIOCSIFTIMESTAMPENABLE:            /* struct ifreq */
3328 	case SIOCSIFTIMESTAMPDISABLE:           /* struct ifreq */
3329 	case SIOCGIFTIMESTAMPENABLED:           /* struct ifreq */
3330 #if (DEBUG || DEVELOPMENT)
3331 	case SIOCSIFDISABLEOUTPUT:              /* struct ifreq */
3332 #endif /* (DEBUG || DEVELOPMENT) */
3333 	case SIOCSIFSUBFAMILY:                  /* struct ifreq */
3334 	case SIOCGECNMODE:                      /* struct ifreq */
3335 	case SIOCSECNMODE:
3336 	case SIOCSQOSMARKINGMODE:               /* struct ifreq */
3337 	case SIOCSQOSMARKINGENABLED:            /* struct ifreq */
3338 	case SIOCGQOSMARKINGMODE:               /* struct ifreq */
3339 	case SIOCGQOSMARKINGENABLED:            /* struct ifreq */
3340 	case SIOCSIFLOWINTERNET:                /* struct ifreq */
3341 	case SIOCGIFLOWINTERNET:                /* struct ifreq */
3342 	case SIOCGIFLOWPOWER:                   /* struct ifreq */
3343 	case SIOCSIFLOWPOWER:                   /* struct ifreq */
3344 	case SIOCGIFMPKLOG:                     /* struct ifreq */
3345 	case SIOCSIFMPKLOG:                     /* struct ifreq */
3346 	case SIOCGIFCONSTRAINED:                /* struct ifreq */
3347 	case SIOCSIFCONSTRAINED:                /* struct ifreq */
3348 	case SIOCSIFESTTHROUGHPUT:              /* struct ifreq */
3349 	case SIOCSIFRADIODETAILS:               /* struct ifreq */
3350 	case SIOCGIFXFLAGS:                     /* struct ifreq */
3351 	case SIOCGIFNOACKPRIO:                  /* struct ifreq */
3352 	case SIOCSIFNOACKPRIO:                  /* struct ifreq */
3353 	case SIOCSIFMARKWAKEPKT:                /* struct ifreq */
3354 	case SIOCSIFNOTRAFFICSHAPING:           /* struct ifreq */
3355 	case SIOCGIFNOTRAFFICSHAPING:           /* struct ifreq */
3356 	case SIOCGIFGENERATIONID:               /* struct ifreq */
3357 	{                       /* struct ifreq */
3358 		struct ifreq ifr;
3359 		bcopy(data, &ifr, sizeof(ifr));
3360 		ifr.ifr_name[IFNAMSIZ - 1] = '\0';
3361 		bcopy(&ifr.ifr_name, ifname, IFNAMSIZ);
3362 		if (ifioctl_restrict_intcoproc(cmd, ifname, NULL, p) == true) {
3363 			error = EPERM;
3364 			goto done;
3365 		}
3366 		if (ifioctl_restrict_management(cmd, ifname, NULL, p) == true) {
3367 			error = EPERM;
3368 			goto done;
3369 		}
3370 		error = ifioctl_ifreq(so, cmd, &ifr, p);
3371 		bcopy(&ifr, data, sizeof(ifr));
3372 		goto done;
3373 	}
3374 	}
3375 
3376 	/*
3377 	 * ioctls which require ifp.  Note that we acquire dlil_ifnet_lock
3378 	 * here to ensure that the ifnet, if found, has been fully attached.
3379 	 */
3380 	dlil_if_lock();
3381 	switch (cmd) {
3382 	case SIOCSIFPHYADDR:                    /* struct {if,in_}aliasreq */
3383 		bcopy(((struct in_aliasreq *)(void *)data)->ifra_name,
3384 		    ifname, IFNAMSIZ);
3385 		ifp = ifunit_ref(ifname);
3386 		break;
3387 
3388 	case SIOCSIFPHYADDR_IN6_32:             /* struct in6_aliasreq_32 */
3389 		bcopy(((struct in6_aliasreq_32 *)(void *)data)->ifra_name,
3390 		    ifname, IFNAMSIZ);
3391 		ifp = ifunit_ref(ifname);
3392 		break;
3393 
3394 	case SIOCSIFPHYADDR_IN6_64:             /* struct in6_aliasreq_64 */
3395 		bcopy(((struct in6_aliasreq_64 *)(void *)data)->ifra_name,
3396 		    ifname, IFNAMSIZ);
3397 		ifp = ifunit_ref(ifname);
3398 		break;
3399 
3400 	case SIOCGIFSTATUS:                     /* struct ifstat */
3401 		ifs = kalloc_type(struct ifstat, Z_WAITOK | Z_NOFAIL);
3402 		bcopy(data, ifs, sizeof(*ifs));
3403 		ifs->ifs_name[IFNAMSIZ - 1] = '\0';
3404 		bcopy(ifs->ifs_name, ifname, IFNAMSIZ);
3405 		ifp = ifunit_ref(ifname);
3406 		break;
3407 
3408 	case SIOCGIFMEDIA32:                    /* struct ifmediareq32 */
3409 	case SIOCGIFXMEDIA32:                    /* struct ifmediareq32 */
3410 		bcopy(((struct ifmediareq32 *)(void *)data)->ifm_name,
3411 		    ifname, IFNAMSIZ);
3412 		ifp = ifunit_ref(ifname);
3413 		break;
3414 
3415 	case SIOCGIFMEDIA64:                    /* struct ifmediareq64 */
3416 	case SIOCGIFXMEDIA64:                    /* struct ifmediareq64 */
3417 		bcopy(((struct ifmediareq64 *)(void *)data)->ifm_name,
3418 		    ifname, IFNAMSIZ);
3419 		ifp = ifunit_ref(ifname);
3420 		break;
3421 
3422 	case SIOCSIFDESC:                       /* struct if_descreq */
3423 	case SIOCGIFDESC:                       /* struct if_descreq */
3424 		bcopy(((struct if_descreq *)(void *)data)->ifdr_name,
3425 		    ifname, IFNAMSIZ);
3426 		ifp = ifunit_ref(ifname);
3427 		break;
3428 
3429 	case SIOCSIFLINKPARAMS:                 /* struct if_linkparamsreq */
3430 	case SIOCGIFLINKPARAMS:                 /* struct if_linkparamsreq */
3431 		bcopy(((struct if_linkparamsreq *)(void *)data)->iflpr_name,
3432 		    ifname, IFNAMSIZ);
3433 		ifp = ifunit_ref(ifname);
3434 		break;
3435 
3436 	case SIOCGIFQUEUESTATS:                 /* struct if_qstatsreq */
3437 		bcopy(((struct if_qstatsreq *)(void *)data)->ifqr_name,
3438 		    ifname, IFNAMSIZ);
3439 		ifp = ifunit_ref(ifname);
3440 		break;
3441 
3442 	case SIOCSIFTHROTTLE:                   /* struct if_throttlereq */
3443 	case SIOCGIFTHROTTLE:                   /* struct if_throttlereq */
3444 		bcopy(((struct if_throttlereq *)(void *)data)->ifthr_name,
3445 		    ifname, IFNAMSIZ);
3446 		ifp = ifunit_ref(ifname);
3447 		break;
3448 
3449 	case SIOCAIFAGENTID:                    /* struct if_agentidreq */
3450 	case SIOCDIFAGENTID:                    /* struct if_agentidreq */
3451 	case SIOCGIFAGENTIDS32:         /* struct if_agentidsreq32 */
3452 	case SIOCGIFAGENTIDS64:         /* struct if_agentidsreq64 */
3453 		bcopy(((struct if_agentidreq *)(void *)data)->ifar_name,
3454 		    ifname, IFNAMSIZ);
3455 		ifp = ifunit_ref(ifname);
3456 		break;
3457 
3458 	case SIOCSIFNETSIGNATURE:               /* struct if_nsreq */
3459 	case SIOCGIFNETSIGNATURE:               /* struct if_nsreq */
3460 		bcopy(((struct if_nsreq *)(void *)data)->ifnsr_name,
3461 		    ifname, IFNAMSIZ);
3462 		ifp = ifunit_ref(ifname);
3463 		break;
3464 
3465 	case SIOCSIFNETWORKID:                  /* struct if_netidreq */
3466 		bcopy(((struct if_netidreq *)(void *)data)->ifnetid_name,
3467 		    ifname, IFNAMSIZ);
3468 		ifp = ifunit_ref(ifname);
3469 		break;
3470 #if SKYWALK
3471 	case SIOCGIFNEXUS:                      /* struct if_nexusreq */
3472 		bcopy(((struct if_nexusreq *)(void *)data)->ifnr_name,
3473 		    ifname, IFNAMSIZ);
3474 		ifp = ifunit_ref(ifname);
3475 		break;
3476 #endif /* SKYWALK */
3477 	case SIOCGIFPROTOLIST32:                /* struct if_protolistreq32 */
3478 	case SIOCGIFPROTOLIST64:                /* struct if_protolistreq64 */
3479 		bcopy(((struct if_protolistreq *)(void *)data)->ifpl_name,
3480 		    ifname, IFNAMSIZ);
3481 		ifp = ifunit_ref(ifname);
3482 		break;
3483 	default:
3484 		/*
3485 		 * This is a bad assumption, but the code seems to
3486 		 * have been doing this in the past; caveat emptor.
3487 		 */
3488 		bcopy(((struct ifreq *)(void *)data)->ifr_name,
3489 		    ifname, IFNAMSIZ);
3490 		ifp = ifunit_ref(ifname);
3491 		break;
3492 	}
3493 	dlil_if_unlock();
3494 
3495 	if (ifp == NULL) {
3496 		error = ENXIO;
3497 		goto done;
3498 	}
3499 
3500 	if (ifioctl_restrict_intcoproc(cmd, NULL, ifp, p) == true) {
3501 		error = EPERM;
3502 		goto done;
3503 	}
3504 	switch (cmd) {
3505 	case SIOCSIFPHYADDR:                    /* struct {if,in_}aliasreq */
3506 	case SIOCSIFPHYADDR_IN6_32:             /* struct in6_aliasreq_32 */
3507 	case SIOCSIFPHYADDR_IN6_64:             /* struct in6_aliasreq_64 */
3508 		error = proc_suser(p);
3509 		if (error != 0) {
3510 			break;
3511 		}
3512 
3513 		error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd, data);
3514 		if (error != 0) {
3515 			break;
3516 		}
3517 
3518 		ifnet_touch_lastchange(ifp);
3519 		break;
3520 
3521 	case SIOCGIFSTATUS:                     /* struct ifstat */
3522 		VERIFY(ifs != NULL);
3523 		ifs->ascii[0] = '\0';
3524 
3525 		error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd, (caddr_t)ifs);
3526 
3527 		bcopy(ifs, data, sizeof(*ifs));
3528 		break;
3529 
3530 	case SIOCGIFMEDIA32:                    /* struct ifmediareq32 */
3531 	case SIOCGIFMEDIA64:                    /* struct ifmediareq64 */
3532 	case SIOCGIFXMEDIA32:                    /* struct ifmediareq32 */
3533 	case SIOCGIFXMEDIA64:                    /* struct ifmediareq64 */
3534 		error = ifioctl_get_media(ifp, so, cmd, data);
3535 		break;
3536 
3537 	case SIOCSIFDESC:                       /* struct if_descreq */
3538 	case SIOCGIFDESC:                       /* struct if_descreq */
3539 		error = ifioctl_ifdesc(ifp, cmd, data, p);
3540 		break;
3541 
3542 	case SIOCSIFLINKPARAMS:                 /* struct if_linkparamsreq */
3543 	case SIOCGIFLINKPARAMS:                 /* struct if_linkparamsreq */
3544 		error = ifioctl_linkparams(ifp, cmd, data, p);
3545 		break;
3546 
3547 	case SIOCGIFQUEUESTATS:                 /* struct if_qstatsreq */
3548 		error = ifioctl_qstats(ifp, cmd, data);
3549 		break;
3550 
3551 	case SIOCSIFTHROTTLE:                   /* struct if_throttlereq */
3552 	case SIOCGIFTHROTTLE:                   /* struct if_throttlereq */
3553 		error = ifioctl_throttle(ifp, cmd, data, p);
3554 		break;
3555 
3556 	case SIOCAIFAGENTID:                    /* struct if_agentidreq */
3557 	case SIOCDIFAGENTID:                    /* struct if_agentidreq */
3558 	case SIOCGIFAGENTIDS32:         /* struct if_agentidsreq32 */
3559 	case SIOCGIFAGENTIDS64:         /* struct if_agentidsreq64 */
3560 		error = ifioctl_netagent(ifp, cmd, data, p);
3561 		break;
3562 
3563 	case SIOCSIFNETSIGNATURE:               /* struct if_nsreq */
3564 	case SIOCGIFNETSIGNATURE:               /* struct if_nsreq */
3565 		error = ifioctl_netsignature(ifp, cmd, data);
3566 		break;
3567 
3568 	case SIOCSIFNETWORKID:                  /* struct if_netidreq */
3569 		error = ifioctl_networkid(ifp, data);
3570 		break;
3571 	case SIOCSIFNAT64PREFIX:                /* struct if_nat64req */
3572 	case SIOCGIFNAT64PREFIX:                /* struct if_nat64req */
3573 		error = ifioctl_nat64prefix(ifp, cmd, data);
3574 		break;
3575 
3576 	case SIOCGIFCLAT46ADDR:                 /* struct if_clat46req */
3577 		error = ifioctl_clat46addr(ifp, cmd, data);
3578 		break;
3579 #if SKYWALK
3580 	case SIOCGIFNEXUS:
3581 		error = ifioctl_nexus(ifp, cmd, data);
3582 		break;
3583 #endif /* SKYWALK */
3584 
3585 	case SIOCGIFPROTOLIST32:                /* struct if_protolistreq32 */
3586 	case SIOCGIFPROTOLIST64:                /* struct if_protolistreq64 */
3587 		error = ifioctl_protolist(ifp, cmd, data);
3588 		break;
3589 
3590 	default:
3591 		if (so->so_proto == NULL) {
3592 			error = EOPNOTSUPP;
3593 			break;
3594 		}
3595 
3596 		socket_lock(so, 1);
3597 		error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
3598 		    data, ifp, p));
3599 		socket_unlock(so, 1);
3600 
3601 		// Don't allow to call SIOCAIFADDR and SIOCDIFADDR with
3602 		// ifreq as the code expects ifaddr
3603 		if ((error == EOPNOTSUPP || error == ENOTSUP) &&
3604 		    !(cmd == SIOCAIFADDR || cmd == SIOCDIFADDR)) {
3605 			error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd, data);
3606 		}
3607 		break;
3608 	}
3609 
3610 done:
3611 	if (ifs != NULL) {
3612 		kfree_type(struct ifstat, ifs);
3613 	}
3614 
3615 	if (if_verbose) {
3616 		if (ifname[0] == '\0') {
3617 			(void) snprintf(ifname, sizeof(ifname), "%s",
3618 			    "NULL");
3619 		} else if (ifp != NULL) {
3620 			(void) snprintf(ifname, sizeof(ifname), "%s",
3621 			    if_name(ifp));
3622 		}
3623 
3624 		if (error != 0) {
3625 			printf("%s[%s,%d]: ifp %s cmd 0x%08lx (%c%c [%lu] "
3626 			    "%c %lu) error %d\n", __func__,
3627 			    proc_name_address(p), proc_pid(p),
3628 			    ifname, cmd, (cmd & IOC_IN) ? 'I' : ' ',
3629 			    (cmd & IOC_OUT) ? 'O' : ' ', IOCPARM_LEN(cmd),
3630 			    (char)IOCGROUP(cmd), cmd & 0xff, error);
3631 		} else if (if_verbose > 1) {
3632 			printf("%s[%s,%d]: ifp %s cmd 0x%08lx (%c%c [%lu] "
3633 			    "%c %lu) OK\n", __func__,
3634 			    proc_name_address(p), proc_pid(p),
3635 			    ifname, cmd, (cmd & IOC_IN) ? 'I' : ' ',
3636 			    (cmd & IOC_OUT) ? 'O' : ' ', IOCPARM_LEN(cmd),
3637 			    (char)IOCGROUP(cmd), cmd & 0xff);
3638 		}
3639 	}
3640 
3641 	if (ifp != NULL) {
3642 		ifnet_decr_iorefcnt(ifp);
3643 	}
3644 	return error;
3645 }
3646 
3647 static __attribute__((noinline)) int
ifioctl_ifreq(struct socket * so,u_long cmd,struct ifreq * ifr,struct proc * p)3648 ifioctl_ifreq(struct socket *so, u_long cmd, struct ifreq *ifr, struct proc *p)
3649 {
3650 	struct ifnet *ifp;
3651 	u_long ocmd = cmd;
3652 	int error = 0;
3653 	struct kev_msg ev_msg;
3654 	struct net_event_data ev_data;
3655 
3656 	bzero(&ev_data, sizeof(struct net_event_data));
3657 	bzero(&ev_msg, sizeof(struct kev_msg));
3658 
3659 	switch (cmd) {
3660 	case SIOCIFCREATE:
3661 	case SIOCIFCREATE2:
3662 		error = proc_suser(p);
3663 		if (error) {
3664 			return error;
3665 		}
3666 		return if_clone_create(ifr->ifr_name, sizeof(ifr->ifr_name),
3667 		           cmd == SIOCIFCREATE2 ? ifr->ifr_data : NULL);
3668 	case SIOCIFDESTROY:
3669 		error = proc_suser(p);
3670 		if (error) {
3671 			return error;
3672 		}
3673 		return if_clone_destroy(ifr->ifr_name);
3674 	}
3675 
3676 	/*
3677 	 * ioctls which require ifp.  Note that we acquire dlil_ifnet_lock
3678 	 * here to ensure that the ifnet, if found, has been fully attached.
3679 	 */
3680 	dlil_if_lock();
3681 	ifp = ifunit(ifr->ifr_name);
3682 	dlil_if_unlock();
3683 
3684 	if (ifp == NULL) {
3685 		return ENXIO;
3686 	}
3687 
3688 	switch (cmd) {
3689 	case SIOCGIFFLAGS:
3690 		ifnet_lock_shared(ifp);
3691 		ifr->ifr_flags = ifp->if_flags;
3692 		ifnet_lock_done(ifp);
3693 		break;
3694 
3695 	case SIOCGIFEFLAGS:
3696 		ifnet_lock_shared(ifp);
3697 		ifr->ifr_eflags = ifp->if_eflags;
3698 		ifnet_lock_done(ifp);
3699 		break;
3700 
3701 	case SIOCGIFXFLAGS:
3702 		ifnet_lock_shared(ifp);
3703 		ifr->ifr_xflags = ifp->if_xflags;
3704 		ifnet_lock_done(ifp);
3705 		break;
3706 
3707 	case SIOCGIFCAP:
3708 		ifnet_lock_shared(ifp);
3709 		ifr->ifr_reqcap = ifp->if_capabilities;
3710 		ifr->ifr_curcap = ifp->if_capenable;
3711 		ifnet_lock_done(ifp);
3712 		break;
3713 
3714 	case SIOCGIFMETRIC:
3715 		ifnet_lock_shared(ifp);
3716 		ifr->ifr_metric = ifp->if_metric;
3717 		ifnet_lock_done(ifp);
3718 		break;
3719 
3720 	case SIOCGIFMTU:
3721 		ifnet_lock_shared(ifp);
3722 		ifr->ifr_mtu = ifp->if_mtu;
3723 		ifnet_lock_done(ifp);
3724 		break;
3725 
3726 	case SIOCGIFPHYS:
3727 		ifnet_lock_shared(ifp);
3728 		ifr->ifr_phys = ifp->if_physical;
3729 		ifnet_lock_done(ifp);
3730 		break;
3731 
3732 	case SIOCSIFFLAGS:
3733 		error = proc_suser(p);
3734 		if (error != 0) {
3735 			break;
3736 		}
3737 
3738 		(void) ifnet_set_flags(ifp, ifr->ifr_flags,
3739 		    (u_int16_t)~IFF_CANTCHANGE);
3740 
3741 		/*
3742 		 * Note that we intentionally ignore any error from below
3743 		 * for the SIOCSIFFLAGS case.
3744 		 */
3745 		(void) ifnet_ioctl(ifp, SOCK_DOM(so), cmd, (caddr_t)ifr);
3746 
3747 		/*
3748 		 * Send the event even upon error from the driver because
3749 		 * we changed the flags.
3750 		 */
3751 		dlil_post_sifflags_msg(ifp);
3752 
3753 		ifnet_touch_lastchange(ifp);
3754 		break;
3755 
3756 	case SIOCSIFCAP:
3757 		error = proc_suser(p);
3758 		if (error != 0) {
3759 			break;
3760 		}
3761 
3762 		if ((ifr->ifr_reqcap & ~ifp->if_capabilities)) {
3763 			error = EINVAL;
3764 			break;
3765 		}
3766 		error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd, (caddr_t)ifr);
3767 
3768 		ifnet_touch_lastchange(ifp);
3769 		break;
3770 
3771 	case SIOCSIFMETRIC:
3772 		error = proc_suser(p);
3773 		if (error != 0) {
3774 			break;
3775 		}
3776 
3777 		ifp->if_metric = ifr->ifr_metric;
3778 
3779 		ev_msg.vendor_code    = KEV_VENDOR_APPLE;
3780 		ev_msg.kev_class      = KEV_NETWORK_CLASS;
3781 		ev_msg.kev_subclass   = KEV_DL_SUBCLASS;
3782 
3783 		ev_msg.event_code = KEV_DL_SIFMETRICS;
3784 		strlcpy(&ev_data.if_name[0], ifp->if_name, IFNAMSIZ);
3785 		ev_data.if_family = ifp->if_family;
3786 		ev_data.if_unit   = (u_int32_t) ifp->if_unit;
3787 		ev_msg.dv[0].data_length = sizeof(struct net_event_data);
3788 		ev_msg.dv[0].data_ptr    = &ev_data;
3789 
3790 		ev_msg.dv[1].data_length = 0;
3791 		dlil_post_complete_msg(ifp, &ev_msg);
3792 
3793 		ifnet_touch_lastchange(ifp);
3794 		break;
3795 
3796 	case SIOCSIFPHYS:
3797 		error = proc_suser(p);
3798 		if (error != 0) {
3799 			break;
3800 		}
3801 
3802 		error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd, (caddr_t)ifr);
3803 		if (error != 0) {
3804 			break;
3805 		}
3806 
3807 		ev_msg.vendor_code    = KEV_VENDOR_APPLE;
3808 		ev_msg.kev_class      = KEV_NETWORK_CLASS;
3809 		ev_msg.kev_subclass   = KEV_DL_SUBCLASS;
3810 
3811 		ev_msg.event_code = KEV_DL_SIFPHYS;
3812 		strlcpy(&ev_data.if_name[0], ifp->if_name, IFNAMSIZ);
3813 		ev_data.if_family = ifp->if_family;
3814 		ev_data.if_unit   = (u_int32_t) ifp->if_unit;
3815 		ev_msg.dv[0].data_length = sizeof(struct net_event_data);
3816 		ev_msg.dv[0].data_ptr    = &ev_data;
3817 		ev_msg.dv[1].data_length = 0;
3818 		dlil_post_complete_msg(ifp, &ev_msg);
3819 
3820 		ifnet_touch_lastchange(ifp);
3821 		break;
3822 
3823 	case SIOCSIFMTU: {
3824 		u_int32_t oldmtu = ifp->if_mtu;
3825 		struct ifclassq *ifq = ifp->if_snd;
3826 
3827 		ASSERT(ifq != NULL);
3828 		error = proc_suser(p);
3829 		if (error != 0) {
3830 			break;
3831 		}
3832 
3833 		if (ifp->if_ioctl == NULL) {
3834 			error = EOPNOTSUPP;
3835 			break;
3836 		}
3837 		if (ifr->ifr_mtu < IF_MINMTU || ifr->ifr_mtu > IF_MAXMTU) {
3838 			error = EINVAL;
3839 			break;
3840 		}
3841 		error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd, (caddr_t)ifr);
3842 		if (error != 0) {
3843 			break;
3844 		}
3845 
3846 		ev_msg.vendor_code    = KEV_VENDOR_APPLE;
3847 		ev_msg.kev_class      = KEV_NETWORK_CLASS;
3848 		ev_msg.kev_subclass   = KEV_DL_SUBCLASS;
3849 
3850 		ev_msg.event_code = KEV_DL_SIFMTU;
3851 		strlcpy(&ev_data.if_name[0], ifp->if_name, IFNAMSIZ);
3852 		ev_data.if_family = ifp->if_family;
3853 		ev_data.if_unit   = (u_int32_t) ifp->if_unit;
3854 		ev_msg.dv[0].data_length = sizeof(struct net_event_data);
3855 		ev_msg.dv[0].data_ptr    = &ev_data;
3856 		ev_msg.dv[1].data_length = 0;
3857 		dlil_post_complete_msg(ifp, &ev_msg);
3858 
3859 		ifnet_touch_lastchange(ifp);
3860 		rt_ifmsg(ifp);
3861 
3862 		/*
3863 		 * If the link MTU changed, do network layer specific procedure
3864 		 * and update all route entries associated with the interface,
3865 		 * so that their MTU metric gets updated.
3866 		 */
3867 		if (ifp->if_mtu != oldmtu) {
3868 			if_rtmtu_update(ifp);
3869 			nd6_setmtu(ifp);
3870 			/* Inform all transmit queues about the new MTU */
3871 			IFCQ_LOCK(ifq);
3872 			ifnet_update_sndq(ifq, CLASSQ_EV_LINK_MTU);
3873 			IFCQ_UNLOCK(ifq);
3874 		}
3875 		break;
3876 	}
3877 
3878 	case SIOCADDMULTI:
3879 	case SIOCDELMULTI:
3880 		error = proc_suser(p);
3881 		if (error != 0) {
3882 			break;
3883 		}
3884 
3885 		/* Don't allow group membership on non-multicast interfaces. */
3886 		if ((ifp->if_flags & IFF_MULTICAST) == 0) {
3887 			error = EOPNOTSUPP;
3888 			break;
3889 		}
3890 
3891 		/* Don't let users screw up protocols' entries. */
3892 		if (ifr->ifr_addr.sa_family != AF_UNSPEC &&
3893 		    ifr->ifr_addr.sa_family != AF_LINK) {
3894 			error = EINVAL;
3895 			break;
3896 		}
3897 		if (ifr->ifr_addr.sa_len > sizeof(struct sockaddr)) {
3898 			ifr->ifr_addr.sa_len = sizeof(struct sockaddr);
3899 		}
3900 
3901 		/*
3902 		 * User is permitted to anonymously join a particular link
3903 		 * multicast group via SIOCADDMULTI.  Subsequent join requested
3904 		 * for the same record which has an outstanding refcnt from a
3905 		 * past if_addmulti_anon() will not result in EADDRINUSE error
3906 		 * (unlike other BSDs.)  Anonymously leaving a group is also
3907 		 * allowed only as long as there is an outstanding refcnt held
3908 		 * by a previous anonymous request, or else ENOENT (even if the
3909 		 * link-layer multicast membership exists for a network-layer
3910 		 * membership.)
3911 		 */
3912 		if (cmd == SIOCADDMULTI) {
3913 			error = if_addmulti_anon(ifp, &ifr->ifr_addr, NULL);
3914 			ev_msg.event_code = KEV_DL_ADDMULTI;
3915 		} else {
3916 			error = if_delmulti_anon(ifp, &ifr->ifr_addr);
3917 			ev_msg.event_code = KEV_DL_DELMULTI;
3918 		}
3919 		if (error != 0) {
3920 			break;
3921 		}
3922 
3923 		ev_msg.vendor_code    = KEV_VENDOR_APPLE;
3924 		ev_msg.kev_class      = KEV_NETWORK_CLASS;
3925 		ev_msg.kev_subclass   = KEV_DL_SUBCLASS;
3926 		strlcpy(&ev_data.if_name[0], ifp->if_name, IFNAMSIZ);
3927 
3928 		ev_data.if_family = ifp->if_family;
3929 		ev_data.if_unit   = (u_int32_t) ifp->if_unit;
3930 		ev_msg.dv[0].data_length = sizeof(struct net_event_data);
3931 		ev_msg.dv[0].data_ptr    = &ev_data;
3932 		ev_msg.dv[1].data_length = 0;
3933 		dlil_post_complete_msg(ifp, &ev_msg);
3934 
3935 		ifnet_touch_lastchange(ifp);
3936 		break;
3937 
3938 	case SIOCSIFMEDIA:
3939 		error = proc_suser(p);
3940 		if (error != 0) {
3941 			break;
3942 		}
3943 		/*
3944 		 * Silently ignore setting IFM_OTHER
3945 		 */
3946 		if (ifr->ifr_media == IFM_OTHER) {
3947 			os_log_info(OS_LOG_DEFAULT,
3948 			    "%s: %s SIOCSIFMEDIA ignore IFM_OTHER",
3949 			    __func__, ifp->if_xname);
3950 			error = 0;
3951 			break;
3952 		}
3953 		error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd, (caddr_t)ifr);
3954 		if (error != 0) {
3955 			break;
3956 		}
3957 		ifnet_touch_lastchange(ifp);
3958 		break;
3959 
3960 	case SIOCDIFPHYADDR:
3961 	case SIOCSIFGENERIC:
3962 	case SIOCSIFLLADDR:
3963 	case SIOCSIFALTMTU:
3964 	case SIOCSIFVLAN:
3965 	case SIOCSIFBOND:
3966 		error = proc_suser(p);
3967 		if (error != 0) {
3968 			break;
3969 		}
3970 
3971 		error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd, (caddr_t)ifr);
3972 		if (error != 0) {
3973 			break;
3974 		}
3975 
3976 		ifnet_touch_lastchange(ifp);
3977 		break;
3978 
3979 	case SIOCGIFLLADDR: {
3980 		struct sockaddr_dl *sdl = SDL(ifp->if_lladdr->ifa_addr);
3981 
3982 		if (sdl->sdl_alen == 0) {
3983 			error = EADDRNOTAVAIL;
3984 			break;
3985 		}
3986 		/* If larger than 14-bytes we'll need another mechanism */
3987 		if (sdl->sdl_alen > sizeof(ifr->ifr_addr.sa_data)) {
3988 			error = EMSGSIZE;
3989 			break;
3990 		}
3991 		/* Follow the same convention used by SIOCSIFLLADDR */
3992 		bzero(&ifr->ifr_addr, sizeof(ifr->ifr_addr));
3993 		ifr->ifr_addr.sa_family = AF_LINK;
3994 		ifr->ifr_addr.sa_len = sdl->sdl_alen;
3995 		error = ifnet_guarded_lladdr_copy_bytes(ifp,
3996 		    &ifr->ifr_addr.sa_data, sdl->sdl_alen);
3997 		break;
3998 	}
3999 
4000 	case SIOCGIFTYPE:
4001 		ifr->ifr_type.ift_type = ifp->if_type;
4002 		ifr->ifr_type.ift_family = ifp->if_family;
4003 		ifr->ifr_type.ift_subfamily = ifp->if_subfamily;
4004 		break;
4005 
4006 	case SIOCGIFFUNCTIONALTYPE:
4007 		ifr->ifr_functional_type = if_functional_type(ifp, FALSE);
4008 		break;
4009 
4010 	case SIOCGIFPSRCADDR:
4011 	case SIOCGIFPDSTADDR:
4012 	case SIOCGIFGENERIC:
4013 	case SIOCGIFDEVMTU:
4014 	case SIOCGIFVLAN:
4015 	case SIOCGIFBOND:
4016 		error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd, (caddr_t)ifr);
4017 		break;
4018 
4019 	case SIOCGIFWAKEFLAGS:
4020 		ifnet_lock_shared(ifp);
4021 		ifr->ifr_wake_flags = ifnet_get_wake_flags(ifp);
4022 		ifnet_lock_done(ifp);
4023 		break;
4024 
4025 	case SIOCGIFGETRTREFCNT:
4026 		ifnet_lock_shared(ifp);
4027 		ifr->ifr_route_refcnt = ifp->if_route_refcnt;
4028 		ifnet_lock_done(ifp);
4029 		break;
4030 
4031 	case SIOCSIFOPPORTUNISTIC:
4032 	case SIOCGIFOPPORTUNISTIC:
4033 		error = ifnet_getset_opportunistic(ifp, cmd, ifr, p);
4034 		break;
4035 
4036 	case SIOCGIFLINKQUALITYMETRIC:
4037 		ifnet_lock_shared(ifp);
4038 		if ((ifp->if_interface_state.valid_bitmask &
4039 		    IF_INTERFACE_STATE_LQM_STATE_VALID)) {
4040 			ifr->ifr_link_quality_metric =
4041 			    ifp->if_interface_state.lqm_state;
4042 		} else if (IF_FULLY_ATTACHED(ifp)) {
4043 			ifr->ifr_link_quality_metric =
4044 			    IFNET_LQM_THRESH_UNKNOWN;
4045 		} else {
4046 			ifr->ifr_link_quality_metric =
4047 			    IFNET_LQM_THRESH_OFF;
4048 		}
4049 		ifnet_lock_done(ifp);
4050 		break;
4051 
4052 	case SIOCSIFLINKQUALITYMETRIC:
4053 		if ((error = priv_check_cred(kauth_cred_get(),
4054 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4055 			return error;
4056 		}
4057 		error = ifnet_set_link_quality(ifp, ifr->ifr_link_quality_metric);
4058 		break;
4059 
4060 	case SIOCSIFLOG:
4061 	case SIOCGIFLOG:
4062 		error = ifnet_getset_log(ifp, cmd, ifr, p);
4063 		break;
4064 
4065 	case SIOCGIFDELEGATE:
4066 		ifnet_lock_shared(ifp);
4067 		ifr->ifr_delegated = ((ifp->if_delegated.ifp != NULL) ?
4068 		    ifp->if_delegated.ifp->if_index : 0);
4069 		ifnet_lock_done(ifp);
4070 		break;
4071 
4072 	case SIOCGIFEXPENSIVE:
4073 		ifnet_lock_shared(ifp);
4074 		if (ifp->if_eflags & IFEF_EXPENSIVE) {
4075 			ifr->ifr_expensive = 1;
4076 		} else {
4077 			ifr->ifr_expensive = 0;
4078 		}
4079 		ifnet_lock_done(ifp);
4080 		break;
4081 
4082 	case SIOCSIFEXPENSIVE:
4083 	{
4084 		struct ifnet *difp;
4085 
4086 		if ((error = priv_check_cred(kauth_cred_get(),
4087 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4088 			return error;
4089 		}
4090 		if (ifr->ifr_expensive) {
4091 			if_set_eflags(ifp, IFEF_EXPENSIVE);
4092 		} else {
4093 			if_clear_eflags(ifp, IFEF_EXPENSIVE);
4094 		}
4095 		ifnet_increment_generation(ifp);
4096 
4097 		/*
4098 		 * Update the expensive bit in the delegated interface
4099 		 * structure.
4100 		 */
4101 		ifnet_head_lock_shared();
4102 		TAILQ_FOREACH(difp, &ifnet_head, if_link) {
4103 			ifnet_lock_exclusive(difp);
4104 			if (difp->if_delegated.ifp == ifp) {
4105 				difp->if_delegated.expensive =
4106 				    ifp->if_eflags & IFEF_EXPENSIVE ? 1 : 0;
4107 				ifnet_increment_generation(difp);
4108 			}
4109 			ifnet_lock_done(difp);
4110 		}
4111 		ifnet_head_done();
4112 		necp_update_all_clients();
4113 		break;
4114 	}
4115 
4116 	case SIOCGIFCONSTRAINED:
4117 		if ((ifp->if_xflags & IFXF_CONSTRAINED) != 0) {
4118 			ifr->ifr_constrained = 1;
4119 		} else {
4120 			ifr->ifr_constrained = 0;
4121 		}
4122 		break;
4123 
4124 	case SIOCSIFCONSTRAINED:
4125 	{
4126 		struct ifnet *difp;
4127 
4128 		if ((error = priv_check_cred(kauth_cred_get(),
4129 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4130 			return error;
4131 		}
4132 		if (ifr->ifr_constrained) {
4133 			if_set_xflags(ifp, IFXF_CONSTRAINED);
4134 		} else {
4135 			if_clear_xflags(ifp, IFXF_CONSTRAINED);
4136 		}
4137 		ifnet_increment_generation(ifp);
4138 		/*
4139 		 * Update the constrained bit in the delegated interface
4140 		 * structure.
4141 		 */
4142 		ifnet_head_lock_shared();
4143 		TAILQ_FOREACH(difp, &ifnet_head, if_link) {
4144 			ifnet_lock_exclusive(difp);
4145 			if (difp->if_delegated.ifp == ifp) {
4146 				difp->if_delegated.constrained =
4147 				    ((ifp->if_xflags & IFXF_CONSTRAINED) != 0) ? 1 : 0;
4148 				ifnet_increment_generation(difp);
4149 			}
4150 			ifnet_lock_done(difp);
4151 		}
4152 		ifnet_head_done();
4153 		necp_update_all_clients();
4154 		break;
4155 	}
4156 
4157 	case SIOCSIFESTTHROUGHPUT:
4158 	{
4159 		bool changed = false;
4160 		struct ifnet *difp;
4161 
4162 		if ((error = priv_check_cred(kauth_cred_get(),
4163 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4164 			return error;
4165 		}
4166 		ifnet_lock_exclusive(ifp);
4167 		changed = (ifp->if_estimated_up_bucket != ifr->ifr_estimated_throughput.up_bucket) ||
4168 		    (ifp->if_estimated_down_bucket != ifr->ifr_estimated_throughput.down_bucket);
4169 		ifp->if_estimated_up_bucket = ifr->ifr_estimated_throughput.up_bucket;
4170 		ifp->if_estimated_down_bucket = ifr->ifr_estimated_throughput.down_bucket;
4171 		if (changed) {
4172 			ifnet_increment_generation(ifp);
4173 		}
4174 		ifnet_lock_done(ifp);
4175 		os_log_info(OS_LOG_DEFAULT,
4176 		    "SIOCSIFESTTHROUGHPUT %s%s up: %u, down: %u",
4177 		    ifp->if_name, changed ? " changed" : "",
4178 		    ifp->if_estimated_up_bucket,
4179 		    ifp->if_estimated_down_bucket);
4180 		if (changed) {
4181 			/*
4182 			 * Update the generation on delegated interfaces.
4183 			 */
4184 			ifnet_head_lock_shared();
4185 			TAILQ_FOREACH(difp, &ifnet_head, if_link) {
4186 				ifnet_lock_exclusive(difp);
4187 				if (difp->if_delegated.ifp == ifp) {
4188 					ifnet_increment_generation(difp);
4189 				}
4190 				ifnet_lock_done(difp);
4191 			}
4192 			ifnet_head_done();
4193 			necp_update_all_clients();
4194 		}
4195 		break;
4196 	}
4197 
4198 	case SIOCSIFRADIODETAILS:
4199 	{
4200 		bool changed = false;
4201 		struct ifnet *difp;
4202 
4203 		if ((error = priv_check_cred(kauth_cred_get(),
4204 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4205 			return error;
4206 		}
4207 		ifnet_lock_exclusive(ifp);
4208 		changed = ifp->if_radio_type != ifr->ifr_radio_details.technology ||
4209 		    ifp->if_radio_channel != ifr->ifr_radio_details.channel;
4210 		ifp->if_radio_type = ifr->ifr_radio_details.technology;
4211 		ifp->if_radio_channel = ifr->ifr_radio_details.channel;
4212 		ifnet_lock_done(ifp);
4213 		os_log_info(OS_LOG_DEFAULT,
4214 		    "SIOCSIFRADIODETAILS %s%s technology: %u, channel: %u",
4215 		    ifp->if_name, changed ? " changed" : "",
4216 		    ifr->ifr_radio_details.technology,
4217 		    ifr->ifr_radio_details.channel);
4218 		if (changed) {
4219 			ifnet_increment_generation(ifp);
4220 			/*
4221 			 * Update the generation on delegated interfaces.
4222 			 */
4223 			ifnet_head_lock_shared();
4224 			TAILQ_FOREACH(difp, &ifnet_head, if_link) {
4225 				ifnet_lock_exclusive(difp);
4226 				if (difp->if_delegated.ifp == ifp) {
4227 					ifnet_increment_generation(difp);
4228 				}
4229 				ifnet_lock_done(difp);
4230 			}
4231 			ifnet_head_done();
4232 			necp_update_all_clients();
4233 		}
4234 		break;
4235 	}
4236 
4237 	case SIOCGIF2KCL:
4238 		ifnet_lock_shared(ifp);
4239 		if (ifp->if_eflags & IFEF_2KCL) {
4240 			ifr->ifr_2kcl = 1;
4241 		} else {
4242 			ifr->ifr_2kcl = 0;
4243 		}
4244 		ifnet_lock_done(ifp);
4245 		break;
4246 
4247 	case SIOCSIF2KCL:
4248 		if ((error = priv_check_cred(kauth_cred_get(),
4249 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4250 			return error;
4251 		}
4252 		if (ifr->ifr_2kcl) {
4253 			if_set_eflags(ifp, IFEF_2KCL);
4254 		} else {
4255 			if_clear_eflags(ifp, IFEF_2KCL);
4256 		}
4257 		break;
4258 	case SIOCGSTARTDELAY:
4259 		ifnet_lock_shared(ifp);
4260 		if (ifp->if_eflags & IFEF_ENQUEUE_MULTI) {
4261 			ifr->ifr_start_delay_qlen =
4262 			    ifp->if_start_delay_qlen;
4263 			ifr->ifr_start_delay_timeout =
4264 			    ifp->if_start_delay_timeout;
4265 		} else {
4266 			ifr->ifr_start_delay_qlen = 0;
4267 			ifr->ifr_start_delay_timeout = 0;
4268 		}
4269 		ifnet_lock_done(ifp);
4270 		break;
4271 	case SIOCSIFDSTADDR:
4272 	case SIOCSIFADDR:
4273 	case SIOCSIFBRDADDR:
4274 	case SIOCSIFNETMASK:
4275 	case OSIOCGIFADDR:
4276 	case OSIOCGIFDSTADDR:
4277 	case OSIOCGIFBRDADDR:
4278 	case OSIOCGIFNETMASK:
4279 	case SIOCSIFKPI:
4280 		VERIFY(so->so_proto != NULL);
4281 
4282 		if (cmd == SIOCSIFDSTADDR || cmd == SIOCSIFADDR ||
4283 		    cmd == SIOCSIFBRDADDR || cmd == SIOCSIFNETMASK) {
4284 #if BYTE_ORDER != BIG_ENDIAN
4285 			if (ifr->ifr_addr.sa_family == 0 &&
4286 			    ifr->ifr_addr.sa_len < 16) {
4287 				ifr->ifr_addr.sa_family = ifr->ifr_addr.sa_len;
4288 				ifr->ifr_addr.sa_len = 16;
4289 			}
4290 #else
4291 			if (ifr->ifr_addr.sa_len == 0) {
4292 				ifr->ifr_addr.sa_len = 16;
4293 			}
4294 #endif
4295 		} else if (cmd == OSIOCGIFADDR) {
4296 			cmd = SIOCGIFADDR;      /* struct ifreq */
4297 		} else if (cmd == OSIOCGIFDSTADDR) {
4298 			cmd = SIOCGIFDSTADDR;   /* struct ifreq */
4299 		} else if (cmd == OSIOCGIFBRDADDR) {
4300 			cmd = SIOCGIFBRDADDR;   /* struct ifreq */
4301 		} else if (cmd == OSIOCGIFNETMASK) {
4302 			cmd = SIOCGIFNETMASK;   /* struct ifreq */
4303 		}
4304 
4305 		socket_lock(so, 1);
4306 		error = ((*so->so_proto->pr_usrreqs->pru_control)(so, cmd,
4307 		    (caddr_t)ifr, ifp, p));
4308 		socket_unlock(so, 1);
4309 
4310 		switch (ocmd) {
4311 		case OSIOCGIFADDR:
4312 		case OSIOCGIFDSTADDR:
4313 		case OSIOCGIFBRDADDR:
4314 		case OSIOCGIFNETMASK:
4315 			bcopy(&ifr->ifr_addr.sa_family, &ifr->ifr_addr,
4316 			    sizeof(u_short));
4317 		}
4318 
4319 		if (cmd == SIOCSIFKPI) {
4320 			int temperr = proc_suser(p);
4321 			if (temperr != 0) {
4322 				error = temperr;
4323 			}
4324 		}
4325 		// Don't allow to call SIOCSIFADDR and SIOCSIFDSTADDR
4326 		// with ifreq as the code expects ifaddr
4327 		if ((error == EOPNOTSUPP || error == ENOTSUP) &&
4328 		    !(cmd == SIOCSIFADDR || cmd == SIOCSIFDSTADDR)) {
4329 			error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd,
4330 			    (caddr_t)ifr);
4331 		}
4332 		break;
4333 
4334 	case SIOCGIFINTERFACESTATE:
4335 		if_get_state(ifp, &ifr->ifr_interface_state);
4336 		break;
4337 
4338 	case SIOCSIFINTERFACESTATE:
4339 		if ((error = priv_check_cred(kauth_cred_get(),
4340 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4341 			return error;
4342 		}
4343 
4344 		error = if_state_update(ifp, &ifr->ifr_interface_state);
4345 
4346 		break;
4347 	case SIOCSIFPROBECONNECTIVITY:
4348 		if ((error = priv_check_cred(kauth_cred_get(),
4349 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4350 			return error;
4351 		}
4352 		error = if_probe_connectivity(ifp,
4353 		    ifr->ifr_probe_connectivity);
4354 		break;
4355 	case SIOCGIFPROBECONNECTIVITY:
4356 		if ((error = priv_check_cred(kauth_cred_get(),
4357 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4358 			return error;
4359 		}
4360 		if (ifp->if_eflags & IFEF_PROBE_CONNECTIVITY) {
4361 			ifr->ifr_probe_connectivity = 1;
4362 		} else {
4363 			ifr->ifr_probe_connectivity = 0;
4364 		}
4365 		break;
4366 	case SIOCGECNMODE:
4367 		if ((ifp->if_eflags & (IFEF_ECN_ENABLE | IFEF_ECN_DISABLE)) ==
4368 		    IFEF_ECN_ENABLE) {
4369 			ifr->ifr_ecn_mode = IFRTYPE_ECN_ENABLE;
4370 		} else if ((ifp->if_eflags & (IFEF_ECN_ENABLE | IFEF_ECN_DISABLE)) ==
4371 		    IFEF_ECN_DISABLE) {
4372 			ifr->ifr_ecn_mode = IFRTYPE_ECN_DISABLE;
4373 		} else {
4374 			ifr->ifr_ecn_mode = IFRTYPE_ECN_DEFAULT;
4375 		}
4376 		break;
4377 	case SIOCSECNMODE:
4378 		if ((error = priv_check_cred(kauth_cred_get(),
4379 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4380 			return error;
4381 		}
4382 		if (ifr->ifr_ecn_mode == IFRTYPE_ECN_DEFAULT) {
4383 			if_clear_eflags(ifp, IFEF_ECN_ENABLE | IFEF_ECN_DISABLE);
4384 		} else if (ifr->ifr_ecn_mode == IFRTYPE_ECN_ENABLE) {
4385 			if_set_eflags(ifp, IFEF_ECN_ENABLE);
4386 			if_clear_eflags(ifp, IFEF_ECN_DISABLE);
4387 		} else if (ifr->ifr_ecn_mode == IFRTYPE_ECN_DISABLE) {
4388 			if_set_eflags(ifp, IFEF_ECN_DISABLE);
4389 			if_clear_eflags(ifp, IFEF_ECN_ENABLE);
4390 		} else {
4391 			error = EINVAL;
4392 		}
4393 		break;
4394 
4395 	case SIOCSIFTIMESTAMPENABLE:
4396 	case SIOCSIFTIMESTAMPDISABLE:
4397 		error = proc_suser(p);
4398 		if (error != 0) {
4399 			break;
4400 		}
4401 
4402 		if ((cmd == SIOCSIFTIMESTAMPENABLE &&
4403 		    (ifp->if_xflags & IFXF_TIMESTAMP_ENABLED) != 0) ||
4404 		    (cmd == SIOCSIFTIMESTAMPDISABLE &&
4405 		    (ifp->if_xflags & IFXF_TIMESTAMP_ENABLED) == 0)) {
4406 			break;
4407 		}
4408 		if (cmd == SIOCSIFTIMESTAMPENABLE) {
4409 			if_set_xflags(ifp, IFXF_TIMESTAMP_ENABLED);
4410 		} else {
4411 			if_clear_xflags(ifp, IFXF_TIMESTAMP_ENABLED);
4412 		}
4413 		/*
4414 		 * Pass the setting to the interface if it supports either
4415 		 * software or hardware time stamping
4416 		 */
4417 		if (ifp->if_capabilities & (IFCAP_HW_TIMESTAMP |
4418 		    IFCAP_SW_TIMESTAMP)) {
4419 			error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd,
4420 			    (caddr_t)ifr);
4421 		}
4422 		break;
4423 	case SIOCGIFTIMESTAMPENABLED: {
4424 		if ((ifp->if_xflags & IFXF_TIMESTAMP_ENABLED) != 0) {
4425 			ifr->ifr_intval = 1;
4426 		} else {
4427 			ifr->ifr_intval = 0;
4428 		}
4429 		break;
4430 	}
4431 	case SIOCSQOSMARKINGMODE:
4432 		if ((error = priv_check_cred(kauth_cred_get(),
4433 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4434 			return error;
4435 		}
4436 		error = if_set_qosmarking_mode(ifp, ifr->ifr_qosmarking_mode);
4437 		break;
4438 
4439 	case SIOCGQOSMARKINGMODE:
4440 		ifr->ifr_qosmarking_mode = ifp->if_qosmarking_mode;
4441 		break;
4442 
4443 	case SIOCSQOSMARKINGENABLED:
4444 		if ((error = priv_check_cred(kauth_cred_get(),
4445 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4446 			return error;
4447 		}
4448 		if (ifr->ifr_qosmarking_enabled != 0) {
4449 			if_set_eflags(ifp, IFEF_QOSMARKING_ENABLED);
4450 		} else {
4451 			if_clear_eflags(ifp, IFEF_QOSMARKING_ENABLED);
4452 		}
4453 		break;
4454 
4455 	case SIOCGQOSMARKINGENABLED:
4456 		ifr->ifr_qosmarking_enabled =
4457 		    ((ifp->if_eflags & IFEF_QOSMARKING_ENABLED) != 0) ? 1 : 0;
4458 		break;
4459 
4460 	case SIOCSIFDISABLEOUTPUT:
4461 #if (DEBUG || DEVELOPMENT)
4462 		if (ifr->ifr_disable_output == 1) {
4463 			error = ifnet_disable_output(ifp);
4464 		} else if (ifr->ifr_disable_output == 0) {
4465 			error = ifnet_enable_output(ifp);
4466 		} else {
4467 			error = EINVAL;
4468 		}
4469 #else
4470 		error = EINVAL;
4471 #endif /* (DEBUG || DEVELOPMENT) */
4472 		break;
4473 
4474 	case SIOCSIFSUBFAMILY:
4475 		if ((error = priv_check_cred(kauth_cred_get(),
4476 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4477 			return error;
4478 		}
4479 #if (DEBUG || DEVELOPMENT)
4480 		if (management_control_unrestricted) {
4481 			uint32_t subfamily = ifr->ifr_type.ift_subfamily;
4482 
4483 			if (subfamily == ifp->if_subfamily) {
4484 				break;
4485 			} else if (subfamily == IFRTYPE_SUBFAMILY_MANAGEMENT && ifp->if_subfamily == 0) {
4486 				ifp->if_subfamily = IFNET_SUBFAMILY_MANAGEMENT;
4487 				ifnet_set_management(ifp, true);
4488 				break;
4489 			} else if (subfamily == 0 && ifp->if_subfamily == IFNET_SUBFAMILY_MANAGEMENT) {
4490 				ifnet_set_management(ifp, false);
4491 				break;
4492 			}
4493 		}
4494 #endif /* (DEBUG || DEVELOPMENT) */
4495 		error = ifnet_ioctl(ifp, SOCK_DOM(so), cmd, (caddr_t)ifr);
4496 		break;
4497 
4498 	case SIOCSIFMANAGEMENT: {
4499 		if (management_control_unrestricted == false &&
4500 		    !IOCurrentTaskHasEntitlement(MANAGEMENT_CONTROL_ENTITLEMENT)) {
4501 			os_log(OS_LOG_DEFAULT, "ifioctl_req: cmd SIOCSIFMANAGEMENT on %s not allowed for %s:%u\n",
4502 			    ifp->if_xname, proc_name_address(p), proc_pid(p));
4503 			return EPERM;
4504 		}
4505 		if (ifr->ifr_intval != 0) {
4506 			ifnet_set_management(ifp, true);
4507 		} else {
4508 			if (ifp->if_subfamily == IFNET_SUBFAMILY_MANAGEMENT) {
4509 				os_log(OS_LOG_DEFAULT, "ifioctl_req: cmd SIOCSIFMANAGEMENT 0 not allowed on %s with subfamily management",
4510 				    ifp->if_xname);
4511 				return EPERM;
4512 			}
4513 			ifnet_set_management(ifp, false);
4514 		}
4515 		break;
4516 	}
4517 	case SIOCSIFLOWINTERNET:
4518 		if ((error = priv_check_cred(kauth_cred_get(),
4519 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4520 			return error;
4521 		}
4522 
4523 		if (ifr->ifr_low_internet & IFRTYPE_LOW_INTERNET_ENABLE_UL) {
4524 			if_set_xflags(ifp, IFXF_LOW_INTERNET_UL);
4525 		} else {
4526 			if_clear_xflags(ifp, IFXF_LOW_INTERNET_UL);
4527 		}
4528 		if (ifr->ifr_low_internet & IFRTYPE_LOW_INTERNET_ENABLE_DL) {
4529 			if_set_xflags(ifp, IFXF_LOW_INTERNET_DL);
4530 		} else {
4531 			if_clear_xflags(ifp, IFXF_LOW_INTERNET_DL);
4532 		}
4533 		break;
4534 	case SIOCGIFLOWINTERNET:
4535 		ifnet_lock_shared(ifp);
4536 		ifr->ifr_low_internet = 0;
4537 		if ((ifp->if_xflags & IFXF_LOW_INTERNET_UL) != 0) {
4538 			ifr->ifr_low_internet |=
4539 			    IFRTYPE_LOW_INTERNET_ENABLE_UL;
4540 		}
4541 		if ((ifp->if_xflags & IFXF_LOW_INTERNET_DL) != 0) {
4542 			ifr->ifr_low_internet |=
4543 			    IFRTYPE_LOW_INTERNET_ENABLE_DL;
4544 		}
4545 		ifnet_lock_done(ifp);
4546 		break;
4547 	case SIOCGIFLOWPOWER:
4548 		ifr->ifr_low_power_mode =
4549 		    ((ifp->if_xflags & IFXF_LOW_POWER) != 0);
4550 		break;
4551 	case SIOCSIFLOWPOWER:
4552 #if (DEVELOPMENT || DEBUG)
4553 		error = if_set_low_power(ifp, (ifr->ifr_low_power_mode != 0));
4554 #else /* DEVELOPMENT || DEBUG */
4555 		error = EOPNOTSUPP;
4556 #endif /* DEVELOPMENT || DEBUG */
4557 		break;
4558 
4559 	case SIOCGIFMPKLOG:
4560 		ifr->ifr_mpk_log = ((ifp->if_xflags & IFXF_MPK_LOG) != 0);
4561 		break;
4562 	case SIOCSIFMPKLOG:
4563 		if (ifr->ifr_mpk_log) {
4564 			if_set_xflags(ifp, IFXF_MPK_LOG);
4565 		} else {
4566 			if_clear_xflags(ifp, IFXF_MPK_LOG);
4567 		}
4568 		break;
4569 	case SIOCGIFNOACKPRIO:
4570 		if ((ifp->if_eflags & IFEF_NOACKPRI) != 0) {
4571 			ifr->ifr_noack_prio = 1;
4572 		} else {
4573 			ifr->ifr_noack_prio = 0;
4574 		}
4575 		break;
4576 
4577 	case SIOCSIFNOACKPRIO:
4578 		if ((error = priv_check_cred(kauth_cred_get(),
4579 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4580 			return error;
4581 		}
4582 		if (ifr->ifr_noack_prio) {
4583 			if_set_eflags(ifp, IFEF_NOACKPRI);
4584 		} else {
4585 			if_clear_eflags(ifp, IFEF_NOACKPRI);
4586 		}
4587 		break;
4588 
4589 	case SIOCSIFMARKWAKEPKT:
4590 #if (DEVELOPMENT || DEBUG)
4591 		if ((error = priv_check_cred(kauth_cred_get(),
4592 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4593 			return error;
4594 		}
4595 		if (net_wake_pkt_debug) {
4596 			os_log(OS_LOG_DEFAULT,
4597 			    "SIOCSIFMARKWAKEPKT %s", ifp->if_xname);
4598 		}
4599 		if (ifr->ifr_intval != 0) {
4600 			ifp->if_xflags |= IFXF_MARK_WAKE_PKT;
4601 		} else {
4602 			ifp->if_xflags &= ~IFXF_MARK_WAKE_PKT;
4603 		}
4604 #else /* DEVELOPMENT || DEBUG */
4605 		error = EOPNOTSUPP;
4606 #endif /* DEVELOPMENT || DEBUG */
4607 		break;
4608 
4609 	case SIOCSIFNOTRAFFICSHAPING:
4610 		if ((error = priv_check_cred(kauth_cred_get(),
4611 		    PRIV_NET_INTERFACE_CONTROL, 0)) != 0) {
4612 			return error;
4613 		}
4614 		os_log_info(OS_LOG_DEFAULT, "SIOCSIFNOTRAFFICSHAPING %s %d",
4615 		    ifp->if_xname, ifr->ifr_intval);
4616 		if (ifr->ifr_intval != 0) {
4617 			ifp->if_xflags |= IFXF_NO_TRAFFIC_SHAPING;
4618 		} else {
4619 			ifp->if_xflags &= ~IFXF_NO_TRAFFIC_SHAPING;
4620 		}
4621 		break;
4622 
4623 	case SIOCGIFNOTRAFFICSHAPING:
4624 		if ((ifp->if_xflags & IFXF_NO_TRAFFIC_SHAPING) != 0) {
4625 			ifr->ifr_intval = 1;
4626 		} else {
4627 			ifr->ifr_intval = 0;
4628 		}
4629 		break;
4630 
4631 	case SIOCGIFGENERATIONID:
4632 		ifr->ifr_creation_generation_id = ifp->if_creation_generation_id;
4633 		break;
4634 
4635 	default:
4636 		VERIFY(0);
4637 		/* NOTREACHED */
4638 	}
4639 
4640 	return error;
4641 }
4642 
4643 int
ifioctllocked(struct socket * so,u_long cmd,caddr_t data,struct proc * p)4644 ifioctllocked(struct socket *so, u_long cmd, caddr_t data, struct proc *p)
4645 {
4646 	int error;
4647 
4648 	socket_unlock(so, 0);
4649 	error = ifioctl(so, cmd, data, p);
4650 	socket_lock(so, 0);
4651 	return error;
4652 }
4653 
4654 /*
4655  * Set/clear promiscuous mode on interface ifp based on the truth value
4656  * of pswitch.  The calls are reference counted so that only the first
4657  * "on" request actually has an effect, as does the final "off" request.
4658  * Results are undefined if the "off" and "on" requests are not matched.
4659  */
4660 errno_t
ifnet_set_promiscuous(ifnet_t ifp,int pswitch)4661 ifnet_set_promiscuous(
4662 	ifnet_t ifp,
4663 	int pswitch)
4664 {
4665 	int error = 0;
4666 	int oldflags = 0;
4667 	int newflags = 0;
4668 
4669 	ifnet_lock_exclusive(ifp);
4670 	oldflags = ifp->if_flags;
4671 	ifp->if_pcount += pswitch ? 1 : -1;
4672 
4673 	if (ifp->if_pcount > 0) {
4674 		ifp->if_flags |= IFF_PROMISC;
4675 	} else {
4676 		ifp->if_flags &= ~IFF_PROMISC;
4677 	}
4678 
4679 	newflags = ifp->if_flags;
4680 	ifnet_lock_done(ifp);
4681 
4682 	if (newflags != oldflags && (newflags & IFF_UP) != 0) {
4683 		error = ifnet_ioctl(ifp, 0, SIOCSIFFLAGS, NULL);
4684 		if (error == 0) {
4685 			rt_ifmsg(ifp);
4686 		} else {
4687 			ifnet_lock_exclusive(ifp);
4688 			// revert the flags
4689 			ifp->if_pcount -= pswitch ? 1 : -1;
4690 			if (ifp->if_pcount > 0) {
4691 				ifp->if_flags |= IFF_PROMISC;
4692 			} else {
4693 				ifp->if_flags &= ~IFF_PROMISC;
4694 			}
4695 			ifnet_lock_done(ifp);
4696 		}
4697 	}
4698 
4699 	if (newflags != oldflags) {
4700 		log(LOG_INFO, "%s: promiscuous mode %s %s (%d)\n",
4701 		    if_name(ifp),
4702 		    (newflags & IFF_PROMISC) != 0 ? "enable" : "disable",
4703 		    error != 0 ? "failed" : "succeeded", error);
4704 	}
4705 	return error;
4706 }
4707 
4708 /*
4709  * Return interface configuration
4710  * of system.  List may be used
4711  * in later ioctl's (above) to get
4712  * other information.
4713  */
4714 /*ARGSUSED*/
4715 static int
ifconf(u_long cmd,user_addr_t ifrp,int * ret_space)4716 ifconf(u_long cmd, user_addr_t ifrp, int *ret_space)
4717 {
4718 	struct ifnet *ifp = NULL;
4719 	struct ifaddr *ifa;
4720 	struct ifreq ifr;
4721 	int error = 0;
4722 	size_t space;
4723 	net_thread_marks_t marks;
4724 
4725 	marks = net_thread_marks_push(NET_THREAD_CKREQ_LLADDR);
4726 
4727 	/*
4728 	 * Zero the ifr buffer to make sure we don't
4729 	 * disclose the contents of the stack.
4730 	 */
4731 	bzero(&ifr, sizeof(struct ifreq));
4732 
4733 	space = *ret_space;
4734 	ifnet_head_lock_shared();
4735 	for (ifp = ifnet_head.tqh_first; space > sizeof(ifr) &&
4736 	    ifp; ifp = ifp->if_link.tqe_next) {
4737 		char workbuf[64];
4738 		size_t ifnlen, addrs;
4739 
4740 		ifnlen = snprintf(workbuf, sizeof(workbuf),
4741 		    "%s", if_name(ifp));
4742 		if (ifnlen + 1 > sizeof(ifr.ifr_name)) {
4743 			error = ENAMETOOLONG;
4744 			break;
4745 		} else {
4746 			strlcpy(ifr.ifr_name, workbuf, IFNAMSIZ);
4747 		}
4748 
4749 		ifnet_lock_shared(ifp);
4750 
4751 		addrs = 0;
4752 		ifa = ifp->if_addrhead.tqh_first;
4753 		for (; space > sizeof(ifr) && ifa;
4754 		    ifa = ifa->ifa_link.tqe_next) {
4755 			struct sockaddr *sa;
4756 			union {
4757 				struct sockaddr sa;
4758 				struct sockaddr_dl sdl;
4759 				uint8_t buf[SOCK_MAXADDRLEN + 1];
4760 			} u;
4761 
4762 			/*
4763 			 * Make sure to accomodate the largest possible
4764 			 * size of SA(if_lladdr)->sa_len.
4765 			 */
4766 			_CASSERT(sizeof(u) == (SOCK_MAXADDRLEN + 1));
4767 
4768 			IFA_LOCK(ifa);
4769 			sa = ifa->ifa_addr;
4770 			addrs++;
4771 
4772 			if (ifa == ifp->if_lladdr) {
4773 				VERIFY(sa->sa_family == AF_LINK);
4774 				bcopy(sa, &u, sa->sa_len);
4775 				IFA_UNLOCK(ifa);
4776 				ifnet_guarded_lladdr_copy_bytes(ifp,
4777 				    LLADDR(&u.sdl), u.sdl.sdl_alen);
4778 				IFA_LOCK(ifa);
4779 				sa = &u.sa;
4780 			}
4781 
4782 			if (cmd == OSIOCGIFCONF32 || cmd == OSIOCGIFCONF64) {
4783 				struct osockaddr *osa =
4784 				    (struct osockaddr *)(void *)&ifr.ifr_addr;
4785 				ifr.ifr_addr = *sa;
4786 				osa->sa_family = sa->sa_family;
4787 				error = copyout((caddr_t)&ifr, ifrp,
4788 				    sizeof(ifr));
4789 				ifrp += sizeof(struct ifreq);
4790 			} else if (sa->sa_len <= sizeof(*sa)) {
4791 				ifr.ifr_addr = *sa;
4792 				error = copyout((caddr_t)&ifr, ifrp,
4793 				    sizeof(ifr));
4794 				ifrp += sizeof(struct ifreq);
4795 			} else {
4796 				if (space <
4797 				    sizeof(ifr) + sa->sa_len - sizeof(*sa)) {
4798 					IFA_UNLOCK(ifa);
4799 					break;
4800 				}
4801 				space -= sa->sa_len - sizeof(*sa);
4802 				error = copyout((caddr_t)&ifr, ifrp,
4803 				    sizeof(ifr.ifr_name));
4804 				if (error == 0) {
4805 					error = copyout((caddr_t)sa, (ifrp +
4806 					    offsetof(struct ifreq, ifr_addr)),
4807 					    sa->sa_len);
4808 				}
4809 				ifrp += (sa->sa_len + offsetof(struct ifreq,
4810 				    ifr_addr));
4811 			}
4812 			IFA_UNLOCK(ifa);
4813 			if (error) {
4814 				break;
4815 			}
4816 			space -= sizeof(ifr);
4817 		}
4818 		ifnet_lock_done(ifp);
4819 
4820 		if (error) {
4821 			break;
4822 		}
4823 		if (!addrs) {
4824 			bzero((caddr_t)&ifr.ifr_addr, sizeof(ifr.ifr_addr));
4825 			error = copyout((caddr_t)&ifr, ifrp, sizeof(ifr));
4826 			if (error) {
4827 				break;
4828 			}
4829 			space -= sizeof(ifr);
4830 			ifrp += sizeof(struct ifreq);
4831 		}
4832 	}
4833 	ifnet_head_done();
4834 	*ret_space -= space;
4835 	net_thread_marks_pop(marks);
4836 	return error;
4837 }
4838 
4839 static bool
set_allmulti(struct ifnet * ifp,bool enable)4840 set_allmulti(struct ifnet * ifp, bool enable)
4841 {
4842 	bool    changed = false;
4843 
4844 	ifnet_lock_exclusive(ifp);
4845 	if (enable) {
4846 		if (ifp->if_amcount++ == 0) {
4847 			ifp->if_flags |= IFF_ALLMULTI;
4848 			changed = true;
4849 		}
4850 	} else {
4851 		if (ifp->if_amcount > 1) {
4852 			ifp->if_amcount--;
4853 		} else {
4854 			ifp->if_amcount = 0;
4855 			ifp->if_flags &= ~IFF_ALLMULTI;
4856 			changed = true;
4857 		}
4858 	}
4859 	ifnet_lock_done(ifp);
4860 	return changed;
4861 }
4862 
4863 /*
4864  * Like ifnet_set_promiscuous(), but for all-multicast-reception mode.
4865  */
4866 int
if_allmulti(struct ifnet * ifp,int onswitch)4867 if_allmulti(struct ifnet *ifp, int onswitch)
4868 {
4869 	bool    enable = onswitch != 0;
4870 	int     error = 0;
4871 
4872 	if (set_allmulti(ifp, enable)) {
4873 		/* state change, tell the driver */
4874 		error = ifnet_ioctl(ifp, 0, SIOCSIFFLAGS, NULL);
4875 		log(LOG_INFO, "%s: %s allmulti %s (%d)\n",
4876 		    if_name(ifp),
4877 		    enable ? "enable" : "disable",
4878 		    error != 0 ? "failed" : "succeeded", error);
4879 		if (error == 0) {
4880 			rt_ifmsg(ifp);
4881 		} else {
4882 			/* restore the reference count, flags */
4883 			(void)set_allmulti(ifp, !enable);
4884 		}
4885 	}
4886 	return error;
4887 }
4888 
4889 static struct ifmultiaddr *
ifma_alloc(zalloc_flags_t how)4890 ifma_alloc(zalloc_flags_t how)
4891 {
4892 	struct ifmultiaddr *ifma;
4893 
4894 	ifma = zalloc_flags(ifma_zone, how | Z_ZERO);
4895 
4896 	if (ifma != NULL) {
4897 		lck_mtx_init(&ifma->ifma_lock, &ifa_mtx_grp, &ifa_mtx_attr);
4898 		ifma->ifma_debug |= IFD_ALLOC;
4899 		if (ifma_debug != 0) {
4900 			ifma->ifma_debug |= IFD_DEBUG;
4901 			ifma->ifma_trace = ifma_trace;
4902 		}
4903 	}
4904 	return ifma;
4905 }
4906 
4907 static void
ifma_free(struct ifmultiaddr * ifma)4908 ifma_free(struct ifmultiaddr *ifma)
4909 {
4910 	IFMA_LOCK(ifma);
4911 
4912 	if (ifma->ifma_protospec != NULL) {
4913 		panic("%s: Protospec not NULL for ifma=%p", __func__, ifma);
4914 		/* NOTREACHED */
4915 	} else if ((ifma->ifma_flags & IFMAF_ANONYMOUS) ||
4916 	    ifma->ifma_anoncnt != 0) {
4917 		panic("%s: Freeing ifma=%p with outstanding anon req",
4918 		    __func__, ifma);
4919 		/* NOTREACHED */
4920 	} else if (ifma->ifma_debug & IFD_ATTACHED) {
4921 		panic("%s: ifma=%p attached to ifma_ifp=%p is being freed",
4922 		    __func__, ifma, ifma->ifma_ifp);
4923 		/* NOTREACHED */
4924 	} else if (!(ifma->ifma_debug & IFD_ALLOC)) {
4925 		panic("%s: ifma %p cannot be freed", __func__, ifma);
4926 		/* NOTREACHED */
4927 	} else if (ifma->ifma_refcount != 0) {
4928 		panic("%s: non-zero refcount ifma=%p", __func__, ifma);
4929 		/* NOTREACHED */
4930 	} else if (ifma->ifma_reqcnt != 0) {
4931 		panic("%s: non-zero reqcnt ifma=%p", __func__, ifma);
4932 		/* NOTREACHED */
4933 	} else if (ifma->ifma_ifp != NULL) {
4934 		panic("%s: non-NULL ifma_ifp=%p for ifma=%p", __func__,
4935 		    ifma->ifma_ifp, ifma);
4936 		/* NOTREACHED */
4937 	} else if (ifma->ifma_ll != NULL) {
4938 		panic("%s: non-NULL ifma_ll=%p for ifma=%p", __func__,
4939 		    ifma->ifma_ll, ifma);
4940 		/* NOTREACHED */
4941 	}
4942 	ifma->ifma_debug &= ~IFD_ALLOC;
4943 	if ((ifma->ifma_debug & (IFD_DEBUG | IFD_TRASHED)) ==
4944 	    (IFD_DEBUG | IFD_TRASHED)) {
4945 		lck_mtx_lock(&ifma_trash_lock);
4946 		TAILQ_REMOVE(&ifma_trash_head, (struct ifmultiaddr_dbg *)ifma,
4947 		    ifma_trash_link);
4948 		lck_mtx_unlock(&ifma_trash_lock);
4949 		ifma->ifma_debug &= ~IFD_TRASHED;
4950 	}
4951 	IFMA_UNLOCK(ifma);
4952 
4953 	if (ifma->ifma_addr != NULL) {
4954 		kfree_data(ifma->ifma_addr, ifma->ifma_addr->sa_len);
4955 		ifma->ifma_addr = NULL;
4956 	}
4957 	lck_mtx_destroy(&ifma->ifma_lock, &ifa_mtx_grp);
4958 	zfree(ifma_zone, ifma);
4959 }
4960 
4961 static void
ifma_trace(struct ifmultiaddr * ifma,int refhold)4962 ifma_trace(struct ifmultiaddr *ifma, int refhold)
4963 {
4964 	struct ifmultiaddr_dbg *ifma_dbg = (struct ifmultiaddr_dbg *)ifma;
4965 	ctrace_t *tr;
4966 	u_int32_t idx;
4967 	u_int16_t *cnt;
4968 
4969 	if (!(ifma->ifma_debug & IFD_DEBUG)) {
4970 		panic("%s: ifma %p has no debug structure", __func__, ifma);
4971 		/* NOTREACHED */
4972 	}
4973 	if (refhold) {
4974 		cnt = &ifma_dbg->ifma_refhold_cnt;
4975 		tr = ifma_dbg->ifma_refhold;
4976 	} else {
4977 		cnt = &ifma_dbg->ifma_refrele_cnt;
4978 		tr = ifma_dbg->ifma_refrele;
4979 	}
4980 
4981 	idx = os_atomic_inc_orig(cnt, relaxed) % IFMA_TRACE_HIST_SIZE;
4982 	ctrace_record(&tr[idx]);
4983 }
4984 
4985 void
ifma_addref(struct ifmultiaddr * ifma,int locked)4986 ifma_addref(struct ifmultiaddr *ifma, int locked)
4987 {
4988 	if (!locked) {
4989 		IFMA_LOCK(ifma);
4990 	} else {
4991 		IFMA_LOCK_ASSERT_HELD(ifma);
4992 	}
4993 
4994 	if (++ifma->ifma_refcount == 0) {
4995 		panic("%s: ifma=%p wraparound refcnt", __func__, ifma);
4996 		/* NOTREACHED */
4997 	} else if (ifma->ifma_trace != NULL) {
4998 		(*ifma->ifma_trace)(ifma, TRUE);
4999 	}
5000 	if (!locked) {
5001 		IFMA_UNLOCK(ifma);
5002 	}
5003 }
5004 
5005 void
ifma_remref(struct ifmultiaddr * ifma)5006 ifma_remref(struct ifmultiaddr *ifma)
5007 {
5008 	struct ifmultiaddr *ll;
5009 
5010 	IFMA_LOCK(ifma);
5011 
5012 	if (ifma->ifma_refcount == 0) {
5013 		panic("%s: ifma=%p negative refcnt", __func__, ifma);
5014 		/* NOTREACHED */
5015 	} else if (ifma->ifma_trace != NULL) {
5016 		(*ifma->ifma_trace)(ifma, FALSE);
5017 	}
5018 
5019 	--ifma->ifma_refcount;
5020 	if (ifma->ifma_refcount > 0) {
5021 		IFMA_UNLOCK(ifma);
5022 		return;
5023 	}
5024 
5025 	ll = ifma->ifma_ll;
5026 	ifma->ifma_ifp = NULL;
5027 	ifma->ifma_ll = NULL;
5028 	IFMA_UNLOCK(ifma);
5029 	ifma_free(ifma);        /* deallocate it */
5030 
5031 	if (ll != NULL) {
5032 		IFMA_REMREF(ll);
5033 	}
5034 }
5035 
5036 static void
if_attach_ifma(struct ifnet * ifp,struct ifmultiaddr * ifma,int anon)5037 if_attach_ifma(struct ifnet *ifp, struct ifmultiaddr *ifma, int anon)
5038 {
5039 	ifnet_lock_assert(ifp, IFNET_LCK_ASSERT_EXCLUSIVE);
5040 	IFMA_LOCK_ASSERT_HELD(ifma);
5041 
5042 	if (ifma->ifma_ifp != ifp) {
5043 		panic("%s: Mismatch ifma_ifp=%p != ifp=%p", __func__,
5044 		    ifma->ifma_ifp, ifp);
5045 		/* NOTREACHED */
5046 	} else if (ifma->ifma_debug & IFD_ATTACHED) {
5047 		panic("%s: Attempt to attach an already attached ifma=%p",
5048 		    __func__, ifma);
5049 		/* NOTREACHED */
5050 	} else if (anon && (ifma->ifma_flags & IFMAF_ANONYMOUS)) {
5051 		panic("%s: ifma=%p unexpected IFMAF_ANONYMOUS", __func__, ifma);
5052 		/* NOTREACHED */
5053 	} else if (ifma->ifma_debug & IFD_TRASHED) {
5054 		panic("%s: Attempt to reattach a detached ifma=%p",
5055 		    __func__, ifma);
5056 		/* NOTREACHED */
5057 	}
5058 
5059 	ifma->ifma_reqcnt++;
5060 	VERIFY(ifma->ifma_reqcnt == 1);
5061 	IFMA_ADDREF_LOCKED(ifma);
5062 	ifma->ifma_debug |= IFD_ATTACHED;
5063 	if (anon) {
5064 		ifma->ifma_anoncnt++;
5065 		VERIFY(ifma->ifma_anoncnt == 1);
5066 		ifma->ifma_flags |= IFMAF_ANONYMOUS;
5067 	}
5068 
5069 	LIST_INSERT_HEAD(&ifp->if_multiaddrs, ifma, ifma_link);
5070 }
5071 
5072 static int
if_detach_ifma(struct ifnet * ifp,struct ifmultiaddr * ifma,int anon)5073 if_detach_ifma(struct ifnet *ifp, struct ifmultiaddr *ifma, int anon)
5074 {
5075 	ifnet_lock_assert(ifp, IFNET_LCK_ASSERT_EXCLUSIVE);
5076 	IFMA_LOCK_ASSERT_HELD(ifma);
5077 
5078 	if (ifma->ifma_reqcnt == 0) {
5079 		panic("%s: ifma=%p negative reqcnt", __func__, ifma);
5080 		/* NOTREACHED */
5081 	} else if (anon && !(ifma->ifma_flags & IFMAF_ANONYMOUS)) {
5082 		panic("%s: ifma=%p missing IFMAF_ANONYMOUS", __func__, ifma);
5083 		/* NOTREACHED */
5084 	} else if (anon && ifma->ifma_anoncnt == 0) {
5085 		panic("%s: ifma=%p negative anonreqcnt", __func__, ifma);
5086 		/* NOTREACHED */
5087 	} else if (ifma->ifma_ifp != ifp) {
5088 		panic("%s: Mismatch ifma_ifp=%p, ifp=%p", __func__,
5089 		    ifma->ifma_ifp, ifp);
5090 		/* NOTREACHED */
5091 	}
5092 
5093 	if (anon) {
5094 		--ifma->ifma_anoncnt;
5095 		if (ifma->ifma_anoncnt > 0) {
5096 			return 0;
5097 		}
5098 		ifma->ifma_flags &= ~IFMAF_ANONYMOUS;
5099 	}
5100 
5101 	--ifma->ifma_reqcnt;
5102 	if (ifma->ifma_reqcnt > 0) {
5103 		return 0;
5104 	}
5105 
5106 	if (ifma->ifma_protospec != NULL) {
5107 		panic("%s: Protospec not NULL for ifma=%p", __func__, ifma);
5108 		/* NOTREACHED */
5109 	} else if ((ifma->ifma_flags & IFMAF_ANONYMOUS) ||
5110 	    ifma->ifma_anoncnt != 0) {
5111 		panic("%s: Detaching ifma=%p with outstanding anon req",
5112 		    __func__, ifma);
5113 		/* NOTREACHED */
5114 	} else if (!(ifma->ifma_debug & IFD_ATTACHED)) {
5115 		panic("%s: Attempt to detach an unattached address ifma=%p",
5116 		    __func__, ifma);
5117 		/* NOTREACHED */
5118 	} else if (ifma->ifma_debug & IFD_TRASHED) {
5119 		panic("%s: ifma %p is already in trash list", __func__, ifma);
5120 		/* NOTREACHED */
5121 	}
5122 
5123 	/*
5124 	 * NOTE: Caller calls IFMA_REMREF
5125 	 */
5126 	ifma->ifma_debug &= ~IFD_ATTACHED;
5127 	LIST_REMOVE(ifma, ifma_link);
5128 	if (LIST_EMPTY(&ifp->if_multiaddrs)) {
5129 		ifp->if_updatemcasts = 0;
5130 	}
5131 
5132 	if (ifma->ifma_debug & IFD_DEBUG) {
5133 		/* Become a regular mutex, just in case */
5134 		IFMA_CONVERT_LOCK(ifma);
5135 		lck_mtx_lock(&ifma_trash_lock);
5136 		TAILQ_INSERT_TAIL(&ifma_trash_head,
5137 		    (struct ifmultiaddr_dbg *)ifma, ifma_trash_link);
5138 		lck_mtx_unlock(&ifma_trash_lock);
5139 		ifma->ifma_debug |= IFD_TRASHED;
5140 	}
5141 
5142 	return 1;
5143 }
5144 
5145 /*
5146  * Find an ifmultiaddr that matches a socket address on an interface.
5147  *
5148  * Caller is responsible for holding the ifnet_lock while calling
5149  * this function.
5150  */
5151 static int
if_addmulti_doesexist(struct ifnet * ifp,const struct sockaddr * sa,struct ifmultiaddr ** retifma,int anon)5152 if_addmulti_doesexist(struct ifnet *ifp, const struct sockaddr *sa,
5153     struct ifmultiaddr **retifma, int anon)
5154 {
5155 	struct ifmultiaddr *ifma;
5156 
5157 	for (ifma = LIST_FIRST(&ifp->if_multiaddrs); ifma != NULL;
5158 	    ifma = LIST_NEXT(ifma, ifma_link)) {
5159 		IFMA_LOCK_SPIN(ifma);
5160 		if (!sa_equal(sa, ifma->ifma_addr)) {
5161 			IFMA_UNLOCK(ifma);
5162 			continue;
5163 		}
5164 		if (anon) {
5165 			VERIFY(!(ifma->ifma_flags & IFMAF_ANONYMOUS) ||
5166 			    ifma->ifma_anoncnt != 0);
5167 			VERIFY((ifma->ifma_flags & IFMAF_ANONYMOUS) ||
5168 			    ifma->ifma_anoncnt == 0);
5169 			ifma->ifma_anoncnt++;
5170 			if (!(ifma->ifma_flags & IFMAF_ANONYMOUS)) {
5171 				VERIFY(ifma->ifma_anoncnt == 1);
5172 				ifma->ifma_flags |= IFMAF_ANONYMOUS;
5173 			}
5174 		}
5175 		if (!anon || ifma->ifma_anoncnt == 1) {
5176 			ifma->ifma_reqcnt++;
5177 			VERIFY(ifma->ifma_reqcnt > 1);
5178 		}
5179 		if (retifma != NULL) {
5180 			*retifma = ifma;
5181 			IFMA_ADDREF_LOCKED(ifma);
5182 		}
5183 		IFMA_UNLOCK(ifma);
5184 		return 0;
5185 	}
5186 	return ENOENT;
5187 }
5188 
5189 /*
5190  * Radar 3642395, make sure all multicasts are in a standard format.
5191  */
5192 static struct sockaddr *
copy_and_normalize(const struct sockaddr * original)5193 copy_and_normalize(const struct sockaddr *original)
5194 {
5195 	int                     alen = 0;
5196 	const u_char            *aptr = NULL;
5197 	struct sockaddr         *copy = NULL;
5198 	struct sockaddr_dl      *sdl_new = NULL;
5199 	int                     len = 0;
5200 
5201 	if (original->sa_family != AF_LINK &&
5202 	    original->sa_family != AF_UNSPEC) {
5203 		/* Just make a copy */
5204 		copy = (struct sockaddr *)kalloc_data(original->sa_len, Z_WAITOK);
5205 		if (copy != NULL) {
5206 			bcopy(original, copy, original->sa_len);
5207 		}
5208 		return copy;
5209 	}
5210 
5211 	switch (original->sa_family) {
5212 	case AF_LINK: {
5213 		const struct sockaddr_dl *sdl_original =
5214 		    (struct sockaddr_dl *)(uintptr_t)(size_t)original;
5215 
5216 		if (sdl_original->sdl_len < offsetof(struct sockaddr_dl, sdl_data)) {
5217 			return NULL;
5218 		}
5219 		if (sdl_original->sdl_nlen + sdl_original->sdl_alen +
5220 		    sdl_original->sdl_slen +
5221 		    offsetof(struct sockaddr_dl, sdl_data) >
5222 		    sdl_original->sdl_len) {
5223 			return NULL;
5224 		}
5225 
5226 		alen = sdl_original->sdl_alen;
5227 		aptr = CONST_LLADDR(sdl_original);
5228 	}
5229 	break;
5230 
5231 	case AF_UNSPEC: {
5232 		if (original->sa_len < ETHER_ADDR_LEN +
5233 		    offsetof(struct sockaddr, sa_data)) {
5234 			return NULL;
5235 		}
5236 
5237 		alen = ETHER_ADDR_LEN;
5238 		aptr = (const u_char *)original->sa_data;
5239 	}
5240 	break;
5241 	}
5242 
5243 	if (alen == 0 || aptr == NULL) {
5244 		return NULL;
5245 	}
5246 
5247 	len = alen + offsetof(struct sockaddr_dl, sdl_data);
5248 	sdl_new = (struct sockaddr_dl *)kalloc_data(len, Z_WAITOK | Z_ZERO);
5249 
5250 	if (sdl_new != NULL) {
5251 		sdl_new->sdl_len = (u_char)len;
5252 		sdl_new->sdl_family = AF_LINK;
5253 		sdl_new->sdl_alen = (u_char)alen;
5254 		bcopy(aptr, LLADDR(sdl_new), alen);
5255 	}
5256 
5257 	return (struct sockaddr *)sdl_new;
5258 }
5259 
5260 /*
5261  * Network-layer protocol domains which hold references to the underlying
5262  * link-layer record must use this routine.
5263  */
5264 int
if_addmulti(struct ifnet * ifp,const struct sockaddr * sa,struct ifmultiaddr ** retifma)5265 if_addmulti(struct ifnet *ifp, const struct sockaddr *sa,
5266     struct ifmultiaddr **retifma)
5267 {
5268 	return if_addmulti_common(ifp, sa, retifma, 0);
5269 }
5270 
5271 /*
5272  * Anything other than network-layer protocol domains which hold references
5273  * to the underlying link-layer record must use this routine: SIOCADDMULTI
5274  * ioctl, ifnet_add_multicast(), if_bond.
5275  */
5276 int
if_addmulti_anon(struct ifnet * ifp,const struct sockaddr * sa,struct ifmultiaddr ** retifma)5277 if_addmulti_anon(struct ifnet *ifp, const struct sockaddr *sa,
5278     struct ifmultiaddr **retifma)
5279 {
5280 	return if_addmulti_common(ifp, sa, retifma, 1);
5281 }
5282 
5283 /*
5284  * Register an additional multicast address with a network interface.
5285  *
5286  * - If the address is already present, bump the reference count on the
5287  *   address and return.
5288  * - If the address is not link-layer, look up a link layer address.
5289  * - Allocate address structures for one or both addresses, and attach to the
5290  *   multicast address list on the interface.  If automatically adding a link
5291  *   layer address, the protocol address will own a reference to the link
5292  *   layer address, to be freed when it is freed.
5293  * - Notify the network device driver of an addition to the multicast address
5294  *   list.
5295  *
5296  * 'sa' points to caller-owned memory with the desired multicast address.
5297  *
5298  * 'retifma' will be used to return a pointer to the resulting multicast
5299  * address reference, if desired.
5300  *
5301  * 'anon' indicates a link-layer address with no protocol address reference
5302  * made to it.  Anything other than network-layer protocol domain requests
5303  * are considered as anonymous.
5304  */
5305 static int
if_addmulti_common(struct ifnet * ifp,const struct sockaddr * sa,struct ifmultiaddr ** retifma,int anon)5306 if_addmulti_common(struct ifnet *ifp, const struct sockaddr *sa,
5307     struct ifmultiaddr **retifma, int anon)
5308 {
5309 	struct sockaddr_storage storage;
5310 	struct sockaddr *llsa = NULL;
5311 	struct sockaddr *dupsa = NULL;
5312 	int error = 0, ll_firstref = 0, lladdr;
5313 	struct ifmultiaddr *ifma = NULL;
5314 	struct ifmultiaddr *llifma = NULL;
5315 
5316 	/* Only AF_UNSPEC/AF_LINK is allowed for an "anonymous" address */
5317 	VERIFY(!anon || sa->sa_family == AF_UNSPEC ||
5318 	    sa->sa_family == AF_LINK);
5319 
5320 	/* If sa is a AF_LINK or AF_UNSPEC, duplicate and normalize it */
5321 	if (sa->sa_family == AF_LINK || sa->sa_family == AF_UNSPEC) {
5322 		dupsa = copy_and_normalize(sa);
5323 		if (dupsa == NULL) {
5324 			error = ENOMEM;
5325 			goto cleanup;
5326 		}
5327 		sa = dupsa;
5328 	}
5329 
5330 	ifnet_lock_exclusive(ifp);
5331 	if (!(ifp->if_flags & IFF_MULTICAST)) {
5332 		error = EADDRNOTAVAIL;
5333 		ifnet_lock_done(ifp);
5334 		goto cleanup;
5335 	}
5336 
5337 	/* If the address is already present, return a new reference to it */
5338 	error = if_addmulti_doesexist(ifp, sa, retifma, anon);
5339 	ifnet_lock_done(ifp);
5340 	if (error == 0) {
5341 		goto cleanup;
5342 	}
5343 
5344 	/*
5345 	 * The address isn't already present; give the link layer a chance
5346 	 * to accept/reject it, and also find out which AF_LINK address this
5347 	 * maps to, if it isn't one already.
5348 	 */
5349 	error = dlil_resolve_multi(ifp, sa, (struct sockaddr *)&storage,
5350 	    sizeof(storage));
5351 	if (error == 0 && storage.ss_len != 0) {
5352 		llsa = copy_and_normalize((struct sockaddr *)&storage);
5353 		if (llsa == NULL) {
5354 			error = ENOMEM;
5355 			goto cleanup;
5356 		}
5357 
5358 		llifma = ifma_alloc(Z_WAITOK);
5359 		if (llifma == NULL) {
5360 			error = ENOMEM;
5361 			goto cleanup;
5362 		}
5363 	}
5364 
5365 	/* to be similar to FreeBSD */
5366 	if (error == EOPNOTSUPP) {
5367 		error = 0;
5368 	} else if (error != 0) {
5369 		goto cleanup;
5370 	}
5371 
5372 	/* Allocate while we aren't holding any locks */
5373 	if (dupsa == NULL) {
5374 		dupsa = copy_and_normalize(sa);
5375 		if (dupsa == NULL) {
5376 			error = ENOMEM;
5377 			goto cleanup;
5378 		}
5379 	}
5380 	ifma = ifma_alloc(Z_WAITOK);
5381 	if (ifma == NULL) {
5382 		error = ENOMEM;
5383 		goto cleanup;
5384 	}
5385 
5386 	ifnet_lock_exclusive(ifp);
5387 	/*
5388 	 * Check again for the matching multicast.
5389 	 */
5390 	error = if_addmulti_doesexist(ifp, sa, retifma, anon);
5391 	if (error == 0) {
5392 		ifnet_lock_done(ifp);
5393 		goto cleanup;
5394 	}
5395 
5396 	if (llifma != NULL) {
5397 		VERIFY(!anon);  /* must not get here if "anonymous" */
5398 		if (if_addmulti_doesexist(ifp, llsa, &ifma->ifma_ll, 0) == 0) {
5399 			kfree_data(llsa, llsa->sa_len);
5400 			llsa = NULL;
5401 			ifma_free(llifma);
5402 			llifma = NULL;
5403 			VERIFY(ifma->ifma_ll->ifma_ifp == ifp);
5404 		} else {
5405 			ll_firstref = 1;
5406 			llifma->ifma_addr = llsa;
5407 			llifma->ifma_ifp = ifp;
5408 			IFMA_LOCK(llifma);
5409 			if_attach_ifma(ifp, llifma, 0);
5410 			/* add extra refcnt for ifma */
5411 			IFMA_ADDREF_LOCKED(llifma);
5412 			IFMA_UNLOCK(llifma);
5413 			ifma->ifma_ll = llifma;
5414 		}
5415 	}
5416 
5417 	/* "anonymous" request should not result in network address */
5418 	VERIFY(!anon || ifma->ifma_ll == NULL);
5419 
5420 	ifma->ifma_addr = dupsa;
5421 	ifma->ifma_ifp = ifp;
5422 	IFMA_LOCK(ifma);
5423 	if_attach_ifma(ifp, ifma, anon);
5424 	IFMA_ADDREF_LOCKED(ifma);               /* for this routine */
5425 	if (retifma != NULL) {
5426 		*retifma = ifma;
5427 		IFMA_ADDREF_LOCKED(*retifma);   /* for caller */
5428 	}
5429 	lladdr = (ifma->ifma_addr->sa_family == AF_UNSPEC ||
5430 	    ifma->ifma_addr->sa_family == AF_LINK);
5431 	IFMA_UNLOCK(ifma);
5432 	ifnet_lock_done(ifp);
5433 
5434 	rt_newmaddrmsg(RTM_NEWMADDR, ifma);
5435 	IFMA_REMREF(ifma);                      /* for this routine */
5436 
5437 	/*
5438 	 * We are certain we have added something, so call down to the
5439 	 * interface to let them know about it.  Do this only for newly-
5440 	 * added AF_LINK/AF_UNSPEC address in the if_multiaddrs set.
5441 	 * Note that the notification is deferred to avoid
5442 	 * locking reodering issues in certain paths.
5443 	 */
5444 	if (lladdr || ll_firstref) {
5445 		ifnet_ioctl_async(ifp, SIOCADDMULTI);
5446 	}
5447 
5448 	if (ifp->if_updatemcasts > 0) {
5449 		ifp->if_updatemcasts = 0;
5450 	}
5451 
5452 	return 0;
5453 
5454 cleanup:
5455 	if (ifma != NULL) {
5456 		ifma_free(ifma);
5457 	}
5458 	if (dupsa != NULL) {
5459 		kfree_data(dupsa, dupsa->sa_len);
5460 	}
5461 	if (llifma != NULL) {
5462 		ifma_free(llifma);
5463 	}
5464 	if (llsa != NULL) {
5465 		kfree_data(llsa, llsa->sa_len);
5466 	}
5467 
5468 	return error;
5469 }
5470 
5471 /*
5472  * Delete a multicast group membership by network-layer group address.
5473  * This routine is deprecated.
5474  */
5475 int
if_delmulti(struct ifnet * ifp,const struct sockaddr * sa)5476 if_delmulti(struct ifnet *ifp, const struct sockaddr *sa)
5477 {
5478 	return if_delmulti_common(NULL, ifp, sa, 0);
5479 }
5480 
5481 /*
5482  * Delete a multicast group membership by group membership pointer.
5483  * Network-layer protocol domains must use this routine.
5484  */
5485 int
if_delmulti_ifma(struct ifmultiaddr * ifma)5486 if_delmulti_ifma(struct ifmultiaddr *ifma)
5487 {
5488 	return if_delmulti_common(ifma, NULL, NULL, 0);
5489 }
5490 
5491 /*
5492  * Anything other than network-layer protocol domains which hold references
5493  * to the underlying link-layer record must use this routine: SIOCDELMULTI
5494  * ioctl, ifnet_remove_multicast(), if_bond.
5495  */
5496 int
if_delmulti_anon(struct ifnet * ifp,const struct sockaddr * sa)5497 if_delmulti_anon(struct ifnet *ifp, const struct sockaddr *sa)
5498 {
5499 	return if_delmulti_common(NULL, ifp, sa, 1);
5500 }
5501 
5502 /*
5503  * Delete a multicast group membership by network-layer group address.
5504  *
5505  * Returns ENOENT if the entry could not be found.
5506  */
5507 static int
if_delmulti_common(struct ifmultiaddr * ifma,struct ifnet * ifp,const struct sockaddr * sa,int anon)5508 if_delmulti_common(struct ifmultiaddr *ifma, struct ifnet *ifp,
5509     const struct sockaddr *sa, int anon)
5510 {
5511 	struct sockaddr         *dupsa = NULL;
5512 	int                     lastref, ll_lastref = 0, lladdr;
5513 	struct ifmultiaddr      *ll = NULL;
5514 
5515 	/* sanity check for callers */
5516 	VERIFY(ifma != NULL || (ifp != NULL && sa != NULL));
5517 
5518 	if (ifma != NULL) {
5519 		ifp = ifma->ifma_ifp;
5520 	}
5521 
5522 	if (sa != NULL &&
5523 	    (sa->sa_family == AF_LINK || sa->sa_family == AF_UNSPEC)) {
5524 		dupsa = copy_and_normalize(sa);
5525 		if (dupsa == NULL) {
5526 			return ENOMEM;
5527 		}
5528 		sa = dupsa;
5529 	}
5530 
5531 	ifnet_lock_exclusive(ifp);
5532 	if (ifma == NULL) {
5533 		for (ifma = LIST_FIRST(&ifp->if_multiaddrs); ifma != NULL;
5534 		    ifma = LIST_NEXT(ifma, ifma_link)) {
5535 			IFMA_LOCK(ifma);
5536 			if (!sa_equal(sa, ifma->ifma_addr) ||
5537 			    (anon && !(ifma->ifma_flags & IFMAF_ANONYMOUS))) {
5538 				VERIFY(!(ifma->ifma_flags & IFMAF_ANONYMOUS) ||
5539 				    ifma->ifma_anoncnt != 0);
5540 				IFMA_UNLOCK(ifma);
5541 				continue;
5542 			}
5543 			/* found; keep it locked */
5544 			break;
5545 		}
5546 		if (ifma == NULL) {
5547 			if (dupsa != NULL) {
5548 				kfree_data(dupsa, dupsa->sa_len);
5549 			}
5550 			ifnet_lock_done(ifp);
5551 			return ENOENT;
5552 		}
5553 	} else {
5554 		IFMA_LOCK(ifma);
5555 	}
5556 	IFMA_LOCK_ASSERT_HELD(ifma);
5557 	IFMA_ADDREF_LOCKED(ifma);       /* for this routine */
5558 	lastref = if_detach_ifma(ifp, ifma, anon);
5559 	VERIFY(!lastref || (!(ifma->ifma_debug & IFD_ATTACHED) &&
5560 	    ifma->ifma_reqcnt == 0));
5561 	VERIFY(!anon || ifma->ifma_ll == NULL);
5562 	ll = ifma->ifma_ll;
5563 	lladdr = (ifma->ifma_addr->sa_family == AF_UNSPEC ||
5564 	    ifma->ifma_addr->sa_family == AF_LINK);
5565 	IFMA_UNLOCK(ifma);
5566 	if (lastref && ll != NULL) {
5567 		IFMA_LOCK(ll);
5568 		ll_lastref = if_detach_ifma(ifp, ll, 0);
5569 		IFMA_UNLOCK(ll);
5570 	}
5571 	ifnet_lock_done(ifp);
5572 
5573 	if (lastref) {
5574 		rt_newmaddrmsg(RTM_DELMADDR, ifma);
5575 	}
5576 
5577 	if ((ll == NULL && lastref && lladdr) || ll_lastref) {
5578 		/*
5579 		 * Make sure the interface driver is notified in the
5580 		 * case of a link layer mcast group being left.  Do
5581 		 * this only for a AF_LINK/AF_UNSPEC address that has
5582 		 * been removed from the if_multiaddrs set.
5583 		 * Note that the notification is deferred to avoid
5584 		 * locking reodering issues in certain paths.
5585 		 */
5586 		ifnet_ioctl_async(ifp, SIOCDELMULTI);
5587 	}
5588 
5589 	if (lastref) {
5590 		IFMA_REMREF(ifma);      /* for if_multiaddrs list */
5591 	}
5592 	if (ll_lastref) {
5593 		IFMA_REMREF(ll);        /* for if_multiaddrs list */
5594 	}
5595 	IFMA_REMREF(ifma);              /* for this routine */
5596 	if (dupsa != NULL) {
5597 		kfree_data(dupsa, dupsa->sa_len);
5598 	}
5599 
5600 	return 0;
5601 }
5602 
5603 /*
5604  * Shutdown all network activity.  Used boot() when halting
5605  * system.
5606  */
5607 int
if_down_all(void)5608 if_down_all(void)
5609 {
5610 	struct ifnet **ifp;
5611 	u_int32_t       count;
5612 	u_int32_t       i;
5613 
5614 	if (ifnet_list_get_all(IFNET_FAMILY_ANY, &ifp, &count) == 0) {
5615 		for (i = 0; i < count; i++) {
5616 			if_down(ifp[i]);
5617 			dlil_proto_unplumb_all(ifp[i]);
5618 		}
5619 		ifnet_list_free(ifp);
5620 	}
5621 
5622 	return 0;
5623 }
5624 
5625 /*
5626  * Delete Routes for a Network Interface
5627  *
5628  * Called for each routing entry via the rnh->rnh_walktree() call above
5629  * to delete all route entries referencing a detaching network interface.
5630  *
5631  * Arguments:
5632  *	rn	pointer to node in the routing table
5633  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
5634  *
5635  * Returns:
5636  *	0	successful
5637  *	errno	failed - reason indicated
5638  *
5639  */
5640 static int
if_rtdel(struct radix_node * rn,void * arg)5641 if_rtdel(struct radix_node *rn, void *arg)
5642 {
5643 	struct rtentry  *rt = (struct rtentry *)rn;
5644 	struct ifnet    *ifp = arg;
5645 	int             err;
5646 
5647 	if (rt == NULL) {
5648 		return 0;
5649 	}
5650 	/*
5651 	 * Checking against RTF_UP protects against walktree
5652 	 * recursion problems with cloned routes.
5653 	 */
5654 	RT_LOCK(rt);
5655 	if (rt->rt_ifp == ifp && (rt->rt_flags & RTF_UP)) {
5656 		/*
5657 		 * Safe to drop rt_lock and use rt_key, rt_gateway,
5658 		 * since holding rnh_lock here prevents another thread
5659 		 * from calling rt_setgate() on this route.
5660 		 */
5661 		RT_UNLOCK(rt);
5662 		err = rtrequest_locked(RTM_DELETE, rt_key(rt), rt->rt_gateway,
5663 		    rt_mask(rt), rt->rt_flags, NULL);
5664 		if (err) {
5665 			log(LOG_WARNING, "if_rtdel: error %d\n", err);
5666 		}
5667 	} else {
5668 		RT_UNLOCK(rt);
5669 	}
5670 	return 0;
5671 }
5672 
5673 /*
5674  * Removes routing table reference to a given interface
5675  * for a given protocol family
5676  */
5677 void
if_rtproto_del(struct ifnet * ifp,int protocol)5678 if_rtproto_del(struct ifnet *ifp, int protocol)
5679 {
5680 	struct radix_node_head  *rnh;
5681 
5682 	if ((protocol <= AF_MAX) && (protocol >= 0) &&
5683 	    ((rnh = rt_tables[protocol]) != NULL) && (ifp != NULL)) {
5684 		lck_mtx_lock(rnh_lock);
5685 		(void) rnh->rnh_walktree(rnh, if_rtdel, ifp);
5686 		lck_mtx_unlock(rnh_lock);
5687 	}
5688 }
5689 
5690 static int
if_rtmtu(struct radix_node * rn,void * arg)5691 if_rtmtu(struct radix_node *rn, void *arg)
5692 {
5693 	struct rtentry *rt = (struct rtentry *)rn;
5694 	struct ifnet *ifp = arg;
5695 
5696 	RT_LOCK(rt);
5697 	if (rt->rt_ifp == ifp) {
5698 		/*
5699 		 * Update the MTU of this entry only if the MTU
5700 		 * has not been locked (RTV_MTU is not set) and
5701 		 * if it was non-zero to begin with.
5702 		 */
5703 		if (!(rt->rt_rmx.rmx_locks & RTV_MTU) && rt->rt_rmx.rmx_mtu) {
5704 			rt->rt_rmx.rmx_mtu = ifp->if_mtu;
5705 			if (rt_key(rt)->sa_family == AF_INET &&
5706 			    INTF_ADJUST_MTU_FOR_CLAT46(ifp)) {
5707 				rt->rt_rmx.rmx_mtu = IN6_LINKMTU(ifp);
5708 				/* Further adjust the size for CLAT46 expansion */
5709 				rt->rt_rmx.rmx_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
5710 			}
5711 		}
5712 	}
5713 	RT_UNLOCK(rt);
5714 
5715 	return 0;
5716 }
5717 
5718 /*
5719  * Update the MTU metric of all route entries in all protocol tables
5720  * associated with a particular interface; this is called when the
5721  * MTU of that interface has changed.
5722  */
5723 static void
if_rtmtu_update(struct ifnet * ifp)5724 if_rtmtu_update(struct ifnet *ifp)
5725 {
5726 	struct radix_node_head *rnh;
5727 	int p;
5728 
5729 	for (p = 0; p < AF_MAX + 1; p++) {
5730 		if ((rnh = rt_tables[p]) == NULL) {
5731 			continue;
5732 		}
5733 
5734 		lck_mtx_lock(rnh_lock);
5735 		(void) rnh->rnh_walktree(rnh, if_rtmtu, ifp);
5736 		lck_mtx_unlock(rnh_lock);
5737 	}
5738 	routegenid_update();
5739 }
5740 
5741 __private_extern__ void
if_data_internal_to_if_data(struct ifnet * ifp,const struct if_data_internal * if_data_int,struct if_data * if_data)5742 if_data_internal_to_if_data(struct ifnet *ifp,
5743     const struct if_data_internal *if_data_int, struct if_data *if_data)
5744 {
5745 #pragma unused(ifp)
5746 #define COPYFIELD(fld)          if_data->fld = if_data_int->fld
5747 #define COPYFIELD32(fld)        if_data->fld = (u_int32_t)(if_data_int->fld)
5748 /* compiler will cast down to 32-bit */
5749 #define COPYFIELD32_ATOMIC(fld) do {                                    \
5750 	uint64_t _val = 0;                                              \
5751 	_val = os_atomic_load((uint64_t *)(void *)(uintptr_t)&if_data_int->fld, relaxed); \
5752 	if_data->fld = (uint32_t) _val;                                 \
5753 } while (0)
5754 
5755 	COPYFIELD(ifi_type);
5756 	COPYFIELD(ifi_typelen);
5757 	COPYFIELD(ifi_physical);
5758 	COPYFIELD(ifi_addrlen);
5759 	COPYFIELD(ifi_hdrlen);
5760 	COPYFIELD(ifi_recvquota);
5761 	COPYFIELD(ifi_xmitquota);
5762 	if_data->ifi_unused1 = 0;
5763 	COPYFIELD(ifi_mtu);
5764 	COPYFIELD(ifi_metric);
5765 	if (if_data_int->ifi_baudrate & 0xFFFFFFFF00000000LL) {
5766 		if_data->ifi_baudrate = 0xFFFFFFFF;
5767 	} else {
5768 		COPYFIELD32(ifi_baudrate);
5769 	}
5770 
5771 	COPYFIELD32_ATOMIC(ifi_ipackets);
5772 	COPYFIELD32_ATOMIC(ifi_ierrors);
5773 	COPYFIELD32_ATOMIC(ifi_opackets);
5774 	COPYFIELD32_ATOMIC(ifi_oerrors);
5775 	COPYFIELD32_ATOMIC(ifi_collisions);
5776 	COPYFIELD32_ATOMIC(ifi_ibytes);
5777 	COPYFIELD32_ATOMIC(ifi_obytes);
5778 	COPYFIELD32_ATOMIC(ifi_imcasts);
5779 	COPYFIELD32_ATOMIC(ifi_omcasts);
5780 	COPYFIELD32_ATOMIC(ifi_iqdrops);
5781 	COPYFIELD32_ATOMIC(ifi_noproto);
5782 
5783 	COPYFIELD(ifi_recvtiming);
5784 	COPYFIELD(ifi_xmittiming);
5785 
5786 	if_data->ifi_lastchange.tv_sec = (uint32_t)if_data_int->ifi_lastchange.tv_sec;
5787 	if_data->ifi_lastchange.tv_usec = if_data_int->ifi_lastchange.tv_usec;
5788 
5789 	if_data->ifi_lastchange.tv_sec += (uint32_t)boottime_sec();
5790 
5791 	if_data->ifi_unused2 = 0;
5792 	COPYFIELD(ifi_hwassist);
5793 	if_data->ifi_reserved1 = 0;
5794 	if_data->ifi_reserved2 = 0;
5795 #undef COPYFIELD32_ATOMIC
5796 #undef COPYFIELD32
5797 #undef COPYFIELD
5798 }
5799 
5800 __private_extern__ void
if_data_internal_to_if_data64(struct ifnet * ifp,const struct if_data_internal * if_data_int,struct if_data64 * if_data64)5801 if_data_internal_to_if_data64(struct ifnet *ifp,
5802     const struct if_data_internal *if_data_int,
5803     struct if_data64 *if_data64)
5804 {
5805 #pragma unused(ifp)
5806 #define COPYFIELD64(fld)        if_data64->fld = if_data_int->fld
5807 #define COPYFIELD64_ATOMIC(fld) do {                                    \
5808 	if_data64->fld = os_atomic_load((uint64_t *)(void *)(uintptr_t)&if_data_int->fld, relaxed); \
5809 } while (0)
5810 
5811 	COPYFIELD64(ifi_type);
5812 	COPYFIELD64(ifi_typelen);
5813 	COPYFIELD64(ifi_physical);
5814 	COPYFIELD64(ifi_addrlen);
5815 	COPYFIELD64(ifi_hdrlen);
5816 	COPYFIELD64(ifi_recvquota);
5817 	COPYFIELD64(ifi_xmitquota);
5818 	if_data64->ifi_unused1 = 0;
5819 	COPYFIELD64(ifi_mtu);
5820 	COPYFIELD64(ifi_metric);
5821 	COPYFIELD64(ifi_baudrate);
5822 
5823 	COPYFIELD64_ATOMIC(ifi_ipackets);
5824 	COPYFIELD64_ATOMIC(ifi_ierrors);
5825 	COPYFIELD64_ATOMIC(ifi_opackets);
5826 	COPYFIELD64_ATOMIC(ifi_oerrors);
5827 	COPYFIELD64_ATOMIC(ifi_collisions);
5828 	COPYFIELD64_ATOMIC(ifi_ibytes);
5829 	COPYFIELD64_ATOMIC(ifi_obytes);
5830 	COPYFIELD64_ATOMIC(ifi_imcasts);
5831 	COPYFIELD64_ATOMIC(ifi_omcasts);
5832 	COPYFIELD64_ATOMIC(ifi_iqdrops);
5833 	COPYFIELD64_ATOMIC(ifi_noproto);
5834 
5835 	/*
5836 	 * Note these two fields are actually 32 bit, so doing
5837 	 * COPYFIELD64_ATOMIC will cause them to be misaligned
5838 	 */
5839 	COPYFIELD64(ifi_recvtiming);
5840 	COPYFIELD64(ifi_xmittiming);
5841 
5842 	if_data64->ifi_lastchange.tv_sec = (uint32_t)if_data_int->ifi_lastchange.tv_sec;
5843 	if_data64->ifi_lastchange.tv_usec = (uint32_t)if_data_int->ifi_lastchange.tv_usec;
5844 
5845 	if_data64->ifi_lastchange.tv_sec += (uint32_t)boottime_sec();
5846 
5847 #undef COPYFIELD64
5848 }
5849 
5850 __private_extern__ void
if_copy_traffic_class(struct ifnet * ifp,struct if_traffic_class * if_tc)5851 if_copy_traffic_class(struct ifnet *ifp,
5852     struct if_traffic_class *if_tc)
5853 {
5854 #define COPY_IF_TC_FIELD64_ATOMIC(fld) do {                     \
5855 	if_tc->fld = os_atomic_load((uint64_t *)(void *)(uintptr_t)&ifp->if_tc.fld, relaxed); \
5856 } while (0)
5857 
5858 	bzero(if_tc, sizeof(*if_tc));
5859 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ibepackets);
5860 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ibebytes);
5861 	COPY_IF_TC_FIELD64_ATOMIC(ifi_obepackets);
5862 	COPY_IF_TC_FIELD64_ATOMIC(ifi_obebytes);
5863 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ibkpackets);
5864 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ibkbytes);
5865 	COPY_IF_TC_FIELD64_ATOMIC(ifi_obkpackets);
5866 	COPY_IF_TC_FIELD64_ATOMIC(ifi_obkbytes);
5867 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ivipackets);
5868 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ivibytes);
5869 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ovipackets);
5870 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ovibytes);
5871 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ivopackets);
5872 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ivobytes);
5873 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ovopackets);
5874 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ovobytes);
5875 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ipvpackets);
5876 	COPY_IF_TC_FIELD64_ATOMIC(ifi_ipvbytes);
5877 	COPY_IF_TC_FIELD64_ATOMIC(ifi_opvpackets);
5878 	COPY_IF_TC_FIELD64_ATOMIC(ifi_opvbytes);
5879 
5880 #undef COPY_IF_TC_FIELD64_ATOMIC
5881 }
5882 
5883 void
if_copy_data_extended(struct ifnet * ifp,struct if_data_extended * if_de)5884 if_copy_data_extended(struct ifnet *ifp, struct if_data_extended *if_de)
5885 {
5886 #define COPY_IF_DE_FIELD64_ATOMIC(fld) do {                     \
5887 	if_de->fld = os_atomic_load((uint64_t *)(void *)(uintptr_t)&ifp->if_data.fld, relaxed); \
5888 } while (0)
5889 
5890 	bzero(if_de, sizeof(*if_de));
5891 	COPY_IF_DE_FIELD64_ATOMIC(ifi_alignerrs);
5892 	COPY_IF_DE_FIELD64_ATOMIC(ifi_dt_bytes);
5893 	COPY_IF_DE_FIELD64_ATOMIC(ifi_fpackets);
5894 	COPY_IF_DE_FIELD64_ATOMIC(ifi_fbytes);
5895 
5896 #undef COPY_IF_DE_FIELD64_ATOMIC
5897 }
5898 
5899 void
if_copy_packet_stats(struct ifnet * ifp,struct if_packet_stats * if_ps)5900 if_copy_packet_stats(struct ifnet *ifp, struct if_packet_stats *if_ps)
5901 {
5902 #define COPY_IF_PS_TCP_FIELD64_ATOMIC(fld) do {                         \
5903 	if_ps->ifi_tcp_##fld = os_atomic_load((uint64_t *)(void *)(uintptr_t)&ifp->if_tcp_stat->fld, relaxed); \
5904 } while (0)
5905 
5906 #define COPY_IF_PS_UDP_FIELD64_ATOMIC(fld) do {                         \
5907 	if_ps->ifi_udp_##fld = os_atomic_load((uint64_t *)(void *)(uintptr_t)&ifp->if_udp_stat->fld, relaxed); \
5908 } while (0)
5909 
5910 	COPY_IF_PS_TCP_FIELD64_ATOMIC(badformat);
5911 	COPY_IF_PS_TCP_FIELD64_ATOMIC(unspecv6);
5912 	COPY_IF_PS_TCP_FIELD64_ATOMIC(synfin);
5913 	COPY_IF_PS_TCP_FIELD64_ATOMIC(badformatipsec);
5914 	COPY_IF_PS_TCP_FIELD64_ATOMIC(noconnnolist);
5915 	COPY_IF_PS_TCP_FIELD64_ATOMIC(noconnlist);
5916 	COPY_IF_PS_TCP_FIELD64_ATOMIC(listbadsyn);
5917 	COPY_IF_PS_TCP_FIELD64_ATOMIC(icmp6unreach);
5918 	COPY_IF_PS_TCP_FIELD64_ATOMIC(deprecate6);
5919 	COPY_IF_PS_TCP_FIELD64_ATOMIC(ooopacket);
5920 	COPY_IF_PS_TCP_FIELD64_ATOMIC(rstinsynrcv);
5921 	COPY_IF_PS_TCP_FIELD64_ATOMIC(dospacket);
5922 	COPY_IF_PS_TCP_FIELD64_ATOMIC(cleanup);
5923 	COPY_IF_PS_TCP_FIELD64_ATOMIC(synwindow);
5924 
5925 	COPY_IF_PS_UDP_FIELD64_ATOMIC(port_unreach);
5926 	COPY_IF_PS_UDP_FIELD64_ATOMIC(faithprefix);
5927 	COPY_IF_PS_UDP_FIELD64_ATOMIC(port0);
5928 	COPY_IF_PS_UDP_FIELD64_ATOMIC(badlength);
5929 	COPY_IF_PS_UDP_FIELD64_ATOMIC(badchksum);
5930 	COPY_IF_PS_UDP_FIELD64_ATOMIC(badmcast);
5931 	COPY_IF_PS_UDP_FIELD64_ATOMIC(cleanup);
5932 	COPY_IF_PS_UDP_FIELD64_ATOMIC(badipsec);
5933 
5934 #undef COPY_IF_PS_TCP_FIELD64_ATOMIC
5935 #undef COPY_IF_PS_UDP_FIELD64_ATOMIC
5936 }
5937 
5938 void
if_copy_rxpoll_stats(struct ifnet * ifp,struct if_rxpoll_stats * if_rs)5939 if_copy_rxpoll_stats(struct ifnet *ifp, struct if_rxpoll_stats *if_rs)
5940 {
5941 	bzero(if_rs, sizeof(*if_rs));
5942 	if (!(ifp->if_eflags & IFEF_RXPOLL) || !ifnet_is_attached(ifp, 1)) {
5943 		return;
5944 	}
5945 	bcopy(&ifp->if_poll_pstats, if_rs, sizeof(*if_rs));
5946 	/* Release the IO refcnt */
5947 	ifnet_decr_iorefcnt(ifp);
5948 }
5949 
5950 void
if_copy_netif_stats(struct ifnet * ifp,struct if_netif_stats * if_ns)5951 if_copy_netif_stats(struct ifnet *ifp, struct if_netif_stats *if_ns)
5952 {
5953 	bzero(if_ns, sizeof(*if_ns));
5954 #if SKYWALK
5955 	if (!(ifp->if_capabilities & IFCAP_SKYWALK) ||
5956 	    !ifnet_is_attached(ifp, 1)) {
5957 		return;
5958 	}
5959 
5960 	if (ifp->if_na != NULL) {
5961 		nx_netif_copy_stats(ifp->if_na, if_ns);
5962 	}
5963 
5964 	/* Release the IO refcnt */
5965 	ifnet_decr_iorefcnt(ifp);
5966 #else /* SKYWALK */
5967 #pragma unused(ifp)
5968 #endif /* SKYWALK */
5969 }
5970 
5971 struct ifaddr *
ifa_remref(struct ifaddr * ifa,int locked)5972 ifa_remref(struct ifaddr *ifa, int locked)
5973 {
5974 	if (!locked) {
5975 		IFA_LOCK_SPIN(ifa);
5976 	} else {
5977 		IFA_LOCK_ASSERT_HELD(ifa);
5978 	}
5979 
5980 	if (ifa->ifa_refcnt == 0) {
5981 		panic("%s: ifa %p negative refcnt", __func__, ifa);
5982 	} else if (ifa->ifa_trace != NULL) {
5983 		(*ifa->ifa_trace)(ifa, FALSE);
5984 	}
5985 	if (--ifa->ifa_refcnt == 0) {
5986 		if (ifa->ifa_debug & IFD_ATTACHED) {
5987 			panic("ifa %p attached to ifp is being freed", ifa);
5988 		}
5989 		/*
5990 		 * Some interface addresses are allocated either statically
5991 		 * or carved out of a larger block.  Only free it if it was
5992 		 * allocated via MALLOC or via the corresponding per-address
5993 		 * family allocator.  Otherwise, leave it alone.
5994 		 */
5995 		if (ifa->ifa_debug & IFD_ALLOC) {
5996 #if XNU_PLATFORM_MacOSX
5997 			if (ifa->ifa_free == NULL) {
5998 				IFA_UNLOCK(ifa);
5999 				/*
6000 				 * support for 3rd party kexts,
6001 				 * old ABI was that this had to be allocated
6002 				 * with MALLOC(M_IFADDR).
6003 				 */
6004 				__typed_allocators_ignore(kheap_free_addr(KHEAP_DEFAULT, ifa));
6005 			} else
6006 #endif /* XNU_PLATFORM_MacOSX */
6007 			{
6008 				/* Become a regular mutex */
6009 				IFA_CONVERT_LOCK(ifa);
6010 				/* callee will unlock */
6011 				(*ifa->ifa_free)(ifa);
6012 			}
6013 		} else {
6014 			IFA_UNLOCK(ifa);
6015 		}
6016 		ifa = NULL;
6017 	}
6018 
6019 	if (!locked && ifa != NULL) {
6020 		IFA_UNLOCK(ifa);
6021 	}
6022 
6023 	return ifa;
6024 }
6025 
6026 void
ifa_addref(struct ifaddr * ifa,int locked)6027 ifa_addref(struct ifaddr *ifa, int locked)
6028 {
6029 	if (!locked) {
6030 		IFA_LOCK_SPIN(ifa);
6031 	} else {
6032 		IFA_LOCK_ASSERT_HELD(ifa);
6033 	}
6034 
6035 	if (++ifa->ifa_refcnt == 0) {
6036 		panic("%s: ifa %p wraparound refcnt", __func__, ifa);
6037 		/* NOTREACHED */
6038 	} else if (ifa->ifa_trace != NULL) {
6039 		(*ifa->ifa_trace)(ifa, TRUE);
6040 	}
6041 	if (!locked) {
6042 		IFA_UNLOCK(ifa);
6043 	}
6044 }
6045 
6046 void
ifa_lock_init(struct ifaddr * ifa)6047 ifa_lock_init(struct ifaddr *ifa)
6048 {
6049 	lck_mtx_init(&ifa->ifa_lock, &ifa_mtx_grp, &ifa_mtx_attr);
6050 }
6051 
6052 void
ifa_lock_destroy(struct ifaddr * ifa)6053 ifa_lock_destroy(struct ifaddr *ifa)
6054 {
6055 	IFA_LOCK_ASSERT_NOTHELD(ifa);
6056 	lck_mtx_destroy(&ifa->ifa_lock, &ifa_mtx_grp);
6057 }
6058 
6059 /*
6060  * 'i' group ioctls.
6061  *
6062  * The switch statement below does nothing at runtime, as it serves as a
6063  * compile time check to ensure that all of the socket 'i' ioctls (those
6064  * in the 'i' group going thru soo_ioctl) that are made available by the
6065  * networking stack is unique.  This works as long as this routine gets
6066  * updated each time a new interface ioctl gets added.
6067  *
6068  * Any failures at compile time indicates duplicated ioctl values.
6069  */
6070 static __attribute__((unused)) void
ifioctl_cassert(void)6071 ifioctl_cassert(void)
6072 {
6073 	/*
6074 	 * This is equivalent to _CASSERT() and the compiler wouldn't
6075 	 * generate any instructions, thus for compile time only.
6076 	 */
6077 	switch ((u_long)0) {
6078 	case 0:
6079 
6080 	/* bsd/net/if_ppp.h */
6081 	case SIOCGPPPSTATS:
6082 	case SIOCGPPPCSTATS:
6083 
6084 	/* bsd/netinet6/in6_var.h */
6085 	case SIOCSIFADDR_IN6:
6086 	case SIOCGIFADDR_IN6:
6087 	case SIOCSIFDSTADDR_IN6:
6088 	case SIOCSIFNETMASK_IN6:
6089 	case SIOCGIFDSTADDR_IN6:
6090 	case SIOCGIFNETMASK_IN6:
6091 	case SIOCDIFADDR_IN6:
6092 	case SIOCAIFADDR_IN6_32:
6093 	case SIOCAIFADDR_IN6_64:
6094 	case SIOCSIFPHYADDR_IN6_32:
6095 	case SIOCSIFPHYADDR_IN6_64:
6096 	case SIOCGIFPSRCADDR_IN6:
6097 	case SIOCGIFPDSTADDR_IN6:
6098 	case SIOCGIFAFLAG_IN6:
6099 	case SIOCGDRLST_IN6_32:
6100 	case SIOCGDRLST_IN6_64:
6101 	case SIOCGPRLST_IN6_32:
6102 	case SIOCGPRLST_IN6_64:
6103 	case OSIOCGIFINFO_IN6:
6104 	case SIOCGIFINFO_IN6:
6105 	case SIOCSNDFLUSH_IN6:
6106 	case SIOCGNBRINFO_IN6_32:
6107 	case SIOCGNBRINFO_IN6_64:
6108 	case SIOCSPFXFLUSH_IN6:
6109 	case SIOCSRTRFLUSH_IN6:
6110 	case SIOCGIFALIFETIME_IN6:
6111 	case SIOCSIFALIFETIME_IN6:
6112 	case SIOCGIFSTAT_IN6:
6113 	case SIOCGIFSTAT_ICMP6:
6114 	case SIOCSDEFIFACE_IN6_32:
6115 	case SIOCSDEFIFACE_IN6_64:
6116 	case SIOCGDEFIFACE_IN6_32:
6117 	case SIOCGDEFIFACE_IN6_64:
6118 	case SIOCSIFINFO_FLAGS:
6119 	case SIOCSSCOPE6:
6120 	case SIOCGSCOPE6:
6121 	case SIOCGSCOPE6DEF:
6122 	case SIOCSIFPREFIX_IN6:
6123 	case SIOCGIFPREFIX_IN6:
6124 	case SIOCDIFPREFIX_IN6:
6125 	case SIOCAIFPREFIX_IN6:
6126 	case SIOCCIFPREFIX_IN6:
6127 	case SIOCSGIFPREFIX_IN6:
6128 	case SIOCPROTOATTACH_IN6_32:
6129 	case SIOCPROTOATTACH_IN6_64:
6130 	case SIOCPROTODETACH_IN6:
6131 	case SIOCLL_START_32:
6132 	case SIOCLL_START_64:
6133 	case SIOCLL_STOP:
6134 	case SIOCAUTOCONF_START:
6135 	case SIOCAUTOCONF_STOP:
6136 	case SIOCSETROUTERMODE_IN6:
6137 	case SIOCGETROUTERMODE_IN6:
6138 	case SIOCLL_CGASTART_32:
6139 	case SIOCLL_CGASTART_64:
6140 	case SIOCGIFCGAPREP_IN6:
6141 	case SIOCSIFCGAPREP_IN6:
6142 
6143 	/* bsd/sys/sockio.h */
6144 	case SIOCSIFADDR:
6145 	case OSIOCGIFADDR:
6146 	case SIOCSIFDSTADDR:
6147 	case OSIOCGIFDSTADDR:
6148 	case SIOCSIFFLAGS:
6149 	case SIOCGIFFLAGS:
6150 	case OSIOCGIFBRDADDR:
6151 	case SIOCSIFBRDADDR:
6152 	case OSIOCGIFCONF32:
6153 	case OSIOCGIFCONF64:
6154 	case OSIOCGIFNETMASK:
6155 	case SIOCSIFNETMASK:
6156 	case SIOCGIFMETRIC:
6157 	case SIOCSIFMETRIC:
6158 	case SIOCDIFADDR:
6159 	case SIOCAIFADDR:
6160 
6161 	case SIOCGIFADDR:
6162 	case SIOCGIFDSTADDR:
6163 	case SIOCGIFBRDADDR:
6164 	case SIOCGIFCONF32:
6165 	case SIOCGIFCONF64:
6166 	case SIOCGIFNETMASK:
6167 	case SIOCAUTOADDR:
6168 	case SIOCAUTONETMASK:
6169 	case SIOCARPIPLL:
6170 
6171 	case SIOCADDMULTI:
6172 	case SIOCDELMULTI:
6173 	case SIOCGIFMTU:
6174 	case SIOCSIFMTU:
6175 	case SIOCGIFPHYS:
6176 	case SIOCSIFPHYS:
6177 	case SIOCSIFMEDIA:
6178 	case SIOCGIFMEDIA32:
6179 	case SIOCGIFMEDIA64:
6180 	case SIOCGIFXMEDIA32:
6181 	case SIOCGIFXMEDIA64:
6182 	case SIOCSIFGENERIC:
6183 	case SIOCGIFGENERIC:
6184 	case SIOCRSLVMULTI:
6185 
6186 	case SIOCSIFLLADDR:
6187 	case SIOCGIFSTATUS:
6188 	case SIOCSIFPHYADDR:
6189 	case SIOCGIFPSRCADDR:
6190 	case SIOCGIFPDSTADDR:
6191 	case SIOCDIFPHYADDR:
6192 
6193 	case SIOCGIFDEVMTU:
6194 	case SIOCSIFALTMTU:
6195 	case SIOCGIFALTMTU:
6196 	case SIOCSIFBOND:
6197 	case SIOCGIFBOND:
6198 
6199 	case SIOCPROTOATTACH:
6200 	case SIOCPROTODETACH:
6201 
6202 	case SIOCSIFCAP:
6203 	case SIOCGIFCAP:
6204 
6205 	case SIOCSIFMANAGEMENT:
6206 
6207 	case SIOCIFCREATE:
6208 	case SIOCIFDESTROY:
6209 	case SIOCIFCREATE2:
6210 
6211 	case SIOCSDRVSPEC32:
6212 	case SIOCGDRVSPEC32:
6213 	case SIOCSDRVSPEC64:
6214 	case SIOCGDRVSPEC64:
6215 
6216 	case SIOCSIFVLAN:
6217 	case SIOCGIFVLAN:
6218 
6219 	case SIOCIFGCLONERS32:
6220 	case SIOCIFGCLONERS64:
6221 
6222 	case SIOCGIFASYNCMAP:
6223 	case SIOCSIFASYNCMAP:
6224 	case SIOCSIFKPI:
6225 	case SIOCGIFKPI:
6226 
6227 	case SIOCGIFWAKEFLAGS:
6228 
6229 	case SIOCGIFGETRTREFCNT:
6230 	case SIOCGIFLINKQUALITYMETRIC:
6231 	case SIOCSIFLINKQUALITYMETRIC:
6232 	case SIOCSIFOPPORTUNISTIC:
6233 	case SIOCGIFOPPORTUNISTIC:
6234 	case SIOCGETROUTERMODE:
6235 	case SIOCSETROUTERMODE:
6236 	case SIOCGIFEFLAGS:
6237 	case SIOCSIFDESC:
6238 	case SIOCGIFDESC:
6239 	case SIOCSIFLINKPARAMS:
6240 	case SIOCGIFLINKPARAMS:
6241 	case SIOCGIFQUEUESTATS:
6242 	case SIOCSIFTHROTTLE:
6243 	case SIOCGIFTHROTTLE:
6244 
6245 	case SIOCGASSOCIDS32:
6246 	case SIOCGASSOCIDS64:
6247 	case SIOCGCONNIDS32:
6248 	case SIOCGCONNIDS64:
6249 	case SIOCGCONNINFO32:
6250 	case SIOCGCONNINFO64:
6251 	case SIOCSCONNORDER:
6252 	case SIOCGCONNORDER:
6253 
6254 	case SIOCSIFLOG:
6255 	case SIOCGIFLOG:
6256 	case SIOCGIFDELEGATE:
6257 	case SIOCGIFLLADDR:
6258 	case SIOCGIFTYPE:
6259 	case SIOCGIFEXPENSIVE:
6260 	case SIOCSIFEXPENSIVE:
6261 	case SIOCGIF2KCL:
6262 	case SIOCSIF2KCL:
6263 	case SIOCGSTARTDELAY:
6264 
6265 	case SIOCAIFAGENTID:
6266 	case SIOCDIFAGENTID:
6267 	case SIOCGIFAGENTIDS32:
6268 	case SIOCGIFAGENTIDS64:
6269 	case SIOCGIFAGENTDATA32:
6270 	case SIOCGIFAGENTDATA64:
6271 
6272 	case SIOCSIFINTERFACESTATE:
6273 	case SIOCGIFINTERFACESTATE:
6274 	case SIOCSIFPROBECONNECTIVITY:
6275 	case SIOCGIFPROBECONNECTIVITY:
6276 
6277 	case SIOCGIFFUNCTIONALTYPE:
6278 	case SIOCSIFNETSIGNATURE:
6279 	case SIOCGIFNETSIGNATURE:
6280 
6281 	case SIOCSIFNETWORKID:
6282 	case SIOCGECNMODE:
6283 	case SIOCSECNMODE:
6284 
6285 	case SIOCSIFORDER:
6286 	case SIOCGIFORDER:
6287 
6288 	case SIOCSQOSMARKINGMODE:
6289 	case SIOCSQOSMARKINGENABLED:
6290 	case SIOCGQOSMARKINGMODE:
6291 	case SIOCGQOSMARKINGENABLED:
6292 
6293 	case SIOCSIFTIMESTAMPENABLE:
6294 	case SIOCSIFTIMESTAMPDISABLE:
6295 	case SIOCGIFTIMESTAMPENABLED:
6296 
6297 	case SIOCSIFDISABLEOUTPUT:
6298 
6299 	case SIOCSIFSUBFAMILY:
6300 
6301 	case SIOCGIFAGENTLIST32:
6302 	case SIOCGIFAGENTLIST64:
6303 
6304 	case SIOCSIFLOWINTERNET:
6305 	case SIOCGIFLOWINTERNET:
6306 
6307 	case SIOCGIFNAT64PREFIX:
6308 	case SIOCSIFNAT64PREFIX:
6309 
6310 	case SIOCGIFCLAT46ADDR:
6311 #if SKYWALK
6312 	case SIOCGIFNEXUS:
6313 #endif /* SKYWALK */
6314 
6315 	case SIOCGIFPROTOLIST32:
6316 	case SIOCGIFPROTOLIST64:
6317 
6318 	case SIOCGIFLOWPOWER:
6319 	case SIOCSIFLOWPOWER:
6320 
6321 	case SIOCGIFMPKLOG:
6322 	case SIOCSIFMPKLOG:
6323 
6324 	case SIOCGIFCONSTRAINED:
6325 	case SIOCSIFCONSTRAINED:
6326 
6327 	case SIOCGIFXFLAGS:
6328 
6329 	case SIOCGIFNOACKPRIO:
6330 	case SIOCSIFNOACKPRIO:
6331 
6332 	case SIOCSIFMARKWAKEPKT:
6333 
6334 	case SIOCSIFNOTRAFFICSHAPING:
6335 	case SIOCGIFNOTRAFFICSHAPING:
6336 		;
6337 	}
6338 }
6339 
6340 #if SKYWALK
6341 /*
6342  * XXX: This API is only used by BSD stack and for now will always return 0.
6343  * For Skywalk native drivers, preamble space need not be allocated in mbuf
6344  * as the preamble will be reserved in the translated skywalk packet
6345  * which is transmitted to the driver.
6346  * For Skywalk compat drivers currently headroom is always set to zero.
6347  */
6348 #endif /* SKYWALK */
6349 uint32_t
ifnet_mbuf_packetpreamblelen(struct ifnet * ifp)6350 ifnet_mbuf_packetpreamblelen(struct ifnet *ifp)
6351 {
6352 #pragma unused(ifp)
6353 	return 0;
6354 }
6355 
6356 /* The following is used to enqueue work items for interface events */
6357 struct intf_event {
6358 	struct ifnet *ifp;
6359 	union sockaddr_in_4_6 addr;
6360 	uint32_t intf_event_code;
6361 };
6362 
6363 struct intf_event_nwk_wq_entry {
6364 	struct nwk_wq_entry nwk_wqe;
6365 	struct intf_event intf_ev_arg;
6366 };
6367 
6368 static void
intf_event_callback(struct nwk_wq_entry * nwk_item)6369 intf_event_callback(struct nwk_wq_entry *nwk_item)
6370 {
6371 	struct intf_event_nwk_wq_entry *p_ev;
6372 
6373 	p_ev = __container_of(nwk_item, struct intf_event_nwk_wq_entry, nwk_wqe);
6374 
6375 	/* Call this before we walk the tree */
6376 	EVENTHANDLER_INVOKE(&ifnet_evhdlr_ctxt, ifnet_event,
6377 	    p_ev->intf_ev_arg.ifp,
6378 	    (struct sockaddr *)&(p_ev->intf_ev_arg.addr),
6379 	    p_ev->intf_ev_arg.intf_event_code);
6380 
6381 	kfree_type(struct intf_event_nwk_wq_entry, p_ev);
6382 }
6383 
6384 void
intf_event_enqueue_nwk_wq_entry(struct ifnet * ifp,struct sockaddr * addrp,uint32_t intf_event_code)6385 intf_event_enqueue_nwk_wq_entry(struct ifnet *ifp, struct sockaddr *addrp,
6386     uint32_t intf_event_code)
6387 {
6388 #pragma unused(addrp)
6389 	struct intf_event_nwk_wq_entry *p_intf_ev = NULL;
6390 
6391 	p_intf_ev = kalloc_type(struct intf_event_nwk_wq_entry,
6392 	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
6393 
6394 	p_intf_ev->intf_ev_arg.ifp = ifp;
6395 	/*
6396 	 * XXX Not using addr in the arg. This will be used
6397 	 * once we need IP address add/delete events
6398 	 */
6399 	p_intf_ev->intf_ev_arg.intf_event_code = intf_event_code;
6400 	p_intf_ev->nwk_wqe.func = intf_event_callback;
6401 	nwk_wq_enqueue(&p_intf_ev->nwk_wqe);
6402 }
6403 
6404 int
if_get_tcp_kao_max(struct ifnet * ifp)6405 if_get_tcp_kao_max(struct ifnet *ifp)
6406 {
6407 	int error = 0;
6408 
6409 	if (ifp->if_tcp_kao_max == 0) {
6410 		struct ifreq ifr;
6411 
6412 		memset(&ifr, 0, sizeof(struct ifreq));
6413 		error = ifnet_ioctl(ifp, 0, SIOCGIFTCPKAOMAX, &ifr);
6414 
6415 		ifnet_lock_exclusive(ifp);
6416 		if (error == 0) {
6417 			ifp->if_tcp_kao_max = ifr.ifr_tcp_kao_max;
6418 		} else if (error == EOPNOTSUPP) {
6419 			ifp->if_tcp_kao_max = default_tcp_kao_max;
6420 		}
6421 		ifnet_lock_done(ifp);
6422 	}
6423 	return error;
6424 }
6425 
6426 int
ifnet_set_management(struct ifnet * ifp,boolean_t on)6427 ifnet_set_management(struct ifnet *ifp, boolean_t on)
6428 {
6429 	if (ifp == NULL) {
6430 		return EINVAL;
6431 	}
6432 	if (if_management_verbose > 0) {
6433 		os_log(OS_LOG_DEFAULT,
6434 		    "interface %s management set %s by %s:%d",
6435 		    ifp->if_xname, on ? "true" : "false",
6436 		    proc_best_name(current_proc()), proc_selfpid());
6437 	}
6438 	if (on) {
6439 		if_set_xflags(ifp, IFXF_MANAGEMENT);
6440 		if_management_interface_check_needed = true;
6441 		in_management_interface_check();
6442 	} else {
6443 		if_clear_xflags(ifp, IFXF_MANAGEMENT);
6444 	}
6445 	return 0;
6446 }
6447