xref: /xnu-12377.61.12/osfmk/kern/thread.c (revision 4d495c6e23c53686cf65f45067f79024cf5dcee8) !
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 #if HAS_MTE
3102 void
current_thread_enter_iomd_faultable_access_with_buffer_provider(task_t provider)3103 current_thread_enter_iomd_faultable_access_with_buffer_provider(task_t provider)
3104 {
3105 	current_thread()->iomd_faultable_buffer_provider = provider;
3106 }
3107 
3108 void
current_thread_exit_iomd_faultable_access(void)3109 current_thread_exit_iomd_faultable_access(void)
3110 {
3111 	current_thread()->iomd_faultable_buffer_provider = NULL;
3112 }
3113 
3114 task_t
current_thread_get_iomd_faultable_access_buffer_provider(void)3115 current_thread_get_iomd_faultable_access_buffer_provider(void)
3116 {
3117 	return current_thread()->iomd_faultable_buffer_provider;
3118 }
3119 #endif /* HAS_MTE */
3120 
3121 uint64_t
thread_tid(thread_t thread)3122 thread_tid(
3123 	thread_t        thread)
3124 {
3125 	return thread != THREAD_NULL? thread->thread_id: 0;
3126 }
3127 
3128 uint64_t
uthread_tid(struct uthread * uth)3129 uthread_tid(
3130 	struct uthread *uth)
3131 {
3132 	if (uth) {
3133 		return thread_tid(get_machthread(uth));
3134 	}
3135 	return 0;
3136 }
3137 
3138 uint64_t
thread_c_switch(thread_t thread)3139 thread_c_switch(thread_t thread)
3140 {
3141 	return thread != THREAD_NULL ? thread->c_switch : 0;
3142 }
3143 
3144 uint16_t
thread_set_tag(thread_t th,uint16_t tag)3145 thread_set_tag(thread_t th, uint16_t tag)
3146 {
3147 	return thread_set_tag_internal(th, tag);
3148 }
3149 
3150 uint16_t
thread_get_tag(thread_t th)3151 thread_get_tag(thread_t th)
3152 {
3153 	return thread_get_tag_internal(th);
3154 }
3155 
3156 uint64_t
thread_last_run_time(thread_t th)3157 thread_last_run_time(thread_t th)
3158 {
3159 	return th->last_run_time;
3160 }
3161 
3162 /*
3163  * Shared resource contention management
3164  *
3165  * The scheduler attempts to load balance the shared resource intensive
3166  * workloads across clusters to ensure that the resource is not heavily
3167  * contended. The kernel relies on external agents (userspace or
3168  * performance controller) to identify shared resource heavy threads.
3169  * The load balancing is achieved based on the scheduler configuration
3170  * enabled on the platform.
3171  */
3172 
3173 
3174 #if CONFIG_SCHED_EDGE
3175 
3176 /*
3177  * On the Edge scheduler, the load balancing is achieved by looking
3178  * at cluster level shared resource loads and migrating resource heavy
3179  * threads dynamically to under utilized cluster. Therefore, when a
3180  * thread is indicated as a resource heavy thread, the policy set
3181  * routine simply adds a flag to the thread which is looked at by
3182  * the scheduler on thread migration decisions.
3183  */
3184 
3185 boolean_t
thread_shared_rsrc_policy_get(thread_t thread,cluster_shared_rsrc_type_t type)3186 thread_shared_rsrc_policy_get(thread_t thread, cluster_shared_rsrc_type_t type)
3187 {
3188 	return thread->th_shared_rsrc_heavy_user[type] || thread->th_shared_rsrc_heavy_perf_control[type];
3189 }
3190 
3191 __options_decl(sched_edge_rsrc_heavy_thread_state, uint32_t, {
3192 	SCHED_EDGE_RSRC_HEAVY_THREAD_SET = 1,
3193 	SCHED_EDGE_RSRC_HEAVY_THREAD_CLR = 2,
3194 });
3195 
3196 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)3197 thread_shared_rsrc_policy_set(thread_t thread, __unused uint32_t index, cluster_shared_rsrc_type_t type, shared_rsrc_policy_agent_t agent)
3198 {
3199 	spl_t s = splsched();
3200 	thread_lock(thread);
3201 
3202 	bool user = (agent == SHARED_RSRC_POLICY_AGENT_DISPATCH) || (agent == SHARED_RSRC_POLICY_AGENT_SYSCTL);
3203 	bool *thread_flags = (user) ? thread->th_shared_rsrc_heavy_user : thread->th_shared_rsrc_heavy_perf_control;
3204 	if (thread_flags[type]) {
3205 		thread_unlock(thread);
3206 		splx(s);
3207 		return KERN_FAILURE;
3208 	}
3209 
3210 	thread_flags[type] = true;
3211 	thread_unlock(thread);
3212 	splx(s);
3213 
3214 	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);
3215 	if (thread == current_thread()) {
3216 		if (agent == SHARED_RSRC_POLICY_AGENT_PERFCTL_QUANTUM) {
3217 			ast_on(AST_PREEMPT);
3218 		} else {
3219 			assert(agent != SHARED_RSRC_POLICY_AGENT_PERFCTL_CSW);
3220 			thread_block(THREAD_CONTINUE_NULL);
3221 		}
3222 	}
3223 	return KERN_SUCCESS;
3224 }
3225 
3226 kern_return_t
thread_shared_rsrc_policy_clear(thread_t thread,cluster_shared_rsrc_type_t type,shared_rsrc_policy_agent_t agent)3227 thread_shared_rsrc_policy_clear(thread_t thread, cluster_shared_rsrc_type_t type, shared_rsrc_policy_agent_t agent)
3228 {
3229 	spl_t s = splsched();
3230 	thread_lock(thread);
3231 
3232 	bool user = (agent == SHARED_RSRC_POLICY_AGENT_DISPATCH) || (agent == SHARED_RSRC_POLICY_AGENT_SYSCTL);
3233 	bool *thread_flags = (user) ? thread->th_shared_rsrc_heavy_user : thread->th_shared_rsrc_heavy_perf_control;
3234 	if (!thread_flags[type]) {
3235 		thread_unlock(thread);
3236 		splx(s);
3237 		return KERN_FAILURE;
3238 	}
3239 
3240 	thread_flags[type] = false;
3241 	thread_unlock(thread);
3242 	splx(s);
3243 
3244 	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);
3245 	if (thread == current_thread()) {
3246 		if (agent == SHARED_RSRC_POLICY_AGENT_PERFCTL_QUANTUM) {
3247 			ast_on(AST_PREEMPT);
3248 		} else {
3249 			assert(agent != SHARED_RSRC_POLICY_AGENT_PERFCTL_CSW);
3250 			thread_block(THREAD_CONTINUE_NULL);
3251 		}
3252 	}
3253 	return KERN_SUCCESS;
3254 }
3255 
3256 #else /* CONFIG_SCHED_EDGE */
3257 
3258 /*
3259  * On non-Edge schedulers, the shared resource contention
3260  * is managed by simply binding threads to specific clusters
3261  * based on the worker index passed by the agents marking
3262  * this thread as resource heavy threads. The thread binding
3263  * approach does not provide any rebalancing opportunities;
3264  * it can also suffer from scheduling delays if the cluster
3265  * where the thread is bound is contended.
3266  */
3267 
3268 boolean_t
thread_shared_rsrc_policy_get(__unused thread_t thread,__unused cluster_shared_rsrc_type_t type)3269 thread_shared_rsrc_policy_get(__unused thread_t thread, __unused cluster_shared_rsrc_type_t type)
3270 {
3271 	return false;
3272 }
3273 
3274 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)3275 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)
3276 {
3277 	return thread_soft_bind_cluster_id(thread, index, THREAD_BIND_ELIGIBLE_ONLY);
3278 }
3279 
3280 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)3281 thread_shared_rsrc_policy_clear(thread_t thread, __unused cluster_shared_rsrc_type_t type, __unused shared_rsrc_policy_agent_t agent)
3282 {
3283 	return thread_soft_bind_cluster_id(thread, 0, THREAD_UNBIND);
3284 }
3285 
3286 #endif /* CONFIG_SCHED_EDGE */
3287 
3288 uint64_t
thread_dispatchqaddr(thread_t thread)3289 thread_dispatchqaddr(
3290 	thread_t                thread)
3291 {
3292 	uint64_t        dispatchqueue_addr;
3293 	uint64_t        thread_handle;
3294 	task_t          task;
3295 
3296 	if (thread == THREAD_NULL) {
3297 		return 0;
3298 	}
3299 
3300 	thread_handle = thread->machine.cthread_self;
3301 	if (thread_handle == 0) {
3302 		return 0;
3303 	}
3304 
3305 	task = get_threadtask(thread);
3306 	void *bsd_info = get_bsdtask_info(task);
3307 	if (thread->inspection == TRUE) {
3308 		dispatchqueue_addr = thread_handle + get_task_dispatchqueue_offset(task);
3309 	} else if (bsd_info) {
3310 		dispatchqueue_addr = thread_handle + get_dispatchqueue_offset_from_proc(bsd_info);
3311 	} else {
3312 		dispatchqueue_addr = 0;
3313 	}
3314 
3315 	return dispatchqueue_addr;
3316 }
3317 
3318 
3319 uint64_t
thread_wqquantum_addr(thread_t thread)3320 thread_wqquantum_addr(thread_t thread)
3321 {
3322 	uint64_t thread_handle;
3323 	task_t   task;
3324 
3325 	if (thread == THREAD_NULL) {
3326 		return 0;
3327 	}
3328 
3329 	thread_handle = thread->machine.cthread_self;
3330 	if (thread_handle == 0) {
3331 		return 0;
3332 	}
3333 	task = get_threadtask(thread);
3334 
3335 	uint64_t wq_quantum_expiry_offset = get_wq_quantum_offset_from_proc(get_bsdtask_info(task));
3336 	if (wq_quantum_expiry_offset == 0) {
3337 		return 0;
3338 	}
3339 
3340 	return wq_quantum_expiry_offset + thread_handle;
3341 }
3342 
3343 uint64_t
thread_rettokern_addr(thread_t thread)3344 thread_rettokern_addr(
3345 	thread_t                thread)
3346 {
3347 	uint64_t        rettokern_addr;
3348 	uint64_t        rettokern_offset;
3349 	uint64_t        thread_handle;
3350 	task_t          task;
3351 	void            *bsd_info;
3352 
3353 	if (thread == THREAD_NULL) {
3354 		return 0;
3355 	}
3356 
3357 	thread_handle = thread->machine.cthread_self;
3358 	if (thread_handle == 0) {
3359 		return 0;
3360 	}
3361 	task = get_threadtask(thread);
3362 	bsd_info = get_bsdtask_info(task);
3363 
3364 	if (bsd_info) {
3365 		rettokern_offset = get_return_to_kernel_offset_from_proc(bsd_info);
3366 
3367 		/* Return 0 if return to kernel offset is not initialized. */
3368 		if (rettokern_offset == 0) {
3369 			rettokern_addr = 0;
3370 		} else {
3371 			rettokern_addr = thread_handle + rettokern_offset;
3372 		}
3373 	} else {
3374 		rettokern_addr = 0;
3375 	}
3376 
3377 	return rettokern_addr;
3378 }
3379 
3380 /*
3381  * Export routines to other components for things that are done as macros
3382  * within the osfmk component.
3383  */
3384 
3385 void
thread_mtx_lock(thread_t thread)3386 thread_mtx_lock(thread_t thread)
3387 {
3388 	lck_mtx_lock(&thread->mutex);
3389 }
3390 
3391 void
thread_mtx_unlock(thread_t thread)3392 thread_mtx_unlock(thread_t thread)
3393 {
3394 	lck_mtx_unlock(&thread->mutex);
3395 }
3396 
3397 void
thread_reference(thread_t thread)3398 thread_reference(
3399 	thread_t        thread)
3400 {
3401 	if (thread != THREAD_NULL) {
3402 		zone_id_require(ZONE_ID_THREAD, sizeof(struct thread), thread);
3403 		os_ref_retain_raw(&thread->ref_count, &thread_refgrp);
3404 	}
3405 }
3406 
3407 void
thread_require(thread_t thread)3408 thread_require(thread_t thread)
3409 {
3410 	zone_id_require(ZONE_ID_THREAD, sizeof(struct thread), thread);
3411 }
3412 
3413 #undef thread_should_halt
3414 
3415 boolean_t
thread_should_halt(thread_t th)3416 thread_should_halt(
3417 	thread_t                th)
3418 {
3419 	return thread_should_halt_fast(th);
3420 }
3421 
3422 /*
3423  * thread_set_voucher_name - reset the voucher port name bound to this thread
3424  *
3425  * Conditions:  nothing locked
3426  */
3427 
3428 kern_return_t
thread_set_voucher_name(mach_port_name_t voucher_name)3429 thread_set_voucher_name(mach_port_name_t voucher_name)
3430 {
3431 	thread_t thread = current_thread();
3432 	ipc_voucher_t new_voucher = IPC_VOUCHER_NULL;
3433 	ipc_voucher_t voucher;
3434 	ledger_t bankledger = NULL;
3435 	struct thread_group *banktg = NULL;
3436 	uint32_t persona_id = 0;
3437 
3438 	if (MACH_PORT_DEAD == voucher_name) {
3439 		return KERN_INVALID_RIGHT;
3440 	}
3441 
3442 	/*
3443 	 * agressively convert to voucher reference
3444 	 */
3445 	if (MACH_PORT_VALID(voucher_name)) {
3446 		new_voucher = convert_port_name_to_voucher(voucher_name);
3447 		if (IPC_VOUCHER_NULL == new_voucher) {
3448 			return KERN_INVALID_ARGUMENT;
3449 		}
3450 	}
3451 	bank_get_bank_ledger_thread_group_and_persona(new_voucher, &bankledger, &banktg, &persona_id);
3452 
3453 	thread_mtx_lock(thread);
3454 	voucher = thread->ith_voucher;
3455 	thread->ith_voucher_name = voucher_name;
3456 	thread->ith_voucher = new_voucher;
3457 	thread_mtx_unlock(thread);
3458 
3459 	bank_swap_thread_bank_ledger(thread, bankledger);
3460 #if CONFIG_THREAD_GROUPS
3461 	thread_group_set_bank(thread, banktg);
3462 #endif /* CONFIG_THREAD_GROUPS */
3463 
3464 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
3465 	    MACHDBG_CODE(DBG_MACH_IPC, MACH_THREAD_SET_VOUCHER) | DBG_FUNC_NONE,
3466 	    (uintptr_t)thread_tid(thread),
3467 	    (uintptr_t)voucher_name,
3468 	    VM_KERNEL_ADDRPERM((uintptr_t)new_voucher),
3469 	    persona_id, 0);
3470 
3471 	if (IPC_VOUCHER_NULL != voucher) {
3472 		ipc_voucher_release(voucher);
3473 	}
3474 
3475 	return KERN_SUCCESS;
3476 }
3477 
3478 /*
3479  *  thread_get_mach_voucher - return a voucher reference for the specified thread voucher
3480  *
3481  *  Conditions:  nothing locked
3482  *
3483  *  NOTE:       At the moment, there is no distinction between the current and effective
3484  *		vouchers because we only set them at the thread level currently.
3485  */
3486 kern_return_t
thread_get_mach_voucher(thread_act_t thread,mach_voucher_selector_t __unused which,ipc_voucher_t * voucherp)3487 thread_get_mach_voucher(
3488 	thread_act_t            thread,
3489 	mach_voucher_selector_t __unused which,
3490 	ipc_voucher_t           *voucherp)
3491 {
3492 	ipc_voucher_t           voucher;
3493 
3494 	if (THREAD_NULL == thread) {
3495 		return KERN_INVALID_ARGUMENT;
3496 	}
3497 
3498 	thread_mtx_lock(thread);
3499 	voucher = thread->ith_voucher;
3500 
3501 	if (IPC_VOUCHER_NULL != voucher) {
3502 		ipc_voucher_reference(voucher);
3503 		thread_mtx_unlock(thread);
3504 		*voucherp = voucher;
3505 		return KERN_SUCCESS;
3506 	}
3507 
3508 	thread_mtx_unlock(thread);
3509 
3510 	*voucherp = IPC_VOUCHER_NULL;
3511 	return KERN_SUCCESS;
3512 }
3513 
3514 /*
3515  *  thread_set_mach_voucher - set a voucher reference for the specified thread voucher
3516  *
3517  *  Conditions: callers holds a reference on the voucher.
3518  *		nothing locked.
3519  *
3520  *  We grab another reference to the voucher and bind it to the thread.
3521  *  The old voucher reference associated with the thread is
3522  *  discarded.
3523  */
3524 kern_return_t
thread_set_mach_voucher(thread_t thread,ipc_voucher_t voucher)3525 thread_set_mach_voucher(
3526 	thread_t                thread,
3527 	ipc_voucher_t           voucher)
3528 {
3529 	ipc_voucher_t old_voucher;
3530 	ledger_t bankledger = NULL;
3531 	struct thread_group *banktg = NULL;
3532 	uint32_t persona_id = 0;
3533 
3534 	if (THREAD_NULL == thread) {
3535 		return KERN_INVALID_ARGUMENT;
3536 	}
3537 
3538 	bank_get_bank_ledger_thread_group_and_persona(voucher, &bankledger, &banktg, &persona_id);
3539 
3540 	thread_mtx_lock(thread);
3541 	/*
3542 	 * Once the thread is started, we will look at `ith_voucher` without
3543 	 * holding any lock.
3544 	 *
3545 	 * Setting the voucher hence can only be done by current_thread() or
3546 	 * before it started. "started" flips under the thread mutex and must be
3547 	 * tested under it too.
3548 	 */
3549 	if (thread != current_thread() && thread->started) {
3550 		thread_mtx_unlock(thread);
3551 		return KERN_INVALID_ARGUMENT;
3552 	}
3553 
3554 	ipc_voucher_reference(voucher);
3555 	old_voucher = thread->ith_voucher;
3556 	thread->ith_voucher = voucher;
3557 	thread->ith_voucher_name = MACH_PORT_NULL;
3558 	thread_mtx_unlock(thread);
3559 
3560 	bank_swap_thread_bank_ledger(thread, bankledger);
3561 #if CONFIG_THREAD_GROUPS
3562 	thread_group_set_bank(thread, banktg);
3563 #endif /* CONFIG_THREAD_GROUPS */
3564 
3565 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
3566 	    MACHDBG_CODE(DBG_MACH_IPC, MACH_THREAD_SET_VOUCHER) | DBG_FUNC_NONE,
3567 	    (uintptr_t)thread_tid(thread),
3568 	    (uintptr_t)MACH_PORT_NULL,
3569 	    VM_KERNEL_ADDRPERM((uintptr_t)voucher),
3570 	    persona_id, 0);
3571 
3572 	ipc_voucher_release(old_voucher);
3573 
3574 	return KERN_SUCCESS;
3575 }
3576 
3577 /*
3578  *  thread_swap_mach_voucher - swap a voucher reference for the specified thread voucher
3579  *
3580  *  Conditions: callers holds a reference on the new and presumed old voucher(s).
3581  *		nothing locked.
3582  *
3583  *  This function is no longer supported.
3584  */
3585 kern_return_t
thread_swap_mach_voucher(__unused thread_t thread,__unused ipc_voucher_t new_voucher,ipc_voucher_t * in_out_old_voucher)3586 thread_swap_mach_voucher(
3587 	__unused thread_t               thread,
3588 	__unused ipc_voucher_t          new_voucher,
3589 	ipc_voucher_t                   *in_out_old_voucher)
3590 {
3591 	/*
3592 	 * Currently this function is only called from a MIG generated
3593 	 * routine which doesn't release the reference on the voucher
3594 	 * addressed by in_out_old_voucher. To avoid leaking this reference,
3595 	 * a call to release it has been added here.
3596 	 */
3597 	ipc_voucher_release(*in_out_old_voucher);
3598 	OS_ANALYZER_SUPPRESS("81787115") return KERN_NOT_SUPPORTED;
3599 }
3600 
3601 /*
3602  *  thread_get_current_voucher_origin_pid - get the pid of the originator of the current voucher.
3603  */
3604 kern_return_t
thread_get_current_voucher_origin_pid(int32_t * pid)3605 thread_get_current_voucher_origin_pid(
3606 	int32_t      *pid)
3607 {
3608 	return thread_get_voucher_origin_pid(current_thread(), pid);
3609 }
3610 
3611 /*
3612  *  thread_get_current_voucher_origin_pid - get the pid of the originator of the current voucher.
3613  */
3614 kern_return_t
thread_get_voucher_origin_pid(thread_t thread,int32_t * pid)3615 thread_get_voucher_origin_pid(thread_t thread, int32_t *pid)
3616 {
3617 	uint32_t buf_size = sizeof(*pid);
3618 	return mach_voucher_attr_command(thread->ith_voucher,
3619 	           MACH_VOUCHER_ATTR_KEY_BANK,
3620 	           BANK_ORIGINATOR_PID,
3621 	           NULL,
3622 	           0,
3623 	           (mach_voucher_attr_content_t)pid,
3624 	           &buf_size);
3625 }
3626 
3627 /*
3628  *  thread_get_current_voucher_proximate_pid - get the pid of the proximate process of the current voucher.
3629  */
3630 kern_return_t
thread_get_voucher_origin_proximate_pid(thread_t thread,int32_t * origin_pid,int32_t * proximate_pid)3631 thread_get_voucher_origin_proximate_pid(thread_t thread, int32_t *origin_pid, int32_t *proximate_pid)
3632 {
3633 	int32_t origin_proximate_pids[2] = { };
3634 	uint32_t buf_size = sizeof(origin_proximate_pids);
3635 	kern_return_t kr = mach_voucher_attr_command(thread->ith_voucher,
3636 	    MACH_VOUCHER_ATTR_KEY_BANK,
3637 	    BANK_ORIGINATOR_PROXIMATE_PID,
3638 	    NULL,
3639 	    0,
3640 	    (mach_voucher_attr_content_t)origin_proximate_pids,
3641 	    &buf_size);
3642 	if (kr == KERN_SUCCESS) {
3643 		*origin_pid = origin_proximate_pids[0];
3644 		*proximate_pid = origin_proximate_pids[1];
3645 	}
3646 	return kr;
3647 }
3648 
3649 #if CONFIG_THREAD_GROUPS
3650 /*
3651  * Returns the current thread's voucher-carried thread group
3652  *
3653  * Reference is borrowed from this being the current voucher, so it does NOT
3654  * return a reference to the group.
3655  */
3656 struct thread_group *
thread_get_current_voucher_thread_group(thread_t thread)3657 thread_get_current_voucher_thread_group(thread_t thread)
3658 {
3659 	assert(thread == current_thread());
3660 
3661 	if (thread->ith_voucher == NULL) {
3662 		return NULL;
3663 	}
3664 
3665 	ledger_t bankledger = NULL;
3666 	struct thread_group *banktg = NULL;
3667 
3668 	bank_get_bank_ledger_thread_group_and_persona(thread->ith_voucher, &bankledger, &banktg, NULL);
3669 
3670 	return banktg;
3671 }
3672 
3673 #endif /* CONFIG_THREAD_GROUPS */
3674 
3675 #if CONFIG_COALITIONS
3676 
3677 uint64_t
thread_get_current_voucher_resource_coalition_id(thread_t thread)3678 thread_get_current_voucher_resource_coalition_id(thread_t thread)
3679 {
3680 	uint64_t id = 0;
3681 	assert(thread == current_thread());
3682 	if (thread->ith_voucher != NULL) {
3683 		id = bank_get_bank_ledger_resource_coalition_id(thread->ith_voucher);
3684 	}
3685 	return id;
3686 }
3687 
3688 #endif /* CONFIG_COALITIONS */
3689 
3690 extern struct workqueue *
3691 proc_get_wqptr(void *proc);
3692 
3693 static bool
task_supports_cooperative_workqueue(task_t task)3694 task_supports_cooperative_workqueue(task_t task)
3695 {
3696 	void *bsd_info = get_bsdtask_info(task);
3697 
3698 	assert(task == current_task());
3699 	if (bsd_info == NULL) {
3700 		return false;
3701 	}
3702 
3703 	uint64_t wq_quantum_expiry_offset = get_wq_quantum_offset_from_proc(bsd_info);
3704 	/* userspace may not yet have called workq_open yet */
3705 	struct workqueue *wq = proc_get_wqptr(bsd_info);
3706 
3707 	return (wq != NULL) && (wq_quantum_expiry_offset != 0);
3708 }
3709 
3710 /* Not safe to call from scheduler paths - should only be called on self */
3711 bool
thread_supports_cooperative_workqueue(thread_t thread)3712 thread_supports_cooperative_workqueue(thread_t thread)
3713 {
3714 	struct uthread *uth = get_bsdthread_info(thread);
3715 	task_t task = get_threadtask(thread);
3716 
3717 	assert(thread == current_thread());
3718 
3719 	return task_supports_cooperative_workqueue(task) &&
3720 	       bsdthread_part_of_cooperative_workqueue(uth);
3721 }
3722 
3723 static inline bool
thread_has_armed_workqueue_quantum(thread_t thread)3724 thread_has_armed_workqueue_quantum(thread_t thread)
3725 {
3726 	return thread->workq_quantum_deadline != 0;
3727 }
3728 
3729 /*
3730  * The workq quantum is a lazy timer that is evaluated at 2 specific times in
3731  * the scheduler:
3732  *
3733  * - context switch time
3734  * - scheduler quantum expiry time.
3735  *
3736  * We're currently expressing the workq quantum with a 0.5 scale factor of the
3737  * scheduler quantum. It is possible that if the workq quantum is rearmed
3738  * shortly after the scheduler quantum begins, we could have a large delay
3739  * between when the workq quantum next expires and when it actually is noticed.
3740  *
3741  * A potential future improvement for the wq quantum expiry logic is to compare
3742  * it to the next actual scheduler quantum deadline and expire it if it is
3743  * within a certain leeway.
3744  */
3745 static inline uint64_t
thread_workq_quantum_size(thread_t thread)3746 thread_workq_quantum_size(thread_t thread)
3747 {
3748 	return (uint64_t) (SCHED(initial_quantum_size)(thread) / 2);
3749 }
3750 
3751 /*
3752  * Always called by thread on itself - either at AST boundary after processing
3753  * an existing quantum expiry, or when a new quantum is armed before the thread
3754  * goes out to userspace to handle a thread request
3755  */
3756 void
thread_arm_workqueue_quantum(thread_t thread)3757 thread_arm_workqueue_quantum(thread_t thread)
3758 {
3759 	/*
3760 	 * If the task is not opted into wq quantum notification, or if the thread
3761 	 * is not part of the cooperative workqueue, don't even bother with tracking
3762 	 * the quantum or calculating expiry
3763 	 */
3764 	if (!thread_supports_cooperative_workqueue(thread)) {
3765 		assert(thread->workq_quantum_deadline == 0);
3766 		return;
3767 	}
3768 
3769 	assert(current_thread() == thread);
3770 	assert(thread_get_tag(thread) & THREAD_TAG_WORKQUEUE);
3771 
3772 	uint64_t current_runtime = thread_get_runtime_self();
3773 	uint64_t deadline = thread_workq_quantum_size(thread) + current_runtime;
3774 
3775 	/*
3776 	 * The update of a workqueue quantum should always be followed by the update
3777 	 * of the AST - see explanation in kern/thread.h for synchronization of this
3778 	 * field
3779 	 */
3780 	thread->workq_quantum_deadline = deadline;
3781 
3782 	/* We're arming a new quantum, clear any previous expiry notification */
3783 	act_clear_astkevent(thread, AST_KEVENT_WORKQ_QUANTUM_EXPIRED);
3784 
3785 	WQ_TRACE(TRACE_wq_quantum_arm, current_runtime, deadline, 0, 0);
3786 
3787 	WORKQ_QUANTUM_HISTORY_WRITE_ENTRY(thread, thread->workq_quantum_deadline, true);
3788 }
3789 
3790 /* Called by a thread on itself when it is about to park */
3791 void
thread_disarm_workqueue_quantum(thread_t thread)3792 thread_disarm_workqueue_quantum(thread_t thread)
3793 {
3794 	/* The update of a workqueue quantum should always be followed by the update
3795 	 * of the AST - see explanation in kern/thread.h for synchronization of this
3796 	 * field */
3797 	thread->workq_quantum_deadline = 0;
3798 	act_clear_astkevent(thread, AST_KEVENT_WORKQ_QUANTUM_EXPIRED);
3799 
3800 	WQ_TRACE(TRACE_wq_quantum_disarm, 0, 0, 0, 0);
3801 
3802 	WORKQ_QUANTUM_HISTORY_WRITE_ENTRY(thread, thread->workq_quantum_deadline, false);
3803 }
3804 
3805 /* This is called at context switch time on a thread that may not be self,
3806  * and at AST time
3807  */
3808 bool
thread_has_expired_workqueue_quantum(thread_t thread,bool should_trace)3809 thread_has_expired_workqueue_quantum(thread_t thread, bool should_trace)
3810 {
3811 	if (!thread_has_armed_workqueue_quantum(thread)) {
3812 		return false;
3813 	}
3814 	/* We do not do a thread_get_runtime_self() here since this function is
3815 	 * called from context switch time or during scheduler quantum expiry and
3816 	 * therefore, we may not be evaluating it on the current thread/self.
3817 	 *
3818 	 * In addition, the timers on the thread have just been updated recently so
3819 	 * we don't need to update them again.
3820 	 */
3821 	uint64_t runtime = recount_thread_time_mach(thread);
3822 	bool expired = runtime > thread->workq_quantum_deadline;
3823 
3824 	if (expired && should_trace) {
3825 		WQ_TRACE(TRACE_wq_quantum_expired, runtime, thread->workq_quantum_deadline, 0, 0);
3826 	}
3827 
3828 	return expired;
3829 }
3830 
3831 /*
3832  * Called on a thread that is being context switched out or during quantum
3833  * expiry on self. Only called from scheduler paths.
3834  */
3835 void
thread_evaluate_workqueue_quantum_expiry(thread_t thread)3836 thread_evaluate_workqueue_quantum_expiry(thread_t thread)
3837 {
3838 	if (thread_has_expired_workqueue_quantum(thread, true)) {
3839 		act_set_astkevent(thread, AST_KEVENT_WORKQ_QUANTUM_EXPIRED);
3840 	}
3841 }
3842 
3843 boolean_t
thread_has_thread_name(thread_t th)3844 thread_has_thread_name(thread_t th)
3845 {
3846 	if (th) {
3847 		return bsd_hasthreadname(get_bsdthread_info(th));
3848 	}
3849 
3850 	/*
3851 	 * This is an odd case; clients may set the thread name based on the lack of
3852 	 * a name, but in this context there is no uthread to attach the name to.
3853 	 */
3854 	return FALSE;
3855 }
3856 
3857 void
thread_set_thread_name(thread_t th,const char * name)3858 thread_set_thread_name(thread_t th, const char* name)
3859 {
3860 	if (th && name) {
3861 		bsd_setthreadname(get_bsdthread_info(th), thread_tid(th), name);
3862 	}
3863 }
3864 
3865 void
thread_get_thread_name(thread_t th,char * name)3866 thread_get_thread_name(thread_t th, char* name)
3867 {
3868 	if (!name) {
3869 		return;
3870 	}
3871 	if (th) {
3872 		bsd_getthreadname(get_bsdthread_info(th), name);
3873 	} else {
3874 		name[0] = '\0';
3875 	}
3876 }
3877 
3878 processor_t
thread_get_runq(thread_t thread)3879 thread_get_runq(thread_t thread)
3880 {
3881 	thread_lock_assert(thread, LCK_ASSERT_OWNED);
3882 	processor_t runq = thread->__runq.runq;
3883 	os_atomic_thread_fence(acquire);
3884 	return runq;
3885 }
3886 
3887 processor_t
thread_get_runq_locked(thread_t thread)3888 thread_get_runq_locked(thread_t thread)
3889 {
3890 	thread_lock_assert(thread, LCK_ASSERT_OWNED);
3891 	processor_t runq = thread->__runq.runq;
3892 	if (runq != PROCESSOR_NULL) {
3893 		pset_assert_locked(runq->processor_set);
3894 	}
3895 	return runq;
3896 }
3897 
3898 void
thread_set_runq_locked(thread_t thread,processor_t new_runq)3899 thread_set_runq_locked(thread_t thread, processor_t new_runq)
3900 {
3901 	thread_lock_assert(thread, LCK_ASSERT_OWNED);
3902 	pset_assert_locked(new_runq->processor_set);
3903 	thread_assert_runq_null(thread);
3904 	thread->__runq.runq = new_runq;
3905 }
3906 
3907 void
thread_clear_runq(thread_t thread)3908 thread_clear_runq(thread_t thread)
3909 {
3910 	thread_assert_runq_nonnull(thread);
3911 	os_atomic_thread_fence(release);
3912 	thread->__runq.runq = PROCESSOR_NULL;
3913 }
3914 
3915 void
thread_clear_runq_locked(thread_t thread)3916 thread_clear_runq_locked(thread_t thread)
3917 {
3918 	thread_lock_assert(thread, LCK_ASSERT_OWNED);
3919 	thread_assert_runq_nonnull(thread);
3920 	thread->__runq.runq = PROCESSOR_NULL;
3921 }
3922 
3923 void
thread_assert_runq_null(__assert_only thread_t thread)3924 thread_assert_runq_null(__assert_only thread_t thread)
3925 {
3926 	assert(thread->__runq.runq == PROCESSOR_NULL);
3927 }
3928 
3929 void
thread_assert_runq_nonnull(thread_t thread)3930 thread_assert_runq_nonnull(thread_t thread)
3931 {
3932 	pset_assert_locked(thread->__runq.runq->processor_set);
3933 	assert(thread->__runq.runq != PROCESSOR_NULL);
3934 }
3935 
3936 void
thread_set_honor_qlimit(thread_t thread)3937 thread_set_honor_qlimit(thread_t thread)
3938 {
3939 	thread->options |= TH_OPT_HONOR_QLIMIT;
3940 }
3941 
3942 void
thread_clear_honor_qlimit(thread_t thread)3943 thread_clear_honor_qlimit(thread_t thread)
3944 {
3945 	thread->options &= (~TH_OPT_HONOR_QLIMIT);
3946 }
3947 
3948 /*
3949  * thread_enable_send_importance - set/clear the SEND_IMPORTANCE thread option bit.
3950  */
3951 void
thread_enable_send_importance(thread_t thread,boolean_t enable)3952 thread_enable_send_importance(thread_t thread, boolean_t enable)
3953 {
3954 	if (enable == TRUE) {
3955 		thread->options |= TH_OPT_SEND_IMPORTANCE;
3956 	} else {
3957 		thread->options &= ~TH_OPT_SEND_IMPORTANCE;
3958 	}
3959 }
3960 
3961 kern_return_t
thread_get_ipc_propagate_attr(thread_t thread,struct thread_attr_for_ipc_propagation * attr)3962 thread_get_ipc_propagate_attr(thread_t thread, struct thread_attr_for_ipc_propagation *attr)
3963 {
3964 	int iotier;
3965 	int qos;
3966 
3967 	if (thread == NULL || attr == NULL) {
3968 		return KERN_INVALID_ARGUMENT;
3969 	}
3970 
3971 	iotier = proc_get_effective_thread_policy(thread, TASK_POLICY_IO);
3972 	qos = proc_get_effective_thread_policy(thread, TASK_POLICY_QOS);
3973 
3974 	if (!qos) {
3975 		qos = thread_user_promotion_qos_for_pri(thread->base_pri);
3976 	}
3977 
3978 	attr->tafip_iotier = iotier;
3979 	attr->tafip_qos = qos;
3980 
3981 	return KERN_SUCCESS;
3982 }
3983 
3984 /*
3985  * thread_set_allocation_name - .
3986  */
3987 
3988 kern_allocation_name_t
thread_set_allocation_name(kern_allocation_name_t new_name)3989 thread_set_allocation_name(kern_allocation_name_t new_name)
3990 {
3991 	kern_allocation_name_t ret;
3992 	thread_kernel_state_t kstate = thread_get_kernel_state(current_thread());
3993 	ret = kstate->allocation_name;
3994 	// fifo
3995 	if (!new_name || !kstate->allocation_name) {
3996 		kstate->allocation_name = new_name;
3997 	}
3998 	return ret;
3999 }
4000 
4001 void *
thread_iokit_tls_get(uint32_t index)4002 thread_iokit_tls_get(uint32_t index)
4003 {
4004 	assert(index < THREAD_SAVE_IOKIT_TLS_COUNT);
4005 	return current_thread()->saved.iokit.tls[index];
4006 }
4007 
4008 void
thread_iokit_tls_set(uint32_t index,void * data)4009 thread_iokit_tls_set(uint32_t index, void * data)
4010 {
4011 	assert(index < THREAD_SAVE_IOKIT_TLS_COUNT);
4012 	current_thread()->saved.iokit.tls[index] = data;
4013 }
4014 
4015 uint64_t
thread_get_last_wait_duration(thread_t thread)4016 thread_get_last_wait_duration(thread_t thread)
4017 {
4018 	return thread->last_made_runnable_time - thread->last_run_time;
4019 }
4020 
4021 integer_t
thread_kern_get_pri(thread_t thr)4022 thread_kern_get_pri(thread_t thr)
4023 {
4024 	return thr->base_pri;
4025 }
4026 
4027 void
thread_kern_set_pri(thread_t thr,integer_t pri)4028 thread_kern_set_pri(thread_t thr, integer_t pri)
4029 {
4030 	sched_set_kernel_thread_priority(thr, pri);
4031 }
4032 
4033 integer_t
thread_kern_get_kernel_maxpri(void)4034 thread_kern_get_kernel_maxpri(void)
4035 {
4036 	return MAXPRI_KERNEL;
4037 }
4038 /*
4039  *	thread_port_with_flavor_no_senders
4040  *
4041  *	Called whenever the Mach port system detects no-senders on
4042  *	the thread inspect or read port. These ports are allocated lazily and
4043  *	should be deallocated here when there are no senders remaining.
4044  */
4045 static void
thread_port_with_flavor_no_senders(ipc_port_t port,mach_port_mscount_t mscount)4046 thread_port_with_flavor_no_senders(ipc_port_t port, mach_port_mscount_t mscount)
4047 {
4048 	thread_ro_t tro;
4049 	thread_t thread;
4050 	mach_thread_flavor_t flavor;
4051 	ipc_kobject_type_t kotype;
4052 
4053 	ip_mq_lock(port);
4054 	if (!ipc_kobject_is_mscount_current_locked(port, mscount)) {
4055 		ip_mq_unlock(port);
4056 		return;
4057 	}
4058 
4059 	kotype = ip_type(port);
4060 	assert((IKOT_THREAD_READ == kotype) || (IKOT_THREAD_INSPECT == kotype));
4061 	thread = ipc_kobject_get_locked(port, kotype);
4062 	if (thread != THREAD_NULL) {
4063 		thread_reference(thread);
4064 	}
4065 	ip_mq_unlock(port);
4066 
4067 	if (thread == THREAD_NULL) {
4068 		/* The thread is exiting or disabled; it will eventually deallocate the port */
4069 		return;
4070 	}
4071 
4072 	if (kotype == IKOT_THREAD_READ) {
4073 		flavor = THREAD_FLAVOR_READ;
4074 	} else {
4075 		flavor = THREAD_FLAVOR_INSPECT;
4076 	}
4077 
4078 	thread_mtx_lock(thread);
4079 	ip_mq_lock(port);
4080 
4081 	/*
4082 	 * If the port is no longer active, then ipc_thread_terminate() ran
4083 	 * and destroyed the kobject already. Just deallocate the task
4084 	 * ref we took and go away.
4085 	 *
4086 	 * It is also possible that several nsrequests are in flight,
4087 	 * only one shall NULL-out the port entry, and this is the one
4088 	 * that gets to dealloc the port.
4089 	 *
4090 	 * Check for a stale no-senders notification. A call to any function
4091 	 * that vends out send rights to this port could resurrect it between
4092 	 * this notification being generated and actually being handled here.
4093 	 */
4094 	tro = get_thread_ro(thread);
4095 	if (tro->tro_ports[flavor] != port ||
4096 	    !ipc_kobject_is_mscount_current_locked(port, mscount)) {
4097 		ip_mq_unlock(port);
4098 		thread_mtx_unlock(thread);
4099 		thread_deallocate(thread);
4100 		return;
4101 	}
4102 
4103 	zalloc_ro_clear_field(ZONE_ID_THREAD_RO, tro, tro_ports[flavor]);
4104 	thread_mtx_unlock(thread);
4105 
4106 	ipc_kobject_dealloc_port_and_unlock(port, mscount, kotype);
4107 
4108 	thread_deallocate(thread);
4109 }
4110 
4111 /*
4112  * The 'thread_region_page_shift' is used by footprint
4113  * to specify the page size that it will use to
4114  * accomplish its accounting work on the task being
4115  * inspected. Since footprint uses a thread for each
4116  * task that it works on, we need to keep the page_shift
4117  * on a per-thread basis.
4118  */
4119 
4120 int
thread_self_region_page_shift(void)4121 thread_self_region_page_shift(void)
4122 {
4123 	/*
4124 	 * Return the page shift that this thread
4125 	 * would like to use for its accounting work.
4126 	 */
4127 	return current_thread()->thread_region_page_shift;
4128 }
4129 
4130 void
thread_self_region_page_shift_set(int pgshift)4131 thread_self_region_page_shift_set(
4132 	int pgshift)
4133 {
4134 	/*
4135 	 * Set the page shift that this thread
4136 	 * would like to use for its accounting work
4137 	 * when dealing with a task.
4138 	 */
4139 	current_thread()->thread_region_page_shift = pgshift;
4140 }
4141 
4142 __startup_func
4143 __static_testable void
ctid_table_init(void)4144 ctid_table_init(void)
4145 {
4146 	/*
4147 	 * Pretend the early boot setup didn't exist,
4148 	 * and pick a mangling nonce.
4149 	 */
4150 	*compact_id_resolve(&ctid_table, 0) = THREAD_NULL;
4151 	ctid_nonce = (uint32_t)early_random() & CTID_MASK;
4152 }
4153 
4154 
4155 /*
4156  * This maps the [0, CTID_MAX_THREAD_NUMBER] range
4157  * to [1, CTID_MAX_THREAD_NUMBER + 1 == CTID_MASK]
4158  * so that in mangled form, '0' is an invalid CTID.
4159  */
4160 static ctid_t
ctid_mangle(compact_id_t cid)4161 ctid_mangle(compact_id_t cid)
4162 {
4163 	return (cid == ctid_nonce ? CTID_MASK : cid) ^ ctid_nonce;
4164 }
4165 
4166 static compact_id_t
ctid_unmangle(ctid_t ctid)4167 ctid_unmangle(ctid_t ctid)
4168 {
4169 	ctid ^= ctid_nonce;
4170 	return ctid == CTID_MASK ? ctid_nonce : ctid;
4171 }
4172 
4173 void
ctid_table_add(thread_t thread)4174 ctid_table_add(thread_t thread)
4175 {
4176 	compact_id_t cid;
4177 
4178 	cid = compact_id_get(&ctid_table, CTID_MAX_THREAD_NUMBER, thread);
4179 	thread->ctid = ctid_mangle(cid);
4180 }
4181 
4182 void
ctid_table_remove(thread_t thread)4183 ctid_table_remove(thread_t thread)
4184 {
4185 	__assert_only thread_t value;
4186 
4187 	value = compact_id_put(&ctid_table, ctid_unmangle(thread->ctid));
4188 	assert3p(value, ==, thread);
4189 	thread->ctid = 0;
4190 }
4191 
4192 thread_t
ctid_get_thread_unsafe(ctid_t ctid)4193 ctid_get_thread_unsafe(ctid_t ctid)
4194 {
4195 	if (ctid && ctid <= CTID_MAX_THREAD_NUMBER && compact_id_slab_valid(&ctid_table, ctid_unmangle(ctid))) {
4196 		return *compact_id_resolve(&ctid_table, ctid_unmangle(ctid));
4197 	}
4198 	return THREAD_NULL;
4199 }
4200 
4201 thread_t
ctid_get_thread(ctid_t ctid)4202 ctid_get_thread(ctid_t ctid)
4203 {
4204 	thread_t thread = THREAD_NULL;
4205 
4206 	if (ctid) {
4207 		thread = *compact_id_resolve(&ctid_table, ctid_unmangle(ctid));
4208 		assert(thread && thread->ctid == ctid);
4209 	}
4210 	return thread;
4211 }
4212 
4213 ctid_t
thread_get_ctid(thread_t thread)4214 thread_get_ctid(thread_t thread)
4215 {
4216 	return thread->ctid;
4217 }
4218 
4219 /*
4220  * Adjust code signature dependent thread state.
4221  *
4222  * Called to allow code signature dependent adjustments to the thread
4223  * state. Note that this is usually called twice for the main thread:
4224  * Once at thread creation by thread_create, when the signature is
4225  * potentially not attached yet (which is usually the case for the
4226  * first/main thread of a task), and once after the task's signature
4227  * has actually been attached.
4228  *
4229  */
4230 kern_return_t
thread_process_signature(thread_t thread,task_t task)4231 thread_process_signature(thread_t thread, task_t task)
4232 {
4233 	return machine_thread_process_signature(thread, task);
4234 }
4235 
4236 #if CONFIG_SPTM
4237 
4238 void
thread_associate_txm_thread_stack(uintptr_t thread_stack)4239 thread_associate_txm_thread_stack(uintptr_t thread_stack)
4240 {
4241 	thread_t self = current_thread();
4242 
4243 	if (self->txm_thread_stack != 0) {
4244 		panic("attempted multiple TXM thread associations: %lu | %lu",
4245 		    self->txm_thread_stack, thread_stack);
4246 	}
4247 
4248 	self->txm_thread_stack = thread_stack;
4249 }
4250 
4251 void
thread_disassociate_txm_thread_stack(uintptr_t thread_stack)4252 thread_disassociate_txm_thread_stack(uintptr_t thread_stack)
4253 {
4254 	thread_t self = current_thread();
4255 
4256 	if (self->txm_thread_stack == 0) {
4257 		panic("attempted to disassociate non-existent TXM thread");
4258 	} else if (self->txm_thread_stack != thread_stack) {
4259 		panic("invalid disassociation for TXM thread: %lu | %lu",
4260 		    self->txm_thread_stack, thread_stack);
4261 	}
4262 
4263 	self->txm_thread_stack = 0;
4264 }
4265 
4266 uintptr_t
thread_get_txm_thread_stack(void)4267 thread_get_txm_thread_stack(void)
4268 {
4269 	return current_thread()->txm_thread_stack;
4270 }
4271 
4272 #endif
4273 
4274 #if CONFIG_DTRACE
4275 uint32_t
dtrace_get_thread_predcache(thread_t thread)4276 dtrace_get_thread_predcache(thread_t thread)
4277 {
4278 	if (thread != THREAD_NULL) {
4279 		return thread->t_dtrace_predcache;
4280 	} else {
4281 		return 0;
4282 	}
4283 }
4284 
4285 int64_t
dtrace_get_thread_vtime(thread_t thread)4286 dtrace_get_thread_vtime(thread_t thread)
4287 {
4288 	if (thread != THREAD_NULL) {
4289 		return thread->t_dtrace_vtime;
4290 	} else {
4291 		return 0;
4292 	}
4293 }
4294 
4295 int
dtrace_get_thread_last_cpu_id(thread_t thread)4296 dtrace_get_thread_last_cpu_id(thread_t thread)
4297 {
4298 	if ((thread != THREAD_NULL) && (thread->last_processor != PROCESSOR_NULL)) {
4299 		return thread->last_processor->cpu_id;
4300 	} else {
4301 		return -1;
4302 	}
4303 }
4304 
4305 int64_t
dtrace_get_thread_tracing(thread_t thread)4306 dtrace_get_thread_tracing(thread_t thread)
4307 {
4308 	if (thread != THREAD_NULL) {
4309 		return thread->t_dtrace_tracing;
4310 	} else {
4311 		return 0;
4312 	}
4313 }
4314 
4315 uint16_t
dtrace_get_thread_inprobe(thread_t thread)4316 dtrace_get_thread_inprobe(thread_t thread)
4317 {
4318 	if (thread != THREAD_NULL) {
4319 		return thread->t_dtrace_inprobe;
4320 	} else {
4321 		return 0;
4322 	}
4323 }
4324 
4325 vm_offset_t
thread_get_kernel_stack(thread_t thread)4326 thread_get_kernel_stack(thread_t thread)
4327 {
4328 	if (thread != THREAD_NULL) {
4329 		return thread->kernel_stack;
4330 	} else {
4331 		return 0;
4332 	}
4333 }
4334 
4335 #if KASAN
4336 struct kasan_thread_data *
kasan_get_thread_data(thread_t thread)4337 kasan_get_thread_data(thread_t thread)
4338 {
4339 	return &thread->kasan_data;
4340 }
4341 #endif
4342 
4343 #if CONFIG_KCOV
4344 kcov_thread_data_t *
kcov_get_thread_data(thread_t thread)4345 kcov_get_thread_data(thread_t thread)
4346 {
4347 	return &thread->kcov_data;
4348 }
4349 #endif
4350 
4351 #if CONFIG_STKSZ
4352 /*
4353  * Returns base of a thread's kernel stack.
4354  *
4355  * Coverage sanitizer instruments every function including those that participates in stack handoff between threads.
4356  * There is a window in which CPU still holds old values but stack has been handed over to anoher thread already.
4357  * In this window kernel_stack is 0 but CPU still uses the original stack (until contex switch occurs). The original
4358  * kernel_stack value is preserved in ksancov_stack during this window.
4359  */
4360 vm_offset_t
kcov_stksz_get_thread_stkbase(thread_t thread)4361 kcov_stksz_get_thread_stkbase(thread_t thread)
4362 {
4363 	if (thread != THREAD_NULL) {
4364 		kcov_thread_data_t *data = kcov_get_thread_data(thread);
4365 		if (data->ktd_stksz.kst_stack) {
4366 			return data->ktd_stksz.kst_stack;
4367 		} else {
4368 			return thread->kernel_stack;
4369 		}
4370 	} else {
4371 		return 0;
4372 	}
4373 }
4374 
4375 vm_offset_t
kcov_stksz_get_thread_stksize(thread_t thread)4376 kcov_stksz_get_thread_stksize(thread_t thread)
4377 {
4378 	if (thread != THREAD_NULL) {
4379 		return kernel_stack_size;
4380 	} else {
4381 		return 0;
4382 	}
4383 }
4384 
4385 void
kcov_stksz_set_thread_stack(thread_t thread,vm_offset_t stack)4386 kcov_stksz_set_thread_stack(thread_t thread, vm_offset_t stack)
4387 {
4388 	kcov_thread_data_t *data = kcov_get_thread_data(thread);
4389 	data->ktd_stksz.kst_stack = stack;
4390 }
4391 #endif /* CONFIG_STKSZ */
4392 
4393 int64_t
dtrace_calc_thread_recent_vtime(thread_t thread)4394 dtrace_calc_thread_recent_vtime(thread_t thread)
4395 {
4396 	if (thread == THREAD_NULL) {
4397 		return 0;
4398 	}
4399 
4400 	struct recount_usage usage = { 0 };
4401 	recount_current_thread_usage(&usage);
4402 	return (int64_t)(recount_usage_time_mach(&usage));
4403 }
4404 
4405 void
dtrace_set_thread_predcache(thread_t thread,uint32_t predcache)4406 dtrace_set_thread_predcache(thread_t thread, uint32_t predcache)
4407 {
4408 	if (thread != THREAD_NULL) {
4409 		thread->t_dtrace_predcache = predcache;
4410 	}
4411 }
4412 
4413 void
dtrace_set_thread_vtime(thread_t thread,int64_t vtime)4414 dtrace_set_thread_vtime(thread_t thread, int64_t vtime)
4415 {
4416 	if (thread != THREAD_NULL) {
4417 		thread->t_dtrace_vtime = vtime;
4418 	}
4419 }
4420 
4421 void
dtrace_set_thread_tracing(thread_t thread,int64_t accum)4422 dtrace_set_thread_tracing(thread_t thread, int64_t accum)
4423 {
4424 	if (thread != THREAD_NULL) {
4425 		thread->t_dtrace_tracing = accum;
4426 	}
4427 }
4428 
4429 void
dtrace_set_thread_inprobe(thread_t thread,uint16_t inprobe)4430 dtrace_set_thread_inprobe(thread_t thread, uint16_t inprobe)
4431 {
4432 	if (thread != THREAD_NULL) {
4433 		thread->t_dtrace_inprobe = inprobe;
4434 	}
4435 }
4436 
4437 void
dtrace_thread_bootstrap(void)4438 dtrace_thread_bootstrap(void)
4439 {
4440 	task_t task = current_task();
4441 
4442 	if (task->thread_count == 1) {
4443 		thread_t thread = current_thread();
4444 		if (thread->t_dtrace_flags & TH_DTRACE_EXECSUCCESS) {
4445 			thread->t_dtrace_flags &= ~TH_DTRACE_EXECSUCCESS;
4446 			DTRACE_PROC(exec__success);
4447 			extern uint64_t kdp_task_exec_meta_flags(task_t task);
4448 			KDBG(BSDDBG_CODE(DBG_BSD_PROC, BSD_PROC_EXEC),
4449 			    task_pid(task), kdp_task_exec_meta_flags(task));
4450 		}
4451 		DTRACE_PROC(start);
4452 	}
4453 	DTRACE_PROC(lwp__start);
4454 }
4455 
4456 void
dtrace_thread_didexec(thread_t thread)4457 dtrace_thread_didexec(thread_t thread)
4458 {
4459 	thread->t_dtrace_flags |= TH_DTRACE_EXECSUCCESS;
4460 }
4461 #endif /* CONFIG_DTRACE */
4462