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