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