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