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