2 * Copyright (c) 2013 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@
28 #include <mach/mach_types.h>
29 #include <kern/assert.h>
30 #include <kern/clock.h>
31 #include <kern/debug.h>
32 #include <kern/host.h>
33 #include <kern/kalloc.h>
34 #include <kern/kern_types.h>
35 #include <kern/machine.h>
36 #include <kern/simple_lock.h>
37 #include <kern/misc_protos.h>
38 #include <kern/sched.h>
39 #include <kern/sched_prim.h>
41 #include <kern/timer_call.h>
42 #include <kern/wait_queue.h>
43 #include <kern/ledger.h>
44 #include <kern/coalition.h>
46 #include <pexpert/pexpert.h>
48 #include <libkern/kernel_mach_header.h>
50 #include <sys/kdebug.h>
55 #define dprintf(...) kprintf(__VA_ARGS__)
57 #define dprintf(...) do { } while(0)
61 extern sched_call_t
workqueue_get_sched_callback(void);
65 * SFI (Selective Forced Idle) operates by enabling a global
66 * timer on the SFI window interval. When it fires, all processors
67 * running a thread that should be SFI-ed are sent an AST.
68 * As threads become runnable while in their "off phase", they
69 * are placed on a deferred ready queue. When a per-class
70 * "on timer" fires, the ready threads for that class are
71 * re-enqueued for running. As an optimization to avoid spurious
72 * wakeups, the timer may be lazily programmed.
76 * The "sfi_lock" simple lock guards access to static configuration
77 * parameters (as specified by userspace), dynamic state changes
78 * (as updated by the timer event routine), and timer data structures.
79 * Since it can be taken with interrupts disabled in some cases, all
80 * uses should be taken with interrupts disabled at splsched(). The
81 * "sfi_lock" also guards the "sfi_wait_class" field of thread_t, and
82 * must only be accessed with it held.
84 * When an "on timer" fires, we must deterministically be able to drain
85 * the wait queue, since if any threads are added to the queue afterwards,
86 * they may never get woken out of SFI wait. So sfi_lock must be
87 * taken before the wait queue's own spinlock.
89 * The wait queue will take the thread's scheduling lock. We may also take
90 * the thread_lock directly to update the "sfi_class" field and determine
91 * if the thread should block in the wait queue, but the lock will be
92 * released before doing so.
94 * The pset lock may also be taken, but not while any other locks are held.
96 * splsched ---> sfi_lock ---> wait_queue ---> thread_lock
97 * \ \ \__ thread_lock (*)
103 decl_simple_lock_data(static,sfi_lock
);
104 static timer_call_data_t sfi_timer_call_entry
;
105 volatile boolean_t sfi_is_enabled
;
107 boolean_t sfi_window_is_set
;
108 uint64_t sfi_window_usecs
;
109 uint64_t sfi_window_interval
;
110 uint64_t sfi_next_off_deadline
;
113 sfi_class_id_t class_id
;
114 thread_continue_t class_continuation
;
115 const char * class_name
;
116 const char * class_ledger_name
;
117 } sfi_class_registration_t
;
120 * To add a new SFI class:
122 * 1) Raise MAX_SFI_CLASS_ID in mach/sfi_class.h
123 * 2) Add a #define for it to mach/sfi_class.h. It need not be inserted in order of restrictiveness.
124 * 3) Add a call to SFI_CLASS_REGISTER below
125 * 4) Augment sfi_thread_classify to categorize threads as early as possible for as restrictive as possible.
126 * 5) Modify thermald to use the SFI class
129 static inline void _sfi_wait_cleanup(sched_call_t callback
);
131 #define SFI_CLASS_REGISTER(class_id, ledger_name) \
132 extern char compile_time_assert_ ## class_id[SFI_CLASS_ ## class_id < MAX_SFI_CLASS_ID ? 1 : -1]; \
133 void __attribute__((noinline,noreturn)) SFI_ ## class_id ## _THREAD_IS_WAITING(void *callback, wait_result_t wret __unused); \
134 void SFI_ ## class_id ## _THREAD_IS_WAITING(void *callback, wait_result_t wret __unused) \
136 _sfi_wait_cleanup(callback); \
137 thread_exception_return(); \
140 sfi_class_registration_t SFI_ ## class_id ## _registration __attribute__((section("__DATA,__sfi_class_reg"),used)) = { SFI_CLASS_ ## class_id, SFI_ ## class_id ## _THREAD_IS_WAITING, "SFI_CLASS_" # class_id, "SFI_CLASS_" # ledger_name };
142 /* SFI_CLASS_UNSPECIFIED not included here */
143 SFI_CLASS_REGISTER(MAINTENANCE
, MAINTENANCE
)
144 SFI_CLASS_REGISTER(DARWIN_BG
, DARWIN_BG
)
145 SFI_CLASS_REGISTER(APP_NAP
, APP_NAP
)
146 SFI_CLASS_REGISTER(MANAGED_FOCAL
, MANAGED
)
147 SFI_CLASS_REGISTER(MANAGED_NONFOCAL
, MANAGED
)
148 SFI_CLASS_REGISTER(UTILITY
, UTILITY
)
149 SFI_CLASS_REGISTER(DEFAULT_FOCAL
, DEFAULT
)
150 SFI_CLASS_REGISTER(DEFAULT_NONFOCAL
, DEFAULT
)
151 SFI_CLASS_REGISTER(LEGACY_FOCAL
, LEGACY
)
152 SFI_CLASS_REGISTER(LEGACY_NONFOCAL
, LEGACY
)
153 SFI_CLASS_REGISTER(USER_INITIATED_FOCAL
, USER_INITIATED
)
154 SFI_CLASS_REGISTER(USER_INITIATED_NONFOCAL
, USER_INITIATED
)
155 SFI_CLASS_REGISTER(USER_INTERACTIVE_FOCAL
, USER_INTERACTIVE
)
156 SFI_CLASS_REGISTER(USER_INTERACTIVE_NONFOCAL
, USER_INTERACTIVE
)
157 SFI_CLASS_REGISTER(KERNEL
, OPTED_OUT
)
158 SFI_CLASS_REGISTER(OPTED_OUT
, OPTED_OUT
)
160 struct sfi_class_state
{
161 uint64_t off_time_usecs
;
162 uint64_t off_time_interval
;
164 timer_call_data_t on_timer
;
165 uint64_t on_timer_deadline
;
166 boolean_t on_timer_programmed
;
168 boolean_t class_sfi_is_enabled
;
169 volatile boolean_t class_in_on_phase
;
171 struct wait_queue wait_queue
; /* threads in ready state */
172 thread_continue_t continuation
;
174 const char * class_name
;
175 const char * class_ledger_name
;
178 /* Static configuration performed in sfi_early_init() */
179 struct sfi_class_state sfi_classes
[MAX_SFI_CLASS_ID
];
181 int sfi_enabled_class_count
;
183 static void sfi_timer_global_off(
184 timer_call_param_t param0
,
185 timer_call_param_t param1
);
187 static void sfi_timer_per_class_on(
188 timer_call_param_t param0
,
189 timer_call_param_t param1
);
191 static sfi_class_registration_t
*
192 sfi_get_registration_data(unsigned long *count
)
194 unsigned long sectlen
= 0;
197 sectdata
= getsectdatafromheader(&_mh_execute_header
, "__DATA", "__sfi_class_reg", §len
);
200 if (sectlen
% sizeof(sfi_class_registration_t
) != 0) {
202 panic("__sfi_class_reg section has invalid size %lu", sectlen
);
203 __builtin_unreachable();
206 *count
= sectlen
/ sizeof(sfi_class_registration_t
);
207 return (sfi_class_registration_t
*)sectdata
;
209 panic("__sfi_class_reg section not found");
210 __builtin_unreachable();
214 /* Called early in boot, when kernel is single-threaded */
215 void sfi_early_init(void)
217 unsigned long i
, count
;
218 sfi_class_registration_t
*registrations
;
220 registrations
= sfi_get_registration_data(&count
);
221 for (i
=0; i
< count
; i
++) {
222 sfi_class_id_t class_id
= registrations
[i
].class_id
;
224 assert(class_id
< MAX_SFI_CLASS_ID
); /* should be caught at compile-time */
225 if (class_id
< MAX_SFI_CLASS_ID
) {
226 if (sfi_classes
[class_id
].continuation
!= NULL
) {
227 panic("Duplicate SFI registration for class 0x%x", class_id
);
229 sfi_classes
[class_id
].class_sfi_is_enabled
= FALSE
;
230 sfi_classes
[class_id
].class_in_on_phase
= TRUE
;
231 sfi_classes
[class_id
].continuation
= registrations
[i
].class_continuation
;
232 sfi_classes
[class_id
].class_name
= registrations
[i
].class_name
;
233 sfi_classes
[class_id
].class_ledger_name
= registrations
[i
].class_ledger_name
;
243 simple_lock_init(&sfi_lock
, 0);
244 timer_call_setup(&sfi_timer_call_entry
, sfi_timer_global_off
, NULL
);
245 sfi_window_is_set
= FALSE
;
246 sfi_enabled_class_count
= 0;
247 sfi_is_enabled
= FALSE
;
249 for (i
= 0; i
< MAX_SFI_CLASS_ID
; i
++) {
250 /* If the class was set up in sfi_early_init(), initialize remaining fields */
251 if (sfi_classes
[i
].continuation
) {
252 timer_call_setup(&sfi_classes
[i
].on_timer
, sfi_timer_per_class_on
, (void *)(uintptr_t)i
);
253 sfi_classes
[i
].on_timer_programmed
= FALSE
;
255 kret
= wait_queue_init(&sfi_classes
[i
].wait_queue
, SYNC_POLICY_FIFO
);
256 assert(kret
== KERN_SUCCESS
);
258 /* The only allowed gap is for SFI_CLASS_UNSPECIFIED */
259 if(i
!= SFI_CLASS_UNSPECIFIED
) {
260 panic("Gap in registered SFI classes");
266 /* Can be called before sfi_init() by task initialization, but after sfi_early_init() */
268 sfi_get_ledger_alias_for_class(sfi_class_id_t class_id
)
271 const char *ledger_name
= NULL
;
273 ledger_name
= sfi_classes
[class_id
].class_ledger_name
;
275 /* Find the first class in the registration table with this ledger name */
277 for (i
= SFI_CLASS_UNSPECIFIED
+ 1; i
< class_id
; i
++) {
278 if (0 == strcmp(sfi_classes
[i
].class_ledger_name
, ledger_name
)) {
279 dprintf("sfi_get_ledger_alias_for_class(0x%x) -> 0x%x\n", class_id
, i
);
284 /* This class is the primary one for the ledger, so there is no alias */
285 dprintf("sfi_get_ledger_alias_for_class(0x%x) -> 0x%x\n", class_id
, SFI_CLASS_UNSPECIFIED
);
286 return SFI_CLASS_UNSPECIFIED
;
289 /* We are permissive on SFI class lookup failures. In sfi_init(), we assert more */
290 return SFI_CLASS_UNSPECIFIED
;
294 sfi_ledger_entry_add(ledger_template_t
template, sfi_class_id_t class_id
)
296 const char *ledger_name
= NULL
;
298 ledger_name
= sfi_classes
[class_id
].class_ledger_name
;
300 dprintf("sfi_ledger_entry_add(%p, 0x%x) -> %s\n", template, class_id
, ledger_name
);
301 return ledger_entry_add(template, ledger_name
, "sfi", "MATUs");
304 static void sfi_timer_global_off(
305 timer_call_param_t param0 __unused
,
306 timer_call_param_t param1 __unused
)
308 uint64_t now
= mach_absolute_time();
310 processor_set_t pset
, nset
;
311 processor_t processor
;
312 uint32_t needs_cause_ast_mask
= 0x0;
317 simple_lock(&sfi_lock
);
318 if (!sfi_is_enabled
) {
319 /* If SFI has been disabled, let all "on" timers drain naturally */
320 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_OFF_TIMER
) | DBG_FUNC_NONE
, 1, 0, 0, 0, 0);
322 simple_unlock(&sfi_lock
);
327 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_OFF_TIMER
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
329 /* First set all configured classes into the off state, and program their "on" timer */
330 for (i
= 0; i
< MAX_SFI_CLASS_ID
; i
++) {
331 if (sfi_classes
[i
].class_sfi_is_enabled
) {
332 uint64_t on_timer_deadline
;
334 sfi_classes
[i
].class_in_on_phase
= FALSE
;
335 sfi_classes
[i
].on_timer_programmed
= TRUE
;
337 /* Push out on-timer */
338 on_timer_deadline
= now
+ sfi_classes
[i
].off_time_interval
;
339 sfi_classes
[i
].on_timer_deadline
= on_timer_deadline
;
341 timer_call_enter1(&sfi_classes
[i
].on_timer
, NULL
, on_timer_deadline
, TIMER_CALL_SYS_CRITICAL
);
343 /* If this class no longer needs SFI, make sure the timer is cancelled */
344 sfi_classes
[i
].class_in_on_phase
= TRUE
;
345 if (sfi_classes
[i
].on_timer_programmed
) {
346 sfi_classes
[i
].on_timer_programmed
= FALSE
;
347 sfi_classes
[i
].on_timer_deadline
= ~0ULL;
348 timer_call_cancel(&sfi_classes
[i
].on_timer
);
352 simple_unlock(&sfi_lock
);
354 /* Iterate over processors, call cause_ast_check() on ones running a thread that should be in an off phase */
355 processor
= processor_list
;
356 pset
= processor
->processor_set
;
361 nset
= processor
->processor_set
;
368 /* "processor" and its pset are locked */
369 if (processor
->state
== PROCESSOR_RUNNING
) {
370 if (AST_NONE
!= sfi_processor_needs_ast(processor
)) {
371 needs_cause_ast_mask
|= (1U << processor
->cpu_id
);
374 } while ((processor
= processor
->processor_list
) != NULL
);
378 processor
= processor_list
;
380 if (needs_cause_ast_mask
& (1U << processor
->cpu_id
)) {
381 if (processor
== current_processor())
384 cause_ast_check(processor
);
386 } while ((processor
= processor
->processor_list
) != NULL
);
388 /* Re-arm timer if still enabled */
389 simple_lock(&sfi_lock
);
390 if (sfi_is_enabled
) {
391 clock_deadline_for_periodic_event(sfi_window_interval
,
393 &sfi_next_off_deadline
);
394 timer_call_enter1(&sfi_timer_call_entry
,
396 sfi_next_off_deadline
,
397 TIMER_CALL_SYS_CRITICAL
);
400 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_OFF_TIMER
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
402 simple_unlock(&sfi_lock
);
407 static void sfi_timer_per_class_on(
408 timer_call_param_t param0
,
409 timer_call_param_t param1 __unused
)
411 sfi_class_id_t sfi_class_id
= (sfi_class_id_t
)(uintptr_t)param0
;
412 struct sfi_class_state
*sfi_class
= &sfi_classes
[sfi_class_id
];
418 simple_lock(&sfi_lock
);
420 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_ON_TIMER
) | DBG_FUNC_START
, sfi_class_id
, 0, 0, 0, 0);
423 * Any threads that may have accumulated in the ready queue for this class should get re-enqueued.
424 * Since we have the sfi_lock held and have changed "class_in_on_phase", we expect
425 * no new threads to be put on this wait queue until the global "off timer" has fired.
428 sfi_class
->class_in_on_phase
= TRUE
;
429 sfi_class
->on_timer_programmed
= FALSE
;
431 kret
= wait_queue_wakeup64_all(&sfi_class
->wait_queue
,
432 CAST_EVENT64_T(sfi_class_id
),
434 assert(kret
== KERN_SUCCESS
|| kret
== KERN_NOT_WAITING
);
436 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_ON_TIMER
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
438 simple_unlock(&sfi_lock
);
444 kern_return_t
sfi_set_window(uint64_t window_usecs
)
446 uint64_t interval
, deadline
;
447 uint64_t now
= mach_absolute_time();
450 uint64_t largest_class_off_interval
= 0;
452 if (window_usecs
< MIN_SFI_WINDOW_USEC
)
453 window_usecs
= MIN_SFI_WINDOW_USEC
;
455 if (window_usecs
> UINT32_MAX
)
456 return (KERN_INVALID_ARGUMENT
);
458 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_SET_WINDOW
), window_usecs
, 0, 0, 0, 0);
460 clock_interval_to_absolutetime_interval((uint32_t)window_usecs
, NSEC_PER_USEC
, &interval
);
461 deadline
= now
+ interval
;
465 simple_lock(&sfi_lock
);
467 /* Check that we are not bringing in the SFI window smaller than any class */
468 for (i
= 0; i
< MAX_SFI_CLASS_ID
; i
++) {
469 if (sfi_classes
[i
].class_sfi_is_enabled
) {
470 largest_class_off_interval
= MAX(largest_class_off_interval
, sfi_classes
[i
].off_time_interval
);
475 * Off window must be strictly greater than all enabled classes,
476 * otherwise threads would build up on ready queue and never be able to run.
478 if (interval
<= largest_class_off_interval
) {
479 simple_unlock(&sfi_lock
);
481 return (KERN_INVALID_ARGUMENT
);
485 * If the new "off" deadline is further out than the current programmed timer,
486 * just let the current one expire (and the new cadence will be established thereafter).
487 * If the new "off" deadline is nearer than the current one, bring it in, so we
488 * can start the new behavior sooner. Note that this may cause the "off" timer to
489 * fire before some of the class "on" timers have fired.
491 sfi_window_usecs
= window_usecs
;
492 sfi_window_interval
= interval
;
493 sfi_window_is_set
= TRUE
;
495 if (sfi_enabled_class_count
== 0) {
496 /* Can't program timer yet */
497 } else if (!sfi_is_enabled
) {
498 sfi_is_enabled
= TRUE
;
499 sfi_next_off_deadline
= deadline
;
500 timer_call_enter1(&sfi_timer_call_entry
,
502 sfi_next_off_deadline
,
503 TIMER_CALL_SYS_CRITICAL
);
504 } else if (deadline
>= sfi_next_off_deadline
) {
505 sfi_next_off_deadline
= deadline
;
507 sfi_next_off_deadline
= deadline
;
508 timer_call_enter1(&sfi_timer_call_entry
,
510 sfi_next_off_deadline
,
511 TIMER_CALL_SYS_CRITICAL
);
514 simple_unlock(&sfi_lock
);
517 return (KERN_SUCCESS
);
520 kern_return_t
sfi_window_cancel(void)
526 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_CANCEL_WINDOW
), 0, 0, 0, 0, 0);
528 /* Disable globals so that global "off-timer" is not re-armed */
529 simple_lock(&sfi_lock
);
530 sfi_window_is_set
= FALSE
;
531 sfi_window_usecs
= 0;
532 sfi_window_interval
= 0;
533 sfi_next_off_deadline
= 0;
534 sfi_is_enabled
= FALSE
;
535 simple_unlock(&sfi_lock
);
539 return (KERN_SUCCESS
);
542 /* Defers SFI off and per-class on timers (if live) by the specified interval
543 * in Mach Absolute Time Units. Currently invoked to align with the global
544 * forced idle mechanism. Making some simplifying assumptions, the iterative GFI
545 * induced SFI on+off deferrals form a geometric series that converges to yield
546 * an effective SFI duty cycle that is scaled by the GFI duty cycle. Initial phase
547 * alignment and congruency of the SFI/GFI periods can distort this to some extent.
550 kern_return_t
sfi_defer(uint64_t sfi_defer_matus
)
553 kern_return_t kr
= KERN_FAILURE
;
556 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_GLOBAL_DEFER
), sfi_defer_matus
, 0, 0, 0, 0);
558 simple_lock(&sfi_lock
);
559 if (!sfi_is_enabled
) {
563 assert(sfi_next_off_deadline
!= 0);
565 sfi_next_off_deadline
+= sfi_defer_matus
;
566 timer_call_enter1(&sfi_timer_call_entry
, NULL
, sfi_next_off_deadline
, TIMER_CALL_SYS_CRITICAL
);
569 for (i
= 0; i
< MAX_SFI_CLASS_ID
; i
++) {
570 if (sfi_classes
[i
].class_sfi_is_enabled
) {
571 if (sfi_classes
[i
].on_timer_programmed
) {
572 uint64_t new_on_deadline
= sfi_classes
[i
].on_timer_deadline
+ sfi_defer_matus
;
573 sfi_classes
[i
].on_timer_deadline
= new_on_deadline
;
574 timer_call_enter1(&sfi_classes
[i
].on_timer
, NULL
, new_on_deadline
, TIMER_CALL_SYS_CRITICAL
);
581 simple_unlock(&sfi_lock
);
589 kern_return_t
sfi_get_window(uint64_t *window_usecs
)
592 uint64_t off_window_us
;
595 simple_lock(&sfi_lock
);
597 off_window_us
= sfi_window_usecs
;
599 simple_unlock(&sfi_lock
);
602 *window_usecs
= off_window_us
;
604 return (KERN_SUCCESS
);
608 kern_return_t
sfi_set_class_offtime(sfi_class_id_t class_id
, uint64_t offtime_usecs
)
612 uint64_t off_window_interval
;
614 if (offtime_usecs
< MIN_SFI_WINDOW_USEC
)
615 offtime_usecs
= MIN_SFI_WINDOW_USEC
;
617 if (class_id
== SFI_CLASS_UNSPECIFIED
|| class_id
>= MAX_SFI_CLASS_ID
)
618 return (KERN_INVALID_ARGUMENT
);
620 if (offtime_usecs
> UINT32_MAX
)
621 return (KERN_INVALID_ARGUMENT
);
623 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_SET_CLASS_OFFTIME
), offtime_usecs
, class_id
, 0, 0, 0);
625 clock_interval_to_absolutetime_interval((uint32_t)offtime_usecs
, NSEC_PER_USEC
, &interval
);
629 simple_lock(&sfi_lock
);
630 off_window_interval
= sfi_window_interval
;
632 /* Check that we are not bringing in class off-time larger than the SFI window */
633 if (off_window_interval
&& (interval
>= off_window_interval
)) {
634 simple_unlock(&sfi_lock
);
636 return (KERN_INVALID_ARGUMENT
);
639 /* We never re-program the per-class on-timer, but rather just let it expire naturally */
640 if (!sfi_classes
[class_id
].class_sfi_is_enabled
) {
641 sfi_enabled_class_count
++;
643 sfi_classes
[class_id
].off_time_usecs
= offtime_usecs
;
644 sfi_classes
[class_id
].off_time_interval
= interval
;
645 sfi_classes
[class_id
].class_sfi_is_enabled
= TRUE
;
647 if (sfi_window_is_set
&& !sfi_is_enabled
) {
648 /* start global off timer */
649 sfi_is_enabled
= TRUE
;
650 sfi_next_off_deadline
= mach_absolute_time() + sfi_window_interval
;
651 timer_call_enter1(&sfi_timer_call_entry
,
653 sfi_next_off_deadline
,
654 TIMER_CALL_SYS_CRITICAL
);
657 simple_unlock(&sfi_lock
);
661 return (KERN_SUCCESS
);
664 kern_return_t
sfi_class_offtime_cancel(sfi_class_id_t class_id
)
668 if (class_id
== SFI_CLASS_UNSPECIFIED
|| class_id
>= MAX_SFI_CLASS_ID
)
669 return (KERN_INVALID_ARGUMENT
);
673 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_CANCEL_CLASS_OFFTIME
), class_id
, 0, 0, 0, 0);
675 simple_lock(&sfi_lock
);
677 /* We never re-program the per-class on-timer, but rather just let it expire naturally */
678 if (sfi_classes
[class_id
].class_sfi_is_enabled
) {
679 sfi_enabled_class_count
--;
681 sfi_classes
[class_id
].off_time_usecs
= 0;
682 sfi_classes
[class_id
].off_time_interval
= 0;
683 sfi_classes
[class_id
].class_sfi_is_enabled
= FALSE
;
685 if (sfi_enabled_class_count
== 0) {
686 sfi_is_enabled
= FALSE
;
689 simple_unlock(&sfi_lock
);
693 return (KERN_SUCCESS
);
696 kern_return_t
sfi_get_class_offtime(sfi_class_id_t class_id
, uint64_t *offtime_usecs
)
698 uint64_t off_time_us
;
701 if (class_id
== SFI_CLASS_UNSPECIFIED
|| class_id
>= MAX_SFI_CLASS_ID
)
706 simple_lock(&sfi_lock
);
707 off_time_us
= sfi_classes
[class_id
].off_time_usecs
;
708 simple_unlock(&sfi_lock
);
712 *offtime_usecs
= off_time_us
;
714 return (KERN_SUCCESS
);
718 * sfi_thread_classify and sfi_processor_active_thread_classify perform the critical
719 * role of quickly categorizing a thread into its SFI class so that an AST_SFI can be
720 * set. As the thread is unwinding to userspace, sfi_ast() performs full locking
721 * and determines whether the thread should enter an SFI wait state. Because of
722 * the inherent races between the time the AST is set and when it is evaluated,
723 * thread classification can be inaccurate (but should always be safe). This is
724 * especially the case for sfi_processor_active_thread_classify, which must
725 * classify the active thread on a remote processor without taking the thread lock.
726 * When in doubt, classification should err on the side of *not* classifying a
727 * thread at all, and wait for the thread itself to either hit a quantum expiration
728 * or block inside the kernel.
732 * Thread must be locked. Ultimately, the real decision to enter
733 * SFI wait happens at the AST boundary.
735 sfi_class_id_t
sfi_thread_classify(thread_t thread
)
737 task_t task
= thread
->task
;
738 boolean_t is_kernel_thread
= (task
== kernel_task
);
739 sched_mode_t thmode
= thread
->sched_mode
;
740 int latency_qos
= proc_get_effective_task_policy(task
, TASK_POLICY_LATENCY_QOS
);
741 int task_role
= proc_get_effective_task_policy(task
, TASK_POLICY_ROLE
);
742 int thread_bg
= proc_get_effective_thread_policy(thread
, TASK_POLICY_DARWIN_BG
);
743 int managed_task
= proc_get_effective_task_policy(task
, TASK_POLICY_SFI_MANAGED
);
744 int thread_qos
= proc_get_effective_thread_policy(thread
, TASK_POLICY_QOS
);
745 boolean_t focal
= FALSE
;
747 /* kernel threads never reach the user AST boundary, and are in a separate world for SFI */
748 if (is_kernel_thread
) {
749 return SFI_CLASS_KERNEL
;
752 if (thread_qos
== THREAD_QOS_MAINTENANCE
)
753 return SFI_CLASS_MAINTENANCE
;
755 if (thread_bg
|| thread_qos
== THREAD_QOS_BACKGROUND
) {
756 return SFI_CLASS_DARWIN_BG
;
759 if (latency_qos
!= 0) {
760 int latency_qos_wtf
= latency_qos
- 1;
762 if ((latency_qos_wtf
>= 4) && (latency_qos_wtf
<= 5)) {
763 return SFI_CLASS_APP_NAP
;
768 * Realtime and fixed priority threads express their duty cycle constraints
769 * via other mechanisms, and are opted out of (most) forms of SFI
771 if (thmode
== TH_MODE_REALTIME
|| thmode
== TH_MODE_FIXED
|| task_role
== TASK_GRAPHICS_SERVER
) {
772 return SFI_CLASS_OPTED_OUT
;
776 * Threads with unspecified, legacy, or user-initiated QOS class can be individually managed.
780 case TASK_CONTROL_APPLICATION
:
781 case TASK_FOREGROUND_APPLICATION
:
785 case TASK_BACKGROUND_APPLICATION
:
786 case TASK_DEFAULT_APPLICATION
:
787 case TASK_UNSPECIFIED
:
788 /* Focal if in coalition with foreground app */
789 if (coalition_focal_task_count(thread
->task
->coalition
) > 0)
798 switch (thread_qos
) {
799 case THREAD_QOS_UNSPECIFIED
:
800 case THREAD_QOS_LEGACY
:
801 case THREAD_QOS_USER_INITIATED
:
803 return SFI_CLASS_MANAGED_FOCAL
;
805 return SFI_CLASS_MANAGED_NONFOCAL
;
811 if (thread_qos
== THREAD_QOS_UTILITY
)
812 return SFI_CLASS_UTILITY
;
815 * Classify threads in non-managed tasks
818 switch (thread_qos
) {
819 case THREAD_QOS_USER_INTERACTIVE
:
820 return SFI_CLASS_USER_INTERACTIVE_FOCAL
;
821 case THREAD_QOS_USER_INITIATED
:
822 return SFI_CLASS_USER_INITIATED_FOCAL
;
823 case THREAD_QOS_LEGACY
:
824 return SFI_CLASS_LEGACY_FOCAL
;
826 return SFI_CLASS_DEFAULT_FOCAL
;
829 switch (thread_qos
) {
830 case THREAD_QOS_USER_INTERACTIVE
:
831 return SFI_CLASS_USER_INTERACTIVE_NONFOCAL
;
832 case THREAD_QOS_USER_INITIATED
:
833 return SFI_CLASS_USER_INITIATED_NONFOCAL
;
834 case THREAD_QOS_LEGACY
:
835 return SFI_CLASS_LEGACY_NONFOCAL
;
837 return SFI_CLASS_DEFAULT_NONFOCAL
;
843 * pset must be locked.
845 sfi_class_id_t
sfi_processor_active_thread_classify(processor_t processor
)
847 return processor
->current_sfi_class
;
851 * thread must be locked. This is inherently racy, with the intent that
852 * at the AST boundary, it will be fully evaluated whether we need to
853 * perform an AST wait
855 ast_t
sfi_thread_needs_ast(thread_t thread
, sfi_class_id_t
*out_class
)
857 sfi_class_id_t class_id
;
859 class_id
= sfi_thread_classify(thread
);
862 *out_class
= class_id
;
864 /* No lock taken, so a stale value may be used. */
865 if (!sfi_classes
[class_id
].class_in_on_phase
)
872 * pset must be locked. We take the SFI class for
873 * the currently running thread which is cached on
874 * the processor_t, and assume it is accurate. In the
875 * worst case, the processor will get an IPI and be asked
876 * to evaluate if the current running thread at that
877 * later point in time should be in an SFI wait.
879 ast_t
sfi_processor_needs_ast(processor_t processor
)
881 sfi_class_id_t class_id
;
883 class_id
= sfi_processor_active_thread_classify(processor
);
885 /* No lock taken, so a stale value may be used. */
886 if (!sfi_classes
[class_id
].class_in_on_phase
)
893 static inline void _sfi_wait_cleanup(sched_call_t callback
) {
894 thread_t self
= current_thread();
895 sfi_class_id_t current_sfi_wait_class
= SFI_CLASS_UNSPECIFIED
;
896 int64_t sfi_wait_time
, sfi_wait_begin
= 0;
898 spl_t s
= splsched();
901 thread_sched_call(self
, callback
);
903 sfi_wait_begin
= self
->wait_sfi_begin_time
;
906 simple_lock(&sfi_lock
);
907 sfi_wait_time
= mach_absolute_time() - sfi_wait_begin
;
908 current_sfi_wait_class
= self
->sfi_wait_class
;
909 self
->sfi_wait_class
= SFI_CLASS_UNSPECIFIED
;
910 simple_unlock(&sfi_lock
);
912 assert(SFI_CLASS_UNSPECIFIED
< current_sfi_wait_class
< MAX_SFI_CLASS_ID
);
913 ledger_credit(self
->task
->ledger
, task_ledgers
.sfi_wait_times
[current_sfi_wait_class
], sfi_wait_time
);
917 * Called at AST context to fully evaluate if the current thread
918 * (which is obviously running) should instead block in an SFI wait.
919 * We must take the sfi_lock to check whether we are in the "off" period
920 * for the class, and if so, block.
922 void sfi_ast(thread_t thread
)
924 sfi_class_id_t class_id
;
926 struct sfi_class_state
*sfi_class
;
927 wait_result_t waitret
;
928 boolean_t did_wait
= FALSE
;
930 thread_continue_t continuation
;
931 sched_call_t workq_callback
= workqueue_get_sched_callback();
932 boolean_t did_clear_wq
= FALSE
;
936 simple_lock(&sfi_lock
);
938 if (!sfi_is_enabled
) {
940 * SFI is not enabled, or has recently been disabled.
941 * There is no point putting this thread on a deferred ready
942 * queue, even if it were classified as needing it, since
943 * SFI will truly be off at the next global off timer
945 simple_unlock(&sfi_lock
);
952 thread
->sfi_class
= class_id
= sfi_thread_classify(thread
);
953 tid
= thread_tid(thread
);
956 * Once the sfi_lock is taken and the thread's ->sfi_class field is updated, we
957 * are committed to transitioning to whatever state is indicated by "->class_in_on_phase".
958 * If another thread tries to call sfi_reevaluate() after this point, it will take the
959 * sfi_lock and see the thread in this wait state. If another thread calls
960 * sfi_reevaluate() before this point, it would see a runnable thread and at most
961 * attempt to send an AST to this processor, but we would have the most accurate
965 /* Optimistically clear workq callback while thread is already locked */
966 if (workq_callback
&& (thread
->sched_call
== workq_callback
)) {
967 thread_sched_call(thread
, NULL
);
970 thread_unlock(thread
);
972 sfi_class
= &sfi_classes
[class_id
];
973 if (!sfi_class
->class_in_on_phase
) {
974 /* Need to block thread in wait queue */
975 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_THREAD_DEFER
), tid
, class_id
, 0, 0, 0);
977 waitret
= wait_queue_assert_wait64(&sfi_class
->wait_queue
,
978 CAST_EVENT64_T(class_id
),
979 THREAD_INTERRUPTIBLE
,
981 if (waitret
== THREAD_WAITING
) {
982 thread
->sfi_wait_class
= class_id
;
984 continuation
= sfi_class
->continuation
;
986 /* thread may be exiting already, all other errors are unexpected */
987 assert(waitret
== THREAD_INTERRUPTED
);
990 simple_unlock(&sfi_lock
);
995 thread_block_reason(continuation
, did_clear_wq
? workq_callback
: NULL
, AST_SFI
);
1000 thread_sched_call(thread
, workq_callback
);
1001 thread_unlock(thread
);
1008 * Thread must be unlocked
1009 * May be called with coalition, task, or thread mutex held
1011 void sfi_reevaluate(thread_t thread
)
1015 sfi_class_id_t class_id
, current_class_id
;
1020 simple_lock(&sfi_lock
);
1022 thread_lock(thread
);
1023 sfi_ast
= sfi_thread_needs_ast(thread
, &class_id
);
1024 thread
->sfi_class
= class_id
;
1027 * This routine chiefly exists to boost threads out of an SFI wait
1028 * if their classification changes before the "on" timer fires.
1030 * If we calculate that a thread is in a different ->sfi_wait_class
1031 * than we think it should be (including no-SFI-wait), we need to
1034 * If the thread is in SFI wait and should not be (or should be waiting
1035 * on a different class' "on" timer), we wake it up. If needed, the
1036 * thread may immediately block again in the different SFI wait state.
1038 * If the thread is not in an SFI wait state and it should be, we need
1039 * to get that thread's attention, possibly by sending an AST to another
1043 if ((current_class_id
= thread
->sfi_wait_class
) != SFI_CLASS_UNSPECIFIED
) {
1045 thread_unlock(thread
); /* not needed anymore */
1047 assert(current_class_id
< MAX_SFI_CLASS_ID
);
1049 if ((sfi_ast
== AST_NONE
) || (class_id
!= current_class_id
)) {
1050 struct sfi_class_state
*sfi_class
= &sfi_classes
[current_class_id
];
1052 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_WAIT_CANCELED
), thread_tid(thread
), current_class_id
, class_id
, 0, 0);
1054 kret
= wait_queue_wakeup64_thread(&sfi_class
->wait_queue
,
1055 CAST_EVENT64_T(current_class_id
),
1058 assert(kret
== KERN_SUCCESS
|| kret
== KERN_NOT_WAITING
);
1062 * Thread's current SFI wait class is not set, and because we
1063 * have the sfi_lock, it won't get set.
1066 if ((thread
->state
& (TH_RUN
| TH_IDLE
)) == TH_RUN
) {
1067 if (sfi_ast
!= AST_NONE
) {
1068 if (thread
== current_thread())
1071 processor_t processor
= thread
->last_processor
;
1073 if (processor
!= PROCESSOR_NULL
&&
1074 processor
->state
== PROCESSOR_RUNNING
&&
1075 processor
->active_thread
== thread
) {
1076 cause_ast_check(processor
);
1079 * Runnable thread that's not on a CPU currently. When a processor
1080 * does context switch to it, the AST will get set based on whether
1081 * the thread is in its "off time".
1088 thread_unlock(thread
);
1091 simple_unlock(&sfi_lock
);