xref: /xnu-10002.1.13/osfmk/ipc/ipc_port.c (revision 1031c584a5e37aff177559b9f69dbd3c8c3fd30a)
1 /*
2  * Copyright (c) 2000-2019 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  * @OSF_FREE_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  * NOTICE: This file was modified by McAfee Research in 2004 to introduce
58  * support for mandatory and extensible security protections.  This notice
59  * is included in support of clause 2.2 (b) of the Apple Public License,
60  * Version 2.0.
61  */
62 /*
63  */
64 /*
65  *	File:	ipc/ipc_port.c
66  *	Author:	Rich Draves
67  *	Date:	1989
68  *
69  *	Functions to manipulate IPC ports.
70  */
71 
72 #include <mach/boolean.h>
73 #include <mach_assert.h>
74 
75 #include <mach/port.h>
76 #include <mach/kern_return.h>
77 #include <kern/backtrace.h>
78 #include <kern/debug.h>
79 #include <kern/ipc_kobject.h>
80 #include <kern/kcdata.h>
81 #include <kern/misc_protos.h>
82 #include <kern/policy_internal.h>
83 #include <kern/thread.h>
84 #include <kern/waitq.h>
85 #include <kern/host_notify.h>
86 #include <ipc/ipc_entry.h>
87 #include <ipc/ipc_space.h>
88 #include <ipc/ipc_object.h>
89 #include <ipc/ipc_right.h>
90 #include <ipc/ipc_port.h>
91 #include <ipc/ipc_pset.h>
92 #include <ipc/ipc_kmsg.h>
93 #include <ipc/ipc_mqueue.h>
94 #include <ipc/ipc_notify.h>
95 #include <ipc/ipc_importance.h>
96 #include <machine/limits.h>
97 #include <kern/turnstile.h>
98 #include <kern/machine.h>
99 
100 #include <security/mac_mach_internal.h>
101 #include <ipc/ipc_service_port.h>
102 
103 #include <string.h>
104 
105 extern bool proc_is_simulated(struct proc *);
106 extern struct proc *current_proc(void);
107 extern int csproc_hardened_runtime(struct proc* p);
108 
109 static TUNABLE(bool, prioritize_launch, "prioritize_launch", true);
110 TUNABLE_WRITEABLE(int, ipc_portbt, "ipc_portbt", false);
111 
112 extern zone_t ipc_kobject_label_zone;
113 
114 LCK_SPIN_DECLARE_ATTR(ipc_port_multiple_lock_data, &ipc_lck_grp, &ipc_lck_attr);
115 ipc_port_timestamp_t ipc_port_timestamp_data;
116 
117 KALLOC_ARRAY_TYPE_DEFINE(ipc_port_request_table,
118     struct ipc_port_request, KT_DEFAULT);
119 
120 #if     MACH_ASSERT
121 static void ipc_port_init_debug(ipc_port_t, void *fp);
122 #endif  /* MACH_ASSERT */
123 
124 void __abortlike
__ipc_port_inactive_panic(ipc_port_t port)125 __ipc_port_inactive_panic(ipc_port_t port)
126 {
127 	panic("Using inactive port %p", port);
128 }
129 
130 static __abortlike void
__ipc_port_translate_receive_panic(ipc_space_t space,ipc_port_t port)131 __ipc_port_translate_receive_panic(ipc_space_t space, ipc_port_t port)
132 {
133 	panic("found receive right in space %p for port %p owned by space %p",
134 	    space, port, ip_get_receiver(port));
135 }
136 
137 __abortlike void
__ipc_right_delta_overflow_panic(ipc_port_t port,natural_t * field,int delta)138 __ipc_right_delta_overflow_panic(ipc_port_t port, natural_t *field, int delta)
139 {
140 	const char *what;
141 	if (field == &port->ip_srights) {
142 		what = "send right";
143 	} else {
144 		what = "send-once right";
145 	}
146 	panic("port %p %s count overflow (delta: %d)", port, what, delta);
147 }
148 
149 static void
150 ipc_port_send_turnstile_recompute_push_locked(
151 	ipc_port_t port);
152 
153 static thread_t
154 ipc_port_get_watchport_inheritor(
155 	ipc_port_t port);
156 
157 static kern_return_t
158 ipc_port_update_qos_n_iotier(
159 	ipc_port_t port,
160 	uint8_t    qos,
161 	uint8_t    iotier);
162 
163 void
ipc_port_release(ipc_port_t port)164 ipc_port_release(ipc_port_t port)
165 {
166 	ip_release(port);
167 }
168 
169 void
ipc_port_reference(ipc_port_t port)170 ipc_port_reference(ipc_port_t port)
171 {
172 	ip_validate(port);
173 	ip_reference(port);
174 }
175 
176 /*
177  *	Routine:	ipc_port_timestamp
178  *	Purpose:
179  *		Retrieve a timestamp value.
180  */
181 
182 ipc_port_timestamp_t
ipc_port_timestamp(void)183 ipc_port_timestamp(void)
184 {
185 	return OSIncrementAtomic(&ipc_port_timestamp_data);
186 }
187 
188 
189 /*
190  *	Routine:	ipc_port_translate_send
191  *	Purpose:
192  *		Look up a send right in a space.
193  *	Conditions:
194  *		Nothing locked before.  If successful, the object
195  *		is returned active and locked.  The caller doesn't get a ref.
196  *	Returns:
197  *		KERN_SUCCESS		Object returned locked.
198  *		KERN_INVALID_TASK	The space is dead.
199  *		KERN_INVALID_NAME	The name doesn't denote a right
200  *		KERN_INVALID_RIGHT	Name doesn't denote the correct right
201  */
202 kern_return_t
ipc_port_translate_send(ipc_space_t space,mach_port_name_t name,ipc_port_t * portp)203 ipc_port_translate_send(
204 	ipc_space_t                     space,
205 	mach_port_name_t                name,
206 	ipc_port_t                     *portp)
207 {
208 	ipc_port_t port = IP_NULL;
209 	ipc_object_t object;
210 	kern_return_t kr;
211 
212 	kr = ipc_object_translate(space, name, MACH_PORT_RIGHT_SEND, &object);
213 	if (kr == KERN_SUCCESS) {
214 		port = ip_object_to_port(object);
215 	}
216 	*portp = port;
217 	return kr;
218 }
219 
220 
221 /*
222  *	Routine:	ipc_port_translate_receive
223  *	Purpose:
224  *		Look up a receive right in a space.
225  *		Performs some minimal security checks against tampering.
226  *	Conditions:
227  *		Nothing locked before.  If successful, the object
228  *		is returned active and locked.  The caller doesn't get a ref.
229  *	Returns:
230  *		KERN_SUCCESS		Object returned locked.
231  *		KERN_INVALID_TASK	The space is dead.
232  *		KERN_INVALID_NAME	The name doesn't denote a right
233  *		KERN_INVALID_RIGHT	Name doesn't denote the correct right
234  */
235 kern_return_t
ipc_port_translate_receive(ipc_space_t space,mach_port_name_t name,ipc_port_t * portp)236 ipc_port_translate_receive(
237 	ipc_space_t                     space,
238 	mach_port_name_t                name,
239 	ipc_port_t                     *portp)
240 {
241 	ipc_port_t port = IP_NULL;
242 	ipc_object_t object;
243 	kern_return_t kr;
244 
245 	kr = ipc_object_translate(space, name, MACH_PORT_RIGHT_RECEIVE, &object);
246 	if (kr == KERN_SUCCESS) {
247 		/* object is locked */
248 		port = ip_object_to_port(object);
249 		if (!ip_in_space(port, space)) {
250 			__ipc_port_translate_receive_panic(space, port);
251 		}
252 	}
253 	*portp = port;
254 	return kr;
255 }
256 
257 
258 /*
259  *	Routine:	ipc_port_request_alloc
260  *	Purpose:
261  *		Try to allocate a request slot.
262  *		If successful, returns the request index.
263  *		Otherwise returns zero.
264  *	Conditions:
265  *		The port is locked and active.
266  *	Returns:
267  *		KERN_SUCCESS		A request index was found.
268  *		KERN_NO_SPACE		No index allocated.
269  */
270 
271 kern_return_t
ipc_port_request_alloc(ipc_port_t port,mach_port_name_t name,ipc_port_t soright,ipc_port_request_opts_t options,ipc_port_request_index_t * indexp)272 ipc_port_request_alloc(
273 	ipc_port_t                      port,
274 	mach_port_name_t                name,
275 	ipc_port_t                      soright,
276 	ipc_port_request_opts_t         options,
277 	ipc_port_request_index_t        *indexp)
278 {
279 	ipc_port_request_table_t table;
280 	ipc_port_request_index_t index;
281 	ipc_port_request_t ipr, base;
282 
283 	require_ip_active(port);
284 	assert(name != MACH_PORT_NULL);
285 	assert(soright != IP_NULL);
286 
287 	table = port->ip_requests;
288 	if (table == NULL) {
289 		return KERN_NO_SPACE;
290 	}
291 
292 	base  = ipc_port_request_table_base(table);
293 	index = base->ipr_next;
294 	if (index == 0) {
295 		return KERN_NO_SPACE;
296 	}
297 
298 	ipr = ipc_port_request_table_get(table, index);
299 	assert(ipr->ipr_soright == IP_NULL);
300 
301 	base->ipr_next = ipr->ipr_next;
302 	ipr->ipr_name = name;
303 	ipr->ipr_soright = IPR_SOR_MAKE(soright, options);
304 
305 	if (options == (IPR_SOR_SPARM_MASK | IPR_SOR_SPREQ_MASK) &&
306 	    port->ip_sprequests == 0) {
307 		port->ip_sprequests = 1;
308 	}
309 
310 	*indexp = index;
311 
312 	return KERN_SUCCESS;
313 }
314 
315 
316 /*
317  *	Routine:	ipc_port_request_hnotify_alloc
318  *	Purpose:
319  *		Try to allocate a request slot.
320  *		If successful, returns the request index.
321  *		Otherwise returns zero.
322  *	Conditions:
323  *		The port is locked and active.
324  *	Returns:
325  *		KERN_SUCCESS		A request index was found.
326  *		KERN_NO_SPACE		No index allocated.
327  */
328 
329 kern_return_t
ipc_port_request_hnotify_alloc(ipc_port_t port,struct host_notify_entry * hnotify,ipc_port_request_index_t * indexp)330 ipc_port_request_hnotify_alloc(
331 	ipc_port_t                      port,
332 	struct host_notify_entry       *hnotify,
333 	ipc_port_request_index_t       *indexp)
334 {
335 	ipc_port_request_table_t table;
336 	ipc_port_request_index_t index;
337 	ipc_port_request_t ipr, base;
338 
339 	require_ip_active(port);
340 
341 	table = port->ip_requests;
342 	if (table == NULL) {
343 		return KERN_NO_SPACE;
344 	}
345 
346 	base  = ipc_port_request_table_base(table);
347 	index = base->ipr_next;
348 	if (index == 0) {
349 		return KERN_NO_SPACE;
350 	}
351 
352 	ipr = ipc_port_request_table_get(table, index);
353 	assert(ipr->ipr_soright == IP_NULL);
354 
355 	base->ipr_next = ipr->ipr_next;
356 	ipr->ipr_name = IPR_HOST_NOTIFY;
357 	ipr->ipr_hnotify = hnotify;
358 
359 	*indexp = index;
360 
361 	return KERN_SUCCESS;
362 }
363 
364 /*
365  *	Routine:	ipc_port_request_grow
366  *	Purpose:
367  *		Grow a port's table of requests.
368  *	Conditions:
369  *		The port must be locked and active.
370  *		Nothing else locked; will allocate memory.
371  *		Upon return the port is unlocked.
372  *	Returns:
373  *		KERN_SUCCESS		Grew the table.
374  *		KERN_SUCCESS		Somebody else grew the table.
375  *		KERN_SUCCESS		The port died.
376  *		KERN_RESOURCE_SHORTAGE	Couldn't allocate new table.
377  *		KERN_NO_SPACE		Couldn't grow to desired size
378  */
379 
380 kern_return_t
ipc_port_request_grow(ipc_port_t port)381 ipc_port_request_grow(
382 	ipc_port_t              port)
383 {
384 	ipc_port_request_table_t otable, ntable;
385 	uint32_t osize, nsize;
386 	uint32_t ocount, ncount;
387 
388 	require_ip_active(port);
389 
390 	otable = port->ip_requests;
391 	if (otable) {
392 		osize = ipc_port_request_table_size(otable);
393 	} else {
394 		osize = 0;
395 	}
396 	nsize = ipc_port_request_table_next_size(2, osize, 16);
397 	if (nsize > CONFIG_IPC_TABLE_REQUEST_SIZE_MAX) {
398 		nsize = CONFIG_IPC_TABLE_REQUEST_SIZE_MAX;
399 	}
400 	if (nsize == osize) {
401 		return KERN_RESOURCE_SHORTAGE;
402 	}
403 
404 	ip_reference(port);
405 	ip_mq_unlock(port);
406 
407 	ntable = ipc_port_request_table_alloc_by_size(nsize, Z_WAITOK | Z_ZERO);
408 	if (ntable == NULL) {
409 		ip_release(port);
410 		return KERN_RESOURCE_SHORTAGE;
411 	}
412 
413 	ip_mq_lock(port);
414 
415 	/*
416 	 *	Check that port is still active and that nobody else
417 	 *	has slipped in and grown the table on us.  Note that
418 	 *	just checking if the current table pointer == otable
419 	 *	isn't sufficient; must check ipr_size.
420 	 */
421 
422 	ocount = ipc_port_request_table_size_to_count(osize);
423 	ncount = ipc_port_request_table_size_to_count(nsize);
424 
425 	if (ip_active(port) && port->ip_requests == otable) {
426 		ipc_port_request_index_t free, i;
427 
428 		/* copy old table to new table */
429 
430 		if (otable != NULL) {
431 			memcpy(ipc_port_request_table_base(ntable),
432 			    ipc_port_request_table_base(otable),
433 			    osize);
434 		} else {
435 			ocount = 1;
436 			free   = 0;
437 		}
438 
439 		/* add new elements to the new table's free list */
440 
441 		for (i = ocount; i < ncount; i++) {
442 			ipc_port_request_table_get_nocheck(ntable, i)->ipr_next = free;
443 			free = i;
444 		}
445 
446 		ipc_port_request_table_base(ntable)->ipr_next = free;
447 		port->ip_requests = ntable;
448 		ip_mq_unlock(port);
449 		ip_release(port);
450 
451 		if (otable != NULL) {
452 			ipc_port_request_table_free(&otable);
453 		}
454 	} else {
455 		ip_mq_unlock(port);
456 		ip_release(port);
457 		ipc_port_request_table_free(&ntable);
458 	}
459 
460 	return KERN_SUCCESS;
461 }
462 
463 /*
464  *	Routine:	ipc_port_request_sparm
465  *	Purpose:
466  *		Arm delayed send-possible request.
467  *	Conditions:
468  *		The port must be locked and active.
469  *
470  *		Returns TRUE if the request was armed
471  *		(or armed with importance in that version).
472  */
473 
474 boolean_t
ipc_port_request_sparm(ipc_port_t port,__assert_only mach_port_name_t name,ipc_port_request_index_t index,mach_msg_option_t option,mach_msg_priority_t priority)475 ipc_port_request_sparm(
476 	ipc_port_t                      port,
477 	__assert_only mach_port_name_t  name,
478 	ipc_port_request_index_t        index,
479 	mach_msg_option_t               option,
480 	mach_msg_priority_t             priority)
481 {
482 	if (index != IE_REQ_NONE) {
483 		ipc_port_request_table_t table;
484 		ipc_port_request_t ipr;
485 
486 		require_ip_active(port);
487 
488 		table = port->ip_requests;
489 		assert(table != NULL);
490 
491 		ipr = ipc_port_request_table_get(table, index);
492 		assert(ipr->ipr_name == name);
493 
494 		/* Is there a valid destination? */
495 		if (IPR_SOR_SPREQ(ipr->ipr_soright)) {
496 			ipr->ipr_soright = IPR_SOR_MAKE(ipr->ipr_soright, IPR_SOR_SPARM_MASK);
497 			port->ip_sprequests = 1;
498 
499 			if (option & MACH_SEND_OVERRIDE) {
500 				/* apply override to message queue */
501 				mach_msg_qos_t qos_ovr;
502 				if (mach_msg_priority_is_pthread_priority(priority)) {
503 					qos_ovr = _pthread_priority_thread_qos(priority);
504 				} else {
505 					qos_ovr = mach_msg_priority_overide_qos(priority);
506 				}
507 				if (qos_ovr) {
508 					ipc_mqueue_override_send_locked(&port->ip_messages, qos_ovr);
509 				}
510 			}
511 
512 #if IMPORTANCE_INHERITANCE
513 			if (((option & MACH_SEND_NOIMPORTANCE) == 0) &&
514 			    (port->ip_impdonation != 0) &&
515 			    (port->ip_spimportant == 0) &&
516 			    (((option & MACH_SEND_IMPORTANCE) != 0) ||
517 			    (task_is_importance_donor(current_task())))) {
518 				return TRUE;
519 			}
520 #else
521 			return TRUE;
522 #endif /* IMPORTANCE_INHERITANCE */
523 		}
524 	}
525 	return FALSE;
526 }
527 
528 /*
529  *	Routine:	ipc_port_request_type
530  *	Purpose:
531  *		Determine the type(s) of port requests enabled for a name.
532  *	Conditions:
533  *		The port must be locked or inactive (to avoid table growth).
534  *		The index must not be IE_REQ_NONE and for the name in question.
535  */
536 mach_port_type_t
ipc_port_request_type(ipc_port_t port,__assert_only mach_port_name_t name,ipc_port_request_index_t index)537 ipc_port_request_type(
538 	ipc_port_t                      port,
539 	__assert_only mach_port_name_t  name,
540 	ipc_port_request_index_t        index)
541 {
542 	ipc_port_request_table_t table;
543 	ipc_port_request_t ipr;
544 	mach_port_type_t type = 0;
545 
546 	table = port->ip_requests;
547 	assert(table != NULL);
548 
549 	assert(index != IE_REQ_NONE);
550 	ipr = ipc_port_request_table_get(table, index);
551 	assert(ipr->ipr_name == name);
552 
553 	if (IP_VALID(IPR_SOR_PORT(ipr->ipr_soright))) {
554 		type |= MACH_PORT_TYPE_DNREQUEST;
555 
556 		if (IPR_SOR_SPREQ(ipr->ipr_soright)) {
557 			type |= MACH_PORT_TYPE_SPREQUEST;
558 
559 			if (!IPR_SOR_SPARMED(ipr->ipr_soright)) {
560 				type |= MACH_PORT_TYPE_SPREQUEST_DELAYED;
561 			}
562 		}
563 	}
564 	return type;
565 }
566 
567 /*
568  *	Routine:	ipc_port_request_cancel
569  *	Purpose:
570  *		Cancel a dead-name/send-possible request and return the send-once right.
571  *	Conditions:
572  *		The port must be locked and active.
573  *		The index must not be IPR_REQ_NONE and must correspond with name.
574  */
575 
576 ipc_port_t
ipc_port_request_cancel(ipc_port_t port,__assert_only mach_port_name_t name,ipc_port_request_index_t index)577 ipc_port_request_cancel(
578 	ipc_port_t                      port,
579 	__assert_only mach_port_name_t  name,
580 	ipc_port_request_index_t        index)
581 {
582 	ipc_port_request_table_t table;
583 	ipc_port_request_t base, ipr;
584 	ipc_port_t request = IP_NULL;
585 
586 	require_ip_active(port);
587 	table = port->ip_requests;
588 	base  = ipc_port_request_table_base(table);
589 	assert(table != NULL);
590 
591 	assert(index != IE_REQ_NONE);
592 	ipr = ipc_port_request_table_get(table, index);
593 	assert(ipr->ipr_name == name);
594 	request = IPR_SOR_PORT(ipr->ipr_soright);
595 
596 	/* return ipr to the free list inside the table */
597 	ipr->ipr_next = base->ipr_next;
598 	ipr->ipr_soright = IP_NULL;
599 	base->ipr_next = index;
600 
601 	return request;
602 }
603 
604 
605 /*
606  *	Routine:	ipc_port_nsrequest
607  *	Purpose:
608  *		Make a no-senders request, returning the
609  *		previously registered send-once right.
610  *		Just cancels the previous request if notify is IP_NULL.
611  *	Conditions:
612  *		The port is locked and active.  It is unlocked.
613  *		Consumes a ref for notify (if non-null), and
614  *		returns previous with a ref (if non-null).
615  */
616 
617 void
ipc_port_nsrequest(ipc_port_t port,mach_port_mscount_t sync,ipc_port_t notify,ipc_port_t * previousp)618 ipc_port_nsrequest(
619 	ipc_port_t              port,
620 	mach_port_mscount_t     sync,
621 	ipc_port_t              notify,
622 	ipc_port_t              *previousp)
623 {
624 	ipc_port_t previous;
625 	mach_port_mscount_t mscount;
626 	require_ip_active(port);
627 
628 	assert(!ip_in_space(port, ipc_space_kernel));
629 	assert(port->ip_nsrequest != IP_KOBJECT_NSREQUEST_ARMED);
630 
631 	previous = port->ip_nsrequest;
632 	mscount = port->ip_mscount;
633 
634 	if ((port->ip_srights == 0) && (sync <= mscount) &&
635 	    (notify != IP_NULL)) {
636 		port->ip_nsrequest = IP_NULL;
637 		ip_mq_unlock(port);
638 		ipc_notify_no_senders(notify, mscount, /* kobject */ false);
639 	} else {
640 		port->ip_nsrequest = notify;
641 		ip_mq_unlock(port);
642 	}
643 
644 	*previousp = previous;
645 }
646 
647 
648 /*
649  *	Routine:	ipc_port_clear_receiver
650  *	Purpose:
651  *		Prepares a receive right for transmission/destruction,
652  *		optionally performs mqueue destruction (with port lock held)
653  *
654  *	Conditions:
655  *		The port is locked and active.
656  *	Returns:
657  *		If should_destroy is TRUE, then the return value indicates
658  *		whether the caller needs to reap kmsg structures that should
659  *		be destroyed (by calling ipc_kmsg_reap_delayed)
660  *
661  *              If should_destroy is FALSE, this always returns FALSE
662  */
663 
664 boolean_t
ipc_port_clear_receiver(ipc_port_t port,boolean_t should_destroy,waitq_link_list_t * free_l)665 ipc_port_clear_receiver(
666 	ipc_port_t          port,
667 	boolean_t           should_destroy,
668 	waitq_link_list_t  *free_l)
669 {
670 	ipc_mqueue_t    mqueue = &port->ip_messages;
671 	boolean_t       reap_messages = FALSE;
672 
673 	/*
674 	 * Pull ourselves out of any sets to which we belong.
675 	 * We hold the write space lock or the receive entry has
676 	 * been deleted, so even though this acquires and releases
677 	 * the port lock, we know we won't be added to any other sets.
678 	 */
679 	if (ip_in_pset(port)) {
680 		waitq_unlink_all_locked(&port->ip_waitq, NULL, free_l);
681 		assert(!ip_in_pset(port));
682 	}
683 
684 	/*
685 	 * Send anyone waiting on the port's queue directly away.
686 	 * Also clear the mscount, seqno, guard bits
687 	 */
688 	if (ip_in_a_space(port)) {
689 		ipc_mqueue_changed(ip_get_receiver(port), &port->ip_waitq);
690 	} else {
691 		ipc_mqueue_changed(NULL, &port->ip_waitq);
692 	}
693 	port->ip_mscount = 0;
694 	mqueue->imq_seqno = 0;
695 	port->ip_context = port->ip_guarded = port->ip_strict_guard = 0;
696 
697 	/*
698 	 * clear the immovable bit so the port can move back to anyone listening
699 	 * for the port destroy notification.
700 	 */
701 	port->ip_immovable_receive = 0;
702 
703 	if (should_destroy) {
704 		/*
705 		 * Mark the port and mqueue invalid, preventing further send/receive
706 		 * operations from succeeding. It's important for this to be
707 		 * done under the same lock hold as the ipc_mqueue_changed
708 		 * call to avoid additional threads blocking on an mqueue
709 		 * that's being destroyed.
710 		 *
711 		 * The port active bit needs to be guarded under mqueue lock for
712 		 * turnstiles
713 		 */
714 
715 		/* port transitions to INACTIVE state */
716 		io_bits_andnot(ip_to_object(port), IO_BITS_ACTIVE);
717 		port->ip_receiver_name = MACH_PORT_NULL;
718 		port->ip_timestamp = ipc_port_timestamp();
719 
720 		reap_messages = ipc_mqueue_destroy_locked(mqueue, free_l);
721 	} else {
722 		/* port transtions to IN-LIMBO state */
723 		port->ip_receiver_name = MACH_PORT_NULL;
724 		port->ip_destination = IP_NULL;
725 	}
726 
727 	return reap_messages;
728 }
729 
730 /*
731  *	Routine:	ipc_port_init
732  *	Purpose:
733  *		Initializes a newly-allocated port.
734  *
735  *		The memory is expected to be zero initialized (allocated with Z_ZERO).
736  */
737 
738 void
ipc_port_init(ipc_port_t port,ipc_space_t space,ipc_port_init_flags_t flags,mach_port_name_t name)739 ipc_port_init(
740 	ipc_port_t              port,
741 	ipc_space_t             space,
742 	ipc_port_init_flags_t   flags,
743 	mach_port_name_t        name)
744 {
745 	int policy = SYNC_POLICY_FIFO;
746 	task_t task = TASK_NULL;
747 
748 	/* the port has been 0 initialized when called */
749 
750 	if (flags & IPC_PORT_INIT_FILTER_MESSAGE) {
751 		io_bits_or(ip_to_object(port), IP_BIT_FILTER_MSG);
752 	}
753 	if (flags & IPC_PORT_INIT_LOCKED) {
754 		policy |= SYNC_POLICY_INIT_LOCKED;
755 	}
756 
757 	/* must be done first, many ip_* bits live inside the waitq */
758 	waitq_init(&port->ip_waitq, WQT_PORT, policy);
759 	if (flags & IPC_PORT_INIT_TG_BLOCK_TRACKING) {
760 		port->ip_tg_block_tracking = true;
761 	}
762 	if (flags & IPC_PORT_INIT_SPECIAL_REPLY) {
763 		port->ip_specialreply = true;
764 	}
765 	if ((flags & IPC_PORT_INIT_REPLY) || (flags & IPC_PORT_INIT_SPECIAL_REPLY)) {
766 		task = current_task_early();
767 
768 		/* Strict enforcement of reply port semantics are disabled for 3p - rdar://97441265. */
769 		if (task && task_get_platform_binary(task)) {
770 			port->ip_immovable_receive = true;
771 			ip_mark_reply_port(port);
772 		} else {
773 			ip_mark_provisional_reply_port(port);
774 		}
775 	}
776 	if (flags & IPC_PORT_ENFORCE_REPLY_PORT_SEMANTICS) {
777 		ip_enforce_reply_port_semantics(port);
778 	}
779 	if (flags & IPC_PORT_ENFORCE_RIGID_REPLY_PORT_SEMANTICS) {
780 		ip_enforce_rigid_reply_port_semantics(port);
781 	}
782 	if (flags & IPC_PORT_INIT_PROVISIONAL_REPLY) {
783 		ip_mark_provisional_reply_port(port);
784 	}
785 
786 	if (flags & IPC_PORT_INIT_PROVISIONAL_ID_PROT_OPTOUT) {
787 		ip_mark_id_prot_opt_out(port);
788 	}
789 
790 	port->ip_kernel_qos_override = THREAD_QOS_UNSPECIFIED;
791 	port->ip_kernel_iotier_override = THROTTLE_LEVEL_END;
792 
793 	ipc_mqueue_init(&port->ip_messages);
794 #if MACH_ASSERT
795 	ipc_port_init_debug(port, __builtin_frame_address(0));
796 #endif  /* MACH_ASSERT */
797 
798 	/* port transitions to IN-SPACE state */
799 	port->ip_receiver_name = name;
800 	port->ip_receiver = space;
801 
802 	if (flags & IPC_PORT_INIT_MAKE_SEND_RIGHT) {
803 		port->ip_srights = 1;
804 		port->ip_mscount = 1;
805 	}
806 }
807 
808 /*
809  *	Routine:	ipc_port_alloc
810  *	Purpose:
811  *		Allocate a port.
812  *	Conditions:
813  *		Nothing locked.  If successful, the port is returned
814  *		locked.  (The caller doesn't have a reference.)
815  *	Returns:
816  *		KERN_SUCCESS		The port is allocated.
817  *		KERN_INVALID_TASK	The space is dead.
818  *		KERN_NO_SPACE		No room for an entry in the space.
819  *		KERN_RESOURCE_SHORTAGE	Couldn't allocate memory.
820  */
821 
822 kern_return_t
ipc_port_alloc(ipc_space_t space,ipc_port_init_flags_t flags,mach_port_name_t * namep,ipc_port_t * portp)823 ipc_port_alloc(
824 	ipc_space_t             space,
825 	ipc_port_init_flags_t   flags,
826 	mach_port_name_t        *namep,
827 	ipc_port_t              *portp)
828 {
829 	ipc_port_t port;
830 	mach_port_name_t name;
831 	kern_return_t kr;
832 	mach_port_type_t type = MACH_PORT_TYPE_RECEIVE;
833 	mach_port_urefs_t urefs = 0;
834 
835 	if (flags & IPC_PORT_INIT_MAKE_SEND_RIGHT) {
836 		type |= MACH_PORT_TYPE_SEND;
837 		urefs = 1;
838 	}
839 	kr = ipc_object_alloc(space, IOT_PORT, type, urefs,
840 	    &name, (ipc_object_t *) &port);
841 	if (kr != KERN_SUCCESS) {
842 		return kr;
843 	}
844 
845 	/* space is locked */
846 	ipc_port_init(port, space, flags | IPC_PORT_INIT_LOCKED, name);
847 	/* port is locked */
848 #if MACH_ASSERT
849 	ipc_port_init_debug(port, __builtin_frame_address(0));
850 #endif  /* MACH_ASSERT */
851 
852 	/* unlock space after init */
853 	is_write_unlock(space);
854 
855 	*namep = name;
856 	*portp = port;
857 
858 	return KERN_SUCCESS;
859 }
860 
861 /*
862  *	Routine:	ipc_port_alloc_name
863  *	Purpose:
864  *		Allocate a port, with a specific name.
865  *	Conditions:
866  *		Nothing locked.  If successful, the port is returned
867  *		locked.  (The caller doesn't have a reference.)
868  *	Returns:
869  *		KERN_SUCCESS		The port is allocated.
870  *		KERN_INVALID_TASK	The space is dead.
871  *		KERN_NAME_EXISTS	The name already denotes a right.
872  *		KERN_RESOURCE_SHORTAGE	Couldn't allocate memory.
873  */
874 
875 kern_return_t
ipc_port_alloc_name(ipc_space_t space,ipc_port_init_flags_t flags,mach_port_name_t name,ipc_port_t * portp)876 ipc_port_alloc_name(
877 	ipc_space_t             space,
878 	ipc_port_init_flags_t   flags,
879 	mach_port_name_t        name,
880 	ipc_port_t              *portp)
881 {
882 	mach_port_type_t type = MACH_PORT_TYPE_RECEIVE;
883 	mach_port_urefs_t urefs = 0;
884 
885 	if (flags & IPC_PORT_INIT_MAKE_SEND_RIGHT) {
886 		type |= MACH_PORT_TYPE_SEND;
887 		urefs = 1;
888 	}
889 	flags |= IPC_PORT_INIT_LOCKED;
890 
891 	return ipc_object_alloc_name(space, IOT_PORT, type, urefs,
892 	           name, (ipc_object_t *)portp, ^(ipc_object_t object){
893 		ipc_port_init(ip_object_to_port(object), space, flags, name);
894 	});
895 }
896 
897 /*
898  *      Routine:	ipc_port_spnotify
899  *	Purpose:
900  *		Generate send-possible port notifications.
901  *	Conditions:
902  *		Nothing locked, reference held on port.
903  */
904 void
ipc_port_spnotify(ipc_port_t port)905 ipc_port_spnotify(
906 	ipc_port_t      port)
907 {
908 	ipc_port_request_index_t index = 0;
909 	ipc_table_elems_t size = 0;
910 
911 	/*
912 	 * If the port has no send-possible request
913 	 * armed, don't bother to lock the port.
914 	 */
915 	if (port->ip_sprequests == 0) {
916 		return;
917 	}
918 
919 	ip_mq_lock(port);
920 
921 #if IMPORTANCE_INHERITANCE
922 	if (port->ip_spimportant != 0) {
923 		port->ip_spimportant = 0;
924 		if (ipc_port_importance_delta(port, IPID_OPTION_NORMAL, -1) == TRUE) {
925 			ip_mq_lock(port);
926 		}
927 	}
928 #endif /* IMPORTANCE_INHERITANCE */
929 
930 	if (port->ip_sprequests == 0) {
931 		ip_mq_unlock(port);
932 		return;
933 	}
934 	port->ip_sprequests = 0;
935 
936 revalidate:
937 	if (ip_active(port)) {
938 		ipc_port_request_table_t requests;
939 
940 		/* table may change each time port unlocked (reload) */
941 		requests = port->ip_requests;
942 		assert(requests != NULL);
943 
944 		/*
945 		 * no need to go beyond table size when first
946 		 * we entered - those are future notifications.
947 		 */
948 		if (size == 0) {
949 			size = ipc_port_request_table_count(requests);
950 		}
951 
952 		/* no need to backtrack either */
953 		while (++index < size) {
954 			ipc_port_request_t ipr = ipc_port_request_table_get_nocheck(requests, index);
955 			mach_port_name_t name = ipr->ipr_name;
956 			ipc_port_t soright = IPR_SOR_PORT(ipr->ipr_soright);
957 			boolean_t armed = IPR_SOR_SPARMED(ipr->ipr_soright);
958 
959 			if (MACH_PORT_VALID(name) && armed && IP_VALID(soright)) {
960 				/* claim send-once right - slot still inuse */
961 				assert(name != IPR_HOST_NOTIFY);
962 				ipr->ipr_soright = IP_NULL;
963 				ip_mq_unlock(port);
964 
965 				ipc_notify_send_possible(soright, name);
966 
967 				ip_mq_lock(port);
968 				goto revalidate;
969 			}
970 		}
971 	}
972 	ip_mq_unlock(port);
973 	return;
974 }
975 
976 /*
977  *      Routine:	ipc_port_dnnotify
978  *	Purpose:
979  *		Generate dead name notifications for
980  *		all outstanding dead-name and send-
981  *		possible requests.
982  *	Conditions:
983  *		Nothing locked.
984  *		Port must be inactive.
985  *		Reference held on port.
986  */
987 void
ipc_port_dnnotify(ipc_port_t port)988 ipc_port_dnnotify(
989 	ipc_port_t      port)
990 {
991 	ipc_port_request_table_t requests = port->ip_requests;
992 
993 	assert(!ip_active(port));
994 	if (requests != NULL) {
995 		ipc_port_request_t ipr = ipc_port_request_table_base(requests);
996 
997 		while ((ipr = ipc_port_request_table_next_elem(requests, ipr))) {
998 			mach_port_name_t name = ipr->ipr_name;
999 			ipc_port_t soright;
1000 
1001 			switch (name) {
1002 			case MACH_PORT_DEAD:
1003 			case MACH_PORT_NULL:
1004 				break;
1005 			case IPR_HOST_NOTIFY:
1006 				host_notify_cancel(ipr->ipr_hnotify);
1007 				break;
1008 			default:
1009 				soright = IPR_SOR_PORT(ipr->ipr_soright);
1010 				if (IP_VALID(soright)) {
1011 					ipc_notify_dead_name(soright, name);
1012 				}
1013 				break;
1014 			}
1015 		}
1016 	}
1017 }
1018 
1019 /*
1020  *	Routine:	ipc_port_destroy
1021  *	Purpose:
1022  *		Destroys a port.  Cleans up queued messages.
1023  *
1024  *		If the port has a backup, it doesn't get destroyed,
1025  *		but is sent in a port-destroyed notification to the backup.
1026  *	Conditions:
1027  *		The port is locked and alive; nothing else locked.
1028  *		The caller has a reference, which is consumed.
1029  *		Afterwards, the port is unlocked and dead.
1030  */
1031 
1032 void
ipc_port_destroy(ipc_port_t port)1033 ipc_port_destroy(ipc_port_t port)
1034 {
1035 	bool special_reply = port->ip_specialreply;
1036 	bool service_port  = port->ip_service_port;
1037 	bool reap_msgs;
1038 
1039 	ipc_port_t pdrequest = IP_NULL;
1040 	struct task_watchport_elem *twe = NULL;
1041 	waitq_link_list_t free_l = { };
1042 
1043 #if IMPORTANCE_INHERITANCE
1044 	ipc_importance_task_t release_imp_task = IIT_NULL;
1045 	thread_t self = current_thread();
1046 	boolean_t top = (self->ith_assertions == 0);
1047 	natural_t assertcnt = 0;
1048 #endif /* IMPORTANCE_INHERITANCE */
1049 
1050 	require_ip_active(port);
1051 	/* port->ip_receiver_name is garbage */
1052 	/* port->ip_receiver/port->ip_destination is garbage */
1053 
1054 	/* clear any reply-port context */
1055 	port->ip_reply_context = 0;
1056 
1057 	/* must be done before we access ip_pdrequest */
1058 	twe = ipc_port_clear_watchport_elem_internal(port);
1059 	assert(!port->ip_has_watchport);
1060 
1061 	if (!special_reply) {
1062 		/* we assume the ref for pdrequest */
1063 		pdrequest = port->ip_pdrequest;
1064 		port->ip_pdrequest = IP_NULL;
1065 	} else if (port->ip_tempowner) {
1066 		panic("ipc_port_destroy: invalid state");
1067 	}
1068 
1069 #if IMPORTANCE_INHERITANCE
1070 	/* determine how many assertions to drop and from whom */
1071 	if (port->ip_tempowner != 0) {
1072 		assert(top);
1073 		release_imp_task = ip_get_imp_task(port);
1074 		if (IIT_NULL != release_imp_task) {
1075 			port->ip_imp_task = IIT_NULL;
1076 			assertcnt = port->ip_impcount;
1077 		}
1078 		/* Otherwise, nothing to drop */
1079 	} else {
1080 		assertcnt = port->ip_impcount;
1081 		if (pdrequest != IP_NULL) {
1082 			/* mark in limbo for the journey */
1083 			port->ip_tempowner = 1;
1084 		}
1085 	}
1086 
1087 	if (top) {
1088 		self->ith_assertions = assertcnt;
1089 	}
1090 #endif /* IMPORTANCE_INHERITANCE */
1091 
1092 	/*
1093 	 * If no port-destroyed notification is armed, calling
1094 	 * ipc_port_clear_receiver() will mark the port inactive
1095 	 * and will wakeup any threads which may be blocked receiving on it.
1096 	 */
1097 	reap_msgs = ipc_port_clear_receiver(port, pdrequest == IP_NULL, &free_l);
1098 	assert(!ip_in_pset(port));
1099 	assert(port->ip_mscount == 0);
1100 
1101 	/*
1102 	 * Handle port-destroyed notification
1103 	 */
1104 	if (pdrequest != IP_NULL) {
1105 		assert(reap_msgs == false);
1106 
1107 		if (service_port) {
1108 			assert(port->ip_splabel != NULL);
1109 			if (ipc_service_port_label_is_special_pdrequest((ipc_service_port_label_t)port->ip_splabel)) {
1110 				ipc_service_port_label_set_flag(port->ip_splabel, ISPL_FLAGS_SEND_PD_NOTIFICATION);
1111 			}
1112 		}
1113 
1114 		ipc_port_send_turnstile_recompute_push_locked(port);
1115 		/* port unlocked */
1116 
1117 		/* consumes our refs for port and pdrequest */
1118 		ipc_notify_port_destroyed(pdrequest, port);
1119 	} else {
1120 		ipc_service_port_label_t splabel = NULL;
1121 		ipc_notify_nsenders_t nsrequest;
1122 
1123 		nsrequest = ipc_notify_no_senders_prepare(port);
1124 
1125 		if (!ip_is_kolabeled(port)) {
1126 			splabel = port->ip_splabel;
1127 			port->ip_splabel = NULL;
1128 			port->ip_service_port = false;
1129 		}
1130 
1131 		ipc_port_send_turnstile_recompute_push_locked(port);
1132 		/* port unlocked */
1133 
1134 		/* unlink the kmsg from special reply port */
1135 		if (special_reply) {
1136 			ipc_port_adjust_special_reply_port(port,
1137 			    IPC_PORT_ADJUST_SR_ALLOW_SYNC_LINKAGE);
1138 		}
1139 
1140 		/* Deallocate the service/connection port label */
1141 		if (splabel) {
1142 			ipc_service_port_label_dealloc(splabel, service_port);
1143 			splabel = NULL;
1144 		}
1145 
1146 		if (reap_msgs) {
1147 			ipc_kmsg_reap_delayed();
1148 		}
1149 
1150 		if (nsrequest.ns_notify) {
1151 			/*
1152 			 * ipc_notify_no_senders_prepare will consume
1153 			 * the reference for kobjects.
1154 			 */
1155 			assert(!nsrequest.ns_is_kobject);
1156 			ip_mq_lock(nsrequest.ns_notify);
1157 			ipc_notify_send_once_and_unlock(nsrequest.ns_notify); /* consumes ref */
1158 		}
1159 
1160 		/* generate dead-name notifications */
1161 		ipc_port_dnnotify(port);
1162 
1163 		ipc_kobject_destroy(port);
1164 
1165 		ip_release(port); /* consume caller's ref */
1166 	}
1167 
1168 	if (twe) {
1169 		task_watchport_elem_deallocate(twe);
1170 		twe = NULL;
1171 	}
1172 
1173 	waitq_link_free_list(WQT_PORT_SET, &free_l);
1174 
1175 #if IMPORTANCE_INHERITANCE
1176 	if (release_imp_task != IIT_NULL) {
1177 		if (assertcnt > 0) {
1178 			assert(top);
1179 			self->ith_assertions = 0;
1180 			assert(ipc_importance_task_is_any_receiver_type(release_imp_task));
1181 			ipc_importance_task_drop_internal_assertion(release_imp_task, assertcnt);
1182 		}
1183 		ipc_importance_task_release(release_imp_task);
1184 	} else if (assertcnt > 0) {
1185 		if (top) {
1186 			self->ith_assertions = 0;
1187 			release_imp_task = current_task()->task_imp_base;
1188 			if (ipc_importance_task_is_any_receiver_type(release_imp_task)) {
1189 				ipc_importance_task_drop_internal_assertion(release_imp_task, assertcnt);
1190 			}
1191 		}
1192 	}
1193 #endif /* IMPORTANCE_INHERITANCE */
1194 }
1195 
1196 /*
1197  *	Routine:	ipc_port_destination_chain_lock
1198  *	Purpose:
1199  *		Search for the end of the chain (a port not in transit),
1200  *		acquiring locks along the way, and return it in `base`.
1201  *
1202  *		Returns true if a reference was taken on `base`
1203  *
1204  *	Conditions:
1205  *		No ports locked.
1206  *		ipc_port_multiple_lock held.
1207  */
1208 boolean_t
ipc_port_destination_chain_lock(ipc_port_t port,ipc_port_t * base)1209 ipc_port_destination_chain_lock(
1210 	ipc_port_t port,
1211 	ipc_port_t *base)
1212 {
1213 	for (;;) {
1214 		ip_mq_lock(port);
1215 
1216 		if (!ip_active(port)) {
1217 			/*
1218 			 * Active ports that are ip_mq_lock()ed cannot go away.
1219 			 *
1220 			 * But inactive ports at the end of walking
1221 			 * an ip_destination chain are only protected
1222 			 * from space termination cleanup while the entire
1223 			 * chain of ports leading to them is held.
1224 			 *
1225 			 * Callers of this code tend to unlock the chain
1226 			 * in the same order than this walk which doesn't
1227 			 * protect `base` properly when it's inactive.
1228 			 *
1229 			 * In that case, take a reference that the caller
1230 			 * is responsible for releasing.
1231 			 */
1232 			ip_reference(port);
1233 			*base = port;
1234 			return true;
1235 		}
1236 
1237 		/* port is active */
1238 		if (!ip_in_transit(port)) {
1239 			*base = port;
1240 			return false;
1241 		}
1242 
1243 		port = ip_get_destination(port);
1244 	}
1245 }
1246 
1247 
1248 /*
1249  *	Routine:	ipc_port_check_circularity
1250  *	Purpose:
1251  *		Check if queueing "port" in a message for "dest"
1252  *		would create a circular group of ports and messages.
1253  *
1254  *		If no circularity (FALSE returned), then "port"
1255  *		is changed from "in limbo" to "in transit".
1256  *
1257  *		That is, we want to set port->ip_destination == dest,
1258  *		but guaranteeing that this doesn't create a circle
1259  *		port->ip_destination->ip_destination->... == port
1260  *
1261  *	Conditions:
1262  *		No ports locked.  References held for "port" and "dest".
1263  */
1264 
1265 boolean_t
ipc_port_check_circularity(ipc_port_t port,ipc_port_t dest)1266 ipc_port_check_circularity(
1267 	ipc_port_t      port,
1268 	ipc_port_t      dest)
1269 {
1270 #if IMPORTANCE_INHERITANCE
1271 	/* adjust importance counts at the same time */
1272 	return ipc_importance_check_circularity(port, dest);
1273 #else
1274 	ipc_port_t base;
1275 	struct task_watchport_elem *watchport_elem = NULL;
1276 	bool took_base_ref = false;
1277 
1278 	assert(port != IP_NULL);
1279 	assert(dest != IP_NULL);
1280 
1281 	if (port == dest) {
1282 		return TRUE;
1283 	}
1284 	base = dest;
1285 
1286 	/* Check if destination needs a turnstile */
1287 	ipc_port_send_turnstile_prepare(dest);
1288 
1289 	/*
1290 	 *	First try a quick check that can run in parallel.
1291 	 *	No circularity if dest is not in transit.
1292 	 */
1293 	ip_mq_lock(port);
1294 	if (ip_mq_lock_try(dest)) {
1295 		if (!ip_in_transit(dest)) {
1296 			goto not_circular;
1297 		}
1298 
1299 		/* dest is in transit; further checking necessary */
1300 
1301 		ip_mq_unlock(dest);
1302 	}
1303 	ip_mq_unlock(port);
1304 
1305 	ipc_port_multiple_lock(); /* massive serialization */
1306 
1307 	/*
1308 	 *	Search for the end of the chain (a port not in transit),
1309 	 *	acquiring locks along the way.
1310 	 */
1311 
1312 	took_base_ref = ipc_port_destination_chain_lock(dest, &base);
1313 	/* all ports in chain from dest to base, inclusive, are locked */
1314 
1315 	if (port == base) {
1316 		/* circularity detected! */
1317 
1318 		ipc_port_multiple_unlock();
1319 
1320 		/* port (== base) is in limbo */
1321 		require_ip_active(port);
1322 		assert(ip_in_limbo(port));
1323 		assert(!took_base_ref);
1324 
1325 		base = dest;
1326 		while (base != IP_NULL) {
1327 			ipc_port_t next;
1328 
1329 			/* dest is in transit or in limbo */
1330 			require_ip_active(base);
1331 			assert(!ip_in_a_space(base));
1332 
1333 			next = ip_get_destination(base);
1334 			ip_mq_unlock(base);
1335 			base = next;
1336 		}
1337 
1338 		ipc_port_send_turnstile_complete(dest);
1339 		return TRUE;
1340 	}
1341 
1342 	/*
1343 	 *	The guarantee:  lock port while the entire chain is locked.
1344 	 *	Once port is locked, we can take a reference to dest,
1345 	 *	add port to the chain, and unlock everything.
1346 	 */
1347 
1348 	ip_mq_lock(port);
1349 	ipc_port_multiple_unlock();
1350 
1351 not_circular:
1352 	require_ip_active(port);
1353 	assert(ip_in_limbo(port));
1354 
1355 	/* Clear the watchport boost */
1356 	watchport_elem = ipc_port_clear_watchport_elem_internal(port);
1357 
1358 	/* Check if the port is being enqueued as a part of sync bootstrap checkin */
1359 	if (dest->ip_specialreply && dest->ip_sync_bootstrap_checkin) {
1360 		port->ip_sync_bootstrap_checkin = 1;
1361 	}
1362 
1363 	ip_reference(dest);
1364 
1365 	/* port transitions to IN-TRANSIT state */
1366 	assert(port->ip_receiver_name == MACH_PORT_NULL);
1367 	port->ip_destination = dest;
1368 
1369 	/* Setup linkage for source port if it has sync ipc push */
1370 	struct turnstile *send_turnstile = TURNSTILE_NULL;
1371 	if (port_send_turnstile(port)) {
1372 		send_turnstile = turnstile_prepare((uintptr_t)port,
1373 		    port_send_turnstile_address(port),
1374 		    TURNSTILE_NULL, TURNSTILE_SYNC_IPC);
1375 
1376 		/*
1377 		 * What ipc_port_adjust_port_locked would do,
1378 		 * but we need to also drop even more locks before
1379 		 * calling turnstile_update_inheritor_complete().
1380 		 */
1381 		ipc_port_adjust_sync_link_state_locked(port, PORT_SYNC_LINK_ANY, NULL);
1382 
1383 		turnstile_update_inheritor(send_turnstile, port_send_turnstile(dest),
1384 		    (TURNSTILE_INHERITOR_TURNSTILE | TURNSTILE_IMMEDIATE_UPDATE));
1385 
1386 		/* update complete and turnstile complete called after dropping all locks */
1387 	}
1388 	/* now unlock chain */
1389 
1390 	ip_mq_unlock(port);
1391 
1392 	for (;;) {
1393 		ipc_port_t next;
1394 
1395 		if (dest == base) {
1396 			break;
1397 		}
1398 
1399 		/* port is IN-TRANSIT */
1400 		require_ip_active(dest);
1401 		assert(ip_in_transit(dest));
1402 
1403 		next = ip_get_destination(dest);
1404 		ip_mq_unlock(dest);
1405 		dest = next;
1406 	}
1407 
1408 	/* base is not IN-TRANSIT */
1409 	assert(!ip_in_transit(base));
1410 
1411 	ip_mq_unlock(base);
1412 	if (took_base_ref) {
1413 		ip_release(base);
1414 	}
1415 
1416 	/* All locks dropped, call turnstile_update_inheritor_complete for source port's turnstile */
1417 	if (send_turnstile) {
1418 		turnstile_update_inheritor_complete(send_turnstile, TURNSTILE_INTERLOCK_NOT_HELD);
1419 
1420 		/* Take the mq lock to call turnstile complete */
1421 		ip_mq_lock(port);
1422 		turnstile_complete((uintptr_t)port, port_send_turnstile_address(port), NULL, TURNSTILE_SYNC_IPC);
1423 		send_turnstile = TURNSTILE_NULL;
1424 		ip_mq_unlock(port);
1425 		turnstile_cleanup();
1426 	}
1427 
1428 	if (watchport_elem) {
1429 		task_watchport_elem_deallocate(watchport_elem);
1430 	}
1431 
1432 	return FALSE;
1433 #endif /* !IMPORTANCE_INHERITANCE */
1434 }
1435 
1436 /*
1437  *	Routine:	ipc_port_watchport_elem
1438  *	Purpose:
1439  *		Get the port's watchport elem field
1440  *
1441  *	Conditions:
1442  *		port locked
1443  */
1444 static struct task_watchport_elem *
ipc_port_watchport_elem(ipc_port_t port)1445 ipc_port_watchport_elem(ipc_port_t port)
1446 {
1447 	if (port->ip_has_watchport) {
1448 		assert(!port->ip_specialreply);
1449 		return port->ip_twe;
1450 	}
1451 	return NULL;
1452 }
1453 
1454 /*
1455  *	Routine:	ipc_port_update_watchport_elem
1456  *	Purpose:
1457  *		Set the port's watchport elem field
1458  *
1459  *	Conditions:
1460  *		port locked and is not a special reply port.
1461  */
1462 static inline struct task_watchport_elem *
ipc_port_update_watchport_elem(ipc_port_t port,struct task_watchport_elem * we)1463 ipc_port_update_watchport_elem(ipc_port_t port, struct task_watchport_elem *we)
1464 {
1465 	struct task_watchport_elem *old_we;
1466 	ipc_port_t pdrequest;
1467 
1468 	assert(!port->ip_specialreply);
1469 
1470 	/*
1471 	 * Note: ip_pdrequest and ip_twe are unioned.
1472 	 *       and ip_has_watchport controls the union "type"
1473 	 */
1474 	if (port->ip_has_watchport) {
1475 		old_we = port->ip_twe;
1476 		pdrequest = old_we->twe_pdrequest;
1477 		old_we->twe_pdrequest = IP_NULL;
1478 	} else {
1479 		old_we = NULL;
1480 		pdrequest = port->ip_pdrequest;
1481 	}
1482 
1483 	if (we) {
1484 		port->ip_has_watchport = true;
1485 		we->twe_pdrequest = pdrequest;
1486 		port->ip_twe = we;
1487 	} else {
1488 		port->ip_has_watchport = false;
1489 		port->ip_pdrequest = pdrequest;
1490 	}
1491 
1492 	return old_we;
1493 }
1494 
1495 /*
1496  *	Routine:	ipc_special_reply_stash_pid_locked
1497  *	Purpose:
1498  *		Set the pid of process that copied out send once right to special reply port.
1499  *
1500  *	Conditions:
1501  *		port locked
1502  */
1503 static inline void
ipc_special_reply_stash_pid_locked(ipc_port_t port,int pid)1504 ipc_special_reply_stash_pid_locked(ipc_port_t port, int pid)
1505 {
1506 	assert(port->ip_specialreply);
1507 	port->ip_pid = pid;
1508 }
1509 
1510 /*
1511  *	Routine:	ipc_special_reply_get_pid_locked
1512  *	Purpose:
1513  *		Get the pid of process that copied out send once right to special reply port.
1514  *
1515  *	Conditions:
1516  *		port locked
1517  */
1518 int
ipc_special_reply_get_pid_locked(ipc_port_t port)1519 ipc_special_reply_get_pid_locked(ipc_port_t port)
1520 {
1521 	assert(port->ip_specialreply);
1522 	return port->ip_pid;
1523 }
1524 
1525 /*
1526  * Update the recv turnstile inheritor for a port.
1527  *
1528  * Sync IPC through the port receive turnstile only happens for the special
1529  * reply port case. It has three sub-cases:
1530  *
1531  * 1. a send-once right is in transit, and pushes on the send turnstile of its
1532  *    destination mqueue.
1533  *
1534  * 2. a send-once right has been stashed on a knote it was copied out "through",
1535  *    as the first such copied out port.
1536  *
1537  * 3. a send-once right has been stashed on a knote it was copied out "through",
1538  *    as the second or more copied out port.
1539  */
1540 void
ipc_port_recv_update_inheritor(ipc_port_t port,struct turnstile * rcv_turnstile,turnstile_update_flags_t flags)1541 ipc_port_recv_update_inheritor(
1542 	ipc_port_t port,
1543 	struct turnstile *rcv_turnstile,
1544 	turnstile_update_flags_t flags)
1545 {
1546 	struct turnstile *inheritor = TURNSTILE_NULL;
1547 	struct knote *kn;
1548 
1549 	if (ip_active(port) && port->ip_specialreply) {
1550 		ip_mq_lock_held(port);
1551 
1552 		switch (port->ip_sync_link_state) {
1553 		case PORT_SYNC_LINK_PORT:
1554 			if (port->ip_sync_inheritor_port != NULL) {
1555 				inheritor = port_send_turnstile(port->ip_sync_inheritor_port);
1556 			}
1557 			break;
1558 
1559 		case PORT_SYNC_LINK_WORKLOOP_KNOTE:
1560 			kn = port->ip_sync_inheritor_knote;
1561 			inheritor = filt_ipc_kqueue_turnstile(kn);
1562 			break;
1563 
1564 		case PORT_SYNC_LINK_WORKLOOP_STASH:
1565 			inheritor = port->ip_sync_inheritor_ts;
1566 			break;
1567 		}
1568 	}
1569 
1570 	turnstile_update_inheritor(rcv_turnstile, inheritor,
1571 	    flags | TURNSTILE_INHERITOR_TURNSTILE);
1572 }
1573 
1574 /*
1575  * Update the send turnstile inheritor for a port.
1576  *
1577  * Sync IPC through the port send turnstile has 7 possible reasons to be linked:
1578  *
1579  * 1. a special reply port is part of sync ipc for bootstrap checkin and needs
1580  *    to push on thread doing the sync ipc.
1581  *
1582  * 2. a receive right is in transit, and pushes on the send turnstile of its
1583  *    destination mqueue.
1584  *
1585  * 3. port was passed as an exec watchport and port is pushing on main thread
1586  *    of the task.
1587  *
1588  * 4. a receive right has been stashed on a knote it was copied out "through",
1589  *    as the first such copied out port (same as PORT_SYNC_LINK_WORKLOOP_KNOTE
1590  *    for the special reply port)
1591  *
1592  * 5. a receive right has been stashed on a knote it was copied out "through",
1593  *    as the second or more copied out port (same as
1594  *    PORT_SYNC_LINK_WORKLOOP_STASH for the special reply port)
1595  *
1596  * 6. a receive right has been copied out as a part of sync bootstrap checkin
1597  *    and needs to push on thread doing the sync bootstrap checkin.
1598  *
1599  * 7. the receive right is monitored by a knote, and pushes on any that is
1600  *    registered on a workloop. filt_machport makes sure that if such a knote
1601  *    exists, it is kept as the first item in the knote list, so we never need
1602  *    to walk.
1603  */
1604 void
ipc_port_send_update_inheritor(ipc_port_t port,struct turnstile * send_turnstile,turnstile_update_flags_t flags)1605 ipc_port_send_update_inheritor(
1606 	ipc_port_t port,
1607 	struct turnstile *send_turnstile,
1608 	turnstile_update_flags_t flags)
1609 {
1610 	ipc_mqueue_t mqueue = &port->ip_messages;
1611 	turnstile_inheritor_t inheritor = TURNSTILE_INHERITOR_NULL;
1612 	struct knote *kn;
1613 	turnstile_update_flags_t inheritor_flags = TURNSTILE_INHERITOR_TURNSTILE;
1614 
1615 	ip_mq_lock_held(port);
1616 
1617 	if (!ip_active(port)) {
1618 		/* this port is no longer active, it should not push anywhere */
1619 	} else if (port->ip_specialreply) {
1620 		/* Case 1. */
1621 		if (port->ip_sync_bootstrap_checkin && prioritize_launch) {
1622 			inheritor = port->ip_messages.imq_srp_owner_thread;
1623 			inheritor_flags = TURNSTILE_INHERITOR_THREAD;
1624 		}
1625 	} else if (ip_in_transit(port)) {
1626 		/* Case 2. */
1627 		inheritor = port_send_turnstile(ip_get_destination(port));
1628 	} else if (port->ip_has_watchport) {
1629 		/* Case 3. */
1630 		if (prioritize_launch) {
1631 			assert(port->ip_sync_link_state == PORT_SYNC_LINK_ANY);
1632 			inheritor = ipc_port_get_watchport_inheritor(port);
1633 			inheritor_flags = TURNSTILE_INHERITOR_THREAD;
1634 		}
1635 	} else if (port->ip_sync_link_state == PORT_SYNC_LINK_WORKLOOP_KNOTE) {
1636 		/* Case 4. */
1637 		inheritor = filt_ipc_kqueue_turnstile(mqueue->imq_inheritor_knote);
1638 	} else if (port->ip_sync_link_state == PORT_SYNC_LINK_WORKLOOP_STASH) {
1639 		/* Case 5. */
1640 		inheritor = mqueue->imq_inheritor_turnstile;
1641 	} else if (port->ip_sync_link_state == PORT_SYNC_LINK_RCV_THREAD) {
1642 		/* Case 6. */
1643 		if (prioritize_launch) {
1644 			inheritor = port->ip_messages.imq_inheritor_thread_ref;
1645 			inheritor_flags = TURNSTILE_INHERITOR_THREAD;
1646 		}
1647 	} else if ((kn = SLIST_FIRST(&port->ip_klist))) {
1648 		/* Case 7. Push on a workloop that is interested */
1649 		if (filt_machport_kqueue_has_turnstile(kn)) {
1650 			assert(port->ip_sync_link_state == PORT_SYNC_LINK_ANY);
1651 			inheritor = filt_ipc_kqueue_turnstile(kn);
1652 		}
1653 	}
1654 
1655 	turnstile_update_inheritor(send_turnstile, inheritor,
1656 	    flags | inheritor_flags);
1657 }
1658 
1659 /*
1660  *	Routine:	ipc_port_send_turnstile_prepare
1661  *	Purpose:
1662  *		Get a reference on port's send turnstile, if
1663  *		port does not have a send turnstile then allocate one.
1664  *
1665  *	Conditions:
1666  *		Nothing is locked.
1667  */
1668 void
ipc_port_send_turnstile_prepare(ipc_port_t port)1669 ipc_port_send_turnstile_prepare(ipc_port_t port)
1670 {
1671 	struct turnstile *turnstile = TURNSTILE_NULL;
1672 	struct turnstile *send_turnstile = TURNSTILE_NULL;
1673 
1674 retry_alloc:
1675 	ip_mq_lock(port);
1676 
1677 	if (port_send_turnstile(port) == NULL ||
1678 	    port_send_turnstile(port)->ts_prim_count == 0) {
1679 		if (turnstile == TURNSTILE_NULL) {
1680 			ip_mq_unlock(port);
1681 			turnstile = turnstile_alloc();
1682 			goto retry_alloc;
1683 		}
1684 
1685 		send_turnstile = turnstile_prepare((uintptr_t)port,
1686 		    port_send_turnstile_address(port),
1687 		    turnstile, TURNSTILE_SYNC_IPC);
1688 		turnstile = TURNSTILE_NULL;
1689 
1690 		ipc_port_send_update_inheritor(port, send_turnstile,
1691 		    TURNSTILE_IMMEDIATE_UPDATE);
1692 
1693 		/* turnstile complete will be called in ipc_port_send_turnstile_complete */
1694 	}
1695 
1696 	/* Increment turnstile counter */
1697 	port_send_turnstile(port)->ts_prim_count++;
1698 	ip_mq_unlock(port);
1699 
1700 	if (send_turnstile) {
1701 		turnstile_update_inheritor_complete(send_turnstile,
1702 		    TURNSTILE_INTERLOCK_NOT_HELD);
1703 	}
1704 	if (turnstile != TURNSTILE_NULL) {
1705 		turnstile_deallocate(turnstile);
1706 	}
1707 }
1708 
1709 
1710 /*
1711  *	Routine:	ipc_port_send_turnstile_complete
1712  *	Purpose:
1713  *		Drop a ref on the port's send turnstile, if the
1714  *		ref becomes zero, deallocate the turnstile.
1715  *
1716  *	Conditions:
1717  *		The space might be locked, use safe deallocate.
1718  */
1719 void
ipc_port_send_turnstile_complete(ipc_port_t port)1720 ipc_port_send_turnstile_complete(ipc_port_t port)
1721 {
1722 	struct turnstile *turnstile = TURNSTILE_NULL;
1723 
1724 	/* Drop turnstile count on dest port */
1725 	ip_mq_lock(port);
1726 
1727 	port_send_turnstile(port)->ts_prim_count--;
1728 	if (port_send_turnstile(port)->ts_prim_count == 0) {
1729 		turnstile_complete((uintptr_t)port, port_send_turnstile_address(port),
1730 		    &turnstile, TURNSTILE_SYNC_IPC);
1731 		assert(turnstile != TURNSTILE_NULL);
1732 	}
1733 	ip_mq_unlock(port);
1734 	turnstile_cleanup();
1735 
1736 	if (turnstile != TURNSTILE_NULL) {
1737 		turnstile_deallocate_safe(turnstile);
1738 		turnstile = TURNSTILE_NULL;
1739 	}
1740 }
1741 
1742 /*
1743  *	Routine:	ipc_port_rcv_turnstile
1744  *	Purpose:
1745  *		Get the port's receive turnstile
1746  *
1747  *	Conditions:
1748  *		mqueue locked or thread waiting on turnstile is locked.
1749  */
1750 static struct turnstile *
ipc_port_rcv_turnstile(ipc_port_t port)1751 ipc_port_rcv_turnstile(ipc_port_t port)
1752 {
1753 	return *port_rcv_turnstile_address(port);
1754 }
1755 
1756 
1757 /*
1758  *	Routine:	ipc_port_link_special_reply_port
1759  *	Purpose:
1760  *		Link the special reply port with the destination port.
1761  *              Allocates turnstile to dest port.
1762  *
1763  *	Conditions:
1764  *		Nothing is locked.
1765  */
1766 void
ipc_port_link_special_reply_port(ipc_port_t special_reply_port,ipc_port_t dest_port,boolean_t sync_bootstrap_checkin)1767 ipc_port_link_special_reply_port(
1768 	ipc_port_t special_reply_port,
1769 	ipc_port_t dest_port,
1770 	boolean_t sync_bootstrap_checkin)
1771 {
1772 	boolean_t drop_turnstile_ref = FALSE;
1773 	boolean_t special_reply = FALSE;
1774 
1775 	/* Check if dest_port needs a turnstile */
1776 	ipc_port_send_turnstile_prepare(dest_port);
1777 
1778 	/* Lock the special reply port and establish the linkage */
1779 	ip_mq_lock(special_reply_port);
1780 
1781 	special_reply = special_reply_port->ip_specialreply;
1782 
1783 	if (sync_bootstrap_checkin && special_reply) {
1784 		special_reply_port->ip_sync_bootstrap_checkin = 1;
1785 	}
1786 
1787 	/* Check if we need to drop the acquired turnstile ref on dest port */
1788 	if (!special_reply ||
1789 	    special_reply_port->ip_sync_link_state != PORT_SYNC_LINK_ANY ||
1790 	    special_reply_port->ip_sync_inheritor_port != IPC_PORT_NULL) {
1791 		drop_turnstile_ref = TRUE;
1792 	} else {
1793 		/* take a reference on dest_port */
1794 		ip_reference(dest_port);
1795 		special_reply_port->ip_sync_inheritor_port = dest_port;
1796 		special_reply_port->ip_sync_link_state = PORT_SYNC_LINK_PORT;
1797 	}
1798 
1799 	ip_mq_unlock(special_reply_port);
1800 
1801 	if (special_reply) {
1802 		/*
1803 		 * For special reply ports, if the destination port is
1804 		 * marked with the thread group blocked tracking flag,
1805 		 * callout to the performance controller.
1806 		 */
1807 		ipc_port_thread_group_blocked(dest_port);
1808 	}
1809 
1810 	if (drop_turnstile_ref) {
1811 		ipc_port_send_turnstile_complete(dest_port);
1812 	}
1813 
1814 	return;
1815 }
1816 
1817 /*
1818  *	Routine:	ipc_port_thread_group_blocked
1819  *	Purpose:
1820  *		Call thread_group_blocked callout if the port
1821  *	        has ip_tg_block_tracking bit set and the thread
1822  *	        has not made this callout already.
1823  *
1824  *	Conditions:
1825  *		Nothing is locked.
1826  */
1827 void
ipc_port_thread_group_blocked(ipc_port_t port __unused)1828 ipc_port_thread_group_blocked(ipc_port_t port __unused)
1829 {
1830 #if CONFIG_THREAD_GROUPS
1831 	bool port_tg_block_tracking = false;
1832 	thread_t self = current_thread();
1833 
1834 	if (self->thread_group == NULL ||
1835 	    (self->options & TH_OPT_IPC_TG_BLOCKED)) {
1836 		return;
1837 	}
1838 
1839 	port_tg_block_tracking = port->ip_tg_block_tracking;
1840 	if (!port_tg_block_tracking) {
1841 		return;
1842 	}
1843 
1844 	machine_thread_group_blocked(self->thread_group, NULL,
1845 	    PERFCONTROL_CALLOUT_BLOCKING_TG_RENDER_SERVER, self);
1846 
1847 	self->options |= TH_OPT_IPC_TG_BLOCKED;
1848 #endif
1849 }
1850 
1851 /*
1852  *	Routine:	ipc_port_thread_group_unblocked
1853  *	Purpose:
1854  *		Call thread_group_unblocked callout if the
1855  *		thread had previously made a thread_group_blocked
1856  *		callout before (indicated by TH_OPT_IPC_TG_BLOCKED
1857  *		flag on the thread).
1858  *
1859  *	Conditions:
1860  *		Nothing is locked.
1861  */
1862 void
ipc_port_thread_group_unblocked(void)1863 ipc_port_thread_group_unblocked(void)
1864 {
1865 #if CONFIG_THREAD_GROUPS
1866 	thread_t self = current_thread();
1867 
1868 	if (!(self->options & TH_OPT_IPC_TG_BLOCKED)) {
1869 		return;
1870 	}
1871 
1872 	machine_thread_group_unblocked(self->thread_group, NULL,
1873 	    PERFCONTROL_CALLOUT_BLOCKING_TG_RENDER_SERVER, self);
1874 
1875 	self->options &= ~TH_OPT_IPC_TG_BLOCKED;
1876 #endif
1877 }
1878 
1879 #if DEVELOPMENT || DEBUG
1880 inline void
ipc_special_reply_port_bits_reset(ipc_port_t special_reply_port)1881 ipc_special_reply_port_bits_reset(ipc_port_t special_reply_port)
1882 {
1883 	special_reply_port->ip_srp_lost_link = 0;
1884 	special_reply_port->ip_srp_msg_sent = 0;
1885 }
1886 
1887 static inline void
ipc_special_reply_port_msg_sent_reset(ipc_port_t special_reply_port)1888 ipc_special_reply_port_msg_sent_reset(ipc_port_t special_reply_port)
1889 {
1890 	if (special_reply_port->ip_specialreply == 1) {
1891 		special_reply_port->ip_srp_msg_sent = 0;
1892 	}
1893 }
1894 
1895 inline void
ipc_special_reply_port_msg_sent(ipc_port_t special_reply_port)1896 ipc_special_reply_port_msg_sent(ipc_port_t special_reply_port)
1897 {
1898 	if (special_reply_port->ip_specialreply == 1) {
1899 		special_reply_port->ip_srp_msg_sent = 1;
1900 	}
1901 }
1902 
1903 static inline void
ipc_special_reply_port_lost_link(ipc_port_t special_reply_port)1904 ipc_special_reply_port_lost_link(ipc_port_t special_reply_port)
1905 {
1906 	if (special_reply_port->ip_specialreply == 1 && special_reply_port->ip_srp_msg_sent == 0) {
1907 		special_reply_port->ip_srp_lost_link = 1;
1908 	}
1909 }
1910 
1911 #else /* DEVELOPMENT || DEBUG */
1912 inline void
ipc_special_reply_port_bits_reset(__unused ipc_port_t special_reply_port)1913 ipc_special_reply_port_bits_reset(__unused ipc_port_t special_reply_port)
1914 {
1915 	return;
1916 }
1917 
1918 static inline void
ipc_special_reply_port_msg_sent_reset(__unused ipc_port_t special_reply_port)1919 ipc_special_reply_port_msg_sent_reset(__unused ipc_port_t special_reply_port)
1920 {
1921 	return;
1922 }
1923 
1924 inline void
ipc_special_reply_port_msg_sent(__unused ipc_port_t special_reply_port)1925 ipc_special_reply_port_msg_sent(__unused ipc_port_t special_reply_port)
1926 {
1927 	return;
1928 }
1929 
1930 static inline void
ipc_special_reply_port_lost_link(__unused ipc_port_t special_reply_port)1931 ipc_special_reply_port_lost_link(__unused ipc_port_t special_reply_port)
1932 {
1933 	return;
1934 }
1935 #endif /* DEVELOPMENT || DEBUG */
1936 
1937 /*
1938  *	Routine:	ipc_port_adjust_special_reply_port_locked
1939  *	Purpose:
1940  *		If the special port has a turnstile, update its inheritor.
1941  *	Condition:
1942  *		Special reply port locked on entry.
1943  *		Special reply port unlocked on return.
1944  *		The passed in port is a special reply port.
1945  *	Returns:
1946  *		None.
1947  */
1948 void
ipc_port_adjust_special_reply_port_locked(ipc_port_t special_reply_port,struct knote * kn,uint8_t flags,boolean_t get_turnstile)1949 ipc_port_adjust_special_reply_port_locked(
1950 	ipc_port_t special_reply_port,
1951 	struct knote *kn,
1952 	uint8_t flags,
1953 	boolean_t get_turnstile)
1954 {
1955 	ipc_port_t dest_port = IPC_PORT_NULL;
1956 	int sync_link_state = PORT_SYNC_LINK_NO_LINKAGE;
1957 	turnstile_inheritor_t inheritor = TURNSTILE_INHERITOR_NULL;
1958 	struct turnstile *ts = TURNSTILE_NULL;
1959 	struct turnstile *port_stashed_turnstile = TURNSTILE_NULL;
1960 
1961 	ip_mq_lock_held(special_reply_port); // ip_sync_link_state is touched
1962 
1963 	if (!special_reply_port->ip_specialreply) {
1964 		// only mach_msg_receive_results_complete() calls this with any port
1965 		assert(get_turnstile);
1966 		goto not_special;
1967 	}
1968 
1969 	if (flags & IPC_PORT_ADJUST_SR_RECEIVED_MSG) {
1970 		ipc_special_reply_port_msg_sent_reset(special_reply_port);
1971 	}
1972 
1973 	if (flags & IPC_PORT_ADJUST_UNLINK_THREAD) {
1974 		special_reply_port->ip_messages.imq_srp_owner_thread = NULL;
1975 	}
1976 
1977 	if (flags & IPC_PORT_ADJUST_RESET_BOOSTRAP_CHECKIN) {
1978 		special_reply_port->ip_sync_bootstrap_checkin = 0;
1979 	}
1980 
1981 	/* Check if the special reply port is marked non-special */
1982 	if (special_reply_port->ip_sync_link_state == PORT_SYNC_LINK_ANY) {
1983 not_special:
1984 		if (get_turnstile) {
1985 			turnstile_complete((uintptr_t)special_reply_port,
1986 			    port_rcv_turnstile_address(special_reply_port), NULL, TURNSTILE_SYNC_IPC);
1987 		}
1988 		ip_mq_unlock(special_reply_port);
1989 		if (get_turnstile) {
1990 			turnstile_cleanup();
1991 		}
1992 		return;
1993 	}
1994 
1995 	if (flags & IPC_PORT_ADJUST_SR_LINK_WORKLOOP) {
1996 		if (ITH_KNOTE_VALID(kn, MACH_MSG_TYPE_PORT_SEND_ONCE)) {
1997 			inheritor = filt_machport_stash_port(kn, special_reply_port,
1998 			    &sync_link_state);
1999 		}
2000 	} else if (flags & IPC_PORT_ADJUST_SR_ALLOW_SYNC_LINKAGE) {
2001 		sync_link_state = PORT_SYNC_LINK_ANY;
2002 	}
2003 
2004 	/* Check if need to break linkage */
2005 	if (!get_turnstile && sync_link_state == PORT_SYNC_LINK_NO_LINKAGE &&
2006 	    special_reply_port->ip_sync_link_state == PORT_SYNC_LINK_NO_LINKAGE) {
2007 		ip_mq_unlock(special_reply_port);
2008 		return;
2009 	}
2010 
2011 	switch (special_reply_port->ip_sync_link_state) {
2012 	case PORT_SYNC_LINK_PORT:
2013 		dest_port = special_reply_port->ip_sync_inheritor_port;
2014 		special_reply_port->ip_sync_inheritor_port = IPC_PORT_NULL;
2015 		break;
2016 	case PORT_SYNC_LINK_WORKLOOP_KNOTE:
2017 		special_reply_port->ip_sync_inheritor_knote = NULL;
2018 		break;
2019 	case PORT_SYNC_LINK_WORKLOOP_STASH:
2020 		port_stashed_turnstile = special_reply_port->ip_sync_inheritor_ts;
2021 		special_reply_port->ip_sync_inheritor_ts = NULL;
2022 		break;
2023 	}
2024 
2025 	/*
2026 	 * Stash (or unstash) the server's PID in the ip_sorights field of the
2027 	 * special reply port, so that stackshot can later retrieve who the client
2028 	 * is blocked on.
2029 	 */
2030 	if (special_reply_port->ip_sync_link_state == PORT_SYNC_LINK_PORT &&
2031 	    sync_link_state == PORT_SYNC_LINK_NO_LINKAGE) {
2032 		ipc_special_reply_stash_pid_locked(special_reply_port, pid_from_task(current_task()));
2033 	} else if (special_reply_port->ip_sync_link_state == PORT_SYNC_LINK_NO_LINKAGE &&
2034 	    sync_link_state == PORT_SYNC_LINK_ANY) {
2035 		/* If we are resetting the special reply port, remove the stashed pid. */
2036 		ipc_special_reply_stash_pid_locked(special_reply_port, 0);
2037 	}
2038 
2039 	special_reply_port->ip_sync_link_state = sync_link_state;
2040 
2041 	switch (sync_link_state) {
2042 	case PORT_SYNC_LINK_WORKLOOP_KNOTE:
2043 		special_reply_port->ip_sync_inheritor_knote = kn;
2044 		break;
2045 	case PORT_SYNC_LINK_WORKLOOP_STASH:
2046 		turnstile_reference(inheritor);
2047 		special_reply_port->ip_sync_inheritor_ts = inheritor;
2048 		break;
2049 	case PORT_SYNC_LINK_NO_LINKAGE:
2050 		if (flags & IPC_PORT_ADJUST_SR_ENABLE_EVENT) {
2051 			ipc_special_reply_port_lost_link(special_reply_port);
2052 		}
2053 		break;
2054 	}
2055 
2056 	/* Get thread's turnstile donated to special reply port */
2057 	if (get_turnstile) {
2058 		turnstile_complete((uintptr_t)special_reply_port,
2059 		    port_rcv_turnstile_address(special_reply_port), NULL, TURNSTILE_SYNC_IPC);
2060 	} else {
2061 		ts = ipc_port_rcv_turnstile(special_reply_port);
2062 		if (ts) {
2063 			turnstile_reference(ts);
2064 			ipc_port_recv_update_inheritor(special_reply_port, ts,
2065 			    TURNSTILE_IMMEDIATE_UPDATE);
2066 		}
2067 	}
2068 
2069 	ip_mq_unlock(special_reply_port);
2070 
2071 	if (get_turnstile) {
2072 		turnstile_cleanup();
2073 	} else if (ts) {
2074 		/* Call turnstile cleanup after dropping the interlock */
2075 		turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_NOT_HELD);
2076 		turnstile_deallocate_safe(ts);
2077 	}
2078 
2079 	if (port_stashed_turnstile) {
2080 		turnstile_deallocate_safe(port_stashed_turnstile);
2081 	}
2082 
2083 	/* Release the ref on the dest port and its turnstile */
2084 	if (dest_port) {
2085 		ipc_port_send_turnstile_complete(dest_port);
2086 		/* release the reference on the dest port, space lock might be held */
2087 		ip_release_safe(dest_port);
2088 	}
2089 }
2090 
2091 /*
2092  *	Routine:	ipc_port_adjust_special_reply_port
2093  *	Purpose:
2094  *		If the special port has a turnstile, update its inheritor.
2095  *	Condition:
2096  *		Nothing locked.
2097  *	Returns:
2098  *		None.
2099  */
2100 void
ipc_port_adjust_special_reply_port(ipc_port_t port,uint8_t flags)2101 ipc_port_adjust_special_reply_port(
2102 	ipc_port_t port,
2103 	uint8_t flags)
2104 {
2105 	if (port->ip_specialreply) {
2106 		ip_mq_lock(port);
2107 		ipc_port_adjust_special_reply_port_locked(port, NULL, flags, FALSE);
2108 	}
2109 }
2110 
2111 /*
2112  *	Routine:	ipc_port_adjust_sync_link_state_locked
2113  *	Purpose:
2114  *		Update the sync link state of the port and the
2115  *		turnstile inheritor.
2116  *	Condition:
2117  *		Port locked on entry.
2118  *		Port locked on return.
2119  *	Returns:
2120  *              None.
2121  */
2122 void
ipc_port_adjust_sync_link_state_locked(ipc_port_t port,int sync_link_state,turnstile_inheritor_t inheritor)2123 ipc_port_adjust_sync_link_state_locked(
2124 	ipc_port_t port,
2125 	int sync_link_state,
2126 	turnstile_inheritor_t inheritor)
2127 {
2128 	switch (port->ip_sync_link_state) {
2129 	case PORT_SYNC_LINK_RCV_THREAD:
2130 		/* deallocate the thread reference for the inheritor */
2131 		thread_deallocate_safe(port->ip_messages.imq_inheritor_thread_ref);
2132 		break;
2133 	case PORT_SYNC_LINK_WORKLOOP_STASH:
2134 		/* deallocate the turnstile reference for the inheritor */
2135 		turnstile_deallocate_safe(port->ip_messages.imq_inheritor_turnstile);
2136 		break;
2137 	}
2138 
2139 	klist_init(&port->ip_klist);
2140 
2141 	switch (sync_link_state) {
2142 	case PORT_SYNC_LINK_WORKLOOP_KNOTE:
2143 		port->ip_messages.imq_inheritor_knote = inheritor;
2144 		break;
2145 	case PORT_SYNC_LINK_WORKLOOP_STASH:
2146 		/* knote can be deleted by userspace, take a reference on turnstile */
2147 		turnstile_reference(inheritor);
2148 		port->ip_messages.imq_inheritor_turnstile = inheritor;
2149 		break;
2150 	case PORT_SYNC_LINK_RCV_THREAD:
2151 		/* The thread could exit without clearing port state, take a thread ref */
2152 		thread_reference((thread_t)inheritor);
2153 		port->ip_messages.imq_inheritor_thread_ref = inheritor;
2154 		break;
2155 	default:
2156 		klist_init(&port->ip_klist);
2157 		sync_link_state = PORT_SYNC_LINK_ANY;
2158 	}
2159 
2160 	port->ip_sync_link_state = sync_link_state;
2161 }
2162 
2163 
2164 /*
2165  *	Routine:	ipc_port_adjust_port_locked
2166  *	Purpose:
2167  *		If the port has a turnstile, update its inheritor.
2168  *	Condition:
2169  *		Port locked on entry.
2170  *		Port unlocked on return.
2171  *	Returns:
2172  *		None.
2173  */
2174 void
ipc_port_adjust_port_locked(ipc_port_t port,struct knote * kn,boolean_t sync_bootstrap_checkin)2175 ipc_port_adjust_port_locked(
2176 	ipc_port_t port,
2177 	struct knote *kn,
2178 	boolean_t sync_bootstrap_checkin)
2179 {
2180 	int sync_link_state = PORT_SYNC_LINK_ANY;
2181 	turnstile_inheritor_t inheritor = TURNSTILE_INHERITOR_NULL;
2182 
2183 	ip_mq_lock_held(port); // ip_sync_link_state is touched
2184 	assert(!port->ip_specialreply);
2185 
2186 	if (kn) {
2187 		inheritor = filt_machport_stash_port(kn, port, &sync_link_state);
2188 		if (sync_link_state == PORT_SYNC_LINK_WORKLOOP_KNOTE) {
2189 			inheritor = kn;
2190 		}
2191 	} else if (sync_bootstrap_checkin) {
2192 		inheritor = current_thread();
2193 		sync_link_state = PORT_SYNC_LINK_RCV_THREAD;
2194 	}
2195 
2196 	ipc_port_adjust_sync_link_state_locked(port, sync_link_state, inheritor);
2197 	port->ip_sync_bootstrap_checkin = 0;
2198 
2199 	ipc_port_send_turnstile_recompute_push_locked(port);
2200 	/* port unlocked */
2201 }
2202 
2203 /*
2204  *	Routine:	ipc_port_clear_sync_rcv_thread_boost_locked
2205  *	Purpose:
2206  *		If the port is pushing on rcv thread, clear it.
2207  *	Condition:
2208  *		Port locked on entry
2209  *		Port unlocked on return.
2210  *	Returns:
2211  *		None.
2212  */
2213 void
ipc_port_clear_sync_rcv_thread_boost_locked(ipc_port_t port)2214 ipc_port_clear_sync_rcv_thread_boost_locked(
2215 	ipc_port_t port)
2216 {
2217 	ip_mq_lock_held(port); // ip_sync_link_state is touched
2218 
2219 	if (port->ip_sync_link_state != PORT_SYNC_LINK_RCV_THREAD) {
2220 		ip_mq_unlock(port);
2221 		return;
2222 	}
2223 
2224 	ipc_port_adjust_sync_link_state_locked(port, PORT_SYNC_LINK_ANY, NULL);
2225 
2226 	ipc_port_send_turnstile_recompute_push_locked(port);
2227 	/* port unlocked */
2228 }
2229 
2230 /*
2231  *	Routine:	ipc_port_has_prdrequest
2232  *	Purpose:
2233  *		Returns whether a port has a port-destroyed request armed
2234  *	Condition:
2235  *		Port is locked.
2236  */
2237 bool
ipc_port_has_prdrequest(ipc_port_t port)2238 ipc_port_has_prdrequest(
2239 	ipc_port_t port)
2240 {
2241 	if (port->ip_specialreply) {
2242 		return false;
2243 	}
2244 	if (port->ip_has_watchport) {
2245 		return port->ip_twe->twe_pdrequest != IP_NULL;
2246 	}
2247 	return port->ip_pdrequest != IP_NULL;
2248 }
2249 
2250 /*
2251  *	Routine:	ipc_port_add_watchport_elem_locked
2252  *	Purpose:
2253  *		Transfer the turnstile boost of watchport to task calling exec.
2254  *	Condition:
2255  *		Port locked on entry.
2256  *		Port unlocked on return.
2257  *	Returns:
2258  *		KERN_SUCESS on success.
2259  *		KERN_FAILURE otherwise.
2260  */
2261 kern_return_t
ipc_port_add_watchport_elem_locked(ipc_port_t port,struct task_watchport_elem * watchport_elem,struct task_watchport_elem ** old_elem)2262 ipc_port_add_watchport_elem_locked(
2263 	ipc_port_t                 port,
2264 	struct task_watchport_elem *watchport_elem,
2265 	struct task_watchport_elem **old_elem)
2266 {
2267 	ip_mq_lock_held(port);
2268 
2269 	/* Watchport boost only works for non-special active ports mapped in an ipc space */
2270 	if (!ip_active(port) || port->ip_specialreply || !ip_in_a_space(port)) {
2271 		ip_mq_unlock(port);
2272 		return KERN_FAILURE;
2273 	}
2274 
2275 	if (port->ip_sync_link_state != PORT_SYNC_LINK_ANY) {
2276 		/* Sever the linkage if the port was pushing on knote */
2277 		ipc_port_adjust_sync_link_state_locked(port, PORT_SYNC_LINK_ANY, NULL);
2278 	}
2279 
2280 	*old_elem = ipc_port_update_watchport_elem(port, watchport_elem);
2281 
2282 	ipc_port_send_turnstile_recompute_push_locked(port);
2283 	/* port unlocked */
2284 	return KERN_SUCCESS;
2285 }
2286 
2287 /*
2288  *	Routine:	ipc_port_clear_watchport_elem_internal_conditional_locked
2289  *	Purpose:
2290  *		Remove the turnstile boost of watchport and recompute the push.
2291  *	Condition:
2292  *		Port locked on entry.
2293  *		Port unlocked on return.
2294  *	Returns:
2295  *		KERN_SUCESS on success.
2296  *		KERN_FAILURE otherwise.
2297  */
2298 kern_return_t
ipc_port_clear_watchport_elem_internal_conditional_locked(ipc_port_t port,struct task_watchport_elem * watchport_elem)2299 ipc_port_clear_watchport_elem_internal_conditional_locked(
2300 	ipc_port_t                 port,
2301 	struct task_watchport_elem *watchport_elem)
2302 {
2303 	ip_mq_lock_held(port);
2304 
2305 	if (ipc_port_watchport_elem(port) != watchport_elem) {
2306 		ip_mq_unlock(port);
2307 		return KERN_FAILURE;
2308 	}
2309 
2310 	ipc_port_clear_watchport_elem_internal(port);
2311 	ipc_port_send_turnstile_recompute_push_locked(port);
2312 	/* port unlocked */
2313 	return KERN_SUCCESS;
2314 }
2315 
2316 /*
2317  *	Routine:	ipc_port_replace_watchport_elem_conditional_locked
2318  *	Purpose:
2319  *		Replace the turnstile boost of watchport and recompute the push.
2320  *	Condition:
2321  *		Port locked on entry.
2322  *		Port unlocked on return.
2323  *	Returns:
2324  *		KERN_SUCESS on success.
2325  *		KERN_FAILURE otherwise.
2326  */
2327 kern_return_t
ipc_port_replace_watchport_elem_conditional_locked(ipc_port_t port,struct task_watchport_elem * old_watchport_elem,struct task_watchport_elem * new_watchport_elem)2328 ipc_port_replace_watchport_elem_conditional_locked(
2329 	ipc_port_t                 port,
2330 	struct task_watchport_elem *old_watchport_elem,
2331 	struct task_watchport_elem *new_watchport_elem)
2332 {
2333 	ip_mq_lock_held(port);
2334 
2335 	if (port->ip_specialreply ||
2336 	    ipc_port_watchport_elem(port) != old_watchport_elem) {
2337 		ip_mq_unlock(port);
2338 		return KERN_FAILURE;
2339 	}
2340 
2341 	ipc_port_update_watchport_elem(port, new_watchport_elem);
2342 	ipc_port_send_turnstile_recompute_push_locked(port);
2343 	/* port unlocked */
2344 	return KERN_SUCCESS;
2345 }
2346 
2347 /*
2348  *	Routine:	ipc_port_clear_watchport_elem_internal
2349  *	Purpose:
2350  *		Remove the turnstile boost of watchport.
2351  *	Condition:
2352  *		Port locked on entry.
2353  *		Port locked on return.
2354  *	Returns:
2355  *		Old task_watchport_elem returned.
2356  */
2357 struct task_watchport_elem *
ipc_port_clear_watchport_elem_internal(ipc_port_t port)2358 ipc_port_clear_watchport_elem_internal(
2359 	ipc_port_t                 port)
2360 {
2361 	ip_mq_lock_held(port);
2362 
2363 	if (!port->ip_has_watchport) {
2364 		return NULL;
2365 	}
2366 
2367 	return ipc_port_update_watchport_elem(port, NULL);
2368 }
2369 
2370 /*
2371  *	Routine:	ipc_port_send_turnstile_recompute_push_locked
2372  *	Purpose:
2373  *		Update send turnstile inheritor of port and recompute the push.
2374  *	Condition:
2375  *		Port locked on entry.
2376  *		Port unlocked on return.
2377  *	Returns:
2378  *		None.
2379  */
2380 static void
ipc_port_send_turnstile_recompute_push_locked(ipc_port_t port)2381 ipc_port_send_turnstile_recompute_push_locked(
2382 	ipc_port_t port)
2383 {
2384 	struct turnstile *send_turnstile = port_send_turnstile(port);
2385 	if (send_turnstile) {
2386 		turnstile_reference(send_turnstile);
2387 		ipc_port_send_update_inheritor(port, send_turnstile,
2388 		    TURNSTILE_IMMEDIATE_UPDATE);
2389 	}
2390 	ip_mq_unlock(port);
2391 
2392 	if (send_turnstile) {
2393 		turnstile_update_inheritor_complete(send_turnstile,
2394 		    TURNSTILE_INTERLOCK_NOT_HELD);
2395 		turnstile_deallocate_safe(send_turnstile);
2396 	}
2397 }
2398 
2399 /*
2400  *	Routine:	ipc_port_get_watchport_inheritor
2401  *	Purpose:
2402  *		Returns inheritor for watchport.
2403  *
2404  *	Conditions:
2405  *		mqueue locked.
2406  *	Returns:
2407  *		watchport inheritor.
2408  */
2409 static thread_t
ipc_port_get_watchport_inheritor(ipc_port_t port)2410 ipc_port_get_watchport_inheritor(
2411 	ipc_port_t port)
2412 {
2413 	ip_mq_lock_held(port);
2414 	return ipc_port_watchport_elem(port)->twe_task->watchports->tw_thread;
2415 }
2416 
2417 /*
2418  *	Routine:	ipc_port_get_receiver_task
2419  *	Purpose:
2420  *		Returns receiver task pointer and its pid (if any) for port.
2421  *
2422  *	Conditions:
2423  *		Assumes the port is locked.
2424  */
2425 pid_t
ipc_port_get_receiver_task_locked(ipc_port_t port,uintptr_t * task)2426 ipc_port_get_receiver_task_locked(ipc_port_t port, uintptr_t *task)
2427 {
2428 	task_t receiver = TASK_NULL;
2429 	pid_t pid = -1;
2430 
2431 	if (!port) {
2432 		goto out;
2433 	}
2434 
2435 	if (ip_in_a_space(port) &&
2436 	    !ip_in_space(port, ipc_space_kernel) &&
2437 	    !ip_in_space(port, ipc_space_reply)) {
2438 		receiver = port->ip_receiver->is_task;
2439 		pid = task_pid(receiver);
2440 	}
2441 
2442 out:
2443 	if (task) {
2444 		*task = (uintptr_t)receiver;
2445 	}
2446 	return pid;
2447 }
2448 
2449 /*
2450  *	Routine:	ipc_port_get_receiver_task
2451  *	Purpose:
2452  *		Returns receiver task pointer and its pid (if any) for port.
2453  *
2454  *	Conditions:
2455  *		Nothing locked. The routine takes port lock.
2456  */
2457 pid_t
ipc_port_get_receiver_task(ipc_port_t port,uintptr_t * task)2458 ipc_port_get_receiver_task(ipc_port_t port, uintptr_t *task)
2459 {
2460 	pid_t pid = -1;
2461 
2462 	if (!port) {
2463 		if (task) {
2464 			*task = (uintptr_t)TASK_NULL;
2465 		}
2466 		return pid;
2467 	}
2468 
2469 	ip_mq_lock(port);
2470 	pid = ipc_port_get_receiver_task_locked(port, task);
2471 	ip_mq_unlock(port);
2472 
2473 	return pid;
2474 }
2475 
2476 /*
2477  *	Routine:	ipc_port_impcount_delta
2478  *	Purpose:
2479  *		Adjust only the importance count associated with a port.
2480  *		If there are any adjustments to be made to receiver task,
2481  *		those are handled elsewhere.
2482  *
2483  *		For now, be defensive during deductions to make sure the
2484  *		impcount for the port doesn't underflow zero.  This will
2485  *		go away when the port boost addition is made atomic (see
2486  *		note in ipc_port_importance_delta()).
2487  *	Conditions:
2488  *		The port is referenced and locked.
2489  *		Nothing else is locked.
2490  */
2491 mach_port_delta_t
ipc_port_impcount_delta(ipc_port_t port,mach_port_delta_t delta,ipc_port_t __unused base)2492 ipc_port_impcount_delta(
2493 	ipc_port_t        port,
2494 	mach_port_delta_t delta,
2495 	ipc_port_t        __unused base)
2496 {
2497 	mach_port_delta_t absdelta;
2498 
2499 	if (!ip_active(port)) {
2500 		return 0;
2501 	}
2502 
2503 	/* adding/doing nothing is easy */
2504 	if (delta >= 0) {
2505 		port->ip_impcount += delta;
2506 		return delta;
2507 	}
2508 
2509 	absdelta = 0 - delta;
2510 	if (port->ip_impcount >= absdelta) {
2511 		port->ip_impcount -= absdelta;
2512 		return delta;
2513 	}
2514 
2515 #if (DEVELOPMENT || DEBUG)
2516 	if (ip_in_a_space(port)) {
2517 		task_t target_task = port->ip_receiver->is_task;
2518 		ipc_importance_task_t target_imp = target_task->task_imp_base;
2519 		const char *target_procname;
2520 		int target_pid;
2521 
2522 		if (target_imp != IIT_NULL) {
2523 			target_procname = target_imp->iit_procname;
2524 			target_pid = target_imp->iit_bsd_pid;
2525 		} else {
2526 			target_procname = "unknown";
2527 			target_pid = -1;
2528 		}
2529 		printf("Over-release of importance assertions for port 0x%x receiver pid %d (%s), "
2530 		    "dropping %d assertion(s) but port only has %d remaining.\n",
2531 		    ip_get_receiver_name(port),
2532 		    target_pid, target_procname,
2533 		    absdelta, port->ip_impcount);
2534 	} else if (base != IP_NULL) {
2535 		assert(ip_in_a_space(base));
2536 		task_t target_task = base->ip_receiver->is_task;
2537 		ipc_importance_task_t target_imp = target_task->task_imp_base;
2538 		const char *target_procname;
2539 		int target_pid;
2540 
2541 		if (target_imp != IIT_NULL) {
2542 			target_procname = target_imp->iit_procname;
2543 			target_pid = target_imp->iit_bsd_pid;
2544 		} else {
2545 			target_procname = "unknown";
2546 			target_pid = -1;
2547 		}
2548 		printf("Over-release of importance assertions for port 0x%lx "
2549 		    "enqueued on port 0x%x with receiver pid %d (%s), "
2550 		    "dropping %d assertion(s) but port only has %d remaining.\n",
2551 		    (unsigned long)VM_KERNEL_UNSLIDE_OR_PERM((uintptr_t)port),
2552 		    ip_get_receiver_name(base),
2553 		    target_pid, target_procname,
2554 		    absdelta, port->ip_impcount);
2555 	}
2556 #endif
2557 
2558 	delta = 0 - port->ip_impcount;
2559 	port->ip_impcount = 0;
2560 	return delta;
2561 }
2562 
2563 /*
2564  *	Routine:	ipc_port_importance_delta_internal
2565  *	Purpose:
2566  *		Adjust the importance count through the given port.
2567  *		If the port is in transit, apply the delta throughout
2568  *		the chain. Determine if the there is a task at the
2569  *		base of the chain that wants/needs to be adjusted,
2570  *		and if so, apply the delta.
2571  *	Conditions:
2572  *		The port is referenced and locked on entry.
2573  *		Importance may be locked.
2574  *		Nothing else is locked.
2575  *		The lock may be dropped on exit.
2576  *		Returns TRUE if lock was dropped.
2577  */
2578 #if IMPORTANCE_INHERITANCE
2579 
2580 boolean_t
ipc_port_importance_delta_internal(ipc_port_t port,natural_t options,mach_port_delta_t * deltap,ipc_importance_task_t * imp_task)2581 ipc_port_importance_delta_internal(
2582 	ipc_port_t              port,
2583 	natural_t               options,
2584 	mach_port_delta_t       *deltap,
2585 	ipc_importance_task_t   *imp_task)
2586 {
2587 	ipc_port_t next, base;
2588 	bool dropped = false;
2589 	bool took_base_ref = false;
2590 
2591 	*imp_task = IIT_NULL;
2592 
2593 	if (*deltap == 0) {
2594 		return FALSE;
2595 	}
2596 
2597 	assert(options == IPID_OPTION_NORMAL || options == IPID_OPTION_SENDPOSSIBLE);
2598 
2599 	base = port;
2600 
2601 	/* if port is in transit, have to search for end of chain */
2602 	if (ip_in_transit(port)) {
2603 		dropped = true;
2604 
2605 
2606 		ip_mq_unlock(port);
2607 		ipc_port_multiple_lock(); /* massive serialization */
2608 
2609 		took_base_ref = ipc_port_destination_chain_lock(port, &base);
2610 		/* all ports in chain from port to base, inclusive, are locked */
2611 
2612 		ipc_port_multiple_unlock();
2613 	}
2614 
2615 	/*
2616 	 * If the port lock is dropped b/c the port is in transit, there is a
2617 	 * race window where another thread can drain messages and/or fire a
2618 	 * send possible notification before we get here.
2619 	 *
2620 	 * We solve this race by checking to see if our caller armed the send
2621 	 * possible notification, whether or not it's been fired yet, and
2622 	 * whether or not we've already set the port's ip_spimportant bit. If
2623 	 * we don't need a send-possible boost, then we'll just apply a
2624 	 * harmless 0-boost to the port.
2625 	 */
2626 	if (options & IPID_OPTION_SENDPOSSIBLE) {
2627 		assert(*deltap == 1);
2628 		if (port->ip_sprequests && port->ip_spimportant == 0) {
2629 			port->ip_spimportant = 1;
2630 		} else {
2631 			*deltap = 0;
2632 		}
2633 	}
2634 
2635 	/* unlock down to the base, adjusting boost(s) at each level */
2636 	for (;;) {
2637 		*deltap = ipc_port_impcount_delta(port, *deltap, base);
2638 
2639 		if (port == base) {
2640 			break;
2641 		}
2642 
2643 		/* port is in transit */
2644 		assert(port->ip_tempowner == 0);
2645 		assert(ip_in_transit(port));
2646 		next = ip_get_destination(port);
2647 		ip_mq_unlock(port);
2648 		port = next;
2649 	}
2650 
2651 	/* find the task (if any) to boost according to the base */
2652 	if (ip_active(base)) {
2653 		if (base->ip_tempowner != 0) {
2654 			if (IIT_NULL != ip_get_imp_task(base)) {
2655 				*imp_task = ip_get_imp_task(base);
2656 			}
2657 			/* otherwise don't boost */
2658 		} else if (ip_in_a_space(base)) {
2659 			ipc_space_t space = ip_get_receiver(base);
2660 
2661 			/* only spaces with boost-accepting tasks */
2662 			if (space->is_task != TASK_NULL &&
2663 			    ipc_importance_task_is_any_receiver_type(space->is_task->task_imp_base)) {
2664 				*imp_task = space->is_task->task_imp_base;
2665 			}
2666 		}
2667 	}
2668 
2669 	/*
2670 	 * Only the base is locked.  If we have to hold or drop task
2671 	 * importance assertions, we'll have to drop that lock as well.
2672 	 */
2673 	if (*imp_task != IIT_NULL) {
2674 		/* take a reference before unlocking base */
2675 		ipc_importance_task_reference(*imp_task);
2676 	}
2677 
2678 	if (dropped) {
2679 		ip_mq_unlock(base);
2680 		if (took_base_ref) {
2681 			/* importance lock might be held */
2682 			ip_release_safe(base);
2683 		}
2684 	}
2685 
2686 	return dropped;
2687 }
2688 #endif /* IMPORTANCE_INHERITANCE */
2689 
2690 /*
2691  *	Routine:	ipc_port_importance_delta
2692  *	Purpose:
2693  *		Adjust the importance count through the given port.
2694  *		If the port is in transit, apply the delta throughout
2695  *		the chain.
2696  *
2697  *		If there is a task at the base of the chain that wants/needs
2698  *		to be adjusted, apply the delta.
2699  *	Conditions:
2700  *		The port is referenced and locked on entry.
2701  *		Nothing else is locked.
2702  *		The lock may be dropped on exit.
2703  *		Returns TRUE if lock was dropped.
2704  */
2705 #if IMPORTANCE_INHERITANCE
2706 
2707 boolean_t
ipc_port_importance_delta(ipc_port_t port,natural_t options,mach_port_delta_t delta)2708 ipc_port_importance_delta(
2709 	ipc_port_t              port,
2710 	natural_t               options,
2711 	mach_port_delta_t       delta)
2712 {
2713 	ipc_importance_task_t imp_task = IIT_NULL;
2714 	boolean_t dropped;
2715 
2716 	dropped = ipc_port_importance_delta_internal(port, options, &delta, &imp_task);
2717 
2718 	if (IIT_NULL == imp_task || delta == 0) {
2719 		return dropped;
2720 	}
2721 
2722 	if (!dropped) {
2723 		ip_mq_unlock(port);
2724 	}
2725 
2726 	assert(ipc_importance_task_is_any_receiver_type(imp_task));
2727 
2728 	if (delta > 0) {
2729 		ipc_importance_task_hold_internal_assertion(imp_task, delta);
2730 	} else {
2731 		ipc_importance_task_drop_internal_assertion(imp_task, -delta);
2732 	}
2733 
2734 	ipc_importance_task_release(imp_task);
2735 	return TRUE;
2736 }
2737 #endif /* IMPORTANCE_INHERITANCE */
2738 
2739 ipc_port_t
ipc_port_make_send_any_locked(ipc_port_t port)2740 ipc_port_make_send_any_locked(
2741 	ipc_port_t      port)
2742 {
2743 	require_ip_active(port);
2744 	port->ip_mscount++;
2745 	ip_srights_inc(port);
2746 	ip_reference(port);
2747 	return port;
2748 }
2749 
2750 ipc_port_t
ipc_port_make_send_any(ipc_port_t port)2751 ipc_port_make_send_any(
2752 	ipc_port_t      port)
2753 {
2754 	ipc_port_t sright = port;
2755 
2756 	if (IP_VALID(port)) {
2757 		ip_mq_lock(port);
2758 		if (ip_active(port)) {
2759 			ipc_port_make_send_any_locked(port);
2760 		} else {
2761 			sright = IP_DEAD;
2762 		}
2763 		ip_mq_unlock(port);
2764 	}
2765 
2766 	return sright;
2767 }
2768 
2769 ipc_port_t
ipc_port_make_send_mqueue(ipc_port_t port)2770 ipc_port_make_send_mqueue(
2771 	ipc_port_t      port)
2772 {
2773 	ipc_port_t sright = port;
2774 	ipc_kobject_type_t kotype;
2775 
2776 	if (IP_VALID(port)) {
2777 		kotype = ip_kotype(port);
2778 
2779 		ip_mq_lock(port);
2780 		if (__improbable(!ip_active(port))) {
2781 			sright = IP_DEAD;
2782 		} else if (kotype == IKOT_NONE) {
2783 			ipc_port_make_send_any_locked(port);
2784 		} else if (kotype == IKOT_TIMER) {
2785 			ipc_kobject_mktimer_require_locked(port);
2786 			ipc_port_make_send_any_locked(port);
2787 		} else {
2788 			sright = IP_NULL;
2789 		}
2790 		ip_mq_unlock(port);
2791 	}
2792 
2793 	return sright;
2794 }
2795 
2796 void
ipc_port_copy_send_any_locked(ipc_port_t port)2797 ipc_port_copy_send_any_locked(
2798 	ipc_port_t      port)
2799 {
2800 	assert(port->ip_srights > 0);
2801 	ip_srights_inc(port);
2802 	ip_reference(port);
2803 }
2804 
2805 ipc_port_t
ipc_port_copy_send_any(ipc_port_t port)2806 ipc_port_copy_send_any(
2807 	ipc_port_t      port)
2808 {
2809 	ipc_port_t sright = port;
2810 
2811 	if (IP_VALID(port)) {
2812 		ip_mq_lock(port);
2813 		if (ip_active(port)) {
2814 			ipc_port_copy_send_any_locked(port);
2815 		} else {
2816 			sright = IP_DEAD;
2817 		}
2818 		ip_mq_unlock(port);
2819 	}
2820 
2821 	return sright;
2822 }
2823 
2824 ipc_port_t
ipc_port_copy_send_mqueue(ipc_port_t port)2825 ipc_port_copy_send_mqueue(
2826 	ipc_port_t      port)
2827 {
2828 	ipc_port_t sright = port;
2829 	ipc_kobject_type_t kotype;
2830 
2831 	if (IP_VALID(port)) {
2832 		kotype = ip_kotype(port);
2833 
2834 		ip_mq_lock(port);
2835 		if (__improbable(!ip_active(port))) {
2836 			sright = IP_DEAD;
2837 		} else if (kotype == IKOT_NONE) {
2838 			ipc_port_copy_send_any_locked(port);
2839 		} else if (kotype == IKOT_TIMER) {
2840 			ipc_kobject_mktimer_require_locked(port);
2841 			ipc_port_copy_send_any_locked(port);
2842 		} else {
2843 			sright = IP_NULL;
2844 		}
2845 		ip_mq_unlock(port);
2846 	}
2847 
2848 	return sright;
2849 }
2850 
2851 /*
2852  *	Routine:	ipc_port_copyout_send
2853  *	Purpose:
2854  *		Copyout a naked send right (possibly null/dead),
2855  *		or if that fails, destroy the right.
2856  *	Conditions:
2857  *		Nothing locked.
2858  */
2859 
2860 static mach_port_name_t
ipc_port_copyout_send_internal(ipc_port_t sright,ipc_space_t space,ipc_object_copyout_flags_t flags)2861 ipc_port_copyout_send_internal(
2862 	ipc_port_t      sright,
2863 	ipc_space_t     space,
2864 	ipc_object_copyout_flags_t flags)
2865 {
2866 	mach_port_name_t name;
2867 
2868 	if (IP_VALID(sright)) {
2869 		kern_return_t kr;
2870 
2871 		kr = ipc_object_copyout(space, ip_to_object(sright),
2872 		    MACH_MSG_TYPE_PORT_SEND, flags, NULL, NULL, &name);
2873 		if (kr != KERN_SUCCESS) {
2874 			if (kr == KERN_INVALID_CAPABILITY) {
2875 				name = MACH_PORT_DEAD;
2876 			} else {
2877 				name = MACH_PORT_NULL;
2878 			}
2879 		}
2880 	} else {
2881 		name = CAST_MACH_PORT_TO_NAME(sright);
2882 	}
2883 
2884 	return name;
2885 }
2886 
2887 mach_port_name_t
ipc_port_copyout_send(ipc_port_t sright,ipc_space_t space)2888 ipc_port_copyout_send(
2889 	ipc_port_t      sright, /* can be invalid */
2890 	ipc_space_t     space)
2891 {
2892 	return ipc_port_copyout_send_internal(sright, space, IPC_OBJECT_COPYOUT_FLAGS_NONE);
2893 }
2894 
2895 /* Used by pthread kext to copyout thread port only */
2896 mach_port_name_t
ipc_port_copyout_send_pinned(ipc_port_t sright,ipc_space_t space)2897 ipc_port_copyout_send_pinned(
2898 	ipc_port_t      sright, /* can be invalid */
2899 	ipc_space_t     space)
2900 {
2901 	assert(space->is_task != TASK_NULL);
2902 
2903 	if (IP_VALID(sright)) {
2904 		assert(ip_kotype(sright) == IKOT_THREAD_CONTROL);
2905 	}
2906 
2907 	if (task_is_pinned(space->is_task)) {
2908 		return ipc_port_copyout_send_internal(sright, space, IPC_OBJECT_COPYOUT_FLAGS_PINNED);
2909 	} else {
2910 		return ipc_port_copyout_send_internal(sright, space, IPC_OBJECT_COPYOUT_FLAGS_NONE);
2911 	}
2912 }
2913 
2914 /*
2915  *	Routine:	ipc_port_release_send_and_unlock
2916  *	Purpose:
2917  *		Release a naked send right.
2918  *		Consumes a ref for the port.
2919  *	Conditions:
2920  *		Port is valid and locked on entry
2921  *		Port is unlocked on exit.
2922  */
2923 void
ipc_port_release_send_and_unlock(ipc_port_t port)2924 ipc_port_release_send_and_unlock(
2925 	ipc_port_t      port)
2926 {
2927 	ipc_notify_nsenders_t nsrequest = { };
2928 
2929 	ip_srights_dec(port);
2930 
2931 	if (ip_active(port) && port->ip_srights == 0) {
2932 		nsrequest = ipc_notify_no_senders_prepare(port);
2933 	}
2934 
2935 	ip_mq_unlock(port);
2936 	ip_release(port);
2937 
2938 	ipc_notify_no_senders_emit(nsrequest);
2939 }
2940 
2941 /*
2942  *	Routine:	ipc_port_release_send
2943  *	Purpose:
2944  *		Release a naked send right.
2945  *		Consumes a ref for the port.
2946  *	Conditions:
2947  *		Nothing locked.
2948  */
2949 
2950 __attribute__((flatten, noinline))
2951 void
ipc_port_release_send(ipc_port_t port)2952 ipc_port_release_send(
2953 	ipc_port_t      port)
2954 {
2955 	if (IP_VALID(port)) {
2956 		ip_mq_lock(port);
2957 		ipc_port_release_send_and_unlock(port);
2958 	}
2959 }
2960 
2961 /*
2962  *	Routine:	ipc_port_make_sonce_locked
2963  *	Purpose:
2964  *		Make a naked send-once right from a receive right.
2965  *	Conditions:
2966  *		The port is locked and active.
2967  */
2968 
2969 ipc_port_t
ipc_port_make_sonce_locked(ipc_port_t port)2970 ipc_port_make_sonce_locked(
2971 	ipc_port_t      port)
2972 {
2973 	require_ip_active(port);
2974 	ip_sorights_inc(port);
2975 	ip_reference(port);
2976 	return port;
2977 }
2978 
2979 /*
2980  *	Routine:	ipc_port_make_sonce
2981  *	Purpose:
2982  *		Make a naked send-once right from a receive right.
2983  *	Conditions:
2984  *		The port is not locked.
2985  */
2986 
2987 ipc_port_t
ipc_port_make_sonce(ipc_port_t port)2988 ipc_port_make_sonce(
2989 	ipc_port_t      port)
2990 {
2991 	if (!IP_VALID(port)) {
2992 		return port;
2993 	}
2994 
2995 	ip_mq_lock(port);
2996 	if (ip_active(port)) {
2997 		ipc_port_make_sonce_locked(port);
2998 		ip_mq_unlock(port);
2999 		return port;
3000 	}
3001 	ip_mq_unlock(port);
3002 	return IP_DEAD;
3003 }
3004 
3005 /*
3006  *	Routine:	ipc_port_release_sonce
3007  *	Purpose:
3008  *		Release a naked send-once right.
3009  *		Consumes a ref for the port.
3010  *
3011  *		In normal situations, this is never used.
3012  *		Send-once rights are only consumed when
3013  *		a message (possibly a send-once notification)
3014  *		is sent to them.
3015  *	Conditions:
3016  *		The port is locked, possibly a space too.
3017  */
3018 void
ipc_port_release_sonce_and_unlock(ipc_port_t port)3019 ipc_port_release_sonce_and_unlock(
3020 	ipc_port_t      port)
3021 {
3022 	ip_mq_lock_held(port);
3023 
3024 	ip_sorights_dec(port);
3025 
3026 	if (port->ip_specialreply) {
3027 		ipc_port_adjust_special_reply_port_locked(port, NULL,
3028 		    IPC_PORT_ADJUST_RESET_BOOSTRAP_CHECKIN, FALSE);
3029 	} else {
3030 		ip_mq_unlock(port);
3031 	}
3032 
3033 	ip_release(port);
3034 }
3035 
3036 /*
3037  *	Routine:	ipc_port_release_sonce
3038  *	Purpose:
3039  *		Release a naked send-once right.
3040  *		Consumes a ref for the port.
3041  *
3042  *		In normal situations, this is never used.
3043  *		Send-once rights are only consumed when
3044  *		a message (possibly a send-once notification)
3045  *		is sent to them.
3046  *	Conditions:
3047  *		Nothing locked except possibly a space.
3048  */
3049 void
ipc_port_release_sonce(ipc_port_t port)3050 ipc_port_release_sonce(
3051 	ipc_port_t      port)
3052 {
3053 	if (IP_VALID(port)) {
3054 		ip_mq_lock(port);
3055 		ipc_port_release_sonce_and_unlock(port);
3056 	}
3057 }
3058 
3059 /*
3060  *	Routine:	ipc_port_release_receive
3061  *	Purpose:
3062  *		Release a naked (in limbo or in transit) receive right.
3063  *		Consumes a ref for the port; destroys the port.
3064  *	Conditions:
3065  *		Nothing locked.
3066  */
3067 
3068 void
ipc_port_release_receive(ipc_port_t port)3069 ipc_port_release_receive(
3070 	ipc_port_t      port)
3071 {
3072 	ipc_port_t dest;
3073 
3074 	if (!IP_VALID(port)) {
3075 		return;
3076 	}
3077 
3078 	ip_mq_lock(port);
3079 	require_ip_active(port);
3080 	assert(!ip_in_a_space(port));
3081 	dest = ip_get_destination(port);
3082 
3083 	ipc_port_destroy(port); /* consumes ref, unlocks */
3084 
3085 	if (dest != IP_NULL) {
3086 		ipc_port_send_turnstile_complete(dest);
3087 		ip_release(dest);
3088 	}
3089 }
3090 
3091 /*
3092  *	Routine:	ipc_port_alloc_special
3093  *	Purpose:
3094  *		Allocate a port in a special space.
3095  *		The new port is returned with one ref.
3096  *		If unsuccessful, IP_NULL is returned.
3097  *	Conditions:
3098  *		Nothing locked.
3099  */
3100 
3101 ipc_port_t
ipc_port_alloc_special(ipc_space_t space,ipc_port_init_flags_t flags)3102 ipc_port_alloc_special(
3103 	ipc_space_t             space,
3104 	ipc_port_init_flags_t   flags)
3105 {
3106 	ipc_port_t port;
3107 
3108 	port = ip_object_to_port(io_alloc(IOT_PORT, Z_WAITOK | Z_ZERO));
3109 	if (port == IP_NULL) {
3110 		return IP_NULL;
3111 	}
3112 
3113 	os_atomic_init(&port->ip_object.io_bits, io_makebits(IOT_PORT));
3114 	os_atomic_init(&port->ip_object.io_references, 1);
3115 
3116 	ipc_port_init(port, space, flags, MACH_PORT_SPECIAL_DEFAULT);
3117 	return port;
3118 }
3119 
3120 /*
3121  *	Routine:	ipc_port_dealloc_special_and_unlock
3122  *	Purpose:
3123  *		Deallocate a port in a special space.
3124  *		Consumes one ref for the port.
3125  *	Conditions:
3126  *		Port is locked.
3127  */
3128 
3129 void
ipc_port_dealloc_special_and_unlock(ipc_port_t port,__assert_only ipc_space_t space)3130 ipc_port_dealloc_special_and_unlock(
3131 	ipc_port_t                      port,
3132 	__assert_only ipc_space_t       space)
3133 {
3134 	require_ip_active(port);
3135 //	assert(port->ip_receiver_name != MACH_PORT_NULL);
3136 	assert(ip_in_space(port, space));
3137 
3138 	/*
3139 	 *	We clear ip_receiver_name and ip_receiver to simplify
3140 	 *	the ipc_space_kernel check in ipc_mqueue_send.
3141 	 */
3142 
3143 	/* port transtions to IN-LIMBO state */
3144 	port->ip_receiver_name = MACH_PORT_NULL;
3145 	port->ip_receiver = IS_NULL;
3146 
3147 	/* relevant part of ipc_port_clear_receiver */
3148 	port->ip_mscount = 0;
3149 	port->ip_messages.imq_seqno = 0;
3150 
3151 	ipc_port_destroy(port);
3152 }
3153 
3154 /*
3155  *	Routine:	ipc_port_dealloc_special
3156  *	Purpose:
3157  *		Deallocate a port in a special space.
3158  *		Consumes one ref for the port.
3159  *	Conditions:
3160  *		Nothing locked.
3161  */
3162 
3163 void
ipc_port_dealloc_special(ipc_port_t port,ipc_space_t space)3164 ipc_port_dealloc_special(
3165 	ipc_port_t        port,
3166 	ipc_space_t       space)
3167 {
3168 	ip_mq_lock(port);
3169 	ipc_port_dealloc_special_and_unlock(port, space);
3170 }
3171 
3172 /*
3173  *	Routine:	ipc_port_finalize
3174  *	Purpose:
3175  *		Called on last reference deallocate to
3176  *		free any remaining data associated with the
3177  *		port.
3178  *	Conditions:
3179  *		Nothing locked.
3180  */
3181 void
ipc_port_finalize(ipc_port_t port)3182 ipc_port_finalize(
3183 	ipc_port_t              port)
3184 {
3185 	ipc_port_request_table_t requests = port->ip_requests;
3186 
3187 	assert(port_send_turnstile(port) == TURNSTILE_NULL);
3188 
3189 	if (waitq_type(&port->ip_waitq) == WQT_PORT) {
3190 		assert(ipc_port_rcv_turnstile(port) == TURNSTILE_NULL);
3191 	}
3192 
3193 	if (ip_active(port)) {
3194 		panic("Trying to free an active port. port %p", port);
3195 	}
3196 
3197 	if (requests) {
3198 		port->ip_requests = NULL;
3199 		ipc_port_request_table_free_noclear(requests);
3200 	}
3201 
3202 	/*
3203 	 * (81997111) now it is safe to deallocate the prealloc message.
3204 	 * Keep the IP_BIT_PREALLOC bit, it has to be sticky as the turnstile
3205 	 * code looks at it without holding locks.
3206 	 */
3207 	if (IP_PREALLOC(port)) {
3208 		ipc_kmsg_t kmsg = port->ip_premsg;
3209 
3210 		if (kmsg == IKM_NULL || ikm_prealloc_inuse_port(kmsg)) {
3211 			panic("port(%p, %p): prealloc message in an invalid state",
3212 			    port, kmsg);
3213 		}
3214 
3215 		port->ip_premsg = IKM_NULL;
3216 		ipc_kmsg_free(kmsg);
3217 	}
3218 
3219 	waitq_deinit(&port->ip_waitq);
3220 #if MACH_ASSERT
3221 	if (port->ip_made_bt) {
3222 		btref_put(port->ip_made_bt);
3223 	}
3224 #endif
3225 }
3226 
3227 /*
3228  *	Routine:	kdp_mqueue_send_find_owner
3229  *	Purpose:
3230  *		Discover the owner of the ipc object that contains the input
3231  *		waitq object. The thread blocked on the waitq should be
3232  *		waiting for an IPC_MQUEUE_FULL event.
3233  *	Conditions:
3234  *		The 'waitinfo->wait_type' value should already be set to
3235  *		kThreadWaitPortSend.
3236  *	Note:
3237  *		If we find out that the containing port is actually in
3238  *		transit, we reset the wait_type field to reflect this.
3239  */
3240 void
kdp_mqueue_send_find_owner(struct waitq * waitq,__assert_only event64_t event,thread_waitinfo_v2_t * waitinfo,struct ipc_service_port_label ** isplp)3241 kdp_mqueue_send_find_owner(
3242 	struct waitq                   *waitq,
3243 	__assert_only event64_t         event,
3244 	thread_waitinfo_v2_t           *waitinfo,
3245 	struct ipc_service_port_label **isplp)
3246 {
3247 	struct turnstile *turnstile;
3248 	assert(waitinfo->wait_type == kThreadWaitPortSend);
3249 	assert(event == IPC_MQUEUE_FULL);
3250 	assert(waitq_type(waitq) == WQT_TURNSTILE);
3251 
3252 	turnstile = waitq_to_turnstile(waitq);
3253 	ipc_port_t port = (ipc_port_t)turnstile->ts_proprietor; /* we are blocking on send */
3254 
3255 	zone_id_require(ZONE_ID_IPC_PORT, sizeof(struct ipc_port), port);
3256 
3257 	waitinfo->owner = 0;
3258 	waitinfo->context  = VM_KERNEL_UNSLIDE_OR_PERM(port);
3259 	if (ip_mq_lock_held_kdp(port)) {
3260 		/*
3261 		 * someone has the port locked: it may be in an
3262 		 * inconsistent state: bail
3263 		 */
3264 		waitinfo->owner = STACKSHOT_WAITOWNER_PORT_LOCKED;
3265 		return;
3266 	}
3267 
3268 	/* now we are the only one accessing the port */
3269 	if (ip_active(port)) {
3270 		/*
3271 		 * In kdp context, port must be left unlocked throughout.
3272 		 * Therefore can't use union field accessor helpers, manually strip PAC
3273 		 * and compare raw pointer.
3274 		 */
3275 		void *raw_ptr = ip_get_receiver_ptr_noauth(port);
3276 
3277 		if (port->ip_tempowner) {
3278 			ipc_importance_task_t imp_task = ip_get_imp_task(port);
3279 			if (imp_task != IIT_NULL && imp_task->iit_task != NULL) {
3280 				/* port is held by a tempowner */
3281 				waitinfo->owner = pid_from_task(port->ip_imp_task->iit_task);
3282 			} else {
3283 				waitinfo->owner = STACKSHOT_WAITOWNER_INTRANSIT;
3284 			}
3285 		} else if (ip_in_a_space(port)) { /* no port lock needed */
3286 			if ((ipc_space_t)raw_ptr == ipc_space_kernel) { /* access union field as ip_receiver */
3287 				/*
3288 				 * The kernel pid is 0, make this
3289 				 * distinguishable from no-owner and
3290 				 * inconsistent port state.
3291 				 */
3292 				waitinfo->owner = STACKSHOT_WAITOWNER_KERNEL;
3293 			} else {
3294 				waitinfo->owner = pid_from_task(((ipc_space_t)raw_ptr)->is_task);
3295 			}
3296 		} else if ((ipc_port_t)raw_ptr != IP_NULL) { /* access union field as ip_destination */
3297 			waitinfo->wait_type = kThreadWaitPortSendInTransit;
3298 			waitinfo->owner     = VM_KERNEL_UNSLIDE_OR_PERM((ipc_port_t)raw_ptr);
3299 		}
3300 		if (port->ip_service_port && port->ip_splabel != NULL) {
3301 			*isplp = (struct ipc_service_port_label *)port->ip_splabel;
3302 		}
3303 	}
3304 }
3305 
3306 /*
3307  *	Routine:	kdp_mqueue_recv_find_owner
3308  *	Purpose:
3309  *		Discover the "owner" of the ipc object that contains the input
3310  *		waitq object. The thread blocked on the waitq is trying to
3311  *		receive on the mqueue.
3312  *	Conditions:
3313  *		The 'waitinfo->wait_type' value should already be set to
3314  *		kThreadWaitPortReceive.
3315  *	Note:
3316  *		If we find that we are actualy waiting on a port set, we reset
3317  *		the wait_type field to reflect this.
3318  */
3319 void
kdp_mqueue_recv_find_owner(struct waitq * waitq,__assert_only event64_t event,thread_waitinfo_v2_t * waitinfo,struct ipc_service_port_label ** isplp)3320 kdp_mqueue_recv_find_owner(
3321 	struct waitq                   *waitq,
3322 	__assert_only event64_t         event,
3323 	thread_waitinfo_v2_t           *waitinfo,
3324 	struct ipc_service_port_label **isplp)
3325 {
3326 	assert(waitinfo->wait_type == kThreadWaitPortReceive);
3327 	assert(event == IPC_MQUEUE_RECEIVE);
3328 
3329 	waitinfo->owner = 0;
3330 
3331 	if (waitq_type(waitq) == WQT_PORT_SET) {
3332 		ipc_pset_t set = ips_from_waitq(waitq);
3333 
3334 		zone_id_require(ZONE_ID_IPC_PORT_SET, sizeof(struct ipc_pset), set);
3335 
3336 		/* Reset wait type to specify waiting on port set receive */
3337 		waitinfo->wait_type = kThreadWaitPortSetReceive;
3338 		waitinfo->context   = VM_KERNEL_UNSLIDE_OR_PERM(set);
3339 		if (ips_mq_lock_held_kdp(set)) {
3340 			waitinfo->owner = STACKSHOT_WAITOWNER_PSET_LOCKED;
3341 		}
3342 		/* There is no specific owner "at the other end" of a port set, so leave unset. */
3343 	} else if (waitq_type(waitq) == WQT_PORT) {
3344 		ipc_port_t port = ip_from_waitq(waitq);
3345 
3346 		zone_id_require(ZONE_ID_IPC_PORT, sizeof(struct ipc_port), port);
3347 
3348 		waitinfo->context = VM_KERNEL_UNSLIDE_OR_PERM(port);
3349 		if (ip_mq_lock_held_kdp(port)) {
3350 			waitinfo->owner = STACKSHOT_WAITOWNER_PORT_LOCKED;
3351 			return;
3352 		}
3353 
3354 		if (ip_active(port)) {
3355 			if (ip_in_a_space(port)) { /* no port lock needed */
3356 				waitinfo->owner = ip_get_receiver_name(port);
3357 			} else {
3358 				waitinfo->owner = STACKSHOT_WAITOWNER_INTRANSIT;
3359 			}
3360 			if (port->ip_specialreply) {
3361 				waitinfo->wait_flags |= STACKSHOT_WAITINFO_FLAGS_SPECIALREPLY;
3362 			}
3363 			if (port->ip_splabel != NULL) {
3364 				*isplp = (struct ipc_service_port_label *)port->ip_splabel;
3365 			}
3366 		}
3367 	}
3368 }
3369 
3370 void
ipc_port_set_label(ipc_port_t port,ipc_label_t label)3371 ipc_port_set_label(
3372 	ipc_port_t              port,
3373 	ipc_label_t             label)
3374 {
3375 	ipc_kobject_label_t labelp;
3376 
3377 	assert(!ip_is_kolabeled(port));
3378 
3379 	labelp = zalloc_flags(ipc_kobject_label_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3380 	labelp->ikol_label = label;
3381 
3382 	port->ip_kolabel = labelp;
3383 	io_bits_or(ip_to_object(port), IO_BITS_KOLABEL);
3384 }
3385 
3386 kern_return_t
ipc_port_reset_thread_attr(ipc_port_t port)3387 ipc_port_reset_thread_attr(
3388 	ipc_port_t port)
3389 {
3390 	uint8_t iotier = THROTTLE_LEVEL_END;
3391 	uint8_t qos = THREAD_QOS_UNSPECIFIED;
3392 
3393 	return ipc_port_update_qos_n_iotier(port, qos, iotier);
3394 }
3395 
3396 kern_return_t
ipc_port_propagate_thread_attr(ipc_port_t port,struct thread_attr_for_ipc_propagation attr)3397 ipc_port_propagate_thread_attr(
3398 	ipc_port_t port,
3399 	struct thread_attr_for_ipc_propagation attr)
3400 {
3401 	uint8_t iotier = attr.tafip_iotier;
3402 	uint8_t qos = attr.tafip_qos;
3403 
3404 	return ipc_port_update_qos_n_iotier(port, qos, iotier);
3405 }
3406 
3407 static kern_return_t
ipc_port_update_qos_n_iotier(ipc_port_t port,uint8_t qos,uint8_t iotier)3408 ipc_port_update_qos_n_iotier(
3409 	ipc_port_t port,
3410 	uint8_t    qos,
3411 	uint8_t    iotier)
3412 {
3413 	if (port == IPC_PORT_NULL) {
3414 		return KERN_INVALID_ARGUMENT;
3415 	}
3416 
3417 	ip_mq_lock(port);
3418 
3419 	if (!ip_active(port)) {
3420 		ip_mq_unlock(port);
3421 		return KERN_TERMINATED;
3422 	}
3423 
3424 	if (port->ip_specialreply) {
3425 		ip_mq_unlock(port);
3426 		return KERN_INVALID_ARGUMENT;
3427 	}
3428 
3429 	port->ip_kernel_iotier_override = iotier;
3430 	port->ip_kernel_qos_override = qos;
3431 
3432 	if (ip_in_a_space(port) &&
3433 	    is_active(ip_get_receiver(port)) &&
3434 	    ipc_port_has_klist(port)) {
3435 		KNOTE(&port->ip_klist, 0);
3436 	}
3437 
3438 	ip_mq_unlock(port);
3439 	return KERN_SUCCESS;
3440 }
3441 
3442 /* Returns true if a rigid reply port violation should be enforced (by killing the process) */
3443 static bool
__ip_rigid_reply_port_semantics_violation(ipc_port_t reply_port,int * reply_port_semantics_violation)3444 __ip_rigid_reply_port_semantics_violation(ipc_port_t reply_port, int *reply_port_semantics_violation)
3445 {
3446 	bool hardened_runtime = csproc_hardened_runtime(current_proc());
3447 
3448 	if (proc_is_simulated(current_proc())
3449 #if CONFIG_ROSETTA
3450 	    || task_is_translated(current_task())
3451 #endif
3452 	    ) {
3453 		return FALSE;
3454 	}
3455 
3456 	if (task_get_platform_binary(current_task())) {
3457 		return TRUE;
3458 	}
3459 	if (!ip_is_provisional_reply_port(reply_port)) {
3460 		/* record telemetry for when third party fails to use a provisional reply port */
3461 		*reply_port_semantics_violation = hardened_runtime ? RRP_HARDENED_RUNTIME_VIOLATOR : RRP_3P_VIOLATOR;
3462 	}
3463 	return FALSE;
3464 }
3465 
3466 bool
ip_violates_reply_port_semantics(ipc_port_t dest_port,ipc_port_t reply_port,int * reply_port_semantics_violation)3467 ip_violates_reply_port_semantics(ipc_port_t dest_port, ipc_port_t reply_port,
3468     int *reply_port_semantics_violation)
3469 {
3470 	if (ip_require_reply_port_semantics(dest_port)
3471 	    && !ip_is_reply_port(reply_port)
3472 	    && !ip_is_provisional_reply_port(reply_port)) {
3473 		*reply_port_semantics_violation = REPLY_PORT_SEMANTICS_VIOLATOR;
3474 		return TRUE;
3475 	}
3476 	return FALSE;
3477 }
3478 
3479 /* Rigid reply port semantics don't allow for provisional reply ports */
3480 bool
ip_violates_rigid_reply_port_semantics(ipc_port_t dest_port,ipc_port_t reply_port,int * violates_3p)3481 ip_violates_rigid_reply_port_semantics(ipc_port_t dest_port, ipc_port_t reply_port, int *violates_3p)
3482 {
3483 	return ip_require_rigid_reply_port_semantics(dest_port)
3484 	       && !ip_is_reply_port(reply_port)
3485 	       && __ip_rigid_reply_port_semantics_violation(reply_port, violates_3p);
3486 }
3487 
3488 #if MACH_ASSERT
3489 #include <kern/machine.h>
3490 
3491 unsigned long   port_count = 0;
3492 unsigned long   port_count_warning = 20000;
3493 unsigned long   port_timestamp = 0;
3494 
3495 void            db_port_stack_trace(
3496 	ipc_port_t      port);
3497 void            db_ref(
3498 	int             refs);
3499 int             db_port_walk(
3500 	unsigned int    verbose,
3501 	unsigned int    display,
3502 	unsigned int    ref_search,
3503 	unsigned int    ref_target);
3504 
3505 #ifdef MACH_BSD
3506 extern int proc_pid(struct proc*);
3507 #endif /* MACH_BSD */
3508 
3509 /*
3510  *	Initialize all of the debugging state in a port.
3511  *	Insert the port into a global list of all allocated ports.
3512  */
3513 void
ipc_port_init_debug(ipc_port_t port,void * fp)3514 ipc_port_init_debug(ipc_port_t port, void *fp)
3515 {
3516 	port->ip_timetrack = port_timestamp++;
3517 
3518 	if (ipc_portbt) {
3519 		port->ip_made_bt = btref_get(fp, 0);
3520 	}
3521 
3522 #ifdef MACH_BSD
3523 	task_t task = current_task_early();
3524 	if (task != TASK_NULL) {
3525 		struct proc *proc = get_bsdtask_info(task);
3526 		if (proc) {
3527 			port->ip_made_pid = proc_pid(proc);
3528 		}
3529 	}
3530 #endif /* MACH_BSD */
3531 }
3532 
3533 #endif  /* MACH_ASSERT */
3534