]> git.saurik.com Git - apple/xnu.git/blob - osfmk/kern/thread.c
xnu-3248.40.184.tar.gz
[apple/xnu.git] / osfmk / kern / thread.c
1 /*
2 * Copyright (c) 2000-2015 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 Software.Distribution@CS.CMU.EDU
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: kern/thread.c
60 * Author: Avadis Tevanian, Jr., Michael Wayne Young, David Golub
61 * Date: 1986
62 *
63 * Thread management primitives implementation.
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 csl-dist@cs.utah.edu any
80 * improvements that they make and grant CSL redistribution rights.
81 *
82 */
83
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>
92
93 #include <machine/thread.h>
94 #include <machine/pal_routines.h>
95 #include <machine/limits.h>
96
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>
121 #if KPC
122 #include <kern/kpc.h>
123 #endif
124
125 #include <ipc/ipc_kmsg.h>
126 #include <ipc/ipc_port.h>
127 #include <bank/bank_types.h>
128
129 #include <vm/vm_kern.h>
130 #include <vm/vm_pageout.h>
131
132 #include <sys/kdebug.h>
133 #include <sys/bsdtask_info.h>
134 #include <mach/sdt.h>
135
136 /*
137 * Exported interfaces
138 */
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>
144
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;
149
150 struct zone *thread_qos_override_zone;
151
152 decl_simple_lock_data(static,thread_stack_lock)
153 static queue_head_t thread_stack_queue;
154
155 decl_simple_lock_data(static,thread_terminate_lock)
156 static queue_head_t thread_terminate_queue;
157
158 static queue_head_t crashed_threads_queue;
159
160 static struct thread thread_template, init_thread;
161
162 static void sched_call_null(
163 int type,
164 thread_t thread);
165
166 #ifdef MACH_BSD
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 */
172
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;
178
179 static uint64_t thread_unique_id = 100;
180
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);
185
186 #if CONFIG_JETSAM
187 void jetsam_on_ledger_cpulimit_exceeded(void);
188 #endif
189
190 /*
191 * Level (in terms of percentage of the limit) at which the CPU usage monitor triggers telemetry.
192 *
193 * (ie when any thread's CPU consumption exceeds 70% of the limit, start taking user
194 * stacktraces, aka micro-stackshots)
195 */
196 #define CPUMON_USTACKSHOTS_TRIGGER_DEFAULT_PCT 70
197
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);
200
201 /*
202 * The smallest interval over which we support limiting CPU consumption is 1ms
203 */
204 #define MINIMUM_CPULIMIT_INTERVAL_MS 1
205
206 void
207 thread_bootstrap(void)
208 {
209 /*
210 * Fill in a template thread for fast initialization.
211 */
212
213 thread_template.runq = PROCESSOR_NULL;
214
215 thread_template.ref_count = 2;
216
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;
227
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;
233
234 thread_template.sfi_class = SFI_CLASS_UNSPECIFIED;
235 thread_template.sfi_wait_class = SFI_CLASS_UNSPECIFIED;
236
237 thread_template.active = 0;
238 thread_template.started = 0;
239 thread_template.static_param = 0;
240 thread_template.policy_reset = 0;
241
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;
251
252 #if MACH_ASSERT
253 thread_template.SHARE_COUNT = 0;
254 thread_template.BG_COUNT = 0;
255 #endif /* MACH_ASSERT */
256
257 thread_template.realtime.deadline = UINT64_MAX;
258
259 thread_template.quantum_remaining = 0;
260 thread_template.last_run_time = 0;
261 thread_template.last_made_runnable_time = 0;
262
263 thread_template.computation_metered = 0;
264 thread_template.computation_epoch = 0;
265
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;
271 #endif
272 thread_template.c_switch = thread_template.p_switch = thread_template.ps_switch = 0;
273
274 thread_template.bound_processor = PROCESSOR_NULL;
275 thread_template.last_processor = PROCESSOR_NULL;
276
277 thread_template.sched_call = sched_call_null;
278
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;
286
287 #if CONFIG_SCHED_SFI
288 thread_template.wait_sfi_begin_time = 0;
289 #endif
290
291 thread_template.wait_timer_is_set = FALSE;
292 thread_template.wait_timer_active = 0;
293
294 thread_template.depress_timer_active = 0;
295
296 thread_template.recover = (vm_offset_t)NULL;
297
298 thread_template.map = VM_MAP_NULL;
299
300 #if CONFIG_DTRACE
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 */
305
306 #if KPC
307 thread_template.kpc_buf = NULL;
308 #endif
309
310 #if HYPERVISOR
311 thread_template.hv_thread_target = NULL;
312 #endif /* HYPERVISOR */
313
314 thread_template.t_chud = 0;
315
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;
323
324 thread_template.affinity_set = NULL;
325
326 thread_template.syscalls_unix = 0;
327 thread_template.syscalls_mach = 0;
328
329 thread_template.t_ledger = LEDGER_NULL;
330 thread_template.t_threadledger = LEDGER_NULL;
331 #ifdef CONFIG_BANK
332 thread_template.t_bankledger = LEDGER_NULL;
333 thread_template.t_deduct_bank_ledger_time = 0;
334 #endif
335
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;
339
340 bzero(&thread_template.overrides, sizeof(thread_template.overrides));
341
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;
345
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;
348
349 thread_template.thread_tag = 0;
350
351 thread_template.ith_voucher_name = MACH_PORT_NULL;
352 thread_template.ith_voucher = IPC_VOUCHER_NULL;
353
354 thread_template.work_interval_id = 0;
355
356 init_thread = thread_template;
357 machine_set_current_thread(&init_thread);
358 }
359
360 extern boolean_t allow_qos_policy_set;
361
362 void
363 thread_init(void)
364 {
365 thread_zone = zinit(
366 sizeof(struct thread),
367 thread_max * sizeof(struct thread),
368 THREAD_CHUNK * sizeof(struct thread),
369 "threads");
370
371 thread_qos_override_zone = zinit(
372 sizeof(struct thread_qos_override),
373 4 * thread_max * sizeof(struct thread_qos_override),
374 PAGE_SIZE,
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);
380
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);
384
385 stack_init();
386
387 /*
388 * Initialize any machine-dependent
389 * per-thread structures necessary.
390 */
391 machine_thread_init();
392
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;
396 }
397
398 PE_parse_boot_argn("-qos-policy-allow", &allow_qos_policy_set, sizeof(allow_qos_policy_set));
399
400 init_thread_ledgers();
401 }
402
403 static void
404 thread_terminate_continue(void)
405 {
406 panic("thread_terminate_continue");
407 /*NOTREACHED*/
408 }
409
410 /*
411 * thread_terminate_self:
412 */
413 void
414 thread_terminate_self(void)
415 {
416 thread_t thread = current_thread();
417 task_t task;
418 spl_t s;
419 int threadcnt;
420
421 pal_thread_terminate_self(thread);
422
423 DTRACE_PROC(lwp__exit);
424
425 thread_mtx_lock(thread);
426
427 ipc_thread_disable(thread);
428
429 thread_mtx_unlock(thread);
430
431 s = splsched();
432 thread_lock(thread);
433
434 assert_thread_sched_count(thread);
435
436 /*
437 * Cancel priority depression, wait for concurrent expirations
438 * on other processors.
439 */
440 if (thread->sched_flags & TH_SFLAG_DEPRESSED_MASK) {
441 thread->sched_flags &= ~TH_SFLAG_DEPRESSED_MASK;
442
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);
445
446 if (timer_call_cancel(&thread->depress_timer))
447 thread->depress_timer_active--;
448 }
449
450 while (thread->depress_timer_active > 0) {
451 thread_unlock(thread);
452 splx(s);
453
454 delay(1);
455
456 s = splsched();
457 thread_lock(thread);
458 }
459
460 thread_sched_call(thread, NULL);
461
462 thread_unlock(thread);
463 splx(s);
464
465
466 thread_mtx_lock(thread);
467
468 thread_policy_reset(thread);
469
470 thread_mtx_unlock(thread);
471
472 task = thread->task;
473 uthread_cleanup(task, thread->uthread, task->bsd_info, thread->inspection == 1 ? TRUE : FALSE);
474 threadcnt = hw_atomic_sub(&task->active_thread_count, 1);
475
476 /*
477 * If we are the last thread to terminate and the task is
478 * associated with a BSD process, perform BSD process exit.
479 */
480 if (threadcnt == 0 && task->bsd_info != NULL) {
481 proc_exit(task->bsd_info);
482 /*
483 * if there is crash info in task
484 * then do the deliver action since this is
485 * last thread for this task.
486 */
487 if (task->corpse_info) {
488 task_deliver_crash_notification(task);
489 }
490 }
491 uthread_cred_free(thread->uthread);
492
493 s = splsched();
494 thread_lock(thread);
495
496 /*
497 * Cancel wait timer, and wait for
498 * concurrent expirations.
499 */
500 if (thread->wait_timer_is_set) {
501 thread->wait_timer_is_set = FALSE;
502
503 if (timer_call_cancel(&thread->wait_timer))
504 thread->wait_timer_active--;
505 }
506
507 while (thread->wait_timer_active > 0) {
508 thread_unlock(thread);
509 splx(s);
510
511 delay(1);
512
513 s = splsched();
514 thread_lock(thread);
515 }
516
517 /*
518 * If there is a reserved stack, release it.
519 */
520 if (thread->reserved_stack != 0) {
521 stack_free_reserved(thread);
522 thread->reserved_stack = 0;
523 }
524
525 /*
526 * Mark thread as terminating, and block.
527 */
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);
535 /* splsched */
536
537 thread_block((thread_continue_t)thread_terminate_continue);
538 /*NOTREACHED*/
539 }
540
541 /* Drop a thread refcount that definitely isn't the last one. */
542 void
543 thread_deallocate_safe(thread_t thread)
544 {
545 if (__improbable(hw_atomic_sub(&(thread)->ref_count, 1) == 0))
546 panic("bad thread refcount!");
547 }
548
549 void
550 thread_deallocate(
551 thread_t thread)
552 {
553 task_t task;
554
555 if (thread == THREAD_NULL)
556 return;
557
558 if (__probable(hw_atomic_sub(&(thread)->ref_count, 1) > 0))
559 return;
560
561 if(!(thread->state & TH_TERMINATE2))
562 panic("thread_deallocate: thread not properly terminated\n");
563
564 assert(thread->runq == PROCESSOR_NULL);
565
566 #if KPC
567 kpc_thread_destroy(thread);
568 #endif
569
570 ipc_thread_terminate(thread);
571
572 proc_thread_qos_deallocate(thread);
573
574 task = thread->task;
575
576 #ifdef MACH_BSD
577 {
578 void *ut = thread->uthread;
579
580 thread->uthread = NULL;
581 uthread_zone_free(ut);
582 }
583 #endif /* MACH_BSD */
584
585 if (thread->t_ledger)
586 ledger_dereference(thread->t_ledger);
587 if (thread->t_threadledger)
588 ledger_dereference(thread->t_threadledger);
589
590 if (IPC_VOUCHER_NULL != thread->ith_voucher)
591 ipc_voucher_release(thread->ith_voucher);
592
593 if (thread->thread_io_stats)
594 kfree(thread->thread_io_stats, sizeof(struct io_stat_info));
595
596 if (thread->kernel_stack != 0)
597 stack_free(thread);
598
599 lck_mtx_destroy(&thread->mutex, &thread_lck_grp);
600 machine_thread_destroy(thread);
601
602 task_deallocate(task);
603
604 zfree(thread_zone, thread);
605 }
606
607 /*
608 * thread_terminate_daemon:
609 *
610 * Perform final clean up for terminating threads.
611 */
612 static void
613 thread_terminate_daemon(void)
614 {
615 thread_t self, thread;
616 task_t task;
617
618 self = current_thread();
619 self->options |= TH_OPT_SYSTEM_CRITICAL;
620
621 (void)splsched();
622 simple_lock(&thread_terminate_lock);
623
624 while ((thread = (thread_t)dequeue_head(&thread_terminate_queue)) != THREAD_NULL) {
625
626 /*
627 * if marked for crash reporting, skip reaping.
628 * The corpse delivery thread will clear bit and enqueue
629 * for reaping when done
630 */
631 if (thread->inspection){
632 enqueue_tail(&crashed_threads_queue, (queue_entry_t)thread);
633 continue;
634 }
635
636 simple_unlock(&thread_terminate_lock);
637 (void)spllo();
638
639 assert(thread->SHARE_COUNT == 0);
640 assert(thread->BG_COUNT == 0);
641
642 task = thread->task;
643
644 task_lock(task);
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);
648 } else {
649 task->total_user_time += timer_grab(&thread->system_timer);
650 }
651
652 task->c_switch += thread->c_switch;
653 task->p_switch += thread->p_switch;
654 task->ps_switch += thread->ps_switch;
655
656 task->syscalls_unix += thread->syscalls_unix;
657 task->syscalls_mach += thread->syscalls_mach;
658
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);
662
663 thread_update_qos_cpu_time(thread, FALSE);
664 queue_remove(&task->threads, thread, thread_t, task_threads);
665 task->thread_count--;
666
667 /*
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.
670 */
671 if (task->thread_count == 1 && task->halting)
672 thread_wakeup((event_t)&task->halting);
673
674 task_unlock(task);
675
676 lck_mtx_lock(&tasks_threads_lock);
677 queue_remove(&threads, thread, thread_t, threads);
678 threads_count--;
679 lck_mtx_unlock(&tasks_threads_lock);
680
681 thread_deallocate(thread);
682
683 (void)splsched();
684 simple_lock(&thread_terminate_lock);
685 }
686
687 assert_wait((event_t)&thread_terminate_queue, THREAD_UNINT);
688 simple_unlock(&thread_terminate_lock);
689 /* splsched */
690
691 self->options &= ~TH_OPT_SYSTEM_CRITICAL;
692 thread_block((thread_continue_t)thread_terminate_daemon);
693 /*NOTREACHED*/
694 }
695
696 /*
697 * thread_terminate_enqueue:
698 *
699 * Enqueue a terminating thread for final disposition.
700 *
701 * Called at splsched.
702 */
703 void
704 thread_terminate_enqueue(
705 thread_t thread)
706 {
707 KERNEL_DEBUG_CONSTANT(TRACE_DATA_THREAD_TERMINATE | DBG_FUNC_NONE, thread->thread_id, 0, 0, 0, 0);
708
709 simple_lock(&thread_terminate_lock);
710 enqueue_tail(&thread_terminate_queue, (queue_entry_t)thread);
711 simple_unlock(&thread_terminate_lock);
712
713 thread_wakeup((event_t)&thread_terminate_queue);
714 }
715
716 /*
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.
720 */
721 void
722 thread_terminate_crashed_threads()
723 {
724 thread_t th_iter, th_remove;
725 boolean_t should_wake_terminate_queue = FALSE;
726
727 simple_lock(&thread_terminate_lock);
728 /*
729 * loop through the crashed threads queue
730 * to put any threads that are not being inspected anymore
731 */
732 th_iter = (thread_t)queue_first(&crashed_threads_queue);
733 while (!queue_end(&crashed_threads_queue, (queue_entry_t)th_iter)) {
734 th_remove = th_iter;
735 th_iter = (thread_t)queue_next(&th_iter->links);
736
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;
743 }
744 }
745
746 simple_unlock(&thread_terminate_lock);
747 if (should_wake_terminate_queue == TRUE) {
748 thread_wakeup((event_t)&thread_terminate_queue);
749 }
750 }
751
752 /*
753 * thread_stack_daemon:
754 *
755 * Perform stack allocation as required due to
756 * invoke failures.
757 */
758 static void
759 thread_stack_daemon(void)
760 {
761 thread_t thread;
762 spl_t s;
763
764 s = splsched();
765 simple_lock(&thread_stack_lock);
766
767 while ((thread = (thread_t)dequeue_head(&thread_stack_queue)) != THREAD_NULL) {
768 simple_unlock(&thread_stack_lock);
769 splx(s);
770
771 /* allocate stack with interrupts enabled so that we can call into VM */
772 stack_alloc(thread);
773
774 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED,MACH_STACK_WAIT) | DBG_FUNC_END, thread_tid(thread), 0, 0, 0, 0);
775
776 s = splsched();
777 thread_lock(thread);
778 thread_setrun(thread, SCHED_PREEMPT | SCHED_TAILQ);
779 thread_unlock(thread);
780
781 simple_lock(&thread_stack_lock);
782 }
783
784 assert_wait((event_t)&thread_stack_queue, THREAD_UNINT);
785 simple_unlock(&thread_stack_lock);
786 splx(s);
787
788 thread_block((thread_continue_t)thread_stack_daemon);
789 /*NOTREACHED*/
790 }
791
792 /*
793 * thread_stack_enqueue:
794 *
795 * Enqueue a thread for stack allocation.
796 *
797 * Called at splsched.
798 */
799 void
800 thread_stack_enqueue(
801 thread_t thread)
802 {
803 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED,MACH_STACK_WAIT) | DBG_FUNC_START, thread_tid(thread), 0, 0, 0, 0);
804
805 simple_lock(&thread_stack_lock);
806 enqueue_tail(&thread_stack_queue, (queue_entry_t)thread);
807 simple_unlock(&thread_stack_lock);
808
809 thread_wakeup((event_t)&thread_stack_queue);
810 }
811
812 void
813 thread_daemon_init(void)
814 {
815 kern_return_t result;
816 thread_t thread = NULL;
817
818 simple_lock_init(&thread_terminate_lock, 0);
819 queue_init(&thread_terminate_queue);
820 queue_init(&crashed_threads_queue);
821
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");
825
826 thread_deallocate(thread);
827
828 simple_lock_init(&thread_stack_lock, 0);
829 queue_init(&thread_stack_queue);
830
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");
834
835 thread_deallocate(thread);
836 }
837
838 #define TH_OPTION_NONE 0x00
839 #define TH_OPTION_NOCRED 0x01
840 #define TH_OPTION_NOSUSP 0x02
841 /*
842 * Create a new thread.
843 * Doesn't start the thread running.
844 *
845 * Task and tasks_threads_lock are returned locked on success.
846 */
847 static kern_return_t
848 thread_create_internal(
849 task_t parent_task,
850 integer_t priority,
851 thread_continue_t continuation,
852 int options,
853 thread_t *out_thread)
854 {
855 thread_t new_thread;
856 static thread_t first_thread;
857
858 /*
859 * Allocate a thread and initialize static fields
860 */
861 if (first_thread == THREAD_NULL)
862 new_thread = first_thread = current_thread();
863 else
864 new_thread = (thread_t)zalloc(thread_zone);
865 if (new_thread == THREAD_NULL)
866 return (KERN_RESOURCE_SHORTAGE);
867
868 if (new_thread != first_thread)
869 *new_thread = thread_template;
870
871 #ifdef MACH_BSD
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);
876 }
877 #endif /* MACH_BSD */
878
879 if (machine_thread_create(new_thread, parent_task) != KERN_SUCCESS) {
880 #ifdef MACH_BSD
881 void *ut = new_thread->uthread;
882
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 */
889
890 zfree(thread_zone, new_thread);
891 return (KERN_FAILURE);
892 }
893
894 new_thread->task = parent_task;
895
896 thread_lock_init(new_thread);
897 wake_lock_init(new_thread);
898
899 lck_mtx_init(&new_thread->mutex, &thread_lck_grp, &thread_lck_attr);
900
901 ipc_thread_init(new_thread);
902
903 new_thread->continuation = continuation;
904
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));
909
910 #if CONFIG_IOSCHED
911 /* Clear out the I/O Scheduling info for AppleFSCompression */
912 new_thread->decmp_upl = NULL;
913 #endif /* CONFIG_IOSCHED */
914
915 lck_mtx_lock(&tasks_threads_lock);
916 task_lock(parent_task);
917
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);
925
926 #ifdef MACH_BSD
927 {
928 void *ut = new_thread->uthread;
929
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);
935 }
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);
944 }
945
946 /* New threads inherit any default state on the task */
947 machine_thread_inherit_taskwide(new_thread, parent_task);
948
949 task_reference_internal(parent_task);
950
951 if (new_thread->task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_PERTHR_LIMIT) {
952 /*
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.
955 */
956 set_astledger(new_thread);
957 }
958
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) {
962
963 ledger_entry_setactive(new_thread->t_threadledger, thread_ledgers.cpu_time);
964 }
965
966 new_thread->cpu_time_last_qos = 0;
967 #ifdef CONFIG_BANK
968 new_thread->t_bankledger = LEDGER_NULL;
969 new_thread->t_deduct_bank_ledger_time = 0;
970 #endif
971
972 new_thread->t_ledger = new_thread->task->ledger;
973 if (new_thread->t_ledger)
974 ledger_reference(new_thread->t_ledger);
975
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) */
980
981 /* Cache the task's map */
982 new_thread->map = parent_task->map;
983
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);
986
987 #if KPC
988 kpc_thread_create(new_thread);
989 #endif
990
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;
994
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) */
1000
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;
1005
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;
1010
1011 new_thread->importance = new_priority - new_thread->task_priority;
1012 new_thread->saved_importance = new_thread->importance;
1013
1014 sched_set_thread_base_priority(new_thread, new_priority);
1015
1016
1017 thread_policy_create(new_thread);
1018
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++;
1022
1023 /* So terminating threads don't need to take the task lock to decrement */
1024 hw_atomic_add(&parent_task->active_thread_count, 1);
1025
1026 /* Protected by the tasks_threads_lock */
1027 new_thread->thread_id = ++thread_unique_id;
1028
1029 queue_enter(&threads, new_thread, thread_t, threads);
1030 threads_count++;
1031
1032 new_thread->active = TRUE;
1033 new_thread->inspection = FALSE;
1034 *out_thread = new_thread;
1035
1036 {
1037 long dbg_arg1, dbg_arg2, dbg_arg3, dbg_arg4;
1038
1039 kdbg_trace_data(parent_task->bsd_info, &dbg_arg2);
1040
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);
1044
1045 kdbg_trace_string(parent_task->bsd_info,
1046 &dbg_arg1, &dbg_arg2, &dbg_arg3, &dbg_arg4);
1047
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);
1051 }
1052
1053 DTRACE_PROC1(lwp__create, thread_t, *out_thread);
1054
1055 return (KERN_SUCCESS);
1056 }
1057
1058 static kern_return_t
1059 thread_create_internal2(
1060 task_t task,
1061 thread_t *new_thread,
1062 boolean_t from_user,
1063 thread_continue_t continuation)
1064 {
1065 kern_return_t result;
1066 thread_t thread;
1067
1068 if (task == TASK_NULL || task == kernel_task)
1069 return (KERN_INVALID_ARGUMENT);
1070
1071 result = thread_create_internal(task, -1, continuation, TH_OPTION_NONE, &thread);
1072 if (result != KERN_SUCCESS)
1073 return (result);
1074
1075 thread->user_stop_count = 1;
1076 thread_hold(thread);
1077 if (task->suspend_count > 0)
1078 thread_hold(thread);
1079
1080 if (from_user)
1081 extmod_statistics_incr_thread_create(task);
1082
1083 task_unlock(task);
1084 lck_mtx_unlock(&tasks_threads_lock);
1085
1086 *new_thread = thread;
1087
1088 return (KERN_SUCCESS);
1089 }
1090
1091 /* No prototype, since task_server.h has the _from_user version if KERNEL_SERVER */
1092 kern_return_t
1093 thread_create(
1094 task_t task,
1095 thread_t *new_thread);
1096
1097 kern_return_t
1098 thread_create(
1099 task_t task,
1100 thread_t *new_thread)
1101 {
1102 return thread_create_internal2(task, new_thread, FALSE, (thread_continue_t)thread_bootstrap_return);
1103 }
1104
1105 kern_return_t
1106 thread_create_from_user(
1107 task_t task,
1108 thread_t *new_thread)
1109 {
1110 return thread_create_internal2(task, new_thread, TRUE, (thread_continue_t)thread_bootstrap_return);
1111 }
1112
1113 kern_return_t
1114 thread_create_with_continuation(
1115 task_t task,
1116 thread_t *new_thread,
1117 thread_continue_t continuation)
1118 {
1119 return thread_create_internal2(task, new_thread, FALSE, continuation);
1120 }
1121
1122 static kern_return_t
1123 thread_create_running_internal2(
1124 register task_t task,
1125 int flavor,
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)
1130 {
1131 register kern_return_t result;
1132 thread_t thread;
1133
1134 if (task == TASK_NULL || task == kernel_task)
1135 return (KERN_INVALID_ARGUMENT);
1136
1137 result = thread_create_internal(task, -1, (thread_continue_t)thread_bootstrap_return, TH_OPTION_NONE, &thread);
1138 if (result != KERN_SUCCESS)
1139 return (result);
1140
1141 result = machine_thread_set_state(thread, flavor, new_state, new_state_count);
1142 if (result != KERN_SUCCESS) {
1143 task_unlock(task);
1144 lck_mtx_unlock(&tasks_threads_lock);
1145
1146 thread_terminate(thread);
1147 thread_deallocate(thread);
1148 return (result);
1149 }
1150
1151 thread_mtx_lock(thread);
1152 thread_start_internal(thread);
1153 thread_mtx_unlock(thread);
1154
1155 if (from_user)
1156 extmod_statistics_incr_thread_create(task);
1157
1158 task_unlock(task);
1159 lck_mtx_unlock(&tasks_threads_lock);
1160
1161 *new_thread = thread;
1162
1163 return (result);
1164 }
1165
1166 /* Prototype, see justification above */
1167 kern_return_t
1168 thread_create_running(
1169 register task_t task,
1170 int flavor,
1171 thread_state_t new_state,
1172 mach_msg_type_number_t new_state_count,
1173 thread_t *new_thread);
1174
1175 kern_return_t
1176 thread_create_running(
1177 register task_t task,
1178 int flavor,
1179 thread_state_t new_state,
1180 mach_msg_type_number_t new_state_count,
1181 thread_t *new_thread)
1182 {
1183 return thread_create_running_internal2(
1184 task, flavor, new_state, new_state_count,
1185 new_thread, FALSE);
1186 }
1187
1188 kern_return_t
1189 thread_create_running_from_user(
1190 register task_t task,
1191 int flavor,
1192 thread_state_t new_state,
1193 mach_msg_type_number_t new_state_count,
1194 thread_t *new_thread)
1195 {
1196 return thread_create_running_internal2(
1197 task, flavor, new_state, new_state_count,
1198 new_thread, TRUE);
1199 }
1200
1201 kern_return_t
1202 thread_create_workq(
1203 task_t task,
1204 thread_continue_t thread_return,
1205 thread_t *new_thread)
1206 {
1207 kern_return_t result;
1208 thread_t thread;
1209
1210 if (task == TASK_NULL || task == kernel_task)
1211 return (KERN_INVALID_ARGUMENT);
1212
1213 result = thread_create_internal(task, -1, thread_return, TH_OPTION_NOCRED | TH_OPTION_NOSUSP, &thread);
1214 if (result != KERN_SUCCESS)
1215 return (result);
1216
1217 thread->user_stop_count = 1;
1218 thread_hold(thread);
1219 if (task->suspend_count > 0)
1220 thread_hold(thread);
1221
1222 task_unlock(task);
1223 lck_mtx_unlock(&tasks_threads_lock);
1224
1225 *new_thread = thread;
1226
1227 return (KERN_SUCCESS);
1228 }
1229
1230 /*
1231 * kernel_thread_create:
1232 *
1233 * Create a thread in the kernel task
1234 * to execute in kernel context.
1235 */
1236 kern_return_t
1237 kernel_thread_create(
1238 thread_continue_t continuation,
1239 void *parameter,
1240 integer_t priority,
1241 thread_t *new_thread)
1242 {
1243 kern_return_t result;
1244 thread_t thread;
1245 task_t task = kernel_task;
1246
1247 result = thread_create_internal(task, priority, continuation, TH_OPTION_NONE, &thread);
1248 if (result != KERN_SUCCESS)
1249 return (result);
1250
1251 task_unlock(task);
1252 lck_mtx_unlock(&tasks_threads_lock);
1253
1254 stack_alloc(thread);
1255 assert(thread->kernel_stack != 0);
1256 thread->reserved_stack = thread->kernel_stack;
1257
1258 thread->parameter = parameter;
1259
1260 if(debug_task & 1)
1261 kprintf("kernel_thread_create: thread = %p continuation = %p\n", thread, continuation);
1262 *new_thread = thread;
1263
1264 return (result);
1265 }
1266
1267 kern_return_t
1268 kernel_thread_start_priority(
1269 thread_continue_t continuation,
1270 void *parameter,
1271 integer_t priority,
1272 thread_t *new_thread)
1273 {
1274 kern_return_t result;
1275 thread_t thread;
1276
1277 result = kernel_thread_create(continuation, parameter, priority, &thread);
1278 if (result != KERN_SUCCESS)
1279 return (result);
1280
1281 *new_thread = thread;
1282
1283 thread_mtx_lock(thread);
1284 thread_start_internal(thread);
1285 thread_mtx_unlock(thread);
1286
1287 return (result);
1288 }
1289
1290 kern_return_t
1291 kernel_thread_start(
1292 thread_continue_t continuation,
1293 void *parameter,
1294 thread_t *new_thread)
1295 {
1296 return kernel_thread_start_priority(continuation, parameter, -1, new_thread);
1297 }
1298
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 */
1301 static void
1302 retrieve_thread_basic_info(thread_t thread, thread_basic_info_t basic_info)
1303 {
1304 int state, flags;
1305
1306 /* fill in info */
1307
1308 thread_read_times(thread, &basic_info->user_time,
1309 &basic_info->system_time);
1310
1311 /*
1312 * Update lazy-evaluated scheduler info because someone wants it.
1313 */
1314 if (SCHED(can_update_priority)(thread))
1315 SCHED(update_priority)(thread);
1316
1317 basic_info->sleep_time = 0;
1318
1319 /*
1320 * To calculate cpu_usage, first correct for timer rate,
1321 * then for 5/8 ageing. The correction factor [3/5] is
1322 * (1/(5/8) - 1).
1323 */
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;
1330 }
1331 #endif
1332
1333 if (basic_info->cpu_usage > TH_USAGE_SCALE)
1334 basic_info->cpu_usage = TH_USAGE_SCALE;
1335
1336 basic_info->policy = ((thread->sched_mode == TH_MODE_TIMESHARE)?
1337 POLICY_TIMESHARE: POLICY_RR);
1338
1339 flags = 0;
1340 if (thread->options & TH_OPT_IDLE_THREAD)
1341 flags |= TH_FLAGS_IDLE;
1342
1343 if (thread->options & TH_OPT_GLOBAL_FORCED_IDLE) {
1344 flags |= TH_FLAGS_GLOBAL_FORCED_IDLE;
1345 }
1346
1347 if (!thread->kernel_stack)
1348 flags |= TH_FLAGS_SWAPPED;
1349
1350 state = 0;
1351 if (thread->state & TH_TERMINATE)
1352 state = TH_STATE_HALTED;
1353 else
1354 if (thread->state & TH_RUN)
1355 state = TH_STATE_RUNNING;
1356 else
1357 if (thread->state & TH_UNINT)
1358 state = TH_STATE_UNINTERRUPTIBLE;
1359 else
1360 if (thread->state & TH_SUSP)
1361 state = TH_STATE_STOPPED;
1362 else
1363 if (thread->state & TH_WAIT)
1364 state = TH_STATE_WAITING;
1365
1366 basic_info->run_state = state;
1367 basic_info->flags = flags;
1368
1369 basic_info->suspend_count = thread->user_stop_count;
1370
1371 return;
1372 }
1373
1374 kern_return_t
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*/
1380 {
1381 spl_t s;
1382
1383 if (thread == THREAD_NULL)
1384 return (KERN_INVALID_ARGUMENT);
1385
1386 if (flavor == THREAD_BASIC_INFO) {
1387
1388 if (*thread_info_count < THREAD_BASIC_INFO_COUNT)
1389 return (KERN_INVALID_ARGUMENT);
1390
1391 s = splsched();
1392 thread_lock(thread);
1393
1394 retrieve_thread_basic_info(thread, (thread_basic_info_t) thread_info_out);
1395
1396 thread_unlock(thread);
1397 splx(s);
1398
1399 *thread_info_count = THREAD_BASIC_INFO_COUNT;
1400
1401 return (KERN_SUCCESS);
1402 }
1403 else
1404 if (flavor == THREAD_IDENTIFIER_INFO) {
1405 register thread_identifier_info_t identifier_info;
1406
1407 if (*thread_info_count < THREAD_IDENTIFIER_INFO_COUNT)
1408 return (KERN_INVALID_ARGUMENT);
1409
1410 identifier_info = (thread_identifier_info_t) thread_info_out;
1411
1412 s = splsched();
1413 thread_lock(thread);
1414
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);
1418
1419 thread_unlock(thread);
1420 splx(s);
1421 return KERN_SUCCESS;
1422 }
1423 else
1424 if (flavor == THREAD_SCHED_TIMESHARE_INFO) {
1425 policy_timeshare_info_t ts_info;
1426
1427 if (*thread_info_count < POLICY_TIMESHARE_INFO_COUNT)
1428 return (KERN_INVALID_ARGUMENT);
1429
1430 ts_info = (policy_timeshare_info_t)thread_info_out;
1431
1432 s = splsched();
1433 thread_lock(thread);
1434
1435 if (thread->sched_mode != TH_MODE_TIMESHARE) {
1436 thread_unlock(thread);
1437 splx(s);
1438 return (KERN_INVALID_POLICY);
1439 }
1440
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;
1445 }
1446 else {
1447 ts_info->base_priority = thread->base_pri;
1448 ts_info->depress_priority = -1;
1449 }
1450
1451 ts_info->cur_priority = thread->sched_pri;
1452 ts_info->max_priority = thread->max_priority;
1453
1454 thread_unlock(thread);
1455 splx(s);
1456
1457 *thread_info_count = POLICY_TIMESHARE_INFO_COUNT;
1458
1459 return (KERN_SUCCESS);
1460 }
1461 else
1462 if (flavor == THREAD_SCHED_FIFO_INFO) {
1463 if (*thread_info_count < POLICY_FIFO_INFO_COUNT)
1464 return (KERN_INVALID_ARGUMENT);
1465
1466 return (KERN_INVALID_POLICY);
1467 }
1468 else
1469 if (flavor == THREAD_SCHED_RR_INFO) {
1470 policy_rr_info_t rr_info;
1471 uint32_t quantum_time;
1472 uint64_t quantum_ns;
1473
1474 if (*thread_info_count < POLICY_RR_INFO_COUNT)
1475 return (KERN_INVALID_ARGUMENT);
1476
1477 rr_info = (policy_rr_info_t) thread_info_out;
1478
1479 s = splsched();
1480 thread_lock(thread);
1481
1482 if (thread->sched_mode == TH_MODE_TIMESHARE) {
1483 thread_unlock(thread);
1484 splx(s);
1485
1486 return (KERN_INVALID_POLICY);
1487 }
1488
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;
1493 }
1494 else {
1495 rr_info->base_priority = thread->base_pri;
1496 rr_info->depress_priority = -1;
1497 }
1498
1499 quantum_time = SCHED(initial_quantum_size)(THREAD_NULL);
1500 absolutetime_to_nanoseconds(quantum_time, &quantum_ns);
1501
1502 rr_info->max_priority = thread->max_priority;
1503 rr_info->quantum = (uint32_t)(quantum_ns / 1000 / 1000);
1504
1505 thread_unlock(thread);
1506 splx(s);
1507
1508 *thread_info_count = POLICY_RR_INFO_COUNT;
1509
1510 return (KERN_SUCCESS);
1511 }
1512 else
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;
1516
1517 if (*thread_info_count < THREAD_EXTENDED_INFO_COUNT) {
1518 return (KERN_INVALID_ARGUMENT);
1519 }
1520
1521 s = splsched();
1522 thread_lock(thread);
1523
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)
1526 */
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));
1530
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;
1539
1540 bsd_getthreadname(thread->uthread,extended_info->pth_name);
1541
1542 thread_unlock(thread);
1543 splx(s);
1544
1545 *thread_info_count = THREAD_EXTENDED_INFO_COUNT;
1546
1547 return (KERN_SUCCESS);
1548 }
1549 else
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);
1555
1556 if (thread_info_out == NULL)
1557 return (KERN_INVALID_ARGUMENT);
1558
1559 dbg_info = (thread_debug_info_internal_t) thread_info_out;
1560 dbg_info->page_creation_count = thread->t_page_creation_count;
1561
1562 *thread_info_count = THREAD_DEBUG_INFO_INTERNAL_COUNT;
1563 return (KERN_SUCCESS);
1564 #endif /* DEVELOPMENT || DEBUG */
1565 return (KERN_NOT_SUPPORTED);
1566 }
1567
1568 return (KERN_INVALID_ARGUMENT);
1569 }
1570
1571 void
1572 thread_read_times(
1573 thread_t thread,
1574 time_value_t *user_time,
1575 time_value_t *system_time)
1576 {
1577 clock_sec_t secs;
1578 clock_usec_t usecs;
1579 uint64_t tval_user, tval_system;
1580
1581 tval_user = timer_grab(&thread->user_timer);
1582 tval_system = timer_grab(&thread->system_timer);
1583
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;
1588
1589 absolutetime_to_microtime(tval_system, &secs, &usecs);
1590 system_time->seconds = (typeof(system_time->seconds))secs;
1591 system_time->microseconds = usecs;
1592 } else {
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;
1598
1599 system_time->seconds = 0;
1600 system_time->microseconds = 0;
1601 }
1602 }
1603
1604 uint64_t thread_get_runtime_self(void)
1605 {
1606 boolean_t interrupt_state;
1607 uint64_t runtime;
1608 thread_t thread = NULL;
1609 processor_t processor = NULL;
1610
1611 thread = current_thread();
1612
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);
1619
1620 return runtime;
1621 }
1622
1623 kern_return_t
1624 thread_assign(
1625 __unused thread_t thread,
1626 __unused processor_set_t new_pset)
1627 {
1628 return (KERN_FAILURE);
1629 }
1630
1631 /*
1632 * thread_assign_default:
1633 *
1634 * Special version of thread_assign for assigning threads to default
1635 * processor set.
1636 */
1637 kern_return_t
1638 thread_assign_default(
1639 thread_t thread)
1640 {
1641 return (thread_assign(thread, &pset0));
1642 }
1643
1644 /*
1645 * thread_get_assignment
1646 *
1647 * Return current assignment for this thread.
1648 */
1649 kern_return_t
1650 thread_get_assignment(
1651 thread_t thread,
1652 processor_set_t *pset)
1653 {
1654 if (thread == NULL)
1655 return (KERN_INVALID_ARGUMENT);
1656
1657 *pset = &pset0;
1658
1659 return (KERN_SUCCESS);
1660 }
1661
1662 /*
1663 * thread_wire_internal:
1664 *
1665 * Specify that the target thread must always be able
1666 * to run and to allocate memory.
1667 */
1668 kern_return_t
1669 thread_wire_internal(
1670 host_priv_t host_priv,
1671 thread_t thread,
1672 boolean_t wired,
1673 boolean_t *prev_state)
1674 {
1675 if (host_priv == NULL || thread != current_thread())
1676 return (KERN_INVALID_ARGUMENT);
1677
1678 assert(host_priv == &realhost);
1679
1680 if (prev_state)
1681 *prev_state = (thread->options & TH_OPT_VMPRIV) != 0;
1682
1683 if (wired) {
1684 if (!(thread->options & TH_OPT_VMPRIV))
1685 vm_page_free_reserve(1); /* XXX */
1686 thread->options |= TH_OPT_VMPRIV;
1687 }
1688 else {
1689 if (thread->options & TH_OPT_VMPRIV)
1690 vm_page_free_reserve(-1); /* XXX */
1691 thread->options &= ~TH_OPT_VMPRIV;
1692 }
1693
1694 return (KERN_SUCCESS);
1695 }
1696
1697
1698 /*
1699 * thread_wire:
1700 *
1701 * User-api wrapper for thread_wire_internal()
1702 */
1703 kern_return_t
1704 thread_wire(
1705 host_priv_t host_priv,
1706 thread_t thread,
1707 boolean_t wired)
1708 {
1709 return (thread_wire_internal(host_priv, thread, wired, NULL));
1710 }
1711
1712
1713 boolean_t
1714 set_vm_privilege(boolean_t privileged)
1715 {
1716 boolean_t was_vmpriv;
1717
1718 if (current_thread()->options & TH_OPT_VMPRIV)
1719 was_vmpriv = TRUE;
1720 else
1721 was_vmpriv = FALSE;
1722
1723 if (privileged != FALSE)
1724 current_thread()->options |= TH_OPT_VMPRIV;
1725 else
1726 current_thread()->options &= ~TH_OPT_VMPRIV;
1727
1728 return (was_vmpriv);
1729 }
1730
1731
1732 /*
1733 * XXX assuming current thread only, for now...
1734 */
1735 void
1736 thread_guard_violation(thread_t thread, unsigned type)
1737 {
1738 assert(thread == current_thread());
1739
1740 spl_t s = splsched();
1741 /*
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
1745 */
1746 thread->guard_exc_info.type = type;
1747 thread_ast_set(thread, AST_GUARD);
1748 ast_propagate(thread->ast);
1749
1750 splx(s);
1751 }
1752
1753 /*
1754 * guard_ast:
1755 *
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.
1761 */
1762 void
1763 guard_ast(thread_t thread)
1764 {
1765 if (thread->guard_exc_info.type == GUARD_TYPE_MACH_PORT)
1766 mach_port_guard_ast(thread);
1767 else
1768 fd_guard_ast(thread);
1769 }
1770
1771 static void
1772 thread_cputime_callback(int warning, __unused const void *arg0, __unused const void *arg1)
1773 {
1774 if (warning == LEDGER_WARNING_ROSE_ABOVE) {
1775 #if CONFIG_TELEMETRY
1776 /*
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.
1782 */
1783 telemetry_task_ctl(current_task(), TF_CPUMON_WARNING, 1);
1784 #endif
1785 return;
1786 }
1787
1788 #if CONFIG_TELEMETRY
1789 /*
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.
1792 */
1793 telemetry_task_ctl(current_task(), TF_CPUMON_WARNING, 0);
1794 #endif
1795
1796 if (warning == 0) {
1797 THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU__SENDING_EXC_RESOURCE();
1798 }
1799 }
1800
1801 void __attribute__((noinline))
1802 THIS_THREAD_IS_CONSUMING_TOO_MUCH_CPU__SENDING_EXC_RESOURCE(void)
1803 {
1804 int pid = 0;
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;
1812 int action;
1813 uint8_t percentage;
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;
1820
1821 mach_exception_data_type_t code[EXCEPTION_CODE_MAX];
1822 struct ledger_entry_info lei;
1823
1824 assert(thread->t_threadledger != LEDGER_NULL);
1825
1826 /*
1827 * Now that a thread has tripped the monitor, disable it for the entire task.
1828 */
1829 task_lock(task);
1830 if ((task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_PERTHR_LIMIT) == 0) {
1831 /*
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.
1835 */
1836 task_unlock(task);
1837 return;
1838 }
1839 if (task->rusage_cpu_flags & TASK_RUSECPU_FLAGS_FATAL_CPUMON) {
1840 fatal = TRUE;
1841 }
1842 task_disable_cpumon(task);
1843 task_unlock(task);
1844
1845 #ifdef MACH_BSD
1846 pid = proc_selfpid();
1847 if (task->bsd_info != NULL)
1848 procname = proc_name_address(task->bsd_info);
1849 #endif
1850
1851 thread_get_cpulimit(&action, &percentage, &interval_ns);
1852
1853 interval_sec = (uint32_t)(interval_ns / NSEC_PER_SEC);
1854
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);
1858
1859 ledger_get_entry_info(thread->t_threadledger, thread_ledgers.cpu_time, &lei);
1860
1861 absolutetime_to_nanoseconds(lei.lei_balance, &balance_ns);
1862 usage_percent = (uint32_t) ((balance_ns * 100ULL) / lei.lei_last_refill);
1863
1864 /* Show refill period in the same units as balance, limit, etc */
1865 nanoseconds_to_absolutetime(lei.lei_refill_period, &lei.lei_refill_period);
1866
1867 limit_percent = (uint32_t) ((lei.lei_limit * 100ULL) / lei.lei_refill_period);
1868
1869 /* TODO: show task total runtime as well? see TASK_ABSOLUTETIME_INFO */
1870
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);
1874 return;
1875 }
1876
1877 if (audio_active) {
1878 printf("process %s[%d] thread %llu caught burning CPU!; EXC_RESOURCE "
1879 "supressed due to audio playback\n", procname, pid, tid);
1880 return;
1881 }
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",
1887 procname, pid, tid,
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,
1892 lei.lei_balance,
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]" : ""));
1897
1898
1899 code[0] = code[1] = 0;
1900 EXC_RESOURCE_ENCODE_TYPE(code[0], RESOURCE_TYPE_CPU);
1901 if (fatal) {
1902 EXC_RESOURCE_ENCODE_FLAVOR(code[0], FLAVOR_CPU_MONITOR_FATAL);
1903 }else {
1904 EXC_RESOURCE_ENCODE_FLAVOR(code[0], FLAVOR_CPU_MONITOR);
1905 }
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);
1910
1911 if (fatal) {
1912 #if CONFIG_JETSAM
1913 jetsam_on_ledger_cpulimit_exceeded();
1914 #else
1915 task_terminate_internal(task);
1916 #endif
1917 }
1918 }
1919
1920 void thread_update_io_stats(thread_t thread, int size, int io_flags)
1921 {
1922 int io_tier;
1923
1924 if (thread->thread_io_stats == NULL || thread->task->task_io_stats == NULL)
1925 return;
1926
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);
1930 }
1931
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);
1935 }
1936
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);
1940 }
1941
1942 io_tier = ((io_flags & DKIO_TIER_MASK) >> DKIO_TIER_SHIFT);
1943 assert (io_tier < IO_NUM_PRIORITIES);
1944
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);
1947
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);
1951
1952 }
1953
1954 void
1955 init_thread_ledgers(void) {
1956 ledger_template_t t;
1957 int idx;
1958
1959 assert(thread_ledger_template == NULL);
1960
1961 if ((t = ledger_template_create("Per-thread ledger")) == NULL)
1962 panic("couldn't create thread ledger template");
1963
1964 if ((idx = ledger_entry_add(t, "cpu_time", "sched", "ns")) < 0) {
1965 panic("couldn't create cpu_time entry for thread ledger template");
1966 }
1967
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");
1970 }
1971
1972 thread_ledgers.cpu_time = idx;
1973
1974 thread_ledger_template = t;
1975 }
1976
1977 /*
1978 * Returns currently applied CPU usage limit, or 0/0 if none is applied.
1979 */
1980 int
1981 thread_get_cpulimit(int *action, uint8_t *percentage, uint64_t *interval_ns)
1982 {
1983 int64_t abstime = 0;
1984 uint64_t limittime = 0;
1985 thread_t thread = current_thread();
1986
1987 *percentage = 0;
1988 *interval_ns = 0;
1989 *action = 0;
1990
1991 if (thread->t_threadledger == LEDGER_NULL) {
1992 /*
1993 * This thread has no per-thread ledger, so it can't possibly
1994 * have a CPU limit applied.
1995 */
1996 return (KERN_SUCCESS);
1997 }
1998
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);
2001
2002 if ((abstime == LEDGER_LIMIT_INFINITY) || (*interval_ns == 0)) {
2003 /*
2004 * This thread's CPU time ledger has no period or limit; so it
2005 * doesn't have a CPU limit applied.
2006 */
2007 return (KERN_SUCCESS);
2008 }
2009
2010 /*
2011 * This calculation is the converse to the one in thread_set_cpulimit().
2012 */
2013 absolutetime_to_nanoseconds(abstime, &limittime);
2014 *percentage = (limittime * 100ULL) / *interval_ns;
2015 assert(*percentage <= 100);
2016
2017 if (thread->options & TH_OPT_PROC_CPULIMIT) {
2018 assert((thread->options & TH_OPT_PRVT_CPULIMIT) == 0);
2019
2020 *action = THREAD_CPULIMIT_BLOCK;
2021 } else if (thread->options & TH_OPT_PRVT_CPULIMIT) {
2022 assert((thread->options & TH_OPT_PROC_CPULIMIT) == 0);
2023
2024 *action = THREAD_CPULIMIT_EXCEPTION;
2025 } else {
2026 *action = THREAD_CPULIMIT_DISABLE;
2027 }
2028
2029 return (KERN_SUCCESS);
2030 }
2031
2032 /*
2033 * Set CPU usage limit on a thread.
2034 *
2035 * Calling with percentage of 0 will unset the limit for this thread.
2036 */
2037 int
2038 thread_set_cpulimit(int action, uint8_t percentage, uint64_t interval_ns)
2039 {
2040 thread_t thread = current_thread();
2041 ledger_t l;
2042 uint64_t limittime = 0;
2043 uint64_t abstime = 0;
2044
2045 assert(percentage <= 100);
2046
2047 if (action == THREAD_CPULIMIT_DISABLE) {
2048 /*
2049 * Remove CPU limit, if any exists.
2050 */
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);
2056 }
2057
2058 return (0);
2059 }
2060
2061 if (interval_ns < MINIMUM_CPULIMIT_INTERVAL_MS * NSEC_PER_MSEC) {
2062 return (KERN_INVALID_ARGUMENT);
2063 }
2064
2065 l = thread->t_threadledger;
2066 if (l == LEDGER_NULL) {
2067 /*
2068 * This thread doesn't yet have a per-thread ledger; so create one with the CPU time entry active.
2069 */
2070 if ((l = ledger_instantiate(thread_ledger_template, LEDGER_CREATE_INACTIVE_ENTRIES)) == LEDGER_NULL)
2071 return (KERN_RESOURCE_SHORTAGE);
2072
2073 /*
2074 * We are the first to create this thread's ledger, so only activate our entry.
2075 */
2076 ledger_entry_setactive(l, thread_ledgers.cpu_time);
2077 thread->t_threadledger = l;
2078 }
2079
2080 /*
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.
2083 */
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);
2087 /*
2088 * Refill the thread's allotted CPU time every interval_ns nanoseconds.
2089 */
2090 ledger_set_period(l, thread_ledgers.cpu_time, interval_ns);
2091
2092 if (action == THREAD_CPULIMIT_EXCEPTION) {
2093 /*
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.
2096 */
2097 if (thread->options & TH_OPT_PRVT_CPULIMIT) {
2098 panic("CPU usage monitor activated, but blocking thread limit exists");
2099 }
2100
2101 /*
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).
2106 */
2107 thread->options |= TH_OPT_PROC_CPULIMIT;
2108 } else {
2109 /*
2110 * We deliberately override any CPU limit imposed by a task-wide limit (eg
2111 * CPU usage monitor).
2112 */
2113 thread->options &= ~TH_OPT_PROC_CPULIMIT;
2114
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);
2119 }
2120
2121 return (0);
2122 }
2123
2124 static void
2125 sched_call_null(
2126 __unused int type,
2127 __unused thread_t thread)
2128 {
2129 return;
2130 }
2131
2132 void
2133 thread_sched_call(
2134 thread_t thread,
2135 sched_call_t call)
2136 {
2137 thread->sched_call = (call != NULL)? call: sched_call_null;
2138 }
2139
2140 void
2141 thread_static_param(
2142 thread_t thread,
2143 boolean_t state)
2144 {
2145 thread_mtx_lock(thread);
2146 thread->static_param = state;
2147 thread_mtx_unlock(thread);
2148 }
2149
2150 uint64_t
2151 thread_tid(
2152 thread_t thread)
2153 {
2154 return (thread != THREAD_NULL? thread->thread_id: 0);
2155 }
2156
2157 uint16_t thread_set_tag(thread_t th, uint16_t tag) {
2158 return thread_set_tag_internal(th, tag);
2159 }
2160 uint16_t thread_get_tag(thread_t th) {
2161 return thread_get_tag_internal(th);
2162 }
2163
2164 uint64_t
2165 thread_dispatchqaddr(
2166 thread_t thread)
2167 {
2168 uint64_t dispatchqueue_addr = 0;
2169 uint64_t thread_handle = 0;
2170
2171 if (thread != THREAD_NULL) {
2172 thread_handle = thread->machine.cthread_self;
2173
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);
2178 }
2179
2180 return (dispatchqueue_addr);
2181 }
2182
2183 /*
2184 * Export routines to other components for things that are done as macros
2185 * within the osfmk component.
2186 */
2187
2188 #undef thread_reference
2189 void thread_reference(thread_t thread);
2190 void
2191 thread_reference(
2192 thread_t thread)
2193 {
2194 if (thread != THREAD_NULL)
2195 thread_reference_internal(thread);
2196 }
2197
2198 #undef thread_should_halt
2199
2200 boolean_t
2201 thread_should_halt(
2202 thread_t th)
2203 {
2204 return (thread_should_halt_fast(th));
2205 }
2206
2207 /*
2208 * thread_set_voucher_name - reset the voucher port name bound to this thread
2209 *
2210 * Conditions: nothing locked
2211 *
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.
2215 */
2216
2217 kern_return_t
2218 thread_set_voucher_name(mach_port_name_t voucher_name)
2219 {
2220 thread_t thread = current_thread();
2221 ipc_voucher_t new_voucher = IPC_VOUCHER_NULL;
2222 ipc_voucher_t voucher;
2223 #ifdef CONFIG_BANK
2224 ledger_t bankledger = NULL;
2225 #endif
2226
2227 if (MACH_PORT_DEAD == voucher_name)
2228 return KERN_INVALID_RIGHT;
2229
2230 /*
2231 * agressively convert to voucher reference
2232 */
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;
2237 }
2238 #ifdef CONFIG_BANK
2239 bankledger = bank_get_voucher_ledger(new_voucher);
2240 #endif
2241
2242 thread_mtx_lock(thread);
2243 voucher = thread->ith_voucher;
2244 thread->ith_voucher_name = voucher_name;
2245 thread->ith_voucher = new_voucher;
2246 #ifdef CONFIG_BANK
2247 bank_swap_thread_bank_ledger(thread, bankledger);
2248 #endif
2249 thread_mtx_unlock(thread);
2250
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),
2256 1, 0);
2257
2258 if (IPC_VOUCHER_NULL != voucher)
2259 ipc_voucher_release(voucher);
2260
2261 return KERN_SUCCESS;
2262 }
2263
2264 /*
2265 * thread_get_mach_voucher - return a voucher reference for the specified thread voucher
2266 *
2267 * Conditions: nothing locked
2268 *
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
2271 * lookup here.
2272 *
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.
2275 */
2276 kern_return_t
2277 thread_get_mach_voucher(
2278 thread_act_t thread,
2279 mach_voucher_selector_t __unused which,
2280 ipc_voucher_t *voucherp)
2281 {
2282 ipc_voucher_t voucher;
2283 mach_port_name_t voucher_name;
2284
2285 if (THREAD_NULL == thread)
2286 return KERN_INVALID_ARGUMENT;
2287
2288 thread_mtx_lock(thread);
2289 voucher = thread->ith_voucher;
2290
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;
2297 }
2298
2299 voucher_name = thread->ith_voucher_name;
2300
2301 /* convert the name to a port, then voucher reference */
2302 if (MACH_PORT_VALID(voucher_name)) {
2303 ipc_port_t port;
2304
2305 if (KERN_SUCCESS !=
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;
2312 }
2313
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);
2319
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),
2323 (uintptr_t)port,
2324 VM_KERNEL_ADDRPERM((uintptr_t)voucher),
2325 2, 0);
2326
2327
2328 ipc_port_release_send(port);
2329 } else
2330 thread_mtx_unlock(thread);
2331
2332 *voucherp = voucher;
2333 return KERN_SUCCESS;
2334 }
2335
2336 /*
2337 * thread_set_mach_voucher - set a voucher reference for the specified thread voucher
2338 *
2339 * Conditions: callers holds a reference on the voucher.
2340 * nothing locked.
2341 *
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
2344 * discarded.
2345 */
2346 kern_return_t
2347 thread_set_mach_voucher(
2348 thread_t thread,
2349 ipc_voucher_t voucher)
2350 {
2351 ipc_voucher_t old_voucher;
2352 #ifdef CONFIG_BANK
2353 ledger_t bankledger = NULL;
2354 #endif
2355
2356 if (THREAD_NULL == thread)
2357 return KERN_INVALID_ARGUMENT;
2358
2359 if (thread != current_thread() || thread->started)
2360 return KERN_INVALID_ARGUMENT;
2361
2362
2363 ipc_voucher_reference(voucher);
2364 #ifdef CONFIG_BANK
2365 bankledger = bank_get_voucher_ledger(voucher);
2366 #endif
2367 thread_mtx_lock(thread);
2368 old_voucher = thread->ith_voucher;
2369 thread->ith_voucher = voucher;
2370 thread->ith_voucher_name = MACH_PORT_NULL;
2371 #ifdef CONFIG_BANK
2372 bank_swap_thread_bank_ledger(thread, bankledger);
2373 #endif
2374 thread_mtx_unlock(thread);
2375
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),
2381 3, 0);
2382
2383 ipc_voucher_release(old_voucher);
2384
2385 return KERN_SUCCESS;
2386 }
2387
2388 /*
2389 * thread_swap_mach_voucher - swap a voucher reference for the specified thread voucher
2390 *
2391 * Conditions: callers holds a reference on the new and presumed old voucher(s).
2392 * nothing locked.
2393 *
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.
2397 */
2398 kern_return_t
2399 thread_swap_mach_voucher(
2400 thread_t thread,
2401 ipc_voucher_t new_voucher,
2402 ipc_voucher_t *in_out_old_voucher)
2403 {
2404 mach_port_name_t old_voucher_name;
2405 ipc_voucher_t old_voucher;
2406 #ifdef CONFIG_BANK
2407 ledger_t bankledger = NULL;
2408 #endif
2409
2410 if (THREAD_NULL == thread)
2411 return KERN_INVALID_TASK;
2412
2413 if (thread != current_thread() || thread->started)
2414 return KERN_INVALID_ARGUMENT;
2415
2416 #ifdef CONFIG_BANK
2417 bankledger = bank_get_voucher_ledger(new_voucher);
2418 #endif
2419
2420 thread_mtx_lock(thread);
2421
2422 old_voucher = thread->ith_voucher;
2423
2424 if (IPC_VOUCHER_NULL == old_voucher) {
2425 old_voucher_name = thread->ith_voucher_name;
2426
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;
2432
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),
2438 4, 0);
2439
2440 }
2441 }
2442
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;
2448 #ifdef CONFIG_BANK
2449 bank_swap_thread_bank_ledger(thread, bankledger);
2450 #endif
2451 thread_mtx_unlock(thread);
2452
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),
2458 5, 0);
2459
2460 ipc_voucher_release(old_voucher);
2461
2462 *in_out_old_voucher = IPC_VOUCHER_NULL;
2463 return KERN_SUCCESS;
2464 }
2465
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;
2471 }
2472
2473 /*
2474 * thread_get_current_voucher_origin_pid - get the pid of the originator of the current voucher.
2475 */
2476 kern_return_t
2477 thread_get_current_voucher_origin_pid(
2478 int32_t *pid)
2479 {
2480 uint32_t buf_size;
2481 kern_return_t kr;
2482 thread_t thread = current_thread();
2483
2484 buf_size = sizeof(*pid);
2485 kr = mach_voucher_attr_command(thread->ith_voucher,
2486 MACH_VOUCHER_ATTR_KEY_BANK,
2487 BANK_ORIGINATOR_PID,
2488 NULL,
2489 0,
2490 (mach_voucher_attr_content_t)pid,
2491 &buf_size);
2492
2493 return kr;
2494 }
2495
2496 /*
2497 * thread_enable_send_importance - set/clear the SEND_IMPORTANCE thread option bit.
2498 */
2499 void thread_enable_send_importance(thread_t thread, boolean_t enable)
2500 {
2501 if (enable == TRUE)
2502 thread->options |= TH_OPT_SEND_IMPORTANCE;
2503 else
2504 thread->options &= ~TH_OPT_SEND_IMPORTANCE;
2505 }
2506
2507 #if CONFIG_DTRACE
2508 uint32_t dtrace_get_thread_predcache(thread_t thread)
2509 {
2510 if (thread != THREAD_NULL)
2511 return thread->t_dtrace_predcache;
2512 else
2513 return 0;
2514 }
2515
2516 int64_t dtrace_get_thread_vtime(thread_t thread)
2517 {
2518 if (thread != THREAD_NULL)
2519 return thread->t_dtrace_vtime;
2520 else
2521 return 0;
2522 }
2523
2524 int dtrace_get_thread_last_cpu_id(thread_t thread)
2525 {
2526 if ((thread != THREAD_NULL) && (thread->last_processor != PROCESSOR_NULL)) {
2527 return thread->last_processor->cpu_id;
2528 } else {
2529 return -1;
2530 }
2531 }
2532
2533 int64_t dtrace_get_thread_tracing(thread_t thread)
2534 {
2535 if (thread != THREAD_NULL)
2536 return thread->t_dtrace_tracing;
2537 else
2538 return 0;
2539 }
2540
2541 boolean_t dtrace_get_thread_reentering(thread_t thread)
2542 {
2543 if (thread != THREAD_NULL)
2544 return (thread->options & TH_OPT_DTRACE) ? TRUE : FALSE;
2545 else
2546 return 0;
2547 }
2548
2549 vm_offset_t dtrace_get_kernel_stack(thread_t thread)
2550 {
2551 if (thread != THREAD_NULL)
2552 return thread->kernel_stack;
2553 else
2554 return 0;
2555 }
2556
2557 int64_t dtrace_calc_thread_recent_vtime(thread_t thread)
2558 {
2559 if (thread != THREAD_NULL) {
2560 processor_t processor = current_processor();
2561 uint64_t abstime = mach_absolute_time();
2562 timer_t timer;
2563
2564 timer = PROCESSOR_DATA(processor, thread_timer);
2565
2566 return timer_grab(&(thread->system_timer)) + timer_grab(&(thread->user_timer)) +
2567 (abstime - timer->tstamp); /* XXX need interrupts off to prevent missed time? */
2568 } else
2569 return 0;
2570 }
2571
2572 void dtrace_set_thread_predcache(thread_t thread, uint32_t predcache)
2573 {
2574 if (thread != THREAD_NULL)
2575 thread->t_dtrace_predcache = predcache;
2576 }
2577
2578 void dtrace_set_thread_vtime(thread_t thread, int64_t vtime)
2579 {
2580 if (thread != THREAD_NULL)
2581 thread->t_dtrace_vtime = vtime;
2582 }
2583
2584 void dtrace_set_thread_tracing(thread_t thread, int64_t accum)
2585 {
2586 if (thread != THREAD_NULL)
2587 thread->t_dtrace_tracing = accum;
2588 }
2589
2590 void dtrace_set_thread_reentering(thread_t thread, boolean_t vbool)
2591 {
2592 if (thread != THREAD_NULL) {
2593 if (vbool)
2594 thread->options |= TH_OPT_DTRACE;
2595 else
2596 thread->options &= (~TH_OPT_DTRACE);
2597 }
2598 }
2599
2600 vm_offset_t dtrace_set_thread_recover(thread_t thread, vm_offset_t recover)
2601 {
2602 vm_offset_t prev = 0;
2603
2604 if (thread != THREAD_NULL) {
2605 prev = thread->recover;
2606 thread->recover = recover;
2607 }
2608 return prev;
2609 }
2610
2611 void dtrace_thread_bootstrap(void)
2612 {
2613 task_t task = current_task();
2614
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);
2620 }
2621 DTRACE_PROC(start);
2622 }
2623 DTRACE_PROC(lwp__start);
2624
2625 }
2626
2627 void
2628 dtrace_thread_didexec(thread_t thread)
2629 {
2630 thread->t_dtrace_flags |= TH_DTRACE_EXECSUCCESS;
2631 }
2632 #endif /* CONFIG_DTRACE */