xref: /xnu-8796.121.2/osfmk/ipc/ipc_pset.c (revision c54f35ca767986246321eb901baf8f5ff7923f6a)
1 /*
2  * Copyright (c) 2000-2004 Apple Computer, 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  * @OSF_COPYRIGHT@
30  */
31 /*
32  * Mach Operating System
33  * Copyright (c) 1991,1990,1989 Carnegie Mellon University
34  * All Rights Reserved.
35  *
36  * Permission to use, copy, modify and distribute this software and its
37  * documentation is hereby granted, provided that both the copyright
38  * notice and this permission notice appear in all copies of the
39  * software, derivative works or modified versions, and any portions
40  * thereof, and that both notices appear in supporting documentation.
41  *
42  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45  *
46  * Carnegie Mellon requests users of this software to return to
47  *
48  *  Software Distribution Coordinator  or  [email protected]
49  *  School of Computer Science
50  *  Carnegie Mellon University
51  *  Pittsburgh PA 15213-3890
52  *
53  * any improvements or extensions that they make and grant Carnegie Mellon
54  * the rights to redistribute these changes.
55  */
56 /*
57  */
58 /*
59  *	File:	ipc/ipc_pset.c
60  *	Author:	Rich Draves
61  *	Date:	1989
62  *
63  *	Functions to manipulate IPC port sets.
64  */
65 
66 #include <mach/port.h>
67 #include <mach/kern_return.h>
68 #include <mach/message.h>
69 #include <ipc/ipc_mqueue.h>
70 #include <ipc/ipc_object.h>
71 #include <ipc/ipc_pset.h>
72 #include <ipc/ipc_right.h>
73 #include <ipc/ipc_space.h>
74 #include <ipc/ipc_port.h>
75 #include <ipc/ipc_kmsg.h>
76 #include <kern/policy_internal.h>
77 
78 #include <kern/kern_types.h>
79 
80 #include <vm/vm_map.h>
81 #include <libkern/section_keywords.h>
82 #include <pthread/priority_private.h>
83 
84 /* processor_set stole ipc_pset_init */
85 static void
ipc_port_set_init(ipc_pset_t pset,mach_port_name_t name,int policy)86 ipc_port_set_init(ipc_pset_t pset, mach_port_name_t name, int policy)
87 {
88 	waitq_init(&pset->ips_wqset, WQT_PORT_SET, policy | SYNC_POLICY_FIFO);
89 	klist_init(&pset->ips_klist);
90 	pset->ips_wqset.wqset_index = MACH_PORT_INDEX(name);
91 }
92 
93 /*
94  *	Routine:	ipc_pset_alloc
95  *	Purpose:
96  *		Allocate a port set.
97  *	Conditions:
98  *		Nothing locked.  If successful, the port set is returned
99  *		locked.  (The caller doesn't have a reference.)
100  *	Returns:
101  *		KERN_SUCCESS		The port set is allocated.
102  *		KERN_INVALID_TASK	The space is dead.
103  *		KERN_NO_SPACE		No room for an entry in the space.
104  */
105 
106 kern_return_t
ipc_pset_alloc(ipc_space_t space,mach_port_name_t * namep,ipc_pset_t * psetp)107 ipc_pset_alloc(
108 	ipc_space_t             space,
109 	mach_port_name_t        *namep,
110 	ipc_pset_t              *psetp)
111 {
112 	ipc_pset_t pset;
113 	mach_port_name_t name;
114 	kern_return_t kr;
115 
116 	kr = ipc_object_alloc(space, IOT_PORT_SET,
117 	    MACH_PORT_TYPE_PORT_SET, 0,
118 	    &name, (ipc_object_t *) &pset);
119 	if (kr != KERN_SUCCESS) {
120 		return kr;
121 	}
122 	/* space is locked */
123 
124 	ipc_port_set_init(pset, name, SYNC_POLICY_INIT_LOCKED);
125 	/* port set is locked */
126 
127 	is_write_unlock(space);
128 
129 	*namep = name;
130 	*psetp = pset;
131 	return KERN_SUCCESS;
132 }
133 
134 /*
135  *	Routine:	ipc_pset_alloc_name
136  *	Purpose:
137  *		Allocate a port set, with a specific name.
138  *	Conditions:
139  *		Nothing locked.  If successful, the port set is returned
140  *		locked.  (The caller doesn't have a reference.)
141  *	Returns:
142  *		KERN_SUCCESS		The port set is allocated.
143  *		KERN_INVALID_TASK	The space is dead.
144  *		KERN_NAME_EXISTS	The name already denotes a right.
145  */
146 
147 kern_return_t
ipc_pset_alloc_name(ipc_space_t space,mach_port_name_t name,ipc_pset_t * psetp)148 ipc_pset_alloc_name(
149 	ipc_space_t             space,
150 	mach_port_name_t        name,
151 	ipc_pset_t              *psetp)
152 {
153 	return ipc_object_alloc_name(space, IOT_PORT_SET,
154 	           MACH_PORT_TYPE_PORT_SET, 0,
155 	           name, (ipc_object_t *)psetp, ^(ipc_object_t object){
156 		ipc_port_set_init(ips_object_to_pset(object), name,
157 		SYNC_POLICY_INIT_LOCKED);
158 	});
159 }
160 
161 
162 /*
163  *	Routine:	ipc_pset_alloc_special
164  *	Purpose:
165  *		Allocate a port set in a special space.
166  *		The new port set is returned with one ref.
167  *		If unsuccessful, IPS_NULL is returned.
168  *	Conditions:
169  *		Nothing locked.
170  */
171 ipc_pset_t
ipc_pset_alloc_special(__assert_only ipc_space_t space)172 ipc_pset_alloc_special(
173 	__assert_only ipc_space_t space)
174 {
175 	ipc_pset_t pset;
176 
177 	assert(space != IS_NULL);
178 	assert(!is_active(space));
179 
180 	pset = ips_object_to_pset(io_alloc(IOT_PORT_SET, Z_WAITOK | Z_ZERO));
181 	if (pset == IPS_NULL) {
182 		return IPS_NULL;
183 	}
184 
185 	os_atomic_init(&pset->ips_object.io_bits, io_makebits(IOT_PORT_SET));
186 	os_atomic_init(&pset->ips_object.io_references, 1);
187 
188 	ipc_port_set_init(pset, MACH_PORT_SPECIAL_DEFAULT, 0);
189 
190 	return pset;
191 }
192 
193 
194 /*
195  *	Routine:	ipc_pset_destroy
196  *	Purpose:
197  *		Destroys a port_set.
198  *	Conditions:
199  *		The port_set is locked and alive.
200  *		The caller has a reference, which is consumed.
201  *		Afterwards, the port_set is unlocked and dead.
202  */
203 
204 void
ipc_pset_destroy(ipc_space_t space,ipc_pset_t pset)205 ipc_pset_destroy(
206 	ipc_space_t     space,
207 	ipc_pset_t      pset)
208 {
209 	waitq_link_list_t free_l = { };
210 
211 	assert(ips_active(pset));
212 
213 	io_bits_andnot(ips_to_object(pset), IO_BITS_ACTIVE);
214 
215 	/*
216 	 * Set all waiters on the portset running to
217 	 * discover the change.
218 	 *
219 	 * Then under the same lock hold, deinit the waitq-set,
220 	 * which will remove all the member message queues,
221 	 * linkages and clean up preposts.
222 	 */
223 	ipc_mqueue_changed(space, &pset->ips_wqset);
224 	waitq_invalidate(&pset->ips_wqset);
225 	waitq_set_unlink_all_locked(&pset->ips_wqset, &free_l);
226 
227 	ips_mq_unlock(pset);
228 
229 	ips_release(pset);       /* consume the ref our caller gave us */
230 
231 	waitq_link_free_list(WQT_PORT_SET, &free_l);
232 }
233 
234 /*
235  *	Routine:	ipc_pset_finalize
236  *	Purpose:
237  *		Called on last reference deallocate to
238  *		free any remaining data associated with the pset.
239  *	Conditions:
240  *		Nothing locked.
241  */
242 void
ipc_pset_finalize(ipc_pset_t pset)243 ipc_pset_finalize(
244 	ipc_pset_t              pset)
245 {
246 	waitq_deinit(&pset->ips_wqset);
247 }
248 
249 
250 /*
251  * Kqueue EVFILT_MACHPORT support
252  *
253  * - kn_ipc_obj points to the monitored ipc port or pset. If the knote is
254  *   using a kqwl, it is eligible to participate in sync IPC overrides.
255  *
256  *   For the first such sync IPC message in the port, we set up the port's
257  *   turnstile to directly push on the kqwl's turnstile (which is in turn set up
258  *   during filt_machportattach). If userspace responds to the message, the
259  *   turnstile push is severed the point of reply. If userspace returns without
260  *   responding to the message, we sever the turnstile push at the
261  *   point of reenabling the knote to deliver the next message. This is why the
262  *   knote needs to remember the port. For more details, see also
263  *   filt_machport_turnstile_complete.
264  *
265  *   If there are multiple other sync IPC messages in the port, messages 2 to n
266  *   redirect their turnstile push to the kqwl through an intermediatry "knote"
267  *   turnstile which in turn, pushes on the kqwl turnstile. This knote turnstile
268  *   is stored in the kn_hook. See also filt_machport_turnstile_prepare_lazily.
269  *
270  * - (in/out) ext[0] holds a mach_vm_address_t to a userspace buffer
271  *   that can be used to direct-deliver messages when
272  *   MACH_RCV_MSG is set in kn_sfflags
273  *
274  * - (in/out) ext[1] holds a mach_msg_size_t representing the size
275  *   of the userspace buffer held in ext[0].
276  *
277  * - (out)    ext[2] is used to deliver qos information
278  *   about the send queue to userspace.
279  *
280  * - (abused) ext[3] is used in kernel to hold a reference to the first port
281  *   with a turnstile that participate to sync IPC override. For more details,
282  *   see filt_machport_stash_port
283  *
284  * - kn_hook is optionally a "knote" turnstile. It is used as the inheritor
285  *   of turnstiles for rights copied out as part of direct message delivery
286  *   when they can participate to sync IPC override.
287  *
288  *   It is used to atomically neuter the sync IPC override when the knote is
289  *   re-enabled.
290  *
291  */
292 
293 #include <sys/event.h>
294 #include <sys/errno.h>
295 
296 static int
filt_machport_filter_result(struct knote * kn,ipc_object_t object)297 filt_machport_filter_result(struct knote *kn, ipc_object_t object)
298 {
299 	struct waitq *wq = io_waitq(object);
300 	ipc_kmsg_t first;
301 	int result = 0;
302 
303 	io_lock_held(object);
304 
305 	if (kn->kn_sfflags & MACH_RCV_MSG) {
306 		result = FILTER_RESET_EVENT_QOS;
307 	}
308 
309 	if (!waitq_is_valid(wq)) {
310 		return result;
311 	}
312 
313 	if (waitq_type(wq) == WQT_PORT_SET) {
314 		ipc_pset_t pset = ips_object_to_pset(object);
315 		return waitq_set_first_prepost(&pset->ips_wqset, WQS_PREPOST_PEEK) ?
316 		       FILTER_ACTIVE : 0;
317 	}
318 
319 	ipc_port_t port = ip_object_to_port(object);
320 	struct kqueue *kqwl = knote_get_kq(kn);
321 
322 	if (port->ip_kernel_iotier_override != kqueue_get_iotier_override(kqwl)) {
323 		kqueue_set_iotier_override(kqwl, port->ip_kernel_iotier_override);
324 		result |= FILTER_ADJUST_EVENT_IOTIER_BIT;
325 	}
326 
327 	first = ipc_kmsg_queue_first(&port->ip_messages.imq_messages);
328 	if (!first) {
329 		return result;
330 	}
331 
332 	result = FILTER_ACTIVE;
333 	if (kn->kn_sfflags & MACH_RCV_MSG) {
334 		result |= FILTER_ADJUST_EVENT_QOS(first->ikm_qos_override);
335 	}
336 
337 #if CONFIG_PREADOPT_TG
338 	struct thread_group *tg = ipc_kmsg_get_thread_group(first);
339 	if (tg) {
340 		struct kqueue *kq = knote_get_kq(kn);
341 		kqueue_set_preadopted_thread_group(kq, tg,
342 		    first->ikm_qos_override);
343 	}
344 #endif
345 
346 	return result;
347 }
348 
349 struct turnstile *
filt_ipc_kqueue_turnstile(struct knote * kn)350 filt_ipc_kqueue_turnstile(struct knote *kn)
351 {
352 	assert(kn->kn_filter == EVFILT_MACHPORT || kn->kn_filter == EVFILT_WORKLOOP);
353 	return kqueue_turnstile(knote_get_kq(kn));
354 }
355 
356 bool
filt_machport_kqueue_has_turnstile(struct knote * kn)357 filt_machport_kqueue_has_turnstile(struct knote *kn)
358 {
359 	assert(kn->kn_filter == EVFILT_MACHPORT);
360 	return ((kn->kn_sfflags & MACH_RCV_MSG) || (kn->kn_sfflags & MACH_RCV_SYNC_PEEK))
361 	       && (kn->kn_flags & EV_DISPATCH);
362 }
363 
364 /*
365  * Stashes a port that participate to sync IPC override on the knote until the
366  * knote is re-enabled.
367  *
368  * It returns:
369  * - the turnstile to use as an inheritor for the stashed port
370  * - the kind of stash that happened as PORT_SYNC_* value among:
371  *   o not stashed (no sync IPC support)
372  *   o stashed in the knote (in kn_ext[3])
373  *   o to be hooked to the kn_hook knote
374  */
375 struct turnstile *
filt_machport_stash_port(struct knote * kn,ipc_port_t port,int * link)376 filt_machport_stash_port(struct knote *kn, ipc_port_t port, int *link)
377 {
378 	struct turnstile *ts = TURNSTILE_NULL;
379 
380 	if (kn->kn_filter == EVFILT_WORKLOOP) {
381 		assert(kn->kn_ipc_obj == NULL);
382 		kn->kn_ipc_obj = ip_to_object(port);
383 		ip_reference(port);
384 		if (link) {
385 			*link = PORT_SYNC_LINK_WORKLOOP_KNOTE;
386 		}
387 		ts = filt_ipc_kqueue_turnstile(kn);
388 	} else if (!filt_machport_kqueue_has_turnstile(kn)) {
389 		if (link) {
390 			*link = PORT_SYNC_LINK_NO_LINKAGE;
391 		}
392 	} else if (kn->kn_ext[3] == 0) {
393 		ip_reference(port);
394 		kn->kn_ext[3] = (uintptr_t)port;
395 		ts = filt_ipc_kqueue_turnstile(kn);
396 		if (link) {
397 			*link = PORT_SYNC_LINK_WORKLOOP_KNOTE;
398 		}
399 	} else {
400 		ts = (struct turnstile *)kn->kn_hook;
401 		if (link) {
402 			*link = PORT_SYNC_LINK_WORKLOOP_STASH;
403 		}
404 	}
405 
406 	return ts;
407 }
408 
409 /*
410  * Lazily prepare a turnstile so that filt_machport_stash_port()
411  * can be called with the mqueue lock held.
412  *
413  * It will allocate a turnstile in kn_hook if:
414  * - the knote supports sync IPC override,
415  * - we already stashed a port in kn_ext[3],
416  * - the object that will be copied out has a chance to ask to be stashed.
417  *
418  * It is setup so that its inheritor is the workloop turnstile that has been
419  * allocated when this knote was attached.
420  */
421 void
filt_machport_turnstile_prepare_lazily(struct knote * kn,mach_msg_type_name_t msgt_name,ipc_port_t port)422 filt_machport_turnstile_prepare_lazily(
423 	struct knote *kn,
424 	mach_msg_type_name_t msgt_name,
425 	ipc_port_t port)
426 {
427 	/* This is called from within filt_machportprocess */
428 	assert((kn->kn_status & KN_SUPPRESSED) && (kn->kn_status & KN_LOCKED));
429 
430 	if (!filt_machport_kqueue_has_turnstile(kn)) {
431 		return;
432 	}
433 
434 	if (kn->kn_ext[3] == 0 || kn->kn_hook) {
435 		return;
436 	}
437 
438 	struct turnstile *ts = filt_ipc_kqueue_turnstile(kn);
439 	if ((msgt_name == MACH_MSG_TYPE_PORT_SEND_ONCE && port->ip_specialreply) ||
440 	    (msgt_name == MACH_MSG_TYPE_PORT_RECEIVE)) {
441 		struct turnstile *kn_ts = turnstile_alloc();
442 		kn_ts = turnstile_prepare((uintptr_t)kn,
443 		    (struct turnstile **)&kn->kn_hook, kn_ts, TURNSTILE_KNOTE);
444 		turnstile_update_inheritor(kn_ts, ts,
445 		    TURNSTILE_IMMEDIATE_UPDATE | TURNSTILE_INHERITOR_TURNSTILE);
446 		turnstile_cleanup();
447 	}
448 }
449 
450 static void
filt_machport_turnstile_complete_port(struct knote * kn,ipc_port_t port)451 filt_machport_turnstile_complete_port(struct knote *kn, ipc_port_t port)
452 {
453 	struct turnstile *ts = TURNSTILE_NULL;
454 
455 	ip_mq_lock(port);
456 	if (port->ip_specialreply) {
457 		/*
458 		 * If the reply has been sent to the special reply port already,
459 		 * then the special reply port may already be reused to do something
460 		 * entirely different.
461 		 *
462 		 * However, the only reason for it to still point to this knote is
463 		 * that it's still waiting for a reply, so when this is the case,
464 		 * neuter the linkage.
465 		 */
466 		if (port->ip_sync_link_state == PORT_SYNC_LINK_WORKLOOP_KNOTE &&
467 		    port->ip_sync_inheritor_knote == kn) {
468 			ipc_port_adjust_special_reply_port_locked(port, NULL,
469 			    (IPC_PORT_ADJUST_SR_NONE | IPC_PORT_ADJUST_SR_ENABLE_EVENT), FALSE);
470 			/* port unlocked */
471 		} else {
472 			ip_mq_unlock(port);
473 		}
474 	} else {
475 		/*
476 		 * For receive rights, if their IMQ_KNOTE() is still this
477 		 * knote, then sever the link.
478 		 */
479 		if (port->ip_sync_link_state == PORT_SYNC_LINK_WORKLOOP_KNOTE &&
480 		    port->ip_messages.imq_inheritor_knote == kn) {
481 			ipc_port_adjust_sync_link_state_locked(port, PORT_SYNC_LINK_ANY, NULL);
482 			ts = port_send_turnstile(port);
483 		}
484 		if (ts) {
485 			turnstile_reference(ts);
486 			turnstile_update_inheritor(ts, TURNSTILE_INHERITOR_NULL,
487 			    TURNSTILE_IMMEDIATE_UPDATE);
488 		}
489 		ip_mq_unlock(port);
490 
491 		if (ts) {
492 			turnstile_update_inheritor_complete(ts,
493 			    TURNSTILE_INTERLOCK_NOT_HELD);
494 			turnstile_deallocate(ts);
495 		}
496 	}
497 
498 	ip_release(port);
499 }
500 
501 void
filt_wldetach_sync_ipc(struct knote * kn)502 filt_wldetach_sync_ipc(struct knote *kn)
503 {
504 	ipc_object_t io = kn->kn_ipc_obj;
505 	filt_machport_turnstile_complete_port(kn, ip_object_to_port(io));
506 	kn->kn_ipc_obj = IO_NULL;
507 }
508 
509 /*
510  * Other half of filt_machport_turnstile_prepare_lazily()
511  *
512  * This is serialized by the knote state machine.
513  */
514 static void
filt_machport_turnstile_complete(struct knote * kn)515 filt_machport_turnstile_complete(struct knote *kn)
516 {
517 	if (kn->kn_ext[3]) {
518 		ipc_port_t port = (ipc_port_t)kn->kn_ext[3];
519 		filt_machport_turnstile_complete_port(kn, port);
520 		kn->kn_ext[3] = 0;
521 	}
522 
523 	if (kn->kn_hook) {
524 		struct turnstile *ts = kn->kn_hook;
525 
526 		turnstile_update_inheritor(ts, TURNSTILE_INHERITOR_NULL,
527 		    TURNSTILE_IMMEDIATE_UPDATE);
528 		turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_HELD);
529 
530 		turnstile_complete((uintptr_t)kn, (struct turnstile **)&kn->kn_hook, &ts, TURNSTILE_KNOTE);
531 		turnstile_cleanup();
532 
533 		assert(ts);
534 		turnstile_deallocate(ts);
535 	}
536 }
537 
538 static void
filt_machport_link(struct klist * klist,struct knote * kn)539 filt_machport_link(struct klist *klist, struct knote *kn)
540 {
541 	struct knote *hd = SLIST_FIRST(klist);
542 
543 	if (hd && filt_machport_kqueue_has_turnstile(kn)) {
544 		SLIST_INSERT_AFTER(hd, kn, kn_selnext);
545 	} else {
546 		SLIST_INSERT_HEAD(klist, kn, kn_selnext);
547 	}
548 }
549 
550 static void
filt_machport_unlink(struct klist * klist,struct knote * kn)551 filt_machport_unlink(struct klist *klist, struct knote *kn)
552 {
553 	struct knote **knprev;
554 
555 	KNOTE_DETACH(klist, kn);
556 
557 	/* make sure the first knote is a knote we can push on */
558 	SLIST_FOREACH_PREVPTR(kn, knprev, klist, kn_selnext) {
559 		if (filt_machport_kqueue_has_turnstile(kn)) {
560 			*knprev = SLIST_NEXT(kn, kn_selnext);
561 			SLIST_INSERT_HEAD(klist, kn, kn_selnext);
562 			break;
563 		}
564 	}
565 }
566 
567 int
filt_wlattach_sync_ipc(struct knote * kn)568 filt_wlattach_sync_ipc(struct knote *kn)
569 {
570 	mach_port_name_t name = (mach_port_name_t)kn->kn_id;
571 	ipc_space_t space = current_space();
572 	ipc_entry_bits_t bits;
573 	ipc_object_t object;
574 	ipc_port_t port = IP_NULL;
575 	int error = 0;
576 
577 	if (ipc_right_lookup_read(space, name, &bits, &object) != KERN_SUCCESS) {
578 		return ENOENT;
579 	}
580 	/* object is locked and active */
581 
582 	if (bits & MACH_PORT_TYPE_RECEIVE) {
583 		port = ip_object_to_port(object);
584 		if (port->ip_specialreply) {
585 			error = ENOENT;
586 		}
587 	} else if (bits & MACH_PORT_TYPE_SEND_ONCE) {
588 		port = ip_object_to_port(object);
589 		if (!port->ip_specialreply) {
590 			error = ENOENT;
591 		}
592 	} else {
593 		error = ENOENT;
594 	}
595 	if (error) {
596 		io_unlock(object);
597 		return error;
598 	}
599 
600 	if (port->ip_sync_link_state == PORT_SYNC_LINK_ANY) {
601 		io_unlock(object);
602 		/*
603 		 * We cannot start a sync IPC inheritance chain, only further one
604 		 * Note: this can also happen if the inheritance chain broke
605 		 * because the original requestor died.
606 		 */
607 		return ENOENT;
608 	}
609 
610 	if (port->ip_specialreply) {
611 		ipc_port_adjust_special_reply_port_locked(port, kn,
612 		    IPC_PORT_ADJUST_SR_LINK_WORKLOOP, FALSE);
613 	} else {
614 		ipc_port_adjust_port_locked(port, kn, FALSE);
615 	}
616 
617 	/* make sure the port was stashed */
618 	assert(kn->kn_ipc_obj == ip_to_object(port));
619 
620 	/* port has been unlocked by ipc_port_adjust_* */
621 
622 	return 0;
623 }
624 
625 static int
filt_machportattach(struct knote * kn,__unused struct kevent_qos_s * kev)626 filt_machportattach(
627 	struct knote *kn,
628 	__unused struct kevent_qos_s *kev)
629 {
630 	mach_port_name_t name = (mach_port_name_t)kn->kn_id;
631 	ipc_space_t space = current_space();
632 	ipc_entry_bits_t bits;
633 	ipc_object_t object;
634 	struct turnstile *send_turnstile = TURNSTILE_NULL;
635 
636 	int error = 0;
637 	int result = 0;
638 	kern_return_t kr;
639 
640 	kn->kn_flags &= ~EV_EOF;
641 	kn->kn_ext[3] = 0;
642 
643 	if (filt_machport_kqueue_has_turnstile(kn)) {
644 		/*
645 		 * If the filter is likely to support sync IPC override,
646 		 * and it happens to be attaching to a workloop,
647 		 * make sure the workloop has an allocated turnstile.
648 		 */
649 		kqueue_alloc_turnstile(knote_get_kq(kn));
650 	}
651 
652 	kr = ipc_right_lookup_read(space, name, &bits, &object);
653 
654 	if (kr != KERN_SUCCESS) {
655 		error = ENOENT;
656 		goto out;
657 	}
658 	/* object is locked and active */
659 
660 	if (bits & MACH_PORT_TYPE_PORT_SET) {
661 		ipc_pset_t pset = ips_object_to_pset(object);
662 
663 		io_reference(object);
664 		kn->kn_ipc_obj = object;
665 		filt_machport_link(&pset->ips_klist, kn);
666 		result = filt_machport_filter_result(kn, object);
667 		io_unlock(object);
668 	} else if (bits & MACH_PORT_TYPE_RECEIVE) {
669 		ipc_port_t port = ip_object_to_port(object);
670 
671 		if (port->ip_specialreply) {
672 			/*
673 			 * Registering for kevents on special reply ports
674 			 * isn't supported for two reasons:
675 			 *
676 			 * 1. it really makes very little sense for a port that
677 			 *    is supposed to be used synchronously
678 			 *
679 			 * 2. their ports's ip_klist field will be used to
680 			 *    store the receive turnstile, so we can't possibly
681 			 *    attach them anyway.
682 			 */
683 			io_unlock(object);
684 			error = ENOTSUP;
685 			goto out;
686 		}
687 
688 		io_reference(object);
689 		kn->kn_ipc_obj = object;
690 		if (port->ip_sync_link_state != PORT_SYNC_LINK_ANY) {
691 			/*
692 			 * We're attaching a port that used to have an IMQ_KNOTE,
693 			 * clobber this state, we'll fixup its turnstile inheritor below.
694 			 */
695 			ipc_port_adjust_sync_link_state_locked(port, PORT_SYNC_LINK_ANY, NULL);
696 		}
697 
698 		filt_machport_link(&port->ip_klist, kn);
699 		result = filt_machport_filter_result(kn, object);
700 
701 		/*
702 		 * Update the port's turnstile inheritor
703 		 *
704 		 * Unlike filt_machportdetach(), we don't have to care about races for
705 		 * turnstile_workloop_pusher_info(): filt_machport_link() doesn't affect
706 		 * already pushing knotes, and if the current one becomes the new
707 		 * pusher, it'll only be visible when turnstile_workloop_pusher_info()
708 		 * returns.
709 		 */
710 		send_turnstile = port_send_turnstile(port);
711 		if (send_turnstile) {
712 			turnstile_reference(send_turnstile);
713 			ipc_port_send_update_inheritor(port, send_turnstile,
714 			    TURNSTILE_IMMEDIATE_UPDATE);
715 
716 			/*
717 			 * rdar://problem/48861190
718 			 *
719 			 * When a listener connection resumes a peer,
720 			 * updating the inheritor above has moved the push
721 			 * from the current thread to the workloop.
722 			 *
723 			 * However, we haven't told the workloop yet
724 			 * that it needs a thread request, and we risk
725 			 * to be preeempted as soon as we drop the space
726 			 * lock below.
727 			 *
728 			 * To avoid this disable preemption and let kevent
729 			 * reenable it after it takes the kqlock.
730 			 */
731 			disable_preemption();
732 			result |= FILTER_THREADREQ_NODEFEER;
733 		}
734 
735 		io_unlock(object);
736 
737 		if (send_turnstile) {
738 			turnstile_update_inheritor_complete(send_turnstile,
739 			    TURNSTILE_INTERLOCK_NOT_HELD);
740 			turnstile_deallocate_safe(send_turnstile);
741 		}
742 	} else {
743 		io_unlock(object);
744 		error = ENOTSUP;
745 	}
746 
747 out:
748 	/* bail out on errors */
749 	if (error) {
750 		knote_set_error(kn, error);
751 		return 0;
752 	}
753 
754 	return result;
755 }
756 
757 static void
filt_machportdetach(struct knote * kn)758 filt_machportdetach(
759 	struct knote *kn)
760 {
761 	ipc_object_t object = kn->kn_ipc_obj;
762 	struct turnstile *send_turnstile = TURNSTILE_NULL;
763 
764 	filt_machport_turnstile_complete(kn);
765 
766 	io_lock(object);
767 	if ((kn->kn_status & KN_VANISHED) || (kn->kn_flags & EV_EOF)) {
768 		/*
769 		 * ipc_mqueue_changed() already unhooked this knote from the waitq,
770 		 */
771 	} else {
772 		ipc_port_t port = IP_NULL;
773 
774 		/*
775 		 * When the knote being detached is the first one in the list,
776 		 * then unlinking the knote *and* updating the turnstile inheritor
777 		 * need to happen atomically with respect to the callers of
778 		 * turnstile_workloop_pusher_info().
779 		 *
780 		 * The caller of turnstile_workloop_pusher_info() will use the kq req
781 		 * lock (and hence the kqlock), so we just need to hold the kqlock too.
782 		 */
783 		if (io_otype(object) == IOT_PORT) {
784 			port = ip_object_to_port(object);
785 			assert(port->ip_sync_link_state == PORT_SYNC_LINK_ANY);
786 			if (kn == SLIST_FIRST(&port->ip_klist)) {
787 				send_turnstile = port_send_turnstile(port);
788 			}
789 			filt_machport_unlink(&port->ip_klist, kn);
790 			struct kqueue *kq = knote_get_kq(kn);
791 			kqueue_set_iotier_override(kq, THROTTLE_LEVEL_END);
792 		} else {
793 			ipc_pset_t pset = ips_object_to_pset(object);
794 
795 			filt_machport_unlink(&pset->ips_klist, kn);
796 		}
797 
798 
799 		if (send_turnstile) {
800 			turnstile_reference(send_turnstile);
801 			ipc_port_send_update_inheritor(port, send_turnstile,
802 			    TURNSTILE_IMMEDIATE_UPDATE);
803 		}
804 	}
805 
806 	/* Clear the knote pointer once the knote has been removed from turnstile */
807 	kn->kn_ipc_obj = IO_NULL;
808 	io_unlock(object);
809 
810 	if (send_turnstile) {
811 		turnstile_update_inheritor_complete(send_turnstile,
812 		    TURNSTILE_INTERLOCK_NOT_HELD);
813 		turnstile_deallocate(send_turnstile);
814 	}
815 
816 	io_release(object);
817 }
818 
819 /*
820  * filt_machportevent - deliver events into the mach port filter
821  *
822  * Mach port message arrival events are currently only posted via the
823  * kqueue filter routine for ports.
824  *
825  * If there is a message at the head of the queue,
826  * we indicate that the knote should go active.  If
827  * the message is to be direct-received, we adjust the
828  * QoS of the knote according the requested and override
829  * QoS of that first message.
830  *
831  * When the knote is for a port-set, the hint is non 0
832  * and is the waitq which is posting.
833  */
834 static int
filt_machportevent(struct knote * kn,long hint __assert_only)835 filt_machportevent(struct knote *kn, long hint __assert_only)
836 {
837 	if (io_otype(kn->kn_ipc_obj) == IOT_PORT_SET) {
838 		/*
839 		 * When called for a port-set,
840 		 * the posting port waitq is locked.
841 		 *
842 		 * waitq_set_first_prepost()
843 		 * in filt_machport_filter_result()
844 		 * would try to lock it and be very sad.
845 		 *
846 		 * Just trust what we know to be true.
847 		 */
848 		assert(hint != 0);
849 		return FILTER_ACTIVE;
850 	}
851 	assert(hint == 0);
852 	return filt_machport_filter_result(kn, kn->kn_ipc_obj);
853 }
854 
855 void
ipc_pset_prepost(struct waitq_set * wqs,struct waitq * waitq)856 ipc_pset_prepost(struct waitq_set *wqs, struct waitq *waitq)
857 {
858 	KNOTE(&ips_from_waitq(wqs)->ips_klist, (long)waitq);
859 }
860 
861 static int
filt_machporttouch(struct knote * kn,struct kevent_qos_s * kev)862 filt_machporttouch(
863 	struct knote *kn,
864 	struct kevent_qos_s *kev)
865 {
866 	ipc_object_t object = kn->kn_ipc_obj;
867 	int result = 0;
868 
869 	/*
870 	 * Specificying MACH_RCV_MSG or MACH_RCV_SYNC_PEEK during attach results in
871 	 * allocation of a turnstile. Modifying the filter flags to include these
872 	 * flags later, without a turnstile being allocated, leads to
873 	 * inconsistencies.
874 	 */
875 	if ((kn->kn_sfflags ^ kev->fflags) & (MACH_RCV_MSG | MACH_RCV_SYNC_PEEK)) {
876 		kev->flags |= EV_ERROR;
877 		kev->data = EINVAL;
878 		return 0;
879 	}
880 
881 	/* copy in new settings and save off new input fflags */
882 	kn->kn_sfflags = kev->fflags;
883 	kn->kn_ext[0] = kev->ext[0];
884 	kn->kn_ext[1] = kev->ext[1];
885 
886 	if (kev->flags & EV_ENABLE) {
887 		/*
888 		 * If the knote is being enabled, make sure there's no lingering
889 		 * IPC overrides from the previous message delivery.
890 		 */
891 		filt_machport_turnstile_complete(kn);
892 	}
893 
894 	io_lock(object);
895 	result = filt_machport_filter_result(kn, object);
896 	io_unlock(object);
897 
898 	return result;
899 }
900 
901 static int
filt_machportprocess(struct knote * kn,struct kevent_qos_s * kev)902 filt_machportprocess(struct knote *kn, struct kevent_qos_s *kev)
903 {
904 	ipc_object_t object = kn->kn_ipc_obj;
905 	thread_t self = current_thread();
906 	kevent_ctx_t kectx = NULL;
907 
908 	wait_result_t wresult;
909 	mach_msg_option64_t option64;
910 	mach_vm_address_t msg_addr;
911 	mach_msg_size_t max_msg_size, cpout_aux_size, cpout_msg_size;
912 	uint32_t ppri;
913 	mach_msg_qos_t oqos;
914 
915 	int result = FILTER_ACTIVE;
916 
917 	/* Capture current state */
918 	knote_fill_kevent(kn, kev, MACH_PORT_NULL);
919 
920 	/* Clear port reference, use ext3 as size of msg aux data */
921 	kev->ext[3] = 0;
922 
923 	/* If already deallocated/moved return one last EOF event */
924 	if (kev->flags & EV_EOF) {
925 		return FILTER_ACTIVE | FILTER_RESET_EVENT_QOS;
926 	}
927 
928 	/*
929 	 * Only honor supported receive options. If no options are
930 	 * provided, just force a MACH_RCV_LARGE to detect the
931 	 * name of the port and sizeof the waiting message.
932 	 *
933 	 * Extend kn_sfflags to 64 bits.
934 	 */
935 	option64 = (mach_msg_option64_t)kn->kn_sfflags & (MACH_RCV_MSG |
936 	    MACH_RCV_LARGE | MACH_RCV_LARGE_IDENTITY |
937 	    MACH_RCV_TRAILER_MASK | MACH_RCV_VOUCHER | MACH_MSG_STRICT_REPLY);
938 
939 	if (option64 & MACH_RCV_MSG) {
940 		msg_addr = (mach_vm_address_t) kn->kn_ext[0];
941 		max_msg_size = (mach_msg_size_t) kn->kn_ext[1];
942 
943 		/*
944 		 * Copy out the incoming message as vector, and append aux data
945 		 * immediately after the message proper (if any) and report its
946 		 * size on ext3.
947 		 */
948 		option64 |= (MACH64_MSG_VECTOR | MACH64_RCV_LINEAR_VECTOR);
949 
950 		/*
951 		 * If the kevent didn't specify a buffer and length, carve a buffer
952 		 * from the filter processing data according to the flags.
953 		 */
954 		if (max_msg_size == 0) {
955 			kectx = kevent_get_context(self);
956 			msg_addr  = (mach_vm_address_t)kectx->kec_data_out;
957 			max_msg_size  = (mach_msg_size_t)kectx->kec_data_resid;
958 			option64 |= (MACH_RCV_LARGE | MACH_RCV_LARGE_IDENTITY);
959 			/* Receive vector linearly onto stack */
960 			if (kectx->kec_process_flags & KEVENT_FLAG_STACK_DATA) {
961 				option64 |= MACH64_RCV_STACK;
962 			}
963 		}
964 	} else {
965 		/* just detect the port name (if a set) and size of the first message */
966 		option64 = MACH_RCV_LARGE;
967 		msg_addr = 0;
968 		max_msg_size = 0;
969 	}
970 
971 	/*
972 	 * Set up to receive a message or the notification of a
973 	 * too large message.  But never allow this call to wait.
974 	 * If the user provided aditional options, like trailer
975 	 * options, pass those through here.  But we don't support
976 	 * scatter lists through this interface.
977 	 *
978 	 * Note: while in filt_machportprocess(),
979 	 *       the knote has a reference on `object` that we can borrow.
980 	 */
981 	self->ith_object = object;
982 
983 	/* Using msg_addr as combined buffer for message proper and aux */
984 	self->ith_msg_addr = msg_addr;
985 	self->ith_max_msize = max_msg_size;
986 	self->ith_msize = 0;
987 
988 	self->ith_aux_addr = 0;
989 	self->ith_max_asize = 0;
990 	self->ith_asize = 0;
991 
992 	self->ith_option = option64;
993 	self->ith_receiver_name = MACH_PORT_NULL;
994 	option64 |= MACH_RCV_TIMEOUT; // never wait
995 	self->ith_state = MACH_RCV_IN_PROGRESS;
996 	self->ith_knote = kn;
997 
998 	io_lock(object);
999 
1000 	wresult = ipc_mqueue_receive_on_thread_and_unlock(
1001 		io_waitq(object),
1002 		option64,
1003 		self->ith_max_msize,       /* max msg suze */
1004 		0,                         /* max aux size 0, using combined buffer */
1005 		0,                         /* immediate timeout */
1006 		THREAD_INTERRUPTIBLE,
1007 		self);
1008 	/* port unlocked */
1009 
1010 	/* If we timed out, or the process is exiting, just zero.  */
1011 	if (wresult == THREAD_RESTART || self->ith_state == MACH_RCV_TIMED_OUT) {
1012 		assert(self->turnstile != TURNSTILE_NULL);
1013 		self->ith_knote = ITH_KNOTE_NULL;
1014 		return 0;
1015 	}
1016 
1017 	assert(wresult == THREAD_NOT_WAITING);
1018 	assert(self->ith_state != MACH_RCV_IN_PROGRESS);
1019 
1020 	/*
1021 	 * If we weren't attempting to receive a message
1022 	 * directly, we need to return the port name in
1023 	 * the kevent structure.
1024 	 */
1025 	if ((option64 & MACH_RCV_MSG) != MACH_RCV_MSG) {
1026 		assert(self->ith_state == MACH_RCV_TOO_LARGE);
1027 		assert(self->ith_kmsg == IKM_NULL);
1028 		kev->data = self->ith_receiver_name;
1029 		self->ith_knote = ITH_KNOTE_NULL;
1030 		return result;
1031 	}
1032 
1033 #if CONFIG_PREADOPT_TG
1034 	/* If we're the first EVFILT_MACHPORT knote that is being processed for this
1035 	 * kqwl, then make sure to preadopt the thread group from the kmsg we're
1036 	 * about to receive. This is to make sure that we fix up the preadoption
1037 	 * thread group correctly on the receive side for the first message.
1038 	 */
1039 	struct kqueue *kq = knote_get_kq(kn);
1040 
1041 	if (self->ith_kmsg) {
1042 		struct thread_group *tg = ipc_kmsg_get_thread_group(self->ith_kmsg);
1043 
1044 		kqueue_process_preadopt_thread_group(self, kq, tg);
1045 	}
1046 #endif
1047 	ipc_port_t port = ip_object_to_port(object);
1048 	struct kqueue *kqwl = knote_get_kq(kn);
1049 	if (port->ip_kernel_iotier_override != kqueue_get_iotier_override(kqwl)) {
1050 		/*
1051 		 * Lock the port to make sure port->ip_kernel_iotier_override does
1052 		 * not change while updating the kqueue override, else kqueue could
1053 		 * have old iotier value.
1054 		 */
1055 		ip_mq_lock(port);
1056 		kqueue_set_iotier_override(kqwl, port->ip_kernel_iotier_override);
1057 		result |= FILTER_ADJUST_EVENT_IOTIER_BIT;
1058 		ip_mq_unlock(port);
1059 	}
1060 
1061 	/*
1062 	 * Attempt to receive the message directly, returning
1063 	 * the results in the fflags field.
1064 	 */
1065 	io_reference(object);
1066 	kev->fflags = mach_msg_receive_results_kevent(&cpout_msg_size,
1067 	    &cpout_aux_size, &ppri, &oqos);
1068 
1069 	/* kmsg and object reference consumed */
1070 
1071 	/*
1072 	 * if the user asked for the identity of ports containing a
1073 	 * a too-large message, return it in the data field (as we
1074 	 * do for messages we didn't try to receive).
1075 	 */
1076 	if (kev->fflags == MACH_RCV_TOO_LARGE) {
1077 		kev->ext[1] = self->ith_msize;
1078 		kev->ext[3] = self->ith_asize;  /* Only lower 32 bits of ext3 are used */
1079 		if (option64 & MACH_RCV_LARGE_IDENTITY) {
1080 			kev->data = self->ith_receiver_name;
1081 		} else {
1082 			kev->data = MACH_PORT_NULL;
1083 		}
1084 	} else {
1085 		kev->ext[1] = cpout_msg_size;
1086 		kev->ext[3] = cpout_aux_size; /* Only lower 32 bits of ext3 are used */
1087 		kev->data = MACH_PORT_NULL;
1088 	}
1089 
1090 	/*
1091 	 * If we used a data buffer carved out from the filt_process data,
1092 	 * store the address used in the knote and adjust the residual and
1093 	 * other parameters for future use.
1094 	 */
1095 	if (kectx) {
1096 		assert(kectx->kec_data_resid >= cpout_msg_size + cpout_aux_size);
1097 		kectx->kec_data_resid -= cpout_msg_size + cpout_aux_size;
1098 		if ((kectx->kec_process_flags & KEVENT_FLAG_STACK_DATA) == 0) {
1099 			kev->ext[0] = kectx->kec_data_out;
1100 			kectx->kec_data_out += cpout_msg_size + cpout_aux_size;
1101 		} else {
1102 			assert(option64 & MACH64_RCV_STACK);
1103 			kev->ext[0] = kectx->kec_data_out + kectx->kec_data_resid;
1104 		}
1105 	}
1106 
1107 	/*
1108 	 * Apply message-based QoS values to output kevent as prescribed.
1109 	 * The kev->ext[2] field gets (msg-qos << 32) | (override-qos).
1110 	 */
1111 	if (kev->fflags == MACH_MSG_SUCCESS) {
1112 		kev->ext[2] = ((uint64_t)ppri << 32) |
1113 		    _pthread_priority_make_from_thread_qos(oqos, 0, 0);
1114 	}
1115 
1116 	self->ith_knote = ITH_KNOTE_NULL;
1117 	return result;
1118 }
1119 
1120 static void
filt_machportsanitizedcopyout(struct knote * kn,struct kevent_qos_s * kev)1121 filt_machportsanitizedcopyout(struct knote *kn, struct kevent_qos_s *kev)
1122 {
1123 	*kev = *(struct kevent_qos_s *)&kn->kn_kevent;
1124 
1125 	// We may have stashed the address to the port that is pushing on the sync
1126 	// IPC so clear it out.
1127 	kev->ext[3] = 0;
1128 }
1129 
1130 SECURITY_READ_ONLY_EARLY(struct filterops) machport_filtops = {
1131 	.f_adjusts_qos = true,
1132 	.f_extended_codes = true,
1133 	.f_attach = filt_machportattach,
1134 	.f_detach = filt_machportdetach,
1135 	.f_event = filt_machportevent,
1136 	.f_touch = filt_machporttouch,
1137 	.f_process = filt_machportprocess,
1138 	.f_sanitized_copyout = filt_machportsanitizedcopyout,
1139 };
1140