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 0x1234ABCDDCBA4321ULL
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) assertf((thread)->thread_magic == THREAD_MAGIC, \
1112 "bad thread magic 0x%llx for thread %p, expected 0x%llx", \
1113 (thread)->thread_magic, (thread), THREAD_MAGIC)
1114 #else
1115 #define assert_thread_magic(thread) do { (void)(thread); } while (0)
1116 #endif
1117
1118 extern thread_t thread_bootstrap(void);
1119
1120 extern void thread_machine_init_template(void);
1121
1122 extern void thread_init(void);
1123
1124 extern void thread_daemon_init(void);
1125
1126 extern void thread_reference(
1127 thread_t thread);
1128
1129 extern void thread_deallocate(
1130 thread_t thread);
1131
1132 extern void thread_inspect_deallocate(
1133 thread_inspect_t thread);
1134
1135 extern void thread_read_deallocate(
1136 thread_read_t thread);
1137
1138 extern kern_return_t thread_terminate(
1139 thread_t thread);
1140
1141 extern void thread_terminate_self(void);
1142
1143 extern kern_return_t thread_terminate_internal(
1144 thread_t thread);
1145
1146 extern void thread_start(
1147 thread_t thread) __attribute__ ((noinline));
1148
1149 extern void thread_start_in_assert_wait(
1150 thread_t thread,
1151 struct waitq *waitq,
1152 event64_t event,
1153 wait_interrupt_t interruptible) __attribute__ ((noinline));
1154
1155 extern void thread_terminate_enqueue(
1156 thread_t thread);
1157
1158 extern void thread_exception_enqueue(
1159 task_t task,
1160 thread_t thread,
1161 exception_type_t etype);
1162
1163 extern void thread_backtrace_enqueue(
1164 kcdata_object_t obj,
1165 exception_port_t ports[static BT_EXC_PORTS_COUNT],
1166 exception_type_t etype);
1167
1168 extern void thread_copy_resource_info(
1169 thread_t dst_thread,
1170 thread_t src_thread);
1171
1172 extern void thread_terminate_crashed_threads(void);
1173
1174 extern void thread_stack_enqueue(
1175 thread_t thread);
1176
1177 extern void thread_hold(
1178 thread_t thread);
1179
1180 extern void thread_release(
1181 thread_t thread);
1182
1183 extern void thread_corpse_continue(void) __dead2;
1184
1185 extern boolean_t thread_is_active(thread_t thread);
1186
1187 extern lck_grp_t thread_lck_grp;
1188
1189 /* Locking for scheduler state, always acquired with interrupts disabled (splsched()) */
1190 #define thread_lock_init(th) simple_lock_init(&(th)->sched_lock, 0)
1191 #define thread_lock(th) simple_lock(&(th)->sched_lock, &thread_lck_grp)
1192 #define thread_unlock(th) simple_unlock(&(th)->sched_lock)
1193 #define thread_lock_assert(th, x) simple_lock_assert(&(th)->sched_lock, (x))
1194
1195 #define wake_lock_init(th) simple_lock_init(&(th)->wake_lock, 0)
1196 #define wake_lock(th) simple_lock(&(th)->wake_lock, &thread_lck_grp)
1197 #define wake_unlock(th) simple_unlock(&(th)->wake_lock)
1198
1199 #define thread_should_halt_fast(thread) (!(thread)->active)
1200
1201 extern void stack_alloc(
1202 thread_t thread);
1203
1204 extern void stack_handoff(
1205 thread_t from,
1206 thread_t to);
1207
1208 extern void stack_free(
1209 thread_t thread);
1210
1211 extern void stack_free_reserved(
1212 thread_t thread);
1213
1214 extern boolean_t stack_alloc_try(
1215 thread_t thread);
1216
1217 extern void stack_collect(void);
1218
1219 extern kern_return_t thread_info_internal(
1220 thread_t thread,
1221 thread_flavor_t flavor,
1222 thread_info_t thread_info_out,
1223 mach_msg_type_number_t *thread_info_count);
1224
1225 extern kern_return_t kernel_thread_create(
1226 thread_continue_t continuation,
1227 void *parameter,
1228 integer_t priority,
1229 thread_t *new_thread);
1230
1231 extern kern_return_t kernel_thread_start_priority(
1232 thread_continue_t continuation,
1233 void *parameter,
1234 integer_t priority,
1235 thread_t *new_thread);
1236
1237 extern void machine_stack_attach(
1238 thread_t thread,
1239 vm_offset_t stack);
1240
1241 extern vm_offset_t machine_stack_detach(
1242 thread_t thread);
1243
1244 extern void machine_stack_handoff(
1245 thread_t old,
1246 thread_t new);
1247
1248 extern thread_t machine_switch_context(
1249 thread_t old_thread,
1250 thread_continue_t continuation,
1251 thread_t new_thread);
1252
1253 extern void machine_load_context(
1254 thread_t thread) __attribute__((noreturn));
1255
1256 extern void machine_thread_state_initialize(
1257 thread_t thread);
1258
1259 extern kern_return_t machine_thread_set_state(
1260 thread_t thread,
1261 thread_flavor_t flavor,
1262 thread_state_t state,
1263 mach_msg_type_number_t count);
1264
1265 extern mach_vm_address_t machine_thread_pc(
1266 thread_t thread);
1267
1268 extern void machine_thread_reset_pc(
1269 thread_t thread,
1270 mach_vm_address_t pc);
1271
1272 extern boolean_t machine_thread_on_core(
1273 thread_t thread);
1274
1275 extern boolean_t machine_thread_on_core_allow_invalid(
1276 thread_t thread);
1277
1278 extern kern_return_t machine_thread_get_state(
1279 thread_t thread,
1280 thread_flavor_t flavor,
1281 thread_state_t state,
1282 mach_msg_type_number_t *count);
1283
1284 extern kern_return_t machine_thread_state_convert_from_user(
1285 thread_t thread,
1286 thread_flavor_t flavor,
1287 thread_state_t tstate,
1288 mach_msg_type_number_t count,
1289 thread_state_t old_tstate,
1290 mach_msg_type_number_t old_count,
1291 thread_set_status_flags_t tssf_flags);
1292
1293 extern kern_return_t machine_thread_state_convert_to_user(
1294 thread_t thread,
1295 thread_flavor_t flavor,
1296 thread_state_t tstate,
1297 mach_msg_type_number_t *count,
1298 thread_set_status_flags_t tssf_flags);
1299
1300 extern kern_return_t machine_thread_dup(
1301 thread_t self,
1302 thread_t target,
1303 boolean_t is_corpse);
1304
1305 extern void machine_thread_init(void);
1306
1307 extern void machine_thread_template_init(thread_t thr_template);
1308
1309 #if __has_feature(ptrauth_calls)
1310 extern bool machine_thread_state_is_debug_flavor(int flavor);
1311 #endif /* __has_feature(ptrauth_calls) */
1312
1313
1314 extern void machine_thread_create(
1315 thread_t thread,
1316 task_t task,
1317 bool first_thread);
1318
1319 extern kern_return_t machine_thread_process_signature(
1320 thread_t thread,
1321 task_t task);
1322
1323 extern void machine_thread_switch_addrmode(
1324 thread_t thread);
1325
1326 extern void machine_thread_destroy(
1327 thread_t thread);
1328
1329 extern void machine_set_current_thread(
1330 thread_t thread);
1331
1332 extern kern_return_t machine_thread_get_kern_state(
1333 thread_t thread,
1334 thread_flavor_t flavor,
1335 thread_state_t tstate,
1336 mach_msg_type_number_t *count);
1337
1338 extern kern_return_t machine_thread_inherit_taskwide(
1339 thread_t thread,
1340 task_t parent_task);
1341
1342 extern kern_return_t machine_thread_set_tsd_base(
1343 thread_t thread,
1344 mach_vm_offset_t tsd_base);
1345
1346 #define thread_mtx_try(thread) lck_mtx_try_lock(&(thread)->mutex)
1347 #define thread_mtx_held(thread) lck_mtx_assert(&(thread)->mutex, LCK_MTX_ASSERT_OWNED)
1348
1349 extern void thread_apc_ast(thread_t thread);
1350
1351 extern void thread_update_qos_cpu_time(thread_t thread);
1352
1353 void act_machine_sv_free(thread_t, int);
1354
1355 vm_offset_t min_valid_stack_address(void);
1356 vm_offset_t max_valid_stack_address(void);
1357
1358 #if CONFIG_SCHED_SMT
1359 extern bool thread_no_smt(thread_t thread);
1360 extern bool processor_active_thread_no_smt(processor_t processor);
1361 #endif /* CONFIG_SCHED_SMT */
1362
1363 extern void thread_set_options(uint32_t thopt);
1364
1365 #if CONFIG_THREAD_GROUPS
1366 struct thread_group *thread_get_current_voucher_thread_group(thread_t thread);
1367 #endif /* CONFIG_THREAD_GROUPS */
1368
1369 #if CONFIG_COALITIONS
1370 uint64_t thread_get_current_voucher_resource_coalition_id(thread_t thread);
1371 #endif /* CONFIG_COALITIONS */
1372
1373 #endif /* MACH_KERNEL_PRIVATE */
1374 #if BSD_KERNEL_PRIVATE
1375
1376 /* Duplicated from osfmk/kern/ipc_tt.h */
1377 __options_decl(port_intrans_options_t, uint32_t, {
1378 PORT_INTRANS_OPTIONS_NONE = 0x0000,
1379 PORT_INTRANS_THREAD_IN_CURRENT_TASK = 0x0001,
1380 PORT_INTRANS_THREAD_NOT_CURRENT_THREAD = 0x0002,
1381
1382 PORT_INTRANS_SKIP_TASK_EVAL = 0x0004,
1383 PORT_INTRANS_ALLOW_CORPSE_TASK = 0x0008,
1384 });
1385
1386 extern thread_t port_name_to_thread(
1387 mach_port_name_t port_name,
1388 port_intrans_options_t options);
1389
1390 #endif /* BSD_KERNEL_PRIVATE */
1391 #ifdef XNU_KERNEL_PRIVATE
1392
1393 extern void thread_require(
1394 thread_t thread);
1395
1396 extern void thread_deallocate_safe(
1397 thread_t thread);
1398
1399 extern uint64_t thread_rettokern_addr(
1400 thread_t thread);
1401
1402 extern uint64_t thread_wqquantum_addr(
1403 thread_t thread);
1404
1405 extern integer_t thread_kern_get_pri(thread_t thr) __pure2;
1406
1407 extern void thread_kern_set_pri(thread_t thr, integer_t pri);
1408
1409 extern integer_t thread_kern_get_kernel_maxpri(void) __pure2;
1410
1411 uint16_t thread_set_tag(thread_t thread, uint16_t tag);
1412 uint16_t thread_get_tag(thread_t thread);
1413
1414 __options_decl(shared_rsrc_policy_agent_t, uint32_t, {
1415 SHARED_RSRC_POLICY_AGENT_DISPATCH = 0,
1416 SHARED_RSRC_POLICY_AGENT_SYSCTL = 1,
1417 SHARED_RSRC_POLICY_AGENT_PERFCTL_CSW = 2,
1418 SHARED_RSRC_POLICY_AGENT_PERFCTL_QUANTUM = 3,
1419 });
1420
1421 boolean_t thread_shared_rsrc_policy_get(thread_t thread, cluster_shared_rsrc_type_t type);
1422 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);
1423 kern_return_t thread_shared_rsrc_policy_clear(thread_t thread, cluster_shared_rsrc_type_t type, shared_rsrc_policy_agent_t agent);
1424
1425 #ifdef MACH_KERNEL_PRIVATE
1426 static inline thread_tag_t
thread_set_tag_internal(thread_t thread,thread_tag_t tag)1427 thread_set_tag_internal(thread_t thread, thread_tag_t tag)
1428 {
1429 return os_atomic_or_orig(&thread->thread_tag, tag, relaxed);
1430 }
1431
1432 static inline thread_tag_t
thread_get_tag_internal(thread_t thread)1433 thread_get_tag_internal(thread_t thread)
1434 {
1435 return thread->thread_tag;
1436 }
1437 #endif /* MACH_KERNEL_PRIVATE */
1438
1439 extern uint64_t thread_last_run_time(
1440 thread_t thread);
1441
1442 extern kern_return_t thread_state_initialize(
1443 thread_t thread);
1444
1445 extern kern_return_t thread_setstatus(
1446 thread_t thread,
1447 int flavor,
1448 thread_state_t tstate,
1449 mach_msg_type_number_t count);
1450
1451 extern kern_return_t thread_setstatus_from_user(
1452 thread_t thread,
1453 int flavor,
1454 thread_state_t tstate,
1455 mach_msg_type_number_t count,
1456 thread_state_t old_tstate,
1457 mach_msg_type_number_t old_count,
1458 thread_set_status_flags_t flags);
1459
1460 extern kern_return_t thread_getstatus(
1461 thread_t thread,
1462 int flavor,
1463 thread_state_t tstate,
1464 mach_msg_type_number_t *count);
1465
1466 extern kern_return_t thread_getstatus_to_user(
1467 thread_t thread,
1468 int flavor,
1469 thread_state_t tstate,
1470 mach_msg_type_number_t *count,
1471 thread_set_status_flags_t flags);
1472
1473 extern kern_return_t thread_create_with_continuation(
1474 task_t task,
1475 thread_t *new_thread,
1476 thread_continue_t continuation);
1477
1478 extern kern_return_t main_thread_create_waiting(
1479 task_t task,
1480 thread_continue_t continuation,
1481 event_t event,
1482 thread_t *new_thread);
1483
1484 extern kern_return_t thread_create_workq_waiting(
1485 task_t task,
1486 thread_continue_t thread_return,
1487 thread_t *new_thread,
1488 bool is_permanently_bound);
1489
1490 extern kern_return_t thread_create_aio_workq_waiting(
1491 task_t task,
1492 thread_continue_t thread_return,
1493 thread_t *new_thread);
1494
1495 extern void thread_yield_internal(
1496 mach_msg_timeout_t interval);
1497
1498 extern void thread_yield_to_preemption(void);
1499
1500 extern void thread_depress_timer_setup(
1501 thread_t self);
1502
1503 /*
1504 * Thread-private CPU limits: apply a private CPU limit to this thread only. Available actions are:
1505 *
1506 * 1) Block. Prevent CPU consumption of the thread from exceeding the limit.
1507 * 2) Exception. Generate a resource consumption exception when the limit is exceeded.
1508 * 3) Disable. Remove any existing CPU limit.
1509 */
1510 #define THREAD_CPULIMIT_BLOCK 0x1
1511 #define THREAD_CPULIMIT_EXCEPTION 0x2
1512 #define THREAD_CPULIMIT_DISABLE 0x3
1513
1514 struct _thread_ledger_indices {
1515 int cpu_time;
1516 };
1517
1518 extern struct _thread_ledger_indices thread_ledgers;
1519
1520 extern int thread_get_cpulimit(int *action, uint8_t *percentage, uint64_t *interval_ns);
1521 extern int thread_set_cpulimit(int action, uint8_t percentage, uint64_t interval_ns);
1522
1523 extern uint64_t thread_cpulimit_remaining(uint64_t now);
1524 extern bool thread_cpulimit_interval_has_expired(uint64_t now);
1525 extern void thread_cpulimit_restart(uint64_t now);
1526
1527 extern void thread_read_times(
1528 thread_t thread,
1529 time_value_t *user_time,
1530 time_value_t *system_time,
1531 time_value_t *runnable_time);
1532
1533 extern void thread_read_times_unsafe(
1534 thread_t thread,
1535 time_value_t *user_time,
1536 time_value_t *system_time,
1537 time_value_t *runnable_time);
1538
1539 extern uint64_t thread_get_runtime_self(void);
1540
1541 extern void thread_setuserstack(
1542 thread_t thread,
1543 mach_vm_offset_t user_stack);
1544
1545 extern user_addr_t thread_adjuserstack(
1546 thread_t thread,
1547 int adjust);
1548
1549
1550 extern void thread_setentrypoint(
1551 thread_t thread,
1552 mach_vm_offset_t entry);
1553
1554 extern kern_return_t thread_set_tsd_base(
1555 thread_t thread,
1556 mach_vm_offset_t tsd_base);
1557
1558 extern kern_return_t thread_setsinglestep(
1559 thread_t thread,
1560 int on);
1561
1562 extern kern_return_t thread_userstack(
1563 thread_t,
1564 int,
1565 thread_state_t,
1566 unsigned int,
1567 mach_vm_offset_t *,
1568 int *,
1569 boolean_t);
1570
1571 extern kern_return_t thread_entrypoint(
1572 thread_t,
1573 int,
1574 thread_state_t,
1575 unsigned int,
1576 mach_vm_offset_t *);
1577
1578 extern kern_return_t thread_userstackdefault(
1579 mach_vm_offset_t *,
1580 boolean_t);
1581
1582 extern kern_return_t thread_wire_internal(
1583 host_priv_t host_priv,
1584 thread_t thread,
1585 boolean_t wired,
1586 boolean_t *prev_state);
1587
1588
1589 extern kern_return_t thread_dup(thread_t);
1590
1591 extern kern_return_t thread_dup2(thread_t, thread_t);
1592
1593 #if !defined(_SCHED_CALL_T_DEFINED)
1594 #define _SCHED_CALL_T_DEFINED
1595 typedef void (*sched_call_t)(
1596 int type,
1597 thread_t thread);
1598 #endif
1599
1600 #define SCHED_CALL_BLOCK 0x1
1601 #define SCHED_CALL_UNBLOCK 0x2
1602
1603 extern void thread_sched_call(
1604 thread_t thread,
1605 sched_call_t call);
1606
1607 extern boolean_t thread_is_static_param(
1608 thread_t thread);
1609
1610 extern task_t get_threadtask(thread_t) __pure2;
1611
1612 extern task_t get_threadtask_early(thread_t) __pure2;
1613
1614 /*
1615 * Thread is running within a 64-bit address space.
1616 */
1617 #define thread_is_64bit_addr(thd) \
1618 task_has_64Bit_addr(get_threadtask(thd))
1619
1620 /*
1621 * Thread is using 64-bit machine state.
1622 */
1623 #define thread_is_64bit_data(thd) \
1624 task_has_64Bit_data(get_threadtask(thd))
1625
1626 struct uthread;
1627
1628 #if defined(__x86_64__)
1629 extern int thread_task_has_ldt(thread_t);
1630 #endif
1631 extern void set_thread_pagein_error(thread_t, int);
1632 extern event_t workq_thread_init_and_wq_lock(task_t, thread_t); // bsd/pthread/
1633 extern event_t aio_workq_thread_init_and_wq_lock(task_t, thread_t); // bsd/aio/
1634
1635 struct proc;
1636 struct uthread;
1637 struct image_params;
1638 extern const size_t uthread_size;
1639 extern thread_ro_t get_thread_ro_unchecked(thread_t) __pure2;
1640 extern thread_ro_t get_thread_ro(thread_t) __pure2;
1641 extern thread_ro_t current_thread_ro_unchecked(void) __pure2;
1642 extern thread_ro_t current_thread_ro(void) __pure2;
1643 extern void clear_thread_ro_proc(thread_t);
1644 extern struct uthread *get_bsdthread_info(thread_t) __pure2;
1645 extern thread_t get_machthread(struct uthread *) __pure2;
1646 extern uint64_t uthread_tid(struct uthread *) __pure2;
1647 extern user_addr_t thread_get_sigreturn_token(thread_t thread);
1648 extern uint32_t thread_get_sigreturn_diversifier(thread_t thread);
1649 extern void uthread_init(task_t, struct uthread *, thread_ro_t, int);
1650 extern void uthread_cleanup_name(struct uthread *uthread);
1651 extern void uthread_cleanup(struct uthread *, thread_ro_t);
1652 extern void uthread_cred_ref(struct ucred *);
1653 extern void uthread_cred_free(struct ucred *);
1654 extern void uthread_destroy(struct uthread *);
1655 extern void uthread_reset_proc_refcount(struct uthread *);
1656
1657 extern void uthread_set_exec_data(struct uthread *uth, struct image_params *imgp);
1658 extern bool uthread_is64bit(struct uthread *uth) __pure2;
1659 #if PROC_REF_DEBUG
1660 extern void uthread_init_proc_refcount(struct uthread *);
1661 extern void uthread_destroy_proc_refcount(struct uthread *);
1662 extern void uthread_assert_zero_proc_refcount(struct uthread *);
1663 #else
1664 #define uthread_init_proc_refcount(uth) ((void)(uth))
1665 #define uthread_destroy_proc_refcount(uth) ((void)(uth))
1666 #define uthread_assert_zero_proc_refcount(uth) ((void)(uth))
1667 #endif
1668 #if CONFIG_DEBUG_SYSCALL_REJECTION
1669 extern uint64_t uthread_get_syscall_rejection_flags(void *);
1670 extern uint64_t *uthread_get_syscall_rejection_mask(void *);
1671 extern uint64_t *uthread_get_syscall_rejection_once_mask(void *);
1672 extern bool uthread_syscall_rejection_is_enabled(void *);
1673 #endif /* CONFIG_DEBUG_SYSCALL_REJECTION */
1674 extern mach_port_name_t uthread_joiner_port(struct uthread *);
1675 extern user_addr_t uthread_joiner_address(struct uthread *);
1676 extern void uthread_joiner_wake(task_t task, struct uthread *);
1677
1678 extern boolean_t thread_should_halt(
1679 thread_t thread);
1680
1681 extern boolean_t thread_should_abort(
1682 thread_t);
1683
1684 extern bool current_thread_in_kernel_fault(void);
1685
1686 extern int is_64signalregset(void);
1687
1688 extern void act_set_kperf(thread_t);
1689 extern void act_set_astledger(thread_t thread);
1690 extern void act_set_astledger_async(thread_t thread);
1691 extern void act_set_io_telemetry_ast(thread_t);
1692 extern void act_set_macf_telemetry_ast(thread_t);
1693 extern void act_set_astproc_resource(thread_t);
1694
1695 extern vm_offset_t thread_get_kernel_stack(thread_t);
1696
1697 extern kern_return_t thread_process_signature(thread_t thread, task_t task);
1698
1699 extern uint32_t dtrace_get_thread_predcache(thread_t);
1700 extern int64_t dtrace_get_thread_vtime(thread_t);
1701 extern int64_t dtrace_get_thread_tracing(thread_t);
1702 extern uint16_t dtrace_get_thread_inprobe(thread_t);
1703 extern int dtrace_get_thread_last_cpu_id(thread_t);
1704 extern vm_offset_t dtrace_get_kernel_stack(thread_t);
1705 #define dtrace_get_kernel_stack thread_get_kernel_stack
1706 extern void dtrace_set_thread_predcache(thread_t, uint32_t);
1707 extern void dtrace_set_thread_vtime(thread_t, int64_t);
1708 extern void dtrace_set_thread_tracing(thread_t, int64_t);
1709 extern void dtrace_set_thread_inprobe(thread_t, uint16_t);
1710 extern void dtrace_thread_bootstrap(void);
1711 extern void dtrace_thread_didexec(thread_t);
1712
1713 extern int64_t dtrace_calc_thread_recent_vtime(thread_t);
1714
1715
1716 extern kern_return_t thread_set_wq_state32(
1717 thread_t thread,
1718 thread_state_t tstate);
1719
1720 extern kern_return_t thread_set_wq_state64(
1721 thread_t thread,
1722 thread_state_t tstate);
1723
1724 extern vm_offset_t kernel_stack_mask;
1725 extern vm_offset_t kernel_stack_size;
1726 extern vm_offset_t kernel_stack_depth_max;
1727
1728 extern void mach_exception_ast(thread_t);
1729 extern void fd_guard_ast(thread_t,
1730 mach_exception_code_t, mach_exception_subcode_t);
1731 extern void vn_guard_ast(thread_t,
1732 mach_exception_code_t, mach_exception_subcode_t);
1733 extern void mach_port_guard_ast(thread_t,
1734 mach_exception_code_t, mach_exception_subcode_t);
1735 extern void virt_memory_guard_ast(thread_t,
1736 mach_exception_code_t, mach_exception_subcode_t);
1737 extern void thread_ast_mach_exception(thread_t,
1738 int, exception_type_t, mach_exception_code_t, mach_exception_subcode_t, bool, bool);
1739 extern void thread_guard_violation(thread_t,
1740 mach_exception_code_t, mach_exception_subcode_t, bool);
1741 extern void thread_update_io_stats(thread_t, int size, int io_flags);
1742
1743 extern kern_return_t thread_set_voucher_name(mach_port_name_t name);
1744 extern kern_return_t thread_get_voucher_origin_pid(thread_t thread, int32_t *pid);
1745 extern kern_return_t thread_get_voucher_origin_proximate_pid(thread_t thread,
1746 int32_t *origin_pid, int32_t *proximate_pid);
1747 extern kern_return_t thread_get_current_voucher_origin_pid(int32_t *pid);
1748
1749 extern void thread_enable_send_importance(thread_t thread, boolean_t enable);
1750
1751 /*
1752 * Translate signal context data pointer to userspace representation
1753 */
1754
1755 extern kern_return_t machine_thread_siguctx_pointer_convert_to_user(
1756 thread_t thread,
1757 user_addr_t *uctxp);
1758
1759 extern void machine_tecs(thread_t thr);
1760
1761 typedef enum cpuvn {
1762 CPUVN_CI = 1
1763 } cpuvn_e;
1764
1765 extern int machine_csv(cpuvn_e cve);
1766 #if defined(__x86_64__)
1767 extern void machine_thread_set_insn_copy_optout(thread_t thr);
1768 #endif
1769
1770 /*
1771 * Translate array of function pointer syscall arguments from userspace representation
1772 */
1773
1774 extern kern_return_t machine_thread_function_pointers_convert_from_user(
1775 thread_t thread,
1776 user_addr_t *fptrs,
1777 uint32_t count);
1778
1779 /*
1780 * Get the duration of the given thread's last wait.
1781 */
1782 uint64_t thread_get_last_wait_duration(thread_t thread);
1783
1784 #if CONFIG_SCHED_SMT
1785 extern bool thread_get_no_smt(void);
1786 #endif /* CONFIG_SCHED_SMT */
1787 #if defined(__x86_64__)
1788 extern bool curtask_get_insn_copy_optout(void);
1789 extern void curtask_set_insn_copy_optout(void);
1790 #endif /* defined(__x86_64__) */
1791
1792 /*! @function ctid_get_thread
1793 * @abstract translates a ctid_t to thread_t
1794 * @discussion ctid are system wide compact thread-id
1795 * associated to thread_t at thread creation
1796 * and recycled at thread termination. If a ctid is
1797 * referenced past the corresponding thread termination,
1798 * it is considered stale, and the behavior is not defined.
1799 * Note that this call does not acquire a reference on the thread,
1800 * so as soon as the matching thread terminates, the ctid
1801 * will become stale, and it could be re-used and associated with
1802 * another thread. You must externally guarantee that the thread
1803 * will not exit while you are using its ctid.
1804 * @result thread_t corresponding to ctid
1805 */
1806 extern thread_t ctid_get_thread(ctid_t ctid);
1807
1808 /*! @function ctid_get_thread
1809 * @abstract translates a ctid_t to thread_t
1810 * @discussion Unsafe variant of ctid_get_thread() to be used
1811 * when the caller can't guarantee the liveness of this ctid_t.
1812 * may return NULL or a freed thread_t.
1813 */
1814 extern thread_t ctid_get_thread_unsafe(ctid_t ctid);
1815
1816 /*!
1817 * @function thread_get_ctid
1818 * @abstract returns the ctid of thread.
1819 * @param thread to find the corresponding ctid.
1820 * @discussion the ctid provided will become stale after the matching thread
1821 * terminates.
1822 * @result uint32_t ctid.
1823 */
1824 extern ctid_t thread_get_ctid(thread_t thread);
1825
1826 #endif /* XNU_KERNEL_PRIVATE */
1827 #ifdef KERNEL_PRIVATE
1828
1829 typedef struct thread_pri_floor {
1830 thread_t thread;
1831 } thread_pri_floor_t;
1832
1833 #ifdef MACH_KERNEL_PRIVATE
1834 extern void thread_floor_boost_ast(thread_t thread);
1835 extern void thread_floor_boost_set_promotion_locked(thread_t thread);
1836 #endif /* MACH_KERNEL_PRIVATE */
1837
1838 /*! @function thread_priority_floor_start
1839 * @abstract boost the current thread priority to floor.
1840 * @discussion Increase the priority of the current thread to at least MINPRI_FLOOR.
1841 * The boost will be mantained until a corresponding thread_priority_floor_end()
1842 * is called. Every call of thread_priority_floor_start() needs to have a corresponding
1843 * call to thread_priority_floor_end() from the same thread.
1844 * No thread can return to userspace before calling thread_priority_floor_end().
1845 *
1846 * NOTE: avoid to use this function. Try to use gate_t or sleep_with_inheritor()
1847 * instead.
1848 * @result a token to be given to the corresponding thread_priority_floor_end()
1849 */
1850 extern thread_pri_floor_t thread_priority_floor_start(void);
1851 /*! @function thread_priority_floor_end
1852 * @abstract ends the floor boost.
1853 * @param token the token obtained from thread_priority_floor_start()
1854 * @discussion ends the priority floor boost started with thread_priority_floor_start()
1855 */
1856 extern void thread_priority_floor_end(thread_pri_floor_t *token);
1857
1858 #if defined(__x86_64__)
1859 extern void thread_set_no_smt(bool set);
1860 #endif /* __x86_64__ */
1861
1862 extern void thread_mtx_lock(thread_t thread);
1863
1864 extern void thread_mtx_unlock(thread_t thread);
1865
1866 extern uint64_t thread_dispatchqaddr(
1867 thread_t thread);
1868
1869 bool thread_is_eager_preempt(thread_t thread);
1870 void thread_set_eager_preempt(thread_t thread);
1871 void thread_clear_eager_preempt(thread_t thread);
1872 void thread_set_honor_qlimit(thread_t thread);
1873 void thread_clear_honor_qlimit(thread_t thread);
1874 extern ipc_port_t convert_thread_to_port(thread_t);
1875 extern ipc_port_t convert_thread_to_port_immovable(thread_t);
1876 extern ipc_port_t convert_thread_inspect_to_port(thread_inspect_t);
1877 extern ipc_port_t convert_thread_read_to_port(thread_read_t);
1878 extern void convert_thread_array_to_ports(thread_act_array_t, size_t, mach_thread_flavor_t);
1879 extern boolean_t is_external_pageout_thread(void);
1880 extern boolean_t is_vm_privileged(void);
1881 extern boolean_t set_vm_privilege(boolean_t);
1882 extern kern_allocation_name_t thread_set_allocation_name(kern_allocation_name_t new_name);
1883 extern void *thread_iokit_tls_get(uint32_t index);
1884 extern void thread_iokit_tls_set(uint32_t index, void * data);
1885 extern int thread_self_region_page_shift(void);
1886 extern void thread_self_region_page_shift_set(int pgshift);
1887 extern kern_return_t thread_create_immovable(task_t task, thread_t *new_thread);
1888 extern kern_return_t thread_terminate_immovable(thread_t thread);
1889
1890 struct thread_attr_for_ipc_propagation;
1891 extern kern_return_t thread_get_ipc_propagate_attr(thread_t thread, struct thread_attr_for_ipc_propagation *attr);
1892 extern size_t thread_get_current_exec_path(char *path, size_t size);
1893 #endif /* KERNEL_PRIVATE */
1894 #ifdef XNU_KERNEL_PRIVATE
1895
1896 extern void
1897 thread_get_thread_name(thread_t th, char* name);
1898
1899 /* Read the runq assignment, under the thread lock. */
1900 extern processor_t thread_get_runq(thread_t thread);
1901
1902 /*
1903 * Read the runq assignment, under both the thread lock and
1904 * the pset lock corresponding to the last non-null assignment.
1905 */
1906 extern processor_t thread_get_runq_locked(thread_t thread);
1907
1908 /*
1909 * Set the runq assignment to a non-null value, under both the
1910 * thread lock and the pset lock corresponding to the new
1911 * assignment.
1912 */
1913 extern void thread_set_runq_locked(thread_t thread, processor_t new_runq);
1914
1915 /*
1916 * Set the runq assignment to PROCESSOR_NULL, under the pset
1917 * lock corresponding to the current non-null assignment.
1918 */
1919 extern void thread_clear_runq(thread_t thread);
1920
1921 /*
1922 * Set the runq assignment to PROCESSOR_NULL, under both the
1923 * thread lock and the pset lock corresponding to the current
1924 * non-null assignment.
1925 */
1926 extern void thread_clear_runq_locked(thread_t thread);
1927
1928 /*
1929 * Assert the runq assignment to be PROCESSOR_NULL, under
1930 * some guarantee that the runq will not change from null to
1931 * non-null, such as holding the thread lock.
1932 */
1933 extern void thread_assert_runq_null(thread_t thread);
1934
1935 /*
1936 * Assert the runq assignment to be non-null, under the pset
1937 * lock corresponding to the current non-null assignment.
1938 */
1939 extern void thread_assert_runq_nonnull(thread_t thread);
1940
1941 extern bool thread_supports_cooperative_workqueue(thread_t thread);
1942 extern void thread_arm_workqueue_quantum(thread_t thread);
1943 extern void thread_disarm_workqueue_quantum(thread_t thread);
1944
1945 extern void thread_evaluate_workqueue_quantum_expiry(thread_t thread);
1946 extern bool thread_has_expired_workqueue_quantum(thread_t thread, bool should_trace);
1947
1948 #if CONFIG_SPTM
1949
1950 extern void
1951 thread_associate_txm_thread_stack(uintptr_t thread_stack);
1952
1953 extern void
1954 thread_disassociate_txm_thread_stack(uintptr_t thread_stack);
1955
1956 extern uintptr_t
1957 thread_get_txm_thread_stack(void);
1958
1959 #endif /* CONFIG_SPTM */
1960
1961 /* Kernel side prototypes for MIG routines */
1962 extern kern_return_t thread_get_exception_ports(
1963 thread_t thread,
1964 exception_mask_t exception_mask,
1965 exception_mask_array_t masks,
1966 mach_msg_type_number_t *CountCnt,
1967 exception_port_array_t ports,
1968 exception_behavior_array_t behaviors,
1969 thread_state_flavor_array_t flavors);
1970
1971 extern kern_return_t thread_get_special_port(
1972 thread_inspect_t thread,
1973 int which,
1974 ipc_port_t *portp);
1975
1976 extern uint64_t thread_c_switch(thread_t thread);
1977
1978 #endif /* XNU_KERNEL_PRIVATE */
1979
1980 /*! @function thread_has_thread_name
1981 * @abstract Checks if a thread has a name.
1982 * @discussion This function takes one input, a thread, and returns
1983 * a boolean value indicating if that thread already has a name associated
1984 * with it.
1985 * @param th The thread to inspect.
1986 * @result TRUE if the thread has a name, FALSE otherwise.
1987 */
1988 extern boolean_t thread_has_thread_name(thread_t th);
1989
1990 /*! @function thread_set_thread_name
1991 * @abstract Set a thread's name.
1992 * @discussion This function takes two input parameters: a thread to name,
1993 * and the name to apply to the thread. The name will be copied over to
1994 * the thread in order to better identify the thread. If the name is
1995 * longer than MAXTHREADNAMESIZE - 1, it will be truncated.
1996 * @param th The thread to be named.
1997 * @param name The name to apply to the thread.
1998 */
1999 extern void thread_set_thread_name(thread_t th, const char* name);
2000
2001 #if !MACH_KERNEL_PRIVATE || !defined(current_thread)
2002 extern thread_t current_thread(void) __pure2;
2003 #endif
2004
2005 #if HAS_MTE
2006 /*! @function current_thread_enter_iomd_faultable_access_with_buffer_provider
2007 * @abstract Store context for a critical faultable region while accessing tagged memory.
2008 * @discussion We have paths in which the kernel is holding a tagged mapping which
2009 * has a true share with userspace. Therefore, userspace can induce the kernel
2010 * to take a TCF by changing the tag after handing the memory to the kernel.
2011 * To deal with this, we enter a critical region while accessing this sort of
2012 * memory, during which we'll recognize the fault as being 'caused by' the
2013 * userspace task.
2014 * @param provider The task to whom tag mismatches should be attributed.
2015 */
2016 void current_thread_enter_iomd_faultable_access_with_buffer_provider(task_t provider);
2017 /*! @function current_thread_exit_iomd_faultable_access
2018 * @abstract Exit a critical region of accessing uncontrolled tagged memory.
2019 * @discussion See current_thread_enter_iomd_faultable_access_with_buffer_provider
2020 */
2021 void current_thread_exit_iomd_faultable_access(void);
2022 /*! @function current_thread_get_iomd_faultable_access_buffer_provider
2023 * @abstract Retrieve the task pointer storing the current faultable buffer provider.
2024 * @discussion See current_thread_enter_iomd_faultable_access_with_buffer_provider
2025 */
2026 task_t current_thread_get_iomd_faultable_access_buffer_provider(void);
2027 #endif /* HAS_MTE */
2028
2029 extern uint64_t thread_tid(thread_t thread) __pure2;
2030
2031 extern void thread_reference(
2032 thread_t thread);
2033
2034 extern void thread_deallocate(
2035 thread_t thread);
2036
2037 /*! @function kernel_thread_start
2038 * @abstract Create a kernel thread.
2039 * @discussion This function takes three input parameters, namely reference
2040 * to the function that the thread should execute, caller specified data
2041 * and a reference which is used to return the newly created kernel
2042 * thread. The function returns KERN_SUCCESS on success or an appropriate
2043 * kernel code type indicating the error. It may be noted that the caller
2044 * is responsible for explicitly releasing the reference to the created
2045 * thread when no longer needed. This should be done by calling
2046 * thread_deallocate(new_thread).
2047 * @param continuation A C-function pointer where the thread will begin execution.
2048 * @param parameter Caller specified data to be passed to the new thread.
2049 * @param new_thread Reference to the new thread is returned in this parameter.
2050 * @result Returns KERN_SUCCESS on success or an appropriate kernel code type.
2051 */
2052
2053 extern kern_return_t kernel_thread_start(
2054 thread_continue_t continuation,
2055 void *parameter,
2056 thread_t *new_thread);
2057
2058 __END_DECLS
2059
2060 #endif /* _KERN_THREAD_H_ */
2061