2 * Copyright (c) 2000-2016 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.
63 * Scheduling primitives
69 #include <mach/mach_types.h>
70 #include <mach/machine.h>
71 #include <mach/policy.h>
72 #include <mach/sync_policy.h>
73 #include <mach/thread_act.h>
75 #include <machine/machine_routines.h>
76 #include <machine/sched_param.h>
77 #include <machine/machine_cpu.h>
78 #include <machine/limits.h>
79 #include <machine/atomic.h>
81 #include <machine/commpage.h>
83 #include <kern/kern_types.h>
84 #include <kern/backtrace.h>
85 #include <kern/clock.h>
86 #include <kern/counters.h>
87 #include <kern/cpu_number.h>
88 #include <kern/cpu_data.h>
90 #include <kern/debug.h>
91 #include <kern/macro_help.h>
92 #include <kern/machine.h>
93 #include <kern/misc_protos.h>
95 #include <kern/monotonic.h>
96 #endif /* MONOTONIC */
97 #include <kern/processor.h>
98 #include <kern/queue.h>
99 #include <kern/sched.h>
100 #include <kern/sched_prim.h>
101 #include <kern/sfi.h>
102 #include <kern/syscall_subr.h>
103 #include <kern/task.h>
104 #include <kern/thread.h>
105 #include <kern/ledger.h>
106 #include <kern/timer_queue.h>
107 #include <kern/waitq.h>
108 #include <kern/policy_internal.h>
109 #include <kern/cpu_quiesce.h>
112 #include <vm/vm_kern.h>
113 #include <vm/vm_map.h>
114 #include <vm/vm_pageout.h>
116 #include <mach/sdt.h>
117 #include <mach/mach_host.h>
118 #include <mach/host_info.h>
120 #include <sys/kdebug.h>
121 #include <kperf/kperf.h>
122 #include <kern/kpc.h>
123 #include <san/kasan.h>
124 #include <kern/pms.h>
125 #include <kern/host.h>
126 #include <stdatomic.h>
129 rt_runq_count(processor_set_t pset
)
131 return atomic_load_explicit(&SCHED(rt_runq
)(pset
)->count
, memory_order_relaxed
);
135 rt_runq_count_incr(processor_set_t pset
)
137 atomic_fetch_add_explicit(&SCHED(rt_runq
)(pset
)->count
, 1, memory_order_relaxed
);
141 rt_runq_count_decr(processor_set_t pset
)
143 atomic_fetch_sub_explicit(&SCHED(rt_runq
)(pset
)->count
, 1, memory_order_relaxed
);
146 #define DEFAULT_PREEMPTION_RATE 100 /* (1/s) */
147 int default_preemption_rate
= DEFAULT_PREEMPTION_RATE
;
149 #define DEFAULT_BG_PREEMPTION_RATE 400 /* (1/s) */
150 int default_bg_preemption_rate
= DEFAULT_BG_PREEMPTION_RATE
;
152 #define MAX_UNSAFE_QUANTA 800
153 int max_unsafe_quanta
= MAX_UNSAFE_QUANTA
;
155 #define MAX_POLL_QUANTA 2
156 int max_poll_quanta
= MAX_POLL_QUANTA
;
158 #define SCHED_POLL_YIELD_SHIFT 4 /* 1/16 */
159 int sched_poll_yield_shift
= SCHED_POLL_YIELD_SHIFT
;
161 uint64_t max_poll_computation
;
163 uint64_t max_unsafe_computation
;
164 uint64_t sched_safe_duration
;
166 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
168 uint32_t std_quantum
;
169 uint32_t min_std_quantum
;
172 uint32_t std_quantum_us
;
173 uint32_t bg_quantum_us
;
175 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
177 uint32_t thread_depress_time
;
178 uint32_t default_timeshare_computation
;
179 uint32_t default_timeshare_constraint
;
181 uint32_t max_rt_quantum
;
182 uint32_t min_rt_quantum
;
184 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
187 uint32_t sched_tick_interval
;
189 /* Timeshare load calculation interval (15ms) */
190 uint32_t sched_load_compute_interval_us
= 15000;
191 uint64_t sched_load_compute_interval_abs
;
192 static _Atomic
uint64_t sched_load_compute_deadline
;
194 uint32_t sched_pri_shifts
[TH_BUCKET_MAX
];
195 uint32_t sched_fixed_shift
;
197 uint32_t sched_decay_usage_age_factor
= 1; /* accelerate 5/8^n usage aging */
199 /* Allow foreground to decay past default to resolve inversions */
200 #define DEFAULT_DECAY_BAND_LIMIT ((BASEPRI_FOREGROUND - BASEPRI_DEFAULT) + 2)
201 int sched_pri_decay_band_limit
= DEFAULT_DECAY_BAND_LIMIT
;
203 /* Defaults for timer deadline profiling */
204 #define TIMER_DEADLINE_TRACKING_BIN_1_DEFAULT 2000000 /* Timers with deadlines <=
206 #define TIMER_DEADLINE_TRACKING_BIN_2_DEFAULT 5000000 /* Timers with deadlines
209 uint64_t timer_deadline_tracking_bin_1
;
210 uint64_t timer_deadline_tracking_bin_2
;
212 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
214 thread_t sched_maintenance_thread
;
216 /* interrupts disabled lock to guard recommended cores state */
217 decl_simple_lock_data(static, sched_recommended_cores_lock
);
218 static uint64_t usercontrol_requested_recommended_cores
= ALL_CORES_RECOMMENDED
;
219 static void sched_update_recommended_cores(uint64_t recommended_cores
);
221 #if __arm__ || __arm64__
222 static void sched_recommended_cores_maintenance(void);
223 uint64_t perfcontrol_failsafe_starvation_threshold
;
224 extern char *proc_name_address(struct proc
*p
);
225 #endif /* __arm__ || __arm64__ */
227 uint64_t sched_one_second_interval
;
231 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
233 static void load_shift_init(void);
234 static void preempt_pri_init(void);
236 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
238 thread_t
processor_idle(
240 processor_t processor
);
245 processor_t processor
,
246 processor_set_t pset
,
249 static void processor_setrun(
250 processor_t processor
,
255 sched_realtime_timebase_init(void);
258 sched_timer_deadline_tracking_init(void);
261 extern int debug_task
;
262 #define TLOG(a, fmt, args...) if(debug_task & a) kprintf(fmt, ## args)
264 #define TLOG(a, fmt, args...) do {} while (0)
268 thread_bind_internal(
270 processor_t processor
);
273 sched_vm_group_maintenance(void);
275 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
276 int8_t sched_load_shifts
[NRQS
];
277 bitmap_t sched_preempt_pri
[BITMAP_LEN(NRQS_MAX
)];
278 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
281 * Statically allocate a buffer to hold the longest possible
282 * scheduler description string, as currently implemented.
283 * bsd/kern/kern_sysctl.c has a corresponding definition in bsd/
284 * to export to userspace via sysctl(3). If either version
285 * changes, update the other.
287 * Note that in addition to being an upper bound on the strings
288 * in the kernel, it's also an exact parameter to PE_get_default(),
289 * which interrogates the device tree on some platforms. That
290 * API requires the caller know the exact size of the device tree
291 * property, so we need both a legacy size (32) and the current size
292 * (48) to deal with old and new device trees. The device tree property
293 * is similarly padded to a fixed size so that the same kernel image
294 * can run on multiple devices with different schedulers configured
295 * in the device tree.
297 char sched_string
[SCHED_STRING_MAX_LENGTH
];
299 uint32_t sched_debug_flags
= SCHED_DEBUG_FLAG_CHOOSE_PROCESSOR_TRACEPOINTS
;
301 /* Global flag which indicates whether Background Stepper Context is enabled */
302 static int cpu_throttle_enabled
= 1;
307 kprintf("Scheduler: Default of %s\n", SCHED(sched_name
));
309 if (!PE_parse_boot_argn("sched_pri_decay_limit", &sched_pri_decay_band_limit
, sizeof(sched_pri_decay_band_limit
))) {
310 /* No boot-args, check in device tree */
311 if (!PE_get_default("kern.sched_pri_decay_limit",
312 &sched_pri_decay_band_limit
,
313 sizeof(sched_pri_decay_band_limit
))) {
314 /* Allow decay all the way to normal limits */
315 sched_pri_decay_band_limit
= DEFAULT_DECAY_BAND_LIMIT
;
319 kprintf("Setting scheduler priority decay band limit %d\n", sched_pri_decay_band_limit
);
321 if (PE_parse_boot_argn("sched_debug", &sched_debug_flags
, sizeof(sched_debug_flags
))) {
322 kprintf("Scheduler: Debug flags 0x%08x\n", sched_debug_flags
);
324 strlcpy(sched_string
, SCHED(sched_name
), sizeof(sched_string
));
326 cpu_quiescent_counter_init();
329 SCHED(rt_init
)(&pset0
);
330 sched_timer_deadline_tracking_init();
332 SCHED(pset_init
)(&pset0
);
333 SCHED(processor_init
)(master_processor
);
337 sched_timebase_init(void)
341 clock_interval_to_absolutetime_interval(1, NSEC_PER_SEC
, &abstime
);
342 sched_one_second_interval
= abstime
;
344 SCHED(timebase_init
)();
345 sched_realtime_timebase_init();
348 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
351 sched_timeshare_init(void)
354 * Calculate the timeslicing quantum
357 if (default_preemption_rate
< 1) {
358 default_preemption_rate
= DEFAULT_PREEMPTION_RATE
;
360 std_quantum_us
= (1000 * 1000) / default_preemption_rate
;
362 printf("standard timeslicing quantum is %d us\n", std_quantum_us
);
364 if (default_bg_preemption_rate
< 1) {
365 default_bg_preemption_rate
= DEFAULT_BG_PREEMPTION_RATE
;
367 bg_quantum_us
= (1000 * 1000) / default_bg_preemption_rate
;
369 printf("standard background quantum is %d us\n", bg_quantum_us
);
377 sched_timeshare_timebase_init(void)
382 /* standard timeslicing quantum */
383 clock_interval_to_absolutetime_interval(
384 std_quantum_us
, NSEC_PER_USEC
, &abstime
);
385 assert((abstime
>> 32) == 0 && (uint32_t)abstime
!= 0);
386 std_quantum
= (uint32_t)abstime
;
388 /* smallest remaining quantum (250 us) */
389 clock_interval_to_absolutetime_interval(250, NSEC_PER_USEC
, &abstime
);
390 assert((abstime
>> 32) == 0 && (uint32_t)abstime
!= 0);
391 min_std_quantum
= (uint32_t)abstime
;
393 /* quantum for background tasks */
394 clock_interval_to_absolutetime_interval(
395 bg_quantum_us
, NSEC_PER_USEC
, &abstime
);
396 assert((abstime
>> 32) == 0 && (uint32_t)abstime
!= 0);
397 bg_quantum
= (uint32_t)abstime
;
399 /* scheduler tick interval */
400 clock_interval_to_absolutetime_interval(USEC_PER_SEC
>> SCHED_TICK_SHIFT
,
401 NSEC_PER_USEC
, &abstime
);
402 assert((abstime
>> 32) == 0 && (uint32_t)abstime
!= 0);
403 sched_tick_interval
= (uint32_t)abstime
;
405 /* timeshare load calculation interval & deadline initialization */
406 clock_interval_to_absolutetime_interval(sched_load_compute_interval_us
, NSEC_PER_USEC
, &sched_load_compute_interval_abs
);
407 sched_load_compute_deadline
= sched_load_compute_interval_abs
;
410 * Compute conversion factor from usage to
411 * timesharing priorities with 5/8 ** n aging.
413 abstime
= (abstime
* 5) / 3;
414 for (shift
= 0; abstime
> BASEPRI_DEFAULT
; ++shift
) {
417 sched_fixed_shift
= shift
;
419 for (uint32_t i
= 0; i
< TH_BUCKET_MAX
; i
++) {
420 sched_pri_shifts
[i
] = INT8_MAX
;
423 max_unsafe_computation
= ((uint64_t)max_unsafe_quanta
) * std_quantum
;
424 sched_safe_duration
= 2 * ((uint64_t)max_unsafe_quanta
) * std_quantum
;
426 max_poll_computation
= ((uint64_t)max_poll_quanta
) * std_quantum
;
427 thread_depress_time
= 1 * std_quantum
;
428 default_timeshare_computation
= std_quantum
/ 2;
429 default_timeshare_constraint
= std_quantum
;
431 #if __arm__ || __arm64__
432 perfcontrol_failsafe_starvation_threshold
= (2 * sched_tick_interval
);
433 #endif /* __arm__ || __arm64__ */
436 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
439 pset_rt_init(processor_set_t pset
)
443 os_atomic_init(&pset
->rt_runq
.count
, 0);
444 queue_init(&pset
->rt_runq
.queue
);
445 memset(&pset
->rt_runq
.runq_stats
, 0, sizeof pset
->rt_runq
.runq_stats
);
449 sched_rtglobal_runq(processor_set_t pset
)
453 return &pset0
.rt_runq
;
457 sched_rtglobal_init(processor_set_t pset
)
459 if (pset
== &pset0
) {
460 return pset_rt_init(pset
);
463 /* Only pset0 rt_runq is used, so make it easy to detect
464 * buggy accesses to others.
466 memset(&pset
->rt_runq
, 0xfd, sizeof pset
->rt_runq
);
470 sched_rtglobal_queue_shutdown(processor_t processor
)
476 sched_realtime_timebase_init(void)
480 /* smallest rt computaton (50 us) */
481 clock_interval_to_absolutetime_interval(50, NSEC_PER_USEC
, &abstime
);
482 assert((abstime
>> 32) == 0 && (uint32_t)abstime
!= 0);
483 min_rt_quantum
= (uint32_t)abstime
;
485 /* maximum rt computation (50 ms) */
486 clock_interval_to_absolutetime_interval(
487 50, 1000 * NSEC_PER_USEC
, &abstime
);
488 assert((abstime
>> 32) == 0 && (uint32_t)abstime
!= 0);
489 max_rt_quantum
= (uint32_t)abstime
;
493 sched_check_spill(processor_set_t pset
, thread_t thread
)
502 sched_thread_should_yield(processor_t processor
, thread_t thread
)
506 return !SCHED(processor_queue_empty
)(processor
) || rt_runq_count(processor
->processor_set
) > 0;
509 /* Default implementations of .steal_thread_enabled */
511 sched_steal_thread_DISABLED(processor_set_t pset
)
518 sched_steal_thread_enabled(processor_set_t pset
)
520 return pset
->node
->pset_count
> 1;
523 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
526 * Set up values for timeshare
530 load_shift_init(void)
532 int8_t k
, *p
= sched_load_shifts
;
535 uint32_t sched_decay_penalty
= 1;
537 if (PE_parse_boot_argn("sched_decay_penalty", &sched_decay_penalty
, sizeof(sched_decay_penalty
))) {
538 kprintf("Overriding scheduler decay penalty %u\n", sched_decay_penalty
);
541 if (PE_parse_boot_argn("sched_decay_usage_age_factor", &sched_decay_usage_age_factor
, sizeof(sched_decay_usage_age_factor
))) {
542 kprintf("Overriding scheduler decay usage age factor %u\n", sched_decay_usage_age_factor
);
545 if (sched_decay_penalty
== 0) {
547 * There is no penalty for timeshare threads for using too much
548 * CPU, so set all load shifts to INT8_MIN. Even under high load,
549 * sched_pri_shift will be >INT8_MAX, and there will be no
550 * penalty applied to threads (nor will sched_usage be updated per
553 for (i
= 0; i
< NRQS
; i
++) {
554 sched_load_shifts
[i
] = INT8_MIN
;
560 *p
++ = INT8_MIN
; *p
++ = 0;
563 * For a given system load "i", the per-thread priority
564 * penalty per quantum of CPU usage is ~2^k priority
565 * levels. "sched_decay_penalty" can cause more
566 * array entries to be filled with smaller "k" values
568 for (i
= 2, j
= 1 << sched_decay_penalty
, k
= 1; i
< NRQS
; ++k
) {
569 for (j
<<= 1; (i
< j
) && (i
< NRQS
); ++i
) {
576 preempt_pri_init(void)
578 bitmap_t
*p
= sched_preempt_pri
;
580 for (int i
= BASEPRI_FOREGROUND
; i
< MINPRI_KERNEL
; ++i
) {
584 for (int i
= BASEPRI_PREEMPT
; i
<= MAXPRI
; ++i
) {
589 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
592 * Thread wait timer expiration.
599 thread_t thread
= p0
;
602 assert_thread_magic(thread
);
606 if (--thread
->wait_timer_active
== 0) {
607 if (thread
->wait_timer_is_set
) {
608 thread
->wait_timer_is_set
= FALSE
;
609 clear_wait_internal(thread
, THREAD_TIMED_OUT
);
612 thread_unlock(thread
);
619 * Unblock thread on wake up.
621 * Returns TRUE if the thread should now be placed on the runqueue.
623 * Thread must be locked.
625 * Called at splsched().
630 wait_result_t wresult
)
632 boolean_t ready_for_runq
= FALSE
;
633 thread_t cthread
= current_thread();
634 uint32_t new_run_count
;
635 int old_thread_state
;
640 thread
->wait_result
= wresult
;
643 * Cancel pending wait timer.
645 if (thread
->wait_timer_is_set
) {
646 if (timer_call_cancel(&thread
->wait_timer
)) {
647 thread
->wait_timer_active
--;
649 thread
->wait_timer_is_set
= FALSE
;
653 * Update scheduling state: not waiting,
656 old_thread_state
= thread
->state
;
657 thread
->state
= (old_thread_state
| TH_RUN
) &
658 ~(TH_WAIT
| TH_UNINT
| TH_WAIT_REPORT
);
660 if ((old_thread_state
& TH_RUN
) == 0) {
661 uint64_t ctime
= mach_approximate_time();
662 thread
->last_made_runnable_time
= thread
->last_basepri_change_time
= ctime
;
663 timer_start(&thread
->runnable_timer
, ctime
);
665 ready_for_runq
= TRUE
;
667 if (old_thread_state
& TH_WAIT_REPORT
) {
668 (*thread
->sched_call
)(SCHED_CALL_UNBLOCK
, thread
);
671 /* Update the runnable thread count */
672 new_run_count
= SCHED(run_count_incr
)(thread
);
675 * Either the thread is idling in place on another processor,
676 * or it hasn't finished context switching yet.
678 assert((thread
->state
& TH_IDLE
) == 0);
680 * The run count is only dropped after the context switch completes
681 * and the thread is still waiting, so we should not run_incr here
683 new_run_count
= os_atomic_load(&sched_run_buckets
[TH_BUCKET_RUN
], relaxed
);
688 * Calculate deadline for real-time threads.
690 if (thread
->sched_mode
== TH_MODE_REALTIME
) {
693 ctime
= mach_absolute_time();
694 thread
->realtime
.deadline
= thread
->realtime
.constraint
+ ctime
;
698 * Clear old quantum, fail-safe computation, etc.
700 thread
->quantum_remaining
= 0;
701 thread
->computation_metered
= 0;
702 thread
->reason
= AST_NONE
;
703 thread
->block_hint
= kThreadWaitNone
;
705 /* Obtain power-relevant interrupt and "platform-idle exit" statistics.
706 * We also account for "double hop" thread signaling via
707 * the thread callout infrastructure.
708 * DRK: consider removing the callout wakeup counters in the future
709 * they're present for verification at the moment.
711 boolean_t aticontext
, pidle
;
712 ml_get_power_state(&aticontext
, &pidle
);
714 if (__improbable(aticontext
&& !(thread_get_tag_internal(thread
) & THREAD_TAG_CALLOUT
))) {
715 DTRACE_SCHED2(iwakeup
, struct thread
*, thread
, struct proc
*, thread
->task
->bsd_info
);
717 uint64_t ttd
= PROCESSOR_DATA(current_processor(), timer_call_ttd
);
720 if (ttd
<= timer_deadline_tracking_bin_1
) {
721 thread
->thread_timer_wakeups_bin_1
++;
722 } else if (ttd
<= timer_deadline_tracking_bin_2
) {
723 thread
->thread_timer_wakeups_bin_2
++;
727 ledger_credit_thread(thread
, thread
->t_ledger
,
728 task_ledgers
.interrupt_wakeups
, 1);
730 ledger_credit_thread(thread
, thread
->t_ledger
,
731 task_ledgers
.platform_idle_wakeups
, 1);
733 } else if (thread_get_tag_internal(cthread
) & THREAD_TAG_CALLOUT
) {
734 /* TODO: what about an interrupt that does a wake taken on a callout thread? */
735 if (cthread
->callout_woken_from_icontext
) {
736 ledger_credit_thread(thread
, thread
->t_ledger
,
737 task_ledgers
.interrupt_wakeups
, 1);
738 thread
->thread_callout_interrupt_wakeups
++;
740 if (cthread
->callout_woken_from_platform_idle
) {
741 ledger_credit_thread(thread
, thread
->t_ledger
,
742 task_ledgers
.platform_idle_wakeups
, 1);
743 thread
->thread_callout_platform_idle_wakeups
++;
746 cthread
->callout_woke_thread
= TRUE
;
750 if (thread_get_tag_internal(thread
) & THREAD_TAG_CALLOUT
) {
751 thread
->callout_woken_from_icontext
= aticontext
;
752 thread
->callout_woken_from_platform_idle
= pidle
;
753 thread
->callout_woke_thread
= FALSE
;
757 if (ready_for_runq
) {
758 kperf_make_runnable(thread
, aticontext
);
762 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
763 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_MAKE_RUNNABLE
) | DBG_FUNC_NONE
,
764 (uintptr_t)thread_tid(thread
), thread
->sched_pri
, thread
->wait_result
,
765 sched_run_buckets
[TH_BUCKET_RUN
], 0);
767 DTRACE_SCHED2(wakeup
, struct thread
*, thread
, struct proc
*, thread
->task
->bsd_info
);
769 return ready_for_runq
;
775 * Unblock and dispatch thread.
777 * thread lock held, IPC locks may be held.
778 * thread must have been pulled from wait queue under same lock hold.
779 * thread must have been waiting
781 * KERN_SUCCESS - Thread was set running
783 * TODO: This should return void
788 wait_result_t wresult
)
790 assert_thread_magic(thread
);
792 assert(thread
->at_safe_point
== FALSE
);
793 assert(thread
->wait_event
== NO_EVENT64
);
794 assert(thread
->waitq
== NULL
);
796 assert(!(thread
->state
& (TH_TERMINATE
| TH_TERMINATE2
)));
797 assert(thread
->state
& TH_WAIT
);
800 if (thread_unblock(thread
, wresult
)) {
801 #if SCHED_TRACE_THREAD_WAKEUPS
802 backtrace(&thread
->thread_wakeup_bt
[0],
803 (sizeof(thread
->thread_wakeup_bt
) / sizeof(uintptr_t)), NULL
);
805 thread_setrun(thread
, SCHED_PREEMPT
| SCHED_TAILQ
);
812 * Routine: thread_mark_wait_locked
814 * Mark a thread as waiting. If, given the circumstances,
815 * it doesn't want to wait (i.e. already aborted), then
816 * indicate that in the return value.
818 * at splsched() and thread is locked.
822 thread_mark_wait_locked(
824 wait_interrupt_t interruptible_orig
)
826 boolean_t at_safe_point
;
827 wait_interrupt_t interruptible
= interruptible_orig
;
829 if (thread
->state
& TH_IDLE
) {
830 panic("Invalid attempt to wait while running the idle thread");
833 assert(!(thread
->state
& (TH_WAIT
| TH_IDLE
| TH_UNINT
| TH_TERMINATE2
| TH_WAIT_REPORT
)));
836 * The thread may have certain types of interrupts/aborts masked
837 * off. Even if the wait location says these types of interrupts
838 * are OK, we have to honor mask settings (outer-scoped code may
839 * not be able to handle aborts at the moment).
841 interruptible
&= TH_OPT_INTMASK
;
842 if (interruptible
> (thread
->options
& TH_OPT_INTMASK
)) {
843 interruptible
= thread
->options
& TH_OPT_INTMASK
;
846 at_safe_point
= (interruptible
== THREAD_ABORTSAFE
);
848 if (interruptible
== THREAD_UNINT
||
849 !(thread
->sched_flags
& TH_SFLAG_ABORT
) ||
851 (thread
->sched_flags
& TH_SFLAG_ABORTSAFELY
))) {
852 if (!(thread
->state
& TH_TERMINATE
)) {
856 int state_bits
= TH_WAIT
;
857 if (!interruptible
) {
858 state_bits
|= TH_UNINT
;
860 if (thread
->sched_call
) {
861 wait_interrupt_t mask
= THREAD_WAIT_NOREPORT_USER
;
862 if (is_kerneltask(thread
->task
)) {
863 mask
= THREAD_WAIT_NOREPORT_KERNEL
;
865 if ((interruptible_orig
& mask
) == 0) {
866 state_bits
|= TH_WAIT_REPORT
;
869 thread
->state
|= state_bits
;
870 thread
->at_safe_point
= at_safe_point
;
872 /* TODO: pass this through assert_wait instead, have
873 * assert_wait just take a struct as an argument */
874 assert(!thread
->block_hint
);
875 thread
->block_hint
= thread
->pending_block_hint
;
876 thread
->pending_block_hint
= kThreadWaitNone
;
878 return thread
->wait_result
= THREAD_WAITING
;
880 if (thread
->sched_flags
& TH_SFLAG_ABORTSAFELY
) {
881 thread
->sched_flags
&= ~TH_SFLAG_ABORTED_MASK
;
884 thread
->pending_block_hint
= kThreadWaitNone
;
886 return thread
->wait_result
= THREAD_INTERRUPTED
;
890 * Routine: thread_interrupt_level
892 * Set the maximum interruptible state for the
893 * current thread. The effective value of any
894 * interruptible flag passed into assert_wait
895 * will never exceed this.
897 * Useful for code that must not be interrupted,
898 * but which calls code that doesn't know that.
900 * The old interrupt level for the thread.
904 thread_interrupt_level(
905 wait_interrupt_t new_level
)
907 thread_t thread
= current_thread();
908 wait_interrupt_t result
= thread
->options
& TH_OPT_INTMASK
;
910 thread
->options
= (thread
->options
& ~TH_OPT_INTMASK
) | (new_level
& TH_OPT_INTMASK
);
918 * Assert that the current thread is about to go to
919 * sleep until the specified event occurs.
924 wait_interrupt_t interruptible
)
926 if (__improbable(event
== NO_EVENT
)) {
927 panic("%s() called with NO_EVENT", __func__
);
930 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
931 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_WAIT
) | DBG_FUNC_NONE
,
932 VM_KERNEL_UNSLIDE_OR_PERM(event
), 0, 0, 0, 0);
935 waitq
= global_eventq(event
);
936 return waitq_assert_wait64(waitq
, CAST_EVENT64_T(event
), interruptible
, TIMEOUT_WAIT_FOREVER
);
942 * Return the global waitq for the specified event
948 return global_eventq(event
);
954 wait_interrupt_t interruptible
,
956 uint32_t scale_factor
)
958 thread_t thread
= current_thread();
959 wait_result_t wresult
;
963 if (__improbable(event
== NO_EVENT
)) {
964 panic("%s() called with NO_EVENT", __func__
);
968 waitq
= global_eventq(event
);
973 clock_interval_to_deadline(interval
, scale_factor
, &deadline
);
975 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
976 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_WAIT
) | DBG_FUNC_NONE
,
977 VM_KERNEL_UNSLIDE_OR_PERM(event
), interruptible
, deadline
, 0, 0);
979 wresult
= waitq_assert_wait64_locked(waitq
, CAST_EVENT64_T(event
),
981 TIMEOUT_URGENCY_SYS_NORMAL
,
982 deadline
, TIMEOUT_NO_LEEWAY
,
991 assert_wait_timeout_with_leeway(
993 wait_interrupt_t interruptible
,
994 wait_timeout_urgency_t urgency
,
997 uint32_t scale_factor
)
999 thread_t thread
= current_thread();
1000 wait_result_t wresult
;
1007 if (__improbable(event
== NO_EVENT
)) {
1008 panic("%s() called with NO_EVENT", __func__
);
1011 now
= mach_absolute_time();
1012 clock_interval_to_absolutetime_interval(interval
, scale_factor
, &abstime
);
1013 deadline
= now
+ abstime
;
1015 clock_interval_to_absolutetime_interval(leeway
, scale_factor
, &slop
);
1017 struct waitq
*waitq
;
1018 waitq
= global_eventq(event
);
1023 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
1024 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_WAIT
) | DBG_FUNC_NONE
,
1025 VM_KERNEL_UNSLIDE_OR_PERM(event
), interruptible
, deadline
, 0, 0);
1027 wresult
= waitq_assert_wait64_locked(waitq
, CAST_EVENT64_T(event
),
1029 urgency
, deadline
, slop
,
1032 waitq_unlock(waitq
);
1038 assert_wait_deadline(
1040 wait_interrupt_t interruptible
,
1043 thread_t thread
= current_thread();
1044 wait_result_t wresult
;
1047 if (__improbable(event
== NO_EVENT
)) {
1048 panic("%s() called with NO_EVENT", __func__
);
1051 struct waitq
*waitq
;
1052 waitq
= global_eventq(event
);
1057 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
1058 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_WAIT
) | DBG_FUNC_NONE
,
1059 VM_KERNEL_UNSLIDE_OR_PERM(event
), interruptible
, deadline
, 0, 0);
1061 wresult
= waitq_assert_wait64_locked(waitq
, CAST_EVENT64_T(event
),
1063 TIMEOUT_URGENCY_SYS_NORMAL
, deadline
,
1064 TIMEOUT_NO_LEEWAY
, thread
);
1065 waitq_unlock(waitq
);
1071 assert_wait_deadline_with_leeway(
1073 wait_interrupt_t interruptible
,
1074 wait_timeout_urgency_t urgency
,
1078 thread_t thread
= current_thread();
1079 wait_result_t wresult
;
1082 if (__improbable(event
== NO_EVENT
)) {
1083 panic("%s() called with NO_EVENT", __func__
);
1086 struct waitq
*waitq
;
1087 waitq
= global_eventq(event
);
1092 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
1093 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_WAIT
) | DBG_FUNC_NONE
,
1094 VM_KERNEL_UNSLIDE_OR_PERM(event
), interruptible
, deadline
, 0, 0);
1096 wresult
= waitq_assert_wait64_locked(waitq
, CAST_EVENT64_T(event
),
1098 urgency
, deadline
, leeway
,
1100 waitq_unlock(waitq
);
1108 * Return TRUE if a thread is running on a processor such that an AST
1109 * is needed to pull it out of userspace execution, or if executing in
1110 * the kernel, bring to a context switch boundary that would cause
1111 * thread state to be serialized in the thread PCB.
1113 * Thread locked, returns the same way. While locked, fields
1114 * like "state" cannot change. "runq" can change only from set to unset.
1116 static inline boolean_t
1117 thread_isoncpu(thread_t thread
)
1119 /* Not running or runnable */
1120 if (!(thread
->state
& TH_RUN
)) {
1124 /* Waiting on a runqueue, not currently running */
1125 /* TODO: This is invalid - it can get dequeued without thread lock, but not context switched. */
1126 if (thread
->runq
!= PROCESSOR_NULL
) {
1131 * Thread does not have a stack yet
1132 * It could be on the stack alloc queue or preparing to be invoked
1134 if (!thread
->kernel_stack
) {
1139 * Thread must be running on a processor, or
1140 * about to run, or just did run. In all these
1141 * cases, an AST to the processor is needed
1142 * to guarantee that the thread is kicked out
1143 * of userspace and the processor has
1144 * context switched (and saved register state).
1152 * Force a preemption point for a thread and wait
1153 * for it to stop running on a CPU. If a stronger
1154 * guarantee is requested, wait until no longer
1155 * runnable. Arbitrates access among
1156 * multiple stop requests. (released by unstop)
1158 * The thread must enter a wait state and stop via a
1161 * Returns FALSE if interrupted.
1166 boolean_t until_not_runnable
)
1168 wait_result_t wresult
;
1169 spl_t s
= splsched();
1173 thread_lock(thread
);
1175 while (thread
->state
& TH_SUSP
) {
1176 thread
->wake_active
= TRUE
;
1177 thread_unlock(thread
);
1179 wresult
= assert_wait(&thread
->wake_active
, THREAD_ABORTSAFE
);
1180 wake_unlock(thread
);
1183 if (wresult
== THREAD_WAITING
) {
1184 wresult
= thread_block(THREAD_CONTINUE_NULL
);
1187 if (wresult
!= THREAD_AWAKENED
) {
1193 thread_lock(thread
);
1196 thread
->state
|= TH_SUSP
;
1198 while ((oncpu
= thread_isoncpu(thread
)) ||
1199 (until_not_runnable
&& (thread
->state
& TH_RUN
))) {
1200 processor_t processor
;
1203 assert(thread
->state
& TH_RUN
);
1204 processor
= thread
->chosen_processor
;
1205 cause_ast_check(processor
);
1208 thread
->wake_active
= TRUE
;
1209 thread_unlock(thread
);
1211 wresult
= assert_wait(&thread
->wake_active
, THREAD_ABORTSAFE
);
1212 wake_unlock(thread
);
1215 if (wresult
== THREAD_WAITING
) {
1216 wresult
= thread_block(THREAD_CONTINUE_NULL
);
1219 if (wresult
!= THREAD_AWAKENED
) {
1220 thread_unstop(thread
);
1226 thread_lock(thread
);
1229 thread_unlock(thread
);
1230 wake_unlock(thread
);
1234 * We return with the thread unlocked. To prevent it from
1235 * transitioning to a runnable state (or from TH_RUN to
1236 * being on the CPU), the caller must ensure the thread
1237 * is stopped via an external means (such as an AST)
1246 * Release a previous stop request and set
1247 * the thread running if appropriate.
1249 * Use only after a successful stop operation.
1255 spl_t s
= splsched();
1258 thread_lock(thread
);
1260 assert((thread
->state
& (TH_RUN
| TH_WAIT
| TH_SUSP
)) != TH_SUSP
);
1262 if (thread
->state
& TH_SUSP
) {
1263 thread
->state
&= ~TH_SUSP
;
1265 if (thread
->wake_active
) {
1266 thread
->wake_active
= FALSE
;
1267 thread_unlock(thread
);
1269 thread_wakeup(&thread
->wake_active
);
1270 wake_unlock(thread
);
1277 thread_unlock(thread
);
1278 wake_unlock(thread
);
1285 * Wait for a thread to stop running. (non-interruptible)
1291 boolean_t until_not_runnable
)
1293 wait_result_t wresult
;
1295 processor_t processor
;
1296 spl_t s
= splsched();
1299 thread_lock(thread
);
1302 * Wait until not running on a CPU. If stronger requirement
1303 * desired, wait until not runnable. Assumption: if thread is
1304 * on CPU, then TH_RUN is set, so we're not waiting in any case
1305 * where the original, pure "TH_RUN" check would have let us
1308 while ((oncpu
= thread_isoncpu(thread
)) ||
1309 (until_not_runnable
&& (thread
->state
& TH_RUN
))) {
1311 assert(thread
->state
& TH_RUN
);
1312 processor
= thread
->chosen_processor
;
1313 cause_ast_check(processor
);
1316 thread
->wake_active
= TRUE
;
1317 thread_unlock(thread
);
1319 wresult
= assert_wait(&thread
->wake_active
, THREAD_UNINT
);
1320 wake_unlock(thread
);
1323 if (wresult
== THREAD_WAITING
) {
1324 thread_block(THREAD_CONTINUE_NULL
);
1329 thread_lock(thread
);
1332 thread_unlock(thread
);
1333 wake_unlock(thread
);
1338 * Routine: clear_wait_internal
1340 * Clear the wait condition for the specified thread.
1341 * Start the thread executing if that is appropriate.
1343 * thread thread to awaken
1344 * result Wakeup result the thread should see
1347 * the thread is locked.
1349 * KERN_SUCCESS thread was rousted out a wait
1350 * KERN_FAILURE thread was waiting but could not be rousted
1351 * KERN_NOT_WAITING thread was not waiting
1353 __private_extern__ kern_return_t
1354 clear_wait_internal(
1356 wait_result_t wresult
)
1358 uint32_t i
= LockTimeOutUsec
;
1359 struct waitq
*waitq
= thread
->waitq
;
1362 if (wresult
== THREAD_INTERRUPTED
&& (thread
->state
& TH_UNINT
)) {
1363 return KERN_FAILURE
;
1366 if (waitq
!= NULL
) {
1367 if (!waitq_pull_thread_locked(waitq
, thread
)) {
1368 thread_unlock(thread
);
1370 if (i
> 0 && !machine_timeout_suspended()) {
1373 thread_lock(thread
);
1374 if (waitq
!= thread
->waitq
) {
1375 return KERN_NOT_WAITING
;
1381 /* TODO: Can we instead assert TH_TERMINATE is not set? */
1382 if ((thread
->state
& (TH_WAIT
| TH_TERMINATE
)) == TH_WAIT
) {
1383 return thread_go(thread
, wresult
);
1385 return KERN_NOT_WAITING
;
1389 panic("clear_wait_internal: deadlock: thread=%p, wq=%p, cpu=%d\n",
1390 thread
, waitq
, cpu_number());
1392 return KERN_FAILURE
;
1399 * Clear the wait condition for the specified thread. Start the thread
1400 * executing if that is appropriate.
1403 * thread thread to awaken
1404 * result Wakeup result the thread should see
1409 wait_result_t result
)
1415 thread_lock(thread
);
1416 ret
= clear_wait_internal(thread
, result
);
1417 thread_unlock(thread
);
1424 * thread_wakeup_prim:
1426 * Common routine for thread_wakeup, thread_wakeup_with_result,
1427 * and thread_wakeup_one.
1433 boolean_t one_thread
,
1434 wait_result_t result
)
1436 if (__improbable(event
== NO_EVENT
)) {
1437 panic("%s() called with NO_EVENT", __func__
);
1440 struct waitq
*wq
= global_eventq(event
);
1443 return waitq_wakeup64_one(wq
, CAST_EVENT64_T(event
), result
, WAITQ_ALL_PRIORITIES
);
1445 return waitq_wakeup64_all(wq
, CAST_EVENT64_T(event
), result
, WAITQ_ALL_PRIORITIES
);
1450 * Wakeup a specified thread if and only if it's waiting for this event
1453 thread_wakeup_thread(
1457 if (__improbable(event
== NO_EVENT
)) {
1458 panic("%s() called with NO_EVENT", __func__
);
1461 if (__improbable(thread
== THREAD_NULL
)) {
1462 panic("%s() called with THREAD_NULL", __func__
);
1465 struct waitq
*wq
= global_eventq(event
);
1467 return waitq_wakeup64_thread(wq
, CAST_EVENT64_T(event
), thread
, THREAD_AWAKENED
);
1471 * Wakeup a thread waiting on an event and promote it to a priority.
1473 * Requires woken thread to un-promote itself when done.
1476 thread_wakeup_one_with_pri(
1480 if (__improbable(event
== NO_EVENT
)) {
1481 panic("%s() called with NO_EVENT", __func__
);
1484 struct waitq
*wq
= global_eventq(event
);
1486 return waitq_wakeup64_one(wq
, CAST_EVENT64_T(event
), THREAD_AWAKENED
, priority
);
1490 * Wakeup a thread waiting on an event,
1491 * promote it to a priority,
1492 * and return a reference to the woken thread.
1494 * Requires woken thread to un-promote itself when done.
1497 thread_wakeup_identify(event_t event
,
1500 if (__improbable(event
== NO_EVENT
)) {
1501 panic("%s() called with NO_EVENT", __func__
);
1504 struct waitq
*wq
= global_eventq(event
);
1506 return waitq_wakeup64_identify(wq
, CAST_EVENT64_T(event
), THREAD_AWAKENED
, priority
);
1512 * Force the current thread to execute on the specified processor.
1513 * Takes effect after the next thread_block().
1515 * Returns the previous binding. PROCESSOR_NULL means
1518 * XXX - DO NOT export this to users - XXX
1522 processor_t processor
)
1524 thread_t self
= current_thread();
1531 prev
= thread_bind_internal(self
, processor
);
1533 thread_unlock(self
);
1540 * thread_bind_internal:
1542 * If the specified thread is not the current thread, and it is currently
1543 * running on another CPU, a remote AST must be sent to that CPU to cause
1544 * the thread to migrate to its bound processor. Otherwise, the migration
1545 * will occur at the next quantum expiration or blocking point.
1547 * When the thread is the current thread, and explicit thread_block() should
1548 * be used to force the current processor to context switch away and
1549 * let the thread migrate to the bound processor.
1551 * Thread must be locked, and at splsched.
1555 thread_bind_internal(
1557 processor_t processor
)
1561 /* <rdar://problem/15102234> */
1562 assert(thread
->sched_pri
< BASEPRI_RTQUEUES
);
1563 /* A thread can't be bound if it's sitting on a (potentially incorrect) runqueue */
1564 assert(thread
->runq
== PROCESSOR_NULL
);
1566 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_THREAD_BIND
), thread_tid(thread
), processor
? (uintptr_t)processor
->cpu_id
: (uintptr_t)-1, 0, 0, 0);
1568 prev
= thread
->bound_processor
;
1569 thread
->bound_processor
= processor
;
1575 * thread_vm_bind_group_add:
1577 * The "VM bind group" is a special mechanism to mark a collection
1578 * of threads from the VM subsystem that, in general, should be scheduled
1579 * with only one CPU of parallelism. To accomplish this, we initially
1580 * bind all the threads to the master processor, which has the effect
1581 * that only one of the threads in the group can execute at once, including
1582 * preempting threads in the group that are a lower priority. Future
1583 * mechanisms may use more dynamic mechanisms to prevent the collection
1584 * of VM threads from using more CPU time than desired.
1586 * The current implementation can result in priority inversions where
1587 * compute-bound priority 95 or realtime threads that happen to have
1588 * landed on the master processor prevent the VM threads from running.
1589 * When this situation is detected, we unbind the threads for one
1590 * scheduler tick to allow the scheduler to run the threads an
1591 * additional CPUs, before restoring the binding (assuming high latency
1592 * is no longer a problem).
1596 * The current max is provisioned for:
1597 * vm_compressor_swap_trigger_thread (92)
1598 * 2 x vm_pageout_iothread_internal (92) when vm_restricted_to_single_processor==TRUE
1599 * vm_pageout_continue (92)
1600 * memorystatus_thread (95)
1602 #define MAX_VM_BIND_GROUP_COUNT (5)
1603 decl_simple_lock_data(static, sched_vm_group_list_lock
);
1604 static thread_t sched_vm_group_thread_list
[MAX_VM_BIND_GROUP_COUNT
];
1605 static int sched_vm_group_thread_count
;
1606 static boolean_t sched_vm_group_temporarily_unbound
= FALSE
;
1609 thread_vm_bind_group_add(void)
1611 thread_t self
= current_thread();
1613 thread_reference_internal(self
);
1614 self
->options
|= TH_OPT_SCHED_VM_GROUP
;
1616 simple_lock(&sched_vm_group_list_lock
, LCK_GRP_NULL
);
1617 assert(sched_vm_group_thread_count
< MAX_VM_BIND_GROUP_COUNT
);
1618 sched_vm_group_thread_list
[sched_vm_group_thread_count
++] = self
;
1619 simple_unlock(&sched_vm_group_list_lock
);
1621 thread_bind(master_processor
);
1623 /* Switch to bound processor if not already there */
1624 thread_block(THREAD_CONTINUE_NULL
);
1628 sched_vm_group_maintenance(void)
1630 uint64_t ctime
= mach_absolute_time();
1631 uint64_t longtime
= ctime
- sched_tick_interval
;
1634 boolean_t high_latency_observed
= FALSE
;
1635 boolean_t runnable_and_not_on_runq_observed
= FALSE
;
1636 boolean_t bind_target_changed
= FALSE
;
1637 processor_t bind_target
= PROCESSOR_NULL
;
1639 /* Make sure nobody attempts to add new threads while we are enumerating them */
1640 simple_lock(&sched_vm_group_list_lock
, LCK_GRP_NULL
);
1644 for (i
= 0; i
< sched_vm_group_thread_count
; i
++) {
1645 thread_t thread
= sched_vm_group_thread_list
[i
];
1646 assert(thread
!= THREAD_NULL
);
1647 thread_lock(thread
);
1648 if ((thread
->state
& (TH_RUN
| TH_WAIT
)) == TH_RUN
) {
1649 if (thread
->runq
!= PROCESSOR_NULL
&& thread
->last_made_runnable_time
< longtime
) {
1650 high_latency_observed
= TRUE
;
1651 } else if (thread
->runq
== PROCESSOR_NULL
) {
1652 /* There are some cases where a thread be transitiong that also fall into this case */
1653 runnable_and_not_on_runq_observed
= TRUE
;
1656 thread_unlock(thread
);
1658 if (high_latency_observed
&& runnable_and_not_on_runq_observed
) {
1659 /* All the things we are looking for are true, stop looking */
1666 if (sched_vm_group_temporarily_unbound
) {
1667 /* If we turned off binding, make sure everything is OK before rebinding */
1668 if (!high_latency_observed
) {
1670 bind_target_changed
= TRUE
;
1671 bind_target
= master_processor
;
1672 sched_vm_group_temporarily_unbound
= FALSE
; /* might be reset to TRUE if change cannot be completed */
1676 * Check if we're in a bad state, which is defined by high
1677 * latency with no core currently executing a thread. If a
1678 * single thread is making progress on a CPU, that means the
1679 * binding concept to reduce parallelism is working as
1682 if (high_latency_observed
&& !runnable_and_not_on_runq_observed
) {
1684 bind_target_changed
= TRUE
;
1685 bind_target
= PROCESSOR_NULL
;
1686 sched_vm_group_temporarily_unbound
= TRUE
;
1690 if (bind_target_changed
) {
1692 for (i
= 0; i
< sched_vm_group_thread_count
; i
++) {
1693 thread_t thread
= sched_vm_group_thread_list
[i
];
1695 assert(thread
!= THREAD_NULL
);
1697 thread_lock(thread
);
1698 removed
= thread_run_queue_remove(thread
);
1699 if (removed
|| ((thread
->state
& (TH_RUN
| TH_WAIT
)) == TH_WAIT
)) {
1700 thread_bind_internal(thread
, bind_target
);
1703 * Thread was in the middle of being context-switched-to,
1704 * or was in the process of blocking. To avoid switching the bind
1705 * state out mid-flight, defer the change if possible.
1707 if (bind_target
== PROCESSOR_NULL
) {
1708 thread_bind_internal(thread
, bind_target
);
1710 sched_vm_group_temporarily_unbound
= TRUE
; /* next pass will try again */
1715 thread_run_queue_reinsert(thread
, SCHED_PREEMPT
| SCHED_TAILQ
);
1717 thread_unlock(thread
);
1722 simple_unlock(&sched_vm_group_list_lock
);
1725 /* Invoked prior to idle entry to determine if, on SMT capable processors, an SMT
1726 * rebalancing opportunity exists when a core is (instantaneously) idle, but
1727 * other SMT-capable cores may be over-committed. TODO: some possible negatives:
1728 * IPI thrash if this core does not remain idle following the load balancing ASTs
1729 * Idle "thrash", when IPI issue is followed by idle entry/core power down
1730 * followed by a wakeup shortly thereafter.
1733 #if (DEVELOPMENT || DEBUG)
1734 int sched_smt_balance
= 1;
1738 /* Invoked with pset locked, returns with pset unlocked */
1740 sched_SMT_balance(processor_t cprocessor
, processor_set_t cpset
)
1742 processor_t ast_processor
= NULL
;
1744 #if (DEVELOPMENT || DEBUG)
1745 if (__improbable(sched_smt_balance
== 0)) {
1746 goto smt_balance_exit
;
1750 assert(cprocessor
== current_processor());
1751 if (cprocessor
->is_SMT
== FALSE
) {
1752 goto smt_balance_exit
;
1755 processor_t sib_processor
= cprocessor
->processor_secondary
? cprocessor
->processor_secondary
: cprocessor
->processor_primary
;
1757 /* Determine if both this processor and its sibling are idle,
1758 * indicating an SMT rebalancing opportunity.
1760 if (sib_processor
->state
!= PROCESSOR_IDLE
) {
1761 goto smt_balance_exit
;
1764 processor_t sprocessor
;
1766 sched_ipi_type_t ipi_type
= SCHED_IPI_NONE
;
1767 uint64_t running_secondary_map
= (cpset
->cpu_state_map
[PROCESSOR_RUNNING
] &
1768 ~cpset
->primary_map
);
1769 for (int cpuid
= lsb_first(running_secondary_map
); cpuid
>= 0; cpuid
= lsb_next(running_secondary_map
, cpuid
)) {
1770 sprocessor
= processor_array
[cpuid
];
1771 if ((sprocessor
->processor_primary
->state
== PROCESSOR_RUNNING
) &&
1772 (sprocessor
->current_pri
< BASEPRI_RTQUEUES
)) {
1773 ipi_type
= sched_ipi_action(sprocessor
, NULL
, false, SCHED_IPI_EVENT_SMT_REBAL
);
1774 if (ipi_type
!= SCHED_IPI_NONE
) {
1775 assert(sprocessor
!= cprocessor
);
1776 ast_processor
= sprocessor
;
1785 if (ast_processor
) {
1786 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_SMT_BALANCE
), ast_processor
->cpu_id
, ast_processor
->state
, ast_processor
->processor_primary
->state
, 0, 0);
1787 sched_ipi_perform(ast_processor
, ipi_type
);
1791 /* Invoked with pset locked, returns with pset unlocked */
1793 sched_SMT_balance(__unused processor_t cprocessor
, processor_set_t cpset
)
1797 #endif /* __SMP__ */
1800 * Called with pset locked, on a processor that is committing to run a new thread
1801 * Will transition an idle or dispatching processor to running as it picks up
1802 * the first new thread from the idle thread.
1805 pset_commit_processor_to_new_thread(processor_set_t pset
, processor_t processor
, thread_t new_thread
)
1807 if (processor
->state
== PROCESSOR_DISPATCHING
|| processor
->state
== PROCESSOR_IDLE
) {
1808 assert(current_thread() == processor
->idle_thread
);
1811 * Dispatching processor is now committed to running new_thread,
1812 * so change its state to PROCESSOR_RUNNING.
1814 pset_update_processor_state(pset
, processor
, PROCESSOR_RUNNING
);
1816 assert((processor
->state
== PROCESSOR_RUNNING
) || (processor
->state
== PROCESSOR_SHUTDOWN
));
1819 processor_state_update_from_thread(processor
, new_thread
);
1822 static processor_t
choose_processor_for_realtime_thread(processor_set_t pset
);
1823 static bool all_available_primaries_are_running_realtime_threads(processor_set_t pset
);
1824 static bool these_processors_are_running_realtime_threads(processor_set_t pset
, uint64_t these_map
);
1825 static bool sched_ok_to_run_realtime_thread(processor_set_t pset
, processor_t processor
);
1826 int sched_allow_rt_smt
= 1;
1827 int sched_avoid_cpu0
= 1;
1832 * Select a new thread for the current processor to execute.
1834 * May select the current thread, which must be locked.
1837 thread_select(thread_t thread
,
1838 processor_t processor
,
1841 processor_set_t pset
= processor
->processor_set
;
1842 thread_t new_thread
= THREAD_NULL
;
1844 assert(processor
== current_processor());
1845 assert((thread
->state
& (TH_RUN
| TH_TERMINATE2
)) == TH_RUN
);
1849 * Update the priority.
1851 if (SCHED(can_update_priority
)(thread
)) {
1852 SCHED(update_priority
)(thread
);
1857 processor_state_update_from_thread(processor
, thread
);
1860 /* Acknowledge any pending IPIs here with pset lock held */
1861 bit_clear(pset
->pending_AST_URGENT_cpu_mask
, processor
->cpu_id
);
1862 bit_clear(pset
->pending_AST_PREEMPT_cpu_mask
, processor
->cpu_id
);
1864 #if defined(CONFIG_SCHED_DEFERRED_AST)
1865 bit_clear(pset
->pending_deferred_AST_cpu_mask
, processor
->cpu_id
);
1868 bool secondary_can_only_run_realtime_thread
= false;
1870 assert(processor
->state
!= PROCESSOR_OFF_LINE
);
1872 if (!processor
->is_recommended
) {
1874 * The performance controller has provided a hint to not dispatch more threads,
1875 * unless they are bound to us (and thus we are the only option
1877 if (!SCHED(processor_bound_count
)(processor
)) {
1880 } else if (processor
->processor_primary
!= processor
) {
1882 * Should this secondary SMT processor attempt to find work? For pset runqueue systems,
1883 * we should look for work only under the same conditions that choose_processor()
1884 * would have assigned work, which is when all primary processors have been assigned work.
1886 * An exception is that bound threads are dispatched to a processor without going through
1887 * choose_processor(), so in those cases we should continue trying to dequeue work.
1889 if (!SCHED(processor_bound_count
)(processor
)) {
1890 if ((pset
->recommended_bitmask
& pset
->primary_map
& pset
->cpu_state_map
[PROCESSOR_IDLE
]) != 0) {
1895 * TODO: What if a secondary core beat an idle primary to waking up from an IPI?
1896 * Should it dequeue immediately, or spin waiting for the primary to wake up?
1899 /* There are no idle primaries */
1901 if (processor
->processor_primary
->current_pri
>= BASEPRI_RTQUEUES
) {
1902 bool secondary_can_run_realtime_thread
= sched_allow_rt_smt
&& rt_runq_count(pset
) && all_available_primaries_are_running_realtime_threads(pset
);
1903 if (!secondary_can_run_realtime_thread
) {
1906 secondary_can_only_run_realtime_thread
= true;
1912 * Test to see if the current thread should continue
1913 * to run on this processor. Must not be attempting to wait, and not
1914 * bound to a different processor, nor be in the wrong
1915 * processor set, nor be forced to context switch by TH_SUSP.
1917 * Note that there are never any RT threads in the regular runqueue.
1919 * This code is very insanely tricky.
1922 /* i.e. not waiting, not TH_SUSP'ed */
1923 bool still_running
= ((thread
->state
& (TH_TERMINATE
| TH_IDLE
| TH_WAIT
| TH_RUN
| TH_SUSP
)) == TH_RUN
);
1926 * Threads running on SMT processors are forced to context switch. Don't rebalance realtime threads.
1927 * TODO: This should check if it's worth it to rebalance, i.e. 'are there any idle primary processors'
1928 * <rdar://problem/47907700>
1930 * A yielding thread shouldn't be forced to context switch.
1933 bool is_yielding
= (*reason
& AST_YIELD
) == AST_YIELD
;
1935 bool needs_smt_rebalance
= !is_yielding
&& thread
->sched_pri
< BASEPRI_RTQUEUES
&& processor
->processor_primary
!= processor
;
1937 bool affinity_mismatch
= thread
->affinity_set
!= AFFINITY_SET_NULL
&& thread
->affinity_set
->aset_pset
!= pset
;
1939 bool bound_elsewhere
= thread
->bound_processor
!= PROCESSOR_NULL
&& thread
->bound_processor
!= processor
;
1941 bool avoid_processor
= !is_yielding
&& SCHED(avoid_processor_enabled
) && SCHED(thread_avoid_processor
)(processor
, thread
);
1943 if (still_running
&& !needs_smt_rebalance
&& !affinity_mismatch
&& !bound_elsewhere
&& !avoid_processor
) {
1945 * This thread is eligible to keep running on this processor.
1947 * RT threads with un-expired quantum stay on processor,
1948 * unless there's a valid RT thread with an earlier deadline.
1950 if (thread
->sched_pri
>= BASEPRI_RTQUEUES
&& processor
->first_timeslice
) {
1951 if (rt_runq_count(pset
) > 0) {
1954 if (rt_runq_count(pset
) > 0) {
1955 thread_t next_rt
= qe_queue_first(&SCHED(rt_runq
)(pset
)->queue
, struct thread
, runq_links
);
1957 if (next_rt
->realtime
.deadline
< processor
->deadline
&&
1958 (next_rt
->bound_processor
== PROCESSOR_NULL
||
1959 next_rt
->bound_processor
== processor
)) {
1960 /* The next RT thread is better, so pick it off the runqueue. */
1961 goto pick_new_rt_thread
;
1965 rt_lock_unlock(pset
);
1968 /* This is still the best RT thread to run. */
1969 processor
->deadline
= thread
->realtime
.deadline
;
1971 sched_update_pset_load_average(pset
);
1973 processor_t next_rt_processor
= PROCESSOR_NULL
;
1974 sched_ipi_type_t next_rt_ipi_type
= SCHED_IPI_NONE
;
1976 if (rt_runq_count(pset
) > 0) {
1977 next_rt_processor
= choose_processor_for_realtime_thread(pset
);
1978 if (next_rt_processor
) {
1979 if (next_rt_processor
->state
== PROCESSOR_IDLE
) {
1980 pset_update_processor_state(pset
, next_rt_processor
, PROCESSOR_DISPATCHING
);
1982 next_rt_ipi_type
= sched_ipi_action(next_rt_processor
, NULL
, false, SCHED_IPI_EVENT_PREEMPT
);
1987 if (next_rt_processor
) {
1988 sched_ipi_perform(next_rt_processor
, next_rt_ipi_type
);
1994 if ((rt_runq_count(pset
) == 0) &&
1995 SCHED(processor_queue_has_priority
)(processor
, thread
->sched_pri
, TRUE
) == FALSE
) {
1996 /* This thread is still the highest priority runnable (non-idle) thread */
1997 processor
->deadline
= UINT64_MAX
;
1999 sched_update_pset_load_average(pset
);
2006 * This processor must context switch.
2007 * If it's due to a rebalance, we should aggressively find this thread a new home.
2009 if (needs_smt_rebalance
|| affinity_mismatch
|| bound_elsewhere
|| avoid_processor
) {
2010 *reason
|= AST_REBALANCE
;
2014 /* OK, so we're not going to run the current thread. Look at the RT queue. */
2015 bool ok_to_run_realtime_thread
= sched_ok_to_run_realtime_thread(pset
, processor
);
2016 if ((rt_runq_count(pset
) > 0) && ok_to_run_realtime_thread
) {
2019 if ((rt_runq_count(pset
) > 0) && ok_to_run_realtime_thread
) {
2020 thread_t next_rt
= qe_queue_first(&SCHED(rt_runq
)(pset
)->queue
, struct thread
, runq_links
);
2022 if (__probable((next_rt
->bound_processor
== PROCESSOR_NULL
||
2023 (next_rt
->bound_processor
== processor
)))) {
2025 new_thread
= qe_dequeue_head(&SCHED(rt_runq
)(pset
)->queue
, struct thread
, runq_links
);
2027 new_thread
->runq
= PROCESSOR_NULL
;
2028 SCHED_STATS_RUNQ_CHANGE(&SCHED(rt_runq
)(pset
)->runq_stats
, rt_runq_count(pset
));
2029 rt_runq_count_decr(pset
);
2031 processor
->deadline
= new_thread
->realtime
.deadline
;
2033 pset_commit_processor_to_new_thread(pset
, processor
, new_thread
);
2035 rt_lock_unlock(pset
);
2036 sched_update_pset_load_average(pset
);
2038 processor_t ast_processor
= PROCESSOR_NULL
;
2039 processor_t next_rt_processor
= PROCESSOR_NULL
;
2040 sched_ipi_type_t ipi_type
= SCHED_IPI_NONE
;
2041 sched_ipi_type_t next_rt_ipi_type
= SCHED_IPI_NONE
;
2043 if (processor
->processor_secondary
!= NULL
) {
2044 processor_t sprocessor
= processor
->processor_secondary
;
2045 if ((sprocessor
->state
== PROCESSOR_RUNNING
) || (sprocessor
->state
== PROCESSOR_DISPATCHING
)) {
2046 ipi_type
= sched_ipi_action(sprocessor
, NULL
, false, SCHED_IPI_EVENT_SMT_REBAL
);
2047 ast_processor
= sprocessor
;
2050 if (rt_runq_count(pset
) > 0) {
2051 next_rt_processor
= choose_processor_for_realtime_thread(pset
);
2052 if (next_rt_processor
) {
2053 if (next_rt_processor
->state
== PROCESSOR_IDLE
) {
2054 pset_update_processor_state(pset
, next_rt_processor
, PROCESSOR_DISPATCHING
);
2056 next_rt_ipi_type
= sched_ipi_action(next_rt_processor
, NULL
, false, SCHED_IPI_EVENT_PREEMPT
);
2061 if (ast_processor
) {
2062 sched_ipi_perform(ast_processor
, ipi_type
);
2065 if (next_rt_processor
) {
2066 sched_ipi_perform(next_rt_processor
, next_rt_ipi_type
);
2073 rt_lock_unlock(pset
);
2075 if (secondary_can_only_run_realtime_thread
) {
2079 processor
->deadline
= UINT64_MAX
;
2081 /* No RT threads, so let's look at the regular threads. */
2082 if ((new_thread
= SCHED(choose_thread
)(processor
, MINPRI
, *reason
)) != THREAD_NULL
) {
2083 sched_update_pset_load_average(pset
);
2085 pset_commit_processor_to_new_thread(pset
, processor
, new_thread
);
2087 processor_t ast_processor
= PROCESSOR_NULL
;
2088 sched_ipi_type_t ipi_type
= SCHED_IPI_NONE
;
2090 processor_t sprocessor
= processor
->processor_secondary
;
2091 if ((sprocessor
!= NULL
) && (sprocessor
->state
== PROCESSOR_RUNNING
)) {
2092 if (thread_no_smt(new_thread
)) {
2093 ipi_type
= sched_ipi_action(sprocessor
, NULL
, false, SCHED_IPI_EVENT_SMT_REBAL
);
2094 ast_processor
= sprocessor
;
2099 if (ast_processor
) {
2100 sched_ipi_perform(ast_processor
, ipi_type
);
2105 if (processor
->must_idle
) {
2106 processor
->must_idle
= false;
2111 if (SCHED(steal_thread_enabled
)(pset
)) {
2113 * No runnable threads, attempt to steal
2114 * from other processors. Returns with pset lock dropped.
2117 if ((new_thread
= SCHED(steal_thread
)(pset
)) != THREAD_NULL
) {
2119 * Avoid taking the pset_lock unless it is necessary to change state.
2120 * It's safe to read processor->state here, as only the current processor can change state
2121 * from this point (interrupts are disabled and this processor is committed to run new_thread).
2123 if (processor
->state
== PROCESSOR_DISPATCHING
|| processor
->state
== PROCESSOR_IDLE
) {
2125 pset_commit_processor_to_new_thread(pset
, processor
, new_thread
);
2128 assert((processor
->state
== PROCESSOR_RUNNING
) || (processor
->state
== PROCESSOR_SHUTDOWN
));
2129 processor_state_update_from_thread(processor
, new_thread
);
2136 * If other threads have appeared, shortcut
2139 if (!SCHED(processor_queue_empty
)(processor
) || (ok_to_run_realtime_thread
&& (rt_runq_count(pset
) > 0))) {
2145 /* Someone selected this processor while we had dropped the lock */
2146 if (bit_test(pset
->pending_AST_URGENT_cpu_mask
, processor
->cpu_id
)) {
2154 * Nothing is runnable, so set this processor idle if it
2157 if ((processor
->state
== PROCESSOR_RUNNING
) || (processor
->state
== PROCESSOR_DISPATCHING
)) {
2158 pset_update_processor_state(pset
, processor
, PROCESSOR_IDLE
);
2159 processor_state_update_idle(processor
);
2163 /* Invoked with pset locked, returns with pset unlocked */
2164 SCHED(processor_balance
)(processor
, pset
);
2169 new_thread
= processor
->idle_thread
;
2170 } while (new_thread
== THREAD_NULL
);
2178 * Called at splsched with neither thread locked.
2180 * Perform a context switch and start executing the new thread.
2182 * Returns FALSE when the context switch didn't happen.
2183 * The reference to the new thread is still consumed.
2185 * "self" is what is currently running on the processor,
2186 * "thread" is the new thread to context switch to
2187 * (which may be the same thread in some cases)
2195 if (__improbable(get_preemption_level() != 0)) {
2196 int pl
= get_preemption_level();
2197 panic("thread_invoke: preemption_level %d, possible cause: %s",
2198 pl
, (pl
< 0 ? "unlocking an unlocked mutex or spinlock" :
2199 "blocking while holding a spinlock, or within interrupt context"));
2202 thread_continue_t continuation
= self
->continuation
;
2203 void *parameter
= self
->parameter
;
2204 processor_t processor
;
2206 uint64_t ctime
= mach_absolute_time();
2208 #ifdef CONFIG_MACH_APPROXIMATE_TIME
2209 commpage_update_mach_approximate_time(ctime
);
2212 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
2213 if ((thread
->state
& TH_IDLE
) == 0) {
2214 sched_timeshare_consider_maintenance(ctime
);
2219 mt_sched_update(self
);
2220 #endif /* MONOTONIC */
2222 assert_thread_magic(self
);
2223 assert(self
== current_thread());
2224 assert(self
->runq
== PROCESSOR_NULL
);
2225 assert((self
->state
& (TH_RUN
| TH_TERMINATE2
)) == TH_RUN
);
2227 thread_lock(thread
);
2229 assert_thread_magic(thread
);
2230 assert((thread
->state
& (TH_RUN
| TH_WAIT
| TH_UNINT
| TH_TERMINATE
| TH_TERMINATE2
)) == TH_RUN
);
2231 assert(thread
->bound_processor
== PROCESSOR_NULL
|| thread
->bound_processor
== current_processor());
2232 assert(thread
->runq
== PROCESSOR_NULL
);
2234 /* Reload precise timing global policy to thread-local policy */
2235 thread
->precise_user_kernel_time
= use_precise_user_kernel_time(thread
);
2237 /* Update SFI class based on other factors */
2238 thread
->sfi_class
= sfi_thread_classify(thread
);
2240 /* Update the same_pri_latency for the thread (used by perfcontrol callouts) */
2241 thread
->same_pri_latency
= ctime
- thread
->last_basepri_change_time
;
2243 * In case a base_pri update happened between the timestamp and
2244 * taking the thread lock
2246 if (ctime
<= thread
->last_basepri_change_time
) {
2247 thread
->same_pri_latency
= ctime
- thread
->last_made_runnable_time
;
2250 /* Allow realtime threads to hang onto a stack. */
2251 if ((self
->sched_mode
== TH_MODE_REALTIME
) && !self
->reserved_stack
) {
2252 self
->reserved_stack
= self
->kernel_stack
;
2255 /* Prepare for spin debugging */
2256 #if INTERRUPT_MASKED_DEBUG
2257 ml_spin_debug_clear(thread
);
2260 if (continuation
!= NULL
) {
2261 if (!thread
->kernel_stack
) {
2263 * If we are using a privileged stack,
2264 * check to see whether we can exchange it with
2265 * that of the other thread.
2267 if (self
->kernel_stack
== self
->reserved_stack
&& !thread
->reserved_stack
) {
2272 * Context switch by performing a stack handoff.
2273 * Requires both threads to be parked in a continuation.
2275 continuation
= thread
->continuation
;
2276 parameter
= thread
->parameter
;
2278 processor
= current_processor();
2279 processor
->active_thread
= thread
;
2280 processor_state_update_from_thread(processor
, thread
);
2282 if (thread
->last_processor
!= processor
&& thread
->last_processor
!= NULL
) {
2283 if (thread
->last_processor
->processor_set
!= processor
->processor_set
) {
2284 thread
->ps_switch
++;
2288 thread
->last_processor
= processor
;
2290 ast_context(thread
);
2292 thread_unlock(thread
);
2294 self
->reason
= reason
;
2296 processor
->last_dispatch
= ctime
;
2297 self
->last_run_time
= ctime
;
2298 processor_timer_switch_thread(ctime
, &thread
->system_timer
);
2299 timer_update(&thread
->runnable_timer
, ctime
);
2300 PROCESSOR_DATA(processor
, kernel_timer
) = &thread
->system_timer
;
2303 * Since non-precise user/kernel time doesn't update the state timer
2304 * during privilege transitions, synthesize an event now.
2306 if (!thread
->precise_user_kernel_time
) {
2307 timer_update(PROCESSOR_DATA(processor
, current_state
), ctime
);
2310 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2311 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_STACK_HANDOFF
) | DBG_FUNC_NONE
,
2312 self
->reason
, (uintptr_t)thread_tid(thread
), self
->sched_pri
, thread
->sched_pri
, 0);
2314 if ((thread
->chosen_processor
!= processor
) && (thread
->chosen_processor
!= PROCESSOR_NULL
)) {
2315 SCHED_DEBUG_CHOOSE_PROCESSOR_KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_MOVED
) | DBG_FUNC_NONE
,
2316 (uintptr_t)thread_tid(thread
), (uintptr_t)thread
->chosen_processor
->cpu_id
, 0, 0, 0);
2319 DTRACE_SCHED2(off__cpu
, struct thread
*, thread
, struct proc
*, thread
->task
->bsd_info
);
2321 SCHED_STATS_CSW(processor
, self
->reason
, self
->sched_pri
, thread
->sched_pri
);
2324 kperf_off_cpu(self
);
2328 * This is where we actually switch thread identity,
2329 * and address space if required. However, register
2330 * state is not switched - this routine leaves the
2331 * stack and register state active on the current CPU.
2333 TLOG(1, "thread_invoke: calling stack_handoff\n");
2334 stack_handoff(self
, thread
);
2336 /* 'self' is now off core */
2337 assert(thread
== current_thread_volatile());
2339 DTRACE_SCHED(on__cpu
);
2342 kperf_on_cpu(thread
, continuation
, NULL
);
2345 thread_dispatch(self
, thread
);
2348 /* Old thread's stack has been moved to the new thread, so explicitly
2350 kasan_unpoison_stack(thread
->kernel_stack
, kernel_stack_size
);
2353 thread
->continuation
= thread
->parameter
= NULL
;
2355 counter(c_thread_invoke_hits
++);
2357 boolean_t enable_interrupts
= TRUE
;
2359 /* idle thread needs to stay interrupts-disabled */
2360 if ((thread
->state
& TH_IDLE
)) {
2361 enable_interrupts
= FALSE
;
2364 assert(continuation
);
2365 call_continuation(continuation
, parameter
,
2366 thread
->wait_result
, enable_interrupts
);
2368 } else if (thread
== self
) {
2369 /* same thread but with continuation */
2371 counter(++c_thread_invoke_same
);
2373 thread_unlock(self
);
2376 kperf_on_cpu(thread
, continuation
, NULL
);
2379 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2380 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED
) | DBG_FUNC_NONE
,
2381 self
->reason
, (uintptr_t)thread_tid(thread
), self
->sched_pri
, thread
->sched_pri
, 0);
2384 /* stack handoff to self - no thread_dispatch(), so clear the stack
2385 * and free the fakestack directly */
2386 kasan_fakestack_drop(self
);
2387 kasan_fakestack_gc(self
);
2388 kasan_unpoison_stack(self
->kernel_stack
, kernel_stack_size
);
2391 self
->continuation
= self
->parameter
= NULL
;
2393 boolean_t enable_interrupts
= TRUE
;
2395 /* idle thread needs to stay interrupts-disabled */
2396 if ((self
->state
& TH_IDLE
)) {
2397 enable_interrupts
= FALSE
;
2400 call_continuation(continuation
, parameter
,
2401 self
->wait_result
, enable_interrupts
);
2406 * Check that the other thread has a stack
2408 if (!thread
->kernel_stack
) {
2410 if (!stack_alloc_try(thread
)) {
2411 counter(c_thread_invoke_misses
++);
2412 thread_unlock(thread
);
2413 thread_stack_enqueue(thread
);
2416 } else if (thread
== self
) {
2418 counter(++c_thread_invoke_same
);
2419 thread_unlock(self
);
2421 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2422 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED
) | DBG_FUNC_NONE
,
2423 self
->reason
, (uintptr_t)thread_tid(thread
), self
->sched_pri
, thread
->sched_pri
, 0);
2430 * Context switch by full context save.
2432 processor
= current_processor();
2433 processor
->active_thread
= thread
;
2434 processor_state_update_from_thread(processor
, thread
);
2436 if (thread
->last_processor
!= processor
&& thread
->last_processor
!= NULL
) {
2437 if (thread
->last_processor
->processor_set
!= processor
->processor_set
) {
2438 thread
->ps_switch
++;
2442 thread
->last_processor
= processor
;
2444 ast_context(thread
);
2446 thread_unlock(thread
);
2448 counter(c_thread_invoke_csw
++);
2450 self
->reason
= reason
;
2452 processor
->last_dispatch
= ctime
;
2453 self
->last_run_time
= ctime
;
2454 processor_timer_switch_thread(ctime
, &thread
->system_timer
);
2455 timer_update(&thread
->runnable_timer
, ctime
);
2456 PROCESSOR_DATA(processor
, kernel_timer
) = &thread
->system_timer
;
2459 * Since non-precise user/kernel time doesn't update the state timer
2460 * during privilege transitions, synthesize an event now.
2462 if (!thread
->precise_user_kernel_time
) {
2463 timer_update(PROCESSOR_DATA(processor
, current_state
), ctime
);
2466 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2467 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED
) | DBG_FUNC_NONE
,
2468 self
->reason
, (uintptr_t)thread_tid(thread
), self
->sched_pri
, thread
->sched_pri
, 0);
2470 if ((thread
->chosen_processor
!= processor
) && (thread
->chosen_processor
!= NULL
)) {
2471 SCHED_DEBUG_CHOOSE_PROCESSOR_KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_MOVED
) | DBG_FUNC_NONE
,
2472 (uintptr_t)thread_tid(thread
), (uintptr_t)thread
->chosen_processor
->cpu_id
, 0, 0, 0);
2475 DTRACE_SCHED2(off__cpu
, struct thread
*, thread
, struct proc
*, thread
->task
->bsd_info
);
2477 SCHED_STATS_CSW(processor
, self
->reason
, self
->sched_pri
, thread
->sched_pri
);
2480 kperf_off_cpu(self
);
2484 * This is where we actually switch register context,
2485 * and address space if required. We will next run
2486 * as a result of a subsequent context switch.
2488 * Once registers are switched and the processor is running "thread",
2489 * the stack variables and non-volatile registers will contain whatever
2490 * was there the last time that thread blocked. No local variables should
2491 * be used after this point, except for the special case of "thread", which
2492 * the platform layer returns as the previous thread running on the processor
2493 * via the function call ABI as a return register, and "self", which may have
2494 * been stored on the stack or a non-volatile register, but a stale idea of
2495 * what was on the CPU is newly-accurate because that thread is again
2496 * running on the CPU.
2498 * If one of the threads is using a continuation, thread_continue
2499 * is used to stitch up its context.
2501 * If we are invoking a thread which is resuming from a continuation,
2502 * the CPU will invoke thread_continue next.
2504 * If the current thread is parking in a continuation, then its state
2505 * won't be saved and the stack will be discarded. When the stack is
2506 * re-allocated, it will be configured to resume from thread_continue.
2508 assert(continuation
== self
->continuation
);
2509 thread
= machine_switch_context(self
, continuation
, thread
);
2510 assert(self
== current_thread_volatile());
2511 TLOG(1, "thread_invoke: returning machine_switch_context: self %p continuation %p thread %p\n", self
, continuation
, thread
);
2513 assert(continuation
== NULL
&& self
->continuation
== NULL
);
2515 DTRACE_SCHED(on__cpu
);
2518 kperf_on_cpu(self
, NULL
, __builtin_frame_address(0));
2521 /* We have been resumed and are set to run. */
2522 thread_dispatch(thread
, self
);
2527 #if defined(CONFIG_SCHED_DEFERRED_AST)
2529 * pset_cancel_deferred_dispatch:
2531 * Cancels all ASTs that we can cancel for the given processor set
2532 * if the current processor is running the last runnable thread in the
2535 * This function assumes the current thread is runnable. This must
2536 * be called with the pset unlocked.
2539 pset_cancel_deferred_dispatch(
2540 processor_set_t pset
,
2541 processor_t processor
)
2543 processor_t active_processor
= NULL
;
2544 uint32_t sampled_sched_run_count
;
2547 sampled_sched_run_count
= os_atomic_load(&sched_run_buckets
[TH_BUCKET_RUN
], relaxed
);
2550 * If we have emptied the run queue, and our current thread is runnable, we
2551 * should tell any processors that are still DISPATCHING that they will
2552 * probably not have any work to do. In the event that there are no
2553 * pending signals that we can cancel, this is also uninteresting.
2555 * In the unlikely event that another thread becomes runnable while we are
2556 * doing this (sched_run_count is atomically updated, not guarded), the
2557 * codepath making it runnable SHOULD (a dangerous word) need the pset lock
2558 * in order to dispatch it to a processor in our pset. So, the other
2559 * codepath will wait while we squash all cancelable ASTs, get the pset
2560 * lock, and then dispatch the freshly runnable thread. So this should be
2561 * correct (we won't accidentally have a runnable thread that hasn't been
2562 * dispatched to an idle processor), if not ideal (we may be restarting the
2563 * dispatch process, which could have some overhead).
2566 if ((sampled_sched_run_count
== 1) && (pset
->pending_deferred_AST_cpu_mask
)) {
2567 uint64_t dispatching_map
= (pset
->cpu_state_map
[PROCESSOR_DISPATCHING
] &
2568 pset
->pending_deferred_AST_cpu_mask
&
2569 ~pset
->pending_AST_URGENT_cpu_mask
);
2570 for (int cpuid
= lsb_first(dispatching_map
); cpuid
>= 0; cpuid
= lsb_next(dispatching_map
, cpuid
)) {
2571 active_processor
= processor_array
[cpuid
];
2573 * If a processor is DISPATCHING, it could be because of
2574 * a cancelable signal.
2576 * IF the processor is not our
2577 * current processor (the current processor should not
2578 * be DISPATCHING, so this is a bit paranoid), AND there
2579 * is a cancelable signal pending on the processor, AND
2580 * there is no non-cancelable signal pending (as there is
2581 * no point trying to backtrack on bringing the processor
2582 * up if a signal we cannot cancel is outstanding), THEN
2583 * it should make sense to roll back the processor state
2584 * to the IDLE state.
2586 * If the racey nature of this approach (as the signal
2587 * will be arbitrated by hardware, and can fire as we
2588 * roll back state) results in the core responding
2589 * despite being pushed back to the IDLE state, it
2590 * should be no different than if the core took some
2591 * interrupt while IDLE.
2593 if (active_processor
!= processor
) {
2595 * Squash all of the processor state back to some
2596 * reasonable facsimile of PROCESSOR_IDLE.
2599 processor_state_update_idle(active_processor
);
2600 active_processor
->deadline
= UINT64_MAX
;
2601 pset_update_processor_state(pset
, active_processor
, PROCESSOR_IDLE
);
2602 bit_clear(pset
->pending_deferred_AST_cpu_mask
, active_processor
->cpu_id
);
2603 machine_signal_idle_cancel(active_processor
);
2611 /* We don't support deferred ASTs; everything is candycanes and sunshine. */
2620 perfcontrol_event event
= (new->state
& TH_IDLE
) ? IDLE
: CONTEXT_SWITCH
;
2621 uint64_t same_pri_latency
= (new->state
& TH_IDLE
) ? 0 : new->same_pri_latency
;
2622 machine_switch_perfcontrol_context(event
, timestamp
, 0,
2623 same_pri_latency
, old
, new);
2630 * Handle threads at context switch. Re-dispatch other thread
2631 * if still running, otherwise update run state and perform
2632 * special actions. Update quantum for other thread and begin
2633 * the quantum for ourselves.
2635 * "thread" is the old thread that we have switched away from.
2636 * "self" is the new current thread that we have context switched to
2638 * Called at splsched.
2646 processor_t processor
= self
->last_processor
;
2648 assert(processor
== current_processor());
2649 assert(self
== current_thread_volatile());
2650 assert(thread
!= self
);
2652 if (thread
!= THREAD_NULL
) {
2654 * Do the perfcontrol callout for context switch.
2655 * The reason we do this here is:
2656 * - thread_dispatch() is called from various places that are not
2657 * the direct context switch path for eg. processor shutdown etc.
2658 * So adding the callout here covers all those cases.
2659 * - We want this callout as early as possible to be close
2660 * to the timestamp taken in thread_invoke()
2661 * - We want to avoid holding the thread lock while doing the
2663 * - We do not want to callout if "thread" is NULL.
2665 thread_csw_callout(thread
, self
, processor
->last_dispatch
);
2668 if (thread
->continuation
!= NULL
) {
2670 * Thread has a continuation and the normal stack is going away.
2671 * Unpoison the stack and mark all fakestack objects as unused.
2673 kasan_fakestack_drop(thread
);
2674 if (thread
->kernel_stack
) {
2675 kasan_unpoison_stack(thread
->kernel_stack
, kernel_stack_size
);
2680 * Free all unused fakestack objects.
2682 kasan_fakestack_gc(thread
);
2686 * If blocked at a continuation, discard
2689 if (thread
->continuation
!= NULL
&& thread
->kernel_stack
!= 0) {
2693 if (thread
->state
& TH_IDLE
) {
2694 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2695 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_DISPATCH
) | DBG_FUNC_NONE
,
2696 (uintptr_t)thread_tid(thread
), 0, thread
->state
,
2697 sched_run_buckets
[TH_BUCKET_RUN
], 0);
2700 int64_t remainder
= 0;
2702 if (processor
->quantum_end
> processor
->last_dispatch
) {
2703 remainder
= processor
->quantum_end
-
2704 processor
->last_dispatch
;
2707 consumed
= thread
->quantum_remaining
- remainder
;
2709 if ((thread
->reason
& AST_LEDGER
) == 0) {
2711 * Bill CPU time to both the task and
2712 * the individual thread.
2714 ledger_credit_thread(thread
, thread
->t_ledger
,
2715 task_ledgers
.cpu_time
, consumed
);
2716 ledger_credit_thread(thread
, thread
->t_threadledger
,
2717 thread_ledgers
.cpu_time
, consumed
);
2718 if (thread
->t_bankledger
) {
2719 ledger_credit_thread(thread
, thread
->t_bankledger
,
2720 bank_ledgers
.cpu_time
,
2721 (consumed
- thread
->t_deduct_bank_ledger_time
));
2723 thread
->t_deduct_bank_ledger_time
= 0;
2727 thread_lock(thread
);
2730 * Apply a priority floor if the thread holds a kernel resource
2731 * Do this before checking starting_pri to avoid overpenalizing
2732 * repeated rwlock blockers.
2734 if (__improbable(thread
->rwlock_count
!= 0)) {
2735 lck_rw_set_promotion_locked(thread
);
2738 boolean_t keep_quantum
= processor
->first_timeslice
;
2741 * Treat a thread which has dropped priority since it got on core
2742 * as having expired its quantum.
2744 if (processor
->starting_pri
> thread
->sched_pri
) {
2745 keep_quantum
= FALSE
;
2748 /* Compute remainder of current quantum. */
2750 processor
->quantum_end
> processor
->last_dispatch
) {
2751 thread
->quantum_remaining
= (uint32_t)remainder
;
2753 thread
->quantum_remaining
= 0;
2756 if (thread
->sched_mode
== TH_MODE_REALTIME
) {
2758 * Cancel the deadline if the thread has
2759 * consumed the entire quantum.
2761 if (thread
->quantum_remaining
== 0) {
2762 thread
->realtime
.deadline
= UINT64_MAX
;
2765 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
2767 * For non-realtime threads treat a tiny
2768 * remaining quantum as an expired quantum
2769 * but include what's left next time.
2771 if (thread
->quantum_remaining
< min_std_quantum
) {
2772 thread
->reason
|= AST_QUANTUM
;
2773 thread
->quantum_remaining
+= SCHED(initial_quantum_size
)(thread
);
2775 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
2779 * If we are doing a direct handoff then
2780 * take the remainder of the quantum.
2782 if ((thread
->reason
& (AST_HANDOFF
| AST_QUANTUM
)) == AST_HANDOFF
) {
2783 self
->quantum_remaining
= thread
->quantum_remaining
;
2784 thread
->reason
|= AST_QUANTUM
;
2785 thread
->quantum_remaining
= 0;
2787 #if defined(CONFIG_SCHED_MULTIQ)
2788 if (SCHED(sched_groups_enabled
) &&
2789 thread
->sched_group
== self
->sched_group
) {
2790 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2791 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_QUANTUM_HANDOFF
),
2792 self
->reason
, (uintptr_t)thread_tid(thread
),
2793 self
->quantum_remaining
, thread
->quantum_remaining
, 0);
2795 self
->quantum_remaining
= thread
->quantum_remaining
;
2796 thread
->quantum_remaining
= 0;
2797 /* Don't set AST_QUANTUM here - old thread might still want to preempt someone else */
2799 #endif /* defined(CONFIG_SCHED_MULTIQ) */
2802 thread
->computation_metered
+= (processor
->last_dispatch
- thread
->computation_epoch
);
2804 if (!(thread
->state
& TH_WAIT
)) {
2808 thread
->last_made_runnable_time
= thread
->last_basepri_change_time
= processor
->last_dispatch
;
2810 machine_thread_going_off_core(thread
, FALSE
, processor
->last_dispatch
, TRUE
);
2812 ast_t reason
= thread
->reason
;
2813 sched_options_t options
= SCHED_NONE
;
2815 if (reason
& AST_REBALANCE
) {
2816 options
|= SCHED_REBALANCE
;
2817 if (reason
& AST_QUANTUM
) {
2819 * Having gone to the trouble of forcing this thread off a less preferred core,
2820 * we should force the preferable core to reschedule immediately to give this
2821 * thread a chance to run instead of just sitting on the run queue where
2822 * it may just be stolen back by the idle core we just forced it off.
2823 * But only do this at the end of a quantum to prevent cascading effects.
2825 options
|= SCHED_PREEMPT
;
2829 if (reason
& AST_QUANTUM
) {
2830 options
|= SCHED_TAILQ
;
2831 } else if (reason
& AST_PREEMPT
) {
2832 options
|= SCHED_HEADQ
;
2834 options
|= (SCHED_PREEMPT
| SCHED_TAILQ
);
2837 thread_setrun(thread
, options
);
2839 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2840 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_DISPATCH
) | DBG_FUNC_NONE
,
2841 (uintptr_t)thread_tid(thread
), thread
->reason
, thread
->state
,
2842 sched_run_buckets
[TH_BUCKET_RUN
], 0);
2844 if (thread
->wake_active
) {
2845 thread
->wake_active
= FALSE
;
2846 thread_unlock(thread
);
2848 thread_wakeup(&thread
->wake_active
);
2850 thread_unlock(thread
);
2853 wake_unlock(thread
);
2858 boolean_t should_terminate
= FALSE
;
2859 uint32_t new_run_count
;
2860 int thread_state
= thread
->state
;
2862 /* Only the first call to thread_dispatch
2863 * after explicit termination should add
2864 * the thread to the termination queue
2866 if ((thread_state
& (TH_TERMINATE
| TH_TERMINATE2
)) == TH_TERMINATE
) {
2867 should_terminate
= TRUE
;
2868 thread_state
|= TH_TERMINATE2
;
2871 timer_stop(&thread
->runnable_timer
, processor
->last_dispatch
);
2873 thread_state
&= ~TH_RUN
;
2874 thread
->state
= thread_state
;
2876 thread
->last_made_runnable_time
= thread
->last_basepri_change_time
= THREAD_NOT_RUNNABLE
;
2877 thread
->chosen_processor
= PROCESSOR_NULL
;
2879 new_run_count
= SCHED(run_count_decr
)(thread
);
2881 #if CONFIG_SCHED_SFI
2882 if (thread
->reason
& AST_SFI
) {
2883 thread
->wait_sfi_begin_time
= processor
->last_dispatch
;
2886 machine_thread_going_off_core(thread
, should_terminate
, processor
->last_dispatch
, FALSE
);
2888 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
2889 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_DISPATCH
) | DBG_FUNC_NONE
,
2890 (uintptr_t)thread_tid(thread
), thread
->reason
, thread_state
,
2893 if (thread_state
& TH_WAIT_REPORT
) {
2894 (*thread
->sched_call
)(SCHED_CALL_BLOCK
, thread
);
2897 if (thread
->wake_active
) {
2898 thread
->wake_active
= FALSE
;
2899 thread_unlock(thread
);
2901 thread_wakeup(&thread
->wake_active
);
2903 thread_unlock(thread
);
2906 wake_unlock(thread
);
2908 if (should_terminate
) {
2909 thread_terminate_enqueue(thread
);
2915 int urgency
= THREAD_URGENCY_NONE
;
2916 uint64_t latency
= 0;
2918 /* Update (new) current thread and reprogram quantum timer */
2921 if (!(self
->state
& TH_IDLE
)) {
2922 uint64_t arg1
, arg2
;
2924 #if CONFIG_SCHED_SFI
2927 new_ast
= sfi_thread_needs_ast(self
, NULL
);
2929 if (new_ast
!= AST_NONE
) {
2934 assertf(processor
->last_dispatch
>= self
->last_made_runnable_time
,
2935 "Non-monotonic time? dispatch at 0x%llx, runnable at 0x%llx",
2936 processor
->last_dispatch
, self
->last_made_runnable_time
);
2938 assert(self
->last_made_runnable_time
<= self
->last_basepri_change_time
);
2940 latency
= processor
->last_dispatch
- self
->last_made_runnable_time
;
2941 assert(latency
>= self
->same_pri_latency
);
2943 urgency
= thread_get_urgency(self
, &arg1
, &arg2
);
2945 thread_tell_urgency(urgency
, arg1
, arg2
, latency
, self
);
2948 * Get a new quantum if none remaining.
2950 if (self
->quantum_remaining
== 0) {
2951 thread_quantum_init(self
);
2955 * Set up quantum timer and timeslice.
2957 processor
->quantum_end
= processor
->last_dispatch
+ self
->quantum_remaining
;
2958 timer_call_quantum_timer_enter(&processor
->quantum_timer
, self
,
2959 processor
->quantum_end
, processor
->last_dispatch
);
2961 processor
->first_timeslice
= TRUE
;
2963 timer_call_quantum_timer_cancel(&processor
->quantum_timer
);
2964 processor
->first_timeslice
= FALSE
;
2966 thread_tell_urgency(THREAD_URGENCY_NONE
, 0, 0, 0, self
);
2969 assert(self
->block_hint
== kThreadWaitNone
);
2970 self
->computation_epoch
= processor
->last_dispatch
;
2971 self
->reason
= AST_NONE
;
2972 processor
->starting_pri
= self
->sched_pri
;
2974 thread_unlock(self
);
2976 machine_thread_going_on_core(self
, urgency
, latency
, self
->same_pri_latency
,
2977 processor
->last_dispatch
);
2979 #if defined(CONFIG_SCHED_DEFERRED_AST)
2981 * TODO: Can we state that redispatching our old thread is also
2984 if ((os_atomic_load(&sched_run_buckets
[TH_BUCKET_RUN
], relaxed
) == 1) && !(self
->state
& TH_IDLE
)) {
2985 pset_cancel_deferred_dispatch(processor
->processor_set
, processor
);
2991 * thread_block_reason:
2993 * Forces a reschedule, blocking the caller if a wait
2994 * has been asserted.
2996 * If a continuation is specified, then thread_invoke will
2997 * attempt to discard the thread's kernel stack. When the
2998 * thread resumes, it will execute the continuation function
2999 * on a new kernel stack.
3001 counter(mach_counter_t c_thread_block_calls
= 0; )
3004 thread_block_reason(
3005 thread_continue_t continuation
,
3009 thread_t self
= current_thread();
3010 processor_t processor
;
3011 thread_t new_thread
;
3014 counter(++c_thread_block_calls
);
3018 processor
= current_processor();
3020 /* If we're explicitly yielding, force a subsequent quantum */
3021 if (reason
& AST_YIELD
) {
3022 processor
->first_timeslice
= FALSE
;
3025 /* We're handling all scheduling AST's */
3026 ast_off(AST_SCHEDULING
);
3029 if ((continuation
!= NULL
) && (self
->task
!= kernel_task
)) {
3030 if (uthread_get_proc_refcount(self
->uthread
) != 0) {
3031 panic("thread_block_reason with continuation uthread %p with uu_proc_refcount != 0", self
->uthread
);
3036 self
->continuation
= continuation
;
3037 self
->parameter
= parameter
;
3039 if (self
->state
& ~(TH_RUN
| TH_IDLE
)) {
3040 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
3041 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_BLOCK
),
3042 reason
, VM_KERNEL_UNSLIDE(continuation
), 0, 0, 0);
3047 new_thread
= thread_select(self
, processor
, &reason
);
3048 thread_unlock(self
);
3049 } while (!thread_invoke(self
, new_thread
, reason
));
3053 return self
->wait_result
;
3059 * Block the current thread if a wait has been asserted.
3063 thread_continue_t continuation
)
3065 return thread_block_reason(continuation
, NULL
, AST_NONE
);
3069 thread_block_parameter(
3070 thread_continue_t continuation
,
3073 return thread_block_reason(continuation
, parameter
, AST_NONE
);
3079 * Switch directly from the current thread to the
3080 * new thread, handing off our quantum if appropriate.
3082 * New thread must be runnable, and not on a run queue.
3084 * Called at splsched.
3089 thread_continue_t continuation
,
3091 thread_t new_thread
)
3093 ast_t reason
= AST_NONE
;
3095 if ((self
->state
& TH_IDLE
) == 0) {
3096 reason
= AST_HANDOFF
;
3099 self
->continuation
= continuation
;
3100 self
->parameter
= parameter
;
3102 while (!thread_invoke(self
, new_thread
, reason
)) {
3103 /* the handoff failed, so we have to fall back to the normal block path */
3104 processor_t processor
= current_processor();
3109 new_thread
= thread_select(self
, processor
, &reason
);
3110 thread_unlock(self
);
3113 return self
->wait_result
;
3119 * Called at splsched when a thread first receives
3120 * a new stack after a continuation.
3122 * Called with THREAD_NULL as the old thread when
3123 * invoked by machine_load_context.
3129 thread_t self
= current_thread();
3130 thread_continue_t continuation
;
3133 DTRACE_SCHED(on__cpu
);
3135 continuation
= self
->continuation
;
3136 parameter
= self
->parameter
;
3138 assert(continuation
!= NULL
);
3141 kperf_on_cpu(self
, continuation
, NULL
);
3144 thread_dispatch(thread
, self
);
3146 self
->continuation
= self
->parameter
= NULL
;
3148 #if INTERRUPT_MASKED_DEBUG
3149 /* Reset interrupt-masked spin debugging timeout */
3150 ml_spin_debug_clear(self
);
3153 TLOG(1, "thread_continue: calling call_continuation\n");
3155 boolean_t enable_interrupts
= TRUE
;
3157 /* bootstrap thread, idle thread need to stay interrupts-disabled */
3158 if (thread
== THREAD_NULL
|| (self
->state
& TH_IDLE
)) {
3159 enable_interrupts
= FALSE
;
3162 call_continuation(continuation
, parameter
, self
->wait_result
, enable_interrupts
);
3167 thread_quantum_init(thread_t thread
)
3169 if (thread
->sched_mode
== TH_MODE_REALTIME
) {
3170 thread
->quantum_remaining
= thread
->realtime
.computation
;
3172 thread
->quantum_remaining
= SCHED(initial_quantum_size
)(thread
);
3177 sched_timeshare_initial_quantum_size(thread_t thread
)
3179 if ((thread
!= THREAD_NULL
) && thread
->th_sched_bucket
== TH_BUCKET_SHARE_BG
) {
3189 * Initialize a run queue before first use.
3196 for (u_int i
= 0; i
< BITMAP_LEN(NRQS
); i
++) {
3199 rq
->urgency
= rq
->count
= 0;
3200 for (int i
= 0; i
< NRQS
; i
++) {
3201 circle_queue_init(&rq
->queues
[i
]);
3206 * run_queue_dequeue:
3208 * Perform a dequeue operation on a run queue,
3209 * and return the resulting thread.
3211 * The run queue must be locked (see thread_run_queue_remove()
3212 * for more info), and not empty.
3217 sched_options_t options
)
3220 circle_queue_t queue
= &rq
->queues
[rq
->highq
];
3222 if (options
& SCHED_HEADQ
) {
3223 thread
= cqe_dequeue_head(queue
, struct thread
, runq_links
);
3225 thread
= cqe_dequeue_tail(queue
, struct thread
, runq_links
);
3228 assert(thread
!= THREAD_NULL
);
3229 assert_thread_magic(thread
);
3231 thread
->runq
= PROCESSOR_NULL
;
3232 SCHED_STATS_RUNQ_CHANGE(&rq
->runq_stats
, rq
->count
);
3234 if (SCHED(priority_is_urgent
)(rq
->highq
)) {
3235 rq
->urgency
--; assert(rq
->urgency
>= 0);
3237 if (circle_queue_empty(queue
)) {
3238 bitmap_clear(rq
->bitmap
, rq
->highq
);
3239 rq
->highq
= bitmap_first(rq
->bitmap
, NRQS
);
3246 * run_queue_enqueue:
3248 * Perform a enqueue operation on a run queue.
3250 * The run queue must be locked (see thread_run_queue_remove()
3257 sched_options_t options
)
3259 circle_queue_t queue
= &rq
->queues
[thread
->sched_pri
];
3260 boolean_t result
= FALSE
;
3262 assert_thread_magic(thread
);
3264 if (circle_queue_empty(queue
)) {
3265 circle_enqueue_tail(queue
, &thread
->runq_links
);
3267 rq_bitmap_set(rq
->bitmap
, thread
->sched_pri
);
3268 if (thread
->sched_pri
> rq
->highq
) {
3269 rq
->highq
= thread
->sched_pri
;
3273 if (options
& SCHED_TAILQ
) {
3274 circle_enqueue_tail(queue
, &thread
->runq_links
);
3276 circle_enqueue_head(queue
, &thread
->runq_links
);
3279 if (SCHED(priority_is_urgent
)(thread
->sched_pri
)) {
3282 SCHED_STATS_RUNQ_CHANGE(&rq
->runq_stats
, rq
->count
);
3291 * Remove a specific thread from a runqueue.
3293 * The run queue must be locked.
3300 circle_queue_t queue
= &rq
->queues
[thread
->sched_pri
];
3302 assert(thread
->runq
!= PROCESSOR_NULL
);
3303 assert_thread_magic(thread
);
3305 circle_dequeue(queue
, &thread
->runq_links
);
3306 SCHED_STATS_RUNQ_CHANGE(&rq
->runq_stats
, rq
->count
);
3308 if (SCHED(priority_is_urgent
)(thread
->sched_pri
)) {
3309 rq
->urgency
--; assert(rq
->urgency
>= 0);
3312 if (circle_queue_empty(queue
)) {
3313 /* update run queue status */
3314 bitmap_clear(rq
->bitmap
, thread
->sched_pri
);
3315 rq
->highq
= bitmap_first(rq
->bitmap
, NRQS
);
3318 thread
->runq
= PROCESSOR_NULL
;
3324 * Peek at the runq and return the highest
3325 * priority thread from the runq.
3327 * The run queue must be locked.
3333 if (rq
->count
> 0) {
3334 circle_queue_t queue
= &rq
->queues
[rq
->highq
];
3335 thread_t thread
= cqe_queue_first(queue
, struct thread
, runq_links
);
3336 assert_thread_magic(thread
);
3343 /* Assumes RT lock is not held, and acquires splsched/rt_lock itself */
3345 sched_rtglobal_runq_scan(sched_update_scan_context_t scan_context
)
3350 processor_set_t pset
= &pset0
;
3355 qe_foreach_element_safe(thread
, &pset
->rt_runq
.queue
, runq_links
) {
3356 if (thread
->last_made_runnable_time
< scan_context
->earliest_rt_make_runnable_time
) {
3357 scan_context
->earliest_rt_make_runnable_time
= thread
->last_made_runnable_time
;
3361 rt_lock_unlock(pset
);
3366 sched_rtglobal_runq_count_sum(void)
3368 return pset0
.rt_runq
.runq_stats
.count_sum
;
3372 * realtime_queue_insert:
3374 * Enqueue a thread for realtime execution.
3377 realtime_queue_insert(processor_t processor
, processor_set_t pset
, thread_t thread
)
3379 queue_t queue
= &SCHED(rt_runq
)(pset
)->queue
;
3380 uint64_t deadline
= thread
->realtime
.deadline
;
3381 boolean_t preempt
= FALSE
;
3385 if (queue_empty(queue
)) {
3386 enqueue_tail(queue
, &thread
->runq_links
);
3389 /* Insert into rt_runq in thread deadline order */
3391 qe_foreach(iter
, queue
) {
3392 thread_t iter_thread
= qe_element(iter
, struct thread
, runq_links
);
3393 assert_thread_magic(iter_thread
);
3395 if (deadline
< iter_thread
->realtime
.deadline
) {
3396 if (iter
== queue_first(queue
)) {
3399 insque(&thread
->runq_links
, queue_prev(iter
));
3401 } else if (iter
== queue_last(queue
)) {
3402 enqueue_tail(queue
, &thread
->runq_links
);
3408 thread
->runq
= processor
;
3409 SCHED_STATS_RUNQ_CHANGE(&SCHED(rt_runq
)(pset
)->runq_stats
, rt_runq_count(pset
));
3410 rt_runq_count_incr(pset
);
3412 rt_lock_unlock(pset
);
3420 * Dispatch a thread for realtime execution.
3422 * Thread must be locked. Associated pset must
3423 * be locked, and is returned unlocked.
3427 processor_t processor
,
3430 processor_set_t pset
= processor
->processor_set
;
3431 pset_assert_locked(pset
);
3434 sched_ipi_type_t ipi_type
= SCHED_IPI_NONE
;
3436 thread
->chosen_processor
= processor
;
3438 /* <rdar://problem/15102234> */
3439 assert(thread
->bound_processor
== PROCESSOR_NULL
);
3441 if (processor
->current_pri
< BASEPRI_RTQUEUES
) {
3442 preempt
= (AST_PREEMPT
| AST_URGENT
);
3443 } else if (thread
->realtime
.deadline
< processor
->deadline
) {
3444 preempt
= (AST_PREEMPT
| AST_URGENT
);
3449 realtime_queue_insert(processor
, pset
, thread
);
3451 ipi_type
= SCHED_IPI_NONE
;
3452 if (preempt
!= AST_NONE
) {
3453 if (processor
->state
== PROCESSOR_IDLE
) {
3454 processor_state_update_from_thread(processor
, thread
);
3455 processor
->deadline
= thread
->realtime
.deadline
;
3456 pset_update_processor_state(pset
, processor
, PROCESSOR_DISPATCHING
);
3457 if (processor
== current_processor()) {
3460 ipi_type
= sched_ipi_action(processor
, thread
, true, SCHED_IPI_EVENT_PREEMPT
);
3462 } else if (processor
->state
== PROCESSOR_DISPATCHING
) {
3463 if ((processor
->current_pri
< thread
->sched_pri
) || (processor
->deadline
> thread
->realtime
.deadline
)) {
3464 processor_state_update_from_thread(processor
, thread
);
3465 processor
->deadline
= thread
->realtime
.deadline
;
3468 if (processor
== current_processor()) {
3471 if ((preempt
& AST_URGENT
) == AST_URGENT
) {
3472 bit_set(pset
->pending_AST_URGENT_cpu_mask
, processor
->cpu_id
);
3475 if ((preempt
& AST_PREEMPT
) == AST_PREEMPT
) {
3476 bit_set(pset
->pending_AST_PREEMPT_cpu_mask
, processor
->cpu_id
);
3479 ipi_type
= sched_ipi_action(processor
, thread
, false, SCHED_IPI_EVENT_PREEMPT
);
3483 /* Selected processor was too busy, just keep thread enqueued and let other processors drain it naturally. */
3487 sched_ipi_perform(processor
, ipi_type
);
3492 sched_ipi_deferred_policy(processor_set_t pset
, processor_t dst
,
3493 __unused sched_ipi_event_t event
)
3495 #if defined(CONFIG_SCHED_DEFERRED_AST)
3496 if (!bit_test(pset
->pending_deferred_AST_cpu_mask
, dst
->cpu_id
)) {
3497 return SCHED_IPI_DEFERRED
;
3499 #else /* CONFIG_SCHED_DEFERRED_AST */
3500 panic("Request for deferred IPI on an unsupported platform; pset: %p CPU: %d", pset
, dst
->cpu_id
);
3501 #endif /* CONFIG_SCHED_DEFERRED_AST */
3502 return SCHED_IPI_NONE
;
3506 sched_ipi_action(processor_t dst
, thread_t thread
, boolean_t dst_idle
, sched_ipi_event_t event
)
3508 sched_ipi_type_t ipi_type
= SCHED_IPI_NONE
;
3509 assert(dst
!= NULL
);
3511 processor_set_t pset
= dst
->processor_set
;
3512 if (current_processor() == dst
) {
3513 return SCHED_IPI_NONE
;
3516 if (bit_test(pset
->pending_AST_URGENT_cpu_mask
, dst
->cpu_id
)) {
3517 return SCHED_IPI_NONE
;
3520 ipi_type
= SCHED(ipi_policy
)(dst
, thread
, dst_idle
, event
);
3522 case SCHED_IPI_NONE
:
3523 return SCHED_IPI_NONE
;
3524 #if defined(CONFIG_SCHED_DEFERRED_AST)
3525 case SCHED_IPI_DEFERRED
:
3526 bit_set(pset
->pending_deferred_AST_cpu_mask
, dst
->cpu_id
);
3528 #endif /* CONFIG_SCHED_DEFERRED_AST */
3530 bit_set(pset
->pending_AST_URGENT_cpu_mask
, dst
->cpu_id
);
3531 bit_set(pset
->pending_AST_PREEMPT_cpu_mask
, dst
->cpu_id
);
3538 sched_ipi_policy(processor_t dst
, thread_t thread
, boolean_t dst_idle
, sched_ipi_event_t event
)
3540 sched_ipi_type_t ipi_type
= SCHED_IPI_NONE
;
3541 boolean_t deferred_ipi_supported
= false;
3542 processor_set_t pset
= dst
->processor_set
;
3544 #if defined(CONFIG_SCHED_DEFERRED_AST)
3545 deferred_ipi_supported
= true;
3546 #endif /* CONFIG_SCHED_DEFERRED_AST */
3549 case SCHED_IPI_EVENT_SPILL
:
3550 case SCHED_IPI_EVENT_SMT_REBAL
:
3551 case SCHED_IPI_EVENT_REBALANCE
:
3552 case SCHED_IPI_EVENT_BOUND_THR
:
3554 * The spill, SMT rebalance, rebalance and the bound thread
3555 * scenarios use immediate IPIs always.
3557 ipi_type
= dst_idle
? SCHED_IPI_IDLE
: SCHED_IPI_IMMEDIATE
;
3559 case SCHED_IPI_EVENT_PREEMPT
:
3560 /* In the preemption case, use immediate IPIs for RT threads */
3561 if (thread
&& (thread
->sched_pri
>= BASEPRI_RTQUEUES
)) {
3562 ipi_type
= dst_idle
? SCHED_IPI_IDLE
: SCHED_IPI_IMMEDIATE
;
3567 * For Non-RT threads preemption,
3568 * If the core is active, use immediate IPIs.
3569 * If the core is idle, use deferred IPIs if supported; otherwise immediate IPI.
3571 if (deferred_ipi_supported
&& dst_idle
) {
3572 return sched_ipi_deferred_policy(pset
, dst
, event
);
3574 ipi_type
= dst_idle
? SCHED_IPI_IDLE
: SCHED_IPI_IMMEDIATE
;
3577 panic("Unrecognized scheduler IPI event type %d", event
);
3579 assert(ipi_type
!= SCHED_IPI_NONE
);
3584 sched_ipi_perform(processor_t dst
, sched_ipi_type_t ipi
)
3587 case SCHED_IPI_NONE
:
3589 case SCHED_IPI_IDLE
:
3590 machine_signal_idle(dst
);
3592 case SCHED_IPI_IMMEDIATE
:
3593 cause_ast_check(dst
);
3595 case SCHED_IPI_DEFERRED
:
3596 machine_signal_idle_deferred(dst
);
3599 panic("Unrecognized scheduler IPI type: %d", ipi
);
3603 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
3606 priority_is_urgent(int priority
)
3608 return bitmap_test(sched_preempt_pri
, priority
) ? TRUE
: FALSE
;
3611 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
3616 * Dispatch a thread for execution on a
3619 * Thread must be locked. Associated pset must
3620 * be locked, and is returned unlocked.
3624 processor_t processor
,
3628 processor_set_t pset
= processor
->processor_set
;
3629 pset_assert_locked(pset
);
3631 enum { eExitIdle
, eInterruptRunning
, eDoNothing
} ipi_action
= eDoNothing
;
3633 sched_ipi_type_t ipi_type
= SCHED_IPI_NONE
;
3635 thread
->chosen_processor
= processor
;
3638 * Set preemption mode.
3640 #if defined(CONFIG_SCHED_DEFERRED_AST)
3641 /* TODO: Do we need to care about urgency (see rdar://problem/20136239)? */
3643 if (SCHED(priority_is_urgent
)(thread
->sched_pri
) && thread
->sched_pri
> processor
->current_pri
) {
3644 preempt
= (AST_PREEMPT
| AST_URGENT
);
3645 } else if (processor
->active_thread
&& thread_eager_preemption(processor
->active_thread
)) {
3646 preempt
= (AST_PREEMPT
| AST_URGENT
);
3647 } else if ((thread
->sched_mode
== TH_MODE_TIMESHARE
) && (thread
->sched_pri
< thread
->base_pri
)) {
3648 if (SCHED(priority_is_urgent
)(thread
->base_pri
) && thread
->sched_pri
> processor
->current_pri
) {
3649 preempt
= (options
& SCHED_PREEMPT
)? AST_PREEMPT
: AST_NONE
;
3654 preempt
= (options
& SCHED_PREEMPT
)? AST_PREEMPT
: AST_NONE
;
3657 if ((options
& (SCHED_PREEMPT
| SCHED_REBALANCE
)) == (SCHED_PREEMPT
| SCHED_REBALANCE
)) {
3659 * Having gone to the trouble of forcing this thread off a less preferred core,
3660 * we should force the preferable core to reschedule immediately to give this
3661 * thread a chance to run instead of just sitting on the run queue where
3662 * it may just be stolen back by the idle core we just forced it off.
3664 preempt
|= AST_PREEMPT
;
3667 SCHED(processor_enqueue
)(processor
, thread
, options
);
3668 sched_update_pset_load_average(pset
);
3670 if (preempt
!= AST_NONE
) {
3671 if (processor
->state
== PROCESSOR_IDLE
) {
3672 processor_state_update_from_thread(processor
, thread
);
3673 processor
->deadline
= UINT64_MAX
;
3674 pset_update_processor_state(pset
, processor
, PROCESSOR_DISPATCHING
);
3675 ipi_action
= eExitIdle
;
3676 } else if (processor
->state
== PROCESSOR_DISPATCHING
) {
3677 if (processor
->current_pri
< thread
->sched_pri
) {
3678 processor_state_update_from_thread(processor
, thread
);
3679 processor
->deadline
= UINT64_MAX
;
3681 } else if ((processor
->state
== PROCESSOR_RUNNING
||
3682 processor
->state
== PROCESSOR_SHUTDOWN
) &&
3683 (thread
->sched_pri
>= processor
->current_pri
)) {
3684 ipi_action
= eInterruptRunning
;
3688 * New thread is not important enough to preempt what is running, but
3689 * special processor states may need special handling
3691 if (processor
->state
== PROCESSOR_SHUTDOWN
&&
3692 thread
->sched_pri
>= processor
->current_pri
) {
3693 ipi_action
= eInterruptRunning
;
3694 } else if (processor
->state
== PROCESSOR_IDLE
) {
3695 processor_state_update_from_thread(processor
, thread
);
3696 processor
->deadline
= UINT64_MAX
;
3697 pset_update_processor_state(pset
, processor
, PROCESSOR_DISPATCHING
);
3699 ipi_action
= eExitIdle
;
3703 if (ipi_action
!= eDoNothing
) {
3704 if (processor
== current_processor()) {
3705 if ((preempt
= csw_check_locked(processor
->active_thread
, processor
, pset
, AST_NONE
)) != AST_NONE
) {
3709 if ((preempt
& AST_URGENT
) == AST_URGENT
) {
3710 bit_set(pset
->pending_AST_URGENT_cpu_mask
, processor
->cpu_id
);
3712 bit_clear(pset
->pending_AST_URGENT_cpu_mask
, processor
->cpu_id
);
3715 if ((preempt
& AST_PREEMPT
) == AST_PREEMPT
) {
3716 bit_set(pset
->pending_AST_PREEMPT_cpu_mask
, processor
->cpu_id
);
3718 bit_clear(pset
->pending_AST_PREEMPT_cpu_mask
, processor
->cpu_id
);
3721 sched_ipi_event_t event
= (options
& SCHED_REBALANCE
) ? SCHED_IPI_EVENT_REBALANCE
: SCHED_IPI_EVENT_PREEMPT
;
3722 ipi_type
= sched_ipi_action(processor
, thread
, (ipi_action
== eExitIdle
), event
);
3726 sched_ipi_perform(processor
, ipi_type
);
3732 * Return the next sibling pset containing
3733 * available processors.
3735 * Returns the original pset if none other is
3738 static processor_set_t
3740 processor_set_t pset
)
3742 processor_set_t nset
= pset
;
3745 nset
= next_pset(nset
);
3746 } while (nset
->online_processor_count
< 1 && nset
!= pset
);
3754 * Choose a processor for the thread, beginning at
3755 * the pset. Accepts an optional processor hint in
3758 * Returns a processor, possibly from a different pset.
3760 * The thread must be locked. The pset must be locked,
3761 * and the resulting pset is locked on return.
3765 processor_set_t starting_pset
,
3766 processor_t processor
,
3769 processor_set_t pset
= starting_pset
;
3770 processor_set_t nset
;
3772 assert(thread
->sched_pri
<= BASEPRI_RTQUEUES
);
3775 * Prefer the hinted processor, when appropriate.
3778 /* Fold last processor hint from secondary processor to its primary */
3779 if (processor
!= PROCESSOR_NULL
) {
3780 processor
= processor
->processor_primary
;
3784 * Only consult platform layer if pset is active, which
3785 * it may not be in some cases when a multi-set system
3786 * is going to sleep.
3788 if (pset
->online_processor_count
) {
3789 if ((processor
== PROCESSOR_NULL
) || (processor
->processor_set
== pset
&& processor
->state
== PROCESSOR_IDLE
)) {
3790 processor_t mc_processor
= machine_choose_processor(pset
, processor
);
3791 if (mc_processor
!= PROCESSOR_NULL
) {
3792 processor
= mc_processor
->processor_primary
;
3798 * At this point, we may have a processor hint, and we may have
3799 * an initial starting pset. If the hint is not in the pset, or
3800 * if the hint is for a processor in an invalid state, discard
3803 if (processor
!= PROCESSOR_NULL
) {
3804 if (processor
->processor_set
!= pset
) {
3805 processor
= PROCESSOR_NULL
;
3806 } else if (!processor
->is_recommended
) {
3807 processor
= PROCESSOR_NULL
;
3808 } else if ((thread
->sched_pri
>= BASEPRI_RTQUEUES
) && !sched_ok_to_run_realtime_thread(pset
, processor
)) {
3809 processor
= PROCESSOR_NULL
;
3811 switch (processor
->state
) {
3812 case PROCESSOR_START
:
3813 case PROCESSOR_SHUTDOWN
:
3814 case PROCESSOR_OFF_LINE
:
3816 * Hint is for a processor that cannot support running new threads.
3818 processor
= PROCESSOR_NULL
;
3820 case PROCESSOR_IDLE
:
3822 * Hint is for an idle processor. Assume it is no worse than any other
3823 * idle processor. The platform layer had an opportunity to provide
3824 * the "least cost idle" processor above.
3827 case PROCESSOR_RUNNING
:
3828 case PROCESSOR_DISPATCHING
:
3830 * Hint is for an active CPU. This fast-path allows
3831 * realtime threads to preempt non-realtime threads
3832 * to regain their previous executing processor.
3834 if ((thread
->sched_pri
>= BASEPRI_RTQUEUES
) &&
3835 (processor
->current_pri
< BASEPRI_RTQUEUES
)) {
3839 /* Otherwise, use hint as part of search below */
3842 processor
= PROCESSOR_NULL
;
3849 * Iterate through the processor sets to locate
3850 * an appropriate processor. Seed results with
3851 * a last-processor hint, if available, so that
3852 * a search must find something strictly better
3855 * A primary/secondary pair of SMT processors are
3856 * "unpaired" if the primary is busy but its
3857 * corresponding secondary is idle (so the physical
3858 * core has full use of its resources).
3861 integer_t lowest_priority
= MAXPRI
+ 1;
3862 integer_t lowest_secondary_priority
= MAXPRI
+ 1;
3863 integer_t lowest_unpaired_primary_priority
= MAXPRI
+ 1;
3864 integer_t lowest_idle_secondary_priority
= MAXPRI
+ 1;
3865 integer_t lowest_count
= INT_MAX
;
3866 uint64_t furthest_deadline
= 1;
3867 processor_t lp_processor
= PROCESSOR_NULL
;
3868 processor_t lp_unpaired_primary_processor
= PROCESSOR_NULL
;
3869 processor_t lp_idle_secondary_processor
= PROCESSOR_NULL
;
3870 processor_t lp_paired_secondary_processor
= PROCESSOR_NULL
;
3871 processor_t lc_processor
= PROCESSOR_NULL
;
3872 processor_t fd_processor
= PROCESSOR_NULL
;
3874 if (processor
!= PROCESSOR_NULL
) {
3875 /* All other states should be enumerated above. */
3876 assert(processor
->state
== PROCESSOR_RUNNING
|| processor
->state
== PROCESSOR_DISPATCHING
);
3878 lowest_priority
= processor
->current_pri
;
3879 lp_processor
= processor
;
3881 if (processor
->current_pri
>= BASEPRI_RTQUEUES
) {
3882 furthest_deadline
= processor
->deadline
;
3883 fd_processor
= processor
;
3886 lowest_count
= SCHED(processor_runq_count
)(processor
);
3887 lc_processor
= processor
;
3893 if (thread
->sched_pri
>= BASEPRI_RTQUEUES
) {
3894 processor
= choose_processor_for_realtime_thread(pset
);
3900 * Choose an idle processor, in pset traversal order
3903 uint64_t idle_primary_map
= (pset
->cpu_state_map
[PROCESSOR_IDLE
] &
3905 pset
->recommended_bitmask
);
3907 /* there shouldn't be a pending AST if the processor is idle */
3908 assert((idle_primary_map
& pset
->pending_AST_URGENT_cpu_mask
) == 0);
3910 cpuid
= lsb_first(idle_primary_map
);
3912 processor
= processor_array
[cpuid
];
3918 * Otherwise, enumerate active and idle processors to find primary candidates
3919 * with lower priority/etc.
3922 uint64_t active_map
= ((pset
->cpu_state_map
[PROCESSOR_RUNNING
] | pset
->cpu_state_map
[PROCESSOR_DISPATCHING
]) &
3923 pset
->recommended_bitmask
&
3924 ~pset
->pending_AST_URGENT_cpu_mask
);
3926 if (SCHED(priority_is_urgent
)(thread
->sched_pri
) == FALSE
) {
3927 active_map
&= ~pset
->pending_AST_PREEMPT_cpu_mask
;
3930 active_map
= bit_ror64(active_map
, (pset
->last_chosen
+ 1));
3931 for (int rotid
= lsb_first(active_map
); rotid
>= 0; rotid
= lsb_next(active_map
, rotid
)) {
3932 cpuid
= ((rotid
+ pset
->last_chosen
+ 1) & 63);
3933 processor
= processor_array
[cpuid
];
3935 integer_t cpri
= processor
->current_pri
;
3936 processor_t primary
= processor
->processor_primary
;
3937 if (primary
!= processor
) {
3938 /* If primary is running a NO_SMT thread, don't choose its secondary */
3939 if (!((primary
->state
== PROCESSOR_RUNNING
) && processor_active_thread_no_smt(primary
))) {
3940 if (cpri
< lowest_secondary_priority
) {
3941 lowest_secondary_priority
= cpri
;
3942 lp_paired_secondary_processor
= processor
;
3946 if (cpri
< lowest_priority
) {
3947 lowest_priority
= cpri
;
3948 lp_processor
= processor
;
3952 if ((cpri
>= BASEPRI_RTQUEUES
) && (processor
->deadline
> furthest_deadline
)) {
3953 furthest_deadline
= processor
->deadline
;
3954 fd_processor
= processor
;
3957 integer_t ccount
= SCHED(processor_runq_count
)(processor
);
3958 if (ccount
< lowest_count
) {
3959 lowest_count
= ccount
;
3960 lc_processor
= processor
;
3965 * For SMT configs, these idle secondary processors must have active primary. Otherwise
3966 * the idle primary would have short-circuited the loop above
3968 uint64_t idle_secondary_map
= (pset
->cpu_state_map
[PROCESSOR_IDLE
] &
3969 ~pset
->primary_map
&
3970 pset
->recommended_bitmask
);
3972 /* there shouldn't be a pending AST if the processor is idle */
3973 assert((idle_secondary_map
& pset
->pending_AST_URGENT_cpu_mask
) == 0);
3974 assert((idle_secondary_map
& pset
->pending_AST_PREEMPT_cpu_mask
) == 0);
3976 for (cpuid
= lsb_first(idle_secondary_map
); cpuid
>= 0; cpuid
= lsb_next(idle_secondary_map
, cpuid
)) {
3977 processor
= processor_array
[cpuid
];
3979 processor_t cprimary
= processor
->processor_primary
;
3981 integer_t primary_pri
= cprimary
->current_pri
;
3984 * TODO: This should also make the same decisions
3985 * as secondary_can_run_realtime_thread
3987 * TODO: Keep track of the pending preemption priority
3988 * of the primary to make this more accurate.
3991 /* If the primary is running a no-smt thread, then don't choose its secondary */
3992 if (cprimary
->state
== PROCESSOR_RUNNING
&&
3993 processor_active_thread_no_smt(cprimary
)) {
3998 * Find the idle secondary processor with the lowest priority primary
4000 * We will choose this processor as a fallback if we find no better
4001 * primary to preempt.
4003 if (primary_pri
< lowest_idle_secondary_priority
) {
4004 lp_idle_secondary_processor
= processor
;
4005 lowest_idle_secondary_priority
= primary_pri
;
4008 /* Find the the lowest priority active primary with idle secondary */
4009 if (primary_pri
< lowest_unpaired_primary_priority
) {
4010 /* If the primary processor is offline or starting up, it's not a candidate for this path */
4011 if (cprimary
->state
!= PROCESSOR_RUNNING
&&
4012 cprimary
->state
!= PROCESSOR_DISPATCHING
) {
4016 if (!cprimary
->is_recommended
) {
4020 /* if the primary is pending preemption, don't try to re-preempt it */
4021 if (bit_test(pset
->pending_AST_URGENT_cpu_mask
, cprimary
->cpu_id
)) {
4025 if (SCHED(priority_is_urgent
)(thread
->sched_pri
) == FALSE
&&
4026 bit_test(pset
->pending_AST_PREEMPT_cpu_mask
, cprimary
->cpu_id
)) {
4030 lowest_unpaired_primary_priority
= primary_pri
;
4031 lp_unpaired_primary_processor
= cprimary
;
4036 * We prefer preempting a primary processor over waking up its secondary.
4037 * The secondary will then be woken up by the preempted thread.
4039 if (thread
->sched_pri
> lowest_unpaired_primary_priority
) {
4040 pset
->last_chosen
= lp_unpaired_primary_processor
->cpu_id
;
4041 return lp_unpaired_primary_processor
;
4045 * We prefer preempting a lower priority active processor over directly
4046 * waking up an idle secondary.
4047 * The preempted thread will then find the idle secondary.
4049 if (thread
->sched_pri
> lowest_priority
) {
4050 pset
->last_chosen
= lp_processor
->cpu_id
;
4051 return lp_processor
;
4054 if (thread
->sched_pri
>= BASEPRI_RTQUEUES
) {
4056 * For realtime threads, the most important aspect is
4057 * scheduling latency, so we will pick an active
4058 * secondary processor in this pset, or preempt
4059 * another RT thread with a further deadline before
4060 * going to the next pset.
4063 if (sched_allow_rt_smt
&& (thread
->sched_pri
> lowest_secondary_priority
)) {
4064 pset
->last_chosen
= lp_paired_secondary_processor
->cpu_id
;
4065 return lp_paired_secondary_processor
;
4068 if (thread
->realtime
.deadline
< furthest_deadline
) {
4069 return fd_processor
;
4074 * lc_processor is used to indicate the best processor set run queue
4075 * on which to enqueue a thread when all available CPUs are busy with
4076 * higher priority threads, so try to make sure it is initialized.
4078 if (lc_processor
== PROCESSOR_NULL
) {
4079 cpumap_t available_map
= ((pset
->cpu_state_map
[PROCESSOR_IDLE
] |
4080 pset
->cpu_state_map
[PROCESSOR_RUNNING
] |
4081 pset
->cpu_state_map
[PROCESSOR_DISPATCHING
]) &
4082 pset
->recommended_bitmask
);
4083 cpuid
= lsb_first(available_map
);
4085 lc_processor
= processor_array
[cpuid
];
4086 lowest_count
= SCHED(processor_runq_count
)(lc_processor
);
4091 * Move onto the next processor set.
4093 * If all primary processors in this pset are running a higher
4094 * priority thread, move on to next pset. Only when we have
4095 * exhausted the search for primary processors do we
4096 * fall back to secondaries.
4098 nset
= next_pset(pset
);
4100 if (nset
!= starting_pset
) {
4106 } while (nset
!= starting_pset
);
4109 * Make sure that we pick a running processor,
4110 * and that the correct processor set is locked.
4111 * Since we may have unlocked the candidate processor's
4112 * pset, it may have changed state.
4114 * All primary processors are running a higher priority
4115 * thread, so the only options left are enqueuing on
4116 * the secondary processor that would perturb the least priority
4117 * primary, or the least busy primary.
4119 boolean_t fallback_processor
= false;
4121 /* lowest_priority is evaluated in the main loops above */
4122 if (lp_idle_secondary_processor
!= PROCESSOR_NULL
) {
4123 processor
= lp_idle_secondary_processor
;
4124 lp_idle_secondary_processor
= PROCESSOR_NULL
;
4125 } else if (lp_paired_secondary_processor
!= PROCESSOR_NULL
) {
4126 processor
= lp_paired_secondary_processor
;
4127 lp_paired_secondary_processor
= PROCESSOR_NULL
;
4128 } else if (lc_processor
!= PROCESSOR_NULL
) {
4129 processor
= lc_processor
;
4130 lc_processor
= PROCESSOR_NULL
;
4133 * All processors are executing higher priority threads, and
4134 * the lowest_count candidate was not usable.
4136 * For AMP platforms running the clutch scheduler always
4137 * return a processor from the requested pset to allow the
4138 * thread to be enqueued in the correct runq. For non-AMP
4139 * platforms, simply return the master_processor.
4141 fallback_processor
= true;
4142 processor
= master_processor
;
4146 * Check that the correct processor set is
4149 if (pset
!= processor
->processor_set
) {
4151 pset
= processor
->processor_set
;
4156 * We must verify that the chosen processor is still available.
4157 * The cases where we pick the master_processor or the fallback
4158 * processor are execptions, since we may need enqueue a thread
4159 * on its runqueue if this is the last remaining processor
4160 * during pset shutdown.
4162 * <rdar://problem/47559304> would really help here since it
4163 * gets rid of the weird last processor SHUTDOWN case where
4164 * the pset is still schedulable.
4166 if (processor
!= master_processor
&& (fallback_processor
== false) && (processor
->state
== PROCESSOR_SHUTDOWN
|| processor
->state
== PROCESSOR_OFF_LINE
)) {
4167 processor
= PROCESSOR_NULL
;
4169 } while (processor
== PROCESSOR_NULL
);
4171 pset
->last_chosen
= processor
->cpu_id
;
4178 * Dispatch thread for execution, onto an idle
4179 * processor or run queue, and signal a preemption
4182 * Thread must be locked.
4187 sched_options_t options
)
4189 processor_t processor
;
4190 processor_set_t pset
;
4192 assert((thread
->state
& (TH_RUN
| TH_WAIT
| TH_UNINT
| TH_TERMINATE
| TH_TERMINATE2
)) == TH_RUN
);
4193 assert(thread
->runq
== PROCESSOR_NULL
);
4196 * Update priority if needed.
4198 if (SCHED(can_update_priority
)(thread
)) {
4199 SCHED(update_priority
)(thread
);
4202 thread
->sfi_class
= sfi_thread_classify(thread
);
4204 assert(thread
->runq
== PROCESSOR_NULL
);
4207 if (thread
->bound_processor
== PROCESSOR_NULL
) {
4211 if (thread
->affinity_set
!= AFFINITY_SET_NULL
) {
4213 * Use affinity set policy hint.
4215 pset
= thread
->affinity_set
->aset_pset
;
4218 processor
= SCHED(choose_processor
)(pset
, PROCESSOR_NULL
, thread
);
4219 pset
= processor
->processor_set
;
4221 SCHED_DEBUG_CHOOSE_PROCESSOR_KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_CHOOSE_PROCESSOR
) | DBG_FUNC_NONE
,
4222 (uintptr_t)thread_tid(thread
), (uintptr_t)-1, processor
->cpu_id
, processor
->state
, 0);
4223 } else if (thread
->last_processor
!= PROCESSOR_NULL
) {
4225 * Simple (last processor) affinity case.
4227 processor
= thread
->last_processor
;
4228 pset
= processor
->processor_set
;
4230 processor
= SCHED(choose_processor
)(pset
, processor
, thread
);
4231 pset
= processor
->processor_set
;
4233 SCHED_DEBUG_CHOOSE_PROCESSOR_KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_CHOOSE_PROCESSOR
) | DBG_FUNC_NONE
,
4234 (uintptr_t)thread_tid(thread
), thread
->last_processor
->cpu_id
, processor
->cpu_id
, processor
->state
, 0);
4239 * Utilitize a per task hint to spread threads
4240 * among the available processor sets.
4242 task_t task
= thread
->task
;
4244 pset
= task
->pset_hint
;
4245 if (pset
== PROCESSOR_SET_NULL
) {
4246 pset
= current_processor()->processor_set
;
4249 pset
= choose_next_pset(pset
);
4252 processor
= SCHED(choose_processor
)(pset
, PROCESSOR_NULL
, thread
);
4253 pset
= processor
->processor_set
;
4254 task
->pset_hint
= pset
;
4256 SCHED_DEBUG_CHOOSE_PROCESSOR_KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_CHOOSE_PROCESSOR
) | DBG_FUNC_NONE
,
4257 (uintptr_t)thread_tid(thread
), (uintptr_t)-1, processor
->cpu_id
, processor
->state
, 0);
4263 * Unconditionally dispatch on the processor.
4265 processor
= thread
->bound_processor
;
4266 pset
= processor
->processor_set
;
4269 SCHED_DEBUG_CHOOSE_PROCESSOR_KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_CHOOSE_PROCESSOR
) | DBG_FUNC_NONE
,
4270 (uintptr_t)thread_tid(thread
), (uintptr_t)-2, processor
->cpu_id
, processor
->state
, 0);
4272 #else /* !__SMP__ */
4273 /* Only one processor to choose */
4274 assert(thread
->bound_processor
== PROCESSOR_NULL
|| thread
->bound_processor
== master_processor
);
4275 processor
= master_processor
;
4276 pset
= processor
->processor_set
;
4278 #endif /* !__SMP__ */
4281 * Dispatch the thread on the chosen processor.
4282 * TODO: This should be based on sched_mode, not sched_pri
4284 if (thread
->sched_pri
>= BASEPRI_RTQUEUES
) {
4285 realtime_setrun(processor
, thread
);
4287 processor_setrun(processor
, thread
, options
);
4289 /* pset is now unlocked */
4290 if (thread
->bound_processor
== PROCESSOR_NULL
) {
4291 SCHED(check_spill
)(pset
, thread
);
4299 processor_set_t pset
= task
->pset_hint
;
4301 if (pset
!= PROCESSOR_SET_NULL
) {
4302 pset
= choose_next_pset(pset
);
4309 * Check for a preemption point in
4310 * the current context.
4312 * Called at splsched with thread locked.
4317 processor_t processor
,
4320 processor_set_t pset
= processor
->processor_set
;
4322 assert(thread
== processor
->active_thread
);
4326 processor_state_update_from_thread(processor
, thread
);
4328 ast_t preempt
= csw_check_locked(thread
, processor
, pset
, check_reason
);
4330 /* Acknowledge the IPI if we decided not to preempt */
4332 if ((preempt
& AST_URGENT
) == 0) {
4333 bit_clear(pset
->pending_AST_URGENT_cpu_mask
, processor
->cpu_id
);
4336 if ((preempt
& AST_PREEMPT
) == 0) {
4337 bit_clear(pset
->pending_AST_PREEMPT_cpu_mask
, processor
->cpu_id
);
4346 * Check for preemption at splsched with
4347 * pset and thread locked
4352 processor_t processor
,
4353 processor_set_t pset
,
4358 if (processor
->first_timeslice
) {
4359 if (rt_runq_count(pset
) > 0) {
4360 return check_reason
| AST_PREEMPT
| AST_URGENT
;
4363 if (rt_runq_count(pset
) > 0) {
4364 if (BASEPRI_RTQUEUES
> processor
->current_pri
) {
4365 return check_reason
| AST_PREEMPT
| AST_URGENT
;
4367 return check_reason
| AST_PREEMPT
;
4374 * If the current thread is running on a processor that is no longer recommended,
4375 * urgently preempt it, at which point thread_select() should
4376 * try to idle the processor and re-dispatch the thread to a recommended processor.
4378 if (!processor
->is_recommended
) {
4379 return check_reason
| AST_PREEMPT
| AST_URGENT
;
4383 result
= SCHED(processor_csw_check
)(processor
);
4384 if (result
!= AST_NONE
) {
4385 return check_reason
| result
| (thread_eager_preemption(thread
) ? AST_URGENT
: AST_NONE
);
4390 * Same for avoid-processor
4392 * TODO: Should these set AST_REBALANCE?
4394 if (SCHED(avoid_processor_enabled
) && SCHED(thread_avoid_processor
)(processor
, thread
)) {
4395 return check_reason
| AST_PREEMPT
;
4399 * Even though we could continue executing on this processor, a
4400 * secondary SMT core should try to shed load to another primary core.
4402 * TODO: Should this do the same check that thread_select does? i.e.
4403 * if no bound threads target this processor, and idle primaries exist, preempt
4404 * The case of RT threads existing is already taken care of above
4407 if (processor
->current_pri
< BASEPRI_RTQUEUES
&&
4408 processor
->processor_primary
!= processor
) {
4409 return check_reason
| AST_PREEMPT
;
4413 if (thread
->state
& TH_SUSP
) {
4414 return check_reason
| AST_PREEMPT
;
4417 #if CONFIG_SCHED_SFI
4419 * Current thread may not need to be preempted, but maybe needs
4422 result
= sfi_thread_needs_ast(thread
, NULL
);
4423 if (result
!= AST_NONE
) {
4424 return check_reason
| result
;
4432 * Handle preemption IPI or IPI in response to setting an AST flag
4433 * Triggered by cause_ast_check
4434 * Called at splsched
4437 ast_check(processor_t processor
)
4439 if (processor
->state
!= PROCESSOR_RUNNING
&&
4440 processor
->state
!= PROCESSOR_SHUTDOWN
) {
4444 thread_t thread
= processor
->active_thread
;
4446 assert(thread
== current_thread());
4448 thread_lock(thread
);
4451 * Propagate thread ast to processor.
4452 * (handles IPI in response to setting AST flag)
4454 ast_propagate(thread
);
4457 * Stash the old urgency and perfctl values to find out if
4458 * csw_check updates them.
4460 thread_urgency_t old_urgency
= processor
->current_urgency
;
4461 perfcontrol_class_t old_perfctl_class
= processor
->current_perfctl_class
;
4465 if ((preempt
= csw_check(thread
, processor
, AST_NONE
)) != AST_NONE
) {
4469 if (old_urgency
!= processor
->current_urgency
) {
4471 * Urgency updates happen with the thread lock held (ugh).
4472 * TODO: This doesn't notice QoS changes...
4474 uint64_t urgency_param1
, urgency_param2
;
4476 thread_urgency_t urgency
= thread_get_urgency(thread
, &urgency_param1
, &urgency_param2
);
4477 thread_tell_urgency(urgency
, urgency_param1
, urgency_param2
, 0, thread
);
4480 thread_unlock(thread
);
4482 if (old_perfctl_class
!= processor
->current_perfctl_class
) {
4484 * We updated the perfctl class of this thread from another core.
4485 * Let CLPC know that the currently running thread has a new
4489 machine_switch_perfcontrol_state_update(PERFCONTROL_ATTR_UPDATE
,
4490 mach_approximate_time(), 0, thread
);
4498 * Set the scheduled priority of the specified thread.
4500 * This may cause the thread to change queues.
4502 * Thread must be locked.
4508 set_sched_pri_options_t options
)
4510 bool is_current_thread
= (thread
== current_thread());
4511 bool removed_from_runq
= false;
4512 bool lazy_update
= ((options
& SETPRI_LAZY
) == SETPRI_LAZY
);
4514 int old_priority
= thread
->sched_pri
;
4516 /* If we're already at this priority, no need to mess with the runqueue */
4517 if (new_priority
== old_priority
) {
4518 #if CONFIG_SCHED_CLUTCH
4519 /* For the first thread in the system, the priority is correct but
4520 * th_sched_bucket is still TH_BUCKET_RUN. Since the clutch
4521 * scheduler relies on the bucket being set for all threads, update
4524 if (thread
->th_sched_bucket
== TH_BUCKET_RUN
) {
4525 assert(is_current_thread
);
4526 SCHED(update_thread_bucket
)(thread
);
4528 #endif /* CONFIG_SCHED_CLUTCH */
4533 if (is_current_thread
) {
4534 assert(thread
->state
& TH_RUN
);
4535 assert(thread
->runq
== PROCESSOR_NULL
);
4537 removed_from_runq
= thread_run_queue_remove(thread
);
4540 thread
->sched_pri
= new_priority
;
4542 #if CONFIG_SCHED_CLUTCH
4544 * Since for the clutch scheduler, the thread's bucket determines its runq
4545 * in the hierarchy it is important to update the bucket when the thread
4546 * lock is held and the thread has been removed from the runq hierarchy.
4548 SCHED(update_thread_bucket
)(thread
);
4550 #endif /* CONFIG_SCHED_CLUTCH */
4552 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_CHANGE_PRIORITY
),
4553 (uintptr_t)thread_tid(thread
),
4556 thread
->sched_usage
,
4559 if (removed_from_runq
) {
4560 thread_run_queue_reinsert(thread
, SCHED_PREEMPT
| SCHED_TAILQ
);
4561 } else if (is_current_thread
) {
4562 processor_t processor
= thread
->last_processor
;
4563 assert(processor
== current_processor());
4565 thread_urgency_t old_urgency
= processor
->current_urgency
;
4568 * When dropping in priority, check if the thread no longer belongs on core.
4569 * If a thread raises its own priority, don't aggressively rebalance it.
4570 * <rdar://problem/31699165>
4572 * csw_check does a processor_state_update_from_thread, but
4573 * we should do our own if we're being lazy.
4575 if (!lazy_update
&& new_priority
< old_priority
) {
4578 if ((preempt
= csw_check(thread
, processor
, AST_NONE
)) != AST_NONE
) {
4582 processor_state_update_from_thread(processor
, thread
);
4586 * set_sched_pri doesn't alter RT params. We expect direct base priority/QoS
4587 * class alterations from user space to occur relatively infrequently, hence
4588 * those are lazily handled. QoS classes have distinct priority bands, and QoS
4589 * inheritance is expected to involve priority changes.
4591 if (processor
->current_urgency
!= old_urgency
) {
4592 uint64_t urgency_param1
, urgency_param2
;
4594 thread_urgency_t new_urgency
= thread_get_urgency(thread
,
4595 &urgency_param1
, &urgency_param2
);
4597 thread_tell_urgency(new_urgency
, urgency_param1
,
4598 urgency_param2
, 0, thread
);
4601 /* TODO: only call this if current_perfctl_class changed */
4602 uint64_t ctime
= mach_approximate_time();
4603 machine_thread_going_on_core(thread
, processor
->current_urgency
, 0, 0, ctime
);
4604 } else if (thread
->state
& TH_RUN
) {
4605 processor_t processor
= thread
->last_processor
;
4608 processor
!= PROCESSOR_NULL
&&
4609 processor
!= current_processor() &&
4610 processor
->active_thread
== thread
) {
4611 cause_ast_check(processor
);
4617 * thread_run_queue_remove_for_handoff
4619 * Pull a thread or its (recursive) push target out of the runqueue
4620 * so that it is ready for thread_run()
4622 * Called at splsched
4624 * Returns the thread that was pulled or THREAD_NULL if no thread could be pulled.
4625 * This may be different than the thread that was passed in.
4628 thread_run_queue_remove_for_handoff(thread_t thread
)
4630 thread_t pulled_thread
= THREAD_NULL
;
4632 thread_lock(thread
);
4635 * Check that the thread is not bound
4636 * to a different processor, and that realtime
4639 * Next, pull it off its run queue. If it
4640 * doesn't come, it's not eligible.
4643 processor_t processor
= current_processor();
4644 if (processor
->current_pri
< BASEPRI_RTQUEUES
&& thread
->sched_pri
< BASEPRI_RTQUEUES
&&
4645 (thread
->bound_processor
== PROCESSOR_NULL
|| thread
->bound_processor
== processor
)) {
4646 if (thread_run_queue_remove(thread
)) {
4647 pulled_thread
= thread
;
4651 thread_unlock(thread
);
4653 return pulled_thread
;
4657 * thread_run_queue_remove:
4659 * Remove a thread from its current run queue and
4660 * return TRUE if successful.
4662 * Thread must be locked.
4664 * If thread->runq is PROCESSOR_NULL, the thread will not re-enter the
4665 * run queues because the caller locked the thread. Otherwise
4666 * the thread is on a run queue, but could be chosen for dispatch
4667 * and removed by another processor under a different lock, which
4668 * will set thread->runq to PROCESSOR_NULL.
4670 * Hence the thread select path must not rely on anything that could
4671 * be changed under the thread lock after calling this function,
4672 * most importantly thread->sched_pri.
4675 thread_run_queue_remove(
4678 boolean_t removed
= FALSE
;
4679 processor_t processor
= thread
->runq
;
4681 if ((thread
->state
& (TH_RUN
| TH_WAIT
)) == TH_WAIT
) {
4682 /* Thread isn't runnable */
4683 assert(thread
->runq
== PROCESSOR_NULL
);
4687 if (processor
== PROCESSOR_NULL
) {
4689 * The thread is either not on the runq,
4690 * or is in the midst of being removed from the runq.
4692 * runq is set to NULL under the pset lock, not the thread
4693 * lock, so the thread may still be in the process of being dequeued
4694 * from the runq. It will wait in invoke for the thread lock to be
4701 if (thread
->sched_pri
< BASEPRI_RTQUEUES
) {
4702 return SCHED(processor_queue_remove
)(processor
, thread
);
4705 processor_set_t pset
= processor
->processor_set
;
4709 if (thread
->runq
!= PROCESSOR_NULL
) {
4711 * Thread is on the RT run queue and we have a lock on
4715 remqueue(&thread
->runq_links
);
4716 SCHED_STATS_RUNQ_CHANGE(&SCHED(rt_runq
)(pset
)->runq_stats
, rt_runq_count(pset
));
4717 rt_runq_count_decr(pset
);
4719 thread
->runq
= PROCESSOR_NULL
;
4724 rt_lock_unlock(pset
);
4730 * Put the thread back where it goes after a thread_run_queue_remove
4732 * Thread must have been removed under the same thread lock hold
4734 * thread locked, at splsched
4737 thread_run_queue_reinsert(thread_t thread
, sched_options_t options
)
4739 assert(thread
->runq
== PROCESSOR_NULL
);
4740 assert(thread
->state
& (TH_RUN
));
4742 thread_setrun(thread
, options
);
4746 sys_override_cpu_throttle(boolean_t enable_override
)
4748 if (enable_override
) {
4749 cpu_throttle_enabled
= 0;
4751 cpu_throttle_enabled
= 1;
4756 thread_get_urgency(thread_t thread
, uint64_t *arg1
, uint64_t *arg2
)
4758 uint64_t urgency_param1
= 0, urgency_param2
= 0;
4760 thread_urgency_t urgency
;
4762 if (thread
== NULL
|| (thread
->state
& TH_IDLE
)) {
4766 urgency
= THREAD_URGENCY_NONE
;
4767 } else if (thread
->sched_mode
== TH_MODE_REALTIME
) {
4768 urgency_param1
= thread
->realtime
.period
;
4769 urgency_param2
= thread
->realtime
.deadline
;
4771 urgency
= THREAD_URGENCY_REAL_TIME
;
4772 } else if (cpu_throttle_enabled
&&
4773 (thread
->sched_pri
<= MAXPRI_THROTTLE
) &&
4774 (thread
->base_pri
<= MAXPRI_THROTTLE
)) {
4776 * Threads that are running at low priority but are not
4777 * tagged with a specific QoS are separated out from
4778 * the "background" urgency. Performance management
4779 * subsystem can decide to either treat these threads
4780 * as normal threads or look at other signals like thermal
4781 * levels for optimal power/perf tradeoffs for a platform.
4783 boolean_t thread_lacks_qos
= (proc_get_effective_thread_policy(thread
, TASK_POLICY_QOS
) == THREAD_QOS_UNSPECIFIED
); //thread_has_qos_policy(thread);
4784 boolean_t task_is_suppressed
= (proc_get_effective_task_policy(thread
->task
, TASK_POLICY_SUP_ACTIVE
) == 0x1);
4787 * Background urgency applied when thread priority is
4788 * MAXPRI_THROTTLE or lower and thread is not promoted
4789 * and thread has a QoS specified
4791 urgency_param1
= thread
->sched_pri
;
4792 urgency_param2
= thread
->base_pri
;
4794 if (thread_lacks_qos
&& !task_is_suppressed
) {
4795 urgency
= THREAD_URGENCY_LOWPRI
;
4797 urgency
= THREAD_URGENCY_BACKGROUND
;
4800 /* For otherwise unclassified threads, report throughput QoS parameters */
4801 urgency_param1
= proc_get_effective_thread_policy(thread
, TASK_POLICY_THROUGH_QOS
);
4802 urgency_param2
= proc_get_effective_task_policy(thread
->task
, TASK_POLICY_THROUGH_QOS
);
4803 urgency
= THREAD_URGENCY_NORMAL
;
4807 *arg1
= urgency_param1
;
4810 *arg2
= urgency_param2
;
4817 thread_get_perfcontrol_class(thread_t thread
)
4819 /* Special case handling */
4820 if (thread
->state
& TH_IDLE
) {
4821 return PERFCONTROL_CLASS_IDLE
;
4823 if (thread
->task
== kernel_task
) {
4824 return PERFCONTROL_CLASS_KERNEL
;
4826 if (thread
->sched_mode
== TH_MODE_REALTIME
) {
4827 return PERFCONTROL_CLASS_REALTIME
;
4830 /* perfcontrol_class based on base_pri */
4831 if (thread
->base_pri
<= MAXPRI_THROTTLE
) {
4832 return PERFCONTROL_CLASS_BACKGROUND
;
4833 } else if (thread
->base_pri
<= BASEPRI_UTILITY
) {
4834 return PERFCONTROL_CLASS_UTILITY
;
4835 } else if (thread
->base_pri
<= BASEPRI_DEFAULT
) {
4836 return PERFCONTROL_CLASS_NONUI
;
4837 } else if (thread
->base_pri
<= BASEPRI_FOREGROUND
) {
4838 return PERFCONTROL_CLASS_UI
;
4840 return PERFCONTROL_CLASS_ABOVEUI
;
4845 * This is the processor idle loop, which just looks for other threads
4846 * to execute. Processor idle threads invoke this without supplying a
4847 * current thread to idle without an asserted wait state.
4849 * Returns a the next thread to execute if dispatched directly.
4853 #define IDLE_KERNEL_DEBUG_CONSTANT(...) KERNEL_DEBUG_CONSTANT(__VA_ARGS__)
4855 #define IDLE_KERNEL_DEBUG_CONSTANT(...) do { } while(0)
4861 processor_t processor
)
4863 processor_set_t pset
= processor
->processor_set
;
4867 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
4868 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_IDLE
) | DBG_FUNC_START
,
4869 (uintptr_t)thread_tid(thread
), 0, 0, 0, 0);
4871 SCHED_STATS_CPU_IDLE_START(processor
);
4873 uint64_t ctime
= mach_absolute_time();
4875 timer_switch(&PROCESSOR_DATA(processor
, system_state
), ctime
, &PROCESSOR_DATA(processor
, idle_state
));
4876 PROCESSOR_DATA(processor
, current_state
) = &PROCESSOR_DATA(processor
, idle_state
);
4878 cpu_quiescent_counter_leave(ctime
);
4882 * Ensure that updates to my processor and pset state,
4883 * made by the IPI source processor before sending the IPI,
4884 * are visible on this processor now (even though we don't
4885 * take the pset lock yet).
4887 atomic_thread_fence(memory_order_acquire
);
4889 if (processor
->state
!= PROCESSOR_IDLE
) {
4892 if (bit_test(pset
->pending_AST_URGENT_cpu_mask
, processor
->cpu_id
)) {
4895 #if defined(CONFIG_SCHED_DEFERRED_AST)
4896 if (bit_test(pset
->pending_deferred_AST_cpu_mask
, processor
->cpu_id
)) {
4900 if (processor
->is_recommended
&& (processor
->processor_primary
== processor
)) {
4901 if (rt_runq_count(pset
)) {
4905 if (SCHED(processor_bound_count
)(processor
)) {
4910 IDLE_KERNEL_DEBUG_CONSTANT(
4911 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_IDLE
) | DBG_FUNC_NONE
, (uintptr_t)thread_tid(thread
), rt_runq_count(pset
), SCHED(processor_runq_count
)(processor
), -1, 0);
4913 machine_track_platform_idle(TRUE
);
4916 /* returns with interrupts enabled */
4918 machine_track_platform_idle(FALSE
);
4923 * Check if we should call sched_timeshare_consider_maintenance() here.
4924 * The CPU was woken out of idle due to an interrupt and we should do the
4925 * call only if the processor is still idle. If the processor is non-idle,
4926 * the threads running on the processor would do the call as part of
4929 if (processor
->state
== PROCESSOR_IDLE
) {
4930 sched_timeshare_consider_maintenance(mach_absolute_time());
4933 IDLE_KERNEL_DEBUG_CONSTANT(
4934 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_IDLE
) | DBG_FUNC_NONE
, (uintptr_t)thread_tid(thread
), rt_runq_count(pset
), SCHED(processor_runq_count
)(processor
), -2, 0);
4936 if (!SCHED(processor_queue_empty
)(processor
)) {
4937 /* Secondary SMT processors respond to directed wakeups
4938 * exclusively. Some platforms induce 'spurious' SMT wakeups.
4940 if (processor
->processor_primary
== processor
) {
4946 ctime
= mach_absolute_time();
4948 timer_switch(&PROCESSOR_DATA(processor
, idle_state
), ctime
, &PROCESSOR_DATA(processor
, system_state
));
4949 PROCESSOR_DATA(processor
, current_state
) = &PROCESSOR_DATA(processor
, system_state
);
4951 cpu_quiescent_counter_join(ctime
);
4953 ast_t reason
= AST_NONE
;
4955 /* We're handling all scheduling AST's */
4956 ast_off(AST_SCHEDULING
);
4959 * thread_select will move the processor from dispatching to running,
4960 * or put it in idle if there's nothing to do.
4962 thread_t current_thread
= current_thread();
4964 thread_lock(current_thread
);
4965 thread_t new_thread
= thread_select(current_thread
, processor
, &reason
);
4966 thread_unlock(current_thread
);
4968 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
4969 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_IDLE
) | DBG_FUNC_END
,
4970 (uintptr_t)thread_tid(thread
), processor
->state
, (uintptr_t)thread_tid(new_thread
), reason
, 0);
4976 * Each processor has a dedicated thread which
4977 * executes the idle loop when there is no suitable
4980 * This continuation is entered with interrupts disabled.
4983 idle_thread(__assert_only
void* parameter
,
4984 __unused wait_result_t result
)
4986 assert(ml_get_interrupts_enabled() == FALSE
);
4987 assert(parameter
== NULL
);
4989 processor_t processor
= current_processor();
4992 * Ensure that anything running in idle context triggers
4993 * preemption-disabled checks.
4995 disable_preemption();
4998 * Enable interrupts temporarily to handle any pending interrupts
4999 * or IPIs before deciding to sleep
5003 thread_t new_thread
= processor_idle(THREAD_NULL
, processor
);
5004 /* returns with interrupts disabled */
5006 enable_preemption();
5008 if (new_thread
!= THREAD_NULL
) {
5009 thread_run(processor
->idle_thread
,
5010 idle_thread
, NULL
, new_thread
);
5014 thread_block(idle_thread
);
5020 processor_t processor
)
5022 kern_return_t result
;
5025 char name
[MAXTHREADNAMESIZE
];
5027 result
= kernel_thread_create(idle_thread
, NULL
, MAXPRI_KERNEL
, &thread
);
5028 if (result
!= KERN_SUCCESS
) {
5032 snprintf(name
, sizeof(name
), "idle #%d", processor
->cpu_id
);
5033 thread_set_thread_name(thread
, name
);
5036 thread_lock(thread
);
5037 thread
->bound_processor
= processor
;
5038 processor
->idle_thread
= thread
;
5039 thread
->sched_pri
= thread
->base_pri
= IDLEPRI
;
5040 thread
->state
= (TH_RUN
| TH_IDLE
);
5041 thread
->options
|= TH_OPT_IDLE_THREAD
;
5042 thread_unlock(thread
);
5045 thread_deallocate(thread
);
5047 return KERN_SUCCESS
;
5053 * Kicks off scheduler services.
5055 * Called at splsched.
5060 kern_return_t result
;
5063 simple_lock_init(&sched_vm_group_list_lock
, 0);
5065 #if __arm__ || __arm64__
5066 simple_lock_init(&sched_recommended_cores_lock
, 0);
5067 #endif /* __arm__ || __arm64__ */
5069 result
= kernel_thread_start_priority((thread_continue_t
)sched_init_thread
,
5070 (void *)SCHED(maintenance_continuation
), MAXPRI_KERNEL
, &thread
);
5071 if (result
!= KERN_SUCCESS
) {
5072 panic("sched_startup");
5075 thread_deallocate(thread
);
5077 assert_thread_magic(thread
);
5080 * Yield to the sched_init_thread once, to
5081 * initialize our own thread after being switched
5084 * The current thread is the only other thread
5085 * active at this point.
5087 thread_block(THREAD_CONTINUE_NULL
);
5091 static _Atomic
uint64_t sched_perfcontrol_callback_deadline
;
5092 #endif /* __arm64__ */
5095 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
5097 static volatile uint64_t sched_maintenance_deadline
;
5098 static uint64_t sched_tick_last_abstime
;
5099 static uint64_t sched_tick_delta
;
5100 uint64_t sched_tick_max_delta
;
5104 * sched_init_thread:
5106 * Perform periodic bookkeeping functions about ten
5110 sched_timeshare_maintenance_continue(void)
5112 uint64_t sched_tick_ctime
, late_time
;
5114 struct sched_update_scan_context scan_context
= {
5115 .earliest_bg_make_runnable_time
= UINT64_MAX
,
5116 .earliest_normal_make_runnable_time
= UINT64_MAX
,
5117 .earliest_rt_make_runnable_time
= UINT64_MAX
5120 sched_tick_ctime
= mach_absolute_time();
5122 if (__improbable(sched_tick_last_abstime
== 0)) {
5123 sched_tick_last_abstime
= sched_tick_ctime
;
5125 sched_tick_delta
= 1;
5127 late_time
= sched_tick_ctime
- sched_tick_last_abstime
;
5128 sched_tick_delta
= late_time
/ sched_tick_interval
;
5129 /* Ensure a delta of 1, since the interval could be slightly
5130 * smaller than the sched_tick_interval due to dispatch
5133 sched_tick_delta
= MAX(sched_tick_delta
, 1);
5135 /* In the event interrupt latencies or platform
5136 * idle events that advanced the timebase resulted
5137 * in periods where no threads were dispatched,
5138 * cap the maximum "tick delta" at SCHED_TICK_MAX_DELTA
5141 sched_tick_delta
= MIN(sched_tick_delta
, SCHED_TICK_MAX_DELTA
);
5143 sched_tick_last_abstime
= sched_tick_ctime
;
5144 sched_tick_max_delta
= MAX(sched_tick_delta
, sched_tick_max_delta
);
5147 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_MAINTENANCE
) | DBG_FUNC_START
,
5148 sched_tick_delta
, late_time
, 0, 0, 0);
5150 /* Add a number of pseudo-ticks corresponding to the elapsed interval
5151 * This could be greater than 1 if substantial intervals where
5152 * all processors are idle occur, which rarely occurs in practice.
5155 sched_tick
+= sched_tick_delta
;
5160 * Compute various averages.
5162 compute_averages(sched_tick_delta
);
5165 * Scan the run queues for threads which
5166 * may need to be updated, and find the earliest runnable thread on the runqueue
5167 * to report its latency.
5169 SCHED(thread_update_scan
)(&scan_context
);
5171 SCHED(rt_runq_scan
)(&scan_context
);
5173 uint64_t ctime
= mach_absolute_time();
5175 uint64_t bg_max_latency
= (ctime
> scan_context
.earliest_bg_make_runnable_time
) ?
5176 ctime
- scan_context
.earliest_bg_make_runnable_time
: 0;
5178 uint64_t default_max_latency
= (ctime
> scan_context
.earliest_normal_make_runnable_time
) ?
5179 ctime
- scan_context
.earliest_normal_make_runnable_time
: 0;
5181 uint64_t realtime_max_latency
= (ctime
> scan_context
.earliest_rt_make_runnable_time
) ?
5182 ctime
- scan_context
.earliest_rt_make_runnable_time
: 0;
5184 machine_max_runnable_latency(bg_max_latency
, default_max_latency
, realtime_max_latency
);
5187 * Check to see if the special sched VM group needs attention.
5189 sched_vm_group_maintenance();
5191 #if __arm__ || __arm64__
5192 /* Check to see if the recommended cores failsafe is active */
5193 sched_recommended_cores_maintenance();
5194 #endif /* __arm__ || __arm64__ */
5197 #if DEBUG || DEVELOPMENT
5199 #include <i386/misc_protos.h>
5200 /* Check for long-duration interrupts */
5201 mp_interrupt_watchdog();
5202 #endif /* __x86_64__ */
5203 #endif /* DEBUG || DEVELOPMENT */
5205 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_MAINTENANCE
) | DBG_FUNC_END
,
5206 sched_pri_shifts
[TH_BUCKET_SHARE_FG
], sched_pri_shifts
[TH_BUCKET_SHARE_BG
],
5207 sched_pri_shifts
[TH_BUCKET_SHARE_UT
], sched_pri_shifts
[TH_BUCKET_SHARE_DF
], 0);
5209 assert_wait((event_t
)sched_timeshare_maintenance_continue
, THREAD_UNINT
);
5210 thread_block((thread_continue_t
)sched_timeshare_maintenance_continue
);
5214 static uint64_t sched_maintenance_wakeups
;
5217 * Determine if the set of routines formerly driven by a maintenance timer
5218 * must be invoked, based on a deadline comparison. Signals the scheduler
5219 * maintenance thread on deadline expiration. Must be invoked at an interval
5220 * lower than the "sched_tick_interval", currently accomplished by
5221 * invocation via the quantum expiration timer and at context switch time.
5222 * Performance matters: this routine reuses a timestamp approximating the
5223 * current absolute time received from the caller, and should perform
5224 * no more than a comparison against the deadline in the common case.
5227 sched_timeshare_consider_maintenance(uint64_t ctime
)
5229 cpu_quiescent_counter_checkin(ctime
);
5231 uint64_t deadline
= sched_maintenance_deadline
;
5233 if (__improbable(ctime
>= deadline
)) {
5234 if (__improbable(current_thread() == sched_maintenance_thread
)) {
5239 uint64_t ndeadline
= ctime
+ sched_tick_interval
;
5241 if (__probable(os_atomic_cmpxchg(&sched_maintenance_deadline
, deadline
, ndeadline
, seq_cst
))) {
5242 thread_wakeup((event_t
)sched_timeshare_maintenance_continue
);
5243 sched_maintenance_wakeups
++;
5247 #if !CONFIG_SCHED_CLUTCH
5249 * Only non-clutch schedulers use the global load calculation EWMA algorithm. For clutch
5250 * scheduler, the load is maintained at the thread group and bucket level.
5252 uint64_t load_compute_deadline
= os_atomic_load_wide(&sched_load_compute_deadline
, relaxed
);
5254 if (__improbable(load_compute_deadline
&& ctime
>= load_compute_deadline
)) {
5255 uint64_t new_deadline
= 0;
5256 if (os_atomic_cmpxchg(&sched_load_compute_deadline
, load_compute_deadline
, new_deadline
, relaxed
)) {
5257 compute_sched_load();
5258 new_deadline
= ctime
+ sched_load_compute_interval_abs
;
5259 os_atomic_store_wide(&sched_load_compute_deadline
, new_deadline
, relaxed
);
5262 #endif /* CONFIG_SCHED_CLUTCH */
5265 uint64_t perf_deadline
= os_atomic_load(&sched_perfcontrol_callback_deadline
, relaxed
);
5267 if (__improbable(perf_deadline
&& ctime
>= perf_deadline
)) {
5268 /* CAS in 0, if success, make callback. Otherwise let the next context switch check again. */
5269 if (os_atomic_cmpxchg(&sched_perfcontrol_callback_deadline
, perf_deadline
, 0, relaxed
)) {
5270 machine_perfcontrol_deadline_passed(perf_deadline
);
5273 #endif /* __arm64__ */
5276 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
5279 sched_init_thread(void (*continuation
)(void))
5281 thread_block(THREAD_CONTINUE_NULL
);
5283 thread_t thread
= current_thread();
5285 thread_set_thread_name(thread
, "sched_maintenance_thread");
5287 sched_maintenance_thread
= thread
;
5294 #if defined(CONFIG_SCHED_TIMESHARE_CORE)
5297 * thread_update_scan / runq_scan:
5299 * Scan the run queues to account for timesharing threads
5300 * which need to be updated.
5302 * Scanner runs in two passes. Pass one squirrels likely
5303 * threads away in an array, pass two does the update.
5305 * This is necessary because the run queue is locked for
5306 * the candidate scan, but the thread is locked for the update.
5308 * Array should be sized to make forward progress, without
5309 * disabling preemption for long periods.
5312 #define THREAD_UPDATE_SIZE 128
5314 static thread_t thread_update_array
[THREAD_UPDATE_SIZE
];
5315 static uint32_t thread_update_count
= 0;
5317 /* Returns TRUE if thread was added, FALSE if thread_update_array is full */
5319 thread_update_add_thread(thread_t thread
)
5321 if (thread_update_count
== THREAD_UPDATE_SIZE
) {
5325 thread_update_array
[thread_update_count
++] = thread
;
5326 thread_reference_internal(thread
);
5331 thread_update_process_threads(void)
5333 assert(thread_update_count
<= THREAD_UPDATE_SIZE
);
5335 for (uint32_t i
= 0; i
< thread_update_count
; i
++) {
5336 thread_t thread
= thread_update_array
[i
];
5337 assert_thread_magic(thread
);
5338 thread_update_array
[i
] = THREAD_NULL
;
5340 spl_t s
= splsched();
5341 thread_lock(thread
);
5342 if (!(thread
->state
& (TH_WAIT
)) && thread
->sched_stamp
!= sched_tick
) {
5343 SCHED(update_priority
)(thread
);
5345 thread_unlock(thread
);
5348 thread_deallocate(thread
);
5351 thread_update_count
= 0;
5355 * Scan a runq for candidate threads.
5357 * Returns TRUE if retry is needed.
5362 sched_update_scan_context_t scan_context
)
5364 int count
= runq
->count
;
5373 for (queue_index
= bitmap_first(runq
->bitmap
, NRQS
);
5375 queue_index
= bitmap_next(runq
->bitmap
, queue_index
)) {
5377 circle_queue_t queue
= &runq
->queues
[queue_index
];
5379 cqe_foreach_element(thread
, queue
, runq_links
) {
5381 assert_thread_magic(thread
);
5383 if (thread
->sched_stamp
!= sched_tick
&&
5384 thread
->sched_mode
== TH_MODE_TIMESHARE
) {
5385 if (thread_update_add_thread(thread
) == FALSE
) {
5390 if (cpu_throttle_enabled
&& ((thread
->sched_pri
<= MAXPRI_THROTTLE
) && (thread
->base_pri
<= MAXPRI_THROTTLE
))) {
5391 if (thread
->last_made_runnable_time
< scan_context
->earliest_bg_make_runnable_time
) {
5392 scan_context
->earliest_bg_make_runnable_time
= thread
->last_made_runnable_time
;
5395 if (thread
->last_made_runnable_time
< scan_context
->earliest_normal_make_runnable_time
) {
5396 scan_context
->earliest_normal_make_runnable_time
= thread
->last_made_runnable_time
;
5406 #endif /* CONFIG_SCHED_TIMESHARE_CORE */
5409 thread_eager_preemption(thread_t thread
)
5411 return (thread
->sched_flags
& TH_SFLAG_EAGERPREEMPT
) != 0;
5415 thread_set_eager_preempt(thread_t thread
)
5419 ast_t ast
= AST_NONE
;
5422 p
= current_processor();
5424 thread_lock(thread
);
5425 thread
->sched_flags
|= TH_SFLAG_EAGERPREEMPT
;
5427 if (thread
== current_thread()) {
5428 ast
= csw_check(thread
, p
, AST_NONE
);
5429 thread_unlock(thread
);
5430 if (ast
!= AST_NONE
) {
5431 (void) thread_block_reason(THREAD_CONTINUE_NULL
, NULL
, ast
);
5434 p
= thread
->last_processor
;
5436 if (p
!= PROCESSOR_NULL
&& p
->state
== PROCESSOR_RUNNING
&&
5437 p
->active_thread
== thread
) {
5441 thread_unlock(thread
);
5448 thread_clear_eager_preempt(thread_t thread
)
5453 thread_lock(thread
);
5455 thread
->sched_flags
&= ~TH_SFLAG_EAGERPREEMPT
;
5457 thread_unlock(thread
);
5462 * Scheduling statistics
5465 sched_stats_handle_csw(processor_t processor
, int reasons
, int selfpri
, int otherpri
)
5467 struct processor_sched_statistics
*stats
;
5468 boolean_t to_realtime
= FALSE
;
5470 stats
= &processor
->processor_data
.sched_stats
;
5473 if (otherpri
>= BASEPRI_REALTIME
) {
5474 stats
->rt_sched_count
++;
5478 if ((reasons
& AST_PREEMPT
) != 0) {
5479 stats
->preempt_count
++;
5481 if (selfpri
>= BASEPRI_REALTIME
) {
5482 stats
->preempted_rt_count
++;
5486 stats
->preempted_by_rt_count
++;
5492 sched_stats_handle_runq_change(struct runq_stats
*stats
, int old_count
)
5494 uint64_t timestamp
= mach_absolute_time();
5496 stats
->count_sum
+= (timestamp
- stats
->last_change_timestamp
) * old_count
;
5497 stats
->last_change_timestamp
= timestamp
;
5501 * For calls from assembly code
5503 #undef thread_wakeup
5512 thread_wakeup_with_result(x
, THREAD_AWAKENED
);
5516 preemption_enabled(void)
5518 return get_preemption_level() == 0 && ml_get_interrupts_enabled();
5522 sched_timer_deadline_tracking_init(void)
5524 nanoseconds_to_absolutetime(TIMER_DEADLINE_TRACKING_BIN_1_DEFAULT
, &timer_deadline_tracking_bin_1
);
5525 nanoseconds_to_absolutetime(TIMER_DEADLINE_TRACKING_BIN_2_DEFAULT
, &timer_deadline_tracking_bin_2
);
5528 #if __arm__ || __arm64__
5530 uint32_t perfcontrol_requested_recommended_cores
= ALL_CORES_RECOMMENDED
;
5531 uint32_t perfcontrol_requested_recommended_core_count
= MAX_CPUS
;
5532 bool perfcontrol_failsafe_active
= false;
5533 bool perfcontrol_sleep_override
= false;
5535 uint64_t perfcontrol_failsafe_maintenance_runnable_time
;
5536 uint64_t perfcontrol_failsafe_activation_time
;
5537 uint64_t perfcontrol_failsafe_deactivation_time
;
5539 /* data covering who likely caused it and how long they ran */
5540 #define FAILSAFE_NAME_LEN 33 /* (2*MAXCOMLEN)+1 from size of p_name */
5541 char perfcontrol_failsafe_name
[FAILSAFE_NAME_LEN
];
5542 int perfcontrol_failsafe_pid
;
5543 uint64_t perfcontrol_failsafe_tid
;
5544 uint64_t perfcontrol_failsafe_thread_timer_at_start
;
5545 uint64_t perfcontrol_failsafe_thread_timer_last_seen
;
5546 uint32_t perfcontrol_failsafe_recommended_at_trigger
;
5549 * Perf controller calls here to update the recommended core bitmask.
5550 * If the failsafe is active, we don't immediately apply the new value.
5551 * Instead, we store the new request and use it after the failsafe deactivates.
5553 * If the failsafe is not active, immediately apply the update.
5555 * No scheduler locks are held, no other locks are held that scheduler might depend on,
5556 * interrupts are enabled
5558 * currently prototype is in osfmk/arm/machine_routines.h
5561 sched_perfcontrol_update_recommended_cores(uint32_t recommended_cores
)
5563 assert(preemption_enabled());
5565 spl_t s
= splsched();
5566 simple_lock(&sched_recommended_cores_lock
, LCK_GRP_NULL
);
5568 perfcontrol_requested_recommended_cores
= recommended_cores
;
5569 perfcontrol_requested_recommended_core_count
= __builtin_popcountll(recommended_cores
);
5571 if ((perfcontrol_failsafe_active
== false) && (perfcontrol_sleep_override
== false)) {
5572 sched_update_recommended_cores(perfcontrol_requested_recommended_cores
& usercontrol_requested_recommended_cores
);
5574 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
5575 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_REC_CORES_FAILSAFE
) | DBG_FUNC_NONE
,
5576 perfcontrol_requested_recommended_cores
,
5577 sched_maintenance_thread
->last_made_runnable_time
, 0, 0, 0);
5580 simple_unlock(&sched_recommended_cores_lock
);
5585 sched_override_recommended_cores_for_sleep(void)
5587 spl_t s
= splsched();
5588 simple_lock(&sched_recommended_cores_lock
, LCK_GRP_NULL
);
5590 if (perfcontrol_sleep_override
== false) {
5591 perfcontrol_sleep_override
= true;
5592 sched_update_recommended_cores(ALL_CORES_RECOMMENDED
);
5595 simple_unlock(&sched_recommended_cores_lock
);
5600 sched_restore_recommended_cores_after_sleep(void)
5602 spl_t s
= splsched();
5603 simple_lock(&sched_recommended_cores_lock
, LCK_GRP_NULL
);
5605 if (perfcontrol_sleep_override
== true) {
5606 perfcontrol_sleep_override
= false;
5607 sched_update_recommended_cores(perfcontrol_requested_recommended_cores
& usercontrol_requested_recommended_cores
);
5610 simple_unlock(&sched_recommended_cores_lock
);
5615 * Consider whether we need to activate the recommended cores failsafe
5617 * Called from quantum timer interrupt context of a realtime thread
5618 * No scheduler locks are held, interrupts are disabled
5621 sched_consider_recommended_cores(uint64_t ctime
, thread_t cur_thread
)
5624 * Check if a realtime thread is starving the system
5625 * and bringing up non-recommended cores would help
5627 * TODO: Is this the correct check for recommended == possible cores?
5628 * TODO: Validate the checks without the relevant lock are OK.
5631 if (__improbable(perfcontrol_failsafe_active
== TRUE
)) {
5632 /* keep track of how long the responsible thread runs */
5634 simple_lock(&sched_recommended_cores_lock
, LCK_GRP_NULL
);
5636 if (perfcontrol_failsafe_active
== TRUE
&&
5637 cur_thread
->thread_id
== perfcontrol_failsafe_tid
) {
5638 perfcontrol_failsafe_thread_timer_last_seen
= timer_grab(&cur_thread
->user_timer
) +
5639 timer_grab(&cur_thread
->system_timer
);
5642 simple_unlock(&sched_recommended_cores_lock
);
5644 /* we're already trying to solve the problem, so bail */
5648 /* The failsafe won't help if there are no more processors to enable */
5649 if (__probable(perfcontrol_requested_recommended_core_count
>= processor_count
)) {
5653 uint64_t too_long_ago
= ctime
- perfcontrol_failsafe_starvation_threshold
;
5655 /* Use the maintenance thread as our canary in the coal mine */
5656 thread_t m_thread
= sched_maintenance_thread
;
5658 /* If it doesn't look bad, nothing to see here */
5659 if (__probable(m_thread
->last_made_runnable_time
>= too_long_ago
)) {
5663 /* It looks bad, take the lock to be sure */
5664 thread_lock(m_thread
);
5666 if (m_thread
->runq
== PROCESSOR_NULL
||
5667 (m_thread
->state
& (TH_RUN
| TH_WAIT
)) != TH_RUN
||
5668 m_thread
->last_made_runnable_time
>= too_long_ago
) {
5670 * Maintenance thread is either on cpu or blocked, and
5671 * therefore wouldn't benefit from more cores
5673 thread_unlock(m_thread
);
5677 uint64_t maintenance_runnable_time
= m_thread
->last_made_runnable_time
;
5679 thread_unlock(m_thread
);
5682 * There are cores disabled at perfcontrol's recommendation, but the
5683 * system is so overloaded that the maintenance thread can't run.
5684 * That likely means that perfcontrol can't run either, so it can't fix
5685 * the recommendation. We have to kick in a failsafe to keep from starving.
5687 * When the maintenance thread has been starved for too long,
5688 * ignore the recommendation from perfcontrol and light up all the cores.
5690 * TODO: Consider weird states like boot, sleep, or debugger
5693 simple_lock(&sched_recommended_cores_lock
, LCK_GRP_NULL
);
5695 if (perfcontrol_failsafe_active
== TRUE
) {
5696 simple_unlock(&sched_recommended_cores_lock
);
5700 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
5701 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_REC_CORES_FAILSAFE
) | DBG_FUNC_START
,
5702 perfcontrol_requested_recommended_cores
, maintenance_runnable_time
, 0, 0, 0);
5704 perfcontrol_failsafe_active
= TRUE
;
5705 perfcontrol_failsafe_activation_time
= mach_absolute_time();
5706 perfcontrol_failsafe_maintenance_runnable_time
= maintenance_runnable_time
;
5707 perfcontrol_failsafe_recommended_at_trigger
= perfcontrol_requested_recommended_cores
;
5709 /* Capture some data about who screwed up (assuming that the thread on core is at fault) */
5710 task_t task
= cur_thread
->task
;
5711 perfcontrol_failsafe_pid
= task_pid(task
);
5712 strlcpy(perfcontrol_failsafe_name
, proc_name_address(task
->bsd_info
), sizeof(perfcontrol_failsafe_name
));
5714 perfcontrol_failsafe_tid
= cur_thread
->thread_id
;
5716 /* Blame the thread for time it has run recently */
5717 uint64_t recent_computation
= (ctime
- cur_thread
->computation_epoch
) + cur_thread
->computation_metered
;
5719 uint64_t last_seen
= timer_grab(&cur_thread
->user_timer
) + timer_grab(&cur_thread
->system_timer
);
5721 /* Compute the start time of the bad behavior in terms of the thread's on core time */
5722 perfcontrol_failsafe_thread_timer_at_start
= last_seen
- recent_computation
;
5723 perfcontrol_failsafe_thread_timer_last_seen
= last_seen
;
5725 /* Ignore the previously recommended core configuration */
5726 sched_update_recommended_cores(ALL_CORES_RECOMMENDED
);
5728 simple_unlock(&sched_recommended_cores_lock
);
5732 * Now that our bacon has been saved by the failsafe, consider whether to turn it off
5734 * Runs in the context of the maintenance thread, no locks held
5737 sched_recommended_cores_maintenance(void)
5739 /* Common case - no failsafe, nothing to be done here */
5740 if (__probable(perfcontrol_failsafe_active
== FALSE
)) {
5744 uint64_t ctime
= mach_absolute_time();
5746 boolean_t print_diagnostic
= FALSE
;
5747 char p_name
[FAILSAFE_NAME_LEN
] = "";
5749 spl_t s
= splsched();
5750 simple_lock(&sched_recommended_cores_lock
, LCK_GRP_NULL
);
5752 /* Check again, under the lock, to avoid races */
5753 if (perfcontrol_failsafe_active
== FALSE
) {
5758 * Ensure that the other cores get another few ticks to run some threads
5759 * If we don't have this hysteresis, the maintenance thread is the first
5760 * to run, and then it immediately kills the other cores
5762 if ((ctime
- perfcontrol_failsafe_activation_time
) < perfcontrol_failsafe_starvation_threshold
) {
5766 /* Capture some diagnostic state under the lock so we can print it out later */
5768 int pid
= perfcontrol_failsafe_pid
;
5769 uint64_t tid
= perfcontrol_failsafe_tid
;
5771 uint64_t thread_usage
= perfcontrol_failsafe_thread_timer_last_seen
-
5772 perfcontrol_failsafe_thread_timer_at_start
;
5773 uint32_t rec_cores_before
= perfcontrol_failsafe_recommended_at_trigger
;
5774 uint32_t rec_cores_after
= perfcontrol_requested_recommended_cores
;
5775 uint64_t failsafe_duration
= ctime
- perfcontrol_failsafe_activation_time
;
5776 strlcpy(p_name
, perfcontrol_failsafe_name
, sizeof(p_name
));
5778 print_diagnostic
= TRUE
;
5780 /* Deactivate the failsafe and reinstate the requested recommendation settings */
5782 perfcontrol_failsafe_deactivation_time
= ctime
;
5783 perfcontrol_failsafe_active
= FALSE
;
5785 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
5786 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_REC_CORES_FAILSAFE
) | DBG_FUNC_END
,
5787 perfcontrol_requested_recommended_cores
, failsafe_duration
, 0, 0, 0);
5789 sched_update_recommended_cores(perfcontrol_requested_recommended_cores
& usercontrol_requested_recommended_cores
);
5792 simple_unlock(&sched_recommended_cores_lock
);
5795 if (print_diagnostic
) {
5796 uint64_t failsafe_duration_ms
= 0, thread_usage_ms
= 0;
5798 absolutetime_to_nanoseconds(failsafe_duration
, &failsafe_duration_ms
);
5799 failsafe_duration_ms
= failsafe_duration_ms
/ NSEC_PER_MSEC
;
5801 absolutetime_to_nanoseconds(thread_usage
, &thread_usage_ms
);
5802 thread_usage_ms
= thread_usage_ms
/ NSEC_PER_MSEC
;
5804 printf("recommended core failsafe kicked in for %lld ms "
5805 "likely due to %s[%d] thread 0x%llx spending "
5806 "%lld ms on cpu at realtime priority - "
5807 "new recommendation: 0x%x -> 0x%x\n",
5808 failsafe_duration_ms
, p_name
, pid
, tid
, thread_usage_ms
,
5809 rec_cores_before
, rec_cores_after
);
5813 #endif /* __arm__ || __arm64__ */
5816 sched_processor_enable(processor_t processor
, boolean_t enable
)
5818 assert(preemption_enabled());
5820 spl_t s
= splsched();
5821 simple_lock(&sched_recommended_cores_lock
, LCK_GRP_NULL
);
5824 bit_set(usercontrol_requested_recommended_cores
, processor
->cpu_id
);
5826 bit_clear(usercontrol_requested_recommended_cores
, processor
->cpu_id
);
5829 #if __arm__ || __arm64__
5830 if ((perfcontrol_failsafe_active
== false) && (perfcontrol_sleep_override
== false)) {
5831 sched_update_recommended_cores(perfcontrol_requested_recommended_cores
& usercontrol_requested_recommended_cores
);
5833 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE
,
5834 MACHDBG_CODE(DBG_MACH_SCHED
, MACH_REC_CORES_FAILSAFE
) | DBG_FUNC_NONE
,
5835 perfcontrol_requested_recommended_cores
,
5836 sched_maintenance_thread
->last_made_runnable_time
, 0, 0, 0);
5838 #else /* __arm__ || __arm64__ */
5839 sched_update_recommended_cores(usercontrol_requested_recommended_cores
);
5840 #endif /* !__arm__ || __arm64__ */
5842 simple_unlock(&sched_recommended_cores_lock
);
5845 return KERN_SUCCESS
;
5850 * Apply a new recommended cores mask to the processors it affects
5851 * Runs after considering failsafes and such
5853 * Iterate over processors and update their ->is_recommended field.
5854 * If a processor is running, we let it drain out at its next
5855 * quantum expiration or blocking point. If a processor is idle, there
5856 * may be more work for it to do, so IPI it.
5858 * interrupts disabled, sched_recommended_cores_lock is held
5861 sched_update_recommended_cores(uint64_t recommended_cores
)
5863 processor_set_t pset
, nset
;
5864 processor_t processor
;
5865 uint64_t needs_exit_idle_mask
= 0x0;
5866 uint32_t avail_count
;
5868 processor
= processor_list
;
5869 pset
= processor
->processor_set
;
5871 KDBG(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_UPDATE_REC_CORES
) | DBG_FUNC_START
,
5873 #if __arm__ || __arm64__
5874 perfcontrol_failsafe_active
, 0, 0);
5875 #else /* __arm__ || __arm64__ */
5877 #endif /* ! __arm__ || __arm64__ */
5879 if (__builtin_popcountll(recommended_cores
) == 0) {
5880 bit_set(recommended_cores
, master_processor
->cpu_id
); /* add boot processor or we hang */
5883 boolean_t pset_newly_recommended
= false;
5885 /* First set recommended cores */
5889 nset
= processor
->processor_set
;
5893 pset_newly_recommended
= false;
5897 if (bit_test(recommended_cores
, processor
->cpu_id
)) {
5898 processor
->is_recommended
= TRUE
;
5899 if (bit_first(pset
->recommended_bitmask
) == -1) {
5900 pset_newly_recommended
= true;
5902 bit_set(pset
->recommended_bitmask
, processor
->cpu_id
);
5904 if (processor
->state
== PROCESSOR_IDLE
) {
5905 if (processor
!= current_processor()) {
5906 bit_set(needs_exit_idle_mask
, processor
->cpu_id
);
5909 if (processor
->state
!= PROCESSOR_OFF_LINE
) {
5912 if (pset_newly_recommended
) {
5913 SCHED(pset_made_schedulable
)(processor
, pset
, false);
5916 } while ((processor
= processor
->processor_list
) != NULL
);
5919 /* Now shutdown not recommended cores */
5920 processor
= processor_list
;
5921 pset
= processor
->processor_set
;
5925 nset
= processor
->processor_set
;
5932 if (!bit_test(recommended_cores
, processor
->cpu_id
)) {
5933 sched_ipi_type_t ipi_type
= SCHED_IPI_NONE
;
5935 processor
->is_recommended
= FALSE
;
5936 bit_clear(pset
->recommended_bitmask
, processor
->cpu_id
);
5938 if ((processor
->state
== PROCESSOR_RUNNING
) || (processor
->state
== PROCESSOR_DISPATCHING
)) {
5939 ipi_type
= SCHED_IPI_IMMEDIATE
;
5941 SCHED(processor_queue_shutdown
)(processor
);
5944 SCHED(rt_queue_shutdown
)(processor
);
5946 if (ipi_type
!= SCHED_IPI_NONE
) {
5947 if (processor
== current_processor()) {
5948 ast_on(AST_PREEMPT
);
5950 sched_ipi_perform(processor
, ipi_type
);
5956 } while ((processor
= processor
->processor_list
) != NULL
);
5958 processor_avail_count_user
= avail_count
;
5959 #if defined(__x86_64__)
5960 commpage_update_active_cpus();
5965 /* Issue all pending IPIs now that the pset lock has been dropped */
5966 for (int cpuid
= lsb_first(needs_exit_idle_mask
); cpuid
>= 0; cpuid
= lsb_next(needs_exit_idle_mask
, cpuid
)) {
5967 processor
= processor_array
[cpuid
];
5968 machine_signal_idle(processor
);
5971 KDBG(MACHDBG_CODE(DBG_MACH_SCHED
, MACH_SCHED_UPDATE_REC_CORES
) | DBG_FUNC_END
,
5972 needs_exit_idle_mask
, 0, 0, 0);
5976 thread_set_options(uint32_t thopt
)
5979 thread_t t
= current_thread();
5984 t
->options
|= thopt
;
5991 thread_set_pending_block_hint(thread_t thread
, block_hint_t block_hint
)
5993 thread
->pending_block_hint
= block_hint
;
5997 qos_max_parallelism(int qos
, uint64_t options
)
5999 return SCHED(qos_max_parallelism
)(qos
, options
);
6003 sched_qos_max_parallelism(__unused
int qos
, uint64_t options
)
6005 host_basic_info_data_t hinfo
;
6006 mach_msg_type_number_t count
= HOST_BASIC_INFO_COUNT
;
6007 /* Query the machine layer for core information */
6008 __assert_only kern_return_t kret
= host_info(host_self(), HOST_BASIC_INFO
,
6009 (host_info_t
)&hinfo
, &count
);
6010 assert(kret
== KERN_SUCCESS
);
6012 if (options
& QOS_PARALLELISM_COUNT_LOGICAL
) {
6013 return hinfo
.logical_cpu
;
6015 return hinfo
.physical_cpu
;
6019 int sched_allow_NO_SMT_threads
= 1;
6021 thread_no_smt(thread_t thread
)
6023 #if DEBUG || DEVELOPMENT
6024 return sched_allow_NO_SMT_threads
&& (thread
->bound_processor
== PROCESSOR_NULL
) && ((thread
->sched_flags
& TH_SFLAG_NO_SMT
) || (thread
->task
->t_flags
& TF_NO_SMT
));
6026 return sched_allow_NO_SMT_threads
&& (thread
->bound_processor
== PROCESSOR_NULL
) && (thread
->sched_flags
& TH_SFLAG_NO_SMT
);
6031 processor_active_thread_no_smt(processor_t processor
)
6033 return sched_allow_NO_SMT_threads
&& !processor
->current_is_bound
&& processor
->current_is_NO_SMT
;
6039 * Set up or replace old timer with new timer
6041 * Returns true if canceled old timer, false if it did not
6044 sched_perfcontrol_update_callback_deadline(uint64_t new_deadline
)
6047 * Exchange deadline for new deadline, if old deadline was nonzero,
6048 * then I cancelled the callback, otherwise I didn't
6051 return os_atomic_xchg(&sched_perfcontrol_callback_deadline
, new_deadline
,
6055 #endif /* __arm64__ */
6058 sched_update_pset_load_average(processor_set_t pset
)
6060 #if CONFIG_SCHED_CLUTCH
6061 int non_rt_load
= sched_clutch_root_count(&pset
->pset_clutch_root
);
6062 #else /* CONFIG_SCHED_CLUTCH */
6063 int non_rt_load
= pset
->pset_runq
.count
;
6064 #endif /* CONFIG_SCHED_CLUTCH */
6066 int load
= ((bit_count(pset
->cpu_state_map
[PROCESSOR_RUNNING
]) + non_rt_load
+ rt_runq_count(pset
)) << PSET_LOAD_NUMERATOR_SHIFT
);
6067 int new_load_average
= (pset
->load_average
+ load
) >> 1;
6069 pset
->load_average
= new_load_average
;
6071 #if (DEVELOPMENT || DEBUG)
6075 /* pset is locked */
6077 choose_processor_for_realtime_thread(processor_set_t pset
)
6079 #if defined(__x86_64__)
6080 bool avoid_cpu0
= sched_avoid_cpu0
&& bit_test(pset
->cpu_bitmask
, 0);
6082 const bool avoid_cpu0
= false;
6085 uint64_t cpu_map
= (pset
->cpu_bitmask
& pset
->recommended_bitmask
& ~pset
->pending_AST_URGENT_cpu_mask
);
6087 cpu_map
= bit_ror64(cpu_map
, 1);
6090 for (int rotid
= lsb_first(cpu_map
); rotid
>= 0; rotid
= lsb_next(cpu_map
, rotid
)) {
6091 int cpuid
= avoid_cpu0
? ((rotid
+ 1) & 63) : rotid
;
6093 processor_t processor
= processor_array
[cpuid
];
6095 if (processor
->processor_primary
!= processor
) {
6099 if (processor
->state
== PROCESSOR_IDLE
) {
6103 if ((processor
->state
!= PROCESSOR_RUNNING
) && (processor
->state
!= PROCESSOR_DISPATCHING
)) {
6107 if (processor
->current_pri
>= BASEPRI_RTQUEUES
) {
6114 if (!sched_allow_rt_smt
) {
6115 return PROCESSOR_NULL
;
6118 /* Consider secondary processors */
6120 /* Also avoid cpu1 */
6121 cpu_map
= bit_ror64(cpu_map
, 1);
6123 for (int rotid
= lsb_first(cpu_map
); rotid
>= 0; rotid
= lsb_next(cpu_map
, rotid
)) {
6124 int cpuid
= avoid_cpu0
? ((rotid
+ 2) & 63) : rotid
;
6126 processor_t processor
= processor_array
[cpuid
];
6128 if (processor
->processor_primary
== processor
) {
6132 if (processor
->state
== PROCESSOR_IDLE
) {
6136 if ((processor
->state
!= PROCESSOR_RUNNING
) && (processor
->state
!= PROCESSOR_DISPATCHING
)) {
6140 if (processor
->current_pri
>= BASEPRI_RTQUEUES
) {
6147 return PROCESSOR_NULL
;
6150 /* pset is locked */
6152 all_available_primaries_are_running_realtime_threads(processor_set_t pset
)
6154 return these_processors_are_running_realtime_threads(pset
, pset
->primary_map
);
6157 /* pset is locked */
6159 these_processors_are_running_realtime_threads(processor_set_t pset
, uint64_t these_map
)
6161 uint64_t cpu_map
= (pset
->cpu_bitmask
& pset
->recommended_bitmask
) & these_map
;
6163 for (int cpuid
= lsb_first(cpu_map
); cpuid
>= 0; cpuid
= lsb_next(cpu_map
, cpuid
)) {
6164 processor_t processor
= processor_array
[cpuid
];
6166 if (processor
->state
== PROCESSOR_IDLE
) {
6170 if (processor
->state
== PROCESSOR_DISPATCHING
) {
6174 if (processor
->state
!= PROCESSOR_RUNNING
) {
6176 * All other processor states are considered unavailable to run
6177 * realtime threads. In particular, we prefer an available secondary
6178 * processor over the risk of leaving a realtime thread on the run queue
6179 * while waiting for a processor in PROCESSOR_START state,
6180 * which should anyway be a rare case.
6185 if (processor
->current_pri
< BASEPRI_RTQUEUES
) {
6194 sched_ok_to_run_realtime_thread(processor_set_t pset
, processor_t processor
)
6196 bool ok_to_run_realtime_thread
= true;
6197 #if defined(__x86_64__)
6198 if (sched_avoid_cpu0
&& processor
->cpu_id
== 0) {
6199 ok_to_run_realtime_thread
= these_processors_are_running_realtime_threads(pset
, pset
->primary_map
& ~0x1);
6200 } else if (sched_avoid_cpu0
&& (processor
->cpu_id
== 1) && processor
->is_SMT
) {
6201 ok_to_run_realtime_thread
= sched_allow_rt_smt
&& these_processors_are_running_realtime_threads(pset
, ~0x2);
6202 } else if (processor
->processor_primary
!= processor
) {
6203 ok_to_run_realtime_thread
= sched_allow_rt_smt
&& all_available_primaries_are_running_realtime_threads(pset
);
6209 return ok_to_run_realtime_thread
;
6213 sched_pset_made_schedulable(__unused processor_t processor
, processor_set_t pset
, boolean_t drop_lock
)
6221 thread_set_no_smt(bool set
)
6223 thread_t thread
= current_thread();
6225 spl_t s
= splsched();
6226 thread_lock(thread
);
6228 thread
->sched_flags
|= TH_SFLAG_NO_SMT
;
6230 thread
->sched_flags
&= ~TH_SFLAG_NO_SMT
;
6232 thread_unlock(thread
);
6237 thread_get_no_smt(void)
6239 return current_thread()->sched_flags
& TH_SFLAG_NO_SMT
;
6242 #if DEBUG || DEVELOPMENT
6243 extern void sysctl_task_set_no_smt(char no_smt
);
6245 sysctl_task_set_no_smt(char no_smt
)
6247 thread_t thread
= current_thread();
6248 task_t task
= thread
->task
;
6250 if (no_smt
== '1') {
6251 task
->t_flags
|= TF_NO_SMT
;
6253 task
->t_flags
&= ~TF_NO_SMT
;
6257 extern char sysctl_task_get_no_smt(void);
6259 sysctl_task_get_no_smt(void)
6261 thread_t thread
= current_thread();
6262 task_t task
= thread
->task
;
6264 if (task
->t_flags
& TF_NO_SMT
) {
6269 #endif /* DEVELOPMENT || DEBUG */
6272 __private_extern__
void
6273 thread_bind_cluster_type(char cluster_type
)