xref: /xnu-8019.80.24/bsd/kern/kern_control.c (revision a325d9c4a84054e40bbe985afedcb50ab80993ea)
1 /*
2  * Copyright (c) 1999-2020 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 /*
30  * Kernel Control domain - allows control connections to
31  *  and to read/write data.
32  *
33  * Vincent Lubet, 040506
34  * Christophe Allie, 010928
35  * Justin C. Walker, 990319
36  */
37 
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/syslog.h>
42 #include <sys/socket.h>
43 #include <sys/socketvar.h>
44 #include <sys/protosw.h>
45 #include <sys/domain.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/sys_domain.h>
49 #include <sys/kern_event.h>
50 #include <sys/kern_control.h>
51 #include <sys/kauth.h>
52 #include <sys/sysctl.h>
53 #include <sys/proc_info.h>
54 #include <net/if_var.h>
55 
56 #include <mach/vm_types.h>
57 
58 #include <kern/thread.h>
59 
60 struct kctl {
61 	TAILQ_ENTRY(kctl)       next;           /* controller chain */
62 	kern_ctl_ref            kctlref;
63 
64 	/* controller information provided when registering */
65 	char                    name[MAX_KCTL_NAME];    /* unique identifier */
66 	u_int32_t               id;
67 	u_int32_t               reg_unit;
68 
69 	/* misc communication information */
70 	u_int32_t               flags;          /* support flags */
71 	u_int32_t               recvbufsize;    /* request more than the default buffer size */
72 	u_int32_t               sendbufsize;    /* request more than the default buffer size */
73 
74 	/* Dispatch functions */
75 	ctl_setup_func          setup;          /* Setup contact */
76 	ctl_bind_func           bind;           /* Prepare contact */
77 	ctl_connect_func        connect;        /* Make contact */
78 	ctl_disconnect_func     disconnect;     /* Break contact */
79 	ctl_send_func           send;           /* Send data to nke */
80 	ctl_send_list_func      send_list;      /* Send list of packets */
81 	ctl_setopt_func         setopt;         /* set kctl configuration */
82 	ctl_getopt_func         getopt;         /* get kctl configuration */
83 	ctl_rcvd_func           rcvd;           /* Notify nke when client reads data */
84 
85 	TAILQ_HEAD(, ctl_cb)    kcb_head;
86 	u_int32_t               lastunit;
87 };
88 
89 #if DEVELOPMENT || DEBUG
90 enum ctl_status {
91 	KCTL_DISCONNECTED = 0,
92 	KCTL_CONNECTING = 1,
93 	KCTL_CONNECTED = 2
94 };
95 #endif /* DEVELOPMENT || DEBUG */
96 
97 struct ctl_cb {
98 	TAILQ_ENTRY(ctl_cb)     next;           /* controller chain */
99 	lck_mtx_t               mtx;
100 	struct socket           *so;            /* controlling socket */
101 	struct kctl             *kctl;          /* back pointer to controller */
102 	void                    *userdata;
103 	struct sockaddr_ctl     sac;
104 	u_int32_t               usecount;
105 	u_int32_t               kcb_usecount;
106 	u_int32_t               require_clearing_count;
107 #if DEVELOPMENT || DEBUG
108 	enum ctl_status         status;
109 #endif /* DEVELOPMENT || DEBUG */
110 };
111 
112 #ifndef ROUNDUP64
113 #define ROUNDUP64(x) P2ROUNDUP((x), sizeof (u_int64_t))
114 #endif
115 
116 #ifndef ADVANCE64
117 #define ADVANCE64(p, n) (void*)((char *)(p) + ROUNDUP64(n))
118 #endif
119 
120 /*
121  * Definitions and vars for we support
122  */
123 
124 #define CTL_SENDSIZE    (2 * 1024)      /* default buffer size */
125 #define CTL_RECVSIZE    (8 * 1024)      /* default buffer size */
126 
127 /*
128  * Definitions and vars for we support
129  */
130 
131 const u_int32_t         ctl_maxunit = 65536;
132 static LCK_ATTR_DECLARE(ctl_lck_attr, 0, 0);
133 static LCK_GRP_DECLARE(ctl_lck_grp, "Kernel Control Protocol");
134 static LCK_MTX_DECLARE_ATTR(ctl_mtx, &ctl_lck_grp, &ctl_lck_attr);
135 
136 /* all the controllers are chained */
137 TAILQ_HEAD(kctl_list, kctl) ctl_head = TAILQ_HEAD_INITIALIZER(ctl_head);
138 
139 static int ctl_attach(struct socket *, int, struct proc *);
140 static int ctl_detach(struct socket *);
141 static int ctl_sofreelastref(struct socket *so);
142 static int ctl_bind(struct socket *, struct sockaddr *, struct proc *);
143 static int ctl_connect(struct socket *, struct sockaddr *, struct proc *);
144 static int ctl_disconnect(struct socket *);
145 static int ctl_ioctl(struct socket *so, u_long cmd, caddr_t data,
146     struct ifnet *ifp, struct proc *p);
147 static int ctl_send(struct socket *, int, struct mbuf *,
148     struct sockaddr *, struct mbuf *, struct proc *);
149 static int ctl_send_list(struct socket *, int, struct mbuf *,
150     struct sockaddr *, struct mbuf *, struct proc *);
151 static int ctl_ctloutput(struct socket *, struct sockopt *);
152 static int ctl_peeraddr(struct socket *so, struct sockaddr **nam);
153 static int ctl_usr_rcvd(struct socket *so, int flags);
154 
155 static struct kctl *ctl_find_by_name(const char *);
156 static struct kctl *ctl_find_by_id_unit(u_int32_t id, u_int32_t unit);
157 
158 static struct socket *kcb_find_socket(kern_ctl_ref kctlref, u_int32_t unit,
159     u_int32_t *);
160 static struct ctl_cb *kcb_find(struct kctl *, u_int32_t unit);
161 static void ctl_post_msg(u_int32_t event_code, u_int32_t id);
162 
163 static int ctl_lock(struct socket *, int, void *);
164 static int ctl_unlock(struct socket *, int, void *);
165 static lck_mtx_t * ctl_getlock(struct socket *, int);
166 
167 static struct pr_usrreqs ctl_usrreqs = {
168 	.pru_attach =           ctl_attach,
169 	.pru_bind =             ctl_bind,
170 	.pru_connect =          ctl_connect,
171 	.pru_control =          ctl_ioctl,
172 	.pru_detach =           ctl_detach,
173 	.pru_disconnect =       ctl_disconnect,
174 	.pru_peeraddr =         ctl_peeraddr,
175 	.pru_rcvd =             ctl_usr_rcvd,
176 	.pru_send =             ctl_send,
177 	.pru_send_list =        ctl_send_list,
178 	.pru_sosend =           sosend,
179 	.pru_sosend_list =      sosend_list,
180 	.pru_soreceive =        soreceive,
181 	.pru_soreceive_list =   soreceive_list,
182 };
183 
184 static struct protosw kctlsw[] = {
185 	{
186 		.pr_type =      SOCK_DGRAM,
187 		.pr_protocol =  SYSPROTO_CONTROL,
188 		.pr_flags =     PR_ATOMIC | PR_CONNREQUIRED | PR_PCBLOCK | PR_WANTRCVD,
189 		.pr_ctloutput = ctl_ctloutput,
190 		.pr_usrreqs =   &ctl_usrreqs,
191 		.pr_lock =      ctl_lock,
192 		.pr_unlock =    ctl_unlock,
193 		.pr_getlock =   ctl_getlock,
194 	},
195 	{
196 		.pr_type =      SOCK_STREAM,
197 		.pr_protocol =  SYSPROTO_CONTROL,
198 		.pr_flags =     PR_CONNREQUIRED | PR_PCBLOCK | PR_WANTRCVD,
199 		.pr_ctloutput = ctl_ctloutput,
200 		.pr_usrreqs =   &ctl_usrreqs,
201 		.pr_lock =      ctl_lock,
202 		.pr_unlock =    ctl_unlock,
203 		.pr_getlock =   ctl_getlock,
204 	}
205 };
206 
207 __private_extern__ int kctl_reg_list SYSCTL_HANDLER_ARGS;
208 __private_extern__ int kctl_pcblist SYSCTL_HANDLER_ARGS;
209 __private_extern__ int kctl_getstat SYSCTL_HANDLER_ARGS;
210 
211 
212 SYSCTL_NODE(_net_systm, OID_AUTO, kctl,
213     CTLFLAG_RW | CTLFLAG_LOCKED, 0, "Kernel control family");
214 
215 struct kctlstat kctlstat;
216 SYSCTL_PROC(_net_systm_kctl, OID_AUTO, stats,
217     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
218     kctl_getstat, "S,kctlstat", "");
219 
220 SYSCTL_PROC(_net_systm_kctl, OID_AUTO, reg_list,
221     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
222     kctl_reg_list, "S,xkctl_reg", "");
223 
224 SYSCTL_PROC(_net_systm_kctl, OID_AUTO, pcblist,
225     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
226     kctl_pcblist, "S,xkctlpcb", "");
227 
228 u_int32_t ctl_autorcvbuf_max = 256 * 1024;
229 SYSCTL_INT(_net_systm_kctl, OID_AUTO, autorcvbufmax,
230     CTLFLAG_RW | CTLFLAG_LOCKED, &ctl_autorcvbuf_max, 0, "");
231 
232 u_int32_t ctl_autorcvbuf_high = 0;
233 SYSCTL_INT(_net_systm_kctl, OID_AUTO, autorcvbufhigh,
234     CTLFLAG_RD | CTLFLAG_LOCKED, &ctl_autorcvbuf_high, 0, "");
235 
236 u_int32_t ctl_debug = 0;
237 SYSCTL_INT(_net_systm_kctl, OID_AUTO, debug,
238     CTLFLAG_RW | CTLFLAG_LOCKED, &ctl_debug, 0, "");
239 
240 #if DEVELOPMENT || DEBUG
241 u_int32_t ctl_panic_debug = 0;
242 SYSCTL_INT(_net_systm_kctl, OID_AUTO, panicdebug,
243     CTLFLAG_RW | CTLFLAG_LOCKED, &ctl_panic_debug, 0, "");
244 #endif /* DEVELOPMENT || DEBUG */
245 
246 #define KCTL_TBL_INC 16
247 
248 static uintptr_t kctl_tbl_size = 0;
249 static u_int32_t kctl_tbl_growing = 0;
250 static u_int32_t kctl_tbl_growing_waiting = 0;
251 static uintptr_t kctl_tbl_count = 0;
252 static struct kctl **kctl_table = NULL;
253 static uintptr_t kctl_ref_gencnt = 0;
254 
255 static void kctl_tbl_grow(void);
256 static kern_ctl_ref kctl_make_ref(struct kctl *kctl);
257 static void kctl_delete_ref(kern_ctl_ref);
258 static struct kctl *kctl_from_ref(kern_ctl_ref);
259 
260 /*
261  * Install the protosw's for the Kernel Control manager.
262  */
263 __private_extern__ void
kern_control_init(struct domain * dp)264 kern_control_init(struct domain *dp)
265 {
266 	struct protosw *pr;
267 	int i;
268 	int kctl_proto_count = (sizeof(kctlsw) / sizeof(struct protosw));
269 
270 	VERIFY(!(dp->dom_flags & DOM_INITIALIZED));
271 	VERIFY(dp == systemdomain);
272 
273 	for (i = 0, pr = &kctlsw[0]; i < kctl_proto_count; i++, pr++) {
274 		net_add_proto(pr, dp, 1);
275 	}
276 }
277 
278 static void
kcb_delete(struct ctl_cb * kcb)279 kcb_delete(struct ctl_cb *kcb)
280 {
281 	if (kcb != 0) {
282 		lck_mtx_destroy(&kcb->mtx, &ctl_lck_grp);
283 		kfree_type(struct ctl_cb, kcb);
284 	}
285 }
286 
287 /*
288  * Kernel Controller user-request functions
289  * attach function must exist and succeed
290  * detach not necessary
291  * we need a pcb for the per socket mutex
292  */
293 static int
ctl_attach(struct socket * so,int proto,struct proc * p)294 ctl_attach(struct socket *so, int proto, struct proc *p)
295 {
296 #pragma unused(proto, p)
297 	struct ctl_cb *kcb = 0;
298 
299 	kcb = kalloc_type(struct ctl_cb, Z_WAITOK | Z_ZERO | Z_NOFAIL);
300 
301 	lck_mtx_init(&kcb->mtx, &ctl_lck_grp, &ctl_lck_attr);
302 	kcb->so = so;
303 	so->so_pcb = (caddr_t)kcb;
304 
305 	return 0;
306 }
307 
308 static int
ctl_sofreelastref(struct socket * so)309 ctl_sofreelastref(struct socket *so)
310 {
311 	struct ctl_cb   *kcb = (struct ctl_cb *)so->so_pcb;
312 
313 	so->so_pcb = 0;
314 
315 	if (kcb != 0) {
316 		struct kctl             *kctl;
317 		if ((kctl = kcb->kctl) != 0) {
318 			lck_mtx_lock(&ctl_mtx);
319 			TAILQ_REMOVE(&kctl->kcb_head, kcb, next);
320 			kctlstat.kcs_pcbcount--;
321 			kctlstat.kcs_gencnt++;
322 			lck_mtx_unlock(&ctl_mtx);
323 		}
324 		kcb_delete(kcb);
325 	}
326 	sofreelastref(so, 1);
327 	return 0;
328 }
329 
330 /*
331  * Use this function and ctl_kcb_require_clearing to serialize
332  * critical calls into the kctl subsystem
333  */
334 static void
ctl_kcb_increment_use_count(struct ctl_cb * kcb,lck_mtx_t * mutex_held)335 ctl_kcb_increment_use_count(struct ctl_cb *kcb, lck_mtx_t *mutex_held)
336 {
337 	LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
338 	while (kcb->require_clearing_count > 0) {
339 		msleep(&kcb->require_clearing_count, mutex_held, PSOCK | PCATCH, "kcb_require_clearing", NULL);
340 	}
341 	kcb->kcb_usecount++;
342 }
343 
344 static void
ctl_kcb_require_clearing(struct ctl_cb * kcb,lck_mtx_t * mutex_held)345 ctl_kcb_require_clearing(struct ctl_cb *kcb, lck_mtx_t *mutex_held)
346 {
347 	assert(kcb->kcb_usecount != 0);
348 	kcb->require_clearing_count++;
349 	kcb->kcb_usecount--;
350 	while (kcb->kcb_usecount > 0) { // we need to wait until no one else is running
351 		msleep(&kcb->kcb_usecount, mutex_held, PSOCK | PCATCH, "kcb_usecount", NULL);
352 	}
353 	kcb->kcb_usecount++;
354 }
355 
356 static void
ctl_kcb_done_clearing(struct ctl_cb * kcb)357 ctl_kcb_done_clearing(struct ctl_cb *kcb)
358 {
359 	assert(kcb->require_clearing_count != 0);
360 	kcb->require_clearing_count--;
361 	wakeup((caddr_t)&kcb->require_clearing_count);
362 }
363 
364 static void
ctl_kcb_decrement_use_count(struct ctl_cb * kcb)365 ctl_kcb_decrement_use_count(struct ctl_cb *kcb)
366 {
367 	assert(kcb->kcb_usecount != 0);
368 	kcb->kcb_usecount--;
369 	wakeup((caddr_t)&kcb->kcb_usecount);
370 }
371 
372 static int
ctl_detach(struct socket * so)373 ctl_detach(struct socket *so)
374 {
375 	struct ctl_cb   *kcb = (struct ctl_cb *)so->so_pcb;
376 
377 	if (kcb == 0) {
378 		return 0;
379 	}
380 
381 	lck_mtx_t *mtx_held = socket_getlock(so, PR_F_WILLUNLOCK);
382 	ctl_kcb_increment_use_count(kcb, mtx_held);
383 	ctl_kcb_require_clearing(kcb, mtx_held);
384 
385 	if (kcb->kctl != NULL && kcb->kctl->bind != NULL &&
386 	    kcb->userdata != NULL && !(so->so_state & SS_ISCONNECTED)) {
387 		// The unit was bound, but not connected
388 		// Invoke the disconnected call to cleanup
389 		if (kcb->kctl->disconnect != NULL) {
390 			socket_unlock(so, 0);
391 			(*kcb->kctl->disconnect)(kcb->kctl->kctlref,
392 			    kcb->sac.sc_unit, kcb->userdata);
393 			socket_lock(so, 0);
394 		}
395 	}
396 
397 	soisdisconnected(so);
398 #if DEVELOPMENT || DEBUG
399 	kcb->status = KCTL_DISCONNECTED;
400 #endif /* DEVELOPMENT || DEBUG */
401 	so->so_flags |= SOF_PCBCLEARING;
402 	ctl_kcb_done_clearing(kcb);
403 	ctl_kcb_decrement_use_count(kcb);
404 	return 0;
405 }
406 
407 static int
ctl_setup_kctl(struct socket * so,struct sockaddr * nam,struct proc * p)408 ctl_setup_kctl(struct socket *so, struct sockaddr *nam, struct proc *p)
409 {
410 	struct kctl *kctl = NULL;
411 	int error = 0;
412 	struct sockaddr_ctl     sa;
413 	struct ctl_cb *kcb = (struct ctl_cb *)so->so_pcb;
414 	struct ctl_cb *kcb_next = NULL;
415 	u_quad_t sbmaxsize;
416 	u_int32_t recvbufsize, sendbufsize;
417 
418 	if (kcb == 0) {
419 		panic("ctl_setup_kctl so_pcb null");
420 	}
421 
422 	if (kcb->kctl != NULL) {
423 		// Already set up, skip
424 		return 0;
425 	}
426 
427 	if (nam->sa_len != sizeof(struct sockaddr_ctl)) {
428 		return EINVAL;
429 	}
430 
431 	bcopy(nam, &sa, sizeof(struct sockaddr_ctl));
432 
433 	lck_mtx_lock(&ctl_mtx);
434 	kctl = ctl_find_by_id_unit(sa.sc_id, sa.sc_unit);
435 	if (kctl == NULL) {
436 		lck_mtx_unlock(&ctl_mtx);
437 		return ENOENT;
438 	}
439 
440 	if (((kctl->flags & CTL_FLAG_REG_SOCK_STREAM) &&
441 	    (so->so_type != SOCK_STREAM)) ||
442 	    (!(kctl->flags & CTL_FLAG_REG_SOCK_STREAM) &&
443 	    (so->so_type != SOCK_DGRAM))) {
444 		lck_mtx_unlock(&ctl_mtx);
445 		return EPROTOTYPE;
446 	}
447 
448 	if (kctl->flags & CTL_FLAG_PRIVILEGED) {
449 		if (p == 0) {
450 			lck_mtx_unlock(&ctl_mtx);
451 			return EINVAL;
452 		}
453 		if (kauth_cred_issuser(kauth_cred_get()) == 0) {
454 			lck_mtx_unlock(&ctl_mtx);
455 			return EPERM;
456 		}
457 	}
458 
459 	if ((kctl->flags & CTL_FLAG_REG_ID_UNIT) || sa.sc_unit != 0) {
460 		if (kcb_find(kctl, sa.sc_unit) != NULL) {
461 			lck_mtx_unlock(&ctl_mtx);
462 			return EBUSY;
463 		}
464 	} else if (kctl->setup != NULL) {
465 		error = (*kctl->setup)(&sa.sc_unit, &kcb->userdata);
466 		if (error != 0) {
467 			lck_mtx_unlock(&ctl_mtx);
468 			return error;
469 		}
470 	} else {
471 		/* Find an unused ID, assumes control IDs are in order */
472 		u_int32_t unit = 1;
473 
474 		TAILQ_FOREACH(kcb_next, &kctl->kcb_head, next) {
475 			if (kcb_next->sac.sc_unit > unit) {
476 				/* Found a gap, lets fill it in */
477 				break;
478 			}
479 			unit = kcb_next->sac.sc_unit + 1;
480 			if (unit == ctl_maxunit) {
481 				break;
482 			}
483 		}
484 
485 		if (unit == ctl_maxunit) {
486 			lck_mtx_unlock(&ctl_mtx);
487 			return EBUSY;
488 		}
489 
490 		sa.sc_unit = unit;
491 	}
492 
493 	bcopy(&sa, &kcb->sac, sizeof(struct sockaddr_ctl));
494 	kcb->kctl = kctl;
495 	if (kcb_next != NULL) {
496 		TAILQ_INSERT_BEFORE(kcb_next, kcb, next);
497 	} else {
498 		TAILQ_INSERT_TAIL(&kctl->kcb_head, kcb, next);
499 	}
500 	kctlstat.kcs_pcbcount++;
501 	kctlstat.kcs_gencnt++;
502 	kctlstat.kcs_connections++;
503 	lck_mtx_unlock(&ctl_mtx);
504 
505 	/*
506 	 * rdar://15526688: Limit the send and receive sizes to sb_max
507 	 * by using the same scaling as sbreserve()
508 	 */
509 	sbmaxsize = (u_quad_t)sb_max * MCLBYTES / (MSIZE + MCLBYTES);
510 
511 	if (kctl->sendbufsize > sbmaxsize) {
512 		sendbufsize = (u_int32_t)sbmaxsize;
513 	} else {
514 		sendbufsize = kctl->sendbufsize;
515 	}
516 
517 	if (kctl->recvbufsize > sbmaxsize) {
518 		recvbufsize = (u_int32_t)sbmaxsize;
519 	} else {
520 		recvbufsize = kctl->recvbufsize;
521 	}
522 
523 	error = soreserve(so, sendbufsize, recvbufsize);
524 	if (error) {
525 		if (ctl_debug) {
526 			printf("%s - soreserve(%llx, %u, %u) error %d\n",
527 			    __func__, (uint64_t)VM_KERNEL_ADDRPERM(so),
528 			    sendbufsize, recvbufsize, error);
529 		}
530 		goto done;
531 	}
532 
533 done:
534 	if (error) {
535 		soisdisconnected(so);
536 #if DEVELOPMENT || DEBUG
537 		kcb->status = KCTL_DISCONNECTED;
538 #endif /* DEVELOPMENT || DEBUG */
539 		lck_mtx_lock(&ctl_mtx);
540 		TAILQ_REMOVE(&kctl->kcb_head, kcb, next);
541 		kcb->kctl = NULL;
542 		kcb->sac.sc_unit = 0;
543 		kctlstat.kcs_pcbcount--;
544 		kctlstat.kcs_gencnt++;
545 		kctlstat.kcs_conn_fail++;
546 		lck_mtx_unlock(&ctl_mtx);
547 	}
548 	return error;
549 }
550 
551 static int
ctl_bind(struct socket * so,struct sockaddr * nam,struct proc * p)552 ctl_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
553 {
554 	int error = 0;
555 	struct ctl_cb *kcb = (struct ctl_cb *)so->so_pcb;
556 
557 	if (kcb == NULL) {
558 		panic("ctl_bind so_pcb null");
559 	}
560 
561 	lck_mtx_t *mtx_held = socket_getlock(so, PR_F_WILLUNLOCK);
562 	ctl_kcb_increment_use_count(kcb, mtx_held);
563 	ctl_kcb_require_clearing(kcb, mtx_held);
564 
565 	error = ctl_setup_kctl(so, nam, p);
566 	if (error) {
567 		goto out;
568 	}
569 
570 	if (kcb->kctl == NULL) {
571 		panic("ctl_bind kctl null");
572 	}
573 
574 	if (kcb->kctl->bind == NULL) {
575 		error = EINVAL;
576 		goto out;
577 	}
578 
579 	socket_unlock(so, 0);
580 	error = (*kcb->kctl->bind)(kcb->kctl->kctlref, &kcb->sac, &kcb->userdata);
581 	socket_lock(so, 0);
582 
583 out:
584 	ctl_kcb_done_clearing(kcb);
585 	ctl_kcb_decrement_use_count(kcb);
586 	return error;
587 }
588 
589 static int
ctl_connect(struct socket * so,struct sockaddr * nam,struct proc * p)590 ctl_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
591 {
592 	int error = 0;
593 	struct ctl_cb *kcb = (struct ctl_cb *)so->so_pcb;
594 
595 	if (kcb == NULL) {
596 		panic("ctl_connect so_pcb null");
597 	}
598 
599 	lck_mtx_t *mtx_held = socket_getlock(so, PR_F_WILLUNLOCK);
600 	ctl_kcb_increment_use_count(kcb, mtx_held);
601 	ctl_kcb_require_clearing(kcb, mtx_held);
602 
603 #if DEVELOPMENT || DEBUG
604 	if (kcb->status != KCTL_DISCONNECTED && ctl_panic_debug) {
605 		panic("kctl already connecting/connected");
606 	}
607 	kcb->status = KCTL_CONNECTING;
608 #endif /* DEVELOPMENT || DEBUG */
609 
610 	error = ctl_setup_kctl(so, nam, p);
611 	if (error) {
612 		goto out;
613 	}
614 
615 	if (kcb->kctl == NULL) {
616 		panic("ctl_connect kctl null");
617 	}
618 
619 	soisconnecting(so);
620 	socket_unlock(so, 0);
621 	error = (*kcb->kctl->connect)(kcb->kctl->kctlref, &kcb->sac, &kcb->userdata);
622 	socket_lock(so, 0);
623 	if (error) {
624 		goto end;
625 	}
626 	soisconnected(so);
627 #if DEVELOPMENT || DEBUG
628 	kcb->status = KCTL_CONNECTED;
629 #endif /* DEVELOPMENT || DEBUG */
630 
631 end:
632 	if (error && kcb->kctl->disconnect) {
633 		/*
634 		 * XXX Make sure we Don't check the return value
635 		 * of disconnect here.
636 		 * ipsec/utun_ctl_disconnect will return error when
637 		 * disconnect gets called after connect failure.
638 		 * However if we decide to check for disconnect return
639 		 * value here. Please make sure to revisit
640 		 * ipsec/utun_ctl_disconnect.
641 		 */
642 		socket_unlock(so, 0);
643 		(*kcb->kctl->disconnect)(kcb->kctl->kctlref, kcb->sac.sc_unit, kcb->userdata);
644 		socket_lock(so, 0);
645 	}
646 	if (error) {
647 		soisdisconnected(so);
648 #if DEVELOPMENT || DEBUG
649 		kcb->status = KCTL_DISCONNECTED;
650 #endif /* DEVELOPMENT || DEBUG */
651 		lck_mtx_lock(&ctl_mtx);
652 		TAILQ_REMOVE(&kcb->kctl->kcb_head, kcb, next);
653 		kcb->kctl = NULL;
654 		kcb->sac.sc_unit = 0;
655 		kctlstat.kcs_pcbcount--;
656 		kctlstat.kcs_gencnt++;
657 		kctlstat.kcs_conn_fail++;
658 		lck_mtx_unlock(&ctl_mtx);
659 	}
660 out:
661 	ctl_kcb_done_clearing(kcb);
662 	ctl_kcb_decrement_use_count(kcb);
663 	return error;
664 }
665 
666 static int
ctl_disconnect(struct socket * so)667 ctl_disconnect(struct socket *so)
668 {
669 	struct ctl_cb   *kcb = (struct ctl_cb *)so->so_pcb;
670 
671 	if ((kcb = (struct ctl_cb *)so->so_pcb)) {
672 		lck_mtx_t *mtx_held = socket_getlock(so, PR_F_WILLUNLOCK);
673 		ctl_kcb_increment_use_count(kcb, mtx_held);
674 		ctl_kcb_require_clearing(kcb, mtx_held);
675 		struct kctl             *kctl = kcb->kctl;
676 
677 		if (kctl && kctl->disconnect) {
678 			socket_unlock(so, 0);
679 			(*kctl->disconnect)(kctl->kctlref, kcb->sac.sc_unit,
680 			    kcb->userdata);
681 			socket_lock(so, 0);
682 		}
683 
684 		soisdisconnected(so);
685 #if DEVELOPMENT || DEBUG
686 		kcb->status = KCTL_DISCONNECTED;
687 #endif /* DEVELOPMENT || DEBUG */
688 
689 		socket_unlock(so, 0);
690 		lck_mtx_lock(&ctl_mtx);
691 		kcb->kctl = 0;
692 		kcb->sac.sc_unit = 0;
693 		while (kcb->usecount != 0) {
694 			msleep(&kcb->usecount, &ctl_mtx, 0, "kcb->usecount", 0);
695 		}
696 		TAILQ_REMOVE(&kctl->kcb_head, kcb, next);
697 		kctlstat.kcs_pcbcount--;
698 		kctlstat.kcs_gencnt++;
699 		lck_mtx_unlock(&ctl_mtx);
700 		socket_lock(so, 0);
701 		ctl_kcb_done_clearing(kcb);
702 		ctl_kcb_decrement_use_count(kcb);
703 	}
704 	return 0;
705 }
706 
707 static int
ctl_peeraddr(struct socket * so,struct sockaddr ** nam)708 ctl_peeraddr(struct socket *so, struct sockaddr **nam)
709 {
710 	struct ctl_cb           *kcb = (struct ctl_cb *)so->so_pcb;
711 	struct kctl                     *kctl;
712 	struct sockaddr_ctl     sc;
713 
714 	if (kcb == NULL) {      /* sanity check */
715 		return ENOTCONN;
716 	}
717 
718 	if ((kctl = kcb->kctl) == NULL) {
719 		return EINVAL;
720 	}
721 
722 	bzero(&sc, sizeof(struct sockaddr_ctl));
723 	sc.sc_len = sizeof(struct sockaddr_ctl);
724 	sc.sc_family = AF_SYSTEM;
725 	sc.ss_sysaddr = AF_SYS_CONTROL;
726 	sc.sc_id =  kctl->id;
727 	sc.sc_unit = kcb->sac.sc_unit;
728 
729 	*nam = dup_sockaddr((struct sockaddr *)&sc, 1);
730 
731 	return 0;
732 }
733 
734 static void
ctl_sbrcv_trim(struct socket * so)735 ctl_sbrcv_trim(struct socket *so)
736 {
737 	struct sockbuf *sb = &so->so_rcv;
738 
739 	if (sb->sb_hiwat > sb->sb_idealsize) {
740 		u_int32_t diff;
741 		int32_t trim;
742 
743 		/*
744 		 * The difference between the ideal size and the
745 		 * current size is the upper bound of the trimage
746 		 */
747 		diff = sb->sb_hiwat - sb->sb_idealsize;
748 		/*
749 		 * We cannot trim below the outstanding data
750 		 */
751 		trim = sb->sb_hiwat - sb->sb_cc;
752 
753 		trim = imin(trim, (int32_t)diff);
754 
755 		if (trim > 0) {
756 			sbreserve(sb, (sb->sb_hiwat - trim));
757 
758 			if (ctl_debug) {
759 				printf("%s - shrunk to %d\n",
760 				    __func__, sb->sb_hiwat);
761 			}
762 		}
763 	}
764 }
765 
766 static int
ctl_usr_rcvd(struct socket * so,int flags)767 ctl_usr_rcvd(struct socket *so, int flags)
768 {
769 	int                     error = 0;
770 	struct ctl_cb           *kcb = (struct ctl_cb *)so->so_pcb;
771 	struct kctl                     *kctl;
772 
773 	if (kcb == NULL) {
774 		return ENOTCONN;
775 	}
776 
777 	lck_mtx_t *mtx_held = socket_getlock(so, PR_F_WILLUNLOCK);
778 	ctl_kcb_increment_use_count(kcb, mtx_held);
779 
780 	if ((kctl = kcb->kctl) == NULL) {
781 		error = EINVAL;
782 		goto out;
783 	}
784 
785 	if (kctl->rcvd) {
786 		socket_unlock(so, 0);
787 		(*kctl->rcvd)(kctl->kctlref, kcb->sac.sc_unit, kcb->userdata, flags);
788 		socket_lock(so, 0);
789 	}
790 
791 	ctl_sbrcv_trim(so);
792 
793 out:
794 	ctl_kcb_decrement_use_count(kcb);
795 	return error;
796 }
797 
798 static int
ctl_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * addr,struct mbuf * control,struct proc * p)799 ctl_send(struct socket *so, int flags, struct mbuf *m,
800     struct sockaddr *addr, struct mbuf *control,
801     struct proc *p)
802 {
803 #pragma unused(addr, p)
804 	int             error = 0;
805 	struct ctl_cb   *kcb = (struct ctl_cb *)so->so_pcb;
806 	struct kctl     *kctl;
807 
808 	if (control) {
809 		m_freem(control);
810 	}
811 
812 	if (kcb == NULL) {      /* sanity check */
813 		error = ENOTCONN;
814 	}
815 
816 	lck_mtx_t *mtx_held = socket_getlock(so, PR_F_WILLUNLOCK);
817 	ctl_kcb_increment_use_count(kcb, mtx_held);
818 
819 	if (error == 0 && (kctl = kcb->kctl) == NULL) {
820 		error = EINVAL;
821 	}
822 
823 	if (error == 0 && kctl->send) {
824 		so_tc_update_stats(m, so, m_get_service_class(m));
825 		socket_unlock(so, 0);
826 		error = (*kctl->send)(kctl->kctlref, kcb->sac.sc_unit, kcb->userdata,
827 		    m, flags);
828 		socket_lock(so, 0);
829 	} else {
830 		m_freem(m);
831 		if (error == 0) {
832 			error = ENOTSUP;
833 		}
834 	}
835 	if (error != 0) {
836 		OSIncrementAtomic64((SInt64 *)&kctlstat.kcs_send_fail);
837 	}
838 	ctl_kcb_decrement_use_count(kcb);
839 
840 	return error;
841 }
842 
843 static int
ctl_send_list(struct socket * so,int flags,struct mbuf * m,__unused struct sockaddr * addr,struct mbuf * control,__unused struct proc * p)844 ctl_send_list(struct socket *so, int flags, struct mbuf *m,
845     __unused struct sockaddr *addr, struct mbuf *control,
846     __unused struct proc *p)
847 {
848 	int             error = 0;
849 	struct ctl_cb   *kcb = (struct ctl_cb *)so->so_pcb;
850 	struct kctl     *kctl;
851 
852 	if (control) {
853 		m_freem_list(control);
854 	}
855 
856 	if (kcb == NULL) {      /* sanity check */
857 		error = ENOTCONN;
858 	}
859 
860 	lck_mtx_t *mtx_held = socket_getlock(so, PR_F_WILLUNLOCK);
861 	ctl_kcb_increment_use_count(kcb, mtx_held);
862 
863 	if (error == 0 && (kctl = kcb->kctl) == NULL) {
864 		error = EINVAL;
865 	}
866 
867 	if (error == 0 && kctl->send_list) {
868 		struct mbuf *nxt;
869 
870 		for (nxt = m; nxt != NULL; nxt = nxt->m_nextpkt) {
871 			so_tc_update_stats(nxt, so, m_get_service_class(nxt));
872 		}
873 
874 		socket_unlock(so, 0);
875 		error = (*kctl->send_list)(kctl->kctlref, kcb->sac.sc_unit,
876 		    kcb->userdata, m, flags);
877 		socket_lock(so, 0);
878 	} else if (error == 0 && kctl->send) {
879 		while (m != NULL && error == 0) {
880 			struct mbuf *nextpkt = m->m_nextpkt;
881 
882 			m->m_nextpkt = NULL;
883 			so_tc_update_stats(m, so, m_get_service_class(m));
884 			socket_unlock(so, 0);
885 			error = (*kctl->send)(kctl->kctlref, kcb->sac.sc_unit,
886 			    kcb->userdata, m, flags);
887 			socket_lock(so, 0);
888 			m = nextpkt;
889 		}
890 		if (m != NULL) {
891 			m_freem_list(m);
892 		}
893 	} else {
894 		m_freem_list(m);
895 		if (error == 0) {
896 			error = ENOTSUP;
897 		}
898 	}
899 	if (error != 0) {
900 		OSIncrementAtomic64((SInt64 *)&kctlstat.kcs_send_list_fail);
901 	}
902 	ctl_kcb_decrement_use_count(kcb);
903 
904 	return error;
905 }
906 
907 static errno_t
ctl_rcvbspace(struct socket * so,size_t datasize,u_int32_t kctlflags,u_int32_t flags)908 ctl_rcvbspace(struct socket *so, size_t datasize,
909     u_int32_t kctlflags, u_int32_t flags)
910 {
911 	struct sockbuf *sb = &so->so_rcv;
912 	u_int32_t space = sbspace(sb);
913 	errno_t error;
914 
915 	if ((kctlflags & CTL_FLAG_REG_CRIT) == 0) {
916 		if ((u_int32_t) space >= datasize) {
917 			error = 0;
918 		} else {
919 			error = ENOBUFS;
920 		}
921 	} else if ((flags & CTL_DATA_CRIT) == 0) {
922 		/*
923 		 * Reserve 25% for critical messages
924 		 */
925 		if (space < (sb->sb_hiwat >> 2) ||
926 		    space < datasize) {
927 			error = ENOBUFS;
928 		} else {
929 			error = 0;
930 		}
931 	} else {
932 		size_t autorcvbuf_max;
933 
934 		/*
935 		 * Allow overcommit of 25%
936 		 */
937 		autorcvbuf_max = min(sb->sb_idealsize + (sb->sb_idealsize >> 2),
938 		    ctl_autorcvbuf_max);
939 
940 		if ((u_int32_t) space >= datasize) {
941 			error = 0;
942 		} else if (tcp_cansbgrow(sb) &&
943 		    sb->sb_hiwat < autorcvbuf_max) {
944 			/*
945 			 * Grow with a little bit of leeway
946 			 */
947 			size_t grow = datasize - space + MSIZE;
948 			u_int32_t cc = (u_int32_t)MIN(MIN((sb->sb_hiwat + grow), autorcvbuf_max), UINT32_MAX);
949 
950 			if (sbreserve(sb, cc) == 1) {
951 				if (sb->sb_hiwat > ctl_autorcvbuf_high) {
952 					ctl_autorcvbuf_high = sb->sb_hiwat;
953 				}
954 
955 				/*
956 				 * A final check
957 				 */
958 				if ((u_int32_t) sbspace(sb) >= datasize) {
959 					error = 0;
960 				} else {
961 					error = ENOBUFS;
962 				}
963 
964 				if (ctl_debug) {
965 					printf("%s - grown to %d error %d\n",
966 					    __func__, sb->sb_hiwat, error);
967 				}
968 			} else {
969 				error = ENOBUFS;
970 			}
971 		} else {
972 			error = ENOBUFS;
973 		}
974 	}
975 	return error;
976 }
977 
978 errno_t
ctl_enqueuembuf(kern_ctl_ref kctlref,u_int32_t unit,struct mbuf * m,u_int32_t flags)979 ctl_enqueuembuf(kern_ctl_ref kctlref, u_int32_t unit, struct mbuf *m,
980     u_int32_t flags)
981 {
982 	struct socket   *so;
983 	errno_t         error = 0;
984 	int             len = m->m_pkthdr.len;
985 	u_int32_t       kctlflags;
986 
987 	so = kcb_find_socket(kctlref, unit, &kctlflags);
988 	if (so == NULL) {
989 		return EINVAL;
990 	}
991 
992 	if (ctl_rcvbspace(so, len, kctlflags, flags) != 0) {
993 		error = ENOBUFS;
994 		OSIncrementAtomic64((SInt64 *)&kctlstat.kcs_enqueue_fullsock);
995 		goto bye;
996 	}
997 	if ((flags & CTL_DATA_EOR)) {
998 		m->m_flags |= M_EOR;
999 	}
1000 
1001 	so_recv_data_stat(so, m, 0);
1002 	if (sbappend_nodrop(&so->so_rcv, m) != 0) {
1003 		if ((flags & CTL_DATA_NOWAKEUP) == 0) {
1004 			sorwakeup(so);
1005 		}
1006 	} else {
1007 		error = ENOBUFS;
1008 		OSIncrementAtomic64((SInt64 *)&kctlstat.kcs_enqueue_fullsock);
1009 	}
1010 bye:
1011 	if (ctl_debug && error != 0 && (flags & CTL_DATA_CRIT)) {
1012 		printf("%s - crit data err %d len %d hiwat %d cc: %d\n",
1013 		    __func__, error, len,
1014 		    so->so_rcv.sb_hiwat, so->so_rcv.sb_cc);
1015 	}
1016 
1017 	socket_unlock(so, 1);
1018 	if (error != 0) {
1019 		OSIncrementAtomic64((SInt64 *)&kctlstat.kcs_enqueue_fail);
1020 	}
1021 
1022 	return error;
1023 }
1024 
1025 /*
1026  * Compute space occupied by mbuf like sbappendrecord
1027  */
1028 static int
m_space(struct mbuf * m)1029 m_space(struct mbuf *m)
1030 {
1031 	int space = 0;
1032 	struct mbuf *nxt;
1033 
1034 	for (nxt = m; nxt != NULL; nxt = nxt->m_next) {
1035 		space += nxt->m_len;
1036 	}
1037 
1038 	return space;
1039 }
1040 
1041 errno_t
ctl_enqueuembuf_list(void * kctlref,u_int32_t unit,struct mbuf * m_list,u_int32_t flags,struct mbuf ** m_remain)1042 ctl_enqueuembuf_list(void *kctlref, u_int32_t unit, struct mbuf *m_list,
1043     u_int32_t flags, struct mbuf **m_remain)
1044 {
1045 	struct socket *so = NULL;
1046 	errno_t error = 0;
1047 	struct mbuf *m, *nextpkt;
1048 	int needwakeup = 0;
1049 	int len = 0;
1050 	u_int32_t kctlflags;
1051 
1052 	/*
1053 	 * Need to point the beginning of the list in case of early exit
1054 	 */
1055 	m = m_list;
1056 
1057 	/*
1058 	 * kcb_find_socket takes the socket lock with a reference
1059 	 */
1060 	so = kcb_find_socket(kctlref, unit, &kctlflags);
1061 	if (so == NULL) {
1062 		error = EINVAL;
1063 		goto done;
1064 	}
1065 
1066 	if (kctlflags & CTL_FLAG_REG_SOCK_STREAM) {
1067 		error = EOPNOTSUPP;
1068 		goto done;
1069 	}
1070 	if (flags & CTL_DATA_EOR) {
1071 		error = EINVAL;
1072 		goto done;
1073 	}
1074 
1075 	for (m = m_list; m != NULL; m = nextpkt) {
1076 		nextpkt = m->m_nextpkt;
1077 
1078 		if (m->m_pkthdr.len == 0 && ctl_debug) {
1079 			printf("%s: %llx m_pkthdr.len is 0",
1080 			    __func__, (uint64_t)VM_KERNEL_ADDRPERM(m));
1081 		}
1082 
1083 		/*
1084 		 * The mbuf is either appended or freed by sbappendrecord()
1085 		 * so it's not reliable from a data standpoint
1086 		 */
1087 		len = m_space(m);
1088 		if (ctl_rcvbspace(so, len, kctlflags, flags) != 0) {
1089 			error = ENOBUFS;
1090 			OSIncrementAtomic64(
1091 				(SInt64 *)&kctlstat.kcs_enqueue_fullsock);
1092 			break;
1093 		} else {
1094 			/*
1095 			 * Unlink from the list, m is on its own
1096 			 */
1097 			m->m_nextpkt = NULL;
1098 			so_recv_data_stat(so, m, 0);
1099 			if (sbappendrecord_nodrop(&so->so_rcv, m) != 0) {
1100 				needwakeup = 1;
1101 			} else {
1102 				/*
1103 				 * We free or return the remaining
1104 				 * mbufs in the list
1105 				 */
1106 				m = nextpkt;
1107 				error = ENOBUFS;
1108 				OSIncrementAtomic64(
1109 					(SInt64 *)&kctlstat.kcs_enqueue_fullsock);
1110 				break;
1111 			}
1112 		}
1113 	}
1114 	if (needwakeup && (flags & CTL_DATA_NOWAKEUP) == 0) {
1115 		sorwakeup(so);
1116 	}
1117 
1118 done:
1119 	if (so != NULL) {
1120 		if (ctl_debug && error != 0 && (flags & CTL_DATA_CRIT)) {
1121 			printf("%s - crit data err %d len %d hiwat %d cc: %d\n",
1122 			    __func__, error, len,
1123 			    so->so_rcv.sb_hiwat, so->so_rcv.sb_cc);
1124 		}
1125 
1126 		socket_unlock(so, 1);
1127 	}
1128 	if (m_remain) {
1129 		*m_remain = m;
1130 
1131 		if (m != NULL && socket_debug && so != NULL &&
1132 		    (so->so_options & SO_DEBUG)) {
1133 			struct mbuf *n;
1134 
1135 			printf("%s m_list %llx\n", __func__,
1136 			    (uint64_t) VM_KERNEL_ADDRPERM(m_list));
1137 			for (n = m; n != NULL; n = n->m_nextpkt) {
1138 				printf(" remain %llx m_next %llx\n",
1139 				    (uint64_t) VM_KERNEL_ADDRPERM(n),
1140 				    (uint64_t) VM_KERNEL_ADDRPERM(n->m_next));
1141 			}
1142 		}
1143 	} else {
1144 		if (m != NULL) {
1145 			m_freem_list(m);
1146 		}
1147 	}
1148 	if (error != 0) {
1149 		OSIncrementAtomic64((SInt64 *)&kctlstat.kcs_enqueue_fail);
1150 	}
1151 	return error;
1152 }
1153 
1154 errno_t
ctl_enqueuedata(void * kctlref,u_int32_t unit,void * data,size_t len,u_int32_t flags)1155 ctl_enqueuedata(void *kctlref, u_int32_t unit, void *data, size_t len,
1156     u_int32_t flags)
1157 {
1158 	struct socket   *so;
1159 	struct mbuf     *m;
1160 	errno_t         error = 0;
1161 	unsigned int    num_needed;
1162 	struct mbuf     *n;
1163 	size_t          curlen = 0;
1164 	u_int32_t       kctlflags;
1165 
1166 	so = kcb_find_socket(kctlref, unit, &kctlflags);
1167 	if (so == NULL) {
1168 		return EINVAL;
1169 	}
1170 
1171 	if (ctl_rcvbspace(so, len, kctlflags, flags) != 0) {
1172 		error = ENOBUFS;
1173 		OSIncrementAtomic64((SInt64 *)&kctlstat.kcs_enqueue_fullsock);
1174 		goto bye;
1175 	}
1176 
1177 	num_needed = 1;
1178 	m = m_allocpacket_internal(&num_needed, len, NULL, M_NOWAIT, 1, 0);
1179 	if (m == NULL) {
1180 		kctlstat.kcs_enqdata_mb_alloc_fail++;
1181 		if (ctl_debug) {
1182 			printf("%s: m_allocpacket_internal(%lu) failed\n",
1183 			    __func__, len);
1184 		}
1185 		error = ENOMEM;
1186 		goto bye;
1187 	}
1188 
1189 	for (n = m; n != NULL; n = n->m_next) {
1190 		size_t mlen = mbuf_maxlen(n);
1191 
1192 		if (mlen + curlen > len) {
1193 			mlen = len - curlen;
1194 		}
1195 		n->m_len = (int32_t)mlen;
1196 		bcopy((char *)data + curlen, n->m_data, mlen);
1197 		curlen += mlen;
1198 	}
1199 	mbuf_pkthdr_setlen(m, curlen);
1200 
1201 	if ((flags & CTL_DATA_EOR)) {
1202 		m->m_flags |= M_EOR;
1203 	}
1204 	so_recv_data_stat(so, m, 0);
1205 	/*
1206 	 * No need to call the "nodrop" variant of sbappend
1207 	 * because the mbuf is local to the scope of the function
1208 	 */
1209 	if (sbappend(&so->so_rcv, m) != 0) {
1210 		if ((flags & CTL_DATA_NOWAKEUP) == 0) {
1211 			sorwakeup(so);
1212 		}
1213 	} else {
1214 		kctlstat.kcs_enqdata_sbappend_fail++;
1215 		error = ENOBUFS;
1216 		OSIncrementAtomic64((SInt64 *)&kctlstat.kcs_enqueue_fullsock);
1217 	}
1218 
1219 bye:
1220 	if (ctl_debug && error != 0 && (flags & CTL_DATA_CRIT)) {
1221 		printf("%s - crit data err %d len %d hiwat %d cc: %d\n",
1222 		    __func__, error, (int)len,
1223 		    so->so_rcv.sb_hiwat, so->so_rcv.sb_cc);
1224 	}
1225 
1226 	socket_unlock(so, 1);
1227 	if (error != 0) {
1228 		OSIncrementAtomic64((SInt64 *)&kctlstat.kcs_enqueue_fail);
1229 	}
1230 	return error;
1231 }
1232 
1233 errno_t
ctl_getenqueuepacketcount(kern_ctl_ref kctlref,u_int32_t unit,u_int32_t * pcnt)1234 ctl_getenqueuepacketcount(kern_ctl_ref kctlref, u_int32_t unit, u_int32_t *pcnt)
1235 {
1236 	struct socket   *so;
1237 	u_int32_t cnt;
1238 	struct mbuf *m1;
1239 
1240 	if (pcnt == NULL) {
1241 		return EINVAL;
1242 	}
1243 
1244 	so = kcb_find_socket(kctlref, unit, NULL);
1245 	if (so == NULL) {
1246 		return EINVAL;
1247 	}
1248 
1249 	cnt = 0;
1250 	m1 = so->so_rcv.sb_mb;
1251 	while (m1 != NULL) {
1252 		if (m1->m_type == MT_DATA ||
1253 		    m1->m_type == MT_HEADER ||
1254 		    m1->m_type == MT_OOBDATA) {
1255 			cnt += 1;
1256 		}
1257 		m1 = m1->m_nextpkt;
1258 	}
1259 	*pcnt = cnt;
1260 
1261 	socket_unlock(so, 1);
1262 
1263 	return 0;
1264 }
1265 
1266 errno_t
ctl_getenqueuespace(kern_ctl_ref kctlref,u_int32_t unit,size_t * space)1267 ctl_getenqueuespace(kern_ctl_ref kctlref, u_int32_t unit, size_t *space)
1268 {
1269 	struct socket   *so;
1270 	long avail;
1271 
1272 	if (space == NULL) {
1273 		return EINVAL;
1274 	}
1275 
1276 	so = kcb_find_socket(kctlref, unit, NULL);
1277 	if (so == NULL) {
1278 		return EINVAL;
1279 	}
1280 
1281 	avail = sbspace(&so->so_rcv);
1282 	*space = (avail < 0) ? 0 : avail;
1283 	socket_unlock(so, 1);
1284 
1285 	return 0;
1286 }
1287 
1288 errno_t
ctl_getenqueuereadable(kern_ctl_ref kctlref,u_int32_t unit,u_int32_t * difference)1289 ctl_getenqueuereadable(kern_ctl_ref kctlref, u_int32_t unit,
1290     u_int32_t *difference)
1291 {
1292 	struct socket   *so;
1293 
1294 	if (difference == NULL) {
1295 		return EINVAL;
1296 	}
1297 
1298 	so = kcb_find_socket(kctlref, unit, NULL);
1299 	if (so == NULL) {
1300 		return EINVAL;
1301 	}
1302 
1303 	if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat) {
1304 		*difference = 0;
1305 	} else {
1306 		*difference = (so->so_rcv.sb_lowat - so->so_rcv.sb_cc);
1307 	}
1308 	socket_unlock(so, 1);
1309 
1310 	return 0;
1311 }
1312 
1313 static int
ctl_ctloutput(struct socket * so,struct sockopt * sopt)1314 ctl_ctloutput(struct socket *so, struct sockopt *sopt)
1315 {
1316 	struct ctl_cb   *kcb = (struct ctl_cb *)so->so_pcb;
1317 	struct kctl     *kctl;
1318 	int     error = 0;
1319 	void    *data = NULL;
1320 	size_t  data_len = 0;
1321 	size_t  len;
1322 
1323 	if (sopt->sopt_level != SYSPROTO_CONTROL) {
1324 		return EINVAL;
1325 	}
1326 
1327 	if (kcb == NULL) {      /* sanity check */
1328 		return ENOTCONN;
1329 	}
1330 
1331 	if ((kctl = kcb->kctl) == NULL) {
1332 		return EINVAL;
1333 	}
1334 
1335 	lck_mtx_t *mtx_held = socket_getlock(so, PR_F_WILLUNLOCK);
1336 	ctl_kcb_increment_use_count(kcb, mtx_held);
1337 
1338 	switch (sopt->sopt_dir) {
1339 	case SOPT_SET:
1340 		if (kctl->setopt == NULL) {
1341 			error = ENOTSUP;
1342 			goto out;
1343 		}
1344 		if (sopt->sopt_valsize != 0) {
1345 			data_len = sopt->sopt_valsize;
1346 			data = kalloc_data(data_len, Z_WAITOK | Z_ZERO);
1347 			if (data == NULL) {
1348 				data_len = 0;
1349 				error = ENOMEM;
1350 				goto out;
1351 			}
1352 			error = sooptcopyin(sopt, data,
1353 			    sopt->sopt_valsize, sopt->sopt_valsize);
1354 		}
1355 		if (error == 0) {
1356 			socket_unlock(so, 0);
1357 			error = (*kctl->setopt)(kctl->kctlref,
1358 			    kcb->sac.sc_unit, kcb->userdata, sopt->sopt_name,
1359 			    data, sopt->sopt_valsize);
1360 			socket_lock(so, 0);
1361 		}
1362 
1363 		kfree_data(data, data_len);
1364 		break;
1365 
1366 	case SOPT_GET:
1367 		if (kctl->getopt == NULL) {
1368 			error = ENOTSUP;
1369 			goto out;
1370 		}
1371 
1372 		if (sopt->sopt_valsize && sopt->sopt_val) {
1373 			data_len = sopt->sopt_valsize;
1374 			data = kalloc_data(data_len, Z_WAITOK | Z_ZERO);
1375 			if (data == NULL) {
1376 				data_len = 0;
1377 				error = ENOMEM;
1378 				goto out;
1379 			}
1380 			/*
1381 			 * 4108337 - copy user data in case the
1382 			 * kernel control needs it
1383 			 */
1384 			error = sooptcopyin(sopt, data,
1385 			    sopt->sopt_valsize, sopt->sopt_valsize);
1386 		}
1387 
1388 		if (error == 0) {
1389 			len = sopt->sopt_valsize;
1390 			socket_unlock(so, 0);
1391 			error = (*kctl->getopt)(kctl->kctlref, kcb->sac.sc_unit,
1392 			    kcb->userdata, sopt->sopt_name,
1393 			    data, &len);
1394 			if (data != NULL && len > sopt->sopt_valsize) {
1395 				panic_plain("ctl_ctloutput: ctl %s returned "
1396 				    "len (%lu) > sopt_valsize (%lu)\n",
1397 				    kcb->kctl->name, len,
1398 				    sopt->sopt_valsize);
1399 			}
1400 			socket_lock(so, 0);
1401 			if (error == 0) {
1402 				if (data != NULL) {
1403 					error = sooptcopyout(sopt, data, len);
1404 				} else {
1405 					sopt->sopt_valsize = len;
1406 				}
1407 			}
1408 		}
1409 
1410 		kfree_data(data, data_len);
1411 		break;
1412 	}
1413 
1414 out:
1415 	ctl_kcb_decrement_use_count(kcb);
1416 	return error;
1417 }
1418 
1419 static int
ctl_ioctl(struct socket * so,u_long cmd,caddr_t data,struct ifnet * ifp,struct proc * p)1420 ctl_ioctl(struct socket *so, u_long cmd, caddr_t data,
1421     struct ifnet *ifp, struct proc *p)
1422 {
1423 #pragma unused(so, ifp, p)
1424 	int     error = ENOTSUP;
1425 
1426 	switch (cmd) {
1427 	/* get the number of controllers */
1428 	case CTLIOCGCOUNT: {
1429 		struct kctl     *kctl;
1430 		u_int32_t n = 0;
1431 
1432 		lck_mtx_lock(&ctl_mtx);
1433 		TAILQ_FOREACH(kctl, &ctl_head, next)
1434 		n++;
1435 		lck_mtx_unlock(&ctl_mtx);
1436 
1437 		bcopy(&n, data, sizeof(n));
1438 		error = 0;
1439 		break;
1440 	}
1441 	case CTLIOCGINFO: {
1442 		struct ctl_info ctl_info;
1443 		struct kctl     *kctl = 0;
1444 		size_t name_len;
1445 
1446 		bcopy(data, &ctl_info, sizeof(ctl_info));
1447 		name_len = strnlen(ctl_info.ctl_name, MAX_KCTL_NAME);
1448 
1449 		if (name_len == 0 || name_len + 1 > MAX_KCTL_NAME) {
1450 			error = EINVAL;
1451 			break;
1452 		}
1453 		lck_mtx_lock(&ctl_mtx);
1454 		kctl = ctl_find_by_name(ctl_info.ctl_name);
1455 		lck_mtx_unlock(&ctl_mtx);
1456 		if (kctl == 0) {
1457 			error = ENOENT;
1458 			break;
1459 		}
1460 		ctl_info.ctl_id = kctl->id;
1461 		bcopy(&ctl_info, data, sizeof(ctl_info));
1462 		error = 0;
1463 		break;
1464 	}
1465 
1466 		/* add controls to get list of NKEs */
1467 	}
1468 
1469 	return error;
1470 }
1471 
1472 static void
kctl_tbl_grow(void)1473 kctl_tbl_grow(void)
1474 {
1475 	struct kctl **new_table;
1476 	uintptr_t new_size;
1477 
1478 	lck_mtx_assert(&ctl_mtx, LCK_MTX_ASSERT_OWNED);
1479 
1480 	if (kctl_tbl_growing) {
1481 		/* Another thread is allocating */
1482 		kctl_tbl_growing_waiting++;
1483 
1484 		do {
1485 			(void) msleep((caddr_t) &kctl_tbl_growing, &ctl_mtx,
1486 			    PSOCK | PCATCH, "kctl_tbl_growing", 0);
1487 		} while (kctl_tbl_growing);
1488 		kctl_tbl_growing_waiting--;
1489 	}
1490 	/* Another thread grew the table */
1491 	if (kctl_table != NULL && kctl_tbl_count < kctl_tbl_size) {
1492 		return;
1493 	}
1494 
1495 	/* Verify we have a sane size */
1496 	if (kctl_tbl_size + KCTL_TBL_INC >= UINT16_MAX) {
1497 		kctlstat.kcs_tbl_size_too_big++;
1498 		if (ctl_debug) {
1499 			printf("%s kctl_tbl_size %lu too big\n",
1500 			    __func__, kctl_tbl_size);
1501 		}
1502 		return;
1503 	}
1504 	kctl_tbl_growing = 1;
1505 
1506 	new_size = kctl_tbl_size + KCTL_TBL_INC;
1507 
1508 	lck_mtx_unlock(&ctl_mtx);
1509 	new_table = kalloc_type(struct kctl *, new_size, Z_WAITOK | Z_ZERO);
1510 	lck_mtx_lock(&ctl_mtx);
1511 
1512 	if (new_table != NULL) {
1513 		if (kctl_table != NULL) {
1514 			bcopy(kctl_table, new_table,
1515 			    kctl_tbl_size * sizeof(struct kctl *));
1516 
1517 			kfree_type(struct kctl *, kctl_tbl_size, kctl_table);
1518 		}
1519 		kctl_table = new_table;
1520 		kctl_tbl_size = new_size;
1521 	}
1522 
1523 	kctl_tbl_growing = 0;
1524 
1525 	if (kctl_tbl_growing_waiting) {
1526 		wakeup(&kctl_tbl_growing);
1527 	}
1528 }
1529 
1530 #define KCTLREF_INDEX_MASK 0x0000FFFF
1531 #define KCTLREF_GENCNT_MASK 0xFFFF0000
1532 #define KCTLREF_GENCNT_SHIFT 16
1533 
1534 static kern_ctl_ref
kctl_make_ref(struct kctl * kctl)1535 kctl_make_ref(struct kctl *kctl)
1536 {
1537 	uintptr_t i;
1538 
1539 	lck_mtx_assert(&ctl_mtx, LCK_MTX_ASSERT_OWNED);
1540 
1541 	if (kctl_tbl_count >= kctl_tbl_size) {
1542 		kctl_tbl_grow();
1543 	}
1544 
1545 	kctl->kctlref = NULL;
1546 	for (i = 0; i < kctl_tbl_size; i++) {
1547 		if (kctl_table[i] == NULL) {
1548 			uintptr_t ref;
1549 
1550 			/*
1551 			 * Reference is index plus one
1552 			 */
1553 			kctl_ref_gencnt += 1;
1554 
1555 			/*
1556 			 * Add generation count as salt to reference to prevent
1557 			 * use after deregister
1558 			 */
1559 			ref = ((kctl_ref_gencnt << KCTLREF_GENCNT_SHIFT) &
1560 			    KCTLREF_GENCNT_MASK) +
1561 			    ((i + 1) & KCTLREF_INDEX_MASK);
1562 
1563 			kctl->kctlref = (void *)(ref);
1564 			kctl_table[i] = kctl;
1565 			kctl_tbl_count++;
1566 			break;
1567 		}
1568 	}
1569 
1570 	if (kctl->kctlref == NULL) {
1571 		panic("%s no space in table", __func__);
1572 	}
1573 
1574 	if (ctl_debug > 0) {
1575 		printf("%s %p for %p\n",
1576 		    __func__, kctl->kctlref, kctl);
1577 	}
1578 
1579 	return kctl->kctlref;
1580 }
1581 
1582 static void
kctl_delete_ref(kern_ctl_ref kctlref)1583 kctl_delete_ref(kern_ctl_ref kctlref)
1584 {
1585 	/*
1586 	 * Reference is index plus one
1587 	 */
1588 	uintptr_t i = (((uintptr_t)kctlref) & KCTLREF_INDEX_MASK) - 1;
1589 
1590 	lck_mtx_assert(&ctl_mtx, LCK_MTX_ASSERT_OWNED);
1591 
1592 	if (i < kctl_tbl_size) {
1593 		struct kctl *kctl = kctl_table[i];
1594 
1595 		if (kctl->kctlref == kctlref) {
1596 			kctl_table[i] = NULL;
1597 			kctl_tbl_count--;
1598 		} else {
1599 			kctlstat.kcs_bad_kctlref++;
1600 		}
1601 	} else {
1602 		kctlstat.kcs_bad_kctlref++;
1603 	}
1604 }
1605 
1606 static struct kctl *
kctl_from_ref(kern_ctl_ref kctlref)1607 kctl_from_ref(kern_ctl_ref kctlref)
1608 {
1609 	/*
1610 	 * Reference is index plus one
1611 	 */
1612 	uintptr_t i = (((uintptr_t)kctlref) & KCTLREF_INDEX_MASK) - 1;
1613 	struct kctl *kctl = NULL;
1614 
1615 	lck_mtx_assert(&ctl_mtx, LCK_MTX_ASSERT_OWNED);
1616 
1617 	if (i >= kctl_tbl_size) {
1618 		kctlstat.kcs_bad_kctlref++;
1619 		return NULL;
1620 	}
1621 	kctl = kctl_table[i];
1622 	if (kctl->kctlref != kctlref) {
1623 		kctlstat.kcs_bad_kctlref++;
1624 		return NULL;
1625 	}
1626 	return kctl;
1627 }
1628 
1629 /*
1630  * Register/unregister a NKE
1631  */
1632 errno_t
ctl_register(struct kern_ctl_reg * userkctl,kern_ctl_ref * kctlref)1633 ctl_register(struct kern_ctl_reg *userkctl, kern_ctl_ref *kctlref)
1634 {
1635 	struct kctl     *kctl = NULL;
1636 	struct kctl     *kctl_next = NULL;
1637 	u_int32_t       id = 1;
1638 	size_t          name_len;
1639 	int             is_extended = 0;
1640 	int             is_setup = 0;
1641 
1642 	if (userkctl == NULL) { /* sanity check */
1643 		return EINVAL;
1644 	}
1645 	if (userkctl->ctl_connect == NULL) {
1646 		return EINVAL;
1647 	}
1648 	name_len = strlen(userkctl->ctl_name);
1649 	if (name_len == 0 || name_len + 1 > MAX_KCTL_NAME) {
1650 		return EINVAL;
1651 	}
1652 
1653 	kctl = kalloc_type(struct kctl, Z_WAITOK | Z_ZERO | Z_NOFAIL);
1654 
1655 	lck_mtx_lock(&ctl_mtx);
1656 
1657 	if (kctl_make_ref(kctl) == NULL) {
1658 		lck_mtx_unlock(&ctl_mtx);
1659 		kfree_type(struct kctl, kctl);
1660 		return ENOMEM;
1661 	}
1662 
1663 	/*
1664 	 * Kernel Control IDs
1665 	 *
1666 	 * CTL_FLAG_REG_ID_UNIT indicates the control ID and unit number are
1667 	 * static. If they do not exist, add them to the list in order. If the
1668 	 * flag is not set, we must find a new unique value. We assume the
1669 	 * list is in order. We find the last item in the list and add one. If
1670 	 * this leads to wrapping the id around, we start at the front of the
1671 	 * list and look for a gap.
1672 	 */
1673 
1674 	if ((userkctl->ctl_flags & CTL_FLAG_REG_ID_UNIT) == 0) {
1675 		/* Must dynamically assign an unused ID */
1676 
1677 		/* Verify the same name isn't already registered */
1678 		if (ctl_find_by_name(userkctl->ctl_name) != NULL) {
1679 			kctl_delete_ref(kctl->kctlref);
1680 			lck_mtx_unlock(&ctl_mtx);
1681 			kfree_type(struct kctl, kctl);
1682 			return EEXIST;
1683 		}
1684 
1685 		/* Start with 1 in case the list is empty */
1686 		id = 1;
1687 		kctl_next = TAILQ_LAST(&ctl_head, kctl_list);
1688 
1689 		if (kctl_next != NULL) {
1690 			/* List was not empty, add one to the last item */
1691 			id = kctl_next->id + 1;
1692 			kctl_next = NULL;
1693 
1694 			/*
1695 			 * If this wrapped the id number, start looking at
1696 			 * the front of the list for an unused id.
1697 			 */
1698 			if (id == 0) {
1699 				/* Find the next unused ID */
1700 				id = 1;
1701 
1702 				TAILQ_FOREACH(kctl_next, &ctl_head, next) {
1703 					if (kctl_next->id > id) {
1704 						/* We found a gap */
1705 						break;
1706 					}
1707 
1708 					id = kctl_next->id + 1;
1709 				}
1710 			}
1711 		}
1712 
1713 		userkctl->ctl_id = id;
1714 		kctl->id = id;
1715 		kctl->reg_unit = -1;
1716 	} else {
1717 		TAILQ_FOREACH(kctl_next, &ctl_head, next) {
1718 			if (kctl_next->id > userkctl->ctl_id) {
1719 				break;
1720 			}
1721 		}
1722 
1723 		if (ctl_find_by_id_unit(userkctl->ctl_id, userkctl->ctl_unit)) {
1724 			kctl_delete_ref(kctl->kctlref);
1725 			lck_mtx_unlock(&ctl_mtx);
1726 			kfree_type(struct kctl, kctl);
1727 			return EEXIST;
1728 		}
1729 		kctl->id = userkctl->ctl_id;
1730 		kctl->reg_unit = userkctl->ctl_unit;
1731 	}
1732 
1733 	is_extended = (userkctl->ctl_flags & CTL_FLAG_REG_EXTENDED);
1734 	is_setup = (userkctl->ctl_flags & CTL_FLAG_REG_SETUP);
1735 
1736 	strlcpy(kctl->name, userkctl->ctl_name, MAX_KCTL_NAME);
1737 	kctl->flags = userkctl->ctl_flags;
1738 
1739 	/*
1740 	 * Let the caller know the default send and receive sizes
1741 	 */
1742 	if (userkctl->ctl_sendsize == 0) {
1743 		kctl->sendbufsize = CTL_SENDSIZE;
1744 		userkctl->ctl_sendsize = kctl->sendbufsize;
1745 	} else {
1746 		kctl->sendbufsize = userkctl->ctl_sendsize;
1747 	}
1748 	if (userkctl->ctl_recvsize == 0) {
1749 		kctl->recvbufsize = CTL_RECVSIZE;
1750 		userkctl->ctl_recvsize = kctl->recvbufsize;
1751 	} else {
1752 		kctl->recvbufsize = userkctl->ctl_recvsize;
1753 	}
1754 
1755 	if (is_setup) {
1756 		kctl->setup = userkctl->ctl_setup;
1757 	}
1758 	kctl->bind = userkctl->ctl_bind;
1759 	kctl->connect = userkctl->ctl_connect;
1760 	kctl->disconnect = userkctl->ctl_disconnect;
1761 	kctl->send = userkctl->ctl_send;
1762 	kctl->setopt = userkctl->ctl_setopt;
1763 	kctl->getopt = userkctl->ctl_getopt;
1764 	if (is_extended) {
1765 		kctl->rcvd = userkctl->ctl_rcvd;
1766 		kctl->send_list = userkctl->ctl_send_list;
1767 	}
1768 
1769 	TAILQ_INIT(&kctl->kcb_head);
1770 
1771 	if (kctl_next) {
1772 		TAILQ_INSERT_BEFORE(kctl_next, kctl, next);
1773 	} else {
1774 		TAILQ_INSERT_TAIL(&ctl_head, kctl, next);
1775 	}
1776 
1777 	kctlstat.kcs_reg_count++;
1778 	kctlstat.kcs_gencnt++;
1779 
1780 	lck_mtx_unlock(&ctl_mtx);
1781 
1782 	*kctlref = kctl->kctlref;
1783 
1784 	ctl_post_msg(KEV_CTL_REGISTERED, kctl->id);
1785 	return 0;
1786 }
1787 
1788 errno_t
ctl_deregister(void * kctlref)1789 ctl_deregister(void *kctlref)
1790 {
1791 	struct kctl             *kctl;
1792 
1793 	lck_mtx_lock(&ctl_mtx);
1794 	if ((kctl = kctl_from_ref(kctlref)) == NULL) {
1795 		kctlstat.kcs_bad_kctlref++;
1796 		lck_mtx_unlock(&ctl_mtx);
1797 		if (ctl_debug != 0) {
1798 			printf("%s invalid kctlref %p\n",
1799 			    __func__, kctlref);
1800 		}
1801 		return EINVAL;
1802 	}
1803 
1804 	if (!TAILQ_EMPTY(&kctl->kcb_head)) {
1805 		lck_mtx_unlock(&ctl_mtx);
1806 		return EBUSY;
1807 	}
1808 
1809 	TAILQ_REMOVE(&ctl_head, kctl, next);
1810 
1811 	kctlstat.kcs_reg_count--;
1812 	kctlstat.kcs_gencnt++;
1813 
1814 	kctl_delete_ref(kctl->kctlref);
1815 	lck_mtx_unlock(&ctl_mtx);
1816 
1817 	ctl_post_msg(KEV_CTL_DEREGISTERED, kctl->id);
1818 	kfree_type(struct kctl, kctl);
1819 	return 0;
1820 }
1821 
1822 /*
1823  * Must be called with global ctl_mtx lock taked
1824  */
1825 static struct kctl *
ctl_find_by_name(const char * name)1826 ctl_find_by_name(const char *name)
1827 {
1828 	struct kctl     *kctl;
1829 
1830 	lck_mtx_assert(&ctl_mtx, LCK_MTX_ASSERT_OWNED);
1831 
1832 	TAILQ_FOREACH(kctl, &ctl_head, next)
1833 	if (strncmp(kctl->name, name, sizeof(kctl->name)) == 0) {
1834 		return kctl;
1835 	}
1836 
1837 	return NULL;
1838 }
1839 
1840 u_int32_t
ctl_id_by_name(const char * name)1841 ctl_id_by_name(const char *name)
1842 {
1843 	u_int32_t       ctl_id = 0;
1844 	struct kctl     *kctl;
1845 
1846 	lck_mtx_lock(&ctl_mtx);
1847 	kctl = ctl_find_by_name(name);
1848 	if (kctl) {
1849 		ctl_id = kctl->id;
1850 	}
1851 	lck_mtx_unlock(&ctl_mtx);
1852 
1853 	return ctl_id;
1854 }
1855 
1856 errno_t
ctl_name_by_id(u_int32_t id,char * out_name,size_t maxsize)1857 ctl_name_by_id(u_int32_t id, char *out_name, size_t maxsize)
1858 {
1859 	int             found = 0;
1860 	struct kctl *kctl;
1861 
1862 	lck_mtx_lock(&ctl_mtx);
1863 	TAILQ_FOREACH(kctl, &ctl_head, next) {
1864 		if (kctl->id == id) {
1865 			break;
1866 		}
1867 	}
1868 
1869 	if (kctl) {
1870 		if (maxsize > MAX_KCTL_NAME) {
1871 			maxsize = MAX_KCTL_NAME;
1872 		}
1873 		strlcpy(out_name, kctl->name, maxsize);
1874 		found = 1;
1875 	}
1876 	lck_mtx_unlock(&ctl_mtx);
1877 
1878 	return found ? 0 : ENOENT;
1879 }
1880 
1881 /*
1882  * Must be called with global ctl_mtx lock taked
1883  *
1884  */
1885 static struct kctl *
ctl_find_by_id_unit(u_int32_t id,u_int32_t unit)1886 ctl_find_by_id_unit(u_int32_t id, u_int32_t unit)
1887 {
1888 	struct kctl     *kctl;
1889 
1890 	lck_mtx_assert(&ctl_mtx, LCK_MTX_ASSERT_OWNED);
1891 
1892 	TAILQ_FOREACH(kctl, &ctl_head, next) {
1893 		if (kctl->id == id && (kctl->flags & CTL_FLAG_REG_ID_UNIT) == 0) {
1894 			return kctl;
1895 		} else if (kctl->id == id && kctl->reg_unit == unit) {
1896 			return kctl;
1897 		}
1898 	}
1899 	return NULL;
1900 }
1901 
1902 /*
1903  * Must be called with kernel controller lock taken
1904  */
1905 static struct ctl_cb *
kcb_find(struct kctl * kctl,u_int32_t unit)1906 kcb_find(struct kctl *kctl, u_int32_t unit)
1907 {
1908 	struct ctl_cb   *kcb;
1909 
1910 	lck_mtx_assert(&ctl_mtx, LCK_MTX_ASSERT_OWNED);
1911 
1912 	TAILQ_FOREACH(kcb, &kctl->kcb_head, next)
1913 	if (kcb->sac.sc_unit == unit) {
1914 		return kcb;
1915 	}
1916 
1917 	return NULL;
1918 }
1919 
1920 static struct socket *
kcb_find_socket(kern_ctl_ref kctlref,u_int32_t unit,u_int32_t * kctlflags)1921 kcb_find_socket(kern_ctl_ref kctlref, u_int32_t unit, u_int32_t *kctlflags)
1922 {
1923 	struct socket *so = NULL;
1924 	struct ctl_cb   *kcb;
1925 	void *lr_saved;
1926 	struct kctl *kctl;
1927 	int i;
1928 
1929 	lr_saved = __builtin_return_address(0);
1930 
1931 	lck_mtx_lock(&ctl_mtx);
1932 	/*
1933 	 * First validate the kctlref
1934 	 */
1935 	if ((kctl = kctl_from_ref(kctlref)) == NULL) {
1936 		kctlstat.kcs_bad_kctlref++;
1937 		lck_mtx_unlock(&ctl_mtx);
1938 		if (ctl_debug != 0) {
1939 			printf("%s invalid kctlref %p\n",
1940 			    __func__, kctlref);
1941 		}
1942 		return NULL;
1943 	}
1944 
1945 	kcb = kcb_find(kctl, unit);
1946 	if (kcb == NULL || kcb->kctl != kctl || (so = kcb->so) == NULL) {
1947 		lck_mtx_unlock(&ctl_mtx);
1948 		return NULL;
1949 	}
1950 	/*
1951 	 * This prevents the socket from being closed
1952 	 */
1953 	kcb->usecount++;
1954 	/*
1955 	 * Respect lock ordering: socket before ctl_mtx
1956 	 */
1957 	lck_mtx_unlock(&ctl_mtx);
1958 
1959 	socket_lock(so, 1);
1960 	/*
1961 	 * The socket lock history is more useful if we store
1962 	 * the address of the caller.
1963 	 */
1964 	i = (so->next_lock_lr + SO_LCKDBG_MAX - 1) % SO_LCKDBG_MAX;
1965 	so->lock_lr[i] = lr_saved;
1966 
1967 	lck_mtx_lock(&ctl_mtx);
1968 
1969 	if ((kctl = kctl_from_ref(kctlref)) == NULL || kcb->kctl == NULL) {
1970 		lck_mtx_unlock(&ctl_mtx);
1971 		socket_unlock(so, 1);
1972 		so = NULL;
1973 		lck_mtx_lock(&ctl_mtx);
1974 	} else if (kctlflags != NULL) {
1975 		*kctlflags = kctl->flags;
1976 	}
1977 
1978 	kcb->usecount--;
1979 	if (kcb->usecount == 0) {
1980 		wakeup((event_t)&kcb->usecount);
1981 	}
1982 
1983 	lck_mtx_unlock(&ctl_mtx);
1984 
1985 	return so;
1986 }
1987 
1988 static void
ctl_post_msg(u_int32_t event_code,u_int32_t id)1989 ctl_post_msg(u_int32_t event_code, u_int32_t id)
1990 {
1991 	struct ctl_event_data   ctl_ev_data;
1992 	struct kev_msg                  ev_msg;
1993 
1994 	lck_mtx_assert(&ctl_mtx, LCK_MTX_ASSERT_NOTOWNED);
1995 
1996 	bzero(&ev_msg, sizeof(struct kev_msg));
1997 	ev_msg.vendor_code = KEV_VENDOR_APPLE;
1998 
1999 	ev_msg.kev_class = KEV_SYSTEM_CLASS;
2000 	ev_msg.kev_subclass = KEV_CTL_SUBCLASS;
2001 	ev_msg.event_code = event_code;
2002 
2003 	/* common nke subclass data */
2004 	bzero(&ctl_ev_data, sizeof(ctl_ev_data));
2005 	ctl_ev_data.ctl_id = id;
2006 	ev_msg.dv[0].data_ptr = &ctl_ev_data;
2007 	ev_msg.dv[0].data_length = sizeof(ctl_ev_data);
2008 
2009 	ev_msg.dv[1].data_length = 0;
2010 
2011 	kev_post_msg(&ev_msg);
2012 }
2013 
2014 static int
ctl_lock(struct socket * so,int refcount,void * lr)2015 ctl_lock(struct socket *so, int refcount, void *lr)
2016 {
2017 	void *lr_saved;
2018 
2019 	if (lr == NULL) {
2020 		lr_saved = __builtin_return_address(0);
2021 	} else {
2022 		lr_saved = lr;
2023 	}
2024 
2025 	if (so->so_pcb != NULL) {
2026 		lck_mtx_lock(&((struct ctl_cb *)so->so_pcb)->mtx);
2027 	} else {
2028 		panic("ctl_lock: so=%p NO PCB! lr=%p lrh= %s",
2029 		    so, lr_saved, solockhistory_nr(so));
2030 		/* NOTREACHED */
2031 	}
2032 
2033 	if (so->so_usecount < 0) {
2034 		panic("ctl_lock: so=%p so_pcb=%p lr=%p ref=%x lrh= %s",
2035 		    so, so->so_pcb, lr_saved, so->so_usecount,
2036 		    solockhistory_nr(so));
2037 		/* NOTREACHED */
2038 	}
2039 
2040 	if (refcount) {
2041 		so->so_usecount++;
2042 	}
2043 
2044 	so->lock_lr[so->next_lock_lr] = lr_saved;
2045 	so->next_lock_lr = (so->next_lock_lr + 1) % SO_LCKDBG_MAX;
2046 	return 0;
2047 }
2048 
2049 static int
ctl_unlock(struct socket * so,int refcount,void * lr)2050 ctl_unlock(struct socket *so, int refcount, void *lr)
2051 {
2052 	void *lr_saved;
2053 	lck_mtx_t *mutex_held;
2054 
2055 	if (lr == NULL) {
2056 		lr_saved = __builtin_return_address(0);
2057 	} else {
2058 		lr_saved = lr;
2059 	}
2060 
2061 #if (MORE_KCTLLOCK_DEBUG && (DEVELOPMENT || DEBUG))
2062 	printf("ctl_unlock: so=%llx sopcb=%x lock=%llx ref=%u lr=%llx\n",
2063 	    (uint64_t)VM_KERNEL_ADDRPERM(so),
2064 	    (uint64_t)VM_KERNEL_ADDRPERM(so->so_pcb,
2065 	    (uint64_t)VM_KERNEL_ADDRPERM(&((struct ctl_cb *)so->so_pcb)->mtx),
2066 	    so->so_usecount, (uint64_t)VM_KERNEL_ADDRPERM(lr_saved));
2067 #endif /* (MORE_KCTLLOCK_DEBUG && (DEVELOPMENT || DEBUG)) */
2068 	if (refcount) {
2069 		so->so_usecount--;
2070 	}
2071 
2072 	if (so->so_usecount < 0) {
2073 		panic("ctl_unlock: so=%p usecount=%x lrh= %s",
2074 		    so, so->so_usecount, solockhistory_nr(so));
2075 		/* NOTREACHED */
2076 	}
2077 	if (so->so_pcb == NULL) {
2078 		panic("ctl_unlock: so=%p NO PCB usecount=%x lr=%p lrh= %s",
2079 		    so, so->so_usecount, (void *)lr_saved,
2080 		    solockhistory_nr(so));
2081 		/* NOTREACHED */
2082 	}
2083 	mutex_held = &((struct ctl_cb *)so->so_pcb)->mtx;
2084 
2085 	    lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
2086 	    so->unlock_lr[so->next_unlock_lr] = lr_saved;
2087 	    so->next_unlock_lr = (so->next_unlock_lr + 1) % SO_LCKDBG_MAX;
2088 	    lck_mtx_unlock(mutex_held);
2089 
2090 	    if (so->so_usecount == 0) {
2091 		ctl_sofreelastref(so);
2092 	}
2093 
2094 	    return 0;
2095 }
2096 
2097 static lck_mtx_t *
2098 ctl_getlock(struct socket *so, int flags)
2099 {
2100 #pragma unused(flags)
2101         struct ctl_cb *kcb = (struct ctl_cb *)so->so_pcb;
2102 
2103         if (so->so_pcb) {
2104                 if (so->so_usecount < 0) {
2105                         panic("ctl_getlock: so=%p usecount=%x lrh= %s",
2106                             so, so->so_usecount, solockhistory_nr(so));
2107 		}
2108                 return &kcb->mtx;
2109 	} else {
2110                 panic("ctl_getlock: so=%p NULL NO so_pcb %s",
2111                     so, solockhistory_nr(so));
2112                 return so->so_proto->pr_domain->dom_mtx;
2113 	}
2114 }
2115 
2116 __private_extern__ int
2117 kctl_reg_list SYSCTL_HANDLER_ARGS
2118 {
2119 #pragma unused(oidp, arg1, arg2)
2120         int error = 0;
2121         u_int64_t i, n;
2122         struct xsystmgen xsg;
2123         void *buf = NULL;
2124         struct kctl *kctl;
2125         size_t item_size = ROUNDUP64(sizeof(struct xkctl_reg));
2126 
2127         buf = kalloc_data(item_size, Z_WAITOK | Z_ZERO | Z_NOFAIL);
2128 
2129         lck_mtx_lock(&ctl_mtx);
2130 
2131         n = kctlstat.kcs_reg_count;
2132 
2133         if (req->oldptr == USER_ADDR_NULL) {
2134                 req->oldidx = (size_t)(n + n / 8) * sizeof(struct xkctl_reg);
2135                 goto done;
2136 	}
2137         if (req->newptr != USER_ADDR_NULL) {
2138                 error = EPERM;
2139                 goto done;
2140 	}
2141         bzero(&xsg, sizeof(xsg));
2142         xsg.xg_len = sizeof(xsg);
2143         xsg.xg_count = n;
2144         xsg.xg_gen = kctlstat.kcs_gencnt;
2145         xsg.xg_sogen = so_gencnt;
2146         error = SYSCTL_OUT(req, &xsg, sizeof(xsg));
2147         if (error) {
2148                 goto done;
2149 	}
2150         /*
2151          * We are done if there is no pcb
2152          */
2153         if (n == 0) {
2154                 goto done;
2155 	}
2156 
2157         for (i = 0, kctl = TAILQ_FIRST(&ctl_head);
2158             i < n && kctl != NULL;
2159             i++, kctl = TAILQ_NEXT(kctl, next)) {
2160                 struct xkctl_reg *xkr = (struct xkctl_reg *)buf;
2161                 struct ctl_cb *kcb;
2162                 u_int32_t pcbcount = 0;
2163 
2164                 TAILQ_FOREACH(kcb, &kctl->kcb_head, next)
2165                 pcbcount++;
2166 
2167                 bzero(buf, item_size);
2168 
2169                 xkr->xkr_len = sizeof(struct xkctl_reg);
2170                 xkr->xkr_kind = XSO_KCREG;
2171                 xkr->xkr_id = kctl->id;
2172                 xkr->xkr_reg_unit = kctl->reg_unit;
2173                 xkr->xkr_flags = kctl->flags;
2174                 xkr->xkr_kctlref = (uint64_t)(kctl->kctlref);
2175                 xkr->xkr_recvbufsize = kctl->recvbufsize;
2176                 xkr->xkr_sendbufsize = kctl->sendbufsize;
2177                 xkr->xkr_lastunit = kctl->lastunit;
2178                 xkr->xkr_pcbcount = pcbcount;
2179                 xkr->xkr_connect = (uint64_t)VM_KERNEL_UNSLIDE(kctl->connect);
2180                 xkr->xkr_disconnect =
2181                     (uint64_t)VM_KERNEL_UNSLIDE(kctl->disconnect);
2182                 xkr->xkr_send = (uint64_t)VM_KERNEL_UNSLIDE(kctl->send);
2183                 xkr->xkr_send_list =
2184                     (uint64_t)VM_KERNEL_UNSLIDE(kctl->send_list);
2185                 xkr->xkr_setopt = (uint64_t)VM_KERNEL_UNSLIDE(kctl->setopt);
2186                 xkr->xkr_getopt = (uint64_t)VM_KERNEL_UNSLIDE(kctl->getopt);
2187                 xkr->xkr_rcvd = (uint64_t)VM_KERNEL_UNSLIDE(kctl->rcvd);
2188                 strlcpy(xkr->xkr_name, kctl->name, sizeof(xkr->xkr_name));
2189 
2190                 error = SYSCTL_OUT(req, buf, item_size);
2191 	}
2192 
2193         if (error == 0) {
2194                 /*
2195                  * Give the user an updated idea of our state.
2196                  * If the generation differs from what we told
2197                  * her before, she knows that something happened
2198                  * while we were processing this request, and it
2199                  * might be necessary to retry.
2200                  */
2201                 bzero(&xsg, sizeof(xsg));
2202                 xsg.xg_len = sizeof(xsg);
2203                 xsg.xg_count = n;
2204                 xsg.xg_gen = kctlstat.kcs_gencnt;
2205                 xsg.xg_sogen = so_gencnt;
2206                 error = SYSCTL_OUT(req, &xsg, sizeof(xsg));
2207                 if (error) {
2208                         goto done;
2209 		}
2210 	}
2211 
2212 done:
2213         lck_mtx_unlock(&ctl_mtx);
2214 
2215         kfree_data(buf, item_size);
2216 
2217         return error;
2218 }
2219 
2220 __private_extern__ int
2221 kctl_pcblist SYSCTL_HANDLER_ARGS
2222 {
2223 #pragma unused(oidp, arg1, arg2)
2224         int error = 0;
2225         u_int64_t n, i;
2226         struct xsystmgen xsg;
2227         void *buf = NULL;
2228         struct kctl *kctl;
2229         size_t item_size = ROUNDUP64(sizeof(struct xkctlpcb)) +
2230             ROUNDUP64(sizeof(struct xsocket_n)) +
2231             2 * ROUNDUP64(sizeof(struct xsockbuf_n)) +
2232             ROUNDUP64(sizeof(struct xsockstat_n));
2233 
2234         buf = kalloc_data(item_size, Z_WAITOK | Z_ZERO | Z_NOFAIL);
2235 
2236         lck_mtx_lock(&ctl_mtx);
2237 
2238         n = kctlstat.kcs_pcbcount;
2239 
2240         if (req->oldptr == USER_ADDR_NULL) {
2241                 req->oldidx = (size_t)(n + n / 8) * item_size;
2242                 goto done;
2243 	}
2244         if (req->newptr != USER_ADDR_NULL) {
2245                 error = EPERM;
2246                 goto done;
2247 	}
2248         bzero(&xsg, sizeof(xsg));
2249         xsg.xg_len = sizeof(xsg);
2250         xsg.xg_count = n;
2251         xsg.xg_gen = kctlstat.kcs_gencnt;
2252         xsg.xg_sogen = so_gencnt;
2253         error = SYSCTL_OUT(req, &xsg, sizeof(xsg));
2254         if (error) {
2255                 goto done;
2256 	}
2257         /*
2258          * We are done if there is no pcb
2259          */
2260         if (n == 0) {
2261                 goto done;
2262 	}
2263 
2264         for (i = 0, kctl = TAILQ_FIRST(&ctl_head);
2265             i < n && kctl != NULL;
2266             kctl = TAILQ_NEXT(kctl, next)) {
2267                 struct ctl_cb *kcb;
2268 
2269                 for (kcb = TAILQ_FIRST(&kctl->kcb_head);
2270                     i < n && kcb != NULL;
2271                     i++, kcb = TAILQ_NEXT(kcb, next)) {
2272                         struct xkctlpcb *xk = (struct xkctlpcb *)buf;
2273                         struct xsocket_n *xso = (struct xsocket_n *)
2274                             ADVANCE64(xk, sizeof(*xk));
2275                         struct xsockbuf_n *xsbrcv = (struct xsockbuf_n *)
2276                             ADVANCE64(xso, sizeof(*xso));
2277                         struct xsockbuf_n *xsbsnd = (struct xsockbuf_n *)
2278                             ADVANCE64(xsbrcv, sizeof(*xsbrcv));
2279                         struct xsockstat_n *xsostats = (struct xsockstat_n *)
2280                             ADVANCE64(xsbsnd, sizeof(*xsbsnd));
2281 
2282                         bzero(buf, item_size);
2283 
2284                         xk->xkp_len = sizeof(struct xkctlpcb);
2285                         xk->xkp_kind = XSO_KCB;
2286                         xk->xkp_unit = kcb->sac.sc_unit;
2287                         xk->xkp_kctpcb = (uint64_t)VM_KERNEL_ADDRPERM(kcb);
2288                         xk->xkp_kctlref = (uint64_t)VM_KERNEL_ADDRPERM(kctl);
2289                         xk->xkp_kctlid = kctl->id;
2290                         strlcpy(xk->xkp_kctlname, kctl->name,
2291                             sizeof(xk->xkp_kctlname));
2292 
2293                         sotoxsocket_n(kcb->so, xso);
2294                         sbtoxsockbuf_n(kcb->so ?
2295                             &kcb->so->so_rcv : NULL, xsbrcv);
2296                         sbtoxsockbuf_n(kcb->so ?
2297                             &kcb->so->so_snd : NULL, xsbsnd);
2298                         sbtoxsockstat_n(kcb->so, xsostats);
2299 
2300                         error = SYSCTL_OUT(req, buf, item_size);
2301 		}
2302 	}
2303 
2304         if (error == 0) {
2305                 /*
2306                  * Give the user an updated idea of our state.
2307                  * If the generation differs from what we told
2308                  * her before, she knows that something happened
2309                  * while we were processing this request, and it
2310                  * might be necessary to retry.
2311                  */
2312                 bzero(&xsg, sizeof(xsg));
2313                 xsg.xg_len = sizeof(xsg);
2314                 xsg.xg_count = n;
2315                 xsg.xg_gen = kctlstat.kcs_gencnt;
2316                 xsg.xg_sogen = so_gencnt;
2317                 error = SYSCTL_OUT(req, &xsg, sizeof(xsg));
2318                 if (error) {
2319                         goto done;
2320 		}
2321 	}
2322 
2323 done:
2324         lck_mtx_unlock(&ctl_mtx);
2325 
2326         kfree_data(buf, item_size);
2327         return error;
2328 }
2329 
2330 int
2331 kctl_getstat SYSCTL_HANDLER_ARGS
2332 {
2333 #pragma unused(oidp, arg1, arg2)
2334         int error = 0;
2335 
2336         lck_mtx_lock(&ctl_mtx);
2337 
2338         if (req->newptr != USER_ADDR_NULL) {
2339                 error = EPERM;
2340                 goto done;
2341 	}
2342         if (req->oldptr == USER_ADDR_NULL) {
2343                 req->oldidx = sizeof(struct kctlstat);
2344                 goto done;
2345 	}
2346 
2347         error = SYSCTL_OUT(req, &kctlstat,
2348             MIN(sizeof(struct kctlstat), req->oldlen));
2349 done:
2350         lck_mtx_unlock(&ctl_mtx);
2351         return error;
2352 }
2353 
2354 void
2355 kctl_fill_socketinfo(struct socket *so, struct socket_info *si)
2356 {
2357         struct ctl_cb *kcb = (struct ctl_cb *)so->so_pcb;
2358         struct kern_ctl_info *kcsi =
2359             &si->soi_proto.pri_kern_ctl;
2360         struct kctl *kctl = kcb->kctl;
2361 
2362         si->soi_kind = SOCKINFO_KERN_CTL;
2363 
2364         if (kctl == 0) {
2365                 return;
2366 	}
2367 
2368         kcsi->kcsi_id = kctl->id;
2369         kcsi->kcsi_reg_unit = kctl->reg_unit;
2370         kcsi->kcsi_flags = kctl->flags;
2371         kcsi->kcsi_recvbufsize = kctl->recvbufsize;
2372         kcsi->kcsi_sendbufsize = kctl->sendbufsize;
2373         kcsi->kcsi_unit = kcb->sac.sc_unit;
2374         strlcpy(kcsi->kcsi_name, kctl->name, MAX_KCTL_NAME);
2375 }
2376