xref: /xnu-11215/osfmk/kern/thread.c (revision 4f1223e8)
1 /*
2  * Copyright (c) 2000-2021 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,1988,1987 Carnegie Mellon University
34  * All Rights Reserved.
35  *
36  * Permission to use, copy, modify and distribute this software and its
37  * documentation is hereby granted, provided that both the copyright
38  * notice and this permission notice appear in all copies of the
39  * software, derivative works or modified versions, and any portions
40  * thereof, and that both notices appear in supporting documentation.
41  *
42  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45  *
46  * Carnegie Mellon requests users of this software to return to
47  *
48  *  Software Distribution Coordinator  or  [email protected]
49  *  School of Computer Science
50  *  Carnegie Mellon University
51  *  Pittsburgh PA 15213-3890
52  *
53  * any improvements or extensions that they make and grant Carnegie Mellon
54  * the rights to redistribute these changes.
55  */
56 /*
57  */
58 /*
59  *	File:	kern/thread.c
60  *	Author:	Avadis Tevanian, Jr., Michael Wayne Young, David Golub
61  *	Date:	1986
62  *
63  *	Thread management primitives implementation.
64  */
65 /*
66  * Copyright (c) 1993 The University of Utah and
67  * the Computer Systems Laboratory (CSL).  All rights reserved.
68  *
69  * Permission to use, copy, modify and distribute this software and its
70  * documentation is hereby granted, provided that both the copyright
71  * notice and this permission notice appear in all copies of the
72  * software, derivative works or modified versions, and any portions
73  * thereof, and that both notices appear in supporting documentation.
74  *
75  * THE UNIVERSITY OF UTAH AND CSL ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS
76  * IS" CONDITION.  THE UNIVERSITY OF UTAH AND CSL DISCLAIM ANY LIABILITY OF
77  * ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
78  *
79  * CSL requests users of this software to return to [email protected] any
80  * improvements that they make and grant CSL redistribution rights.
81  *
82  */
83 
84 #include <mach/mach_types.h>
85 #include <mach/boolean.h>
86 #include <mach/policy.h>
87 #include <mach/thread_info.h>
88 #include <mach/thread_special_ports.h>
89 #include <mach/thread_act.h>
90 #include <mach/thread_status.h>
91 #include <mach/time_value.h>
92 #include <mach/vm_param.h>
93 
94 #include <machine/thread.h>
95 #include <machine/pal_routines.h>
96 #include <machine/limits.h>
97 
98 #include <kern/kern_types.h>
99 #include <kern/kalloc.h>
100 #include <kern/cpu_data.h>
101 #include <kern/extmod_statistics.h>
102 #include <kern/ipc_mig.h>
103 #include <kern/ipc_tt.h>
104 #include <kern/mach_param.h>
105 #include <kern/machine.h>
106 #include <kern/misc_protos.h>
107 #include <kern/processor.h>
108 #include <kern/queue.h>
109 #include <kern/restartable.h>
110 #include <kern/sched.h>
111 #include <kern/sched_prim.h>
112 #include <kern/syscall_subr.h>
113 #include <kern/task.h>
114 #include <kern/thread.h>
115 #include <kern/thread_group.h>
116 #include <kern/coalition.h>
117 #include <kern/host.h>
118 #include <kern/zalloc.h>
119 #include <kern/assert.h>
120 #include <kern/exc_resource.h>
121 #include <kern/exc_guard.h>
122 #include <kern/telemetry.h>
123 #include <kern/policy_internal.h>
124 #include <kern/turnstile.h>
125 #include <kern/sched_clutch.h>
126 #include <kern/recount.h>
127 #include <kern/smr.h>
128 #include <kern/ast.h>
129 #include <kern/compact_id.h>
130 
131 #include <corpses/task_corpse.h>
132 #include <kern/kpc.h>
133 
134 #if CONFIG_PERVASIVE_CPI
135 #include <kern/monotonic.h>
136 #include <machine/monotonic.h>
137 #endif /* CONFIG_PERVASIVE_CPI */
138 
139 #include <ipc/ipc_kmsg.h>
140 #include <ipc/ipc_port.h>
141 #include <bank/bank_types.h>
142 
143 #include <vm/vm_kern_xnu.h>
144 #include <vm/vm_pageout_xnu.h>
145 
146 #include <sys/kdebug.h>
147 #include <sys/bsdtask_info.h>
148 #include <mach/sdt.h>
149 #include <san/kasan.h>
150 #include <san/kcov_stksz.h>
151 
152 #include <stdatomic.h>
153 
154 #if defined(HAS_APPLE_PAC)
155 #include <ptrauth.h>
156 #include <arm64/proc_reg.h>
157 #endif /* defined(HAS_APPLE_PAC) */
158 
159 /*
160  * Exported interfaces
161  */
162 #include <mach/task_server.h>
163 #include <mach/thread_act_server.h>
164 #include <mach/mach_host_server.h>
165 #include <mach/host_priv_server.h>
166 #include <mach/mach_voucher_server.h>
167 #include <kern/policy_internal.h>
168 
169 #if CONFIG_MACF
170 #include <security/mac_mach_internal.h>
171 #endif
172 
173 #include <pthread/workqueue_trace.h>
174 
175 #if CONFIG_EXCLAVES
176 #include <mach/exclaves.h>
177 #endif
178 
179 LCK_GRP_DECLARE(thread_lck_grp, "thread");
180 
181 static SECURITY_READ_ONLY_LATE(zone_t) thread_zone;
182 ZONE_DEFINE_ID(ZONE_ID_THREAD_RO, "threads_ro", struct thread_ro, ZC_READONLY);
183 
184 static void thread_port_with_flavor_no_senders(ipc_port_t, mach_port_mscount_t);
185 
186 IPC_KOBJECT_DEFINE(IKOT_THREAD_CONTROL);
187 IPC_KOBJECT_DEFINE(IKOT_THREAD_READ,
188     .iko_op_no_senders = thread_port_with_flavor_no_senders);
189 IPC_KOBJECT_DEFINE(IKOT_THREAD_INSPECT,
190     .iko_op_no_senders = thread_port_with_flavor_no_senders);
191 
192 static struct mpsc_daemon_queue thread_stack_queue;
193 static struct mpsc_daemon_queue thread_terminate_queue;
194 static struct mpsc_daemon_queue thread_deallocate_queue;
195 static struct mpsc_daemon_queue thread_exception_queue;
196 static struct mpsc_daemon_queue thread_backtrace_queue;
197 
198 decl_simple_lock_data(static, crashed_threads_lock);
199 static queue_head_t             crashed_threads_queue;
200 
201 struct thread_exception_elt {
202 	struct mpsc_queue_chain link;
203 	exception_type_t        exception_type;
204 	task_t                  exception_task;
205 	thread_t                exception_thread;
206 };
207 
208 struct thread_backtrace_elt {
209 	struct mpsc_queue_chain link;
210 	exception_type_t        exception_type;
211 	kcdata_object_t         obj;
212 	exception_port_t        exc_ports[BT_EXC_PORTS_COUNT]; /* send rights */
213 };
214 
215 static SECURITY_READ_ONLY_LATE(struct thread) thread_template = {
216 #if MACH_ASSERT
217 	.thread_magic               = THREAD_MAGIC,
218 #endif /* MACH_ASSERT */
219 	.wait_result                = THREAD_WAITING,
220 	.options                    = THREAD_ABORTSAFE,
221 	.state                      = TH_WAIT | TH_UNINT,
222 	.th_sched_bucket            = TH_BUCKET_RUN,
223 	.base_pri                   = BASEPRI_DEFAULT,
224 	.realtime.deadline          = UINT64_MAX,
225 	.last_made_runnable_time    = THREAD_NOT_RUNNABLE,
226 	.last_basepri_change_time   = THREAD_NOT_RUNNABLE,
227 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
228 	.pri_shift                  = INT8_MAX,
229 #endif
230 	/* timers are initialized in thread_bootstrap */
231 };
232 
233 #define CTID_SIZE_BIT           20
234 #define CTID_MASK               ((1u << CTID_SIZE_BIT) - 1)
235 #define CTID_MAX_THREAD_NUMBER  (CTID_MASK - 1)
236 static_assert(CTID_MAX_THREAD_NUMBER <= COMPACT_ID_MAX);
237 
238 #ifndef __LITTLE_ENDIAN__
239 #error "ctid relies on the ls bits of uint32_t to be populated"
240 #endif
241 
242 __startup_data
243 static struct thread init_thread;
244 static SECURITY_READ_ONLY_LATE(uint32_t) ctid_nonce;
245 COMPACT_ID_TABLE_DEFINE(static, ctid_table);
246 
247 __startup_func
248 static void
thread_zone_startup(void)249 thread_zone_startup(void)
250 {
251 	size_t size = sizeof(struct thread);
252 
253 #ifdef MACH_BSD
254 	size += roundup(uthread_size, _Alignof(struct thread));
255 #endif
256 	thread_zone = zone_create_ext("threads", size,
257 	    ZC_SEQUESTER | ZC_ZFREE_CLEARMEM, ZONE_ID_THREAD, NULL);
258 }
259 STARTUP(ZALLOC, STARTUP_RANK_FOURTH, thread_zone_startup);
260 
261 static void thread_deallocate_enqueue(thread_t thread);
262 static void thread_deallocate_complete(thread_t thread);
263 
264 static void ctid_table_remove(thread_t thread);
265 static void ctid_table_add(thread_t thread);
266 static void ctid_table_init(void);
267 
268 #ifdef MACH_BSD
269 extern void proc_exit(void *);
270 extern mach_exception_data_type_t proc_encode_exit_exception_code(void *);
271 extern uint64_t get_dispatchqueue_offset_from_proc(void *);
272 extern uint64_t get_return_to_kernel_offset_from_proc(void *p);
273 extern uint64_t get_wq_quantum_offset_from_proc(void *);
274 extern int      proc_selfpid(void);
275 extern void     proc_name(int, char*, int);
276 extern char *   proc_name_address(void *p);
277 exception_type_t get_exception_from_corpse_crashinfo(kcdata_descriptor_t corpse_info);
278 extern void kdebug_proc_name_args(struct proc *proc, long args[static 4]);
279 #endif /* MACH_BSD */
280 
281 extern bool bsdthread_part_of_cooperative_workqueue(struct uthread *uth);
282 extern bool disable_exc_resource;
283 extern bool disable_exc_resource_during_audio;
284 extern int audio_active;
285 extern int debug_task;
286 int thread_max = CONFIG_THREAD_MAX;     /* Max number of threads */
287 int task_threadmax = CONFIG_THREAD_MAX;
288 
289 static uint64_t         thread_unique_id = 100;
290 
291 struct _thread_ledger_indices thread_ledgers = { .cpu_time = -1 };
292 static ledger_template_t thread_ledger_template = NULL;
293 static void init_thread_ledgers(void);
294 
295 #if CONFIG_JETSAM
296 void jetsam_on_ledger_cpulimit_exceeded(void);
297 #endif
298 
299 extern int task_thread_soft_limit;
300 
301 
302 /*
303  * Level (in terms of percentage of the limit) at which the CPU usage monitor triggers telemetry.
304  *
305  * (ie when any thread's CPU consumption exceeds 70% of the limit, start taking user
306  *  stacktraces, aka micro-stackshots)
307  */
308 #define CPUMON_USTACKSHOTS_TRIGGER_DEFAULT_PCT 70
309 
310 /* Percentage. Level at which we start gathering telemetry. */
311 static TUNABLE(uint8_t, cpumon_ustackshots_trigger_pct,
312     "cpumon_ustackshots_trigger_pct", CPUMON_USTACKSHOTS_TRIGGER_DEFAULT_PCT);
313 void __attribute__((noinline)) SENDING_NOTIFICATION__THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU(void);
314 
315 #if DEVELOPMENT || DEBUG
316 TUNABLE_WRITEABLE(int, exc_resource_threads_enabled, "exc_resource_threads_enabled", 1);
317 
318 void __attribute__((noinline)) SENDING_NOTIFICATION__TASK_HAS_TOO_MANY_THREADS(task_t, int);
319 #endif /* DEVELOPMENT || DEBUG */
320 
321 /*
322  * The smallest interval over which we support limiting CPU consumption is 1ms
323  */
324 #define MINIMUM_CPULIMIT_INTERVAL_MS 1
325 
326 os_refgrp_decl(static, thread_refgrp, "thread", NULL);
327 
328 static inline void
init_thread_from_template(thread_t thread)329 init_thread_from_template(thread_t thread)
330 {
331 	/*
332 	 * In general, struct thread isn't trivially-copyable, since it may
333 	 * contain pointers to thread-specific state.  This may be enforced at
334 	 * compile time on architectures that store authed + diversified
335 	 * pointers in machine_thread.
336 	 *
337 	 * In this specific case, where we're initializing a new thread from a
338 	 * thread_template, we know all diversified pointers are NULL; these are
339 	 * safe to bitwise copy.
340 	 */
341 #pragma clang diagnostic push
342 #pragma clang diagnostic ignored "-Wnontrivial-memaccess"
343 	memcpy(thread, &thread_template, sizeof(*thread));
344 #pragma clang diagnostic pop
345 }
346 
347 static void
thread_ro_create(task_t parent_task,thread_t th,thread_ro_t tro_tpl)348 thread_ro_create(task_t parent_task, thread_t th, thread_ro_t tro_tpl)
349 {
350 #if __x86_64__
351 	th->t_task = parent_task;
352 #endif
353 	tro_tpl->tro_owner = th;
354 	tro_tpl->tro_task  = parent_task;
355 	th->t_tro = zalloc_ro(ZONE_ID_THREAD_RO, Z_WAITOK | Z_ZERO | Z_NOFAIL);
356 	zalloc_ro_update_elem(ZONE_ID_THREAD_RO, th->t_tro, tro_tpl);
357 }
358 
359 static void
thread_ro_destroy(thread_t th)360 thread_ro_destroy(thread_t th)
361 {
362 	thread_ro_t tro = get_thread_ro(th);
363 #if MACH_BSD
364 	struct ucred *cred = tro->tro_cred;
365 	struct ucred *rcred = tro->tro_realcred;
366 #endif
367 	zfree_ro(ZONE_ID_THREAD_RO, tro);
368 #if MACH_BSD
369 	uthread_cred_free(cred);
370 	uthread_cred_free(rcred);
371 #endif
372 }
373 
374 __startup_func
375 thread_t
thread_bootstrap(void)376 thread_bootstrap(void)
377 {
378 	/*
379 	 *	Fill in a template thread for fast initialization.
380 	 */
381 	timer_init(&thread_template.runnable_timer);
382 
383 	init_thread_from_template(&init_thread);
384 	/* fiddle with init thread to skip asserts in set_sched_pri */
385 	init_thread.sched_pri = MAXPRI_KERNEL;
386 
387 	/*
388 	 * We can't quite use ctid yet, on ARM thread_bootstrap() is called
389 	 * before we can call random or anything,
390 	 * so we just make it barely work and it will get fixed up
391 	 * when the first thread is actually made.
392 	 */
393 	*compact_id_resolve(&ctid_table, 0) = &init_thread;
394 	init_thread.ctid = CTID_MASK;
395 
396 	return &init_thread;
397 }
398 
399 void
thread_machine_init_template(void)400 thread_machine_init_template(void)
401 {
402 	machine_thread_template_init(&thread_template);
403 }
404 
405 void
thread_init(void)406 thread_init(void)
407 {
408 	/*
409 	 *	Initialize any machine-dependent
410 	 *	per-thread structures necessary.
411 	 */
412 	machine_thread_init();
413 
414 	init_thread_ledgers();
415 }
416 
417 boolean_t
thread_is_active(thread_t thread)418 thread_is_active(thread_t thread)
419 {
420 	return thread->active;
421 }
422 
423 void
thread_corpse_continue(void)424 thread_corpse_continue(void)
425 {
426 	thread_t thread = current_thread();
427 
428 	thread_terminate_internal(thread);
429 
430 	/*
431 	 * Handle the thread termination directly
432 	 * here instead of returning to userspace.
433 	 */
434 	assert(thread->active == FALSE);
435 	thread_ast_clear(thread, AST_APC);
436 	thread_apc_ast(thread);
437 
438 	panic("thread_corpse_continue");
439 	/*NOTREACHED*/
440 }
441 
442 __dead2
443 static void
thread_terminate_continue(void)444 thread_terminate_continue(void)
445 {
446 	panic("thread_terminate_continue");
447 	/*NOTREACHED*/
448 }
449 
450 /*
451  *	thread_terminate_self:
452  */
453 void
thread_terminate_self(void)454 thread_terminate_self(void)
455 {
456 	thread_t    thread = current_thread();
457 	thread_ro_t tro    = get_thread_ro(thread);
458 	task_t      task   = tro->tro_task;
459 	void *bsd_info = get_bsdtask_info(task);
460 	int threadcnt;
461 
462 	pal_thread_terminate_self(thread);
463 
464 	DTRACE_PROC(lwp__exit);
465 
466 	thread_mtx_lock(thread);
467 
468 	ipc_thread_disable(thread);
469 
470 	thread_mtx_unlock(thread);
471 
472 	thread_sched_call(thread, NULL);
473 
474 	spl_t s = splsched();
475 	thread_lock(thread);
476 
477 	thread_depress_abort_locked(thread);
478 
479 	/*
480 	 * Before we take the thread_lock right above,
481 	 * act_set_ast_reset_pcs() might not yet observe
482 	 * that the thread is inactive, and could have
483 	 * requested an IPI Ack.
484 	 *
485 	 * Once we unlock the thread, we know that
486 	 * act_set_ast_reset_pcs() can't fail to notice
487 	 * that thread->active is false,
488 	 * and won't set new ones.
489 	 */
490 	thread_reset_pcs_ack_IPI(thread);
491 
492 	thread_unlock(thread);
493 
494 	splx(s);
495 
496 #if CONFIG_TASKWATCH
497 	thead_remove_taskwatch(thread);
498 #endif /* CONFIG_TASKWATCH */
499 
500 	work_interval_thread_terminate(thread);
501 
502 	thread_mtx_lock(thread);
503 
504 	thread_policy_reset(thread);
505 
506 	thread_mtx_unlock(thread);
507 
508 	assert(thread->th_work_interval == NULL);
509 
510 	bank_swap_thread_bank_ledger(thread, NULL);
511 
512 	if (kdebug_enable && bsd_hasthreadname(get_bsdthread_info(thread))) {
513 		char threadname[MAXTHREADNAMESIZE];
514 		bsd_getthreadname(get_bsdthread_info(thread), threadname);
515 		kernel_debug_string_simple(TRACE_STRING_THREADNAME_PREV, threadname);
516 	}
517 
518 	uthread_cleanup(get_bsdthread_info(thread), tro);
519 
520 	if (kdebug_enable && bsd_info && !task_is_exec_copy(task)) {
521 		/* trace out pid before we sign off */
522 		long dbg_arg1 = 0;
523 		long dbg_arg2 = 0;
524 
525 		kdbg_trace_data(get_bsdtask_info(task), &dbg_arg1, &dbg_arg2);
526 #if CONFIG_PERVASIVE_CPI
527 		if (kdebug_debugid_enabled(DBG_MT_INSTRS_CYCLES_THR_EXIT)) {
528 			struct recount_usage usage = { 0 };
529 			struct recount_usage perf_only = { 0 };
530 			boolean_t intrs_end = ml_set_interrupts_enabled(FALSE);
531 			recount_current_thread_usage_perf_only(&usage, &perf_only);
532 			ml_set_interrupts_enabled(intrs_end);
533 			KDBG_RELEASE(DBG_MT_INSTRS_CYCLES_THR_EXIT,
534 			    recount_usage_instructions(&usage),
535 			    recount_usage_cycles(&usage),
536 			    recount_usage_system_time_mach(&usage),
537 			    usage.ru_metrics[RCT_LVL_USER].rm_time_mach);
538 #if __AMP__
539 			KDBG_RELEASE(DBG_MT_P_INSTRS_CYCLES_THR_EXIT,
540 			    recount_usage_instructions(&perf_only),
541 			    recount_usage_cycles(&perf_only),
542 			    recount_usage_system_time_mach(&perf_only),
543 			    perf_only.ru_metrics[RCT_LVL_USER].rm_time_mach);
544 #endif // __AMP__
545 		}
546 #endif/* CONFIG_PERVASIVE_CPI */
547 		KDBG_RELEASE(TRACE_DATA_THREAD_TERMINATE_PID, dbg_arg1, dbg_arg2);
548 	}
549 
550 	/*
551 	 * After this subtraction, this thread should never access
552 	 * task->bsd_info unless it got 0 back from the os_atomic_dec.  It
553 	 * could be racing with other threads to be the last thread in the
554 	 * process, and the last thread in the process will tear down the proc
555 	 * structure and zero-out task->bsd_info.
556 	 */
557 	threadcnt = os_atomic_dec(&task->active_thread_count, relaxed);
558 
559 #if CONFIG_COALITIONS
560 	/*
561 	 * Leave the coalitions when last thread of task is exiting and the
562 	 * task is not a corpse.
563 	 */
564 	if (threadcnt == 0 && !task->corpse_info) {
565 		coalitions_remove_task(task);
566 	}
567 #endif
568 
569 	/*
570 	 * If we are the last thread to terminate and the task is
571 	 * associated with a BSD process, perform BSD process exit.
572 	 */
573 	if (threadcnt == 0 && bsd_info != NULL) {
574 		mach_exception_data_type_t subcode = 0;
575 		if (kdebug_enable) {
576 			/* since we're the last thread in this process, trace out the command name too */
577 			long args[4] = { 0 };
578 			kdebug_proc_name_args(bsd_info, args);
579 #if CONFIG_PERVASIVE_CPI
580 			if (kdebug_debugid_enabled(DBG_MT_INSTRS_CYCLES_PROC_EXIT)) {
581 				struct recount_usage usage = { 0 };
582 				struct recount_usage perf_only = { 0 };
583 				recount_current_task_usage_perf_only(&usage, &perf_only);
584 				KDBG_RELEASE(DBG_MT_INSTRS_CYCLES_PROC_EXIT,
585 				    recount_usage_instructions(&usage),
586 				    recount_usage_cycles(&usage),
587 				    recount_usage_system_time_mach(&usage),
588 				    usage.ru_metrics[RCT_LVL_USER].rm_time_mach);
589 #if __AMP__
590 				KDBG_RELEASE(DBG_MT_P_INSTRS_CYCLES_PROC_EXIT,
591 				    recount_usage_instructions(&perf_only),
592 				    recount_usage_cycles(&perf_only),
593 				    recount_usage_system_time_mach(&perf_only),
594 				    perf_only.ru_metrics[RCT_LVL_USER].rm_time_mach);
595 #endif // __AMP__
596 			}
597 #endif/* CONFIG_PERVASIVE_CPI */
598 			KDBG_RELEASE(TRACE_STRING_PROC_EXIT, args[0], args[1], args[2], args[3]);
599 		}
600 
601 		/* Get the exit reason before proc_exit */
602 		subcode = proc_encode_exit_exception_code(bsd_info);
603 		proc_exit(bsd_info);
604 		bsd_info = NULL;
605 #if CONFIG_EXCLAVES
606 		task_clear_conclave(task);
607 #endif
608 		/*
609 		 * if there is crash info in task
610 		 * then do the deliver action since this is
611 		 * last thread for this task.
612 		 */
613 		if (task->corpse_info) {
614 			/* reset all except task name port */
615 			ipc_task_reset(task);
616 			/* enable all task ports (name port unchanged) */
617 			ipc_task_enable(task);
618 			exception_type_t etype = get_exception_from_corpse_crashinfo(task->corpse_info);
619 			task_deliver_crash_notification(task, current_thread(), etype, subcode);
620 		}
621 	}
622 
623 	if (threadcnt == 0) {
624 		task_lock(task);
625 		if (task_is_a_corpse_fork(task)) {
626 			thread_wakeup((event_t)&task->active_thread_count);
627 		}
628 		task_unlock(task);
629 	}
630 
631 #if CONFIG_EXCLAVES
632 	exclaves_thread_terminate(thread);
633 #endif
634 
635 	if (thread->th_vm_faults_disabled) {
636 		panic("Thread %p terminating with vm_faults disabled.", thread);
637 	}
638 
639 	s = splsched();
640 	thread_lock(thread);
641 
642 	/*
643 	 * Ensure that the depress timer is no longer enqueued,
644 	 * so the timer can be safely deallocated
645 	 *
646 	 * TODO: build timer_call_cancel_wait
647 	 */
648 
649 	assert((thread->sched_flags & TH_SFLAG_DEPRESSED_MASK) == 0);
650 
651 	uint32_t delay_us = 1;
652 
653 	while (thread->depress_timer_active > 0) {
654 		thread_unlock(thread);
655 		splx(s);
656 
657 		delay(delay_us++);
658 
659 		if (delay_us > USEC_PER_SEC) {
660 			panic("depress timer failed to inactivate!"
661 			    "thread: %p depress_timer_active: %d",
662 			    thread, thread->depress_timer_active);
663 		}
664 
665 		s = splsched();
666 		thread_lock(thread);
667 	}
668 
669 	/*
670 	 *	Cancel wait timer, and wait for
671 	 *	concurrent expirations.
672 	 */
673 	if (thread->wait_timer_armed) {
674 		thread->wait_timer_armed = false;
675 
676 		if (timer_call_cancel(thread->wait_timer)) {
677 			thread->wait_timer_active--;
678 		}
679 	}
680 
681 	delay_us = 1;
682 
683 	while (thread->wait_timer_active > 0) {
684 		thread_unlock(thread);
685 		splx(s);
686 
687 		delay(delay_us++);
688 
689 		if (delay_us > USEC_PER_SEC) {
690 			panic("wait timer failed to inactivate!"
691 			    "thread: %p, wait_timer_active: %d, "
692 			    "wait_timer_armed: %d",
693 			    thread, thread->wait_timer_active,
694 			    thread->wait_timer_armed);
695 		}
696 
697 		s = splsched();
698 		thread_lock(thread);
699 	}
700 
701 	/*
702 	 *	If there is a reserved stack, release it.
703 	 */
704 	if (thread->reserved_stack != 0) {
705 		stack_free_reserved(thread);
706 		thread->reserved_stack = 0;
707 	}
708 
709 	/*
710 	 *	Mark thread as terminating, and block.
711 	 */
712 	thread->state |= TH_TERMINATE;
713 	thread_mark_wait_locked(thread, THREAD_UNINT);
714 
715 #if CONFIG_EXCLAVES
716 	assert(thread->th_exclaves_ipc_ctx.ipcb == NULL);
717 	assert(thread->th_exclaves_ipc_ctx.scid == 0);
718 	assert(thread->th_exclaves_intstate == 0);
719 	assert(thread->th_exclaves_state == 0);
720 #endif
721 	assert(thread->th_work_interval_flags == TH_WORK_INTERVAL_FLAGS_NONE);
722 	assert(thread->kern_promotion_schedpri == 0);
723 	if (thread->rwlock_count > 0) {
724 		panic("rwlock_count is %d for thread %p, possibly it still holds a rwlock", thread->rwlock_count, thread);
725 	}
726 	assert(thread->priority_floor_count == 0);
727 	assert(thread->handoff_thread == THREAD_NULL);
728 	assert(thread->th_work_interval == NULL);
729 	assert(thread->t_rr_state.trr_value == 0);
730 #if DEBUG || DEVELOPMENT
731 	assert(thread->th_test_ctx == NULL);
732 #endif
733 
734 	assert3u(0, ==, thread->sched_flags &
735 	    (TH_SFLAG_WAITQ_PROMOTED |
736 	    TH_SFLAG_RW_PROMOTED |
737 	    TH_SFLAG_EXEC_PROMOTED |
738 	    TH_SFLAG_FLOOR_PROMOTED |
739 	    TH_SFLAG_PROMOTED |
740 	    TH_SFLAG_DEPRESS));
741 
742 	thread_unlock(thread);
743 	/* splsched */
744 
745 	thread_block((thread_continue_t)thread_terminate_continue);
746 	/*NOTREACHED*/
747 }
748 
749 static bool
thread_ref_release(thread_t thread)750 thread_ref_release(thread_t thread)
751 {
752 	if (thread == THREAD_NULL) {
753 		return false;
754 	}
755 
756 	assert_thread_magic(thread);
757 
758 	return os_ref_release_raw(&thread->ref_count, &thread_refgrp) == 0;
759 }
760 
761 /* Drop a thread refcount safely without triggering a zfree */
762 void
thread_deallocate_safe(thread_t thread)763 thread_deallocate_safe(thread_t thread)
764 {
765 	if (__improbable(thread_ref_release(thread))) {
766 		/* enqueue the thread for thread deallocate deamon to call thread_deallocate_complete */
767 		thread_deallocate_enqueue(thread);
768 	}
769 }
770 
771 void
thread_deallocate(thread_t thread)772 thread_deallocate(thread_t thread)
773 {
774 	if (__improbable(thread_ref_release(thread))) {
775 		thread_deallocate_complete(thread);
776 	}
777 }
778 
779 void
thread_deallocate_complete(thread_t thread)780 thread_deallocate_complete(
781 	thread_t                        thread)
782 {
783 	task_t                          task;
784 
785 	assert_thread_magic(thread);
786 
787 	assert(os_ref_get_count_raw(&thread->ref_count) == 0);
788 
789 	if (!(thread->state & TH_TERMINATE2)) {
790 		panic("thread_deallocate: thread not properly terminated");
791 	}
792 
793 	thread_assert_runq_null(thread);
794 	assert(!(thread->state & TH_WAKING));
795 
796 #if CONFIG_CPU_COUNTERS
797 	kpc_thread_destroy(thread);
798 #endif /* CONFIG_CPU_COUNTERS */
799 
800 	ipc_thread_terminate(thread);
801 
802 	proc_thread_qos_deallocate(thread);
803 
804 	task = get_threadtask(thread);
805 
806 #ifdef MACH_BSD
807 	uthread_destroy(get_bsdthread_info(thread));
808 #endif /* MACH_BSD */
809 
810 	if (thread->t_ledger) {
811 		ledger_dereference(thread->t_ledger);
812 	}
813 	if (thread->t_threadledger) {
814 		ledger_dereference(thread->t_threadledger);
815 	}
816 
817 	assert(thread->turnstile != TURNSTILE_NULL);
818 	if (thread->turnstile) {
819 		turnstile_deallocate(thread->turnstile);
820 	}
821 	turnstile_compact_id_put(thread->ctsid);
822 
823 	if (IPC_VOUCHER_NULL != thread->ith_voucher) {
824 		ipc_voucher_release(thread->ith_voucher);
825 	}
826 
827 	kfree_data(thread->thread_io_stats, sizeof(struct io_stat_info));
828 #if CONFIG_PREADOPT_TG
829 	if (thread->old_preadopt_thread_group) {
830 		thread_group_release(thread->old_preadopt_thread_group);
831 	}
832 
833 	if (thread->preadopt_thread_group) {
834 		thread_group_release(thread->preadopt_thread_group);
835 	}
836 #endif /* CONFIG_PREADOPT_TG */
837 
838 	if (thread->kernel_stack != 0) {
839 		stack_free(thread);
840 	}
841 
842 	recount_thread_deinit(&thread->th_recount);
843 
844 	lck_mtx_destroy(&thread->mutex, &thread_lck_grp);
845 	machine_thread_destroy(thread);
846 
847 	task_deallocate_grp(task, TASK_GRP_INTERNAL);
848 
849 #if MACH_ASSERT
850 	assert_thread_magic(thread);
851 	thread->thread_magic = 0;
852 #endif /* MACH_ASSERT */
853 
854 	lck_mtx_lock(&tasks_threads_lock);
855 	assert(terminated_threads_count > 0);
856 	queue_remove(&terminated_threads, thread, thread_t, threads);
857 	terminated_threads_count--;
858 	lck_mtx_unlock(&tasks_threads_lock);
859 
860 	timer_call_free(thread->depress_timer);
861 	timer_call_free(thread->wait_timer);
862 
863 	ctid_table_remove(thread);
864 
865 	thread_ro_destroy(thread);
866 	zfree(thread_zone, thread);
867 }
868 
869 /*
870  *	thread_inspect_deallocate:
871  *
872  *	Drop a thread inspection reference.
873  */
874 void
thread_inspect_deallocate(thread_inspect_t thread_inspect)875 thread_inspect_deallocate(
876 	thread_inspect_t                thread_inspect)
877 {
878 	return thread_deallocate((thread_t)thread_inspect);
879 }
880 
881 /*
882  *	thread_read_deallocate:
883  *
884  *	Drop a reference on thread read port.
885  */
886 void
thread_read_deallocate(thread_read_t thread_read)887 thread_read_deallocate(
888 	thread_read_t                thread_read)
889 {
890 	return thread_deallocate((thread_t)thread_read);
891 }
892 
893 
894 /*
895  *	thread_exception_queue_invoke:
896  *
897  *	Deliver EXC_{RESOURCE,GUARD} exception
898  */
899 static void
thread_exception_queue_invoke(mpsc_queue_chain_t elm,__assert_only mpsc_daemon_queue_t dq)900 thread_exception_queue_invoke(mpsc_queue_chain_t elm,
901     __assert_only mpsc_daemon_queue_t dq)
902 {
903 	struct thread_exception_elt *elt;
904 	task_t task;
905 	thread_t thread;
906 	exception_type_t etype;
907 
908 	assert(dq == &thread_exception_queue);
909 	elt = mpsc_queue_element(elm, struct thread_exception_elt, link);
910 
911 	etype = elt->exception_type;
912 	task = elt->exception_task;
913 	thread = elt->exception_thread;
914 	assert_thread_magic(thread);
915 
916 	kfree_type(struct thread_exception_elt, elt);
917 
918 	/* wait for all the threads in the task to terminate */
919 	task_lock(task);
920 	task_wait_till_threads_terminate_locked(task);
921 	task_unlock(task);
922 
923 	/* Consumes the task ref returned by task_generate_corpse_internal */
924 	task_deallocate(task);
925 	/* Consumes the thread ref returned by task_generate_corpse_internal */
926 	thread_deallocate(thread);
927 
928 	/* Deliver the notification, also clears the corpse. */
929 	task_deliver_crash_notification(task, thread, etype, 0);
930 }
931 
932 static void
thread_backtrace_queue_invoke(mpsc_queue_chain_t elm,__assert_only mpsc_daemon_queue_t dq)933 thread_backtrace_queue_invoke(mpsc_queue_chain_t elm,
934     __assert_only mpsc_daemon_queue_t dq)
935 {
936 	struct thread_backtrace_elt *elt;
937 	kcdata_object_t obj;
938 	exception_port_t exc_ports[BT_EXC_PORTS_COUNT]; /* send rights */
939 	exception_type_t etype;
940 
941 	assert(dq == &thread_backtrace_queue);
942 	elt = mpsc_queue_element(elm, struct thread_backtrace_elt, link);
943 
944 	obj = elt->obj;
945 	memcpy(exc_ports, elt->exc_ports, sizeof(ipc_port_t) * BT_EXC_PORTS_COUNT);
946 	etype = elt->exception_type;
947 
948 	kfree_type(struct thread_backtrace_elt, elt);
949 
950 	/* Deliver to backtrace exception ports */
951 	exception_deliver_backtrace(obj, exc_ports, etype);
952 
953 	/*
954 	 * Release port right and kcdata object refs given by
955 	 * task_enqueue_exception_with_corpse()
956 	 */
957 
958 	for (unsigned int i = 0; i < BT_EXC_PORTS_COUNT; i++) {
959 		ipc_port_release_send(exc_ports[i]);
960 	}
961 
962 	kcdata_object_release(obj);
963 }
964 
965 /*
966  *	thread_exception_enqueue:
967  *
968  *	Enqueue a corpse port to be delivered an EXC_{RESOURCE,GUARD}.
969  */
970 void
thread_exception_enqueue(task_t task,thread_t thread,exception_type_t etype)971 thread_exception_enqueue(
972 	task_t          task,
973 	thread_t        thread,
974 	exception_type_t etype)
975 {
976 	assert(EXC_RESOURCE == etype || EXC_GUARD == etype);
977 	struct thread_exception_elt *elt = kalloc_type(struct thread_exception_elt, Z_WAITOK | Z_NOFAIL);
978 	elt->exception_type = etype;
979 	elt->exception_task = task;
980 	elt->exception_thread = thread;
981 
982 	mpsc_daemon_enqueue(&thread_exception_queue, &elt->link,
983 	    MPSC_QUEUE_DISABLE_PREEMPTION);
984 }
985 
986 void
thread_backtrace_enqueue(kcdata_object_t obj,exception_port_t ports[static BT_EXC_PORTS_COUNT],exception_type_t etype)987 thread_backtrace_enqueue(
988 	kcdata_object_t  obj,
989 	exception_port_t ports[static BT_EXC_PORTS_COUNT],
990 	exception_type_t etype)
991 {
992 	struct thread_backtrace_elt *elt = kalloc_type(struct thread_backtrace_elt, Z_WAITOK | Z_NOFAIL);
993 	elt->obj = obj;
994 	elt->exception_type = etype;
995 
996 	memcpy(elt->exc_ports, ports, sizeof(ipc_port_t) * BT_EXC_PORTS_COUNT);
997 
998 	mpsc_daemon_enqueue(&thread_backtrace_queue, &elt->link,
999 	    MPSC_QUEUE_DISABLE_PREEMPTION);
1000 }
1001 
1002 /*
1003  *	thread_copy_resource_info
1004  *
1005  *	Copy the resource info counters from source
1006  *	thread to destination thread.
1007  */
1008 void
thread_copy_resource_info(thread_t dst_thread,thread_t src_thread)1009 thread_copy_resource_info(
1010 	thread_t dst_thread,
1011 	thread_t src_thread)
1012 {
1013 	dst_thread->c_switch = src_thread->c_switch;
1014 	dst_thread->p_switch = src_thread->p_switch;
1015 	dst_thread->ps_switch = src_thread->ps_switch;
1016 	dst_thread->sched_time_save = src_thread->sched_time_save;
1017 	dst_thread->runnable_timer = src_thread->runnable_timer;
1018 	dst_thread->vtimer_user_save = src_thread->vtimer_user_save;
1019 	dst_thread->vtimer_prof_save = src_thread->vtimer_prof_save;
1020 	dst_thread->vtimer_rlim_save = src_thread->vtimer_rlim_save;
1021 	dst_thread->vtimer_qos_save = src_thread->vtimer_qos_save;
1022 	dst_thread->syscalls_unix = src_thread->syscalls_unix;
1023 	dst_thread->syscalls_mach = src_thread->syscalls_mach;
1024 	ledger_rollup(dst_thread->t_threadledger, src_thread->t_threadledger);
1025 	recount_thread_copy(&dst_thread->th_recount, &src_thread->th_recount);
1026 	*dst_thread->thread_io_stats = *src_thread->thread_io_stats;
1027 }
1028 
1029 static void
thread_terminate_queue_invoke(mpsc_queue_chain_t e,__assert_only mpsc_daemon_queue_t dq)1030 thread_terminate_queue_invoke(mpsc_queue_chain_t e,
1031     __assert_only mpsc_daemon_queue_t dq)
1032 {
1033 	thread_t thread = mpsc_queue_element(e, struct thread, mpsc_links);
1034 	task_t task = get_threadtask(thread);
1035 
1036 	assert(dq == &thread_terminate_queue);
1037 
1038 	task_lock(task);
1039 
1040 	/*
1041 	 * if marked for crash reporting, skip reaping.
1042 	 * The corpse delivery thread will clear bit and enqueue
1043 	 * for reaping when done
1044 	 *
1045 	 * Note: the inspection field is set under the task lock
1046 	 *
1047 	 * FIXME[mad]: why enqueue for termination before `inspection` is false ?
1048 	 */
1049 	if (__improbable(thread->inspection)) {
1050 		simple_lock(&crashed_threads_lock, &thread_lck_grp);
1051 		task_unlock(task);
1052 
1053 		enqueue_tail(&crashed_threads_queue, &thread->runq_links);
1054 		simple_unlock(&crashed_threads_lock);
1055 		return;
1056 	}
1057 
1058 	recount_task_rollup_thread(&task->tk_recount, &thread->th_recount);
1059 
1060 	task->total_runnable_time += timer_grab(&thread->runnable_timer);
1061 	task->c_switch += thread->c_switch;
1062 	task->p_switch += thread->p_switch;
1063 	task->ps_switch += thread->ps_switch;
1064 
1065 	task->syscalls_unix += thread->syscalls_unix;
1066 	task->syscalls_mach += thread->syscalls_mach;
1067 
1068 	task->task_timer_wakeups_bin_1 += thread->thread_timer_wakeups_bin_1;
1069 	task->task_timer_wakeups_bin_2 += thread->thread_timer_wakeups_bin_2;
1070 	task->task_gpu_ns += ml_gpu_stat(thread);
1071 	task->decompressions += thread->decompressions;
1072 
1073 	thread_update_qos_cpu_time(thread);
1074 
1075 	queue_remove(&task->threads, thread, thread_t, task_threads);
1076 	task->thread_count--;
1077 
1078 	/*
1079 	 * If the task is being halted, and there is only one thread
1080 	 * left in the task after this one, then wakeup that thread.
1081 	 */
1082 	if (task->thread_count == 1 && task->halting) {
1083 		thread_wakeup((event_t)&task->halting);
1084 	}
1085 
1086 	task_unlock(task);
1087 
1088 	lck_mtx_lock(&tasks_threads_lock);
1089 	queue_remove(&threads, thread, thread_t, threads);
1090 	threads_count--;
1091 	queue_enter(&terminated_threads, thread, thread_t, threads);
1092 	terminated_threads_count++;
1093 	lck_mtx_unlock(&tasks_threads_lock);
1094 
1095 #if MACH_BSD
1096 	/*
1097 	 * The thread no longer counts against the task's thread count,
1098 	 * we can now wake up any pending joiner.
1099 	 *
1100 	 * Note that the inheritor will be set to `thread` which is
1101 	 * incorrect once it is on the termination queue, however
1102 	 * the termination queue runs at MINPRI_KERNEL which is higher
1103 	 * than any user thread, so this isn't a priority inversion.
1104 	 */
1105 	if (thread_get_tag(thread) & THREAD_TAG_USER_JOIN) {
1106 		struct uthread *uth = get_bsdthread_info(thread);
1107 		mach_port_name_t kport = uthread_joiner_port(uth);
1108 
1109 		/*
1110 		 * Clear the port low two bits to tell pthread that thread is gone.
1111 		 */
1112 #ifndef NO_PORT_GEN
1113 		kport &= ~MACH_PORT_MAKE(0, IE_BITS_GEN_MASK + IE_BITS_GEN_ONE);
1114 #else
1115 		kport |= MACH_PORT_MAKE(0, ~(IE_BITS_GEN_MASK + IE_BITS_GEN_ONE));
1116 #endif
1117 		(void)copyoutmap_atomic32(task->map, kport,
1118 		    uthread_joiner_address(uth));
1119 		uthread_joiner_wake(task, uth);
1120 	}
1121 #endif
1122 
1123 	thread_deallocate(thread);
1124 }
1125 
1126 static void
thread_deallocate_queue_invoke(mpsc_queue_chain_t e,__assert_only mpsc_daemon_queue_t dq)1127 thread_deallocate_queue_invoke(mpsc_queue_chain_t e,
1128     __assert_only mpsc_daemon_queue_t dq)
1129 {
1130 	thread_t thread = mpsc_queue_element(e, struct thread, mpsc_links);
1131 
1132 	assert(dq == &thread_deallocate_queue);
1133 
1134 	thread_deallocate_complete(thread);
1135 }
1136 
1137 /*
1138  *	thread_terminate_enqueue:
1139  *
1140  *	Enqueue a terminating thread for final disposition.
1141  *
1142  *	Called at splsched.
1143  */
1144 void
thread_terminate_enqueue(thread_t thread)1145 thread_terminate_enqueue(
1146 	thread_t                thread)
1147 {
1148 	KDBG_RELEASE(TRACE_DATA_THREAD_TERMINATE, thread->thread_id);
1149 
1150 	mpsc_daemon_enqueue(&thread_terminate_queue, &thread->mpsc_links,
1151 	    MPSC_QUEUE_DISABLE_PREEMPTION);
1152 }
1153 
1154 /*
1155  *	thread_deallocate_enqueue:
1156  *
1157  *	Enqueue a thread for final deallocation.
1158  */
1159 static void
thread_deallocate_enqueue(thread_t thread)1160 thread_deallocate_enqueue(
1161 	thread_t                thread)
1162 {
1163 	mpsc_daemon_enqueue(&thread_deallocate_queue, &thread->mpsc_links,
1164 	    MPSC_QUEUE_DISABLE_PREEMPTION);
1165 }
1166 
1167 /*
1168  * thread_terminate_crashed_threads:
1169  * walk the list of crashed threads and put back set of threads
1170  * who are no longer being inspected.
1171  */
1172 void
thread_terminate_crashed_threads(void)1173 thread_terminate_crashed_threads(void)
1174 {
1175 	thread_t th_remove;
1176 
1177 	simple_lock(&crashed_threads_lock, &thread_lck_grp);
1178 	/*
1179 	 * loop through the crashed threads queue
1180 	 * to put any threads that are not being inspected anymore
1181 	 */
1182 
1183 	qe_foreach_element_safe(th_remove, &crashed_threads_queue, runq_links) {
1184 		/* make sure current_thread is never in crashed queue */
1185 		assert(th_remove != current_thread());
1186 
1187 		if (th_remove->inspection == FALSE) {
1188 			remqueue(&th_remove->runq_links);
1189 			mpsc_daemon_enqueue(&thread_terminate_queue, &th_remove->mpsc_links,
1190 			    MPSC_QUEUE_NONE);
1191 		}
1192 	}
1193 
1194 	simple_unlock(&crashed_threads_lock);
1195 }
1196 
1197 /*
1198  *	thread_stack_queue_invoke:
1199  *
1200  *	Perform stack allocation as required due to
1201  *	invoke failures.
1202  */
1203 static void
thread_stack_queue_invoke(mpsc_queue_chain_t elm,__assert_only mpsc_daemon_queue_t dq)1204 thread_stack_queue_invoke(mpsc_queue_chain_t elm,
1205     __assert_only mpsc_daemon_queue_t dq)
1206 {
1207 	thread_t thread = mpsc_queue_element(elm, struct thread, mpsc_links);
1208 
1209 	assert(dq == &thread_stack_queue);
1210 
1211 	/* allocate stack with interrupts enabled so that we can call into VM */
1212 	stack_alloc(thread);
1213 
1214 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_STACK_WAIT) | DBG_FUNC_END, thread_tid(thread), 0, 0, 0, 0);
1215 
1216 	spl_t s = splsched();
1217 	thread_lock(thread);
1218 	thread_setrun(thread, SCHED_PREEMPT | SCHED_TAILQ);
1219 	thread_unlock(thread);
1220 	splx(s);
1221 }
1222 
1223 /*
1224  *	thread_stack_enqueue:
1225  *
1226  *	Enqueue a thread for stack allocation.
1227  *
1228  *	Called at splsched.
1229  */
1230 void
thread_stack_enqueue(thread_t thread)1231 thread_stack_enqueue(
1232 	thread_t                thread)
1233 {
1234 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_STACK_WAIT) | DBG_FUNC_START, thread_tid(thread), 0, 0, 0, 0);
1235 	assert_thread_magic(thread);
1236 
1237 	mpsc_daemon_enqueue(&thread_stack_queue, &thread->mpsc_links,
1238 	    MPSC_QUEUE_DISABLE_PREEMPTION);
1239 }
1240 
1241 void
thread_daemon_init(void)1242 thread_daemon_init(void)
1243 {
1244 	kern_return_t   result;
1245 
1246 	thread_deallocate_daemon_init();
1247 
1248 	thread_deallocate_daemon_register_queue(&thread_terminate_queue,
1249 	    thread_terminate_queue_invoke);
1250 
1251 	thread_deallocate_daemon_register_queue(&thread_deallocate_queue,
1252 	    thread_deallocate_queue_invoke);
1253 
1254 	ipc_object_deallocate_register_queue();
1255 
1256 	simple_lock_init(&crashed_threads_lock, 0);
1257 	queue_init(&crashed_threads_queue);
1258 
1259 	result = mpsc_daemon_queue_init_with_thread(&thread_stack_queue,
1260 	    thread_stack_queue_invoke, BASEPRI_PREEMPT_HIGH,
1261 	    "daemon.thread-stack", MPSC_DAEMON_INIT_NONE);
1262 	if (result != KERN_SUCCESS) {
1263 		panic("thread_daemon_init: thread_stack_daemon");
1264 	}
1265 
1266 	result = mpsc_daemon_queue_init_with_thread(&thread_exception_queue,
1267 	    thread_exception_queue_invoke, MINPRI_KERNEL,
1268 	    "daemon.thread-exception", MPSC_DAEMON_INIT_NONE);
1269 
1270 	if (result != KERN_SUCCESS) {
1271 		panic("thread_daemon_init: thread_exception_daemon");
1272 	}
1273 
1274 	result = mpsc_daemon_queue_init_with_thread(&thread_backtrace_queue,
1275 	    thread_backtrace_queue_invoke, MINPRI_KERNEL,
1276 	    "daemon.thread-backtrace", MPSC_DAEMON_INIT_NONE);
1277 
1278 	if (result != KERN_SUCCESS) {
1279 		panic("thread_daemon_init: thread_backtrace_daemon");
1280 	}
1281 }
1282 
1283 __options_decl(thread_create_internal_options_t, uint32_t, {
1284 	TH_OPTION_NONE          = 0x00,
1285 	TH_OPTION_NOSUSP        = 0x02,
1286 	TH_OPTION_WORKQ         = 0x04,
1287 	TH_OPTION_MAINTHREAD    = 0x08,
1288 });
1289 
1290 void
main_thread_set_immovable_pinned(thread_t thread)1291 main_thread_set_immovable_pinned(thread_t thread)
1292 {
1293 	ipc_main_thread_set_immovable_pinned(thread);
1294 }
1295 
1296 /*
1297  * Create a new thread.
1298  * Doesn't start the thread running.
1299  *
1300  * Task and tasks_threads_lock are returned locked on success.
1301  */
1302 static kern_return_t
thread_create_internal(task_t parent_task,integer_t priority,thread_continue_t continuation,void * parameter,thread_create_internal_options_t options,thread_t * out_thread)1303 thread_create_internal(
1304 	task_t                                  parent_task,
1305 	integer_t                               priority,
1306 	thread_continue_t                       continuation,
1307 	void                                    *parameter,
1308 	thread_create_internal_options_t        options,
1309 	thread_t                                *out_thread)
1310 {
1311 	thread_t                  new_thread;
1312 	ipc_thread_init_options_t init_options = IPC_THREAD_INIT_NONE;
1313 	struct thread_ro          tro_tpl = { };
1314 	bool first_thread = false;
1315 	kern_return_t kr = KERN_FAILURE;
1316 
1317 	/*
1318 	 *	Allocate a thread and initialize static fields
1319 	 */
1320 	new_thread = zalloc_flags(thread_zone, Z_WAITOK | Z_NOFAIL);
1321 
1322 	if (__improbable(current_thread() == &init_thread)) {
1323 		/*
1324 		 * The first thread ever is a global, but because we want to be
1325 		 * able to zone_id_require() threads, we have to stop using the
1326 		 * global piece of memory we used to boostrap the kernel and
1327 		 * jump to a proper thread from a zone.
1328 		 *
1329 		 * This is why that one thread will inherit its original
1330 		 * state differently.
1331 		 *
1332 		 * Also remember this thread in `vm_pageout_scan_thread`
1333 		 * as this is what the first thread ever becomes.
1334 		 *
1335 		 * Also pre-warm the depress timer since the VM pageout scan
1336 		 * daemon might need to use it.
1337 		 */
1338 		assert(vm_pageout_scan_thread == THREAD_NULL);
1339 		vm_pageout_scan_thread = new_thread;
1340 
1341 		first_thread = true;
1342 #pragma clang diagnostic push
1343 #pragma clang diagnostic ignored "-Wnontrivial-memaccess"
1344 		/* work around 74481146 */
1345 		memcpy(new_thread, &init_thread, sizeof(*new_thread));
1346 #pragma clang diagnostic pop
1347 
1348 		/*
1349 		 * Make the ctid table functional
1350 		 */
1351 		ctid_table_init();
1352 		new_thread->ctid = 0;
1353 	} else {
1354 		init_thread_from_template(new_thread);
1355 	}
1356 
1357 	if (options & TH_OPTION_MAINTHREAD) {
1358 		init_options |= IPC_THREAD_INIT_MAINTHREAD;
1359 	}
1360 
1361 	os_ref_init_count_raw(&new_thread->ref_count, &thread_refgrp, 2);
1362 	machine_thread_create(new_thread, parent_task, first_thread);
1363 
1364 	machine_thread_process_signature(new_thread, parent_task);
1365 
1366 #ifdef MACH_BSD
1367 	uthread_init(parent_task, get_bsdthread_info(new_thread),
1368 	    &tro_tpl, (options & TH_OPTION_WORKQ) != 0);
1369 	if (!task_is_a_corpse(parent_task)) {
1370 		/*
1371 		 * uthread_init will set tro_cred (with a +1)
1372 		 * and tro_proc for live tasks.
1373 		 */
1374 		assert(tro_tpl.tro_cred && tro_tpl.tro_proc);
1375 	}
1376 #endif  /* MACH_BSD */
1377 
1378 	thread_lock_init(new_thread);
1379 	wake_lock_init(new_thread);
1380 
1381 	lck_mtx_init(&new_thread->mutex, &thread_lck_grp, LCK_ATTR_NULL);
1382 
1383 	ipc_thread_init(parent_task, new_thread, &tro_tpl, init_options);
1384 
1385 	thread_ro_create(parent_task, new_thread, &tro_tpl);
1386 
1387 	new_thread->continuation = continuation;
1388 	new_thread->parameter = parameter;
1389 	new_thread->inheritor_flags = TURNSTILE_UPDATE_FLAGS_NONE;
1390 	new_thread->requested_policy = default_thread_requested_policy;
1391 	new_thread->__runq.runq = PROCESSOR_NULL;
1392 	priority_queue_init(&new_thread->sched_inheritor_queue);
1393 	priority_queue_init(&new_thread->base_inheritor_queue);
1394 #if CONFIG_SCHED_CLUTCH
1395 	priority_queue_entry_init(&new_thread->th_clutch_runq_link);
1396 	priority_queue_entry_init(&new_thread->th_clutch_pri_link);
1397 #endif /* CONFIG_SCHED_CLUTCH */
1398 
1399 #if CONFIG_SCHED_EDGE
1400 	new_thread->th_bound_cluster_enqueued = false;
1401 	for (cluster_shared_rsrc_type_t shared_rsrc_type = CLUSTER_SHARED_RSRC_TYPE_MIN; shared_rsrc_type < CLUSTER_SHARED_RSRC_TYPE_COUNT; shared_rsrc_type++) {
1402 		new_thread->th_shared_rsrc_enqueued[shared_rsrc_type] = false;
1403 		new_thread->th_shared_rsrc_heavy_user[shared_rsrc_type] = false;
1404 		new_thread->th_shared_rsrc_heavy_perf_control[shared_rsrc_type] = false;
1405 	}
1406 #endif /* CONFIG_SCHED_EDGE */
1407 	new_thread->th_bound_cluster_id = THREAD_BOUND_CLUSTER_NONE;
1408 
1409 	/* Allocate I/O Statistics structure */
1410 	new_thread->thread_io_stats = kalloc_data(sizeof(struct io_stat_info),
1411 	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
1412 
1413 #if KASAN_CLASSIC
1414 	kasan_init_thread(&new_thread->kasan_data);
1415 #endif /* KASAN_CLASSIC */
1416 
1417 #if CONFIG_KCOV
1418 	kcov_init_thread(&new_thread->kcov_data);
1419 #endif
1420 
1421 #if CONFIG_IOSCHED
1422 	/* Clear out the I/O Scheduling info for AppleFSCompression */
1423 	new_thread->decmp_upl = NULL;
1424 #endif /* CONFIG_IOSCHED */
1425 
1426 	new_thread->thread_region_page_shift = 0;
1427 
1428 #if DEVELOPMENT || DEBUG
1429 	task_lock(parent_task);
1430 	uint16_t thread_limit = parent_task->task_thread_limit;
1431 	if (exc_resource_threads_enabled &&
1432 	    thread_limit > 0 &&
1433 	    parent_task->thread_count >= thread_limit &&
1434 	    !parent_task->task_has_crossed_thread_limit &&
1435 	    !(task_is_a_corpse(parent_task))) {
1436 		int thread_count = parent_task->thread_count;
1437 		parent_task->task_has_crossed_thread_limit = TRUE;
1438 		task_unlock(parent_task);
1439 		SENDING_NOTIFICATION__TASK_HAS_TOO_MANY_THREADS(parent_task, thread_count);
1440 	} else {
1441 		task_unlock(parent_task);
1442 	}
1443 #endif
1444 
1445 	lck_mtx_lock(&tasks_threads_lock);
1446 	task_lock(parent_task);
1447 
1448 	/*
1449 	 * Fail thread creation if parent task is being torn down or has too many threads
1450 	 * If the caller asked for TH_OPTION_NOSUSP, also fail if the parent task is suspended
1451 	 */
1452 	if (parent_task->active == 0 || parent_task->halting ||
1453 	    (parent_task->suspend_count > 0 && (options & TH_OPTION_NOSUSP) != 0) ||
1454 	    (parent_task->thread_count >= task_threadmax && parent_task != kernel_task)) {
1455 		task_unlock(parent_task);
1456 		lck_mtx_unlock(&tasks_threads_lock);
1457 
1458 		ipc_thread_disable(new_thread);
1459 		ipc_thread_terminate(new_thread);
1460 		kfree_data(new_thread->thread_io_stats,
1461 		    sizeof(struct io_stat_info));
1462 		lck_mtx_destroy(&new_thread->mutex, &thread_lck_grp);
1463 		kr = KERN_FAILURE;
1464 		goto out_thread_cleanup;
1465 	}
1466 
1467 	/* Protected by the tasks_threads_lock */
1468 	new_thread->thread_id = ++thread_unique_id;
1469 
1470 	ctid_table_add(new_thread);
1471 
1472 	/* New threads inherit any default state on the task */
1473 	machine_thread_inherit_taskwide(new_thread, parent_task);
1474 
1475 	task_reference_grp(parent_task, TASK_GRP_INTERNAL);
1476 
1477 	if (parent_task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_PERTHR_LIMIT) {
1478 		/*
1479 		 * This task has a per-thread CPU limit; make sure this new thread
1480 		 * gets its limit set too, before it gets out of the kernel.
1481 		 */
1482 		act_set_astledger(new_thread);
1483 	}
1484 
1485 	/* Instantiate a thread ledger. Do not fail thread creation if ledger creation fails. */
1486 	if ((new_thread->t_threadledger = ledger_instantiate(thread_ledger_template,
1487 	    LEDGER_CREATE_INACTIVE_ENTRIES)) != LEDGER_NULL) {
1488 		ledger_entry_setactive(new_thread->t_threadledger, thread_ledgers.cpu_time);
1489 	}
1490 
1491 	new_thread->t_bankledger = LEDGER_NULL;
1492 	new_thread->t_deduct_bank_ledger_time = 0;
1493 	new_thread->t_deduct_bank_ledger_energy = 0;
1494 
1495 	new_thread->t_ledger = parent_task->ledger;
1496 	if (new_thread->t_ledger) {
1497 		ledger_reference(new_thread->t_ledger);
1498 	}
1499 
1500 	recount_thread_init(&new_thread->th_recount);
1501 
1502 	/* Cache the task's map */
1503 	new_thread->map = parent_task->map;
1504 
1505 	new_thread->depress_timer = timer_call_alloc(thread_depress_expire, new_thread);
1506 	new_thread->wait_timer = timer_call_alloc(thread_timer_expire, new_thread);
1507 
1508 #if CONFIG_CPU_COUNTERS
1509 	kpc_thread_create(new_thread);
1510 #endif /* CONFIG_CPU_COUNTERS */
1511 
1512 	/* Set the thread's scheduling parameters */
1513 	new_thread->sched_mode = SCHED(initial_thread_sched_mode)(parent_task);
1514 	new_thread->max_priority = parent_task->max_priority;
1515 	new_thread->task_priority = parent_task->priority;
1516 
1517 #if CONFIG_THREAD_GROUPS
1518 	thread_group_init_thread(new_thread, parent_task);
1519 #endif /* CONFIG_THREAD_GROUPS */
1520 
1521 	int new_priority = (priority < 0) ? parent_task->priority: priority;
1522 	new_priority = (priority < 0)? parent_task->priority: priority;
1523 	if (new_priority > new_thread->max_priority) {
1524 		new_priority = new_thread->max_priority;
1525 	}
1526 #if !defined(XNU_TARGET_OS_OSX)
1527 	if (new_priority < MAXPRI_THROTTLE) {
1528 		new_priority = MAXPRI_THROTTLE;
1529 	}
1530 #endif /* !defined(XNU_TARGET_OS_OSX) */
1531 
1532 	new_thread->importance = new_priority - new_thread->task_priority;
1533 
1534 	sched_set_thread_base_priority(new_thread, new_priority);
1535 
1536 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
1537 	new_thread->sched_stamp = sched_tick;
1538 #if CONFIG_SCHED_CLUTCH
1539 	new_thread->pri_shift = sched_clutch_thread_pri_shift(new_thread, new_thread->th_sched_bucket);
1540 #else /* CONFIG_SCHED_CLUTCH */
1541 	new_thread->pri_shift = sched_pri_shifts[new_thread->th_sched_bucket];
1542 #endif /* CONFIG_SCHED_CLUTCH */
1543 #endif /* defined(CONFIG_SCHED_TIMESHARE_CORE) */
1544 
1545 	if (parent_task->max_priority <= MAXPRI_THROTTLE) {
1546 		sched_thread_mode_demote(new_thread, TH_SFLAG_THROTTLED);
1547 	}
1548 
1549 	thread_policy_create(new_thread);
1550 
1551 	/* Chain the thread onto the task's list */
1552 	queue_enter(&parent_task->threads, new_thread, thread_t, task_threads);
1553 	parent_task->thread_count++;
1554 
1555 	/* So terminating threads don't need to take the task lock to decrement */
1556 	os_atomic_inc(&parent_task->active_thread_count, relaxed);
1557 
1558 	queue_enter(&threads, new_thread, thread_t, threads);
1559 	threads_count++;
1560 
1561 	new_thread->active = TRUE;
1562 	if (task_is_a_corpse_fork(parent_task)) {
1563 		/* Set the inspection bit if the task is a corpse fork */
1564 		new_thread->inspection = TRUE;
1565 	} else {
1566 		new_thread->inspection = FALSE;
1567 	}
1568 	new_thread->corpse_dup = FALSE;
1569 	new_thread->turnstile = turnstile_alloc();
1570 	new_thread->ctsid = turnstile_compact_id_get();
1571 
1572 
1573 	*out_thread = new_thread;
1574 
1575 	if (kdebug_enable) {
1576 		long args[4] = {};
1577 
1578 		kdbg_trace_data(get_bsdtask_info(parent_task), &args[1], &args[3]);
1579 
1580 		/*
1581 		 * Starting with 26604425, exec'ing creates a new task/thread.
1582 		 *
1583 		 * NEWTHREAD in the current process has two possible meanings:
1584 		 *
1585 		 * 1) Create a new thread for this process.
1586 		 * 2) Create a new thread for the future process this will become in an
1587 		 * exec.
1588 		 *
1589 		 * To disambiguate these, arg3 will be set to TRUE for case #2.
1590 		 *
1591 		 * The value we need to find (TPF_EXEC_COPY) is stable in the case of a
1592 		 * task exec'ing. The read of t_procflags does not take the proc_lock.
1593 		 */
1594 		args[2] = task_is_exec_copy(parent_task) ? 1 : 0;
1595 
1596 		KDBG_RELEASE(TRACE_DATA_NEWTHREAD, (uintptr_t)thread_tid(new_thread),
1597 		    args[1], args[2], args[3]);
1598 
1599 		kdebug_proc_name_args(get_bsdtask_info(parent_task), args);
1600 		KDBG_RELEASE(TRACE_STRING_NEWTHREAD, args[0], args[1], args[2],
1601 		    args[3]);
1602 	}
1603 
1604 	DTRACE_PROC1(lwp__create, thread_t, *out_thread);
1605 
1606 	kr = KERN_SUCCESS;
1607 	goto done;
1608 
1609 out_thread_cleanup:
1610 #ifdef MACH_BSD
1611 	{
1612 		struct uthread *ut = get_bsdthread_info(new_thread);
1613 
1614 		uthread_cleanup(ut, &tro_tpl);
1615 		uthread_destroy(ut);
1616 	}
1617 #endif  /* MACH_BSD */
1618 
1619 	machine_thread_destroy(new_thread);
1620 
1621 	thread_ro_destroy(new_thread);
1622 	zfree(thread_zone, new_thread);
1623 
1624 done:
1625 	return kr;
1626 }
1627 
1628 static kern_return_t
thread_create_with_options_internal(task_t task,thread_t * new_thread,boolean_t from_user,thread_create_internal_options_t options,thread_continue_t continuation)1629 thread_create_with_options_internal(
1630 	task_t                            task,
1631 	thread_t                          *new_thread,
1632 	boolean_t                         from_user,
1633 	thread_create_internal_options_t  options,
1634 	thread_continue_t                 continuation)
1635 {
1636 	kern_return_t           result;
1637 	thread_t                thread;
1638 
1639 	if (task == TASK_NULL || task == kernel_task) {
1640 		return KERN_INVALID_ARGUMENT;
1641 	}
1642 
1643 #if CONFIG_MACF
1644 	if (from_user && current_task() != task &&
1645 	    mac_proc_check_remote_thread_create(task, -1, NULL, 0) != 0) {
1646 		return KERN_DENIED;
1647 	}
1648 #endif
1649 
1650 	result = thread_create_internal(task, -1, continuation, NULL, options, &thread);
1651 	if (result != KERN_SUCCESS) {
1652 		return result;
1653 	}
1654 
1655 	thread->user_stop_count = 1;
1656 	thread_hold(thread);
1657 	if (task->suspend_count > 0) {
1658 		thread_hold(thread);
1659 	}
1660 
1661 	if (from_user) {
1662 		extmod_statistics_incr_thread_create(task);
1663 	}
1664 
1665 	task_unlock(task);
1666 	lck_mtx_unlock(&tasks_threads_lock);
1667 
1668 	*new_thread = thread;
1669 
1670 	return KERN_SUCCESS;
1671 }
1672 
1673 kern_return_t
thread_create_immovable(task_t task,thread_t * new_thread)1674 thread_create_immovable(
1675 	task_t                          task,
1676 	thread_t                        *new_thread)
1677 {
1678 	return thread_create_with_options_internal(task, new_thread, FALSE,
1679 	           TH_OPTION_NONE, (thread_continue_t)thread_bootstrap_return);
1680 }
1681 
1682 kern_return_t
thread_create_from_user(task_t task,thread_t * new_thread)1683 thread_create_from_user(
1684 	task_t                          task,
1685 	thread_t                        *new_thread)
1686 {
1687 	/* All thread ports are created immovable by default */
1688 	return thread_create_with_options_internal(task, new_thread, TRUE, TH_OPTION_NONE,
1689 	           (thread_continue_t)thread_bootstrap_return);
1690 }
1691 
1692 kern_return_t
thread_create_with_continuation(task_t task,thread_t * new_thread,thread_continue_t continuation)1693 thread_create_with_continuation(
1694 	task_t                          task,
1695 	thread_t                        *new_thread,
1696 	thread_continue_t               continuation)
1697 {
1698 	return thread_create_with_options_internal(task, new_thread, FALSE, TH_OPTION_NONE, continuation);
1699 }
1700 
1701 /*
1702  * Create a thread that is already started, but is waiting on an event
1703  */
1704 static kern_return_t
thread_create_waiting_internal(task_t task,thread_continue_t continuation,event_t event,block_hint_t block_hint,thread_create_internal_options_t options,thread_t * new_thread)1705 thread_create_waiting_internal(
1706 	task_t                  task,
1707 	thread_continue_t       continuation,
1708 	event_t                 event,
1709 	block_hint_t            block_hint,
1710 	thread_create_internal_options_t options,
1711 	thread_t                *new_thread)
1712 {
1713 	kern_return_t result;
1714 	thread_t thread;
1715 	wait_interrupt_t wait_interrupt = THREAD_INTERRUPTIBLE;
1716 
1717 	if (task == TASK_NULL || task == kernel_task) {
1718 		return KERN_INVALID_ARGUMENT;
1719 	}
1720 
1721 	result = thread_create_internal(task, -1, continuation, NULL,
1722 	    options, &thread);
1723 	if (result != KERN_SUCCESS) {
1724 		return result;
1725 	}
1726 
1727 	/* note no user_stop_count or thread_hold here */
1728 
1729 	if (task->suspend_count > 0) {
1730 		thread_hold(thread);
1731 	}
1732 
1733 	thread_mtx_lock(thread);
1734 	thread_set_pending_block_hint(thread, block_hint);
1735 	if (options & TH_OPTION_WORKQ) {
1736 		thread->static_param = true;
1737 		event = workq_thread_init_and_wq_lock(task, thread);
1738 	} else if (options & TH_OPTION_MAINTHREAD) {
1739 		wait_interrupt = THREAD_UNINT;
1740 	}
1741 	thread_start_in_assert_wait(thread,
1742 	    assert_wait_queue(event), CAST_EVENT64_T(event),
1743 	    wait_interrupt);
1744 	thread_mtx_unlock(thread);
1745 
1746 	task_unlock(task);
1747 	lck_mtx_unlock(&tasks_threads_lock);
1748 
1749 	*new_thread = thread;
1750 
1751 	return KERN_SUCCESS;
1752 }
1753 
1754 kern_return_t
main_thread_create_waiting(task_t task,thread_continue_t continuation,event_t event,thread_t * new_thread)1755 main_thread_create_waiting(
1756 	task_t                          task,
1757 	thread_continue_t               continuation,
1758 	event_t                         event,
1759 	thread_t                        *new_thread)
1760 {
1761 	return thread_create_waiting_internal(task, continuation, event,
1762 	           kThreadWaitNone, TH_OPTION_MAINTHREAD, new_thread);
1763 }
1764 
1765 
1766 static kern_return_t
thread_create_running_internal2(task_t task,int flavor,thread_state_t new_state,mach_msg_type_number_t new_state_count,thread_t * new_thread,boolean_t from_user)1767 thread_create_running_internal2(
1768 	task_t         task,
1769 	int                     flavor,
1770 	thread_state_t          new_state,
1771 	mach_msg_type_number_t  new_state_count,
1772 	thread_t                                *new_thread,
1773 	boolean_t                               from_user)
1774 {
1775 	kern_return_t  result;
1776 	thread_t                                thread;
1777 
1778 	if (task == TASK_NULL || task == kernel_task) {
1779 		return KERN_INVALID_ARGUMENT;
1780 	}
1781 
1782 #if CONFIG_MACF
1783 	if (from_user && current_task() != task &&
1784 	    mac_proc_check_remote_thread_create(task, flavor, new_state, new_state_count) != 0) {
1785 		return KERN_DENIED;
1786 	}
1787 #endif
1788 
1789 	result = thread_create_internal(task, -1,
1790 	    (thread_continue_t)thread_bootstrap_return, NULL,
1791 	    TH_OPTION_NONE, &thread);
1792 	if (result != KERN_SUCCESS) {
1793 		return result;
1794 	}
1795 
1796 	if (task->suspend_count > 0) {
1797 		thread_hold(thread);
1798 	}
1799 
1800 	if (from_user) {
1801 		result = machine_thread_state_convert_from_user(thread, flavor,
1802 		    new_state, new_state_count, NULL, 0, TSSF_FLAGS_NONE);
1803 	}
1804 	if (result == KERN_SUCCESS) {
1805 		result = machine_thread_set_state(thread, flavor, new_state,
1806 		    new_state_count);
1807 	}
1808 	if (result != KERN_SUCCESS) {
1809 		task_unlock(task);
1810 		lck_mtx_unlock(&tasks_threads_lock);
1811 
1812 		thread_terminate(thread);
1813 		thread_deallocate(thread);
1814 		return result;
1815 	}
1816 
1817 	thread_mtx_lock(thread);
1818 	thread_start(thread);
1819 	thread_mtx_unlock(thread);
1820 
1821 	if (from_user) {
1822 		extmod_statistics_incr_thread_create(task);
1823 	}
1824 
1825 	task_unlock(task);
1826 	lck_mtx_unlock(&tasks_threads_lock);
1827 
1828 	*new_thread = thread;
1829 
1830 	return result;
1831 }
1832 
1833 /* Prototype, see justification above */
1834 kern_return_t
1835 thread_create_running(
1836 	task_t         task,
1837 	int                     flavor,
1838 	thread_state_t          new_state,
1839 	mach_msg_type_number_t  new_state_count,
1840 	thread_t                                *new_thread);
1841 
1842 kern_return_t
thread_create_running(task_t task,int flavor,thread_state_t new_state,mach_msg_type_number_t new_state_count,thread_t * new_thread)1843 thread_create_running(
1844 	task_t         task,
1845 	int                     flavor,
1846 	thread_state_t          new_state,
1847 	mach_msg_type_number_t  new_state_count,
1848 	thread_t                                *new_thread)
1849 {
1850 	return thread_create_running_internal2(
1851 		task, flavor, new_state, new_state_count,
1852 		new_thread, FALSE);
1853 }
1854 
1855 kern_return_t
thread_create_running_from_user(task_t task,int flavor,thread_state_t new_state,mach_msg_type_number_t new_state_count,thread_t * new_thread)1856 thread_create_running_from_user(
1857 	task_t         task,
1858 	int                     flavor,
1859 	thread_state_t          new_state,
1860 	mach_msg_type_number_t  new_state_count,
1861 	thread_t                                *new_thread)
1862 {
1863 	return thread_create_running_internal2(
1864 		task, flavor, new_state, new_state_count,
1865 		new_thread, TRUE);
1866 }
1867 
1868 kern_return_t
thread_create_workq_waiting(task_t task,thread_continue_t continuation,thread_t * new_thread,bool is_permanently_bound)1869 thread_create_workq_waiting(
1870 	task_t              task,
1871 	thread_continue_t   continuation,
1872 	thread_t            *new_thread,
1873 	bool                is_permanently_bound)
1874 {
1875 	/*
1876 	 * Create thread, but don't pin control port just yet, in case someone calls
1877 	 * task_threads() and deallocates pinned port before kernel copyout happens,
1878 	 * which will result in pinned port guard exception. Instead, pin and copyout
1879 	 * atomically during workq_setup_and_run().
1880 	 */
1881 	int options = TH_OPTION_WORKQ;
1882 
1883 	/*
1884 	 * Until we add a support for delayed thread creation for permanently
1885 	 * bound workqueue threads, we do not pass TH_OPTION_NOSUSP for their
1886 	 * creation.
1887 	 */
1888 	if (!is_permanently_bound) {
1889 		options |= TH_OPTION_NOSUSP;
1890 	}
1891 
1892 	return thread_create_waiting_internal(task, continuation, NULL,
1893 	           is_permanently_bound ? kThreadWaitParkedBoundWorkQueue : kThreadWaitParkedWorkQueue,
1894 	           options, new_thread);
1895 }
1896 
1897 /*
1898  *	kernel_thread_create:
1899  *
1900  *	Create a thread in the kernel task
1901  *	to execute in kernel context.
1902  */
1903 kern_return_t
kernel_thread_create(thread_continue_t continuation,void * parameter,integer_t priority,thread_t * new_thread)1904 kernel_thread_create(
1905 	thread_continue_t       continuation,
1906 	void                            *parameter,
1907 	integer_t                       priority,
1908 	thread_t                        *new_thread)
1909 {
1910 	kern_return_t           result;
1911 	thread_t                        thread;
1912 	task_t                          task = kernel_task;
1913 
1914 	result = thread_create_internal(task, priority, continuation, parameter,
1915 	    TH_OPTION_NONE, &thread);
1916 	if (result != KERN_SUCCESS) {
1917 		return result;
1918 	}
1919 
1920 	task_unlock(task);
1921 	lck_mtx_unlock(&tasks_threads_lock);
1922 
1923 	stack_alloc(thread);
1924 	assert(thread->kernel_stack != 0);
1925 #if !defined(XNU_TARGET_OS_OSX)
1926 	if (priority > BASEPRI_KERNEL)
1927 #endif
1928 	thread->reserved_stack = thread->kernel_stack;
1929 
1930 	if (debug_task & 1) {
1931 		kprintf("kernel_thread_create: thread = %p continuation = %p\n", thread, continuation);
1932 	}
1933 	*new_thread = thread;
1934 
1935 	return result;
1936 }
1937 
1938 kern_return_t
kernel_thread_start_priority(thread_continue_t continuation,void * parameter,integer_t priority,thread_t * new_thread)1939 kernel_thread_start_priority(
1940 	thread_continue_t       continuation,
1941 	void                            *parameter,
1942 	integer_t                       priority,
1943 	thread_t                        *new_thread)
1944 {
1945 	kern_return_t   result;
1946 	thread_t                thread;
1947 
1948 	result = kernel_thread_create(continuation, parameter, priority, &thread);
1949 	if (result != KERN_SUCCESS) {
1950 		return result;
1951 	}
1952 
1953 	*new_thread = thread;
1954 
1955 	thread_mtx_lock(thread);
1956 	thread_start(thread);
1957 	thread_mtx_unlock(thread);
1958 
1959 	return result;
1960 }
1961 
1962 kern_return_t
kernel_thread_start(thread_continue_t continuation,void * parameter,thread_t * new_thread)1963 kernel_thread_start(
1964 	thread_continue_t       continuation,
1965 	void                            *parameter,
1966 	thread_t                        *new_thread)
1967 {
1968 	return kernel_thread_start_priority(continuation, parameter, -1, new_thread);
1969 }
1970 
1971 /* Separated into helper function so it can be used by THREAD_BASIC_INFO and THREAD_EXTENDED_INFO */
1972 /* it is assumed that the thread is locked by the caller */
1973 static void
retrieve_thread_basic_info(thread_t thread,thread_basic_info_t basic_info)1974 retrieve_thread_basic_info(thread_t thread, thread_basic_info_t basic_info)
1975 {
1976 	int     state, flags;
1977 
1978 	/* fill in info */
1979 
1980 	thread_read_times(thread, &basic_info->user_time,
1981 	    &basic_info->system_time, NULL);
1982 
1983 	/*
1984 	 *	Update lazy-evaluated scheduler info because someone wants it.
1985 	 */
1986 	if (SCHED(can_update_priority)(thread)) {
1987 		SCHED(update_priority)(thread);
1988 	}
1989 
1990 	basic_info->sleep_time = 0;
1991 
1992 	/*
1993 	 *	To calculate cpu_usage, first correct for timer rate,
1994 	 *	then for 5/8 ageing.  The correction factor [3/5] is
1995 	 *	(1/(5/8) - 1).
1996 	 */
1997 	basic_info->cpu_usage = 0;
1998 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
1999 	if (sched_tick_interval) {
2000 		basic_info->cpu_usage = (integer_t)(((uint64_t)thread->cpu_usage
2001 		    * TH_USAGE_SCALE) /     sched_tick_interval);
2002 		basic_info->cpu_usage = (basic_info->cpu_usage * 3) / 5;
2003 	}
2004 #endif
2005 
2006 	if (basic_info->cpu_usage > TH_USAGE_SCALE) {
2007 		basic_info->cpu_usage = TH_USAGE_SCALE;
2008 	}
2009 
2010 	basic_info->policy = ((thread->sched_mode == TH_MODE_TIMESHARE)?
2011 	    POLICY_TIMESHARE: POLICY_RR);
2012 
2013 	flags = 0;
2014 	if (thread->options & TH_OPT_IDLE_THREAD) {
2015 		flags |= TH_FLAGS_IDLE;
2016 	}
2017 
2018 	if (thread->options & TH_OPT_GLOBAL_FORCED_IDLE) {
2019 		flags |= TH_FLAGS_GLOBAL_FORCED_IDLE;
2020 	}
2021 
2022 	if (!thread->kernel_stack) {
2023 		flags |= TH_FLAGS_SWAPPED;
2024 	}
2025 
2026 	state = 0;
2027 	if (thread->state & TH_TERMINATE) {
2028 		state = TH_STATE_HALTED;
2029 	} else if (thread->state & TH_RUN) {
2030 		state = TH_STATE_RUNNING;
2031 	} else if (thread->state & TH_UNINT) {
2032 		state = TH_STATE_UNINTERRUPTIBLE;
2033 	} else if (thread->state & TH_SUSP) {
2034 		state = TH_STATE_STOPPED;
2035 	} else if (thread->state & TH_WAIT) {
2036 		state = TH_STATE_WAITING;
2037 	}
2038 
2039 	basic_info->run_state = state;
2040 	basic_info->flags = flags;
2041 
2042 	basic_info->suspend_count = thread->user_stop_count;
2043 
2044 	return;
2045 }
2046 
2047 kern_return_t
thread_info_internal(thread_t thread,thread_flavor_t flavor,thread_info_t thread_info_out,mach_msg_type_number_t * thread_info_count)2048 thread_info_internal(
2049 	thread_t                thread,
2050 	thread_flavor_t                 flavor,
2051 	thread_info_t                   thread_info_out,        /* ptr to OUT array */
2052 	mach_msg_type_number_t  *thread_info_count)     /*IN/OUT*/
2053 {
2054 	spl_t   s;
2055 
2056 	if (thread == THREAD_NULL) {
2057 		return KERN_INVALID_ARGUMENT;
2058 	}
2059 
2060 	if (flavor == THREAD_BASIC_INFO) {
2061 		if (*thread_info_count < THREAD_BASIC_INFO_COUNT) {
2062 			return KERN_INVALID_ARGUMENT;
2063 		}
2064 
2065 		s = splsched();
2066 		thread_lock(thread);
2067 
2068 		retrieve_thread_basic_info(thread, (thread_basic_info_t) thread_info_out);
2069 
2070 		thread_unlock(thread);
2071 		splx(s);
2072 
2073 		*thread_info_count = THREAD_BASIC_INFO_COUNT;
2074 
2075 		return KERN_SUCCESS;
2076 	} else if (flavor == THREAD_IDENTIFIER_INFO) {
2077 		thread_identifier_info_t        identifier_info;
2078 
2079 		if (*thread_info_count < THREAD_IDENTIFIER_INFO_COUNT) {
2080 			return KERN_INVALID_ARGUMENT;
2081 		}
2082 
2083 		identifier_info = __IGNORE_WCASTALIGN((thread_identifier_info_t)thread_info_out);
2084 
2085 		s = splsched();
2086 		thread_lock(thread);
2087 
2088 		identifier_info->thread_id = thread->thread_id;
2089 		identifier_info->thread_handle = thread->machine.cthread_self;
2090 		identifier_info->dispatch_qaddr = thread_dispatchqaddr(thread);
2091 
2092 		thread_unlock(thread);
2093 		splx(s);
2094 		return KERN_SUCCESS;
2095 	} else if (flavor == THREAD_SCHED_TIMESHARE_INFO) {
2096 		policy_timeshare_info_t         ts_info;
2097 
2098 		if (*thread_info_count < POLICY_TIMESHARE_INFO_COUNT) {
2099 			return KERN_INVALID_ARGUMENT;
2100 		}
2101 
2102 		ts_info = (policy_timeshare_info_t)thread_info_out;
2103 
2104 		s = splsched();
2105 		thread_lock(thread);
2106 
2107 		if (thread->sched_mode != TH_MODE_TIMESHARE) {
2108 			thread_unlock(thread);
2109 			splx(s);
2110 			return KERN_INVALID_POLICY;
2111 		}
2112 
2113 		ts_info->depressed = (thread->sched_flags & TH_SFLAG_DEPRESSED_MASK) != 0;
2114 		if (ts_info->depressed) {
2115 			ts_info->base_priority = DEPRESSPRI;
2116 			ts_info->depress_priority = thread->base_pri;
2117 		} else {
2118 			ts_info->base_priority = thread->base_pri;
2119 			ts_info->depress_priority = -1;
2120 		}
2121 
2122 		ts_info->cur_priority = thread->sched_pri;
2123 		ts_info->max_priority = thread->max_priority;
2124 
2125 		thread_unlock(thread);
2126 		splx(s);
2127 
2128 		*thread_info_count = POLICY_TIMESHARE_INFO_COUNT;
2129 
2130 		return KERN_SUCCESS;
2131 	} else if (flavor == THREAD_SCHED_FIFO_INFO) {
2132 		if (*thread_info_count < POLICY_FIFO_INFO_COUNT) {
2133 			return KERN_INVALID_ARGUMENT;
2134 		}
2135 
2136 		return KERN_INVALID_POLICY;
2137 	} else if (flavor == THREAD_SCHED_RR_INFO) {
2138 		policy_rr_info_t                        rr_info;
2139 		uint32_t quantum_time;
2140 		uint64_t quantum_ns;
2141 
2142 		if (*thread_info_count < POLICY_RR_INFO_COUNT) {
2143 			return KERN_INVALID_ARGUMENT;
2144 		}
2145 
2146 		rr_info = (policy_rr_info_t) thread_info_out;
2147 
2148 		s = splsched();
2149 		thread_lock(thread);
2150 
2151 		if (thread->sched_mode == TH_MODE_TIMESHARE) {
2152 			thread_unlock(thread);
2153 			splx(s);
2154 
2155 			return KERN_INVALID_POLICY;
2156 		}
2157 
2158 		rr_info->depressed = (thread->sched_flags & TH_SFLAG_DEPRESSED_MASK) != 0;
2159 		if (rr_info->depressed) {
2160 			rr_info->base_priority = DEPRESSPRI;
2161 			rr_info->depress_priority = thread->base_pri;
2162 		} else {
2163 			rr_info->base_priority = thread->base_pri;
2164 			rr_info->depress_priority = -1;
2165 		}
2166 
2167 		quantum_time = SCHED(initial_quantum_size)(THREAD_NULL);
2168 		absolutetime_to_nanoseconds(quantum_time, &quantum_ns);
2169 
2170 		rr_info->max_priority = thread->max_priority;
2171 		rr_info->quantum = (uint32_t)(quantum_ns / 1000 / 1000);
2172 
2173 		thread_unlock(thread);
2174 		splx(s);
2175 
2176 		*thread_info_count = POLICY_RR_INFO_COUNT;
2177 
2178 		return KERN_SUCCESS;
2179 	} else if (flavor == THREAD_EXTENDED_INFO) {
2180 		thread_basic_info_data_t        basic_info;
2181 		thread_extended_info_t          extended_info = __IGNORE_WCASTALIGN((thread_extended_info_t)thread_info_out);
2182 
2183 		if (*thread_info_count < THREAD_EXTENDED_INFO_COUNT) {
2184 			return KERN_INVALID_ARGUMENT;
2185 		}
2186 
2187 		s = splsched();
2188 		thread_lock(thread);
2189 
2190 		/* NOTE: This mimics fill_taskthreadinfo(), which is the function used by proc_pidinfo() for
2191 		 * the PROC_PIDTHREADINFO flavor (which can't be used on corpses)
2192 		 */
2193 		retrieve_thread_basic_info(thread, &basic_info);
2194 		extended_info->pth_user_time = (((uint64_t)basic_info.user_time.seconds * NSEC_PER_SEC) + ((uint64_t)basic_info.user_time.microseconds * NSEC_PER_USEC));
2195 		extended_info->pth_system_time = (((uint64_t)basic_info.system_time.seconds * NSEC_PER_SEC) + ((uint64_t)basic_info.system_time.microseconds * NSEC_PER_USEC));
2196 
2197 		extended_info->pth_cpu_usage = basic_info.cpu_usage;
2198 		extended_info->pth_policy = basic_info.policy;
2199 		extended_info->pth_run_state = basic_info.run_state;
2200 		extended_info->pth_flags = basic_info.flags;
2201 		extended_info->pth_sleep_time = basic_info.sleep_time;
2202 		extended_info->pth_curpri = thread->sched_pri;
2203 		extended_info->pth_priority = thread->base_pri;
2204 		extended_info->pth_maxpriority = thread->max_priority;
2205 
2206 		bsd_getthreadname(get_bsdthread_info(thread), extended_info->pth_name);
2207 
2208 		thread_unlock(thread);
2209 		splx(s);
2210 
2211 		*thread_info_count = THREAD_EXTENDED_INFO_COUNT;
2212 
2213 		return KERN_SUCCESS;
2214 	} else if (flavor == THREAD_DEBUG_INFO_INTERNAL) {
2215 #if DEVELOPMENT || DEBUG
2216 		thread_debug_info_internal_t dbg_info;
2217 		if (*thread_info_count < THREAD_DEBUG_INFO_INTERNAL_COUNT) {
2218 			return KERN_NOT_SUPPORTED;
2219 		}
2220 
2221 		if (thread_info_out == NULL) {
2222 			return KERN_INVALID_ARGUMENT;
2223 		}
2224 
2225 		dbg_info = __IGNORE_WCASTALIGN((thread_debug_info_internal_t)thread_info_out);
2226 		dbg_info->page_creation_count = thread->t_page_creation_count;
2227 
2228 		*thread_info_count = THREAD_DEBUG_INFO_INTERNAL_COUNT;
2229 		return KERN_SUCCESS;
2230 #endif /* DEVELOPMENT || DEBUG */
2231 		return KERN_NOT_SUPPORTED;
2232 	}
2233 
2234 	return KERN_INVALID_ARGUMENT;
2235 }
2236 
2237 static void
_convert_mach_to_time_value(uint64_t time_mach,time_value_t * time)2238 _convert_mach_to_time_value(uint64_t time_mach, time_value_t *time)
2239 {
2240 	clock_sec_t  secs;
2241 	clock_usec_t usecs;
2242 	absolutetime_to_microtime(time_mach, &secs, &usecs);
2243 	time->seconds = (typeof(time->seconds))secs;
2244 	time->microseconds = usecs;
2245 }
2246 
2247 void
thread_read_times(thread_t thread,time_value_t * user_time,time_value_t * system_time,time_value_t * runnable_time)2248 thread_read_times(
2249 	thread_t      thread,
2250 	time_value_t *user_time,
2251 	time_value_t *system_time,
2252 	time_value_t *runnable_time)
2253 {
2254 	if (user_time && system_time) {
2255 		struct recount_times_mach times = recount_thread_times(thread);
2256 		_convert_mach_to_time_value(times.rtm_user, user_time);
2257 		_convert_mach_to_time_value(times.rtm_system, system_time);
2258 	}
2259 
2260 	if (runnable_time) {
2261 		uint64_t runnable_time_mach = timer_grab(&thread->runnable_timer);
2262 		_convert_mach_to_time_value(runnable_time_mach, runnable_time);
2263 	}
2264 }
2265 
2266 uint64_t
thread_get_runtime_self(void)2267 thread_get_runtime_self(void)
2268 {
2269 	/*
2270 	 * Must be guaranteed to stay on the same CPU and not be updated by the
2271 	 * scheduler.
2272 	 */
2273 	boolean_t interrupt_state = ml_set_interrupts_enabled(FALSE);
2274 	uint64_t time_mach = recount_current_thread_time_mach();
2275 	ml_set_interrupts_enabled(interrupt_state);
2276 	return time_mach;
2277 }
2278 
2279 /*
2280  *	thread_wire_internal:
2281  *
2282  *	Specify that the target thread must always be able
2283  *	to run and to allocate memory.
2284  */
2285 kern_return_t
thread_wire_internal(host_priv_t host_priv,thread_t thread,boolean_t wired,boolean_t * prev_state)2286 thread_wire_internal(
2287 	host_priv_t             host_priv,
2288 	thread_t                thread,
2289 	boolean_t               wired,
2290 	boolean_t               *prev_state)
2291 {
2292 	if (host_priv == NULL || thread != current_thread()) {
2293 		return KERN_INVALID_ARGUMENT;
2294 	}
2295 
2296 	if (prev_state) {
2297 		*prev_state = (thread->options & TH_OPT_VMPRIV) != 0;
2298 	}
2299 
2300 	if (wired) {
2301 		if (!(thread->options & TH_OPT_VMPRIV)) {
2302 			vm_page_free_reserve(1); /* XXX */
2303 		}
2304 		thread->options |= TH_OPT_VMPRIV;
2305 	} else {
2306 		if (thread->options & TH_OPT_VMPRIV) {
2307 			vm_page_free_reserve(-1); /* XXX */
2308 		}
2309 		thread->options &= ~TH_OPT_VMPRIV;
2310 	}
2311 
2312 	return KERN_SUCCESS;
2313 }
2314 
2315 
2316 /*
2317  *	thread_wire:
2318  *
2319  *	User-api wrapper for thread_wire_internal()
2320  */
2321 kern_return_t
thread_wire(host_priv_t host_priv __unused,thread_t thread __unused,boolean_t wired __unused)2322 thread_wire(
2323 	host_priv_t     host_priv __unused,
2324 	thread_t        thread __unused,
2325 	boolean_t       wired __unused)
2326 {
2327 	return KERN_NOT_SUPPORTED;
2328 }
2329 
2330 boolean_t
is_external_pageout_thread(void)2331 is_external_pageout_thread(void)
2332 {
2333 	return current_thread() == pgo_iothread_external_state.pgo_iothread;
2334 }
2335 
2336 boolean_t
is_vm_privileged(void)2337 is_vm_privileged(void)
2338 {
2339 	return current_thread()->options & TH_OPT_VMPRIV ? TRUE : FALSE;
2340 }
2341 
2342 boolean_t
set_vm_privilege(boolean_t privileged)2343 set_vm_privilege(boolean_t privileged)
2344 {
2345 	boolean_t       was_vmpriv;
2346 
2347 	if (current_thread()->options & TH_OPT_VMPRIV) {
2348 		was_vmpriv = TRUE;
2349 	} else {
2350 		was_vmpriv = FALSE;
2351 	}
2352 
2353 	if (privileged != FALSE) {
2354 		current_thread()->options |= TH_OPT_VMPRIV;
2355 	} else {
2356 		current_thread()->options &= ~TH_OPT_VMPRIV;
2357 	}
2358 
2359 	return was_vmpriv;
2360 }
2361 
2362 void
thread_floor_boost_set_promotion_locked(thread_t thread)2363 thread_floor_boost_set_promotion_locked(thread_t thread)
2364 {
2365 	assert(thread->priority_floor_count > 0);
2366 
2367 	if (!(thread->sched_flags & TH_SFLAG_FLOOR_PROMOTED)) {
2368 		sched_thread_promote_reason(thread, TH_SFLAG_FLOOR_PROMOTED, 0);
2369 	}
2370 }
2371 
2372 /*!  @function thread_priority_floor_start
2373  *   @abstract boost the current thread priority to floor.
2374  *   @discussion Increase the priority of the current thread to at least MINPRI_FLOOR.
2375  *       The boost will be mantained until a corresponding thread_priority_floor_end()
2376  *       is called. Every call of thread_priority_floor_start() needs to have a corresponding
2377  *       call to thread_priority_floor_end() from the same thread.
2378  *       No thread can return to userspace before calling thread_priority_floor_end().
2379  *
2380  *       NOTE: avoid to use this function. Try to use gate_t or sleep_with_inheritor()
2381  *       instead.
2382  *   @result a token to be given to the corresponding thread_priority_floor_end()
2383  */
2384 thread_pri_floor_t
thread_priority_floor_start(void)2385 thread_priority_floor_start(void)
2386 {
2387 	thread_pri_floor_t ret;
2388 	thread_t thread = current_thread();
2389 	__assert_only uint16_t prev_priority_floor_count;
2390 
2391 	assert(thread->priority_floor_count < UINT16_MAX);
2392 	prev_priority_floor_count = thread->priority_floor_count++;
2393 #if MACH_ASSERT
2394 	/*
2395 	 * Set the ast to check that the
2396 	 * priority_floor_count is going to be set to zero when
2397 	 * going back to userspace.
2398 	 * Set it only once when we increment it for the first time.
2399 	 */
2400 	if (prev_priority_floor_count == 0) {
2401 		act_set_debug_assert();
2402 	}
2403 #endif
2404 
2405 	ret.thread = thread;
2406 	return ret;
2407 }
2408 
2409 /*!  @function thread_priority_floor_end
2410  *   @abstract ends the floor boost.
2411  *   @param token the token obtained from thread_priority_floor_start()
2412  *   @discussion ends the priority floor boost started with thread_priority_floor_start()
2413  */
2414 void
thread_priority_floor_end(thread_pri_floor_t * token)2415 thread_priority_floor_end(thread_pri_floor_t *token)
2416 {
2417 	thread_t thread = current_thread();
2418 
2419 	assert(thread->priority_floor_count > 0);
2420 	assertf(token->thread == thread, "thread_priority_floor_end called from a different thread from thread_priority_floor_start %p %p", thread, token->thread);
2421 
2422 	if ((thread->priority_floor_count-- == 1) && (thread->sched_flags & TH_SFLAG_FLOOR_PROMOTED)) {
2423 		spl_t s = splsched();
2424 		thread_lock(thread);
2425 
2426 		if (thread->sched_flags & TH_SFLAG_FLOOR_PROMOTED) {
2427 			sched_thread_unpromote_reason(thread, TH_SFLAG_FLOOR_PROMOTED, 0);
2428 		}
2429 
2430 		thread_unlock(thread);
2431 		splx(s);
2432 	}
2433 
2434 	token->thread = NULL;
2435 }
2436 
2437 /*
2438  * XXX assuming current thread only, for now...
2439  */
2440 void
thread_guard_violation(thread_t thread,mach_exception_data_type_t code,mach_exception_data_type_t subcode,boolean_t fatal)2441 thread_guard_violation(thread_t thread,
2442     mach_exception_data_type_t code, mach_exception_data_type_t subcode, boolean_t fatal)
2443 {
2444 	assert(thread == current_thread());
2445 
2446 	/* Don't set up the AST for kernel threads; this check is needed to ensure
2447 	 * that the guard_exc_* fields in the thread structure are set only by the
2448 	 * current thread and therefore, don't require a lock.
2449 	 */
2450 	if (get_threadtask(thread) == kernel_task) {
2451 		return;
2452 	}
2453 
2454 	assert(EXC_GUARD_DECODE_GUARD_TYPE(code));
2455 
2456 	/*
2457 	 * Use the saved state area of the thread structure
2458 	 * to store all info required to handle the AST when
2459 	 * returning to userspace. It's possible that there is
2460 	 * already a pending guard exception. If it's non-fatal,
2461 	 * it can only be over-written by a fatal exception code.
2462 	 */
2463 	if (thread->guard_exc_info.code && (thread->guard_exc_fatal || !fatal)) {
2464 		return;
2465 	}
2466 
2467 	thread->guard_exc_info.code = code;
2468 	thread->guard_exc_info.subcode = subcode;
2469 	thread->guard_exc_fatal = fatal ? 1 : 0;
2470 
2471 	spl_t s = splsched();
2472 	thread_ast_set(thread, AST_GUARD);
2473 	ast_propagate(thread);
2474 	splx(s);
2475 }
2476 
2477 #if CONFIG_DEBUG_SYSCALL_REJECTION
2478 extern void rejected_syscall_guard_ast(thread_t __unused t, mach_exception_data_type_t code, mach_exception_data_type_t subcode);
2479 #endif /* CONFIG_DEBUG_SYSCALL_REJECTION */
2480 
2481 /*
2482  *	guard_ast:
2483  *
2484  *	Handle AST_GUARD for a thread. This routine looks at the
2485  *	state saved in the thread structure to determine the cause
2486  *	of this exception. Based on this value, it invokes the
2487  *	appropriate routine which determines other exception related
2488  *	info and raises the exception.
2489  */
2490 void
guard_ast(thread_t t)2491 guard_ast(thread_t t)
2492 {
2493 	const mach_exception_data_type_t
2494 	    code = t->guard_exc_info.code,
2495 	    subcode = t->guard_exc_info.subcode;
2496 
2497 	t->guard_exc_info.code = 0;
2498 	t->guard_exc_info.subcode = 0;
2499 	t->guard_exc_fatal = 0;
2500 
2501 	switch (EXC_GUARD_DECODE_GUARD_TYPE(code)) {
2502 	case GUARD_TYPE_NONE:
2503 		/* lingering AST_GUARD on the processor? */
2504 		break;
2505 	case GUARD_TYPE_MACH_PORT:
2506 		mach_port_guard_ast(t, code, subcode);
2507 		break;
2508 	case GUARD_TYPE_FD:
2509 		fd_guard_ast(t, code, subcode);
2510 		break;
2511 	case GUARD_TYPE_VN:
2512 		vn_guard_ast(t, code, subcode);
2513 		break;
2514 	case GUARD_TYPE_VIRT_MEMORY:
2515 		virt_memory_guard_ast(t, code, subcode);
2516 		break;
2517 #if CONFIG_DEBUG_SYSCALL_REJECTION
2518 	case GUARD_TYPE_REJECTED_SC:
2519 		rejected_syscall_guard_ast(t, code, subcode);
2520 		break;
2521 #endif /* CONFIG_DEBUG_SYSCALL_REJECTION */
2522 	default:
2523 		panic("guard_exc_info %llx %llx", code, subcode);
2524 	}
2525 }
2526 
2527 static void
thread_cputime_callback(int warning,__unused const void * arg0,__unused const void * arg1)2528 thread_cputime_callback(int warning, __unused const void *arg0, __unused const void *arg1)
2529 {
2530 	if (warning == 0) {
2531 		SENDING_NOTIFICATION__THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU();
2532 	}
2533 }
2534 
2535 void __attribute__((noinline))
SENDING_NOTIFICATION__THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU(void)2536 SENDING_NOTIFICATION__THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU(void)
2537 {
2538 	int          pid                = 0;
2539 	task_t           task                           = current_task();
2540 	thread_t     thread             = current_thread();
2541 	uint64_t     tid                = thread->thread_id;
2542 	const char       *procname          = "unknown";
2543 	time_value_t thread_total_time  = {0, 0};
2544 	time_value_t thread_system_time;
2545 	time_value_t thread_user_time;
2546 	int          action;
2547 	uint8_t      percentage;
2548 	uint32_t     usage_percent = 0;
2549 	uint32_t     interval_sec;
2550 	uint64_t     interval_ns;
2551 	uint64_t     balance_ns;
2552 	boolean_t        fatal = FALSE;
2553 	boolean_t        send_exc_resource = TRUE; /* in addition to RESOURCE_NOTIFY */
2554 	kern_return_t   kr;
2555 
2556 #ifdef EXC_RESOURCE_MONITORS
2557 	mach_exception_data_type_t      code[EXCEPTION_CODE_MAX];
2558 #endif /* EXC_RESOURCE_MONITORS */
2559 	struct ledger_entry_info        lei;
2560 
2561 	assert(thread->t_threadledger != LEDGER_NULL);
2562 
2563 	/*
2564 	 * Extract the fatal bit and suspend the monitor (which clears the bit).
2565 	 */
2566 	task_lock(task);
2567 	if (task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_FATAL_CPUMON) {
2568 		fatal = TRUE;
2569 		send_exc_resource = TRUE;
2570 	}
2571 	/* Only one thread can be here at a time.  Whichever makes it through
2572 	 *  first will successfully suspend the monitor and proceed to send the
2573 	 *  notification.  Other threads will get an error trying to suspend the
2574 	 *  monitor and give up on sending the notification.  In the first release,
2575 	 *  the monitor won't be resumed for a number of seconds, but we may
2576 	 *  eventually need to handle low-latency resume.
2577 	 */
2578 	kr = task_suspend_cpumon(task);
2579 	task_unlock(task);
2580 	if (kr == KERN_INVALID_ARGUMENT) {
2581 		return;
2582 	}
2583 
2584 #ifdef MACH_BSD
2585 	pid = proc_selfpid();
2586 	void *bsd_info = get_bsdtask_info(task);
2587 	if (bsd_info != NULL) {
2588 		procname = proc_name_address(bsd_info);
2589 	}
2590 #endif
2591 
2592 	thread_get_cpulimit(&action, &percentage, &interval_ns);
2593 
2594 	interval_sec = (uint32_t)(interval_ns / NSEC_PER_SEC);
2595 
2596 	thread_read_times(thread, &thread_user_time, &thread_system_time, NULL);
2597 	time_value_add(&thread_total_time, &thread_user_time);
2598 	time_value_add(&thread_total_time, &thread_system_time);
2599 	ledger_get_entry_info(thread->t_threadledger, thread_ledgers.cpu_time, &lei);
2600 
2601 	/* credit/debit/balance/limit are in absolute time units;
2602 	 *  the refill info is in nanoseconds. */
2603 	absolutetime_to_nanoseconds(lei.lei_balance, &balance_ns);
2604 	if (lei.lei_last_refill > 0) {
2605 		usage_percent = (uint32_t)((balance_ns * 100ULL) / lei.lei_last_refill);
2606 	}
2607 
2608 	/* TODO: show task total runtime (via TASK_ABSOLUTETIME_INFO)? */
2609 	printf("process %s[%d] thread %llu caught burning CPU! It used more than %d%% CPU over %u seconds\n",
2610 	    procname, pid, tid, percentage, interval_sec);
2611 	printf("  (actual recent usage: %d%% over ~%llu seconds)\n",
2612 	    usage_percent, (lei.lei_last_refill + NSEC_PER_SEC / 2) / NSEC_PER_SEC);
2613 	printf("  Thread lifetime cpu usage %d.%06ds, (%d.%06d user, %d.%06d sys)\n",
2614 	    thread_total_time.seconds, thread_total_time.microseconds,
2615 	    thread_user_time.seconds, thread_user_time.microseconds,
2616 	    thread_system_time.seconds, thread_system_time.microseconds);
2617 	printf("  Ledger balance: %lld; mabs credit: %lld; mabs debit: %lld\n",
2618 	    lei.lei_balance, lei.lei_credit, lei.lei_debit);
2619 	printf("  mabs limit: %llu; mabs period: %llu ns; last refill: %llu ns%s.\n",
2620 	    lei.lei_limit, lei.lei_refill_period, lei.lei_last_refill,
2621 	    (fatal ? " [fatal violation]" : ""));
2622 
2623 	/*
2624 	 *  For now, send RESOURCE_NOTIFY in parallel with EXC_RESOURCE.  Once
2625 	 *  we have logging parity, we will stop sending EXC_RESOURCE (24508922).
2626 	 */
2627 
2628 	/* RESOURCE_NOTIFY MIG specifies nanoseconds of CPU time */
2629 	lei.lei_balance = balance_ns;
2630 	absolutetime_to_nanoseconds(lei.lei_limit, &lei.lei_limit);
2631 	trace_resource_violation(RMON_CPUUSAGE_VIOLATED, &lei);
2632 	kr = send_resource_violation(send_cpu_usage_violation, task, &lei,
2633 	    fatal ? kRNFatalLimitFlag : 0);
2634 	if (kr) {
2635 		printf("send_resource_violation(CPU usage, ...): error %#x\n", kr);
2636 	}
2637 
2638 #ifdef EXC_RESOURCE_MONITORS
2639 	if (send_exc_resource) {
2640 		if (disable_exc_resource) {
2641 			printf("process %s[%d] thread %llu caught burning CPU! "
2642 			    "EXC_RESOURCE%s suppressed by a boot-arg\n",
2643 			    procname, pid, tid, fatal ? " (and termination)" : "");
2644 			return;
2645 		}
2646 
2647 		if (disable_exc_resource_during_audio && audio_active) {
2648 			printf("process %s[%d] thread %llu caught burning CPU! "
2649 			    "EXC_RESOURCE & termination suppressed due to audio playback\n",
2650 			    procname, pid, tid);
2651 			return;
2652 		}
2653 	}
2654 
2655 
2656 	if (send_exc_resource) {
2657 		code[0] = code[1] = 0;
2658 		EXC_RESOURCE_ENCODE_TYPE(code[0], RESOURCE_TYPE_CPU);
2659 		if (fatal) {
2660 			EXC_RESOURCE_ENCODE_FLAVOR(code[0], FLAVOR_CPU_MONITOR_FATAL);
2661 		} else {
2662 			EXC_RESOURCE_ENCODE_FLAVOR(code[0], FLAVOR_CPU_MONITOR);
2663 		}
2664 		EXC_RESOURCE_CPUMONITOR_ENCODE_INTERVAL(code[0], interval_sec);
2665 		EXC_RESOURCE_CPUMONITOR_ENCODE_PERCENTAGE(code[0], percentage);
2666 		EXC_RESOURCE_CPUMONITOR_ENCODE_PERCENTAGE(code[1], usage_percent);
2667 		exception_triage(EXC_RESOURCE, code, EXCEPTION_CODE_MAX);
2668 	}
2669 #endif /* EXC_RESOURCE_MONITORS */
2670 
2671 	if (fatal) {
2672 #if CONFIG_JETSAM
2673 		jetsam_on_ledger_cpulimit_exceeded();
2674 #else
2675 		task_terminate_internal(task);
2676 #endif
2677 	}
2678 }
2679 
2680 bool os_variant_has_internal_diagnostics(const char *subsystem);
2681 
2682 #if DEVELOPMENT || DEBUG
2683 
2684 void __attribute__((noinline))
SENDING_NOTIFICATION__TASK_HAS_TOO_MANY_THREADS(task_t task,int thread_count)2685 SENDING_NOTIFICATION__TASK_HAS_TOO_MANY_THREADS(task_t task, int thread_count)
2686 {
2687 	mach_exception_data_type_t code[EXCEPTION_CODE_MAX] = {0};
2688 	int pid = task_pid(task);
2689 	char procname[MAXCOMLEN + 1] = "unknown";
2690 
2691 	if (pid == 1) {
2692 		/*
2693 		 * Cannot suspend launchd
2694 		 */
2695 		return;
2696 	}
2697 
2698 	proc_name(pid, procname, sizeof(procname));
2699 
2700 	/*
2701 	 * Skip all checks for testing when exc_resource_threads_enabled is overriden
2702 	 */
2703 	if (exc_resource_threads_enabled == 2) {
2704 		goto skip_checks;
2705 	}
2706 
2707 	if (disable_exc_resource) {
2708 		printf("process %s[%d] crossed thread count high watermark (%d), EXC_RESOURCE "
2709 		    "suppressed by a boot-arg.\n", procname, pid, thread_count);
2710 		return;
2711 	}
2712 
2713 	if (!os_variant_has_internal_diagnostics("com.apple.xnu")) {
2714 		printf("process %s[%d] crossed thread count high watermark (%d), EXC_RESOURCE "
2715 		    "suppressed, internal diagnostics disabled.\n", procname, pid, thread_count);
2716 		return;
2717 	}
2718 
2719 	if (disable_exc_resource_during_audio && audio_active) {
2720 		printf("process %s[%d] crossed thread count high watermark (%d), EXC_RESOURCE "
2721 		    "suppressed due to audio playback.\n", procname, pid, thread_count);
2722 		return;
2723 	}
2724 
2725 	if (!exc_via_corpse_forking) {
2726 		printf("process %s[%d] crossed thread count high watermark (%d), EXC_RESOURCE "
2727 		    "suppressed due to corpse forking being disabled.\n", procname, pid,
2728 		    thread_count);
2729 		return;
2730 	}
2731 
2732 skip_checks:
2733 	printf("process %s[%d] crossed thread count high watermark (%d), sending "
2734 	    "EXC_RESOURCE\n", procname, pid, thread_count);
2735 
2736 	EXC_RESOURCE_ENCODE_TYPE(code[0], RESOURCE_TYPE_THREADS);
2737 	EXC_RESOURCE_ENCODE_FLAVOR(code[0], FLAVOR_THREADS_HIGH_WATERMARK);
2738 	EXC_RESOURCE_THREADS_ENCODE_THREADS(code[0], thread_count);
2739 
2740 	task_enqueue_exception_with_corpse(task, EXC_RESOURCE, code, EXCEPTION_CODE_MAX, NULL, FALSE);
2741 }
2742 #endif /* DEVELOPMENT || DEBUG */
2743 
2744 void
thread_update_io_stats(thread_t thread,int size,int io_flags)2745 thread_update_io_stats(thread_t thread, int size, int io_flags)
2746 {
2747 	task_t task = get_threadtask(thread);
2748 	int io_tier;
2749 
2750 	if (thread->thread_io_stats == NULL || task->task_io_stats == NULL) {
2751 		return;
2752 	}
2753 
2754 	if (io_flags & DKIO_READ) {
2755 		UPDATE_IO_STATS(thread->thread_io_stats->disk_reads, size);
2756 		UPDATE_IO_STATS_ATOMIC(task->task_io_stats->disk_reads, size);
2757 	}
2758 
2759 	if (io_flags & DKIO_META) {
2760 		UPDATE_IO_STATS(thread->thread_io_stats->metadata, size);
2761 		UPDATE_IO_STATS_ATOMIC(task->task_io_stats->metadata, size);
2762 	}
2763 
2764 	if (io_flags & DKIO_PAGING) {
2765 		UPDATE_IO_STATS(thread->thread_io_stats->paging, size);
2766 		UPDATE_IO_STATS_ATOMIC(task->task_io_stats->paging, size);
2767 	}
2768 
2769 	io_tier = ((io_flags & DKIO_TIER_MASK) >> DKIO_TIER_SHIFT);
2770 	assert(io_tier < IO_NUM_PRIORITIES);
2771 
2772 	UPDATE_IO_STATS(thread->thread_io_stats->io_priority[io_tier], size);
2773 	UPDATE_IO_STATS_ATOMIC(task->task_io_stats->io_priority[io_tier], size);
2774 
2775 	/* Update Total I/O Counts */
2776 	UPDATE_IO_STATS(thread->thread_io_stats->total_io, size);
2777 	UPDATE_IO_STATS_ATOMIC(task->task_io_stats->total_io, size);
2778 
2779 	if (!(io_flags & DKIO_READ)) {
2780 		DTRACE_IO3(physical_writes, struct task *, task, uint32_t, size, int, io_flags);
2781 		ledger_credit(task->ledger, task_ledgers.physical_writes, size);
2782 	}
2783 }
2784 
2785 static void
init_thread_ledgers(void)2786 init_thread_ledgers(void)
2787 {
2788 	ledger_template_t t;
2789 	int idx;
2790 
2791 	assert(thread_ledger_template == NULL);
2792 
2793 	if ((t = ledger_template_create("Per-thread ledger")) == NULL) {
2794 		panic("couldn't create thread ledger template");
2795 	}
2796 
2797 	if ((idx = ledger_entry_add(t, "cpu_time", "sched", "ns")) < 0) {
2798 		panic("couldn't create cpu_time entry for thread ledger template");
2799 	}
2800 
2801 	if (ledger_set_callback(t, idx, thread_cputime_callback, NULL, NULL) < 0) {
2802 		panic("couldn't set thread ledger callback for cpu_time entry");
2803 	}
2804 
2805 	thread_ledgers.cpu_time = idx;
2806 
2807 	ledger_template_complete(t);
2808 	thread_ledger_template = t;
2809 }
2810 
2811 /*
2812  * Returns the amount of (abs) CPU time that remains before the limit would be
2813  * hit or the amount of time left in the current interval, whichever is smaller.
2814  * This value changes as CPU time is consumed and the ledgers refilled.
2815  * Used to limit the quantum of a thread.
2816  */
2817 uint64_t
thread_cpulimit_remaining(uint64_t now)2818 thread_cpulimit_remaining(uint64_t now)
2819 {
2820 	thread_t thread = current_thread();
2821 
2822 	if ((thread->options &
2823 	    (TH_OPT_PROC_CPULIMIT | TH_OPT_PRVT_CPULIMIT)) == 0) {
2824 		return UINT64_MAX;
2825 	}
2826 
2827 	/* Amount of time left in the current interval. */
2828 	const uint64_t interval_remaining =
2829 	    ledger_get_interval_remaining(thread->t_threadledger, thread_ledgers.cpu_time, now);
2830 
2831 	/* Amount that can be spent until the limit is hit. */
2832 	const uint64_t remaining =
2833 	    ledger_get_remaining(thread->t_threadledger, thread_ledgers.cpu_time);
2834 
2835 	return MIN(interval_remaining, remaining);
2836 }
2837 
2838 /*
2839  * Returns true if a new interval should be started.
2840  */
2841 bool
thread_cpulimit_interval_has_expired(uint64_t now)2842 thread_cpulimit_interval_has_expired(uint64_t now)
2843 {
2844 	thread_t thread = current_thread();
2845 
2846 	if ((thread->options &
2847 	    (TH_OPT_PROC_CPULIMIT | TH_OPT_PRVT_CPULIMIT)) == 0) {
2848 		return false;
2849 	}
2850 
2851 	return ledger_get_interval_remaining(thread->t_threadledger,
2852 	           thread_ledgers.cpu_time, now) == 0;
2853 }
2854 
2855 /*
2856  * Balances the ledger and sets the last refill time to `now`.
2857  */
2858 void
thread_cpulimit_restart(uint64_t now)2859 thread_cpulimit_restart(uint64_t now)
2860 {
2861 	thread_t thread = current_thread();
2862 
2863 	assert3u(thread->options & (TH_OPT_PROC_CPULIMIT | TH_OPT_PRVT_CPULIMIT), !=, 0);
2864 
2865 	ledger_restart(thread->t_threadledger, thread_ledgers.cpu_time, now);
2866 }
2867 
2868 /*
2869  * Returns currently applied CPU usage limit, or 0/0 if none is applied.
2870  */
2871 int
thread_get_cpulimit(int * action,uint8_t * percentage,uint64_t * interval_ns)2872 thread_get_cpulimit(int *action, uint8_t *percentage, uint64_t *interval_ns)
2873 {
2874 	int64_t         abstime = 0;
2875 	uint64_t        limittime = 0;
2876 	thread_t        thread = current_thread();
2877 
2878 	*percentage  = 0;
2879 	*interval_ns = 0;
2880 	*action      = 0;
2881 
2882 	if (thread->t_threadledger == LEDGER_NULL) {
2883 		/*
2884 		 * This thread has no per-thread ledger, so it can't possibly
2885 		 * have a CPU limit applied.
2886 		 */
2887 		return KERN_SUCCESS;
2888 	}
2889 
2890 	ledger_get_period(thread->t_threadledger, thread_ledgers.cpu_time, interval_ns);
2891 	ledger_get_limit(thread->t_threadledger, thread_ledgers.cpu_time, &abstime);
2892 
2893 	if ((abstime == LEDGER_LIMIT_INFINITY) || (*interval_ns == 0)) {
2894 		/*
2895 		 * This thread's CPU time ledger has no period or limit; so it
2896 		 * doesn't have a CPU limit applied.
2897 		 */
2898 		return KERN_SUCCESS;
2899 	}
2900 
2901 	/*
2902 	 * This calculation is the converse to the one in thread_set_cpulimit().
2903 	 */
2904 	absolutetime_to_nanoseconds(abstime, &limittime);
2905 	*percentage = (uint8_t)((limittime * 100ULL) / *interval_ns);
2906 	assert(*percentage <= 100);
2907 
2908 	if (thread->options & TH_OPT_PROC_CPULIMIT) {
2909 		assert((thread->options & TH_OPT_PRVT_CPULIMIT) == 0);
2910 
2911 		*action = THREAD_CPULIMIT_BLOCK;
2912 	} else if (thread->options & TH_OPT_PRVT_CPULIMIT) {
2913 		assert((thread->options & TH_OPT_PROC_CPULIMIT) == 0);
2914 
2915 		*action = THREAD_CPULIMIT_EXCEPTION;
2916 	} else {
2917 		*action = THREAD_CPULIMIT_DISABLE;
2918 	}
2919 
2920 	return KERN_SUCCESS;
2921 }
2922 
2923 /*
2924  * Set CPU usage limit on a thread.
2925  */
2926 int
thread_set_cpulimit(int action,uint8_t percentage,uint64_t interval_ns)2927 thread_set_cpulimit(int action, uint8_t percentage, uint64_t interval_ns)
2928 {
2929 	thread_t        thread = current_thread();
2930 	ledger_t        l;
2931 	uint64_t        limittime = 0;
2932 	uint64_t        abstime = 0;
2933 
2934 	assert(percentage <= 100);
2935 	assert(percentage > 0 || action == THREAD_CPULIMIT_DISABLE);
2936 
2937 	/*
2938 	 * Disallow any change to the CPU limit if the TH_OPT_FORCED_LEDGER
2939 	 * flag is set.
2940 	 */
2941 	if ((thread->options & TH_OPT_FORCED_LEDGER) != 0) {
2942 		return KERN_FAILURE;
2943 	}
2944 
2945 	if (action == THREAD_CPULIMIT_DISABLE) {
2946 		/*
2947 		 * Remove CPU limit, if any exists.
2948 		 */
2949 		if (thread->t_threadledger != LEDGER_NULL) {
2950 			l = thread->t_threadledger;
2951 			ledger_set_limit(l, thread_ledgers.cpu_time, LEDGER_LIMIT_INFINITY, 0);
2952 			ledger_set_action(l, thread_ledgers.cpu_time, LEDGER_ACTION_IGNORE);
2953 			thread->options &= ~(TH_OPT_PROC_CPULIMIT | TH_OPT_PRVT_CPULIMIT);
2954 		}
2955 
2956 		return 0;
2957 	}
2958 
2959 	if (interval_ns < MINIMUM_CPULIMIT_INTERVAL_MS * NSEC_PER_MSEC) {
2960 		return KERN_INVALID_ARGUMENT;
2961 	}
2962 
2963 	l = thread->t_threadledger;
2964 	if (l == LEDGER_NULL) {
2965 		/*
2966 		 * This thread doesn't yet have a per-thread ledger; so create one with the CPU time entry active.
2967 		 */
2968 		if ((l = ledger_instantiate(thread_ledger_template, LEDGER_CREATE_INACTIVE_ENTRIES)) == LEDGER_NULL) {
2969 			return KERN_RESOURCE_SHORTAGE;
2970 		}
2971 
2972 		/*
2973 		 * We are the first to create this thread's ledger, so only activate our entry.
2974 		 */
2975 		ledger_entry_setactive(l, thread_ledgers.cpu_time);
2976 		thread->t_threadledger = l;
2977 	}
2978 
2979 	/*
2980 	 * The limit is specified as a percentage of CPU over an interval in nanoseconds.
2981 	 * Calculate the amount of CPU time that the thread needs to consume in order to hit the limit.
2982 	 */
2983 	limittime = (interval_ns * percentage) / 100;
2984 	nanoseconds_to_absolutetime(limittime, &abstime);
2985 	ledger_set_limit(l, thread_ledgers.cpu_time, abstime, cpumon_ustackshots_trigger_pct);
2986 	/*
2987 	 * Refill the thread's allotted CPU time every interval_ns nanoseconds.
2988 	 */
2989 	ledger_set_period(l, thread_ledgers.cpu_time, interval_ns);
2990 
2991 	if (action == THREAD_CPULIMIT_EXCEPTION) {
2992 		/*
2993 		 * We don't support programming the CPU usage monitor on a task if any of its
2994 		 * threads have a per-thread blocking CPU limit configured.
2995 		 */
2996 		if (thread->options & TH_OPT_PRVT_CPULIMIT) {
2997 			panic("CPU usage monitor activated, but blocking thread limit exists");
2998 		}
2999 
3000 		/*
3001 		 * Make a note that this thread's CPU limit is being used for the task-wide CPU
3002 		 * usage monitor. We don't have to arm the callback which will trigger the
3003 		 * exception, because that was done for us in ledger_instantiate (because the
3004 		 * ledger template used has a default callback).
3005 		 */
3006 		thread->options |= TH_OPT_PROC_CPULIMIT;
3007 	} else {
3008 		/*
3009 		 * We deliberately override any CPU limit imposed by a task-wide limit (eg
3010 		 * CPU usage monitor).
3011 		 */
3012 		thread->options &= ~TH_OPT_PROC_CPULIMIT;
3013 
3014 		thread->options |= TH_OPT_PRVT_CPULIMIT;
3015 		/* The per-thread ledger template by default has a callback for CPU time */
3016 		ledger_disable_callback(l, thread_ledgers.cpu_time);
3017 		ledger_set_action(l, thread_ledgers.cpu_time, LEDGER_ACTION_BLOCK);
3018 	}
3019 
3020 	return 0;
3021 }
3022 
3023 void
thread_sched_call(thread_t thread,sched_call_t call)3024 thread_sched_call(
3025 	thread_t                thread,
3026 	sched_call_t    call)
3027 {
3028 	assert((thread->state & TH_WAIT_REPORT) == 0);
3029 	thread->sched_call = call;
3030 }
3031 
3032 uint64_t
thread_tid(thread_t thread)3033 thread_tid(
3034 	thread_t        thread)
3035 {
3036 	return thread != THREAD_NULL? thread->thread_id: 0;
3037 }
3038 
3039 uint64_t
uthread_tid(struct uthread * uth)3040 uthread_tid(
3041 	struct uthread *uth)
3042 {
3043 	if (uth) {
3044 		return thread_tid(get_machthread(uth));
3045 	}
3046 	return 0;
3047 }
3048 
3049 uint16_t
thread_set_tag(thread_t th,uint16_t tag)3050 thread_set_tag(thread_t th, uint16_t tag)
3051 {
3052 	return thread_set_tag_internal(th, tag);
3053 }
3054 
3055 uint16_t
thread_get_tag(thread_t th)3056 thread_get_tag(thread_t th)
3057 {
3058 	return thread_get_tag_internal(th);
3059 }
3060 
3061 uint64_t
thread_last_run_time(thread_t th)3062 thread_last_run_time(thread_t th)
3063 {
3064 	return th->last_run_time;
3065 }
3066 
3067 /*
3068  * Shared resource contention management
3069  *
3070  * The scheduler attempts to load balance the shared resource intensive
3071  * workloads across clusters to ensure that the resource is not heavily
3072  * contended. The kernel relies on external agents (userspace or
3073  * performance controller) to identify shared resource heavy threads.
3074  * The load balancing is achieved based on the scheduler configuration
3075  * enabled on the platform.
3076  */
3077 
3078 
3079 #if CONFIG_SCHED_EDGE
3080 
3081 /*
3082  * On the Edge scheduler, the load balancing is achieved by looking
3083  * at cluster level shared resource loads and migrating resource heavy
3084  * threads dynamically to under utilized cluster. Therefore, when a
3085  * thread is indicated as a resource heavy thread, the policy set
3086  * routine simply adds a flag to the thread which is looked at by
3087  * the scheduler on thread migration decisions.
3088  */
3089 
3090 boolean_t
thread_shared_rsrc_policy_get(thread_t thread,cluster_shared_rsrc_type_t type)3091 thread_shared_rsrc_policy_get(thread_t thread, cluster_shared_rsrc_type_t type)
3092 {
3093 	return thread->th_shared_rsrc_heavy_user[type] || thread->th_shared_rsrc_heavy_perf_control[type];
3094 }
3095 
3096 __options_decl(sched_edge_rsrc_heavy_thread_state, uint32_t, {
3097 	SCHED_EDGE_RSRC_HEAVY_THREAD_SET = 1,
3098 	SCHED_EDGE_RSRC_HEAVY_THREAD_CLR = 2,
3099 });
3100 
3101 kern_return_t
thread_shared_rsrc_policy_set(thread_t thread,__unused uint32_t index,cluster_shared_rsrc_type_t type,shared_rsrc_policy_agent_t agent)3102 thread_shared_rsrc_policy_set(thread_t thread, __unused uint32_t index, cluster_shared_rsrc_type_t type, shared_rsrc_policy_agent_t agent)
3103 {
3104 	spl_t s = splsched();
3105 	thread_lock(thread);
3106 
3107 	bool user = (agent == SHARED_RSRC_POLICY_AGENT_DISPATCH) || (agent == SHARED_RSRC_POLICY_AGENT_SYSCTL);
3108 	bool *thread_flags = (user) ? thread->th_shared_rsrc_heavy_user : thread->th_shared_rsrc_heavy_perf_control;
3109 	if (thread_flags[type]) {
3110 		thread_unlock(thread);
3111 		splx(s);
3112 		return KERN_FAILURE;
3113 	}
3114 
3115 	thread_flags[type] = true;
3116 	thread_unlock(thread);
3117 	splx(s);
3118 
3119 	KDBG(MACHDBG_CODE(DBG_MACH_SCHED_CLUTCH, MACH_SCHED_EDGE_RSRC_HEAVY_THREAD) | DBG_FUNC_NONE, SCHED_EDGE_RSRC_HEAVY_THREAD_SET, thread_tid(thread), type, agent);
3120 	if (thread == current_thread()) {
3121 		if (agent == SHARED_RSRC_POLICY_AGENT_PERFCTL_QUANTUM) {
3122 			ast_on(AST_PREEMPT);
3123 		} else {
3124 			assert(agent != SHARED_RSRC_POLICY_AGENT_PERFCTL_CSW);
3125 			thread_block(THREAD_CONTINUE_NULL);
3126 		}
3127 	}
3128 	return KERN_SUCCESS;
3129 }
3130 
3131 kern_return_t
thread_shared_rsrc_policy_clear(thread_t thread,cluster_shared_rsrc_type_t type,shared_rsrc_policy_agent_t agent)3132 thread_shared_rsrc_policy_clear(thread_t thread, cluster_shared_rsrc_type_t type, shared_rsrc_policy_agent_t agent)
3133 {
3134 	spl_t s = splsched();
3135 	thread_lock(thread);
3136 
3137 	bool user = (agent == SHARED_RSRC_POLICY_AGENT_DISPATCH) || (agent == SHARED_RSRC_POLICY_AGENT_SYSCTL);
3138 	bool *thread_flags = (user) ? thread->th_shared_rsrc_heavy_user : thread->th_shared_rsrc_heavy_perf_control;
3139 	if (!thread_flags[type]) {
3140 		thread_unlock(thread);
3141 		splx(s);
3142 		return KERN_FAILURE;
3143 	}
3144 
3145 	thread_flags[type] = false;
3146 	thread_unlock(thread);
3147 	splx(s);
3148 
3149 	KDBG(MACHDBG_CODE(DBG_MACH_SCHED_CLUTCH, MACH_SCHED_EDGE_RSRC_HEAVY_THREAD) | DBG_FUNC_NONE, SCHED_EDGE_RSRC_HEAVY_THREAD_CLR, thread_tid(thread), type, agent);
3150 	if (thread == current_thread()) {
3151 		if (agent == SHARED_RSRC_POLICY_AGENT_PERFCTL_QUANTUM) {
3152 			ast_on(AST_PREEMPT);
3153 		} else {
3154 			assert(agent != SHARED_RSRC_POLICY_AGENT_PERFCTL_CSW);
3155 			thread_block(THREAD_CONTINUE_NULL);
3156 		}
3157 	}
3158 	return KERN_SUCCESS;
3159 }
3160 
3161 #else /* CONFIG_SCHED_EDGE */
3162 
3163 /*
3164  * On non-Edge schedulers, the shared resource contention
3165  * is managed by simply binding threads to specific clusters
3166  * based on the worker index passed by the agents marking
3167  * this thread as resource heavy threads. The thread binding
3168  * approach does not provide any rebalancing opportunities;
3169  * it can also suffer from scheduling delays if the cluster
3170  * where the thread is bound is contended.
3171  */
3172 
3173 boolean_t
thread_shared_rsrc_policy_get(__unused thread_t thread,__unused cluster_shared_rsrc_type_t type)3174 thread_shared_rsrc_policy_get(__unused thread_t thread, __unused cluster_shared_rsrc_type_t type)
3175 {
3176 	return false;
3177 }
3178 
3179 kern_return_t
thread_shared_rsrc_policy_set(thread_t thread,uint32_t index,__unused cluster_shared_rsrc_type_t type,__unused shared_rsrc_policy_agent_t agent)3180 thread_shared_rsrc_policy_set(thread_t thread, uint32_t index, __unused cluster_shared_rsrc_type_t type, __unused shared_rsrc_policy_agent_t agent)
3181 {
3182 	return thread_bind_cluster_id(thread, index, THREAD_BIND_SOFT | THREAD_BIND_ELIGIBLE_ONLY);
3183 }
3184 
3185 kern_return_t
thread_shared_rsrc_policy_clear(thread_t thread,__unused cluster_shared_rsrc_type_t type,__unused shared_rsrc_policy_agent_t agent)3186 thread_shared_rsrc_policy_clear(thread_t thread, __unused cluster_shared_rsrc_type_t type, __unused shared_rsrc_policy_agent_t agent)
3187 {
3188 	return thread_bind_cluster_id(thread, 0, THREAD_UNBIND);
3189 }
3190 
3191 #endif /* CONFIG_SCHED_EDGE */
3192 
3193 uint64_t
thread_dispatchqaddr(thread_t thread)3194 thread_dispatchqaddr(
3195 	thread_t                thread)
3196 {
3197 	uint64_t        dispatchqueue_addr;
3198 	uint64_t        thread_handle;
3199 	task_t          task;
3200 
3201 	if (thread == THREAD_NULL) {
3202 		return 0;
3203 	}
3204 
3205 	thread_handle = thread->machine.cthread_self;
3206 	if (thread_handle == 0) {
3207 		return 0;
3208 	}
3209 
3210 	task = get_threadtask(thread);
3211 	void *bsd_info = get_bsdtask_info(task);
3212 	if (thread->inspection == TRUE) {
3213 		dispatchqueue_addr = thread_handle + get_task_dispatchqueue_offset(task);
3214 	} else if (bsd_info) {
3215 		dispatchqueue_addr = thread_handle + get_dispatchqueue_offset_from_proc(bsd_info);
3216 	} else {
3217 		dispatchqueue_addr = 0;
3218 	}
3219 
3220 	return dispatchqueue_addr;
3221 }
3222 
3223 
3224 uint64_t
thread_wqquantum_addr(thread_t thread)3225 thread_wqquantum_addr(thread_t thread)
3226 {
3227 	uint64_t thread_handle;
3228 	task_t   task;
3229 
3230 	if (thread == THREAD_NULL) {
3231 		return 0;
3232 	}
3233 
3234 	thread_handle = thread->machine.cthread_self;
3235 	if (thread_handle == 0) {
3236 		return 0;
3237 	}
3238 	task = get_threadtask(thread);
3239 
3240 	uint64_t wq_quantum_expiry_offset = get_wq_quantum_offset_from_proc(get_bsdtask_info(task));
3241 	if (wq_quantum_expiry_offset == 0) {
3242 		return 0;
3243 	}
3244 
3245 	return wq_quantum_expiry_offset + thread_handle;
3246 }
3247 
3248 uint64_t
thread_rettokern_addr(thread_t thread)3249 thread_rettokern_addr(
3250 	thread_t                thread)
3251 {
3252 	uint64_t        rettokern_addr;
3253 	uint64_t        rettokern_offset;
3254 	uint64_t        thread_handle;
3255 	task_t          task;
3256 	void            *bsd_info;
3257 
3258 	if (thread == THREAD_NULL) {
3259 		return 0;
3260 	}
3261 
3262 	thread_handle = thread->machine.cthread_self;
3263 	if (thread_handle == 0) {
3264 		return 0;
3265 	}
3266 	task = get_threadtask(thread);
3267 	bsd_info = get_bsdtask_info(task);
3268 
3269 	if (bsd_info) {
3270 		rettokern_offset = get_return_to_kernel_offset_from_proc(bsd_info);
3271 
3272 		/* Return 0 if return to kernel offset is not initialized. */
3273 		if (rettokern_offset == 0) {
3274 			rettokern_addr = 0;
3275 		} else {
3276 			rettokern_addr = thread_handle + rettokern_offset;
3277 		}
3278 	} else {
3279 		rettokern_addr = 0;
3280 	}
3281 
3282 	return rettokern_addr;
3283 }
3284 
3285 /*
3286  * Export routines to other components for things that are done as macros
3287  * within the osfmk component.
3288  */
3289 
3290 void
thread_mtx_lock(thread_t thread)3291 thread_mtx_lock(thread_t thread)
3292 {
3293 	lck_mtx_lock(&thread->mutex);
3294 }
3295 
3296 void
thread_mtx_unlock(thread_t thread)3297 thread_mtx_unlock(thread_t thread)
3298 {
3299 	lck_mtx_unlock(&thread->mutex);
3300 }
3301 
3302 void
thread_reference(thread_t thread)3303 thread_reference(
3304 	thread_t        thread)
3305 {
3306 	if (thread != THREAD_NULL) {
3307 		zone_id_require(ZONE_ID_THREAD, sizeof(struct thread), thread);
3308 		os_ref_retain_raw(&thread->ref_count, &thread_refgrp);
3309 	}
3310 }
3311 
3312 void
thread_require(thread_t thread)3313 thread_require(thread_t thread)
3314 {
3315 	zone_id_require(ZONE_ID_THREAD, sizeof(struct thread), thread);
3316 }
3317 
3318 #undef thread_should_halt
3319 
3320 boolean_t
thread_should_halt(thread_t th)3321 thread_should_halt(
3322 	thread_t                th)
3323 {
3324 	return thread_should_halt_fast(th);
3325 }
3326 
3327 /*
3328  * thread_set_voucher_name - reset the voucher port name bound to this thread
3329  *
3330  * Conditions:  nothing locked
3331  */
3332 
3333 kern_return_t
thread_set_voucher_name(mach_port_name_t voucher_name)3334 thread_set_voucher_name(mach_port_name_t voucher_name)
3335 {
3336 	thread_t thread = current_thread();
3337 	ipc_voucher_t new_voucher = IPC_VOUCHER_NULL;
3338 	ipc_voucher_t voucher;
3339 	ledger_t bankledger = NULL;
3340 	struct thread_group *banktg = NULL;
3341 	uint32_t persona_id = 0;
3342 
3343 	if (MACH_PORT_DEAD == voucher_name) {
3344 		return KERN_INVALID_RIGHT;
3345 	}
3346 
3347 	/*
3348 	 * agressively convert to voucher reference
3349 	 */
3350 	if (MACH_PORT_VALID(voucher_name)) {
3351 		new_voucher = convert_port_name_to_voucher(voucher_name);
3352 		if (IPC_VOUCHER_NULL == new_voucher) {
3353 			return KERN_INVALID_ARGUMENT;
3354 		}
3355 	}
3356 	bank_get_bank_ledger_thread_group_and_persona(new_voucher, &bankledger, &banktg, &persona_id);
3357 
3358 	thread_mtx_lock(thread);
3359 	voucher = thread->ith_voucher;
3360 	thread->ith_voucher_name = voucher_name;
3361 	thread->ith_voucher = new_voucher;
3362 	thread_mtx_unlock(thread);
3363 
3364 	bank_swap_thread_bank_ledger(thread, bankledger);
3365 #if CONFIG_THREAD_GROUPS
3366 	thread_group_set_bank(thread, banktg);
3367 #endif /* CONFIG_THREAD_GROUPS */
3368 
3369 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
3370 	    MACHDBG_CODE(DBG_MACH_IPC, MACH_THREAD_SET_VOUCHER) | DBG_FUNC_NONE,
3371 	    (uintptr_t)thread_tid(thread),
3372 	    (uintptr_t)voucher_name,
3373 	    VM_KERNEL_ADDRPERM((uintptr_t)new_voucher),
3374 	    persona_id, 0);
3375 
3376 	if (IPC_VOUCHER_NULL != voucher) {
3377 		ipc_voucher_release(voucher);
3378 	}
3379 
3380 	return KERN_SUCCESS;
3381 }
3382 
3383 /*
3384  *  thread_get_mach_voucher - return a voucher reference for the specified thread voucher
3385  *
3386  *  Conditions:  nothing locked
3387  *
3388  *  NOTE:       At the moment, there is no distinction between the current and effective
3389  *		vouchers because we only set them at the thread level currently.
3390  */
3391 kern_return_t
thread_get_mach_voucher(thread_act_t thread,mach_voucher_selector_t __unused which,ipc_voucher_t * voucherp)3392 thread_get_mach_voucher(
3393 	thread_act_t            thread,
3394 	mach_voucher_selector_t __unused which,
3395 	ipc_voucher_t           *voucherp)
3396 {
3397 	ipc_voucher_t           voucher;
3398 
3399 	if (THREAD_NULL == thread) {
3400 		return KERN_INVALID_ARGUMENT;
3401 	}
3402 
3403 	thread_mtx_lock(thread);
3404 	voucher = thread->ith_voucher;
3405 
3406 	if (IPC_VOUCHER_NULL != voucher) {
3407 		ipc_voucher_reference(voucher);
3408 		thread_mtx_unlock(thread);
3409 		*voucherp = voucher;
3410 		return KERN_SUCCESS;
3411 	}
3412 
3413 	thread_mtx_unlock(thread);
3414 
3415 	*voucherp = IPC_VOUCHER_NULL;
3416 	return KERN_SUCCESS;
3417 }
3418 
3419 /*
3420  *  thread_set_mach_voucher - set a voucher reference for the specified thread voucher
3421  *
3422  *  Conditions: callers holds a reference on the voucher.
3423  *		nothing locked.
3424  *
3425  *  We grab another reference to the voucher and bind it to the thread.
3426  *  The old voucher reference associated with the thread is
3427  *  discarded.
3428  */
3429 kern_return_t
thread_set_mach_voucher(thread_t thread,ipc_voucher_t voucher)3430 thread_set_mach_voucher(
3431 	thread_t                thread,
3432 	ipc_voucher_t           voucher)
3433 {
3434 	ipc_voucher_t old_voucher;
3435 	ledger_t bankledger = NULL;
3436 	struct thread_group *banktg = NULL;
3437 	uint32_t persona_id = 0;
3438 
3439 	if (THREAD_NULL == thread) {
3440 		return KERN_INVALID_ARGUMENT;
3441 	}
3442 
3443 	bank_get_bank_ledger_thread_group_and_persona(voucher, &bankledger, &banktg, &persona_id);
3444 
3445 	thread_mtx_lock(thread);
3446 	/*
3447 	 * Once the thread is started, we will look at `ith_voucher` without
3448 	 * holding any lock.
3449 	 *
3450 	 * Setting the voucher hence can only be done by current_thread() or
3451 	 * before it started. "started" flips under the thread mutex and must be
3452 	 * tested under it too.
3453 	 */
3454 	if (thread != current_thread() && thread->started) {
3455 		thread_mtx_unlock(thread);
3456 		return KERN_INVALID_ARGUMENT;
3457 	}
3458 
3459 	ipc_voucher_reference(voucher);
3460 	old_voucher = thread->ith_voucher;
3461 	thread->ith_voucher = voucher;
3462 	thread->ith_voucher_name = MACH_PORT_NULL;
3463 	thread_mtx_unlock(thread);
3464 
3465 	bank_swap_thread_bank_ledger(thread, bankledger);
3466 #if CONFIG_THREAD_GROUPS
3467 	thread_group_set_bank(thread, banktg);
3468 #endif /* CONFIG_THREAD_GROUPS */
3469 
3470 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
3471 	    MACHDBG_CODE(DBG_MACH_IPC, MACH_THREAD_SET_VOUCHER) | DBG_FUNC_NONE,
3472 	    (uintptr_t)thread_tid(thread),
3473 	    (uintptr_t)MACH_PORT_NULL,
3474 	    VM_KERNEL_ADDRPERM((uintptr_t)voucher),
3475 	    persona_id, 0);
3476 
3477 	ipc_voucher_release(old_voucher);
3478 
3479 	return KERN_SUCCESS;
3480 }
3481 
3482 /*
3483  *  thread_swap_mach_voucher - swap a voucher reference for the specified thread voucher
3484  *
3485  *  Conditions: callers holds a reference on the new and presumed old voucher(s).
3486  *		nothing locked.
3487  *
3488  *  This function is no longer supported.
3489  */
3490 kern_return_t
thread_swap_mach_voucher(__unused thread_t thread,__unused ipc_voucher_t new_voucher,ipc_voucher_t * in_out_old_voucher)3491 thread_swap_mach_voucher(
3492 	__unused thread_t               thread,
3493 	__unused ipc_voucher_t          new_voucher,
3494 	ipc_voucher_t                   *in_out_old_voucher)
3495 {
3496 	/*
3497 	 * Currently this function is only called from a MIG generated
3498 	 * routine which doesn't release the reference on the voucher
3499 	 * addressed by in_out_old_voucher. To avoid leaking this reference,
3500 	 * a call to release it has been added here.
3501 	 */
3502 	ipc_voucher_release(*in_out_old_voucher);
3503 	OS_ANALYZER_SUPPRESS("81787115") return KERN_NOT_SUPPORTED;
3504 }
3505 
3506 /*
3507  *  thread_get_current_voucher_origin_pid - get the pid of the originator of the current voucher.
3508  */
3509 kern_return_t
thread_get_current_voucher_origin_pid(int32_t * pid)3510 thread_get_current_voucher_origin_pid(
3511 	int32_t      *pid)
3512 {
3513 	return thread_get_voucher_origin_pid(current_thread(), pid);
3514 }
3515 
3516 /*
3517  *  thread_get_current_voucher_origin_pid - get the pid of the originator of the current voucher.
3518  */
3519 kern_return_t
thread_get_voucher_origin_pid(thread_t thread,int32_t * pid)3520 thread_get_voucher_origin_pid(thread_t thread, int32_t *pid)
3521 {
3522 	uint32_t buf_size = sizeof(*pid);
3523 	return mach_voucher_attr_command(thread->ith_voucher,
3524 	           MACH_VOUCHER_ATTR_KEY_BANK,
3525 	           BANK_ORIGINATOR_PID,
3526 	           NULL,
3527 	           0,
3528 	           (mach_voucher_attr_content_t)pid,
3529 	           &buf_size);
3530 }
3531 
3532 /*
3533  *  thread_get_current_voucher_proximate_pid - get the pid of the proximate process of the current voucher.
3534  */
3535 kern_return_t
thread_get_voucher_origin_proximate_pid(thread_t thread,int32_t * origin_pid,int32_t * proximate_pid)3536 thread_get_voucher_origin_proximate_pid(thread_t thread, int32_t *origin_pid, int32_t *proximate_pid)
3537 {
3538 	int32_t origin_proximate_pids[2] = { };
3539 	uint32_t buf_size = sizeof(origin_proximate_pids);
3540 	kern_return_t kr = mach_voucher_attr_command(thread->ith_voucher,
3541 	    MACH_VOUCHER_ATTR_KEY_BANK,
3542 	    BANK_ORIGINATOR_PROXIMATE_PID,
3543 	    NULL,
3544 	    0,
3545 	    (mach_voucher_attr_content_t)origin_proximate_pids,
3546 	    &buf_size);
3547 	if (kr == KERN_SUCCESS) {
3548 		*origin_pid = origin_proximate_pids[0];
3549 		*proximate_pid = origin_proximate_pids[1];
3550 	}
3551 	return kr;
3552 }
3553 
3554 #if CONFIG_THREAD_GROUPS
3555 /*
3556  * Returns the current thread's voucher-carried thread group
3557  *
3558  * Reference is borrowed from this being the current voucher, so it does NOT
3559  * return a reference to the group.
3560  */
3561 struct thread_group *
thread_get_current_voucher_thread_group(thread_t thread)3562 thread_get_current_voucher_thread_group(thread_t thread)
3563 {
3564 	assert(thread == current_thread());
3565 
3566 	if (thread->ith_voucher == NULL) {
3567 		return NULL;
3568 	}
3569 
3570 	ledger_t bankledger = NULL;
3571 	struct thread_group *banktg = NULL;
3572 
3573 	bank_get_bank_ledger_thread_group_and_persona(thread->ith_voucher, &bankledger, &banktg, NULL);
3574 
3575 	return banktg;
3576 }
3577 
3578 #endif /* CONFIG_THREAD_GROUPS */
3579 
3580 #if CONFIG_COALITIONS
3581 
3582 uint64_t
thread_get_current_voucher_resource_coalition_id(thread_t thread)3583 thread_get_current_voucher_resource_coalition_id(thread_t thread)
3584 {
3585 	uint64_t id = 0;
3586 	assert(thread == current_thread());
3587 	if (thread->ith_voucher != NULL) {
3588 		id = bank_get_bank_ledger_resource_coalition_id(thread->ith_voucher);
3589 	}
3590 	return id;
3591 }
3592 
3593 #endif /* CONFIG_COALITIONS */
3594 
3595 extern struct workqueue *
3596 proc_get_wqptr(void *proc);
3597 
3598 static bool
task_supports_cooperative_workqueue(task_t task)3599 task_supports_cooperative_workqueue(task_t task)
3600 {
3601 	void *bsd_info = get_bsdtask_info(task);
3602 
3603 	assert(task == current_task());
3604 	if (bsd_info == NULL) {
3605 		return false;
3606 	}
3607 
3608 	uint64_t wq_quantum_expiry_offset = get_wq_quantum_offset_from_proc(bsd_info);
3609 	/* userspace may not yet have called workq_open yet */
3610 	struct workqueue *wq = proc_get_wqptr(bsd_info);
3611 
3612 	return (wq != NULL) && (wq_quantum_expiry_offset != 0);
3613 }
3614 
3615 /* Not safe to call from scheduler paths - should only be called on self */
3616 bool
thread_supports_cooperative_workqueue(thread_t thread)3617 thread_supports_cooperative_workqueue(thread_t thread)
3618 {
3619 	struct uthread *uth = get_bsdthread_info(thread);
3620 	task_t task = get_threadtask(thread);
3621 
3622 	assert(thread == current_thread());
3623 
3624 	return task_supports_cooperative_workqueue(task) &&
3625 	       bsdthread_part_of_cooperative_workqueue(uth);
3626 }
3627 
3628 static inline bool
thread_has_armed_workqueue_quantum(thread_t thread)3629 thread_has_armed_workqueue_quantum(thread_t thread)
3630 {
3631 	return thread->workq_quantum_deadline != 0;
3632 }
3633 
3634 /*
3635  * The workq quantum is a lazy timer that is evaluated at 2 specific times in
3636  * the scheduler:
3637  *
3638  * - context switch time
3639  * - scheduler quantum expiry time.
3640  *
3641  * We're currently expressing the workq quantum with a 0.5 scale factor of the
3642  * scheduler quantum. It is possible that if the workq quantum is rearmed
3643  * shortly after the scheduler quantum begins, we could have a large delay
3644  * between when the workq quantum next expires and when it actually is noticed.
3645  *
3646  * A potential future improvement for the wq quantum expiry logic is to compare
3647  * it to the next actual scheduler quantum deadline and expire it if it is
3648  * within a certain leeway.
3649  */
3650 static inline uint64_t
thread_workq_quantum_size(thread_t thread)3651 thread_workq_quantum_size(thread_t thread)
3652 {
3653 	return (uint64_t) (SCHED(initial_quantum_size)(thread) / 2);
3654 }
3655 
3656 /*
3657  * Always called by thread on itself - either at AST boundary after processing
3658  * an existing quantum expiry, or when a new quantum is armed before the thread
3659  * goes out to userspace to handle a thread request
3660  */
3661 void
thread_arm_workqueue_quantum(thread_t thread)3662 thread_arm_workqueue_quantum(thread_t thread)
3663 {
3664 	/*
3665 	 * If the task is not opted into wq quantum notification, or if the thread
3666 	 * is not part of the cooperative workqueue, don't even bother with tracking
3667 	 * the quantum or calculating expiry
3668 	 */
3669 	if (!thread_supports_cooperative_workqueue(thread)) {
3670 		assert(thread->workq_quantum_deadline == 0);
3671 		return;
3672 	}
3673 
3674 	assert(current_thread() == thread);
3675 	assert(thread_get_tag(thread) & THREAD_TAG_WORKQUEUE);
3676 
3677 	uint64_t current_runtime = thread_get_runtime_self();
3678 	uint64_t deadline = thread_workq_quantum_size(thread) + current_runtime;
3679 
3680 	/*
3681 	 * The update of a workqueue quantum should always be followed by the update
3682 	 * of the AST - see explanation in kern/thread.h for synchronization of this
3683 	 * field
3684 	 */
3685 	thread->workq_quantum_deadline = deadline;
3686 
3687 	/* We're arming a new quantum, clear any previous expiry notification */
3688 	act_clear_astkevent(thread, AST_KEVENT_WORKQ_QUANTUM_EXPIRED);
3689 
3690 	WQ_TRACE(TRACE_wq_quantum_arm, current_runtime, deadline, 0, 0);
3691 
3692 	WORKQ_QUANTUM_HISTORY_WRITE_ENTRY(thread, thread->workq_quantum_deadline, true);
3693 }
3694 
3695 /* Called by a thread on itself when it is about to park */
3696 void
thread_disarm_workqueue_quantum(thread_t thread)3697 thread_disarm_workqueue_quantum(thread_t thread)
3698 {
3699 	/* The update of a workqueue quantum should always be followed by the update
3700 	 * of the AST - see explanation in kern/thread.h for synchronization of this
3701 	 * field */
3702 	thread->workq_quantum_deadline = 0;
3703 	act_clear_astkevent(thread, AST_KEVENT_WORKQ_QUANTUM_EXPIRED);
3704 
3705 	WQ_TRACE(TRACE_wq_quantum_disarm, 0, 0, 0, 0);
3706 
3707 	WORKQ_QUANTUM_HISTORY_WRITE_ENTRY(thread, thread->workq_quantum_deadline, false);
3708 }
3709 
3710 /* This is called at context switch time on a thread that may not be self,
3711  * and at AST time
3712  */
3713 bool
thread_has_expired_workqueue_quantum(thread_t thread,bool should_trace)3714 thread_has_expired_workqueue_quantum(thread_t thread, bool should_trace)
3715 {
3716 	if (!thread_has_armed_workqueue_quantum(thread)) {
3717 		return false;
3718 	}
3719 	/* We do not do a thread_get_runtime_self() here since this function is
3720 	 * called from context switch time or during scheduler quantum expiry and
3721 	 * therefore, we may not be evaluating it on the current thread/self.
3722 	 *
3723 	 * In addition, the timers on the thread have just been updated recently so
3724 	 * we don't need to update them again.
3725 	 */
3726 	uint64_t runtime = recount_thread_time_mach(thread);
3727 	bool expired = runtime > thread->workq_quantum_deadline;
3728 
3729 	if (expired && should_trace) {
3730 		WQ_TRACE(TRACE_wq_quantum_expired, runtime, thread->workq_quantum_deadline, 0, 0);
3731 	}
3732 
3733 	return expired;
3734 }
3735 
3736 /*
3737  * Called on a thread that is being context switched out or during quantum
3738  * expiry on self. Only called from scheduler paths.
3739  */
3740 void
thread_evaluate_workqueue_quantum_expiry(thread_t thread)3741 thread_evaluate_workqueue_quantum_expiry(thread_t thread)
3742 {
3743 	if (thread_has_expired_workqueue_quantum(thread, true)) {
3744 		act_set_astkevent(thread, AST_KEVENT_WORKQ_QUANTUM_EXPIRED);
3745 	}
3746 }
3747 
3748 boolean_t
thread_has_thread_name(thread_t th)3749 thread_has_thread_name(thread_t th)
3750 {
3751 	if (th) {
3752 		return bsd_hasthreadname(get_bsdthread_info(th));
3753 	}
3754 
3755 	/*
3756 	 * This is an odd case; clients may set the thread name based on the lack of
3757 	 * a name, but in this context there is no uthread to attach the name to.
3758 	 */
3759 	return FALSE;
3760 }
3761 
3762 void
thread_set_thread_name(thread_t th,const char * name)3763 thread_set_thread_name(thread_t th, const char* name)
3764 {
3765 	if (th && name) {
3766 		bsd_setthreadname(get_bsdthread_info(th), thread_tid(th), name);
3767 	}
3768 }
3769 
3770 void
thread_get_thread_name(thread_t th,char * name)3771 thread_get_thread_name(thread_t th, char* name)
3772 {
3773 	if (!name) {
3774 		return;
3775 	}
3776 	if (th) {
3777 		bsd_getthreadname(get_bsdthread_info(th), name);
3778 	} else {
3779 		name[0] = '\0';
3780 	}
3781 }
3782 
3783 processor_t
thread_get_runq(thread_t thread)3784 thread_get_runq(thread_t thread)
3785 {
3786 	thread_lock_assert(thread, LCK_ASSERT_OWNED);
3787 	processor_t runq = thread->__runq.runq;
3788 	os_atomic_thread_fence(acquire);
3789 	return runq;
3790 }
3791 
3792 processor_t
thread_get_runq_locked(thread_t thread)3793 thread_get_runq_locked(thread_t thread)
3794 {
3795 	thread_lock_assert(thread, LCK_ASSERT_OWNED);
3796 	processor_t runq = thread->__runq.runq;
3797 	if (runq != PROCESSOR_NULL) {
3798 		pset_assert_locked(runq->processor_set);
3799 	}
3800 	return runq;
3801 }
3802 
3803 void
thread_set_runq_locked(thread_t thread,processor_t new_runq)3804 thread_set_runq_locked(thread_t thread, processor_t new_runq)
3805 {
3806 	thread_lock_assert(thread, LCK_ASSERT_OWNED);
3807 	pset_assert_locked(new_runq->processor_set);
3808 	thread_assert_runq_null(thread);
3809 	thread->__runq.runq = new_runq;
3810 }
3811 
3812 void
thread_clear_runq(thread_t thread)3813 thread_clear_runq(thread_t thread)
3814 {
3815 	thread_assert_runq_nonnull(thread);
3816 	os_atomic_thread_fence(release);
3817 	thread->__runq.runq = PROCESSOR_NULL;
3818 }
3819 
3820 void
thread_clear_runq_locked(thread_t thread)3821 thread_clear_runq_locked(thread_t thread)
3822 {
3823 	thread_lock_assert(thread, LCK_ASSERT_OWNED);
3824 	thread_assert_runq_nonnull(thread);
3825 	thread->__runq.runq = PROCESSOR_NULL;
3826 }
3827 
3828 void
thread_assert_runq_null(__assert_only thread_t thread)3829 thread_assert_runq_null(__assert_only thread_t thread)
3830 {
3831 	assert(thread->__runq.runq == PROCESSOR_NULL);
3832 }
3833 
3834 void
thread_assert_runq_nonnull(thread_t thread)3835 thread_assert_runq_nonnull(thread_t thread)
3836 {
3837 	pset_assert_locked(thread->__runq.runq->processor_set);
3838 	assert(thread->__runq.runq != PROCESSOR_NULL);
3839 }
3840 
3841 void
thread_set_honor_qlimit(thread_t thread)3842 thread_set_honor_qlimit(thread_t thread)
3843 {
3844 	thread->options |= TH_OPT_HONOR_QLIMIT;
3845 }
3846 
3847 void
thread_clear_honor_qlimit(thread_t thread)3848 thread_clear_honor_qlimit(thread_t thread)
3849 {
3850 	thread->options &= (~TH_OPT_HONOR_QLIMIT);
3851 }
3852 
3853 /*
3854  * thread_enable_send_importance - set/clear the SEND_IMPORTANCE thread option bit.
3855  */
3856 void
thread_enable_send_importance(thread_t thread,boolean_t enable)3857 thread_enable_send_importance(thread_t thread, boolean_t enable)
3858 {
3859 	if (enable == TRUE) {
3860 		thread->options |= TH_OPT_SEND_IMPORTANCE;
3861 	} else {
3862 		thread->options &= ~TH_OPT_SEND_IMPORTANCE;
3863 	}
3864 }
3865 
3866 kern_return_t
thread_get_ipc_propagate_attr(thread_t thread,struct thread_attr_for_ipc_propagation * attr)3867 thread_get_ipc_propagate_attr(thread_t thread, struct thread_attr_for_ipc_propagation *attr)
3868 {
3869 	int iotier;
3870 	int qos;
3871 
3872 	if (thread == NULL || attr == NULL) {
3873 		return KERN_INVALID_ARGUMENT;
3874 	}
3875 
3876 	iotier = proc_get_effective_thread_policy(thread, TASK_POLICY_IO);
3877 	qos = proc_get_effective_thread_policy(thread, TASK_POLICY_QOS);
3878 
3879 	if (!qos) {
3880 		qos = thread_user_promotion_qos_for_pri(thread->base_pri);
3881 	}
3882 
3883 	attr->tafip_iotier = iotier;
3884 	attr->tafip_qos = qos;
3885 
3886 	return KERN_SUCCESS;
3887 }
3888 
3889 /*
3890  * thread_set_allocation_name - .
3891  */
3892 
3893 kern_allocation_name_t
thread_set_allocation_name(kern_allocation_name_t new_name)3894 thread_set_allocation_name(kern_allocation_name_t new_name)
3895 {
3896 	kern_allocation_name_t ret;
3897 	thread_kernel_state_t kstate = thread_get_kernel_state(current_thread());
3898 	ret = kstate->allocation_name;
3899 	// fifo
3900 	if (!new_name || !kstate->allocation_name) {
3901 		kstate->allocation_name = new_name;
3902 	}
3903 	return ret;
3904 }
3905 
3906 void *
thread_iokit_tls_get(uint32_t index)3907 thread_iokit_tls_get(uint32_t index)
3908 {
3909 	assert(index < THREAD_SAVE_IOKIT_TLS_COUNT);
3910 	return current_thread()->saved.iokit.tls[index];
3911 }
3912 
3913 void
thread_iokit_tls_set(uint32_t index,void * data)3914 thread_iokit_tls_set(uint32_t index, void * data)
3915 {
3916 	assert(index < THREAD_SAVE_IOKIT_TLS_COUNT);
3917 	current_thread()->saved.iokit.tls[index] = data;
3918 }
3919 
3920 uint64_t
thread_get_last_wait_duration(thread_t thread)3921 thread_get_last_wait_duration(thread_t thread)
3922 {
3923 	return thread->last_made_runnable_time - thread->last_run_time;
3924 }
3925 
3926 integer_t
thread_kern_get_pri(thread_t thr)3927 thread_kern_get_pri(thread_t thr)
3928 {
3929 	return thr->base_pri;
3930 }
3931 
3932 void
thread_kern_set_pri(thread_t thr,integer_t pri)3933 thread_kern_set_pri(thread_t thr, integer_t pri)
3934 {
3935 	sched_set_kernel_thread_priority(thr, pri);
3936 }
3937 
3938 integer_t
thread_kern_get_kernel_maxpri(void)3939 thread_kern_get_kernel_maxpri(void)
3940 {
3941 	return MAXPRI_KERNEL;
3942 }
3943 /*
3944  *	thread_port_with_flavor_no_senders
3945  *
3946  *	Called whenever the Mach port system detects no-senders on
3947  *	the thread inspect or read port. These ports are allocated lazily and
3948  *	should be deallocated here when there are no senders remaining.
3949  */
3950 static void
thread_port_with_flavor_no_senders(ipc_port_t port,mach_port_mscount_t mscount __unused)3951 thread_port_with_flavor_no_senders(
3952 	ipc_port_t          port,
3953 	mach_port_mscount_t mscount __unused)
3954 {
3955 	thread_ro_t tro;
3956 	thread_t thread;
3957 	mach_thread_flavor_t flavor;
3958 	ipc_kobject_type_t kotype;
3959 
3960 	ip_mq_lock(port);
3961 	if (port->ip_srights > 0) {
3962 		ip_mq_unlock(port);
3963 		return;
3964 	}
3965 	kotype = ip_kotype(port);
3966 	assert((IKOT_THREAD_READ == kotype) || (IKOT_THREAD_INSPECT == kotype));
3967 	thread = ipc_kobject_get_locked(port, kotype);
3968 	if (thread != THREAD_NULL) {
3969 		thread_reference(thread);
3970 	}
3971 	ip_mq_unlock(port);
3972 
3973 	if (thread == THREAD_NULL) {
3974 		/* The thread is exiting or disabled; it will eventually deallocate the port */
3975 		return;
3976 	}
3977 
3978 	if (kotype == IKOT_THREAD_READ) {
3979 		flavor = THREAD_FLAVOR_READ;
3980 	} else {
3981 		flavor = THREAD_FLAVOR_INSPECT;
3982 	}
3983 
3984 	thread_mtx_lock(thread);
3985 	ip_mq_lock(port);
3986 
3987 	/*
3988 	 * If the port is no longer active, then ipc_thread_terminate() ran
3989 	 * and destroyed the kobject already. Just deallocate the task
3990 	 * ref we took and go away.
3991 	 *
3992 	 * It is also possible that several nsrequests are in flight,
3993 	 * only one shall NULL-out the port entry, and this is the one
3994 	 * that gets to dealloc the port.
3995 	 *
3996 	 * Check for a stale no-senders notification. A call to any function
3997 	 * that vends out send rights to this port could resurrect it between
3998 	 * this notification being generated and actually being handled here.
3999 	 */
4000 	tro = get_thread_ro(thread);
4001 	if (!ip_active(port) ||
4002 	    tro->tro_ports[flavor] != port ||
4003 	    port->ip_srights > 0) {
4004 		ip_mq_unlock(port);
4005 		thread_mtx_unlock(thread);
4006 		thread_deallocate(thread);
4007 		return;
4008 	}
4009 
4010 	assert(tro->tro_ports[flavor] == port);
4011 	zalloc_ro_clear_field(ZONE_ID_THREAD_RO, tro, tro_ports[flavor]);
4012 	thread_mtx_unlock(thread);
4013 
4014 	ipc_kobject_dealloc_port_and_unlock(port, 0, kotype);
4015 
4016 	thread_deallocate(thread);
4017 }
4018 
4019 /*
4020  * The 'thread_region_page_shift' is used by footprint
4021  * to specify the page size that it will use to
4022  * accomplish its accounting work on the task being
4023  * inspected. Since footprint uses a thread for each
4024  * task that it works on, we need to keep the page_shift
4025  * on a per-thread basis.
4026  */
4027 
4028 int
thread_self_region_page_shift(void)4029 thread_self_region_page_shift(void)
4030 {
4031 	/*
4032 	 * Return the page shift that this thread
4033 	 * would like to use for its accounting work.
4034 	 */
4035 	return current_thread()->thread_region_page_shift;
4036 }
4037 
4038 void
thread_self_region_page_shift_set(int pgshift)4039 thread_self_region_page_shift_set(
4040 	int pgshift)
4041 {
4042 	/*
4043 	 * Set the page shift that this thread
4044 	 * would like to use for its accounting work
4045 	 * when dealing with a task.
4046 	 */
4047 	current_thread()->thread_region_page_shift = pgshift;
4048 }
4049 
4050 __startup_func
4051 static void
ctid_table_init(void)4052 ctid_table_init(void)
4053 {
4054 	/*
4055 	 * Pretend the early boot setup didn't exist,
4056 	 * and pick a mangling nonce.
4057 	 */
4058 	*compact_id_resolve(&ctid_table, 0) = THREAD_NULL;
4059 	ctid_nonce = (uint32_t)early_random() & CTID_MASK;
4060 }
4061 
4062 
4063 /*
4064  * This maps the [0, CTID_MAX_THREAD_NUMBER] range
4065  * to [1, CTID_MAX_THREAD_NUMBER + 1 == CTID_MASK]
4066  * so that in mangled form, '0' is an invalid CTID.
4067  */
4068 static ctid_t
ctid_mangle(compact_id_t cid)4069 ctid_mangle(compact_id_t cid)
4070 {
4071 	return (cid == ctid_nonce ? CTID_MASK : cid) ^ ctid_nonce;
4072 }
4073 
4074 static compact_id_t
ctid_unmangle(ctid_t ctid)4075 ctid_unmangle(ctid_t ctid)
4076 {
4077 	ctid ^= ctid_nonce;
4078 	return ctid == CTID_MASK ? ctid_nonce : ctid;
4079 }
4080 
4081 void
ctid_table_add(thread_t thread)4082 ctid_table_add(thread_t thread)
4083 {
4084 	compact_id_t cid;
4085 
4086 	cid = compact_id_get(&ctid_table, CTID_MAX_THREAD_NUMBER, thread);
4087 	thread->ctid = ctid_mangle(cid);
4088 }
4089 
4090 void
ctid_table_remove(thread_t thread)4091 ctid_table_remove(thread_t thread)
4092 {
4093 	__assert_only thread_t value;
4094 
4095 	value = compact_id_put(&ctid_table, ctid_unmangle(thread->ctid));
4096 	assert3p(value, ==, thread);
4097 	thread->ctid = 0;
4098 }
4099 
4100 thread_t
ctid_get_thread_unsafe(ctid_t ctid)4101 ctid_get_thread_unsafe(ctid_t ctid)
4102 {
4103 	if (ctid) {
4104 		return *compact_id_resolve(&ctid_table, ctid_unmangle(ctid));
4105 	}
4106 	return THREAD_NULL;
4107 }
4108 
4109 thread_t
ctid_get_thread(ctid_t ctid)4110 ctid_get_thread(ctid_t ctid)
4111 {
4112 	thread_t thread = THREAD_NULL;
4113 
4114 	if (ctid) {
4115 		thread = *compact_id_resolve(&ctid_table, ctid_unmangle(ctid));
4116 		assert(thread && thread->ctid == ctid);
4117 	}
4118 	return thread;
4119 }
4120 
4121 ctid_t
thread_get_ctid(thread_t thread)4122 thread_get_ctid(thread_t thread)
4123 {
4124 	return thread->ctid;
4125 }
4126 
4127 /*
4128  * Adjust code signature dependent thread state.
4129  *
4130  * Called to allow code signature dependent adjustments to the thread
4131  * state. Note that this is usually called twice for the main thread:
4132  * Once at thread creation by thread_create, when the signature is
4133  * potentially not attached yet (which is usually the case for the
4134  * first/main thread of a task), and once after the task's signature
4135  * has actually been attached.
4136  *
4137  */
4138 kern_return_t
thread_process_signature(thread_t thread,task_t task)4139 thread_process_signature(thread_t thread, task_t task)
4140 {
4141 	return machine_thread_process_signature(thread, task);
4142 }
4143 
4144 #if CONFIG_SPTM
4145 
4146 void
thread_associate_txm_thread_stack(uintptr_t thread_stack)4147 thread_associate_txm_thread_stack(uintptr_t thread_stack)
4148 {
4149 	thread_t self = current_thread();
4150 
4151 	if (self->txm_thread_stack != 0) {
4152 		panic("attempted multiple TXM thread associations: %lu | %lu",
4153 		    self->txm_thread_stack, thread_stack);
4154 	}
4155 
4156 	self->txm_thread_stack = thread_stack;
4157 }
4158 
4159 void
thread_disassociate_txm_thread_stack(uintptr_t thread_stack)4160 thread_disassociate_txm_thread_stack(uintptr_t thread_stack)
4161 {
4162 	thread_t self = current_thread();
4163 
4164 	if (self->txm_thread_stack == 0) {
4165 		panic("attempted to disassociate non-existent TXM thread");
4166 	} else if (self->txm_thread_stack != thread_stack) {
4167 		panic("invalid disassociation for TXM thread: %lu | %lu",
4168 		    self->txm_thread_stack, thread_stack);
4169 	}
4170 
4171 	self->txm_thread_stack = 0;
4172 }
4173 
4174 uintptr_t
thread_get_txm_thread_stack(void)4175 thread_get_txm_thread_stack(void)
4176 {
4177 	return current_thread()->txm_thread_stack;
4178 }
4179 
4180 #endif
4181 
4182 #if CONFIG_DTRACE
4183 uint32_t
dtrace_get_thread_predcache(thread_t thread)4184 dtrace_get_thread_predcache(thread_t thread)
4185 {
4186 	if (thread != THREAD_NULL) {
4187 		return thread->t_dtrace_predcache;
4188 	} else {
4189 		return 0;
4190 	}
4191 }
4192 
4193 int64_t
dtrace_get_thread_vtime(thread_t thread)4194 dtrace_get_thread_vtime(thread_t thread)
4195 {
4196 	if (thread != THREAD_NULL) {
4197 		return thread->t_dtrace_vtime;
4198 	} else {
4199 		return 0;
4200 	}
4201 }
4202 
4203 int
dtrace_get_thread_last_cpu_id(thread_t thread)4204 dtrace_get_thread_last_cpu_id(thread_t thread)
4205 {
4206 	if ((thread != THREAD_NULL) && (thread->last_processor != PROCESSOR_NULL)) {
4207 		return thread->last_processor->cpu_id;
4208 	} else {
4209 		return -1;
4210 	}
4211 }
4212 
4213 int64_t
dtrace_get_thread_tracing(thread_t thread)4214 dtrace_get_thread_tracing(thread_t thread)
4215 {
4216 	if (thread != THREAD_NULL) {
4217 		return thread->t_dtrace_tracing;
4218 	} else {
4219 		return 0;
4220 	}
4221 }
4222 
4223 uint16_t
dtrace_get_thread_inprobe(thread_t thread)4224 dtrace_get_thread_inprobe(thread_t thread)
4225 {
4226 	if (thread != THREAD_NULL) {
4227 		return thread->t_dtrace_inprobe;
4228 	} else {
4229 		return 0;
4230 	}
4231 }
4232 
4233 vm_offset_t
thread_get_kernel_stack(thread_t thread)4234 thread_get_kernel_stack(thread_t thread)
4235 {
4236 	if (thread != THREAD_NULL) {
4237 		return thread->kernel_stack;
4238 	} else {
4239 		return 0;
4240 	}
4241 }
4242 
4243 #if KASAN
4244 struct kasan_thread_data *
kasan_get_thread_data(thread_t thread)4245 kasan_get_thread_data(thread_t thread)
4246 {
4247 	return &thread->kasan_data;
4248 }
4249 #endif
4250 
4251 #if CONFIG_KCOV
4252 kcov_thread_data_t *
kcov_get_thread_data(thread_t thread)4253 kcov_get_thread_data(thread_t thread)
4254 {
4255 	return &thread->kcov_data;
4256 }
4257 #endif
4258 
4259 #if CONFIG_STKSZ
4260 /*
4261  * Returns base of a thread's kernel stack.
4262  *
4263  * Coverage sanitizer instruments every function including those that participates in stack handoff between threads.
4264  * There is a window in which CPU still holds old values but stack has been handed over to anoher thread already.
4265  * In this window kernel_stack is 0 but CPU still uses the original stack (until contex switch occurs). The original
4266  * kernel_stack value is preserved in ksancov_stack during this window.
4267  */
4268 vm_offset_t
kcov_stksz_get_thread_stkbase(thread_t thread)4269 kcov_stksz_get_thread_stkbase(thread_t thread)
4270 {
4271 	if (thread != THREAD_NULL) {
4272 		kcov_thread_data_t *data = kcov_get_thread_data(thread);
4273 		if (data->ktd_stksz.kst_stack) {
4274 			return data->ktd_stksz.kst_stack;
4275 		} else {
4276 			return thread->kernel_stack;
4277 		}
4278 	} else {
4279 		return 0;
4280 	}
4281 }
4282 
4283 vm_offset_t
kcov_stksz_get_thread_stksize(thread_t thread)4284 kcov_stksz_get_thread_stksize(thread_t thread)
4285 {
4286 	if (thread != THREAD_NULL) {
4287 		return kernel_stack_size;
4288 	} else {
4289 		return 0;
4290 	}
4291 }
4292 
4293 void
kcov_stksz_set_thread_stack(thread_t thread,vm_offset_t stack)4294 kcov_stksz_set_thread_stack(thread_t thread, vm_offset_t stack)
4295 {
4296 	kcov_thread_data_t *data = kcov_get_thread_data(thread);
4297 	data->ktd_stksz.kst_stack = stack;
4298 }
4299 #endif /* CONFIG_STKSZ */
4300 
4301 int64_t
dtrace_calc_thread_recent_vtime(thread_t thread)4302 dtrace_calc_thread_recent_vtime(thread_t thread)
4303 {
4304 	if (thread == THREAD_NULL) {
4305 		return 0;
4306 	}
4307 
4308 	struct recount_usage usage = { 0 };
4309 	recount_current_thread_usage(&usage);
4310 	return (int64_t)(recount_usage_time_mach(&usage));
4311 }
4312 
4313 void
dtrace_set_thread_predcache(thread_t thread,uint32_t predcache)4314 dtrace_set_thread_predcache(thread_t thread, uint32_t predcache)
4315 {
4316 	if (thread != THREAD_NULL) {
4317 		thread->t_dtrace_predcache = predcache;
4318 	}
4319 }
4320 
4321 void
dtrace_set_thread_vtime(thread_t thread,int64_t vtime)4322 dtrace_set_thread_vtime(thread_t thread, int64_t vtime)
4323 {
4324 	if (thread != THREAD_NULL) {
4325 		thread->t_dtrace_vtime = vtime;
4326 	}
4327 }
4328 
4329 void
dtrace_set_thread_tracing(thread_t thread,int64_t accum)4330 dtrace_set_thread_tracing(thread_t thread, int64_t accum)
4331 {
4332 	if (thread != THREAD_NULL) {
4333 		thread->t_dtrace_tracing = accum;
4334 	}
4335 }
4336 
4337 void
dtrace_set_thread_inprobe(thread_t thread,uint16_t inprobe)4338 dtrace_set_thread_inprobe(thread_t thread, uint16_t inprobe)
4339 {
4340 	if (thread != THREAD_NULL) {
4341 		thread->t_dtrace_inprobe = inprobe;
4342 	}
4343 }
4344 
4345 void
dtrace_thread_bootstrap(void)4346 dtrace_thread_bootstrap(void)
4347 {
4348 	task_t task = current_task();
4349 
4350 	if (task->thread_count == 1) {
4351 		thread_t thread = current_thread();
4352 		if (thread->t_dtrace_flags & TH_DTRACE_EXECSUCCESS) {
4353 			thread->t_dtrace_flags &= ~TH_DTRACE_EXECSUCCESS;
4354 			DTRACE_PROC(exec__success);
4355 			KDBG(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXEC),
4356 			    task_pid(task));
4357 		}
4358 		DTRACE_PROC(start);
4359 	}
4360 	DTRACE_PROC(lwp__start);
4361 }
4362 
4363 void
dtrace_thread_didexec(thread_t thread)4364 dtrace_thread_didexec(thread_t thread)
4365 {
4366 	thread->t_dtrace_flags |= TH_DTRACE_EXECSUCCESS;
4367 }
4368 #endif /* CONFIG_DTRACE */
4369