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