xref: /xnu-12377.81.4/osfmk/kern/thread.h (revision 043036a2b3718f7f0be807e2870f8f47d3fa0796)
1 /*
2  * Copyright (c) 2000-2019 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * @OSF_FREE_COPYRIGHT@
30  */
31 /*
32  * Mach Operating System
33  * Copyright (c) 1991,1990,1989,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:	thread.h
60  *	Author:	Avadis Tevanian, Jr.
61  *
62  *	This file contains the structure definitions for threads.
63  *
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 #ifndef _KERN_THREAD_H_
85 #define _KERN_THREAD_H_
86 
87 #include <mach/kern_return.h>
88 #include <mach/mach_types.h>
89 #include <mach/mach_param.h>
90 #include <mach/message.h>
91 #include <mach/boolean.h>
92 #include <mach/vm_param.h>
93 #include <mach/thread_info.h>
94 #include <mach/thread_status.h>
95 #include <mach/exception_types.h>
96 
97 #include <kern/kern_types.h>
98 #include <vm/vm_kern.h>
99 #include <sys/cdefs.h>
100 #include <sys/_types/_size_t.h>
101 
102 #ifdef MACH_KERNEL_PRIVATE
103 #include <mach_assert.h>
104 #include <mach_ldebug.h>
105 
106 #include <ipc/ipc_types.h>
107 
108 #include <mach/port.h>
109 #include <kern/cpu_number.h>
110 #include <kern/smp.h>
111 #include <kern/smr_types.h>
112 #include <kern/queue.h>
113 
114 #include <kern/timer.h>
115 #include <kern/simple_lock.h>
116 #include <kern/locks.h>
117 #include <kern/sched.h>
118 #include <kern/sched_prim.h>
119 #include <mach/sfi_class.h>
120 #include <kern/thread_call.h>
121 #include <kern/thread_group.h>
122 #include <kern/timer_call.h>
123 #include <kern/task.h>
124 #include <kern/exception.h>
125 #include <kern/affinity.h>
126 #include <kern/debug.h>
127 #include <kern/block_hint.h>
128 #include <kern/recount.h>
129 #include <kern/turnstile.h>
130 #include <kern/mpsc_queue.h>
131 
132 #if CONFIG_EXCLAVES
133 #include <mach/exclaves.h>
134 #endif /* CONFIG_EXCLAVES */
135 
136 #include <kern/waitq.h>
137 #include <san/kasan.h>
138 #include <san/kcov_data.h>
139 #include <os/refcnt.h>
140 
141 #include <ipc/ipc_kmsg.h>
142 
143 #include <machine/atomic.h>
144 #include <machine/cpu_data.h>
145 #include <machine/thread.h>
146 
147 #endif  /* MACH_KERNEL_PRIVATE */
148 #ifdef XNU_KERNEL_PRIVATE
149 /* priority queue static asserts fail for __ARM64_ARCH_8_32__ kext builds */
150 #include <kern/priority_queue.h>
151 #endif /* XNU_KERNEL_PRIVATE */
152 
153 __BEGIN_DECLS
154 
155 #ifdef XNU_KERNEL_PRIVATE
156 #if CONFIG_TASKWATCH
157 /* Taskwatch related. TODO: find this a better home */
158 typedef struct task_watcher task_watch_t;
159 #endif /* CONFIG_TASKWATCH */
160 
161 /* Thread tags; for easy identification. */
162 __options_closed_decl(thread_tag_t, uint16_t, {
163 	THREAD_TAG_MAINTHREAD   = 0x01,
164 	THREAD_TAG_CALLOUT      = 0x02,
165 	THREAD_TAG_IOWORKLOOP   = 0x04,
166 	THREAD_TAG_PTHREAD      = 0x10,
167 	THREAD_TAG_WORKQUEUE    = 0x20,
168 	THREAD_TAG_USER_JOIN    = 0x40,
169 	THREAD_TAG_AIO_WORKQUEUE    = 0x80,
170 });
171 
172 typedef struct thread_ro *thread_ro_t;
173 
174 /*!
175  * @struct thread_ro
176  *
177  * @brief
178  * A structure allocated in a read only zone that safely
179  * represents the linkages of a thread to its cred, proc, task, ...
180  *
181  * @discussion
182  * The lifetime of a @c thread_ro structure is 1:1 with that
183  * of a @c thread_t or a @c uthread_t and holding a thread reference
184  * always allows to dereference this structure safely.
185  */
186 struct thread_ro {
187 	struct thread              *tro_owner;
188 #if MACH_BSD
189 	__xnu_struct_group(thread_ro_creds, tro_creds, {
190 		/*
191 		 * @c tro_cred holds the current thread credentials.
192 		 *
193 		 * For most threads, this is a cache of the proc's
194 		 * credentials that has been updated at the last
195 		 * syscall boundary via current_cached_proc_cred_update().
196 		 *
197 		 * If the thread assumed a different identity using settid(),
198 		 * then the proc cached credential lives in @c tro_realcred
199 		 * instead.
200 		 */
201 		struct ucred       *tro_cred;
202 		struct ucred       *tro_realcred;
203 	});
204 	struct proc                *tro_proc;
205 	struct proc_ro             *tro_proc_ro;
206 #endif
207 	struct task                *tro_task;
208 
209 	struct ipc_port            *tro_ports[THREAD_SELF_PORT_COUNT];  /* no right */
210 #if CONFIG_CSR
211 	struct ipc_port            *tro_settable_self_port;             /* send right */
212 #endif /* CONFIG_CSR */
213 
214 	struct exception_action    *tro_exc_actions;
215 };
216 
217 /*
218  * Flags for `thread set status`.
219  */
220 __options_decl(thread_set_status_flags_t, uint32_t, {
221 	TSSF_FLAGS_NONE = 0,
222 
223 	/* Translate the state to user. */
224 	TSSF_TRANSLATE_TO_USER = 0x01,
225 
226 	/* Translate the state to user. Preserve flags */
227 	TSSF_PRESERVE_FLAGS = 0x02,
228 
229 	/* Check kernel signed flag */
230 	TSSF_CHECK_USER_FLAGS = 0x04,
231 
232 	/* Allow only user state PTRS */
233 	TSSF_ALLOW_ONLY_USER_PTRS = 0x08,
234 
235 	/* Generate random diversifier and stash it */
236 	TSSF_RANDOM_USER_DIV = 0x10,
237 
238 	/* Stash sigreturn token */
239 	TSSF_STASH_SIGRETURN_TOKEN = 0x20,
240 
241 	/* Check sigreturn token */
242 	TSSF_CHECK_SIGRETURN_TOKEN = 0x40,
243 
244 	/* Allow only matching sigreturn token */
245 	TSSF_ALLOW_ONLY_MATCHING_TOKEN = 0x80,
246 
247 	/* Stash diversifier from thread */
248 	TSSF_THREAD_USER_DIV = 0x100,
249 
250 	/* Check for entitlement */
251 	TSSF_CHECK_ENTITLEMENT = 0x200,
252 
253 	/* Stash diversifier from task */
254 	TSSF_TASK_USER_DIV = 0x400,
255 
256 	/* Only take the PC from the new thread state */
257 	TSSF_ONLY_PC = 0x800,
258 });
259 
260 /*
261  * Size in bits of compact thread id (ctid).
262  */
263 #define CTID_SIZE_BIT 20
264 typedef uint32_t ctid_t;
265 
266 #endif /* XNU_KERNEL_PRIVATE */
267 #ifdef MACH_KERNEL_PRIVATE
268 
269 extern zone_t thread_ro_zone;
270 
271 __options_decl(thread_work_interval_flags_t, uint32_t, {
272 	TH_WORK_INTERVAL_FLAGS_NONE            = 0x0,
273 #if CONFIG_SCHED_AUTO_JOIN
274 	/* Flags to indicate status about work interval thread is currently part of */
275 	TH_WORK_INTERVAL_FLAGS_AUTO_JOIN_LEAK  = 0x1,
276 #endif /* CONFIG_SCHED_AUTO_JOIN */
277 	TH_WORK_INTERVAL_FLAGS_HAS_WORKLOAD_ID = 0x2,
278 	TH_WORK_INTERVAL_FLAGS_RT_ALLOWED      = 0x4,
279 });
280 
281 #if CONFIG_EXCLAVES
282 /* Thread exclaves interrupt-safe state bits (ORd) */
283 __options_decl(thread_exclaves_intstate_flags_t, uint32_t, {
284 	/* Thread is currently executing in secure kernel or exclaves userspace
285 	 * or was interrupted/preempted while doing so. */
286 	TH_EXCLAVES_EXECUTION                  = 0x1,
287 });
288 
289 __options_decl(thread_exclaves_state_flags_t, uint16_t, {
290 /* Thread exclaves state bits (ORd) */
291 	/* Thread is handling RPC from a client in xnu or Darwin userspace (but
292 	 * may have returned to xnu due to an exclaves scheduler request or having
293 	 * upcalled). Must not re-enter exclaves via RPC or return to Darwin
294 	 * userspace. */
295 	TH_EXCLAVES_RPC                        = 0x1,
296 	/* Thread has made an upcall RPC request back into xnu while handling RPC
297 	 * into exclaves from a client in xnu or Darwin userspace. Must not
298 	 * re-enter exclaves via RPC or return to Darwin userspace. */
299 	TH_EXCLAVES_UPCALL                     = 0x2,
300 	/* Thread has made an exclaves scheduler request (such as a wait or wake)
301 	 * from the xnu scheduler while handling RPC into exclaves from a client in
302 	 * xnu or Darwin userspace. Must not re-enter exclaves via RPC or return to
303 	 * Darwin userspace. */
304 	TH_EXCLAVES_SCHEDULER_REQUEST          = 0x4,
305 	/* Thread is calling into xnu proxy server directly (but may have
306 	 * returned to xnu due to an exclaves scheduler request or having
307 	 * upcalled). Must not re-enter exclaves or return to Darwin userspace.
308 	 */
309 	TH_EXCLAVES_XNUPROXY                   = 0x8,
310 	/* Thread is calling into the exclaves scheduler directly.
311 	 * Must not re-enter exclaves or return to Darwin userspace.
312 	 */
313 	TH_EXCLAVES_SCHEDULER_CALL             = 0x10,
314 	/* Thread has called the stop upcall and once the thread returns from
315 	 * downcall, exit_with_reason needs to be called on the task.
316 	 */
317 	TH_EXCLAVES_STOP_UPCALL_PENDING        = 0x20,
318 	/* Thread is expecting that an exclaves-side thread may be spawned.
319 	 */
320 	TH_EXCLAVES_SPAWN_EXPECTED             = 0x40,
321 	/* Thread is resuming the panic thread.
322 	 * Must not re-enter exclaves or return to Darwin userspace.
323 	 */
324 	TH_EXCLAVES_RESUME_PANIC_THREAD        = 0x80,
325 });
326 #define TH_EXCLAVES_STATE_ANY           ( \
327     TH_EXCLAVES_RPC               | \
328     TH_EXCLAVES_UPCALL            | \
329     TH_EXCLAVES_SCHEDULER_REQUEST | \
330     TH_EXCLAVES_XNUPROXY          | \
331     TH_EXCLAVES_SCHEDULER_CALL    | \
332     TH_EXCLAVES_RESUME_PANIC_THREAD)
333 
334 __options_decl(thread_exclaves_inspection_flags_t, uint16_t, {
335 	/* Thread is on Stackshot's inspection queue */
336 	TH_EXCLAVES_INSPECTION_STACKSHOT       = 0x1,
337 	/* Thread is on Kperf's inspection queue */
338 	TH_EXCLAVES_INSPECTION_KPERF           = 0x2,
339 	/* Thread must not be inspected (may deadlock, etc.) - set by collector thread*/
340 	TH_EXCLAVES_INSPECTION_NOINSPECT       = 0x8000,
341 });
342 
343 #endif /* CONFIG_EXCLAVES */
344 
345 typedef union thread_rr_state {
346 	uint32_t trr_value;
347 	struct {
348 #define TRR_FAULT_NONE     0
349 #define TRR_FAULT_PENDING  1
350 #define TRR_FAULT_OBSERVED 2
351 		/*
352 		 * Set to TRR_FAULT_PENDING with interrupts disabled
353 		 * by the thread when it is entering a user fault codepath.
354 		 *
355 		 * Moved to TRR_FAULT_OBSERVED from TRR_FAULT_PENDING:
356 		 * - by the thread if at IPI time,
357 		 * - or by task_restartable_ranges_synchronize() if the thread
358 		 *   is interrupted (under the thread lock)
359 		 *
360 		 * Cleared by the thread when returning from a user fault
361 		 * codepath.
362 		 */
363 		uint8_t  trr_fault_state;
364 
365 		/*
366 		 * Set by task_restartable_ranges_synchronize()
367 		 * if trr_fault_state is TRR_FAULT_OBSERVED
368 		 * and a rendez vous at the AST is required.
369 		 *
370 		 * Set atomically if trr_fault_state == TRR_FAULT_OBSERVED,
371 		 * and trr_ipi_ack_pending == 0
372 		 */
373 		uint8_t  trr_sync_waiting;
374 
375 		/*
376 		 * Updated under the thread_lock(),
377 		 * set by task_restartable_ranges_synchronize()
378 		 * when the thread was IPIed and the caller is waiting
379 		 * for an ACK.
380 		 */
381 		uint16_t trr_ipi_ack_pending;
382 	};
383 } thread_rr_state_t;
384 
385 struct thread {
386 #if MACH_ASSERT
387 #define THREAD_MAGIC 0x1fc01fc01fc01fc0ULL /* materializes with a single mov immediate */
388 	/* Ensure nothing uses &thread as a queue entry */
389 	uint64_t                thread_magic;
390 #endif /* MACH_ASSERT */
391 
392 	/*
393 	 *	NOTE:	The runq field in the thread structure has an unusual
394 	 *	locking protocol.  If its value is PROCESSOR_NULL, then it is
395 	 *	locked by the thread_lock, but if its value is something else
396 	 *	then it is locked by the associated run queue lock. It is
397 	 *	set to PROCESSOR_NULL without holding the thread lock, but the
398 	 *	transition from PROCESSOR_NULL to non-null must be done
399 	 *	under the thread lock and the run queue lock. To enforce the
400 	 *	protocol, runq should only be accessed using the
401 	 *	thread_get/set/clear_runq functions and locked variants below.
402 	 *
403 	 *	New waitq APIs allow the 'links' and '__runq' fields to be
404 	 *	anywhere in the thread structure.
405 	 */
406 	union {
407 		queue_chain_t                   runq_links;             /* run queue links */
408 		queue_chain_t                   wait_links;             /* wait queue links */
409 		struct mpsc_queue_chain         mpsc_links;             /* thread daemon mpsc links */
410 		struct priority_queue_entry_sched wait_prioq_links;       /* priority ordered waitq links */
411 	};
412 
413 	event64_t               wait_event;     /* wait queue event */
414 	struct { processor_t    runq; } __runq; /* internally managed run queue assignment, see above comment */
415 	waitq_t                 waitq;          /* wait queue this thread is enqueued on */
416 	struct turnstile       *turnstile;      /* thread's turnstile, protected by primitives interlock */
417 	void                   *inheritor;      /* inheritor of the primitive the thread will block on */
418 	struct priority_queue_sched_max sched_inheritor_queue; /* Inheritor queue for kernel promotion */
419 	struct priority_queue_sched_max base_inheritor_queue; /* Inheritor queue for user promotion */
420 
421 #if CONFIG_SCHED_EDGE
422 	bool            th_bound_cluster_enqueued;
423 	bool            th_shared_rsrc_enqueued[CLUSTER_SHARED_RSRC_TYPE_COUNT];
424 	bool            th_shared_rsrc_heavy_user[CLUSTER_SHARED_RSRC_TYPE_COUNT];
425 	bool            th_shared_rsrc_heavy_perf_control[CLUSTER_SHARED_RSRC_TYPE_COUNT];
426 	/*
427 	 * Caution! These bits should only be written/read by the current,
428 	 * just previous, or thread_setrun()-ing processor, before this
429 	 * thread can be picked up to run by its next processor.
430 	 */
431 	uint8_t
432 	    th_expired_quantum_on_lower_core:1,
433 	    th_expired_quantum_on_higher_core:1,
434 	:0;
435 #endif /* CONFIG_SCHED_EDGE */
436 
437 #if CONFIG_SCHED_CLUTCH
438 	/*
439 	 * In the clutch scheduler, the threads are maintained in runqs at the clutch_bucket
440 	 * level (clutch_bucket defines a unique thread group and scheduling bucket pair). The
441 	 * thread is linked via a couple of linkages in the clutch bucket:
442 	 *
443 	 * - A stable priority queue linkage which is the main runqueue (based on sched_pri) for the clutch bucket
444 	 * - A regular priority queue linkage which is based on thread's base/promoted pri (used for clutch bucket priority calculation)
445 	 * - A queue linkage used for timesharing operations of threads at the scheduler tick
446 	 */
447 	struct priority_queue_entry_stable      th_clutch_runq_link;
448 	struct priority_queue_entry_sched       th_clutch_pri_link;
449 	queue_chain_t                           th_clutch_timeshare_link;
450 #endif /* CONFIG_SCHED_CLUTCH */
451 
452 	/* Data updated during assert_wait/thread_wakeup */
453 	decl_simple_lock_data(, sched_lock);     /* scheduling lock (thread_lock()) */
454 	decl_simple_lock_data(, wake_lock);      /* for thread stop / wait (wake_lock()) */
455 	uint16_t                options;        /* options set by thread itself */
456 #define TH_OPT_INTMASK          0x0003          /* interrupt / abort level */
457 #define TH_OPT_VMPRIV           0x0004          /* may allocate reserved memory */
458 #define TH_OPT_SYSTEM_CRITICAL  0x0010          /* Thread must always be allowed to run - even under heavy load */
459 #define TH_OPT_PROC_CPULIMIT    0x0020          /* Thread has a task-wide CPU limit applied to it */
460 #define TH_OPT_PRVT_CPULIMIT    0x0040          /* Thread has a thread-private CPU limit applied to it */
461 #define TH_OPT_IDLE_THREAD      0x0080          /* Thread is a per-processor idle thread */
462 #define TH_OPT_GLOBAL_FORCED_IDLE       0x0100  /* Thread performs forced idle for thermal control */
463 #define TH_OPT_SCHED_VM_GROUP   0x0200          /* Thread belongs to special scheduler VM group */
464 #define TH_OPT_HONOR_QLIMIT     0x0400          /* Thread will honor qlimit while sending mach_msg, regardless of MACH_SEND_ALWAYS */
465 #define TH_OPT_SEND_IMPORTANCE  0x0800          /* Thread will allow importance donation from kernel rpc */
466 #define TH_OPT_ZONE_PRIV        0x1000          /* Thread may use the zone replenish reserve */
467 #define TH_OPT_IPC_TG_BLOCKED   0x2000          /* Thread blocked in sync IPC and has made the thread group blocked callout */
468 #define TH_OPT_FORCED_LEDGER    0x4000          /* Thread has a forced CPU limit  */
469 #define TH_IN_MACH_EXCEPTION    0x8000          /* Thread is currently handling a mach exception */
470 #if CONFIG_EXCLAVES
471 #define TH_OPT_AOE              0x10000   /* Thread is an AOE exclave thread */
472 #endif /* CONFIG_EXCLAVES */
473 
474 	bool                    wake_active;    /* wake event on stop */
475 	bool                    at_safe_point;  /* thread_abort_safely allowed */
476 	uint8_t                 sched_saved_run_weight;
477 #if DEVELOPMENT || DEBUG
478 	bool                    pmap_footprint_suspended;
479 #endif /* DEVELOPMENT || DEBUG */
480 
481 
482 	ast_t                   reason;         /* why we blocked */
483 	uint32_t                quantum_remaining;
484 	wait_result_t           wait_result;    /* outcome of wait -
485 	                                        * may be examined by this thread
486 	                                        * WITHOUT locking */
487 	thread_rr_state_t       t_rr_state;     /* state for restartable ranges */
488 	thread_continue_t       continuation;   /* continue here next dispatch */
489 	void                   *parameter;      /* continuation parameter */
490 
491 	/* Data updated/used in thread_invoke */
492 	vm_offset_t             kernel_stack;   /* current kernel stack */
493 	vm_offset_t             reserved_stack; /* reserved kernel stack */
494 
495 	/*** Machine-dependent state ***/
496 	struct machine_thread   machine;
497 
498 #if KASAN
499 	struct kasan_thread_data kasan_data;
500 #endif
501 #if CONFIG_KCOV
502 	kcov_thread_data_t       kcov_data;
503 #endif
504 
505 	/* Thread state: */
506 	int                     state;
507 /*
508  *	Thread states [bits or'ed]
509  * All but TH_WAIT_REPORT are encoded in SS_TH_FLAGS
510  * All are encoded in kcdata.py ('ths_state')
511  */
512 #define TH_WAIT                 0x01            /* queued for waiting */
513 #define TH_SUSP                 0x02            /* stopped or requested to stop */
514 #define TH_RUN                  0x04            /* running or on runq */
515 #define TH_UNINT                0x08            /* waiting uninteruptibly */
516 #define TH_TERMINATE            0x10            /* halted at termination */
517 #define TH_TERMINATE2           0x20            /* added to termination queue */
518 #define TH_WAIT_REPORT          0x40            /* the wait is using the sched_call,
519 	                                        * only set if TH_WAIT is also set */
520 #define TH_IDLE                 0x80            /* idling processor */
521 #define TH_WAKING              0x100            /* between waitq remove and thread_go */
522 
523 	/* Scheduling information */
524 	sched_mode_t            sched_mode;     /* scheduling mode */
525 	sched_mode_t            saved_mode;     /* saved mode during forced mode demotion */
526 
527 	/* This thread's contribution to global sched counters */
528 	sched_bucket_t          th_sched_bucket;
529 
530 	sfi_class_id_t          sfi_class;      /* SFI class (XXX Updated on CSW/QE/AST) */
531 	sfi_class_id_t          sfi_wait_class; /* Currently in SFI wait for this class, protected by sfi_lock */
532 
533 	uint32_t                sched_flags;            /* current flag bits */
534 #if CONFIG_SCHED_SMT
535 #define TH_SFLAG_NO_SMT                 0x0001          /* On an SMT CPU, this thread must be scheduled alone */
536 #endif /* CONFIG_SCHED_SMT */
537 
538 #define TH_SFLAG_FAILSAFE               0x0002          /* fail-safe has tripped */
539 #define TH_SFLAG_THROTTLED              0x0004          /* throttled thread forced to timeshare mode (may be applied in addition to failsafe) */
540 
541 /* unused TH_SFLAG_PROMOTED             0x0008 */
542 #define TH_SFLAG_ABORT                  0x0010          /* abort interruptible waits */
543 #define TH_SFLAG_ABORTSAFELY            0x0020          /* ... but only those at safe point */
544 #define TH_SFLAG_ABORTED_MASK           (TH_SFLAG_ABORT | TH_SFLAG_ABORTSAFELY)
545 #define TH_SFLAG_DEPRESS                0x0040          /* normal depress yield */
546 #define TH_SFLAG_POLLDEPRESS            0x0080          /* polled depress yield */
547 #define TH_SFLAG_DEPRESSED_MASK         (TH_SFLAG_DEPRESS | TH_SFLAG_POLLDEPRESS)
548 /* unused TH_SFLAG_PRI_UPDATE           0x0100 */
549 #define TH_SFLAG_EAGERPREEMPT           0x0200          /* Any preemption of this thread should be treated as if AST_URGENT applied */
550 #define TH_SFLAG_RW_PROMOTED            0x0400          /* promote reason: blocking with RW lock held */
551 #define TH_SFLAG_BASE_PRI_FROZEN        0x0800          /* (effective) base_pri is frozen */
552 #define TH_SFLAG_WAITQ_PROMOTED         0x1000          /* promote reason: waitq wakeup (generally for IPC receive) */
553 
554 #if __AMP__
555 /* unused TH_SFLAG_ECORE_ONLY           0x2000 */
556 /* unused TH_SFLAG_PCORE_ONLY           0x4000 */
557 #endif
558 
559 #define TH_SFLAG_EXEC_PROMOTED          0x8000          /* promote reason: thread is in an exec */
560 
561 #define TH_SFLAG_THREAD_GROUP_AUTO_JOIN 0x10000         /* thread has been auto-joined to thread group */
562 #if __AMP__
563 /* unused TH_SFLAG_BOUND_SOFT           0x20000 */
564 #endif /* __AMP__ */
565 
566 #if CONFIG_PREADOPT_TG
567 #define TH_SFLAG_REEVALUTE_TG_HIERARCHY_LATER 0x40000   /* thread needs to reevaluate its TG hierarchy */
568 #endif
569 
570 #define TH_SFLAG_FLOOR_PROMOTED               0x80000   /* promote reason: boost requested */
571 
572 /* 'promote reasons' that request a priority floor only, not a custom priority */
573 #define TH_SFLAG_PROMOTE_REASON_MASK    (TH_SFLAG_RW_PROMOTED | TH_SFLAG_WAITQ_PROMOTED | TH_SFLAG_EXEC_PROMOTED | TH_SFLAG_FLOOR_PROMOTED)
574 
575 #define TH_SFLAG_RT_DISALLOWED         0x100000         /* thread wants RT but may not have joined a work interval that allows it */
576 #define TH_SFLAG_DEMOTED_MASK      (TH_SFLAG_THROTTLED | TH_SFLAG_FAILSAFE | TH_SFLAG_RT_DISALLOWED)     /* saved_mode contains previous sched_mode */
577 #define TH_SFLAG_RT_CPULIMIT         0x200000           /* thread should have a CPU limit applied. */
578 
579 #define TH_SFLAG_FAILSAFE_REPORTED 0x400000 /* whether the kernel has already logged that thread triggered the failsafe (to prevent log spam) */
580 
581 	int16_t                 sched_pri;              /* scheduled (current) priority */
582 	int16_t                 base_pri;               /* effective base priority (equal to req_base_pri unless TH_SFLAG_BASE_PRI_FROZEN) */
583 	int16_t                 req_base_pri;           /* requested base priority */
584 	int16_t                 max_priority;           /* copy of max base priority */
585 	int16_t                 task_priority;          /* copy of task base priority */
586 	uint16_t                priority_floor_count;   /* number of push to boost the floor priority */
587 	int16_t                 suspend_count;          /* Kernel holds on this thread  */
588 #if HAS_MTE
589 	uint8_t                 page_wait_class;        /* The type of VM page this thread will wait on next */
590 #endif /* HAS_MTE */
591 
592 	int                     iotier_override;        /* atomic operations to set, cleared on ret to user */
593 	os_ref_atomic_t         ref_count;              /* number of references to me */
594 
595 	uint32_t                rwlock_count;           /* Number of lck_rw_t locks held by thread */
596 	struct smrq_slist_head  smr_stack;
597 #ifdef DEBUG_RW
598 	rw_lock_debug_t         rw_lock_held;           /* rw_locks currently held by the thread */
599 #endif /* DEBUG_RW */
600 
601 	integer_t               importance;             /* task-relative importance */
602 
603 	/* Priority depression expiration */
604 	integer_t               depress_timer_active;
605 	timer_call_t            depress_timer;
606 
607 	/* real-time parameters */
608 	struct {                                        /* see mach/thread_policy.h */
609 		uint32_t            period;
610 		uint32_t            computation;
611 		uint32_t            constraint;
612 		bool                preemptible;
613 		uint8_t             priority_offset;   /* base_pri = BASEPRI_RTQUEUES + priority_offset */
614 		uint64_t            deadline;
615 	}                       realtime;
616 
617 	uint64_t                last_run_time;          /* time when thread was switched away from */
618 	uint64_t                last_made_runnable_time;        /* time when thread was unblocked or preempted */
619 	uint64_t                last_basepri_change_time;       /* time when thread was last changed in basepri while runnable */
620 	uint64_t                same_pri_latency;
621 	/*
622 	 * workq_quantum_deadline is the workq thread's next runtime deadline. This
623 	 * value is set to 0 if the thread has no such deadline applicable to it.
624 	 *
625 	 * The synchronization for this field is due to how this field is modified
626 	 * 1) This field is always modified on the thread by itself or on the thread
627 	 * when it is not running/runnable
628 	 * 2) Change of this field is immediately followed by a
629 	 * corresponding change to the AST_KEVENT to either set or clear the
630 	 * AST_KEVENT_WORKQ_QUANTUM_EXPIRED bit
631 	 *
632 	 * workq_quantum_deadline can be modified by the thread on itself during
633 	 * interrupt context. However, due to (2) and due to the fact that the
634 	 * change to the AST_KEVENT is volatile, this forces the compiler to
635 	 * guarantee the order between the write to workq_quantum_deadline and the
636 	 * kevent field and therefore guarantees the correct synchronization.
637 	 */
638 	uint64_t                workq_quantum_deadline;
639 
640 #if WORKQ_QUANTUM_HISTORY_DEBUG
641 
642 #define WORKQ_QUANTUM_HISTORY_COUNT 16
643 	struct workq_quantum_history {
644 		uint64_t time;
645 		uint64_t deadline;
646 		bool arm;
647 	} workq_quantum_history[WORKQ_QUANTUM_HISTORY_COUNT];
648 	uint64_t workq_quantum_history_index;
649 
650 #define WORKQ_QUANTUM_HISTORY_WRITE_ENTRY(thread, ...)  ({\
651 	        thread_t __th = (thread); \
652 	        uint64_t __index = os_atomic_inc_orig(&thread->workq_quantum_history_index, relaxed); \
653 	        struct workq_quantum_history _wq_quantum_history = { mach_approximate_time(), __VA_ARGS__}; \
654 	        __th->workq_quantum_history[__index % WORKQ_QUANTUM_HISTORY_COUNT] = \
655 	                        (struct workq_quantum_history) _wq_quantum_history; \
656 	})
657 #else /* WORKQ_QUANTUM_HISTORY_DEBUG */
658 #define WORKQ_QUANTUM_HISTORY_WRITE_ENTRY(thread, ...)
659 #endif /* WORKQ_QUANTUM_HISTORY_DEBUG */
660 
661 #define THREAD_NOT_RUNNABLE (~0ULL)
662 
663 #if CONFIG_THREAD_GROUPS
664 	struct thread_group     *thread_group;
665 #endif
666 
667 	/* Data used during setrun/dispatch */
668 	processor_t             bound_processor;        /* bound to a processor? */
669 	processor_t             last_processor;         /* processor last dispatched on */
670 	processor_t             chosen_processor;       /* Where we want to run this thread */
671 
672 	/* Fail-safe computation since last unblock or qualifying yield */
673 	uint64_t                computation_metered;
674 	uint64_t                computation_epoch;
675 	uint64_t                computation_interrupt_epoch;
676 	uint64_t                safe_release;           /* when to release fail-safe */
677 
678 	/* Call out from scheduler */
679 	void                  (*sched_call)(int type, thread_t thread);
680 
681 	/* Statistics and timesharing calculations */
682 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
683 	natural_t               sched_stamp;            /* last scheduler tick */
684 	natural_t               sched_usage;            /* timesharing cpu usage [sched] */
685 	natural_t               pri_shift;              /* usage -> priority from pset */
686 	natural_t               cpu_usage;              /* instrumented cpu usage [%cpu] */
687 	natural_t               cpu_delta;              /* accumulated cpu_usage delta */
688 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
689 
690 	uint32_t                c_switch;               /* total context switches */
691 	uint32_t                p_switch;               /* total processor switches */
692 	uint32_t                ps_switch;              /* total pset switches */
693 
694 	/* Timing data structures */
695 	uint64_t                sched_time_save;        /* saved time for scheduler tick */
696 	uint64_t                vtimer_user_save;       /* saved values for vtimers */
697 	uint64_t                vtimer_prof_save;
698 	uint64_t                vtimer_rlim_save;
699 	uint64_t                vtimer_qos_save;
700 
701 	timer_data_t            runnable_timer;         /* time the thread is runnable (including running) */
702 
703 	struct recount_thread   th_recount;             /* resource accounting */
704 
705 #if CONFIG_SCHED_SFI
706 	/* Timing for wait state */
707 	uint64_t                wait_sfi_begin_time;    /* start time for thread waiting in SFI */
708 #endif
709 
710 	/*
711 	 * Processor/cache affinity
712 	 * - affinity_threads links task threads with the same affinity set
713 	 */
714 	queue_chain_t           affinity_threads;
715 	affinity_set_t          affinity_set;
716 
717 #if CONFIG_TASKWATCH
718 	task_watch_t           *taskwatch;              /* task watch */
719 #endif /* CONFIG_TASKWATCH */
720 
721 	/* Various bits of state to stash across a continuation, exclusive to the current thread block point */
722 	union {
723 		struct {
724 			/* set before ipc_mqueue_receive() as implicit arguments */
725 			mach_msg_recv_bufs_t    recv_bufs;      /* receive context */
726 			mach_msg_option64_t     option;         /* 64 bits options for receive */
727 			ipc_object_t            object;         /* object received on */
728 
729 			/* set by ipc_mqueue_receive() as implicit results */
730 			mach_msg_return_t       state;          /* receive state */
731 			mach_port_seqno_t       seqno;          /* seqno of recvd message */
732 			mach_msg_size_t         msize;          /* actual size for the msg */
733 			mach_msg_size_t         asize;          /* actual size for aux data */
734 			mach_port_name_t        receiver_name;  /* the receive port name */
735 			struct ipc_kmsg *XNU_PTRAUTH_SIGNED_PTR("thread.ith_kmsg") kmsg;  /* received message */
736 		} receive;
737 		struct {
738 			struct semaphore        *waitsemaphore;         /* semaphore ref */
739 			struct semaphore        *signalsemaphore;       /* semaphore ref */
740 			int                     options;                /* semaphore options */
741 			kern_return_t           result;                 /* primary result */
742 			mach_msg_continue_t continuation;
743 		} sema;
744 		struct {
745 #define THREAD_SAVE_IOKIT_TLS_COUNT     8
746 			void                    *tls[THREAD_SAVE_IOKIT_TLS_COUNT];
747 		} iokit;
748 	} saved;
749 
750 	/* Only user threads can cause Mach exceptions, only kernel threads can be thread call threads */
751 	union {
752 		/* Thread call thread's state structure, stored on its stack */
753 		struct thread_call_thread_state *thc_state;
754 
755 		/* Structure to save information about Mach exception */
756 		struct {
757 			int                             os_reason;
758 			exception_type_t                exception_type;
759 			mach_exception_code_t           code;
760 			mach_exception_subcode_t        subcode;
761 		} mach_exc_info;
762 	};
763 
764 	/* User level suspensions */
765 	int32_t                 user_stop_count;
766 
767 	/* IPC data structures */
768 #if IMPORTANCE_INHERITANCE
769 	natural_t ith_assertions;                       /* assertions pending drop */
770 #endif
771 	circle_queue_head_t     ith_messages;           /* messages to reap */
772 	mach_port_t             ith_kernel_reply_port;  /* reply port for kernel RPCs */
773 
774 	/* VM Fault Tolerance */
775 	bool                    th_vm_faults_disabled;
776 
777 	/* Ast/Halt data structures */
778 	bool                    recover;                /* True if page faulted in recoverable IO */
779 
780 #if DEBUG || DEVELOPMENT
781 	struct thread_test_context *th_test_ctx;        /* thread-specific data for kernel tests */
782 #endif
783 
784 	queue_chain_t           threads;                /* global list of all threads */
785 
786 	/* Activation */
787 	queue_chain_t           task_threads;
788 
789 	/* Task membership */
790 #if __x86_64__ || __arm__
791 	struct task            *t_task;
792 #endif
793 	struct thread_ro       *t_tro;
794 	vm_map_t                map;
795 	thread_t                handoff_thread;
796 
797 	/* Timed wait expiration */
798 	timer_call_t            wait_timer;
799 	uint16_t                wait_timer_active; /* is the call running */
800 	bool                    wait_timer_armed; /* should the wait be cleared */
801 
802 	/* Miscellaneous bits guarded by mutex */
803 	uint32_t
804 	    active:1,           /* Thread is active and has not been terminated */
805 	    ipc_active:1,       /* IPC with the thread ports is allowed */
806 	    started:1,          /* Thread has been started after creation */
807 	    static_param:1,     /* Disallow policy parameter changes */
808 	    inspection:1,       /* TRUE when task is being inspected by crash reporter */
809 	    policy_reset:1,     /* Disallow policy parameter changes on terminating threads */
810 	    suspend_parked:1,   /* thread parked in thread_suspended */
811 	    corpse_dup:1,       /* TRUE when thread is an inactive duplicate in a corpse */
812 	:0;
813 
814 	/* Pending thread ast(s) */
815 	os_atomic(ast_t)        ast;
816 
817 	decl_lck_mtx_data(, mutex);
818 
819 	struct ipc_port         *ith_special_reply_port;   /* ref to special reply port */
820 
821 #if CONFIG_DTRACE
822 	uint16_t                t_dtrace_flags;         /* DTrace thread states */
823 #define TH_DTRACE_EXECSUCCESS   0x01
824 	uint16_t                t_dtrace_inprobe;       /* Executing under dtrace_probe */
825 	uint32_t                t_dtrace_predcache;     /* DTrace per thread predicate value hint */
826 	int64_t                 t_dtrace_tracing;       /* Thread time under dtrace_probe() */
827 	int64_t                 t_dtrace_vtime;
828 #endif
829 
830 	clock_sec_t             t_page_creation_time;
831 	uint32_t                t_page_creation_count;
832 	uint32_t                t_page_creation_throttled;
833 #if (DEVELOPMENT || DEBUG)
834 	uint64_t                t_page_creation_throttled_hard;
835 	uint64_t                t_page_creation_throttled_soft;
836 #endif /* DEVELOPMENT || DEBUG */
837 	int                     t_pagein_error;         /* for vm_fault(), holds error from vnop_pagein() */
838 
839 	mach_port_name_t        ith_voucher_name;
840 	ipc_voucher_t           ith_voucher;
841 
842 #ifdef KPERF
843 /* The high 8 bits are the number of frames to sample of a user callstack. */
844 #define T_KPERF_CALLSTACK_DEPTH_OFFSET     (24)
845 #define T_KPERF_SET_CALLSTACK_DEPTH(DEPTH) (((uint32_t)(DEPTH)) << T_KPERF_CALLSTACK_DEPTH_OFFSET)
846 #define T_KPERF_GET_CALLSTACK_DEPTH(FLAGS) ((FLAGS) >> T_KPERF_CALLSTACK_DEPTH_OFFSET)
847 #define T_KPERF_ACTIONID_OFFSET            (18)
848 #define T_KPERF_SET_ACTIONID(AID)          (((uint32_t)(AID)) << T_KPERF_ACTIONID_OFFSET)
849 #define T_KPERF_GET_ACTIONID(FLAGS)        ((FLAGS) >> T_KPERF_ACTIONID_OFFSET)
850 #endif
851 
852 #define T_KPERF_AST_CALLSTACK 0x1 /* dump a callstack on thread's next AST */
853 #define T_KPERF_AST_DISPATCH  0x2 /* dump a name on thread's next AST */
854 #define T_KPC_ALLOC           0x4 /* thread needs a kpc_buf allocated */
855 
856 #define T_KPERF_AST_ALL \
857     (T_KPERF_AST_CALLSTACK | T_KPERF_AST_DISPATCH | T_KPC_ALLOC)
858 /* only go up to T_KPERF_ACTIONID_OFFSET - 1 */
859 
860 #ifdef KPERF
861 	uint32_t                kperf_ast;
862 	uint32_t                kperf_pet_gen;  /* last generation of PET that sampled this thread*/
863 	uint32_t                kperf_c_switch; /* last dispatch detection */
864 	uint32_t                kperf_pet_cnt;  /* how many times a thread has been sampled by PET */
865 #if CONFIG_EXCLAVES
866 	uint32_t                kperf_exclaves_ast;
867 #endif
868 #endif
869 
870 #ifdef CONFIG_CPU_COUNTERS
871 	/* accumulated performance counters for this thread */
872 	uint64_t               *kpc_buf;
873 #endif /* CONFIG_CPU_COUNTERS */
874 
875 #if HYPERVISOR
876 	/* hypervisor virtual CPU object associated with this thread */
877 	void                   *hv_thread_target;
878 #endif /* HYPERVISOR */
879 
880 	/* Statistics accumulated per-thread and aggregated per-task */
881 	uint32_t                syscalls_unix;
882 	uint32_t                syscalls_mach;
883 	ledger_t                t_ledger;
884 	ledger_t                t_threadledger; /* per thread ledger */
885 	ledger_t                t_bankledger;                /* ledger to charge someone */
886 	uint64_t                t_deduct_bank_ledger_time;   /* cpu time to be deducted from bank ledger */
887 	uint64_t                t_deduct_bank_ledger_energy; /* energy to be deducted from bank ledger */
888 
889 	uint64_t                thread_id;             /* system wide unique thread-id */
890 	uint32_t                ctid;                  /* system wide compact thread-id */
891 	uint32_t                ctsid;                 /* this thread ts ID */
892 
893 	/* policy is protected by the thread mutex */
894 	struct thread_requested_policy  requested_policy;
895 	struct thread_effective_policy  effective_policy;
896 
897 	/* usynch override is protected by the task lock, eventually will be thread mutex */
898 	struct thread_qos_override {
899 		struct thread_qos_override      *override_next;
900 		uint32_t        override_contended_resource_count;
901 		int16_t         override_qos;
902 		int16_t         override_resource_type;
903 		user_addr_t     override_resource;
904 	} *overrides;
905 
906 	uint32_t                kevent_overrides;
907 	uint8_t                 user_promotion_basepri;
908 	uint8_t                 kern_promotion_schedpri;
909 	_Atomic uint16_t        kevent_ast_bits;
910 
911 	io_stat_info_t          thread_io_stats; /* per-thread I/O statistics */
912 
913 	uint32_t                thread_callout_interrupt_wakeups;
914 	uint32_t                thread_callout_platform_idle_wakeups;
915 	uint32_t                thread_timer_wakeups_bin_1;
916 	uint32_t                thread_timer_wakeups_bin_2;
917 	thread_tag_t            thread_tag;
918 
919 	/*
920 	 * callout_* fields are only set for thread call threads whereas mach_exc_* are set
921 	 * by user threads on themselves while taking a Mach exception. So it's okay for them to
922 	 * share this bitfield.
923 	 */
924 	uint16_t
925 	    callout_woken_from_icontext:1,
926 	    callout_woken_from_platform_idle:1,
927 	    callout_woke_thread:1,
928 	    mach_exc_fatal:1,
929 	    mach_exc_ktriage:1,
930 	    thread_bitfield_unused:11;
931 
932 #define THREAD_BOUND_CLUSTER_NONE       (UINT32_MAX)
933 	/*
934 	 * Cluster to which the thread is soft-bound for scheduling. The thread will always run
935 	 * on its bound cluster unless that cluster has been derecommended for scheduling.
936 	 */
937 	uint32_t                 th_bound_cluster_id;
938 
939 #if CONFIG_THREAD_GROUPS
940 #if CONFIG_PREADOPT_TG
941 	/* The preadopt thread group is set on the thread
942 	 *
943 	 *   a) By another thread when it is a creator and it is scheduled with the
944 	 *   thread group on the TR
945 	 *   b) On itself when it binds a thread request and becomes a
946 	 *   servicer or when it rebinds to the thread request
947 	 *   c) On itself when it processes knotes and finds the first
948 	 *   EVFILT_MACHPORT event to deliver to userspace
949 	 *
950 	 * Note that this is a full reference owned by the thread_t and not a
951 	 * borrowed reference.
952 	 *
953 	 * This reference is cleared from the thread_t by the thread itself at the
954 	 * following times:
955 	 *   a) When it explicitly adopts a work interval or a bank voucher
956 	 *   b) If it still exists on the thread, after it has unbound and is about
957 	 *   to park
958 	 *   c) During thread termination if one still exists
959 	 *   d) When a different preadoption thread group is set on the thread
960 	 *
961 	 * It is modified under the thread lock.
962 	 */
963 	struct thread_group     *preadopt_thread_group;
964 
965 	/* This field here is present in order to make sure that the t->thread_group
966 	 * is always pointing to a valid thread group and isn't a dangling pointer.
967 	 *
968 	 * Consider the following scenario:
969 	 *	a) t->thread_group points to the preadoption thread group
970 	 *	b) The preadoption thread group is modified on the thread but we are
971 	 *	unable to resolve the hierarchy immediately due to the current state of
972 	 *	the thread
973 	 *
974 	 *	In order to make sure that t->thread_group points to a valid thread
975 	 *	group until we can resolve the hierarchy again, we save the existing
976 	 *	thread_group it points to in old_preadopt_thread_group. The next time a
977 	 *	hierarchy resolution is done, we know that t->thread_group will not point
978 	 *	to this field anymore so we can clear it.
979 	 *
980 	 *	 This field is always going to take the reference that was previously in
981 	 *	 preadopt_thread_group so it will have a full +1
982 	 */
983 	struct thread_group     *old_preadopt_thread_group;
984 #endif /* CONFIG_PREADOPT_TG */
985 
986 	/* This is a borrowed reference to the TG from the ith_voucher and is saved
987 	 * here since we may not always be in the right context to able to do the
988 	 * lookups.
989 	 *
990 	 * It is set always set on self under the thread lock */
991 	struct thread_group     *bank_thread_group;
992 
993 	/*  Whether this is the autojoin thread group or the work interval thread
994 	 *  group depends on whether the thread's sched_flags has the
995 	 *  TH_SFLAG_THREAD_GROUP_AUTO_JOIN bit set */
996 	union {
997 		/* This is a borrowed reference to the auto join thread group from the
998 		 * work_interval. It is set with the thread lock held */
999 		struct thread_group             *auto_join_thread_group;
1000 		/* This is a borrowed reference to the explicit work_interval thread group
1001 		 * and is always set on self */
1002 		struct thread_group             *work_interval_thread_group;
1003 	};
1004 #endif /* CONFIG_THREAD_GROUPS */
1005 
1006 	/* work interval (if any) associated with the thread. Only modified by
1007 	 * current thread on itself or when another thread when the thread is held
1008 	 * off of runq */
1009 	struct work_interval            *th_work_interval;
1010 	thread_work_interval_flags_t    th_work_interval_flags;
1011 
1012 #if SCHED_TRACE_THREAD_WAKEUPS
1013 	uintptr_t               thread_wakeup_bt[64];
1014 #endif
1015 	turnstile_update_flags_t inheritor_flags; /* inheritor flags for inheritor field */
1016 	block_hint_t            pending_block_hint;
1017 	block_hint_t            block_hint;      /* What type of primitive last caused us to block. */
1018 	uint32_t                decompressions;  /* Per-thread decompressions counter to be added to per-task decompressions counter */
1019 	int                     thread_region_page_shift; /* Page shift that this thread would like to use when */
1020 	                                                  /* introspecting a task. This is currently being used */
1021 	                                                  /* by footprint which uses a thread for each task being inspected. */
1022 #if CONFIG_SCHED_RT_ALLOW
1023 	/* Used when a thread is requested to set/clear its own CPU limit */
1024 	uint32_t
1025 	    t_ledger_req_action:2,
1026 	    t_ledger_req_percentage:7,
1027 	    t_ledger_req_interval_ms:16,
1028 	:0;
1029 #endif /* CONFIG_SCHED_RT_ALLOW */
1030 
1031 #if CONFIG_IOSCHED
1032 	void                   *decmp_upl;
1033 #endif /* CONFIG_IOSCHED */
1034 	struct knote            *ith_knote;         /* knote fired for rcv */
1035 
1036 #if CONFIG_SPTM
1037 	/* TXM thread stack associated with this thread */
1038 	uintptr_t               txm_thread_stack;
1039 #endif
1040 
1041 #if CONFIG_EXCLAVES
1042 	/* Per-thread IPC context for exclaves communication. Only modified by the
1043 	 * current thread on itself. */
1044 	exclaves_ctx_t      th_exclaves_ipc_ctx;
1045 	/* Thread exclaves interrupt-safe state. Only mutated by the current thread
1046 	 * on itself with interrupts disabled, and only ever read by the current
1047 	 * thread (with no locking), including from interrupt context, or during
1048 	 * debug/stackshot. */
1049 	thread_exclaves_intstate_flags_t th_exclaves_intstate;
1050 	/* Thread exclaves state. Only mutated by the current thread on itself, and
1051 	 * only ever read by the current thread (with no locking). Unsafe to read
1052 	 * from interrupt context. */
1053 	thread_exclaves_state_flags_t th_exclaves_state;
1054 	/* Thread stackshot state. Prevents returning to Exclave world until after
1055 	 * an external agent has triggered inspection (likely via Exclave stackshot),
1056 	 * and woken this thread. */
1057 	thread_exclaves_inspection_flags_t _Atomic th_exclaves_inspection_state;
1058 	/* Task for which conclave teardown is being called by this thread. Used
1059 	 * for context by conclave crash info upcall to find the task for appending
1060 	 * the conclave crash info. */
1061 	task_t conclave_stop_task;
1062 	/* Queue of threads being inspected by Stackshot.
1063 	 * Modified under exclaves_collect_mtx. */
1064 	queue_chain_t th_exclaves_inspection_queue_stackshot;
1065 	/* Queue of threads being inspected by kperf.
1066 	 * Modified under exclaves_collect_mtx. */
1067 	queue_chain_t th_exclaves_inspection_queue_kperf;
1068 #endif /* CONFIG_EXCLAVES */
1069 #if HAS_MTE
1070 	/*
1071 	 * Temporary context used while performing faultable accesess on IOMD memory.
1072 	 * This holds the task that originally provided the backing memory for the IOMD.
1073 	 * This value being non-NULL signifies that we're in the critical faultable access window.
1074 	 */
1075 	task_t iomd_faultable_buffer_provider;
1076 #endif /* HAS_MTE */
1077 };
1078 
1079 #define ith_receive         saved.receive
1080 /* arguments */
1081 #define ith_recv_bufs       saved.receive.recv_bufs
1082 #define ith_object          saved.receive.object
1083 #define ith_option          saved.receive.option
1084 /* results */
1085 #define ith_state           saved.receive.state
1086 #define ith_seqno           saved.receive.seqno
1087 #define ith_msize           saved.receive.msize
1088 #define ith_asize           saved.receive.asize
1089 #define ith_receiver_name   saved.receive.receiver_name
1090 #define ith_kmsg            saved.receive.kmsg
1091 
1092 #define sth_waitsemaphore   saved.sema.waitsemaphore
1093 #define sth_signalsemaphore saved.sema.signalsemaphore
1094 #define sth_options         saved.sema.options
1095 #define sth_result          saved.sema.result
1096 #define sth_continuation    saved.sema.continuation
1097 
1098 #define ITH_KNOTE_NULL      ((void *)NULL)
1099 #define ITH_KNOTE_PSEUDO    ((void *)0xdeadbeef)
1100 /*
1101  * The ith_knote is used during message delivery, and can safely be interpreted
1102  * only when used for one of these codepaths, which the test for the msgt_name
1103  * being RECEIVE or SEND_ONCE is about.
1104  */
1105 #define ITH_KNOTE_VALID(kn, msgt_name) \
1106 	        (((kn) != ITH_KNOTE_NULL && (kn) != ITH_KNOTE_PSEUDO) && \
1107 	         ((msgt_name) == MACH_MSG_TYPE_PORT_RECEIVE || \
1108 	         (msgt_name) == MACH_MSG_TYPE_PORT_SEND_ONCE))
1109 
1110 #if MACH_ASSERT
1111 #define assert_thread_magic(thread) assert3u((thread)->thread_magic, ==, THREAD_MAGIC)
1112 #else
1113 #define assert_thread_magic(thread) do { (void)(thread); } while (0)
1114 #endif
1115 
1116 extern thread_t         thread_bootstrap(void);
1117 
1118 extern void             thread_machine_init_template(void);
1119 
1120 extern void             thread_init(void);
1121 
1122 extern void             thread_daemon_init(void);
1123 
1124 extern void             thread_reference(
1125 	thread_t                thread);
1126 
1127 extern void             thread_deallocate(
1128 	thread_t                thread);
1129 
1130 extern void             thread_inspect_deallocate(
1131 	thread_inspect_t        thread);
1132 
1133 extern void             thread_read_deallocate(
1134 	thread_read_t           thread);
1135 
1136 extern kern_return_t    thread_terminate(
1137 	thread_t                thread);
1138 
1139 extern void             thread_terminate_self(void);
1140 
1141 extern kern_return_t    thread_terminate_internal(
1142 	thread_t                thread);
1143 
1144 extern void             thread_start(
1145 	thread_t                thread) __attribute__ ((noinline));
1146 
1147 extern void             thread_start_in_assert_wait(
1148 	thread_t                thread,
1149 	struct waitq           *waitq,
1150 	event64_t               event,
1151 	wait_interrupt_t        interruptible) __attribute__ ((noinline));
1152 
1153 extern void             thread_terminate_enqueue(
1154 	thread_t                thread);
1155 
1156 extern void             thread_exception_enqueue(
1157 	task_t                  task,
1158 	thread_t                thread,
1159 	exception_type_t        etype);
1160 
1161 extern void             thread_backtrace_enqueue(
1162 	kcdata_object_t         obj,
1163 	exception_port_t        ports[static BT_EXC_PORTS_COUNT],
1164 	exception_type_t        etype);
1165 
1166 extern void                     thread_copy_resource_info(
1167 	thread_t dst_thread,
1168 	thread_t src_thread);
1169 
1170 extern void                     thread_terminate_crashed_threads(void);
1171 
1172 extern void                     thread_stack_enqueue(
1173 	thread_t                thread);
1174 
1175 extern void                     thread_hold(
1176 	thread_t        thread);
1177 
1178 extern void                     thread_release(
1179 	thread_t        thread);
1180 
1181 extern void                     thread_corpse_continue(void) __dead2;
1182 
1183 extern boolean_t                thread_is_active(thread_t thread);
1184 
1185 extern lck_grp_t                thread_lck_grp;
1186 
1187 /* Locking for scheduler state, always acquired with interrupts disabled (splsched()) */
1188 #define thread_lock_init(th)    simple_lock_init(&(th)->sched_lock, 0)
1189 #define thread_lock(th)                 simple_lock(&(th)->sched_lock, &thread_lck_grp)
1190 #define thread_unlock(th)               simple_unlock(&(th)->sched_lock)
1191 #define thread_lock_assert(th, x)       simple_lock_assert(&(th)->sched_lock, (x))
1192 
1193 #define wake_lock_init(th)              simple_lock_init(&(th)->wake_lock, 0)
1194 #define wake_lock(th)                   simple_lock(&(th)->wake_lock, &thread_lck_grp)
1195 #define wake_unlock(th)                 simple_unlock(&(th)->wake_lock)
1196 
1197 #define thread_should_halt_fast(thread)         (!(thread)->active)
1198 
1199 extern void                             stack_alloc(
1200 	thread_t                thread);
1201 
1202 extern void                     stack_handoff(
1203 	thread_t                from,
1204 	thread_t                to);
1205 
1206 extern void                             stack_free(
1207 	thread_t                thread);
1208 
1209 extern void                             stack_free_reserved(
1210 	thread_t                thread);
1211 
1212 extern boolean_t                stack_alloc_try(
1213 	thread_t            thread);
1214 
1215 extern void                             stack_collect(void);
1216 
1217 extern kern_return_t    thread_info_internal(
1218 	thread_t                                thread,
1219 	thread_flavor_t                 flavor,
1220 	thread_info_t                   thread_info_out,
1221 	mach_msg_type_number_t  *thread_info_count);
1222 
1223 extern kern_return_t    kernel_thread_create(
1224 	thread_continue_t       continuation,
1225 	void                            *parameter,
1226 	integer_t                       priority,
1227 	thread_t                        *new_thread);
1228 
1229 extern kern_return_t    kernel_thread_start_priority(
1230 	thread_continue_t       continuation,
1231 	void                            *parameter,
1232 	integer_t                       priority,
1233 	thread_t                        *new_thread);
1234 
1235 extern void                             machine_stack_attach(
1236 	thread_t                thread,
1237 	vm_offset_t             stack);
1238 
1239 extern vm_offset_t              machine_stack_detach(
1240 	thread_t                thread);
1241 
1242 extern void                             machine_stack_handoff(
1243 	thread_t                old,
1244 	thread_t                new);
1245 
1246 extern thread_t                 machine_switch_context(
1247 	thread_t                        old_thread,
1248 	thread_continue_t       continuation,
1249 	thread_t                        new_thread);
1250 
1251 extern void                             machine_load_context(
1252 	thread_t                thread) __attribute__((noreturn));
1253 
1254 extern void             machine_thread_state_initialize(
1255 	thread_t                                thread);
1256 
1257 extern kern_return_t    machine_thread_set_state(
1258 	thread_t                                thread,
1259 	thread_flavor_t                 flavor,
1260 	thread_state_t                  state,
1261 	mach_msg_type_number_t  count);
1262 
1263 extern mach_vm_address_t machine_thread_pc(
1264 	thread_t                thread);
1265 
1266 extern void machine_thread_reset_pc(
1267 	thread_t                thread,
1268 	mach_vm_address_t       pc);
1269 
1270 extern boolean_t        machine_thread_on_core(
1271 	thread_t                thread);
1272 
1273 extern boolean_t        machine_thread_on_core_allow_invalid(
1274 	thread_t                thread);
1275 
1276 extern kern_return_t    machine_thread_get_state(
1277 	thread_t                                thread,
1278 	thread_flavor_t                 flavor,
1279 	thread_state_t                  state,
1280 	mach_msg_type_number_t  *count);
1281 
1282 extern kern_return_t    machine_thread_state_convert_from_user(
1283 	thread_t                                thread,
1284 	thread_flavor_t                 flavor,
1285 	thread_state_t                  tstate,
1286 	mach_msg_type_number_t  count,
1287 	thread_state_t old_tstate,
1288 	mach_msg_type_number_t old_count,
1289 	thread_set_status_flags_t tssf_flags);
1290 
1291 extern kern_return_t    machine_thread_state_convert_to_user(
1292 	thread_t                                thread,
1293 	thread_flavor_t                 flavor,
1294 	thread_state_t                  tstate,
1295 	mach_msg_type_number_t  *count,
1296 	thread_set_status_flags_t tssf_flags);
1297 
1298 extern kern_return_t    machine_thread_dup(
1299 	thread_t                self,
1300 	thread_t                target,
1301 	boolean_t               is_corpse);
1302 
1303 extern void             machine_thread_init(void);
1304 
1305 extern void             machine_thread_template_init(thread_t thr_template);
1306 
1307 #if __has_feature(ptrauth_calls)
1308 extern bool             machine_thread_state_is_debug_flavor(int flavor);
1309 #endif /* __has_feature(ptrauth_calls) */
1310 
1311 
1312 extern void             machine_thread_create(
1313 	thread_t                thread,
1314 	task_t                  task,
1315 	bool                    first_thread);
1316 
1317 extern kern_return_t    machine_thread_process_signature(
1318 	thread_t                thread,
1319 	task_t                  task);
1320 
1321 extern void             machine_thread_switch_addrmode(
1322 	thread_t                 thread);
1323 
1324 extern void                 machine_thread_destroy(
1325 	thread_t                thread);
1326 
1327 extern void                             machine_set_current_thread(
1328 	thread_t                        thread);
1329 
1330 extern kern_return_t    machine_thread_get_kern_state(
1331 	thread_t                                thread,
1332 	thread_flavor_t                 flavor,
1333 	thread_state_t                  tstate,
1334 	mach_msg_type_number_t  *count);
1335 
1336 extern kern_return_t    machine_thread_inherit_taskwide(
1337 	thread_t                thread,
1338 	task_t                  parent_task);
1339 
1340 extern kern_return_t    machine_thread_set_tsd_base(
1341 	thread_t                                thread,
1342 	mach_vm_offset_t                tsd_base);
1343 
1344 #define thread_mtx_try(thread)                  lck_mtx_try_lock(&(thread)->mutex)
1345 #define thread_mtx_held(thread)                 lck_mtx_assert(&(thread)->mutex, LCK_MTX_ASSERT_OWNED)
1346 
1347 extern void thread_apc_ast(thread_t thread);
1348 
1349 extern void thread_update_qos_cpu_time(thread_t thread);
1350 
1351 void act_machine_sv_free(thread_t, int);
1352 
1353 vm_offset_t                     min_valid_stack_address(void);
1354 vm_offset_t                     max_valid_stack_address(void);
1355 
1356 #if CONFIG_SCHED_SMT
1357 extern bool thread_no_smt(thread_t thread);
1358 extern bool processor_active_thread_no_smt(processor_t processor);
1359 #endif /* CONFIG_SCHED_SMT */
1360 
1361 extern void thread_set_options(uint32_t thopt);
1362 
1363 #if CONFIG_THREAD_GROUPS
1364 struct thread_group *thread_get_current_voucher_thread_group(thread_t thread);
1365 #endif /* CONFIG_THREAD_GROUPS */
1366 
1367 #if CONFIG_COALITIONS
1368 uint64_t thread_get_current_voucher_resource_coalition_id(thread_t thread);
1369 #endif /* CONFIG_COALITIONS */
1370 
1371 #endif  /* MACH_KERNEL_PRIVATE */
1372 #if BSD_KERNEL_PRIVATE
1373 
1374 /* Duplicated from osfmk/kern/ipc_tt.h */
1375 __options_decl(port_intrans_options_t, uint32_t, {
1376 	PORT_INTRANS_OPTIONS_NONE              = 0x0000,
1377 	PORT_INTRANS_THREAD_IN_CURRENT_TASK    = 0x0001,
1378 	PORT_INTRANS_THREAD_NOT_CURRENT_THREAD = 0x0002,
1379 
1380 	PORT_INTRANS_SKIP_TASK_EVAL            = 0x0004,
1381 	PORT_INTRANS_ALLOW_CORPSE_TASK         = 0x0008,
1382 });
1383 
1384 extern thread_t port_name_to_thread(
1385 	mach_port_name_t            port_name,
1386 	port_intrans_options_t    options);
1387 
1388 #endif /* BSD_KERNEL_PRIVATE */
1389 #ifdef XNU_KERNEL_PRIVATE
1390 
1391 extern void                     thread_require(
1392 	thread_t        thread);
1393 
1394 extern void                     thread_deallocate_safe(
1395 	thread_t                thread);
1396 
1397 extern uint64_t                 thread_rettokern_addr(
1398 	thread_t thread);
1399 
1400 extern uint64_t                 thread_wqquantum_addr(
1401 	thread_t thread);
1402 
1403 extern integer_t        thread_kern_get_pri(thread_t thr) __pure2;
1404 
1405 extern void             thread_kern_set_pri(thread_t thr, integer_t pri);
1406 
1407 extern integer_t        thread_kern_get_kernel_maxpri(void) __pure2;
1408 
1409 uint16_t        thread_set_tag(thread_t thread, uint16_t tag);
1410 uint16_t        thread_get_tag(thread_t thread);
1411 
1412 __options_decl(shared_rsrc_policy_agent_t, uint32_t, {
1413 	SHARED_RSRC_POLICY_AGENT_DISPATCH = 0,
1414 	SHARED_RSRC_POLICY_AGENT_SYSCTL = 1,
1415 	SHARED_RSRC_POLICY_AGENT_PERFCTL_CSW = 2,
1416 	SHARED_RSRC_POLICY_AGENT_PERFCTL_QUANTUM = 3,
1417 });
1418 
1419 boolean_t       thread_shared_rsrc_policy_get(thread_t thread, cluster_shared_rsrc_type_t type);
1420 kern_return_t   thread_shared_rsrc_policy_set(thread_t thread, uint32_t index, cluster_shared_rsrc_type_t type, shared_rsrc_policy_agent_t agent);
1421 kern_return_t   thread_shared_rsrc_policy_clear(thread_t thread, cluster_shared_rsrc_type_t type, shared_rsrc_policy_agent_t agent);
1422 
1423 #ifdef MACH_KERNEL_PRIVATE
1424 static inline thread_tag_t
thread_set_tag_internal(thread_t thread,thread_tag_t tag)1425 thread_set_tag_internal(thread_t thread, thread_tag_t tag)
1426 {
1427 	return os_atomic_or_orig(&thread->thread_tag, tag, relaxed);
1428 }
1429 
1430 static inline thread_tag_t
thread_get_tag_internal(thread_t thread)1431 thread_get_tag_internal(thread_t thread)
1432 {
1433 	return thread->thread_tag;
1434 }
1435 #endif /* MACH_KERNEL_PRIVATE */
1436 
1437 extern uint64_t         thread_last_run_time(
1438 	thread_t                thread);
1439 
1440 extern kern_return_t    thread_state_initialize(
1441 	thread_t                thread);
1442 
1443 extern kern_return_t    thread_setstatus(
1444 	thread_t                thread,
1445 	int                     flavor,
1446 	thread_state_t          tstate,
1447 	mach_msg_type_number_t  count);
1448 
1449 extern kern_return_t    thread_setstatus_from_user(
1450 	thread_t                thread,
1451 	int                     flavor,
1452 	thread_state_t          tstate,
1453 	mach_msg_type_number_t  count,
1454 	thread_state_t          old_tstate,
1455 	mach_msg_type_number_t  old_count,
1456 	thread_set_status_flags_t flags);
1457 
1458 extern kern_return_t    thread_getstatus(
1459 	thread_t                thread,
1460 	int                     flavor,
1461 	thread_state_t          tstate,
1462 	mach_msg_type_number_t *count);
1463 
1464 extern kern_return_t    thread_getstatus_to_user(
1465 	thread_t                thread,
1466 	int                     flavor,
1467 	thread_state_t          tstate,
1468 	mach_msg_type_number_t *count,
1469 	thread_set_status_flags_t flags);
1470 
1471 extern kern_return_t    thread_create_with_continuation(
1472 	task_t                  task,
1473 	thread_t               *new_thread,
1474 	thread_continue_t       continuation);
1475 
1476 extern kern_return_t main_thread_create_waiting(
1477 	task_t                  task,
1478 	thread_continue_t       continuation,
1479 	event_t                 event,
1480 	thread_t               *new_thread);
1481 
1482 extern kern_return_t    thread_create_workq_waiting(
1483 	task_t                  task,
1484 	thread_continue_t       thread_return,
1485 	thread_t               *new_thread,
1486 	bool                    is_permanently_bound);
1487 
1488 extern kern_return_t    thread_create_aio_workq_waiting(
1489 	task_t                  task,
1490 	thread_continue_t       thread_return,
1491 	thread_t                *new_thread);
1492 
1493 extern  void    thread_yield_internal(
1494 	mach_msg_timeout_t      interval);
1495 
1496 extern void thread_yield_to_preemption(void);
1497 
1498 extern void thread_depress_timer_setup(
1499 	thread_t                self);
1500 
1501 /*
1502  * Thread-private CPU limits: apply a private CPU limit to this thread only. Available actions are:
1503  *
1504  * 1) Block. Prevent CPU consumption of the thread from exceeding the limit.
1505  * 2) Exception. Generate a resource consumption exception when the limit is exceeded.
1506  * 3) Disable. Remove any existing CPU limit.
1507  */
1508 #define THREAD_CPULIMIT_BLOCK           0x1
1509 #define THREAD_CPULIMIT_EXCEPTION       0x2
1510 #define THREAD_CPULIMIT_DISABLE         0x3
1511 
1512 struct _thread_ledger_indices {
1513 	int cpu_time;
1514 };
1515 
1516 extern struct _thread_ledger_indices thread_ledgers;
1517 
1518 extern int thread_get_cpulimit(int *action, uint8_t *percentage, uint64_t *interval_ns);
1519 extern int thread_set_cpulimit(int action, uint8_t percentage, uint64_t interval_ns);
1520 
1521 extern uint64_t thread_cpulimit_remaining(uint64_t now);
1522 extern bool thread_cpulimit_interval_has_expired(uint64_t now);
1523 extern void thread_cpulimit_restart(uint64_t now);
1524 
1525 extern void thread_read_times(
1526 	thread_t         thread,
1527 	time_value_t    *user_time,
1528 	time_value_t    *system_time,
1529 	time_value_t    *runnable_time);
1530 
1531 extern void thread_read_times_unsafe(
1532 	thread_t         thread,
1533 	time_value_t    *user_time,
1534 	time_value_t    *system_time,
1535 	time_value_t    *runnable_time);
1536 
1537 extern uint64_t         thread_get_runtime_self(void);
1538 
1539 extern void                     thread_setuserstack(
1540 	thread_t                thread,
1541 	mach_vm_offset_t        user_stack);
1542 
1543 extern user_addr_t         thread_adjuserstack(
1544 	thread_t                thread,
1545 	int                             adjust);
1546 
1547 
1548 extern void                     thread_setentrypoint(
1549 	thread_t                thread,
1550 	mach_vm_offset_t        entry);
1551 
1552 extern kern_return_t    thread_set_tsd_base(
1553 	thread_t        thread,
1554 	mach_vm_offset_t tsd_base);
1555 
1556 extern kern_return_t    thread_setsinglestep(
1557 	thread_t                thread,
1558 	int                     on);
1559 
1560 extern kern_return_t    thread_userstack(
1561 	thread_t,
1562 	int,
1563 	thread_state_t,
1564 	unsigned int,
1565 	mach_vm_offset_t *,
1566 	int *,
1567 	boolean_t);
1568 
1569 extern kern_return_t    thread_entrypoint(
1570 	thread_t,
1571 	int,
1572 	thread_state_t,
1573 	unsigned int,
1574 	mach_vm_offset_t *);
1575 
1576 extern kern_return_t    thread_userstackdefault(
1577 	mach_vm_offset_t *,
1578 	boolean_t);
1579 
1580 extern kern_return_t    thread_wire_internal(
1581 	host_priv_t             host_priv,
1582 	thread_t                thread,
1583 	boolean_t               wired,
1584 	boolean_t               *prev_state);
1585 
1586 
1587 extern kern_return_t    thread_dup(thread_t);
1588 
1589 extern kern_return_t thread_dup2(thread_t, thread_t);
1590 
1591 #if !defined(_SCHED_CALL_T_DEFINED)
1592 #define _SCHED_CALL_T_DEFINED
1593 typedef void    (*sched_call_t)(
1594 	int                             type,
1595 	thread_t                thread);
1596 #endif
1597 
1598 #define SCHED_CALL_BLOCK                0x1
1599 #define SCHED_CALL_UNBLOCK              0x2
1600 
1601 extern void             thread_sched_call(
1602 	thread_t                thread,
1603 	sched_call_t    call);
1604 
1605 extern boolean_t        thread_is_static_param(
1606 	thread_t                thread);
1607 
1608 extern task_t   get_threadtask(thread_t) __pure2;
1609 
1610 extern task_t   get_threadtask_early(thread_t) __pure2;
1611 
1612 /*
1613  * Thread is running within a 64-bit address space.
1614  */
1615 #define thread_is_64bit_addr(thd)       \
1616 	task_has_64Bit_addr(get_threadtask(thd))
1617 
1618 /*
1619  * Thread is using 64-bit machine state.
1620  */
1621 #define thread_is_64bit_data(thd)       \
1622 	task_has_64Bit_data(get_threadtask(thd))
1623 
1624 struct uthread;
1625 
1626 #if defined(__x86_64__)
1627 extern int              thread_task_has_ldt(thread_t);
1628 #endif
1629 extern void             set_thread_pagein_error(thread_t, int);
1630 extern event_t          workq_thread_init_and_wq_lock(task_t, thread_t); // bsd/pthread/
1631 extern event_t          aio_workq_thread_init_and_wq_lock(task_t, thread_t); // bsd/aio/
1632 
1633 struct proc;
1634 struct uthread;
1635 struct image_params;
1636 extern const size_t     uthread_size;
1637 extern thread_ro_t      get_thread_ro_unchecked(thread_t) __pure2;
1638 extern thread_ro_t      get_thread_ro(thread_t) __pure2;
1639 extern thread_ro_t      current_thread_ro_unchecked(void) __pure2;
1640 extern thread_ro_t      current_thread_ro(void) __pure2;
1641 extern void             clear_thread_ro_proc(thread_t);
1642 extern struct uthread  *get_bsdthread_info(thread_t) __pure2;
1643 extern thread_t         get_machthread(struct uthread *) __pure2;
1644 extern uint64_t         uthread_tid(struct uthread *) __pure2;
1645 extern user_addr_t      thread_get_sigreturn_token(thread_t thread);
1646 extern uint32_t         thread_get_sigreturn_diversifier(thread_t thread);
1647 extern void             uthread_init(task_t, struct uthread *, thread_ro_t, int);
1648 extern void             uthread_cleanup_name(struct uthread *uthread);
1649 extern void             uthread_cleanup(struct uthread *, thread_ro_t);
1650 extern void             uthread_cred_ref(struct ucred *);
1651 extern void             uthread_cred_free(struct ucred *);
1652 extern void             uthread_destroy(struct uthread *);
1653 extern void             uthread_reset_proc_refcount(struct uthread *);
1654 
1655 extern void             uthread_set_exec_data(struct uthread *uth, struct image_params *imgp);
1656 extern bool             uthread_is64bit(struct uthread *uth) __pure2;
1657 #if PROC_REF_DEBUG
1658 extern void             uthread_init_proc_refcount(struct uthread *);
1659 extern void             uthread_destroy_proc_refcount(struct uthread *);
1660 extern void             uthread_assert_zero_proc_refcount(struct uthread *);
1661 #else
1662 #define                 uthread_init_proc_refcount(uth)        ((void)(uth))
1663 #define                 uthread_destroy_proc_refcount(uth)     ((void)(uth))
1664 #define                 uthread_assert_zero_proc_refcount(uth) ((void)(uth))
1665 #endif
1666 #if CONFIG_DEBUG_SYSCALL_REJECTION
1667 extern uint64_t         uthread_get_syscall_rejection_flags(void *);
1668 extern uint64_t         *uthread_get_syscall_rejection_mask(void *);
1669 extern uint64_t         *uthread_get_syscall_rejection_once_mask(void *);
1670 extern bool             uthread_syscall_rejection_is_enabled(void *);
1671 #endif /* CONFIG_DEBUG_SYSCALL_REJECTION */
1672 extern mach_port_name_t  uthread_joiner_port(struct uthread *);
1673 extern user_addr_t       uthread_joiner_address(struct uthread *);
1674 extern void              uthread_joiner_wake(task_t task, struct uthread *);
1675 
1676 extern boolean_t        thread_should_halt(
1677 	thread_t                thread);
1678 
1679 extern boolean_t        thread_should_abort(
1680 	thread_t);
1681 
1682 extern bool current_thread_in_kernel_fault(void);
1683 
1684 extern int is_64signalregset(void);
1685 
1686 extern void act_set_kperf(thread_t);
1687 extern void act_set_astledger(thread_t thread);
1688 extern void act_set_astledger_async(thread_t thread);
1689 extern void act_set_io_telemetry_ast(thread_t);
1690 extern void act_set_macf_telemetry_ast(thread_t);
1691 extern void act_set_astproc_resource(thread_t);
1692 
1693 extern vm_offset_t thread_get_kernel_stack(thread_t);
1694 
1695 extern kern_return_t thread_process_signature(thread_t thread, task_t task);
1696 
1697 extern uint32_t dtrace_get_thread_predcache(thread_t);
1698 extern int64_t dtrace_get_thread_vtime(thread_t);
1699 extern int64_t dtrace_get_thread_tracing(thread_t);
1700 extern uint16_t dtrace_get_thread_inprobe(thread_t);
1701 extern int dtrace_get_thread_last_cpu_id(thread_t);
1702 extern vm_offset_t dtrace_get_kernel_stack(thread_t);
1703 #define dtrace_get_kernel_stack thread_get_kernel_stack
1704 extern void dtrace_set_thread_predcache(thread_t, uint32_t);
1705 extern void dtrace_set_thread_vtime(thread_t, int64_t);
1706 extern void dtrace_set_thread_tracing(thread_t, int64_t);
1707 extern void dtrace_set_thread_inprobe(thread_t, uint16_t);
1708 extern void dtrace_thread_bootstrap(void);
1709 extern void dtrace_thread_didexec(thread_t);
1710 
1711 extern int64_t dtrace_calc_thread_recent_vtime(thread_t);
1712 
1713 
1714 extern kern_return_t    thread_set_wq_state32(
1715 	thread_t          thread,
1716 	thread_state_t    tstate);
1717 
1718 extern kern_return_t    thread_set_wq_state64(
1719 	thread_t          thread,
1720 	thread_state_t    tstate);
1721 
1722 extern vm_offset_t      kernel_stack_mask;
1723 extern vm_offset_t      kernel_stack_size;
1724 extern vm_offset_t      kernel_stack_depth_max;
1725 
1726 extern void mach_exception_ast(thread_t);
1727 extern void fd_guard_ast(thread_t,
1728     mach_exception_code_t, mach_exception_subcode_t);
1729 extern void vn_guard_ast(thread_t,
1730     mach_exception_code_t, mach_exception_subcode_t);
1731 extern void mach_port_guard_ast(thread_t,
1732     mach_exception_code_t, mach_exception_subcode_t);
1733 extern void virt_memory_guard_ast(thread_t,
1734     mach_exception_code_t, mach_exception_subcode_t);
1735 extern void thread_ast_mach_exception(thread_t,
1736     int, exception_type_t, mach_exception_code_t, mach_exception_subcode_t, bool, bool);
1737 extern void thread_guard_violation(thread_t,
1738     mach_exception_code_t, mach_exception_subcode_t, bool);
1739 extern void thread_update_io_stats(thread_t, int size, int io_flags);
1740 
1741 extern kern_return_t    thread_set_voucher_name(mach_port_name_t name);
1742 extern kern_return_t thread_get_voucher_origin_pid(thread_t thread, int32_t *pid);
1743 extern kern_return_t thread_get_voucher_origin_proximate_pid(thread_t thread,
1744     int32_t *origin_pid, int32_t *proximate_pid);
1745 extern kern_return_t thread_get_current_voucher_origin_pid(int32_t *pid);
1746 
1747 extern void thread_enable_send_importance(thread_t thread, boolean_t enable);
1748 
1749 /*
1750  * Translate signal context data pointer to userspace representation
1751  */
1752 
1753 extern kern_return_t    machine_thread_siguctx_pointer_convert_to_user(
1754 	thread_t thread,
1755 	user_addr_t *uctxp);
1756 
1757 extern void machine_tecs(thread_t thr);
1758 
1759 typedef enum cpuvn {
1760 	CPUVN_CI = 1
1761 } cpuvn_e;
1762 
1763 extern int machine_csv(cpuvn_e cve);
1764 #if defined(__x86_64__)
1765 extern void machine_thread_set_insn_copy_optout(thread_t thr);
1766 #endif
1767 
1768 /*
1769  * Translate array of function pointer syscall arguments from userspace representation
1770  */
1771 
1772 extern kern_return_t    machine_thread_function_pointers_convert_from_user(
1773 	thread_t thread,
1774 	user_addr_t *fptrs,
1775 	uint32_t count);
1776 
1777 /*
1778  * Get the duration of the given thread's last wait.
1779  */
1780 uint64_t thread_get_last_wait_duration(thread_t thread);
1781 
1782 #if CONFIG_SCHED_SMT
1783 extern bool thread_get_no_smt(void);
1784 #endif /* CONFIG_SCHED_SMT */
1785 #if defined(__x86_64__)
1786 extern bool curtask_get_insn_copy_optout(void);
1787 extern void curtask_set_insn_copy_optout(void);
1788 #endif /* defined(__x86_64__) */
1789 
1790 /*! @function ctid_get_thread
1791  *  @abstract translates a ctid_t to thread_t
1792  *  @discussion ctid are system wide compact thread-id
1793  *              associated to thread_t at thread creation
1794  *              and recycled at thread termination. If a ctid is
1795  *              referenced past the corresponding thread termination,
1796  *              it is considered stale, and the behavior is not defined.
1797  *              Note that this call does not acquire a reference on the thread,
1798  *              so as soon as the matching thread terminates, the ctid
1799  *              will become stale, and it could be re-used and associated with
1800  *              another thread. You must externally guarantee that the thread
1801  *              will not exit while you are using its ctid.
1802  *  @result   thread_t corresponding to ctid
1803  */
1804 extern thread_t ctid_get_thread(ctid_t ctid);
1805 
1806 /*! @function ctid_get_thread
1807  *  @abstract translates a ctid_t to thread_t
1808  *  @discussion Unsafe variant of ctid_get_thread() to be used
1809  *              when the caller can't guarantee the liveness of this ctid_t.
1810  *              may return NULL or a freed thread_t.
1811  */
1812 extern thread_t ctid_get_thread_unsafe(ctid_t ctid);
1813 
1814 /*!
1815  *   @function thread_get_ctid
1816  *   @abstract returns the ctid of thread.
1817  *   @param thread to find the corresponding ctid.
1818  *   @discussion the ctid provided will become stale after the matching thread
1819  *               terminates.
1820  *   @result uint32_t ctid.
1821  */
1822 extern ctid_t thread_get_ctid(thread_t thread);
1823 
1824 #endif  /* XNU_KERNEL_PRIVATE */
1825 #ifdef KERNEL_PRIVATE
1826 
1827 typedef struct thread_pri_floor {
1828 	thread_t thread;
1829 } thread_pri_floor_t;
1830 
1831 #ifdef MACH_KERNEL_PRIVATE
1832 extern void thread_floor_boost_ast(thread_t thread);
1833 extern void thread_floor_boost_set_promotion_locked(thread_t thread);
1834 #endif /* MACH_KERNEL_PRIVATE */
1835 
1836 /*!  @function thread_priority_floor_start
1837  *   @abstract boost the current thread priority to floor.
1838  *   @discussion Increase the priority of the current thread to at least MINPRI_FLOOR.
1839  *       The boost will be mantained until a corresponding thread_priority_floor_end()
1840  *       is called. Every call of thread_priority_floor_start() needs to have a corresponding
1841  *       call to thread_priority_floor_end() from the same thread.
1842  *       No thread can return to userspace before calling thread_priority_floor_end().
1843  *
1844  *       NOTE: avoid to use this function. Try to use gate_t or sleep_with_inheritor()
1845  *       instead.
1846  *   @result a token to be given to the corresponding thread_priority_floor_end()
1847  */
1848 extern thread_pri_floor_t thread_priority_floor_start(void);
1849 /*!  @function thread_priority_floor_end
1850  *   @abstract ends the floor boost.
1851  *   @param token the token obtained from thread_priority_floor_start()
1852  *   @discussion ends the priority floor boost started with thread_priority_floor_start()
1853  */
1854 extern void thread_priority_floor_end(thread_pri_floor_t *token);
1855 
1856 #if defined(__x86_64__)
1857 extern void thread_set_no_smt(bool set);
1858 #endif /* __x86_64__ */
1859 
1860 extern void thread_mtx_lock(thread_t thread);
1861 
1862 extern void thread_mtx_unlock(thread_t thread);
1863 
1864 extern uint64_t thread_dispatchqaddr(
1865 	thread_t thread);
1866 
1867 bool thread_is_eager_preempt(thread_t thread);
1868 void thread_set_eager_preempt(thread_t thread);
1869 void thread_clear_eager_preempt(thread_t thread);
1870 void thread_set_honor_qlimit(thread_t thread);
1871 void thread_clear_honor_qlimit(thread_t thread);
1872 extern ipc_port_t convert_thread_to_port(thread_t);
1873 extern ipc_port_t convert_thread_to_port_immovable(thread_t);
1874 extern ipc_port_t convert_thread_inspect_to_port(thread_inspect_t);
1875 extern ipc_port_t convert_thread_read_to_port(thread_read_t);
1876 extern void       convert_thread_array_to_ports(thread_act_array_t, size_t, mach_thread_flavor_t);
1877 extern boolean_t is_external_pageout_thread(void);
1878 extern boolean_t is_vm_privileged(void);
1879 extern boolean_t set_vm_privilege(boolean_t);
1880 extern kern_allocation_name_t thread_set_allocation_name(kern_allocation_name_t new_name);
1881 extern void *thread_iokit_tls_get(uint32_t index);
1882 extern void thread_iokit_tls_set(uint32_t index, void * data);
1883 extern int thread_self_region_page_shift(void);
1884 extern void thread_self_region_page_shift_set(int pgshift);
1885 extern kern_return_t thread_create_immovable(task_t task, thread_t *new_thread);
1886 extern kern_return_t thread_terminate_immovable(thread_t thread);
1887 
1888 struct thread_attr_for_ipc_propagation;
1889 extern kern_return_t thread_get_ipc_propagate_attr(thread_t thread, struct thread_attr_for_ipc_propagation *attr);
1890 extern size_t thread_get_current_exec_path(char *path, size_t size);
1891 #endif /* KERNEL_PRIVATE */
1892 #ifdef XNU_KERNEL_PRIVATE
1893 
1894 extern void
1895 thread_get_thread_name(thread_t th, char* name);
1896 
1897 /* Read the runq assignment, under the thread lock. */
1898 extern processor_t thread_get_runq(thread_t thread);
1899 
1900 /*
1901  * Read the runq assignment, under both the thread lock and
1902  * the pset lock corresponding to the last non-null assignment.
1903  */
1904 extern processor_t thread_get_runq_locked(thread_t thread);
1905 
1906 /*
1907  * Set the runq assignment to a non-null value, under both the
1908  * thread lock and the pset lock corresponding to the new
1909  * assignment.
1910  */
1911 extern void thread_set_runq_locked(thread_t thread, processor_t new_runq);
1912 
1913 /*
1914  * Set the runq assignment to PROCESSOR_NULL, under the pset
1915  * lock corresponding to the current non-null assignment.
1916  */
1917 extern void thread_clear_runq(thread_t thread);
1918 
1919 /*
1920  * Set the runq assignment to PROCESSOR_NULL, under both the
1921  * thread lock and the pset lock corresponding to the current
1922  * non-null assignment.
1923  */
1924 extern void thread_clear_runq_locked(thread_t thread);
1925 
1926 /*
1927  * Assert the runq assignment to be PROCESSOR_NULL, under
1928  * some guarantee that the runq will not change from null to
1929  * non-null, such as holding the thread lock.
1930  */
1931 extern void thread_assert_runq_null(thread_t thread);
1932 
1933 /*
1934  * Assert the runq assignment to be non-null, under the pset
1935  * lock corresponding to the current non-null assignment.
1936  */
1937 extern void thread_assert_runq_nonnull(thread_t thread);
1938 
1939 extern bool thread_supports_cooperative_workqueue(thread_t thread);
1940 extern void thread_arm_workqueue_quantum(thread_t thread);
1941 extern void thread_disarm_workqueue_quantum(thread_t thread);
1942 
1943 extern void thread_evaluate_workqueue_quantum_expiry(thread_t thread);
1944 extern bool thread_has_expired_workqueue_quantum(thread_t thread, bool should_trace);
1945 
1946 #if CONFIG_SPTM
1947 
1948 extern void
1949 thread_associate_txm_thread_stack(uintptr_t thread_stack);
1950 
1951 extern void
1952 thread_disassociate_txm_thread_stack(uintptr_t thread_stack);
1953 
1954 extern uintptr_t
1955 thread_get_txm_thread_stack(void);
1956 
1957 #endif /* CONFIG_SPTM */
1958 
1959 /* Kernel side prototypes for MIG routines */
1960 extern kern_return_t thread_get_exception_ports(
1961 	thread_t                        thread,
1962 	exception_mask_t                exception_mask,
1963 	exception_mask_array_t          masks,
1964 	mach_msg_type_number_t          *CountCnt,
1965 	exception_port_array_t          ports,
1966 	exception_behavior_array_t      behaviors,
1967 	thread_state_flavor_array_t     flavors);
1968 
1969 extern kern_return_t thread_get_special_port(
1970 	thread_inspect_t         thread,
1971 	int                      which,
1972 	ipc_port_t              *portp);
1973 
1974 extern uint64_t thread_c_switch(thread_t thread);
1975 
1976 #endif /* XNU_KERNEL_PRIVATE */
1977 
1978 /*! @function thread_has_thread_name
1979  *   @abstract Checks if a thread has a name.
1980  *   @discussion This function takes one input, a thread, and returns
1981  *       a boolean value indicating if that thread already has a name associated
1982  *       with it.
1983  *   @param th The thread to inspect.
1984  *   @result TRUE if the thread has a name, FALSE otherwise.
1985  */
1986 extern boolean_t thread_has_thread_name(thread_t th);
1987 
1988 /*! @function thread_set_thread_name
1989  *   @abstract Set a thread's name.
1990  *   @discussion This function takes two input parameters: a thread to name,
1991  *       and the name to apply to the thread.  The name will be copied over to
1992  *       the thread in order to better identify the thread.  If the name is
1993  *       longer than MAXTHREADNAMESIZE - 1, it will be truncated.
1994  *   @param th The thread to be named.
1995  *   @param name The name to apply to the thread.
1996  */
1997 extern void thread_set_thread_name(thread_t th, const char* name);
1998 
1999 #if !MACH_KERNEL_PRIVATE || !defined(current_thread)
2000 extern thread_t current_thread(void) __pure2;
2001 #endif
2002 
2003 #if HAS_MTE
2004 /*! @function current_thread_enter_iomd_faultable_access_with_buffer_provider
2005  *   @abstract Store context for a critical faultable region while accessing tagged memory.
2006  *       @discussion We have paths in which the kernel is holding a tagged mapping which
2007  *              has a true share with userspace. Therefore, userspace can induce the kernel
2008  *              to take a TCF by changing the tag after handing the memory to the kernel.
2009  *              To deal with this, we enter a critical region while accessing this sort of
2010  *              memory, during which we'll recognize the fault as being 'caused by' the
2011  *              userspace task.
2012  *   @param provider The task to whom tag mismatches should be attributed.
2013  */
2014 void current_thread_enter_iomd_faultable_access_with_buffer_provider(task_t provider);
2015 /*! @function current_thread_exit_iomd_faultable_access
2016  *   @abstract Exit a critical region of accessing uncontrolled tagged memory.
2017  *       @discussion See current_thread_enter_iomd_faultable_access_with_buffer_provider
2018  */
2019 void current_thread_exit_iomd_faultable_access(void);
2020 /*! @function current_thread_get_iomd_faultable_access_buffer_provider
2021  *   @abstract Retrieve the task pointer storing the current faultable buffer provider.
2022  *       @discussion See current_thread_enter_iomd_faultable_access_with_buffer_provider
2023  */
2024 task_t current_thread_get_iomd_faultable_access_buffer_provider(void);
2025 #endif /* HAS_MTE */
2026 
2027 extern uint64_t thread_tid(thread_t thread) __pure2;
2028 
2029 extern void thread_reference(
2030 	thread_t        thread);
2031 
2032 extern void thread_deallocate(
2033 	thread_t        thread);
2034 
2035 /*! @function kernel_thread_start
2036  *   @abstract Create a kernel thread.
2037  *   @discussion This function takes three input parameters, namely reference
2038  *       to the function that the thread should execute, caller specified data
2039  *       and a reference which is used to return the newly created kernel
2040  *       thread. The function returns KERN_SUCCESS on success or an appropriate
2041  *       kernel code type indicating the error. It may be noted that the caller
2042  *       is responsible for explicitly releasing the reference to the created
2043  *       thread when no longer needed. This should be done by calling
2044  *       thread_deallocate(new_thread).
2045  *   @param continuation A C-function pointer where the thread will begin execution.
2046  *   @param parameter Caller specified data to be passed to the new thread.
2047  *   @param new_thread Reference to the new thread is returned in this parameter.
2048  *   @result Returns KERN_SUCCESS on success or an appropriate kernel code type.
2049  */
2050 
2051 extern kern_return_t    kernel_thread_start(
2052 	thread_continue_t       continuation,
2053 	void                    *parameter,
2054 	thread_t                *new_thread);
2055 
2056 __END_DECLS
2057 
2058 #endif  /* _KERN_THREAD_H_ */
2059