2 * Copyright (c) 2000-2015 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * @OSF_FREE_COPYRIGHT@
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
34 * All Rights Reserved.
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.
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.
46 * Carnegie Mellon requests users of this software to return to
48 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
60 * Author: Avadis Tevanian, Jr., Michael Wayne Young, David Golub
63 * Thread management primitives implementation.
66 * Copyright (c) 1993 The University of Utah and
67 * the Computer Systems Laboratory (CSL). All rights reserved.
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.
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.
79 * CSL requests users of this software to return to csl-dist@cs.utah.edu any
80 * improvements that they make and grant CSL redistribution rights.
84 #include <mach/mach_types.h>
85 #include <mach/boolean.h>
86 #include <mach/policy.h>
87 #include <mach/thread_info.h>
88 #include <mach/thread_special_ports.h>
89 #include <mach/thread_status.h>
90 #include <mach/time_value.h>
91 #include <mach/vm_param.h>
93 #include <machine/thread.h>
94 #include <machine/pal_routines.h>
95 #include <machine/limits.h>
97 #include <kern/kern_types.h>
98 #include <kern/kalloc.h>
99 #include <kern/cpu_data.h>
100 #include <kern/counters.h>
101 #include <kern/extmod_statistics.h>
102 #include <kern/ipc_mig.h>
103 #include <kern/ipc_tt.h>
104 #include <kern/mach_param.h>
105 #include <kern/machine.h>
106 #include <kern/misc_protos.h>
107 #include <kern/processor.h>
108 #include <kern/queue.h>
109 #include <kern/sched.h>
110 #include <kern/sched_prim.h>
111 #include <kern/sync_lock.h>
112 #include <kern/syscall_subr.h>
113 #include <kern/task.h>
114 #include <kern/thread.h>
115 #include <kern/host.h>
116 #include <kern/zalloc.h>
117 #include <kern/assert.h>
118 #include <kern/exc_resource.h>
119 #include <kern/telemetry.h>
120 #include <corpses/task_corpse.h>
122 #include <kern/kpc.h>
125 #include <ipc/ipc_kmsg.h>
126 #include <ipc/ipc_port.h>
127 #include <bank/bank_types.h>
129 #include <vm/vm_kern.h>
130 #include <vm/vm_pageout.h>
132 #include <sys/kdebug.h>
133 #include <sys/bsdtask_info.h>
134 #include <mach/sdt.h>
137 * Exported interfaces
139 #include <mach/task_server.h>
140 #include <mach/thread_act_server.h>
141 #include <mach/mach_host_server.h>
142 #include <mach/host_priv_server.h>
143 #include <mach/mach_voucher_server.h>
145 static struct zone
*thread_zone
;
146 static lck_grp_attr_t thread_lck_grp_attr
;
147 lck_attr_t thread_lck_attr
;
148 lck_grp_t thread_lck_grp
;
150 struct zone
*thread_qos_override_zone
;
152 decl_simple_lock_data(static,thread_stack_lock
)
153 static queue_head_t thread_stack_queue
;
155 decl_simple_lock_data(static,thread_terminate_lock
)
156 static queue_head_t thread_terminate_queue
;
158 static queue_head_t crashed_threads_queue
;
160 static struct thread thread_template
, init_thread
;
162 static void sched_call_null(
167 extern void proc_exit(void *);
168 extern uint64_t get_dispatchqueue_offset_from_proc(void *);
169 extern int proc_selfpid(void);
170 extern char * proc_name_address(void *p
);
171 #endif /* MACH_BSD */
173 extern int disable_exc_resource
;
174 extern int audio_active
;
175 extern int debug_task
;
176 int thread_max
= CONFIG_THREAD_MAX
; /* Max number of threads */
177 int task_threadmax
= CONFIG_THREAD_MAX
;
179 static uint64_t thread_unique_id
= 100;
181 struct _thread_ledger_indices thread_ledgers
= { -1 };
182 static ledger_template_t thread_ledger_template
= NULL
;
183 void init_thread_ledgers(void);
184 int task_disable_cpumon(task_t task
);
187 void jetsam_on_ledger_cpulimit_exceeded(void);
191 * Level (in terms of percentage of the limit) at which the CPU usage monitor triggers telemetry.
193 * (ie when any thread's CPU consumption exceeds 70% of the limit, start taking user
194 * stacktraces, aka micro-stackshots)
196 #define CPUMON_USTACKSHOTS_TRIGGER_DEFAULT_PCT 70
198 int cpumon_ustackshots_trigger_pct
; /* Percentage. Level at which we start gathering telemetry. */
199 void __attribute__((noinline
)) THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU__SENDING_EXC_RESOURCE(void);
202 * The smallest interval over which we support limiting CPU consumption is 1ms
204 #define MINIMUM_CPULIMIT_INTERVAL_MS 1
207 thread_bootstrap(void)
210 * Fill in a template thread for fast initialization.
213 thread_template
.runq
= PROCESSOR_NULL
;
215 thread_template
.ref_count
= 2;
217 thread_template
.reason
= AST_NONE
;
218 thread_template
.at_safe_point
= FALSE
;
219 thread_template
.wait_event
= NO_EVENT64
;
220 thread_template
.waitq
= NULL
;
221 thread_template
.wait_result
= THREAD_WAITING
;
222 thread_template
.options
= THREAD_ABORTSAFE
;
223 thread_template
.state
= TH_WAIT
| TH_UNINT
;
224 thread_template
.wake_active
= FALSE
;
225 thread_template
.continuation
= THREAD_CONTINUE_NULL
;
226 thread_template
.parameter
= NULL
;
228 thread_template
.importance
= 0;
229 thread_template
.sched_mode
= TH_MODE_NONE
;
230 thread_template
.sched_flags
= 0;
231 thread_template
.saved_mode
= TH_MODE_NONE
;
232 thread_template
.safe_release
= 0;
234 thread_template
.sfi_class
= SFI_CLASS_UNSPECIFIED
;
235 thread_template
.sfi_wait_class
= SFI_CLASS_UNSPECIFIED
;
237 thread_template
.active
= 0;
238 thread_template
.started
= 0;
239 thread_template
.static_param
= 0;
240 thread_template
.policy_reset
= 0;
242 thread_template
.base_pri
= BASEPRI_DEFAULT
;
243 thread_template
.sched_pri
= 0;
244 thread_template
.max_priority
= 0;
245 thread_template
.task_priority
= 0;
246 thread_template
.promotions
= 0;
247 thread_template
.pending_promoter_index
= 0;
248 thread_template
.pending_promoter
[0] = NULL
;
249 thread_template
.pending_promoter
[1] = NULL
;
250 thread_template
.rwlock_count
= 0;
253 thread_template
.SHARE_COUNT
= 0;
254 thread_template
.BG_COUNT
= 0;
255 #endif /* MACH_ASSERT */
257 thread_template
.realtime
.deadline
= UINT64_MAX
;
259 thread_template
.quantum_remaining
= 0;
260 thread_template
.last_run_time
= 0;
261 thread_template
.last_made_runnable_time
= 0;
263 thread_template
.computation_metered
= 0;
264 thread_template
.computation_epoch
= 0;
266 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
267 thread_template
.sched_stamp
= 0;
268 thread_template
.pri_shift
= INT8_MAX
;
269 thread_template
.sched_usage
= 0;
270 thread_template
.cpu_usage
= thread_template
.cpu_delta
= 0;
272 thread_template
.c_switch
= thread_template
.p_switch
= thread_template
.ps_switch
= 0;
274 thread_template
.bound_processor
= PROCESSOR_NULL
;
275 thread_template
.last_processor
= PROCESSOR_NULL
;
277 thread_template
.sched_call
= sched_call_null
;
279 timer_init(&thread_template
.user_timer
);
280 timer_init(&thread_template
.system_timer
);
281 thread_template
.user_timer_save
= 0;
282 thread_template
.system_timer_save
= 0;
283 thread_template
.vtimer_user_save
= 0;
284 thread_template
.vtimer_prof_save
= 0;
285 thread_template
.vtimer_rlim_save
= 0;
288 thread_template
.wait_sfi_begin_time
= 0;
291 thread_template
.wait_timer_is_set
= FALSE
;
292 thread_template
.wait_timer_active
= 0;
294 thread_template
.depress_timer_active
= 0;
296 thread_template
.recover
= (vm_offset_t
)NULL
;
298 thread_template
.map
= VM_MAP_NULL
;
301 thread_template
.t_dtrace_predcache
= 0;
302 thread_template
.t_dtrace_vtime
= 0;
303 thread_template
.t_dtrace_tracing
= 0;
304 #endif /* CONFIG_DTRACE */
307 thread_template
.kpc_buf
= NULL
;
311 thread_template
.hv_thread_target
= NULL
;
312 #endif /* HYPERVISOR */
314 thread_template
.t_chud
= 0;
316 #if (DEVELOPMENT || DEBUG)
317 thread_template
.t_page_creation_throttled_hard
= 0;
318 thread_template
.t_page_creation_throttled_soft
= 0;
319 #endif /* DEVELOPMENT || DEBUG */
320 thread_template
.t_page_creation_throttled
= 0;
321 thread_template
.t_page_creation_count
= 0;
322 thread_template
.t_page_creation_time
= 0;
324 thread_template
.affinity_set
= NULL
;
326 thread_template
.syscalls_unix
= 0;
327 thread_template
.syscalls_mach
= 0;
329 thread_template
.t_ledger
= LEDGER_NULL
;
330 thread_template
.t_threadledger
= LEDGER_NULL
;
332 thread_template
.t_bankledger
= LEDGER_NULL
;
333 thread_template
.t_deduct_bank_ledger_time
= 0;
336 thread_template
.requested_policy
= default_task_requested_policy
;
337 thread_template
.effective_policy
= default_task_effective_policy
;
338 thread_template
.pended_policy
= default_task_pended_policy
;
340 bzero(&thread_template
.overrides
, sizeof(thread_template
.overrides
));
342 thread_template
.iotier_override
= THROTTLE_LEVEL_NONE
;
343 thread_template
.thread_io_stats
= NULL
;
344 thread_template
.thread_callout_interrupt_wakeups
= thread_template
.thread_callout_platform_idle_wakeups
= 0;
346 thread_template
.thread_timer_wakeups_bin_1
= thread_template
.thread_timer_wakeups_bin_2
= 0;
347 thread_template
.callout_woken_from_icontext
= thread_template
.callout_woken_from_platform_idle
= 0;
349 thread_template
.thread_tag
= 0;
351 thread_template
.ith_voucher_name
= MACH_PORT_NULL
;
352 thread_template
.ith_voucher
= IPC_VOUCHER_NULL
;
354 thread_template
.work_interval_id
= 0;
356 init_thread
= thread_template
;
357 machine_set_current_thread(&init_thread
);
360 extern boolean_t allow_qos_policy_set
;
366 sizeof(struct thread
),
367 thread_max
* sizeof(struct thread
),
368 THREAD_CHUNK
* sizeof(struct thread
),
371 thread_qos_override_zone
= zinit(
372 sizeof(struct thread_qos_override
),
373 4 * thread_max
* sizeof(struct thread_qos_override
),
375 "thread qos override");
376 zone_change(thread_qos_override_zone
, Z_EXPAND
, TRUE
);
377 zone_change(thread_qos_override_zone
, Z_COLLECT
, TRUE
);
378 zone_change(thread_qos_override_zone
, Z_CALLERACCT
, FALSE
);
379 zone_change(thread_qos_override_zone
, Z_NOENCRYPT
, TRUE
);
381 lck_grp_attr_setdefault(&thread_lck_grp_attr
);
382 lck_grp_init(&thread_lck_grp
, "thread", &thread_lck_grp_attr
);
383 lck_attr_setdefault(&thread_lck_attr
);
388 * Initialize any machine-dependent
389 * per-thread structures necessary.
391 machine_thread_init();
393 if (!PE_parse_boot_argn("cpumon_ustackshots_trigger_pct", &cpumon_ustackshots_trigger_pct
,
394 sizeof (cpumon_ustackshots_trigger_pct
))) {
395 cpumon_ustackshots_trigger_pct
= CPUMON_USTACKSHOTS_TRIGGER_DEFAULT_PCT
;
398 PE_parse_boot_argn("-qos-policy-allow", &allow_qos_policy_set
, sizeof(allow_qos_policy_set
));
400 init_thread_ledgers();
404 thread_terminate_continue(void)
406 panic("thread_terminate_continue");
411 * thread_terminate_self:
414 thread_terminate_self(void)
416 thread_t thread
= current_thread();
421 pal_thread_terminate_self(thread
);
423 DTRACE_PROC(lwp__exit
);
425 thread_mtx_lock(thread
);
427 ipc_thread_disable(thread
);
429 thread_mtx_unlock(thread
);
434 assert_thread_sched_count(thread
);
437 * Cancel priority depression, wait for concurrent expirations
438 * on other processors.
440 if (thread
->sched_flags
& TH_SFLAG_DEPRESSED_MASK
) {
441 thread
->sched_flags
&= ~TH_SFLAG_DEPRESSED_MASK
;
443 /* If our priority was low because of a depressed yield, restore it in case we block below */
444 thread_recompute_sched_pri(thread
, FALSE
);
446 if (timer_call_cancel(&thread
->depress_timer
))
447 thread
->depress_timer_active
--;
450 while (thread
->depress_timer_active
> 0) {
451 thread_unlock(thread
);
460 thread_sched_call(thread
, NULL
);
462 thread_unlock(thread
);
466 thread_mtx_lock(thread
);
468 thread_policy_reset(thread
);
470 thread_mtx_unlock(thread
);
473 uthread_cleanup(task
, thread
->uthread
, task
->bsd_info
, thread
->inspection
== 1 ? TRUE
: FALSE
);
474 threadcnt
= hw_atomic_sub(&task
->active_thread_count
, 1);
477 * If we are the last thread to terminate and the task is
478 * associated with a BSD process, perform BSD process exit.
480 if (threadcnt
== 0 && task
->bsd_info
!= NULL
) {
481 proc_exit(task
->bsd_info
);
483 * if there is crash info in task
484 * then do the deliver action since this is
485 * last thread for this task.
487 if (task
->corpse_info
) {
488 task_deliver_crash_notification(task
);
491 uthread_cred_free(thread
->uthread
);
497 * Cancel wait timer, and wait for
498 * concurrent expirations.
500 if (thread
->wait_timer_is_set
) {
501 thread
->wait_timer_is_set
= FALSE
;
503 if (timer_call_cancel(&thread
->wait_timer
))
504 thread
->wait_timer_active
--;
507 while (thread
->wait_timer_active
> 0) {
508 thread_unlock(thread
);
518 * If there is a reserved stack, release it.
520 if (thread
->reserved_stack
!= 0) {
521 stack_free_reserved(thread
);
522 thread
->reserved_stack
= 0;
526 * Mark thread as terminating, and block.
528 thread
->state
|= TH_TERMINATE
;
529 thread_mark_wait_locked(thread
, THREAD_UNINT
);
530 assert((thread
->sched_flags
& TH_SFLAG_PROMOTED
) == 0);
531 assert(thread
->promotions
== 0);
532 assert(!(thread
->sched_flags
& TH_SFLAG_WAITQ_PROMOTED
));
533 assert(thread
->rwlock_count
== 0);
534 thread_unlock(thread
);
537 thread_block((thread_continue_t
)thread_terminate_continue
);
541 /* Drop a thread refcount that definitely isn't the last one. */
543 thread_deallocate_safe(thread_t thread
)
545 if (__improbable(hw_atomic_sub(&(thread
)->ref_count
, 1) == 0))
546 panic("bad thread refcount!");
555 if (thread
== THREAD_NULL
)
558 if (__probable(hw_atomic_sub(&(thread
)->ref_count
, 1) > 0))
561 if(!(thread
->state
& TH_TERMINATE2
))
562 panic("thread_deallocate: thread not properly terminated\n");
564 assert(thread
->runq
== PROCESSOR_NULL
);
567 kpc_thread_destroy(thread
);
570 ipc_thread_terminate(thread
);
572 proc_thread_qos_deallocate(thread
);
578 void *ut
= thread
->uthread
;
580 thread
->uthread
= NULL
;
581 uthread_zone_free(ut
);
583 #endif /* MACH_BSD */
585 if (thread
->t_ledger
)
586 ledger_dereference(thread
->t_ledger
);
587 if (thread
->t_threadledger
)
588 ledger_dereference(thread
->t_threadledger
);
590 if (IPC_VOUCHER_NULL
!= thread
->ith_voucher
)
591 ipc_voucher_release(thread
->ith_voucher
);
593 if (thread
->thread_io_stats
)
594 kfree(thread
->thread_io_stats
, sizeof(struct io_stat_info
));
596 if (thread
->kernel_stack
!= 0)
599 lck_mtx_destroy(&thread
->mutex
, &thread_lck_grp
);
600 machine_thread_destroy(thread
);
602 task_deallocate(task
);
604 zfree(thread_zone
, thread
);
608 * thread_terminate_daemon:
610 * Perform final clean up for terminating threads.
613 thread_terminate_daemon(void)
615 thread_t self
, thread
;
618 self
= current_thread();
619 self
->options
|= TH_OPT_SYSTEM_CRITICAL
;
622 simple_lock(&thread_terminate_lock
);
624 while ((thread
= (thread_t
)dequeue_head(&thread_terminate_queue
)) != THREAD_NULL
) {
627 * if marked for crash reporting, skip reaping.
628 * The corpse delivery thread will clear bit and enqueue
629 * for reaping when done
631 if (thread
->inspection
){
632 enqueue_tail(&crashed_threads_queue
, (queue_entry_t
)thread
);
636 simple_unlock(&thread_terminate_lock
);
639 assert(thread
->SHARE_COUNT
== 0);
640 assert(thread
->BG_COUNT
== 0);
645 task
->total_user_time
+= timer_grab(&thread
->user_timer
);
646 if (thread
->precise_user_kernel_time
) {
647 task
->total_system_time
+= timer_grab(&thread
->system_timer
);
649 task
->total_user_time
+= timer_grab(&thread
->system_timer
);
652 task
->c_switch
+= thread
->c_switch
;
653 task
->p_switch
+= thread
->p_switch
;
654 task
->ps_switch
+= thread
->ps_switch
;
656 task
->syscalls_unix
+= thread
->syscalls_unix
;
657 task
->syscalls_mach
+= thread
->syscalls_mach
;
659 task
->task_timer_wakeups_bin_1
+= thread
->thread_timer_wakeups_bin_1
;
660 task
->task_timer_wakeups_bin_2
+= thread
->thread_timer_wakeups_bin_2
;
661 task
->task_gpu_ns
+= ml_gpu_stat(thread
);
663 thread_update_qos_cpu_time(thread
, FALSE
);
664 queue_remove(&task
->threads
, thread
, thread_t
, task_threads
);
665 task
->thread_count
--;
668 * If the task is being halted, and there is only one thread
669 * left in the task after this one, then wakeup that thread.
671 if (task
->thread_count
== 1 && task
->halting
)
672 thread_wakeup((event_t
)&task
->halting
);
676 lck_mtx_lock(&tasks_threads_lock
);
677 queue_remove(&threads
, thread
, thread_t
, threads
);
679 lck_mtx_unlock(&tasks_threads_lock
);
681 thread_deallocate(thread
);
684 simple_lock(&thread_terminate_lock
);
687 assert_wait((event_t
)&thread_terminate_queue
, THREAD_UNINT
);
688 simple_unlock(&thread_terminate_lock
);
691 self
->options
&= ~TH_OPT_SYSTEM_CRITICAL
;
692 thread_block((thread_continue_t
)thread_terminate_daemon
);
697 * thread_terminate_enqueue:
699 * Enqueue a terminating thread for final disposition.
701 * Called at splsched.
704 thread_terminate_enqueue(
707 KERNEL_DEBUG_CONSTANT(TRACE_DATA_THREAD_TERMINATE
| DBG_FUNC_NONE
, thread
->thread_id
, 0, 0, 0, 0);
709 simple_lock(&thread_terminate_lock
);
710 enqueue_tail(&thread_terminate_queue
, (queue_entry_t
)thread
);
711 simple_unlock(&thread_terminate_lock
);
713 thread_wakeup((event_t
)&thread_terminate_queue
);
717 * thread_terminate_crashed_threads:
718 * walk the list of crashed therds and put back set of threads
719 * who are no longer being inspected.
722 thread_terminate_crashed_threads()
724 thread_t th_iter
, th_remove
;
725 boolean_t should_wake_terminate_queue
= FALSE
;
727 simple_lock(&thread_terminate_lock
);
729 * loop through the crashed threads queue
730 * to put any threads that are not being inspected anymore
732 th_iter
= (thread_t
)queue_first(&crashed_threads_queue
);
733 while (!queue_end(&crashed_threads_queue
, (queue_entry_t
)th_iter
)) {
735 th_iter
= (thread_t
)queue_next(&th_iter
->links
);
737 /* make sure current_thread is never in crashed queue */
738 assert(th_remove
!= current_thread());
739 if (th_remove
->inspection
!= TRUE
){
740 remque((queue_entry_t
)th_remove
);
741 enqueue_tail(&thread_terminate_queue
, (queue_entry_t
)th_remove
);
742 should_wake_terminate_queue
= TRUE
;
746 simple_unlock(&thread_terminate_lock
);
747 if (should_wake_terminate_queue
== TRUE
) {
748 thread_wakeup((event_t
)&thread_terminate_queue
);
753 * thread_stack_daemon:
755 * Perform stack allocation as required due to
759 thread_stack_daemon(void)
765 simple_lock(&thread_stack_lock
);
767 while ((thread
= (thread_t
)dequeue_head(&thread_stack_queue
)) != THREAD_NULL
) {
768 simple_unlock(&thread_stack_lock
);
771 /* allocate stack with interrupts enabled so that we can call into VM */
774 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
,MACH_STACK_WAIT
) | DBG_FUNC_END
, thread_tid(thread
), 0, 0, 0, 0);
778 thread_setrun(thread
, SCHED_PREEMPT
| SCHED_TAILQ
);
779 thread_unlock(thread
);
781 simple_lock(&thread_stack_lock
);
784 assert_wait((event_t
)&thread_stack_queue
, THREAD_UNINT
);
785 simple_unlock(&thread_stack_lock
);
788 thread_block((thread_continue_t
)thread_stack_daemon
);
793 * thread_stack_enqueue:
795 * Enqueue a thread for stack allocation.
797 * Called at splsched.
800 thread_stack_enqueue(
803 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
,MACH_STACK_WAIT
) | DBG_FUNC_START
, thread_tid(thread
), 0, 0, 0, 0);
805 simple_lock(&thread_stack_lock
);
806 enqueue_tail(&thread_stack_queue
, (queue_entry_t
)thread
);
807 simple_unlock(&thread_stack_lock
);
809 thread_wakeup((event_t
)&thread_stack_queue
);
813 thread_daemon_init(void)
815 kern_return_t result
;
816 thread_t thread
= NULL
;
818 simple_lock_init(&thread_terminate_lock
, 0);
819 queue_init(&thread_terminate_queue
);
820 queue_init(&crashed_threads_queue
);
822 result
= kernel_thread_start_priority((thread_continue_t
)thread_terminate_daemon
, NULL
, MINPRI_KERNEL
, &thread
);
823 if (result
!= KERN_SUCCESS
)
824 panic("thread_daemon_init: thread_terminate_daemon");
826 thread_deallocate(thread
);
828 simple_lock_init(&thread_stack_lock
, 0);
829 queue_init(&thread_stack_queue
);
831 result
= kernel_thread_start_priority((thread_continue_t
)thread_stack_daemon
, NULL
, BASEPRI_PREEMPT
, &thread
);
832 if (result
!= KERN_SUCCESS
)
833 panic("thread_daemon_init: thread_stack_daemon");
835 thread_deallocate(thread
);
838 #define TH_OPTION_NONE 0x00
839 #define TH_OPTION_NOCRED 0x01
840 #define TH_OPTION_NOSUSP 0x02
842 * Create a new thread.
843 * Doesn't start the thread running.
845 * Task and tasks_threads_lock are returned locked on success.
848 thread_create_internal(
851 thread_continue_t continuation
,
853 thread_t
*out_thread
)
856 static thread_t first_thread
;
859 * Allocate a thread and initialize static fields
861 if (first_thread
== THREAD_NULL
)
862 new_thread
= first_thread
= current_thread();
864 new_thread
= (thread_t
)zalloc(thread_zone
);
865 if (new_thread
== THREAD_NULL
)
866 return (KERN_RESOURCE_SHORTAGE
);
868 if (new_thread
!= first_thread
)
869 *new_thread
= thread_template
;
872 new_thread
->uthread
= uthread_alloc(parent_task
, new_thread
, (options
& TH_OPTION_NOCRED
) != 0);
873 if (new_thread
->uthread
== NULL
) {
874 zfree(thread_zone
, new_thread
);
875 return (KERN_RESOURCE_SHORTAGE
);
877 #endif /* MACH_BSD */
879 if (machine_thread_create(new_thread
, parent_task
) != KERN_SUCCESS
) {
881 void *ut
= new_thread
->uthread
;
883 new_thread
->uthread
= NULL
;
884 /* cred free may not be necessary */
885 uthread_cleanup(parent_task
, ut
, parent_task
->bsd_info
, FALSE
);
886 uthread_cred_free(ut
);
887 uthread_zone_free(ut
);
888 #endif /* MACH_BSD */
890 zfree(thread_zone
, new_thread
);
891 return (KERN_FAILURE
);
894 new_thread
->task
= parent_task
;
896 thread_lock_init(new_thread
);
897 wake_lock_init(new_thread
);
899 lck_mtx_init(&new_thread
->mutex
, &thread_lck_grp
, &thread_lck_attr
);
901 ipc_thread_init(new_thread
);
903 new_thread
->continuation
= continuation
;
905 /* Allocate I/O Statistics structure */
906 new_thread
->thread_io_stats
= (io_stat_info_t
)kalloc(sizeof(struct io_stat_info
));
907 assert(new_thread
->thread_io_stats
!= NULL
);
908 bzero(new_thread
->thread_io_stats
, sizeof(struct io_stat_info
));
911 /* Clear out the I/O Scheduling info for AppleFSCompression */
912 new_thread
->decmp_upl
= NULL
;
913 #endif /* CONFIG_IOSCHED */
915 lck_mtx_lock(&tasks_threads_lock
);
916 task_lock(parent_task
);
918 if ( !parent_task
->active
|| parent_task
->halting
||
919 ((options
& TH_OPTION_NOSUSP
) != 0 &&
920 parent_task
->suspend_count
> 0) ||
921 (parent_task
->thread_count
>= task_threadmax
&&
922 parent_task
!= kernel_task
) ) {
923 task_unlock(parent_task
);
924 lck_mtx_unlock(&tasks_threads_lock
);
928 void *ut
= new_thread
->uthread
;
930 new_thread
->uthread
= NULL
;
931 uthread_cleanup(parent_task
, ut
, parent_task
->bsd_info
, FALSE
);
932 /* cred free may not be necessary */
933 uthread_cred_free(ut
);
934 uthread_zone_free(ut
);
936 #endif /* MACH_BSD */
937 ipc_thread_disable(new_thread
);
938 ipc_thread_terminate(new_thread
);
939 kfree(new_thread
->thread_io_stats
, sizeof(struct io_stat_info
));
940 lck_mtx_destroy(&new_thread
->mutex
, &thread_lck_grp
);
941 machine_thread_destroy(new_thread
);
942 zfree(thread_zone
, new_thread
);
943 return (KERN_FAILURE
);
946 /* New threads inherit any default state on the task */
947 machine_thread_inherit_taskwide(new_thread
, parent_task
);
949 task_reference_internal(parent_task
);
951 if (new_thread
->task
->rusage_cpu_flags
& TASK_RUSECPU_FLAGS_PERTHR_LIMIT
) {
953 * This task has a per-thread CPU limit; make sure this new thread
954 * gets its limit set too, before it gets out of the kernel.
956 set_astledger(new_thread
);
959 /* Instantiate a thread ledger. Do not fail thread creation if ledger creation fails. */
960 if ((new_thread
->t_threadledger
= ledger_instantiate(thread_ledger_template
,
961 LEDGER_CREATE_INACTIVE_ENTRIES
)) != LEDGER_NULL
) {
963 ledger_entry_setactive(new_thread
->t_threadledger
, thread_ledgers
.cpu_time
);
966 new_thread
->cpu_time_last_qos
= 0;
968 new_thread
->t_bankledger
= LEDGER_NULL
;
969 new_thread
->t_deduct_bank_ledger_time
= 0;
972 new_thread
->t_ledger
= new_thread
->task
->ledger
;
973 if (new_thread
->t_ledger
)
974 ledger_reference(new_thread
->t_ledger
);
976 #if defined(CONFIG_SCHED_MULTIQ)
977 /* Cache the task's sched_group */
978 new_thread
->sched_group
= parent_task
->sched_group
;
979 #endif /* defined(CONFIG_SCHED_MULTIQ) */
981 /* Cache the task's map */
982 new_thread
->map
= parent_task
->map
;
984 timer_call_setup(&new_thread
->wait_timer
, thread_timer_expire
, new_thread
);
985 timer_call_setup(&new_thread
->depress_timer
, thread_depress_expire
, new_thread
);
988 kpc_thread_create(new_thread
);
991 /* Only need to update policies pushed from task to thread */
992 new_thread
->requested_policy
.bg_iotier
= parent_task
->effective_policy
.bg_iotier
;
993 new_thread
->requested_policy
.terminated
= parent_task
->effective_policy
.terminated
;
995 /* Set the thread's scheduling parameters */
996 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
997 new_thread
->sched_stamp
= sched_tick
;
998 new_thread
->pri_shift
= sched_pri_shift
;
999 #endif /* defined(CONFIG_SCHED_TIMESHARE_CORE) */
1001 new_thread
->sched_mode
= SCHED(initial_thread_sched_mode
)(parent_task
);
1002 new_thread
->sched_flags
= 0;
1003 new_thread
->max_priority
= parent_task
->max_priority
;
1004 new_thread
->task_priority
= parent_task
->priority
;
1006 int new_priority
= (priority
< 0) ? parent_task
->priority
: priority
;
1007 new_priority
= (priority
< 0)? parent_task
->priority
: priority
;
1008 if (new_priority
> new_thread
->max_priority
)
1009 new_priority
= new_thread
->max_priority
;
1011 new_thread
->importance
= new_priority
- new_thread
->task_priority
;
1012 new_thread
->saved_importance
= new_thread
->importance
;
1014 sched_set_thread_base_priority(new_thread
, new_priority
);
1017 thread_policy_create(new_thread
);
1019 /* Chain the thread onto the task's list */
1020 queue_enter(&parent_task
->threads
, new_thread
, thread_t
, task_threads
);
1021 parent_task
->thread_count
++;
1023 /* So terminating threads don't need to take the task lock to decrement */
1024 hw_atomic_add(&parent_task
->active_thread_count
, 1);
1026 /* Protected by the tasks_threads_lock */
1027 new_thread
->thread_id
= ++thread_unique_id
;
1029 queue_enter(&threads
, new_thread
, thread_t
, threads
);
1032 new_thread
->active
= TRUE
;
1033 new_thread
->inspection
= FALSE
;
1034 *out_thread
= new_thread
;
1037 long dbg_arg1
, dbg_arg2
, dbg_arg3
, dbg_arg4
;
1039 kdbg_trace_data(parent_task
->bsd_info
, &dbg_arg2
);
1041 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
1042 TRACEDBG_CODE(DBG_TRACE_DATA
, 1) | DBG_FUNC_NONE
,
1043 (vm_address_t
)(uintptr_t)thread_tid(new_thread
), dbg_arg2
, 0, 0, 0);
1045 kdbg_trace_string(parent_task
->bsd_info
,
1046 &dbg_arg1
, &dbg_arg2
, &dbg_arg3
, &dbg_arg4
);
1048 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
1049 TRACEDBG_CODE(DBG_TRACE_STRING
, 1) | DBG_FUNC_NONE
,
1050 dbg_arg1
, dbg_arg2
, dbg_arg3
, dbg_arg4
, 0);
1053 DTRACE_PROC1(lwp__create
, thread_t
, *out_thread
);
1055 return (KERN_SUCCESS
);
1058 static kern_return_t
1059 thread_create_internal2(
1061 thread_t
*new_thread
,
1062 boolean_t from_user
,
1063 thread_continue_t continuation
)
1065 kern_return_t result
;
1068 if (task
== TASK_NULL
|| task
== kernel_task
)
1069 return (KERN_INVALID_ARGUMENT
);
1071 result
= thread_create_internal(task
, -1, continuation
, TH_OPTION_NONE
, &thread
);
1072 if (result
!= KERN_SUCCESS
)
1075 thread
->user_stop_count
= 1;
1076 thread_hold(thread
);
1077 if (task
->suspend_count
> 0)
1078 thread_hold(thread
);
1081 extmod_statistics_incr_thread_create(task
);
1084 lck_mtx_unlock(&tasks_threads_lock
);
1086 *new_thread
= thread
;
1088 return (KERN_SUCCESS
);
1091 /* No prototype, since task_server.h has the _from_user version if KERNEL_SERVER */
1095 thread_t
*new_thread
);
1100 thread_t
*new_thread
)
1102 return thread_create_internal2(task
, new_thread
, FALSE
, (thread_continue_t
)thread_bootstrap_return
);
1106 thread_create_from_user(
1108 thread_t
*new_thread
)
1110 return thread_create_internal2(task
, new_thread
, TRUE
, (thread_continue_t
)thread_bootstrap_return
);
1114 thread_create_with_continuation(
1116 thread_t
*new_thread
,
1117 thread_continue_t continuation
)
1119 return thread_create_internal2(task
, new_thread
, FALSE
, continuation
);
1122 static kern_return_t
1123 thread_create_running_internal2(
1124 register task_t task
,
1126 thread_state_t new_state
,
1127 mach_msg_type_number_t new_state_count
,
1128 thread_t
*new_thread
,
1129 boolean_t from_user
)
1131 register kern_return_t result
;
1134 if (task
== TASK_NULL
|| task
== kernel_task
)
1135 return (KERN_INVALID_ARGUMENT
);
1137 result
= thread_create_internal(task
, -1, (thread_continue_t
)thread_bootstrap_return
, TH_OPTION_NONE
, &thread
);
1138 if (result
!= KERN_SUCCESS
)
1141 result
= machine_thread_set_state(thread
, flavor
, new_state
, new_state_count
);
1142 if (result
!= KERN_SUCCESS
) {
1144 lck_mtx_unlock(&tasks_threads_lock
);
1146 thread_terminate(thread
);
1147 thread_deallocate(thread
);
1151 thread_mtx_lock(thread
);
1152 thread_start_internal(thread
);
1153 thread_mtx_unlock(thread
);
1156 extmod_statistics_incr_thread_create(task
);
1159 lck_mtx_unlock(&tasks_threads_lock
);
1161 *new_thread
= thread
;
1166 /* Prototype, see justification above */
1168 thread_create_running(
1169 register task_t task
,
1171 thread_state_t new_state
,
1172 mach_msg_type_number_t new_state_count
,
1173 thread_t
*new_thread
);
1176 thread_create_running(
1177 register task_t task
,
1179 thread_state_t new_state
,
1180 mach_msg_type_number_t new_state_count
,
1181 thread_t
*new_thread
)
1183 return thread_create_running_internal2(
1184 task
, flavor
, new_state
, new_state_count
,
1189 thread_create_running_from_user(
1190 register task_t task
,
1192 thread_state_t new_state
,
1193 mach_msg_type_number_t new_state_count
,
1194 thread_t
*new_thread
)
1196 return thread_create_running_internal2(
1197 task
, flavor
, new_state
, new_state_count
,
1202 thread_create_workq(
1204 thread_continue_t thread_return
,
1205 thread_t
*new_thread
)
1207 kern_return_t result
;
1210 if (task
== TASK_NULL
|| task
== kernel_task
)
1211 return (KERN_INVALID_ARGUMENT
);
1213 result
= thread_create_internal(task
, -1, thread_return
, TH_OPTION_NOCRED
| TH_OPTION_NOSUSP
, &thread
);
1214 if (result
!= KERN_SUCCESS
)
1217 thread
->user_stop_count
= 1;
1218 thread_hold(thread
);
1219 if (task
->suspend_count
> 0)
1220 thread_hold(thread
);
1223 lck_mtx_unlock(&tasks_threads_lock
);
1225 *new_thread
= thread
;
1227 return (KERN_SUCCESS
);
1231 * kernel_thread_create:
1233 * Create a thread in the kernel task
1234 * to execute in kernel context.
1237 kernel_thread_create(
1238 thread_continue_t continuation
,
1241 thread_t
*new_thread
)
1243 kern_return_t result
;
1245 task_t task
= kernel_task
;
1247 result
= thread_create_internal(task
, priority
, continuation
, TH_OPTION_NONE
, &thread
);
1248 if (result
!= KERN_SUCCESS
)
1252 lck_mtx_unlock(&tasks_threads_lock
);
1254 stack_alloc(thread
);
1255 assert(thread
->kernel_stack
!= 0);
1256 thread
->reserved_stack
= thread
->kernel_stack
;
1258 thread
->parameter
= parameter
;
1261 kprintf("kernel_thread_create: thread = %p continuation = %p\n", thread
, continuation
);
1262 *new_thread
= thread
;
1268 kernel_thread_start_priority(
1269 thread_continue_t continuation
,
1272 thread_t
*new_thread
)
1274 kern_return_t result
;
1277 result
= kernel_thread_create(continuation
, parameter
, priority
, &thread
);
1278 if (result
!= KERN_SUCCESS
)
1281 *new_thread
= thread
;
1283 thread_mtx_lock(thread
);
1284 thread_start_internal(thread
);
1285 thread_mtx_unlock(thread
);
1291 kernel_thread_start(
1292 thread_continue_t continuation
,
1294 thread_t
*new_thread
)
1296 return kernel_thread_start_priority(continuation
, parameter
, -1, new_thread
);
1299 /* Separated into helper function so it can be used by THREAD_BASIC_INFO and THREAD_EXTENDED_INFO */
1300 /* it is assumed that the thread is locked by the caller */
1302 retrieve_thread_basic_info(thread_t thread
, thread_basic_info_t basic_info
)
1308 thread_read_times(thread
, &basic_info
->user_time
,
1309 &basic_info
->system_time
);
1312 * Update lazy-evaluated scheduler info because someone wants it.
1314 if (SCHED(can_update_priority
)(thread
))
1315 SCHED(update_priority
)(thread
);
1317 basic_info
->sleep_time
= 0;
1320 * To calculate cpu_usage, first correct for timer rate,
1321 * then for 5/8 ageing. The correction factor [3/5] is
1324 basic_info
->cpu_usage
= 0;
1325 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
1326 if (sched_tick_interval
) {
1327 basic_info
->cpu_usage
= (integer_t
)(((uint64_t)thread
->cpu_usage
1328 * TH_USAGE_SCALE
) / sched_tick_interval
);
1329 basic_info
->cpu_usage
= (basic_info
->cpu_usage
* 3) / 5;
1333 if (basic_info
->cpu_usage
> TH_USAGE_SCALE
)
1334 basic_info
->cpu_usage
= TH_USAGE_SCALE
;
1336 basic_info
->policy
= ((thread
->sched_mode
== TH_MODE_TIMESHARE
)?
1337 POLICY_TIMESHARE
: POLICY_RR
);
1340 if (thread
->options
& TH_OPT_IDLE_THREAD
)
1341 flags
|= TH_FLAGS_IDLE
;
1343 if (thread
->options
& TH_OPT_GLOBAL_FORCED_IDLE
) {
1344 flags
|= TH_FLAGS_GLOBAL_FORCED_IDLE
;
1347 if (!thread
->kernel_stack
)
1348 flags
|= TH_FLAGS_SWAPPED
;
1351 if (thread
->state
& TH_TERMINATE
)
1352 state
= TH_STATE_HALTED
;
1354 if (thread
->state
& TH_RUN
)
1355 state
= TH_STATE_RUNNING
;
1357 if (thread
->state
& TH_UNINT
)
1358 state
= TH_STATE_UNINTERRUPTIBLE
;
1360 if (thread
->state
& TH_SUSP
)
1361 state
= TH_STATE_STOPPED
;
1363 if (thread
->state
& TH_WAIT
)
1364 state
= TH_STATE_WAITING
;
1366 basic_info
->run_state
= state
;
1367 basic_info
->flags
= flags
;
1369 basic_info
->suspend_count
= thread
->user_stop_count
;
1375 thread_info_internal(
1376 register thread_t thread
,
1377 thread_flavor_t flavor
,
1378 thread_info_t thread_info_out
, /* ptr to OUT array */
1379 mach_msg_type_number_t
*thread_info_count
) /*IN/OUT*/
1383 if (thread
== THREAD_NULL
)
1384 return (KERN_INVALID_ARGUMENT
);
1386 if (flavor
== THREAD_BASIC_INFO
) {
1388 if (*thread_info_count
< THREAD_BASIC_INFO_COUNT
)
1389 return (KERN_INVALID_ARGUMENT
);
1392 thread_lock(thread
);
1394 retrieve_thread_basic_info(thread
, (thread_basic_info_t
) thread_info_out
);
1396 thread_unlock(thread
);
1399 *thread_info_count
= THREAD_BASIC_INFO_COUNT
;
1401 return (KERN_SUCCESS
);
1404 if (flavor
== THREAD_IDENTIFIER_INFO
) {
1405 register thread_identifier_info_t identifier_info
;
1407 if (*thread_info_count
< THREAD_IDENTIFIER_INFO_COUNT
)
1408 return (KERN_INVALID_ARGUMENT
);
1410 identifier_info
= (thread_identifier_info_t
) thread_info_out
;
1413 thread_lock(thread
);
1415 identifier_info
->thread_id
= thread
->thread_id
;
1416 identifier_info
->thread_handle
= thread
->machine
.cthread_self
;
1417 identifier_info
->dispatch_qaddr
= thread_dispatchqaddr(thread
);
1419 thread_unlock(thread
);
1421 return KERN_SUCCESS
;
1424 if (flavor
== THREAD_SCHED_TIMESHARE_INFO
) {
1425 policy_timeshare_info_t ts_info
;
1427 if (*thread_info_count
< POLICY_TIMESHARE_INFO_COUNT
)
1428 return (KERN_INVALID_ARGUMENT
);
1430 ts_info
= (policy_timeshare_info_t
)thread_info_out
;
1433 thread_lock(thread
);
1435 if (thread
->sched_mode
!= TH_MODE_TIMESHARE
) {
1436 thread_unlock(thread
);
1438 return (KERN_INVALID_POLICY
);
1441 ts_info
->depressed
= (thread
->sched_flags
& TH_SFLAG_DEPRESSED_MASK
) != 0;
1442 if (ts_info
->depressed
) {
1443 ts_info
->base_priority
= DEPRESSPRI
;
1444 ts_info
->depress_priority
= thread
->base_pri
;
1447 ts_info
->base_priority
= thread
->base_pri
;
1448 ts_info
->depress_priority
= -1;
1451 ts_info
->cur_priority
= thread
->sched_pri
;
1452 ts_info
->max_priority
= thread
->max_priority
;
1454 thread_unlock(thread
);
1457 *thread_info_count
= POLICY_TIMESHARE_INFO_COUNT
;
1459 return (KERN_SUCCESS
);
1462 if (flavor
== THREAD_SCHED_FIFO_INFO
) {
1463 if (*thread_info_count
< POLICY_FIFO_INFO_COUNT
)
1464 return (KERN_INVALID_ARGUMENT
);
1466 return (KERN_INVALID_POLICY
);
1469 if (flavor
== THREAD_SCHED_RR_INFO
) {
1470 policy_rr_info_t rr_info
;
1471 uint32_t quantum_time
;
1472 uint64_t quantum_ns
;
1474 if (*thread_info_count
< POLICY_RR_INFO_COUNT
)
1475 return (KERN_INVALID_ARGUMENT
);
1477 rr_info
= (policy_rr_info_t
) thread_info_out
;
1480 thread_lock(thread
);
1482 if (thread
->sched_mode
== TH_MODE_TIMESHARE
) {
1483 thread_unlock(thread
);
1486 return (KERN_INVALID_POLICY
);
1489 rr_info
->depressed
= (thread
->sched_flags
& TH_SFLAG_DEPRESSED_MASK
) != 0;
1490 if (rr_info
->depressed
) {
1491 rr_info
->base_priority
= DEPRESSPRI
;
1492 rr_info
->depress_priority
= thread
->base_pri
;
1495 rr_info
->base_priority
= thread
->base_pri
;
1496 rr_info
->depress_priority
= -1;
1499 quantum_time
= SCHED(initial_quantum_size
)(THREAD_NULL
);
1500 absolutetime_to_nanoseconds(quantum_time
, &quantum_ns
);
1502 rr_info
->max_priority
= thread
->max_priority
;
1503 rr_info
->quantum
= (uint32_t)(quantum_ns
/ 1000 / 1000);
1505 thread_unlock(thread
);
1508 *thread_info_count
= POLICY_RR_INFO_COUNT
;
1510 return (KERN_SUCCESS
);
1513 if (flavor
== THREAD_EXTENDED_INFO
) {
1514 thread_basic_info_data_t basic_info
;
1515 thread_extended_info_t extended_info
= (thread_extended_info_t
) thread_info_out
;
1517 if (*thread_info_count
< THREAD_EXTENDED_INFO_COUNT
) {
1518 return (KERN_INVALID_ARGUMENT
);
1522 thread_lock(thread
);
1524 /* NOTE: This mimics fill_taskthreadinfo(), which is the function used by proc_pidinfo() for
1525 * the PROC_PIDTHREADINFO flavor (which can't be used on corpses)
1527 retrieve_thread_basic_info(thread
, &basic_info
);
1528 extended_info
->pth_user_time
= ((basic_info
.user_time
.seconds
* (integer_t
)NSEC_PER_SEC
) + (basic_info
.user_time
.microseconds
* (integer_t
)NSEC_PER_USEC
));
1529 extended_info
->pth_system_time
= ((basic_info
.system_time
.seconds
* (integer_t
)NSEC_PER_SEC
) + (basic_info
.system_time
.microseconds
* (integer_t
)NSEC_PER_USEC
));
1531 extended_info
->pth_cpu_usage
= basic_info
.cpu_usage
;
1532 extended_info
->pth_policy
= basic_info
.policy
;
1533 extended_info
->pth_run_state
= basic_info
.run_state
;
1534 extended_info
->pth_flags
= basic_info
.flags
;
1535 extended_info
->pth_sleep_time
= basic_info
.sleep_time
;
1536 extended_info
->pth_curpri
= thread
->sched_pri
;
1537 extended_info
->pth_priority
= thread
->base_pri
;
1538 extended_info
->pth_maxpriority
= thread
->max_priority
;
1540 bsd_getthreadname(thread
->uthread
,extended_info
->pth_name
);
1542 thread_unlock(thread
);
1545 *thread_info_count
= THREAD_EXTENDED_INFO_COUNT
;
1547 return (KERN_SUCCESS
);
1550 if (flavor
== THREAD_DEBUG_INFO_INTERNAL
) {
1551 #if DEVELOPMENT || DEBUG
1552 thread_debug_info_internal_t dbg_info
;
1553 if (*thread_info_count
< THREAD_DEBUG_INFO_INTERNAL_COUNT
)
1554 return (KERN_NOT_SUPPORTED
);
1556 if (thread_info_out
== NULL
)
1557 return (KERN_INVALID_ARGUMENT
);
1559 dbg_info
= (thread_debug_info_internal_t
) thread_info_out
;
1560 dbg_info
->page_creation_count
= thread
->t_page_creation_count
;
1562 *thread_info_count
= THREAD_DEBUG_INFO_INTERNAL_COUNT
;
1563 return (KERN_SUCCESS
);
1564 #endif /* DEVELOPMENT || DEBUG */
1565 return (KERN_NOT_SUPPORTED
);
1568 return (KERN_INVALID_ARGUMENT
);
1574 time_value_t
*user_time
,
1575 time_value_t
*system_time
)
1579 uint64_t tval_user
, tval_system
;
1581 tval_user
= timer_grab(&thread
->user_timer
);
1582 tval_system
= timer_grab(&thread
->system_timer
);
1584 if (thread
->precise_user_kernel_time
) {
1585 absolutetime_to_microtime(tval_user
, &secs
, &usecs
);
1586 user_time
->seconds
= (typeof(user_time
->seconds
))secs
;
1587 user_time
->microseconds
= usecs
;
1589 absolutetime_to_microtime(tval_system
, &secs
, &usecs
);
1590 system_time
->seconds
= (typeof(system_time
->seconds
))secs
;
1591 system_time
->microseconds
= usecs
;
1593 /* system_timer may represent either sys or user */
1594 tval_user
+= tval_system
;
1595 absolutetime_to_microtime(tval_user
, &secs
, &usecs
);
1596 user_time
->seconds
= (typeof(user_time
->seconds
))secs
;
1597 user_time
->microseconds
= usecs
;
1599 system_time
->seconds
= 0;
1600 system_time
->microseconds
= 0;
1604 uint64_t thread_get_runtime_self(void)
1606 boolean_t interrupt_state
;
1608 thread_t thread
= NULL
;
1609 processor_t processor
= NULL
;
1611 thread
= current_thread();
1613 /* Not interrupt safe, as the scheduler may otherwise update timer values underneath us */
1614 interrupt_state
= ml_set_interrupts_enabled(FALSE
);
1615 processor
= current_processor();
1616 timer_switch(PROCESSOR_DATA(processor
, thread_timer
), mach_absolute_time(), PROCESSOR_DATA(processor
, thread_timer
));
1617 runtime
= (timer_grab(&thread
->user_timer
) + timer_grab(&thread
->system_timer
));
1618 ml_set_interrupts_enabled(interrupt_state
);
1625 __unused thread_t thread
,
1626 __unused processor_set_t new_pset
)
1628 return (KERN_FAILURE
);
1632 * thread_assign_default:
1634 * Special version of thread_assign for assigning threads to default
1638 thread_assign_default(
1641 return (thread_assign(thread
, &pset0
));
1645 * thread_get_assignment
1647 * Return current assignment for this thread.
1650 thread_get_assignment(
1652 processor_set_t
*pset
)
1655 return (KERN_INVALID_ARGUMENT
);
1659 return (KERN_SUCCESS
);
1663 * thread_wire_internal:
1665 * Specify that the target thread must always be able
1666 * to run and to allocate memory.
1669 thread_wire_internal(
1670 host_priv_t host_priv
,
1673 boolean_t
*prev_state
)
1675 if (host_priv
== NULL
|| thread
!= current_thread())
1676 return (KERN_INVALID_ARGUMENT
);
1678 assert(host_priv
== &realhost
);
1681 *prev_state
= (thread
->options
& TH_OPT_VMPRIV
) != 0;
1684 if (!(thread
->options
& TH_OPT_VMPRIV
))
1685 vm_page_free_reserve(1); /* XXX */
1686 thread
->options
|= TH_OPT_VMPRIV
;
1689 if (thread
->options
& TH_OPT_VMPRIV
)
1690 vm_page_free_reserve(-1); /* XXX */
1691 thread
->options
&= ~TH_OPT_VMPRIV
;
1694 return (KERN_SUCCESS
);
1701 * User-api wrapper for thread_wire_internal()
1705 host_priv_t host_priv
,
1709 return (thread_wire_internal(host_priv
, thread
, wired
, NULL
));
1714 set_vm_privilege(boolean_t privileged
)
1716 boolean_t was_vmpriv
;
1718 if (current_thread()->options
& TH_OPT_VMPRIV
)
1723 if (privileged
!= FALSE
)
1724 current_thread()->options
|= TH_OPT_VMPRIV
;
1726 current_thread()->options
&= ~TH_OPT_VMPRIV
;
1728 return (was_vmpriv
);
1733 * XXX assuming current thread only, for now...
1736 thread_guard_violation(thread_t thread
, unsigned type
)
1738 assert(thread
== current_thread());
1740 spl_t s
= splsched();
1742 * Use the saved state area of the thread structure
1743 * to store all info required to handle the AST when
1744 * returning to userspace
1746 thread
->guard_exc_info
.type
= type
;
1747 thread_ast_set(thread
, AST_GUARD
);
1748 ast_propagate(thread
->ast
);
1756 * Handle AST_GUARD for a thread. This routine looks at the
1757 * state saved in the thread structure to determine the cause
1758 * of this exception. Based on this value, it invokes the
1759 * appropriate routine which determines other exception related
1760 * info and raises the exception.
1763 guard_ast(thread_t thread
)
1765 if (thread
->guard_exc_info
.type
== GUARD_TYPE_MACH_PORT
)
1766 mach_port_guard_ast(thread
);
1768 fd_guard_ast(thread
);
1772 thread_cputime_callback(int warning
, __unused
const void *arg0
, __unused
const void *arg1
)
1774 if (warning
== LEDGER_WARNING_ROSE_ABOVE
) {
1775 #if CONFIG_TELEMETRY
1777 * This thread is in danger of violating the CPU usage monitor. Enable telemetry
1778 * on the entire task so there are micro-stackshots available if and when
1779 * EXC_RESOURCE is triggered. We could have chosen to enable micro-stackshots
1780 * for this thread only; but now that this task is suspect, knowing what all of
1781 * its threads are up to will be useful.
1783 telemetry_task_ctl(current_task(), TF_CPUMON_WARNING
, 1);
1788 #if CONFIG_TELEMETRY
1790 * If the balance has dipped below the warning level (LEDGER_WARNING_DIPPED_BELOW) or
1791 * exceeded the limit, turn telemetry off for the task.
1793 telemetry_task_ctl(current_task(), TF_CPUMON_WARNING
, 0);
1797 THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU__SENDING_EXC_RESOURCE();
1801 void __attribute__((noinline
))
1802 THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU__SENDING_EXC_RESOURCE(void)
1805 task_t task
= current_task();
1806 thread_t thread
= current_thread();
1807 uint64_t tid
= thread
->thread_id
;
1808 const char *procname
= "unknown";
1809 time_value_t thread_total_time
= {0, 0};
1810 time_value_t thread_system_time
;
1811 time_value_t thread_user_time
;
1814 uint32_t limit_percent
;
1815 uint32_t usage_percent
;
1816 uint32_t interval_sec
;
1817 uint64_t interval_ns
;
1818 uint64_t balance_ns
;
1819 boolean_t fatal
= FALSE
;
1821 mach_exception_data_type_t code
[EXCEPTION_CODE_MAX
];
1822 struct ledger_entry_info lei
;
1824 assert(thread
->t_threadledger
!= LEDGER_NULL
);
1827 * Now that a thread has tripped the monitor, disable it for the entire task.
1830 if ((task
->rusage_cpu_flags
& TASK_RUSECPU_FLAGS_PERTHR_LIMIT
) == 0) {
1832 * The CPU usage monitor has been disabled on our task, so some other
1833 * thread must have gotten here first. We only send one exception per
1834 * task lifetime, so there's nothing left for us to do here.
1839 if (task
->rusage_cpu_flags
& TASK_RUSECPU_FLAGS_FATAL_CPUMON
) {
1842 task_disable_cpumon(task
);
1846 pid
= proc_selfpid();
1847 if (task
->bsd_info
!= NULL
)
1848 procname
= proc_name_address(task
->bsd_info
);
1851 thread_get_cpulimit(&action
, &percentage
, &interval_ns
);
1853 interval_sec
= (uint32_t)(interval_ns
/ NSEC_PER_SEC
);
1855 thread_read_times(thread
, &thread_user_time
, &thread_system_time
);
1856 time_value_add(&thread_total_time
, &thread_user_time
);
1857 time_value_add(&thread_total_time
, &thread_system_time
);
1859 ledger_get_entry_info(thread
->t_threadledger
, thread_ledgers
.cpu_time
, &lei
);
1861 absolutetime_to_nanoseconds(lei
.lei_balance
, &balance_ns
);
1862 usage_percent
= (uint32_t) ((balance_ns
* 100ULL) / lei
.lei_last_refill
);
1864 /* Show refill period in the same units as balance, limit, etc */
1865 nanoseconds_to_absolutetime(lei
.lei_refill_period
, &lei
.lei_refill_period
);
1867 limit_percent
= (uint32_t) ((lei
.lei_limit
* 100ULL) / lei
.lei_refill_period
);
1869 /* TODO: show task total runtime as well? see TASK_ABSOLUTETIME_INFO */
1871 if (disable_exc_resource
) {
1872 printf("process %s[%d] thread %llu caught burning CPU!; EXC_RESOURCE "
1873 "supressed by a boot-arg\n", procname
, pid
, tid
);
1878 printf("process %s[%d] thread %llu caught burning CPU!; EXC_RESOURCE "
1879 "supressed due to audio playback\n", procname
, pid
, tid
);
1882 printf("process %s[%d] thread %llu caught burning CPU! "
1883 "It used more than %d%% CPU (Actual recent usage: %d%%) over %d seconds. "
1884 "thread lifetime cpu usage %d.%06d seconds, (%d.%06d user, %d.%06d system) "
1885 "ledger info: balance: %lld credit: %lld debit: %lld limit: %llu (%d%%) "
1886 "period: %llu time since last refill (ns): %llu %s\n",
1888 percentage
, usage_percent
, interval_sec
,
1889 thread_total_time
.seconds
, thread_total_time
.microseconds
,
1890 thread_user_time
.seconds
, thread_user_time
.microseconds
,
1891 thread_system_time
.seconds
, thread_system_time
.microseconds
,
1893 lei
.lei_credit
, lei
.lei_debit
,
1894 lei
.lei_limit
, limit_percent
,
1895 lei
.lei_refill_period
, lei
.lei_last_refill
,
1896 (fatal
? "[fatal violation]" : ""));
1899 code
[0] = code
[1] = 0;
1900 EXC_RESOURCE_ENCODE_TYPE(code
[0], RESOURCE_TYPE_CPU
);
1902 EXC_RESOURCE_ENCODE_FLAVOR(code
[0], FLAVOR_CPU_MONITOR_FATAL
);
1904 EXC_RESOURCE_ENCODE_FLAVOR(code
[0], FLAVOR_CPU_MONITOR
);
1906 EXC_RESOURCE_CPUMONITOR_ENCODE_INTERVAL(code
[0], interval_sec
);
1907 EXC_RESOURCE_CPUMONITOR_ENCODE_PERCENTAGE(code
[0], limit_percent
);
1908 EXC_RESOURCE_CPUMONITOR_ENCODE_PERCENTAGE(code
[1], usage_percent
);
1909 exception_triage(EXC_RESOURCE
, code
, EXCEPTION_CODE_MAX
);
1913 jetsam_on_ledger_cpulimit_exceeded();
1915 task_terminate_internal(task
);
1920 void thread_update_io_stats(thread_t thread
, int size
, int io_flags
)
1924 if (thread
->thread_io_stats
== NULL
|| thread
->task
->task_io_stats
== NULL
)
1927 if (io_flags
& DKIO_READ
) {
1928 UPDATE_IO_STATS(thread
->thread_io_stats
->disk_reads
, size
);
1929 UPDATE_IO_STATS_ATOMIC(thread
->task
->task_io_stats
->disk_reads
, size
);
1932 if (io_flags
& DKIO_META
) {
1933 UPDATE_IO_STATS(thread
->thread_io_stats
->metadata
, size
);
1934 UPDATE_IO_STATS_ATOMIC(thread
->task
->task_io_stats
->metadata
, size
);
1937 if (io_flags
& DKIO_PAGING
) {
1938 UPDATE_IO_STATS(thread
->thread_io_stats
->paging
, size
);
1939 UPDATE_IO_STATS_ATOMIC(thread
->task
->task_io_stats
->paging
, size
);
1942 io_tier
= ((io_flags
& DKIO_TIER_MASK
) >> DKIO_TIER_SHIFT
);
1943 assert (io_tier
< IO_NUM_PRIORITIES
);
1945 UPDATE_IO_STATS(thread
->thread_io_stats
->io_priority
[io_tier
], size
);
1946 UPDATE_IO_STATS_ATOMIC(thread
->task
->task_io_stats
->io_priority
[io_tier
], size
);
1948 /* Update Total I/O Counts */
1949 UPDATE_IO_STATS(thread
->thread_io_stats
->total_io
, size
);
1950 UPDATE_IO_STATS_ATOMIC(thread
->task
->task_io_stats
->total_io
, size
);
1955 init_thread_ledgers(void) {
1956 ledger_template_t t
;
1959 assert(thread_ledger_template
== NULL
);
1961 if ((t
= ledger_template_create("Per-thread ledger")) == NULL
)
1962 panic("couldn't create thread ledger template");
1964 if ((idx
= ledger_entry_add(t
, "cpu_time", "sched", "ns")) < 0) {
1965 panic("couldn't create cpu_time entry for thread ledger template");
1968 if (ledger_set_callback(t
, idx
, thread_cputime_callback
, NULL
, NULL
) < 0) {
1969 panic("couldn't set thread ledger callback for cpu_time entry");
1972 thread_ledgers
.cpu_time
= idx
;
1974 thread_ledger_template
= t
;
1978 * Returns currently applied CPU usage limit, or 0/0 if none is applied.
1981 thread_get_cpulimit(int *action
, uint8_t *percentage
, uint64_t *interval_ns
)
1983 int64_t abstime
= 0;
1984 uint64_t limittime
= 0;
1985 thread_t thread
= current_thread();
1991 if (thread
->t_threadledger
== LEDGER_NULL
) {
1993 * This thread has no per-thread ledger, so it can't possibly
1994 * have a CPU limit applied.
1996 return (KERN_SUCCESS
);
1999 ledger_get_period(thread
->t_threadledger
, thread_ledgers
.cpu_time
, interval_ns
);
2000 ledger_get_limit(thread
->t_threadledger
, thread_ledgers
.cpu_time
, &abstime
);
2002 if ((abstime
== LEDGER_LIMIT_INFINITY
) || (*interval_ns
== 0)) {
2004 * This thread's CPU time ledger has no period or limit; so it
2005 * doesn't have a CPU limit applied.
2007 return (KERN_SUCCESS
);
2011 * This calculation is the converse to the one in thread_set_cpulimit().
2013 absolutetime_to_nanoseconds(abstime
, &limittime
);
2014 *percentage
= (limittime
* 100ULL) / *interval_ns
;
2015 assert(*percentage
<= 100);
2017 if (thread
->options
& TH_OPT_PROC_CPULIMIT
) {
2018 assert((thread
->options
& TH_OPT_PRVT_CPULIMIT
) == 0);
2020 *action
= THREAD_CPULIMIT_BLOCK
;
2021 } else if (thread
->options
& TH_OPT_PRVT_CPULIMIT
) {
2022 assert((thread
->options
& TH_OPT_PROC_CPULIMIT
) == 0);
2024 *action
= THREAD_CPULIMIT_EXCEPTION
;
2026 *action
= THREAD_CPULIMIT_DISABLE
;
2029 return (KERN_SUCCESS
);
2033 * Set CPU usage limit on a thread.
2035 * Calling with percentage of 0 will unset the limit for this thread.
2038 thread_set_cpulimit(int action
, uint8_t percentage
, uint64_t interval_ns
)
2040 thread_t thread
= current_thread();
2042 uint64_t limittime
= 0;
2043 uint64_t abstime
= 0;
2045 assert(percentage
<= 100);
2047 if (action
== THREAD_CPULIMIT_DISABLE
) {
2049 * Remove CPU limit, if any exists.
2051 if (thread
->t_threadledger
!= LEDGER_NULL
) {
2052 l
= thread
->t_threadledger
;
2053 ledger_set_limit(l
, thread_ledgers
.cpu_time
, LEDGER_LIMIT_INFINITY
, 0);
2054 ledger_set_action(l
, thread_ledgers
.cpu_time
, LEDGER_ACTION_IGNORE
);
2055 thread
->options
&= ~(TH_OPT_PROC_CPULIMIT
| TH_OPT_PRVT_CPULIMIT
);
2061 if (interval_ns
< MINIMUM_CPULIMIT_INTERVAL_MS
* NSEC_PER_MSEC
) {
2062 return (KERN_INVALID_ARGUMENT
);
2065 l
= thread
->t_threadledger
;
2066 if (l
== LEDGER_NULL
) {
2068 * This thread doesn't yet have a per-thread ledger; so create one with the CPU time entry active.
2070 if ((l
= ledger_instantiate(thread_ledger_template
, LEDGER_CREATE_INACTIVE_ENTRIES
)) == LEDGER_NULL
)
2071 return (KERN_RESOURCE_SHORTAGE
);
2074 * We are the first to create this thread's ledger, so only activate our entry.
2076 ledger_entry_setactive(l
, thread_ledgers
.cpu_time
);
2077 thread
->t_threadledger
= l
;
2081 * The limit is specified as a percentage of CPU over an interval in nanoseconds.
2082 * Calculate the amount of CPU time that the thread needs to consume in order to hit the limit.
2084 limittime
= (interval_ns
* percentage
) / 100;
2085 nanoseconds_to_absolutetime(limittime
, &abstime
);
2086 ledger_set_limit(l
, thread_ledgers
.cpu_time
, abstime
, cpumon_ustackshots_trigger_pct
);
2088 * Refill the thread's allotted CPU time every interval_ns nanoseconds.
2090 ledger_set_period(l
, thread_ledgers
.cpu_time
, interval_ns
);
2092 if (action
== THREAD_CPULIMIT_EXCEPTION
) {
2094 * We don't support programming the CPU usage monitor on a task if any of its
2095 * threads have a per-thread blocking CPU limit configured.
2097 if (thread
->options
& TH_OPT_PRVT_CPULIMIT
) {
2098 panic("CPU usage monitor activated, but blocking thread limit exists");
2102 * Make a note that this thread's CPU limit is being used for the task-wide CPU
2103 * usage monitor. We don't have to arm the callback which will trigger the
2104 * exception, because that was done for us in ledger_instantiate (because the
2105 * ledger template used has a default callback).
2107 thread
->options
|= TH_OPT_PROC_CPULIMIT
;
2110 * We deliberately override any CPU limit imposed by a task-wide limit (eg
2111 * CPU usage monitor).
2113 thread
->options
&= ~TH_OPT_PROC_CPULIMIT
;
2115 thread
->options
|= TH_OPT_PRVT_CPULIMIT
;
2116 /* The per-thread ledger template by default has a callback for CPU time */
2117 ledger_disable_callback(l
, thread_ledgers
.cpu_time
);
2118 ledger_set_action(l
, thread_ledgers
.cpu_time
, LEDGER_ACTION_BLOCK
);
2127 __unused thread_t thread
)
2137 thread
->sched_call
= (call
!= NULL
)? call
: sched_call_null
;
2141 thread_static_param(
2145 thread_mtx_lock(thread
);
2146 thread
->static_param
= state
;
2147 thread_mtx_unlock(thread
);
2154 return (thread
!= THREAD_NULL
? thread
->thread_id
: 0);
2157 uint16_t thread_set_tag(thread_t th
, uint16_t tag
) {
2158 return thread_set_tag_internal(th
, tag
);
2160 uint16_t thread_get_tag(thread_t th
) {
2161 return thread_get_tag_internal(th
);
2165 thread_dispatchqaddr(
2168 uint64_t dispatchqueue_addr
= 0;
2169 uint64_t thread_handle
= 0;
2171 if (thread
!= THREAD_NULL
) {
2172 thread_handle
= thread
->machine
.cthread_self
;
2174 if (thread
->inspection
== TRUE
)
2175 dispatchqueue_addr
= thread_handle
+ get_task_dispatchqueue_offset(thread
->task
);
2176 else if (thread
->task
->bsd_info
)
2177 dispatchqueue_addr
= thread_handle
+ get_dispatchqueue_offset_from_proc(thread
->task
->bsd_info
);
2180 return (dispatchqueue_addr
);
2184 * Export routines to other components for things that are done as macros
2185 * within the osfmk component.
2188 #undef thread_reference
2189 void thread_reference(thread_t thread
);
2194 if (thread
!= THREAD_NULL
)
2195 thread_reference_internal(thread
);
2198 #undef thread_should_halt
2204 return (thread_should_halt_fast(th
));
2208 * thread_set_voucher_name - reset the voucher port name bound to this thread
2210 * Conditions: nothing locked
2212 * If we already converted the previous name to a cached voucher
2213 * reference, then we discard that reference here. The next lookup
2214 * will cache it again.
2218 thread_set_voucher_name(mach_port_name_t voucher_name
)
2220 thread_t thread
= current_thread();
2221 ipc_voucher_t new_voucher
= IPC_VOUCHER_NULL
;
2222 ipc_voucher_t voucher
;
2224 ledger_t bankledger
= NULL
;
2227 if (MACH_PORT_DEAD
== voucher_name
)
2228 return KERN_INVALID_RIGHT
;
2231 * agressively convert to voucher reference
2233 if (MACH_PORT_VALID(voucher_name
)) {
2234 new_voucher
= convert_port_name_to_voucher(voucher_name
);
2235 if (IPC_VOUCHER_NULL
== new_voucher
)
2236 return KERN_INVALID_ARGUMENT
;
2239 bankledger
= bank_get_voucher_ledger(new_voucher
);
2242 thread_mtx_lock(thread
);
2243 voucher
= thread
->ith_voucher
;
2244 thread
->ith_voucher_name
= voucher_name
;
2245 thread
->ith_voucher
= new_voucher
;
2247 bank_swap_thread_bank_ledger(thread
, bankledger
);
2249 thread_mtx_unlock(thread
);
2251 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2252 MACHDBG_CODE(DBG_MACH_IPC
,MACH_THREAD_SET_VOUCHER
) | DBG_FUNC_NONE
,
2253 (uintptr_t)thread_tid(thread
),
2254 (uintptr_t)voucher_name
,
2255 VM_KERNEL_ADDRPERM((uintptr_t)new_voucher
),
2258 if (IPC_VOUCHER_NULL
!= voucher
)
2259 ipc_voucher_release(voucher
);
2261 return KERN_SUCCESS
;
2265 * thread_get_mach_voucher - return a voucher reference for the specified thread voucher
2267 * Conditions: nothing locked
2269 * A reference to the voucher may be lazily pending, if someone set the voucher name
2270 * but nobody has done a lookup yet. In that case, we'll have to do the equivalent
2273 * NOTE: At the moment, there is no distinction between the current and effective
2274 * vouchers because we only set them at the thread level currently.
2277 thread_get_mach_voucher(
2278 thread_act_t thread
,
2279 mach_voucher_selector_t __unused which
,
2280 ipc_voucher_t
*voucherp
)
2282 ipc_voucher_t voucher
;
2283 mach_port_name_t voucher_name
;
2285 if (THREAD_NULL
== thread
)
2286 return KERN_INVALID_ARGUMENT
;
2288 thread_mtx_lock(thread
);
2289 voucher
= thread
->ith_voucher
;
2291 /* if already cached, just return a ref */
2292 if (IPC_VOUCHER_NULL
!= voucher
) {
2293 ipc_voucher_reference(voucher
);
2294 thread_mtx_unlock(thread
);
2295 *voucherp
= voucher
;
2296 return KERN_SUCCESS
;
2299 voucher_name
= thread
->ith_voucher_name
;
2301 /* convert the name to a port, then voucher reference */
2302 if (MACH_PORT_VALID(voucher_name
)) {
2306 ipc_object_copyin(thread
->task
->itk_space
, voucher_name
,
2307 MACH_MSG_TYPE_COPY_SEND
, (ipc_object_t
*)&port
)) {
2308 thread
->ith_voucher_name
= MACH_PORT_NULL
;
2309 thread_mtx_unlock(thread
);
2310 *voucherp
= IPC_VOUCHER_NULL
;
2311 return KERN_SUCCESS
;
2314 /* convert to a voucher ref to return, and cache a ref on thread */
2315 voucher
= convert_port_to_voucher(port
);
2316 ipc_voucher_reference(voucher
);
2317 thread
->ith_voucher
= voucher
;
2318 thread_mtx_unlock(thread
);
2320 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2321 MACHDBG_CODE(DBG_MACH_IPC
,MACH_THREAD_SET_VOUCHER
) | DBG_FUNC_NONE
,
2322 (uintptr_t)thread_tid(thread
),
2324 VM_KERNEL_ADDRPERM((uintptr_t)voucher
),
2328 ipc_port_release_send(port
);
2330 thread_mtx_unlock(thread
);
2332 *voucherp
= voucher
;
2333 return KERN_SUCCESS
;
2337 * thread_set_mach_voucher - set a voucher reference for the specified thread voucher
2339 * Conditions: callers holds a reference on the voucher.
2342 * We grab another reference to the voucher and bind it to the thread. Any lazy
2343 * binding is erased. The old voucher reference associated with the thread is
2347 thread_set_mach_voucher(
2349 ipc_voucher_t voucher
)
2351 ipc_voucher_t old_voucher
;
2353 ledger_t bankledger
= NULL
;
2356 if (THREAD_NULL
== thread
)
2357 return KERN_INVALID_ARGUMENT
;
2359 if (thread
!= current_thread() || thread
->started
)
2360 return KERN_INVALID_ARGUMENT
;
2363 ipc_voucher_reference(voucher
);
2365 bankledger
= bank_get_voucher_ledger(voucher
);
2367 thread_mtx_lock(thread
);
2368 old_voucher
= thread
->ith_voucher
;
2369 thread
->ith_voucher
= voucher
;
2370 thread
->ith_voucher_name
= MACH_PORT_NULL
;
2372 bank_swap_thread_bank_ledger(thread
, bankledger
);
2374 thread_mtx_unlock(thread
);
2376 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2377 MACHDBG_CODE(DBG_MACH_IPC
,MACH_THREAD_SET_VOUCHER
) | DBG_FUNC_NONE
,
2378 (uintptr_t)thread_tid(thread
),
2379 (uintptr_t)MACH_PORT_NULL
,
2380 VM_KERNEL_ADDRPERM((uintptr_t)voucher
),
2383 ipc_voucher_release(old_voucher
);
2385 return KERN_SUCCESS
;
2389 * thread_swap_mach_voucher - swap a voucher reference for the specified thread voucher
2391 * Conditions: callers holds a reference on the new and presumed old voucher(s).
2394 * If the old voucher is still the same as passed in, replace it with new voucher
2395 * and discard the old (and the reference passed in). Otherwise, discard the new
2396 * and return an updated old voucher.
2399 thread_swap_mach_voucher(
2401 ipc_voucher_t new_voucher
,
2402 ipc_voucher_t
*in_out_old_voucher
)
2404 mach_port_name_t old_voucher_name
;
2405 ipc_voucher_t old_voucher
;
2407 ledger_t bankledger
= NULL
;
2410 if (THREAD_NULL
== thread
)
2411 return KERN_INVALID_TASK
;
2413 if (thread
!= current_thread() || thread
->started
)
2414 return KERN_INVALID_ARGUMENT
;
2417 bankledger
= bank_get_voucher_ledger(new_voucher
);
2420 thread_mtx_lock(thread
);
2422 old_voucher
= thread
->ith_voucher
;
2424 if (IPC_VOUCHER_NULL
== old_voucher
) {
2425 old_voucher_name
= thread
->ith_voucher_name
;
2427 /* perform lazy binding if needed */
2428 if (MACH_PORT_VALID(old_voucher_name
)) {
2429 old_voucher
= convert_port_name_to_voucher(old_voucher_name
);
2430 thread
->ith_voucher_name
= MACH_PORT_NULL
;
2431 thread
->ith_voucher
= old_voucher
;
2433 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2434 MACHDBG_CODE(DBG_MACH_IPC
,MACH_THREAD_SET_VOUCHER
) | DBG_FUNC_NONE
,
2435 (uintptr_t)thread_tid(thread
),
2436 (uintptr_t)old_voucher_name
,
2437 VM_KERNEL_ADDRPERM((uintptr_t)old_voucher
),
2443 /* swap in new voucher, if old voucher matches the one supplied */
2444 if (old_voucher
== *in_out_old_voucher
) {
2445 ipc_voucher_reference(new_voucher
);
2446 thread
->ith_voucher
= new_voucher
;
2447 thread
->ith_voucher_name
= MACH_PORT_NULL
;
2449 bank_swap_thread_bank_ledger(thread
, bankledger
);
2451 thread_mtx_unlock(thread
);
2453 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2454 MACHDBG_CODE(DBG_MACH_IPC
,MACH_THREAD_SET_VOUCHER
) | DBG_FUNC_NONE
,
2455 (uintptr_t)thread_tid(thread
),
2456 (uintptr_t)MACH_PORT_NULL
,
2457 VM_KERNEL_ADDRPERM((uintptr_t)new_voucher
),
2460 ipc_voucher_release(old_voucher
);
2462 *in_out_old_voucher
= IPC_VOUCHER_NULL
;
2463 return KERN_SUCCESS
;
2466 /* Otherwise, just return old voucher reference */
2467 ipc_voucher_reference(old_voucher
);
2468 thread_mtx_unlock(thread
);
2469 *in_out_old_voucher
= old_voucher
;
2470 return KERN_SUCCESS
;
2474 * thread_get_current_voucher_origin_pid - get the pid of the originator of the current voucher.
2477 thread_get_current_voucher_origin_pid(
2482 thread_t thread
= current_thread();
2484 buf_size
= sizeof(*pid
);
2485 kr
= mach_voucher_attr_command(thread
->ith_voucher
,
2486 MACH_VOUCHER_ATTR_KEY_BANK
,
2487 BANK_ORIGINATOR_PID
,
2490 (mach_voucher_attr_content_t
)pid
,
2497 * thread_enable_send_importance - set/clear the SEND_IMPORTANCE thread option bit.
2499 void thread_enable_send_importance(thread_t thread
, boolean_t enable
)
2502 thread
->options
|= TH_OPT_SEND_IMPORTANCE
;
2504 thread
->options
&= ~TH_OPT_SEND_IMPORTANCE
;
2508 uint32_t dtrace_get_thread_predcache(thread_t thread
)
2510 if (thread
!= THREAD_NULL
)
2511 return thread
->t_dtrace_predcache
;
2516 int64_t dtrace_get_thread_vtime(thread_t thread
)
2518 if (thread
!= THREAD_NULL
)
2519 return thread
->t_dtrace_vtime
;
2524 int dtrace_get_thread_last_cpu_id(thread_t thread
)
2526 if ((thread
!= THREAD_NULL
) && (thread
->last_processor
!= PROCESSOR_NULL
)) {
2527 return thread
->last_processor
->cpu_id
;
2533 int64_t dtrace_get_thread_tracing(thread_t thread
)
2535 if (thread
!= THREAD_NULL
)
2536 return thread
->t_dtrace_tracing
;
2541 boolean_t
dtrace_get_thread_reentering(thread_t thread
)
2543 if (thread
!= THREAD_NULL
)
2544 return (thread
->options
& TH_OPT_DTRACE
) ? TRUE
: FALSE
;
2549 vm_offset_t
dtrace_get_kernel_stack(thread_t thread
)
2551 if (thread
!= THREAD_NULL
)
2552 return thread
->kernel_stack
;
2557 int64_t dtrace_calc_thread_recent_vtime(thread_t thread
)
2559 if (thread
!= THREAD_NULL
) {
2560 processor_t processor
= current_processor();
2561 uint64_t abstime
= mach_absolute_time();
2564 timer
= PROCESSOR_DATA(processor
, thread_timer
);
2566 return timer_grab(&(thread
->system_timer
)) + timer_grab(&(thread
->user_timer
)) +
2567 (abstime
- timer
->tstamp
); /* XXX need interrupts off to prevent missed time? */
2572 void dtrace_set_thread_predcache(thread_t thread
, uint32_t predcache
)
2574 if (thread
!= THREAD_NULL
)
2575 thread
->t_dtrace_predcache
= predcache
;
2578 void dtrace_set_thread_vtime(thread_t thread
, int64_t vtime
)
2580 if (thread
!= THREAD_NULL
)
2581 thread
->t_dtrace_vtime
= vtime
;
2584 void dtrace_set_thread_tracing(thread_t thread
, int64_t accum
)
2586 if (thread
!= THREAD_NULL
)
2587 thread
->t_dtrace_tracing
= accum
;
2590 void dtrace_set_thread_reentering(thread_t thread
, boolean_t vbool
)
2592 if (thread
!= THREAD_NULL
) {
2594 thread
->options
|= TH_OPT_DTRACE
;
2596 thread
->options
&= (~TH_OPT_DTRACE
);
2600 vm_offset_t
dtrace_set_thread_recover(thread_t thread
, vm_offset_t recover
)
2602 vm_offset_t prev
= 0;
2604 if (thread
!= THREAD_NULL
) {
2605 prev
= thread
->recover
;
2606 thread
->recover
= recover
;
2611 void dtrace_thread_bootstrap(void)
2613 task_t task
= current_task();
2615 if (task
->thread_count
== 1) {
2616 thread_t thread
= current_thread();
2617 if (thread
->t_dtrace_flags
& TH_DTRACE_EXECSUCCESS
) {
2618 thread
->t_dtrace_flags
&= ~TH_DTRACE_EXECSUCCESS
;
2619 DTRACE_PROC(exec__success
);
2623 DTRACE_PROC(lwp__start
);
2628 dtrace_thread_didexec(thread_t thread
)
2630 thread
->t_dtrace_flags
|= TH_DTRACE_EXECSUCCESS
;
2632 #endif /* CONFIG_DTRACE */