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 boolean_t on_timer_programmed
;
167 boolean_t class_sfi_is_enabled
;
168 volatile boolean_t class_in_on_phase
;
170 struct wait_queue wait_queue
; /* threads in ready state */
171 thread_continue_t continuation
;
173 const char * class_name
;
174 const char * class_ledger_name
;
177 /* Static configuration performed in sfi_early_init() */
178 struct sfi_class_state sfi_classes
[MAX_SFI_CLASS_ID
];
180 int sfi_enabled_class_count
;
182 static void sfi_timer_global_off(
183 timer_call_param_t param0
,
184 timer_call_param_t param1
);
186 static void sfi_timer_per_class_on(
187 timer_call_param_t param0
,
188 timer_call_param_t param1
);
190 static sfi_class_registration_t
*
191 sfi_get_registration_data(unsigned long *count
)
193 unsigned long sectlen
= 0;
196 sectdata
= getsectdatafromheader(&_mh_execute_header
, "__DATA", "__sfi_class_reg", §len
);
199 if (sectlen
% sizeof(sfi_class_registration_t
) != 0) {
201 panic("__sfi_class_reg section has invalid size %lu", sectlen
);
202 __builtin_unreachable();
205 *count
= sectlen
/ sizeof(sfi_class_registration_t
);
206 return (sfi_class_registration_t
*)sectdata
;
208 panic("__sfi_class_reg section not found");
209 __builtin_unreachable();
213 /* Called early in boot, when kernel is single-threaded */
214 void sfi_early_init(void)
216 unsigned long i
, count
;
217 sfi_class_registration_t
*registrations
;
219 registrations
= sfi_get_registration_data(&count
);
220 for (i
=0; i
< count
; i
++) {
221 sfi_class_id_t class_id
= registrations
[i
].class_id
;
223 assert(class_id
< MAX_SFI_CLASS_ID
); /* should be caught at compile-time */
224 if (class_id
< MAX_SFI_CLASS_ID
) {
225 if (sfi_classes
[class_id
].continuation
!= NULL
) {
226 panic("Duplicate SFI registration for class 0x%x", class_id
);
228 sfi_classes
[class_id
].class_sfi_is_enabled
= FALSE
;
229 sfi_classes
[class_id
].class_in_on_phase
= TRUE
;
230 sfi_classes
[class_id
].continuation
= registrations
[i
].class_continuation
;
231 sfi_classes
[class_id
].class_name
= registrations
[i
].class_name
;
232 sfi_classes
[class_id
].class_ledger_name
= registrations
[i
].class_ledger_name
;
242 simple_lock_init(&sfi_lock
, 0);
243 timer_call_setup(&sfi_timer_call_entry
, sfi_timer_global_off
, NULL
);
244 sfi_window_is_set
= FALSE
;
245 sfi_enabled_class_count
= 0;
246 sfi_is_enabled
= FALSE
;
248 for (i
= 0; i
< MAX_SFI_CLASS_ID
; i
++) {
249 /* If the class was set up in sfi_early_init(), initialize remaining fields */
250 if (sfi_classes
[i
].continuation
) {
251 timer_call_setup(&sfi_classes
[i
].on_timer
, sfi_timer_per_class_on
, (void *)(uintptr_t)i
);
252 sfi_classes
[i
].on_timer_programmed
= FALSE
;
254 kret
= wait_queue_init(&sfi_classes
[i
].wait_queue
, SYNC_POLICY_FIFO
);
255 assert(kret
== KERN_SUCCESS
);
257 /* The only allowed gap is for SFI_CLASS_UNSPECIFIED */
258 if(i
!= SFI_CLASS_UNSPECIFIED
) {
259 panic("Gap in registered SFI classes");
265 /* Can be called before sfi_init() by task initialization, but after sfi_early_init() */
267 sfi_get_ledger_alias_for_class(sfi_class_id_t class_id
)
270 const char *ledger_name
= NULL
;
272 ledger_name
= sfi_classes
[class_id
].class_ledger_name
;
274 /* Find the first class in the registration table with this ledger name */
276 for (i
= SFI_CLASS_UNSPECIFIED
+ 1; i
< class_id
; i
++) {
277 if (0 == strcmp(sfi_classes
[i
].class_ledger_name
, ledger_name
)) {
278 dprintf("sfi_get_ledger_alias_for_class(0x%x) -> 0x%x\n", class_id
, i
);
283 /* This class is the primary one for the ledger, so there is no alias */
284 dprintf("sfi_get_ledger_alias_for_class(0x%x) -> 0x%x\n", class_id
, SFI_CLASS_UNSPECIFIED
);
285 return SFI_CLASS_UNSPECIFIED
;
288 /* We are permissive on SFI class lookup failures. In sfi_init(), we assert more */
289 return SFI_CLASS_UNSPECIFIED
;
293 sfi_ledger_entry_add(ledger_template_t
template, sfi_class_id_t class_id
)
295 const char *ledger_name
= NULL
;
297 ledger_name
= sfi_classes
[class_id
].class_ledger_name
;
299 dprintf("sfi_ledger_entry_add(%p, 0x%x) -> %s\n", template, class_id
, ledger_name
);
300 return ledger_entry_add(template, ledger_name
, "sfi", "MATUs");
303 static void sfi_timer_global_off(
304 timer_call_param_t param0 __unused
,
305 timer_call_param_t param1 __unused
)
307 uint64_t now
= mach_absolute_time();
309 processor_set_t pset
, nset
;
310 processor_t processor
;
311 uint32_t needs_cause_ast_mask
= 0x0;
316 simple_lock(&sfi_lock
);
317 if (!sfi_is_enabled
) {
318 /* If SFI has been disabled, let all "on" timers drain naturally */
319 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_OFF_TIMER
) | DBG_FUNC_NONE
, 1, 0, 0, 0, 0);
321 simple_unlock(&sfi_lock
);
326 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_OFF_TIMER
) | DBG_FUNC_START
, 0, 0, 0, 0, 0);
328 /* First set all configured classes into the off state, and program their "on" timer */
329 for (i
= 0; i
< MAX_SFI_CLASS_ID
; i
++) {
330 if (sfi_classes
[i
].class_sfi_is_enabled
) {
331 uint64_t on_timer_deadline
;
333 sfi_classes
[i
].class_in_on_phase
= FALSE
;
334 sfi_classes
[i
].on_timer_programmed
= TRUE
;
336 /* Push out on-timer */
337 on_timer_deadline
= now
+ sfi_classes
[i
].off_time_interval
;
338 timer_call_enter1(&sfi_classes
[i
].on_timer
, NULL
, on_timer_deadline
, TIMER_CALL_SYS_CRITICAL
);
340 /* If this class no longer needs SFI, make sure the timer is cancelled */
341 sfi_classes
[i
].class_in_on_phase
= TRUE
;
342 if (sfi_classes
[i
].on_timer_programmed
) {
343 sfi_classes
[i
].on_timer_programmed
= FALSE
;
344 timer_call_cancel(&sfi_classes
[i
].on_timer
);
348 simple_unlock(&sfi_lock
);
350 /* Iterate over processors, call cause_ast_check() on ones running a thread that should be in an off phase */
351 processor
= processor_list
;
352 pset
= processor
->processor_set
;
357 nset
= processor
->processor_set
;
364 /* "processor" and its pset are locked */
365 if (processor
->state
== PROCESSOR_RUNNING
) {
366 if (AST_NONE
!= sfi_processor_needs_ast(processor
)) {
367 needs_cause_ast_mask
|= (1U << processor
->cpu_id
);
370 } while ((processor
= processor
->processor_list
) != NULL
);
374 processor
= processor_list
;
376 if (needs_cause_ast_mask
& (1U << processor
->cpu_id
)) {
377 if (processor
== current_processor())
380 cause_ast_check(processor
);
382 } while ((processor
= processor
->processor_list
) != NULL
);
384 /* Re-arm timer if still enabled */
385 simple_lock(&sfi_lock
);
386 if (sfi_is_enabled
) {
387 clock_deadline_for_periodic_event(sfi_window_interval
,
389 &sfi_next_off_deadline
);
390 timer_call_enter1(&sfi_timer_call_entry
,
392 sfi_next_off_deadline
,
393 TIMER_CALL_SYS_CRITICAL
);
396 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_OFF_TIMER
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
398 simple_unlock(&sfi_lock
);
403 static void sfi_timer_per_class_on(
404 timer_call_param_t param0
,
405 timer_call_param_t param1 __unused
)
407 sfi_class_id_t sfi_class_id
= (sfi_class_id_t
)(uintptr_t)param0
;
408 struct sfi_class_state
*sfi_class
= &sfi_classes
[sfi_class_id
];
414 simple_lock(&sfi_lock
);
416 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_ON_TIMER
) | DBG_FUNC_START
, sfi_class_id
, 0, 0, 0, 0);
419 * Any threads that may have accumulated in the ready queue for this class should get re-enqueued.
420 * Since we have the sfi_lock held and have changed "class_in_on_phase", we expect
421 * no new threads to be put on this wait queue until the global "off timer" has fired.
423 sfi_class
->class_in_on_phase
= TRUE
;
424 kret
= wait_queue_wakeup64_all(&sfi_class
->wait_queue
,
425 CAST_EVENT64_T(sfi_class_id
),
427 assert(kret
== KERN_SUCCESS
|| kret
== KERN_NOT_WAITING
);
429 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_ON_TIMER
) | DBG_FUNC_END
, 0, 0, 0, 0, 0);
431 simple_unlock(&sfi_lock
);
437 kern_return_t
sfi_set_window(uint64_t window_usecs
)
439 uint64_t interval
, deadline
;
440 uint64_t now
= mach_absolute_time();
443 uint64_t largest_class_off_interval
= 0;
445 if (window_usecs
< MIN_SFI_WINDOW_USEC
)
446 window_usecs
= MIN_SFI_WINDOW_USEC
;
448 if (window_usecs
> UINT32_MAX
)
449 return (KERN_INVALID_ARGUMENT
);
451 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_SET_WINDOW
), window_usecs
, 0, 0, 0, 0);
453 clock_interval_to_absolutetime_interval((uint32_t)window_usecs
, NSEC_PER_USEC
, &interval
);
454 deadline
= now
+ interval
;
458 simple_lock(&sfi_lock
);
460 /* Check that we are not bringing in the SFI window smaller than any class */
461 for (i
= 0; i
< MAX_SFI_CLASS_ID
; i
++) {
462 if (sfi_classes
[i
].class_sfi_is_enabled
) {
463 largest_class_off_interval
= MAX(largest_class_off_interval
, sfi_classes
[i
].off_time_interval
);
468 * Off window must be strictly greater than all enabled classes,
469 * otherwise threads would build up on ready queue and never be able to run.
471 if (interval
<= largest_class_off_interval
) {
472 simple_unlock(&sfi_lock
);
474 return (KERN_INVALID_ARGUMENT
);
478 * If the new "off" deadline is further out than the current programmed timer,
479 * just let the current one expire (and the new cadence will be established thereafter).
480 * If the new "off" deadline is nearer than the current one, bring it in, so we
481 * can start the new behavior sooner. Note that this may cause the "off" timer to
482 * fire before some of the class "on" timers have fired.
484 sfi_window_usecs
= window_usecs
;
485 sfi_window_interval
= interval
;
486 sfi_window_is_set
= TRUE
;
488 if (sfi_enabled_class_count
== 0) {
489 /* Can't program timer yet */
490 } else if (!sfi_is_enabled
) {
491 sfi_is_enabled
= TRUE
;
492 sfi_next_off_deadline
= deadline
;
493 timer_call_enter1(&sfi_timer_call_entry
,
495 sfi_next_off_deadline
,
496 TIMER_CALL_SYS_CRITICAL
);
497 } else if (deadline
>= sfi_next_off_deadline
) {
498 sfi_next_off_deadline
= deadline
;
500 sfi_next_off_deadline
= deadline
;
501 timer_call_enter1(&sfi_timer_call_entry
,
503 sfi_next_off_deadline
,
504 TIMER_CALL_SYS_CRITICAL
);
507 simple_unlock(&sfi_lock
);
510 return (KERN_SUCCESS
);
513 kern_return_t
sfi_window_cancel(void)
519 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_CANCEL_WINDOW
), 0, 0, 0, 0, 0);
521 /* Disable globals so that global "off-timer" is not re-armed */
522 simple_lock(&sfi_lock
);
523 sfi_window_is_set
= FALSE
;
524 sfi_window_usecs
= 0;
525 sfi_window_interval
= 0;
526 sfi_next_off_deadline
= 0;
527 sfi_is_enabled
= FALSE
;
528 simple_unlock(&sfi_lock
);
532 return (KERN_SUCCESS
);
536 kern_return_t
sfi_get_window(uint64_t *window_usecs
)
539 uint64_t off_window_us
;
542 simple_lock(&sfi_lock
);
544 off_window_us
= sfi_window_usecs
;
546 simple_unlock(&sfi_lock
);
549 *window_usecs
= off_window_us
;
551 return (KERN_SUCCESS
);
555 kern_return_t
sfi_set_class_offtime(sfi_class_id_t class_id
, uint64_t offtime_usecs
)
559 uint64_t off_window_interval
;
561 if (offtime_usecs
< MIN_SFI_WINDOW_USEC
)
562 offtime_usecs
= MIN_SFI_WINDOW_USEC
;
564 if (class_id
== SFI_CLASS_UNSPECIFIED
|| class_id
>= MAX_SFI_CLASS_ID
)
565 return (KERN_INVALID_ARGUMENT
);
567 if (offtime_usecs
> UINT32_MAX
)
568 return (KERN_INVALID_ARGUMENT
);
570 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_SET_CLASS_OFFTIME
), offtime_usecs
, class_id
, 0, 0, 0);
572 clock_interval_to_absolutetime_interval((uint32_t)offtime_usecs
, NSEC_PER_USEC
, &interval
);
576 simple_lock(&sfi_lock
);
577 off_window_interval
= sfi_window_interval
;
579 /* Check that we are not bringing in class off-time larger than the SFI window */
580 if (off_window_interval
&& (interval
>= off_window_interval
)) {
581 simple_unlock(&sfi_lock
);
583 return (KERN_INVALID_ARGUMENT
);
586 /* We never re-program the per-class on-timer, but rather just let it expire naturally */
587 if (!sfi_classes
[class_id
].class_sfi_is_enabled
) {
588 sfi_enabled_class_count
++;
590 sfi_classes
[class_id
].off_time_usecs
= offtime_usecs
;
591 sfi_classes
[class_id
].off_time_interval
= interval
;
592 sfi_classes
[class_id
].class_sfi_is_enabled
= TRUE
;
594 if (sfi_window_is_set
&& !sfi_is_enabled
) {
595 /* start global off timer */
596 sfi_is_enabled
= TRUE
;
597 sfi_next_off_deadline
= mach_absolute_time() + sfi_window_interval
;
598 timer_call_enter1(&sfi_timer_call_entry
,
600 sfi_next_off_deadline
,
601 TIMER_CALL_SYS_CRITICAL
);
604 simple_unlock(&sfi_lock
);
608 return (KERN_SUCCESS
);
611 kern_return_t
sfi_class_offtime_cancel(sfi_class_id_t class_id
)
615 if (class_id
== SFI_CLASS_UNSPECIFIED
|| class_id
>= MAX_SFI_CLASS_ID
)
616 return (KERN_INVALID_ARGUMENT
);
620 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_CANCEL_CLASS_OFFTIME
), class_id
, 0, 0, 0, 0);
622 simple_lock(&sfi_lock
);
624 /* We never re-program the per-class on-timer, but rather just let it expire naturally */
625 if (sfi_classes
[class_id
].class_sfi_is_enabled
) {
626 sfi_enabled_class_count
--;
628 sfi_classes
[class_id
].off_time_usecs
= 0;
629 sfi_classes
[class_id
].off_time_interval
= 0;
630 sfi_classes
[class_id
].class_sfi_is_enabled
= FALSE
;
632 if (sfi_enabled_class_count
== 0) {
633 sfi_is_enabled
= FALSE
;
636 simple_unlock(&sfi_lock
);
640 return (KERN_SUCCESS
);
643 kern_return_t
sfi_get_class_offtime(sfi_class_id_t class_id
, uint64_t *offtime_usecs
)
645 uint64_t off_time_us
;
648 if (class_id
== SFI_CLASS_UNSPECIFIED
|| class_id
>= MAX_SFI_CLASS_ID
)
653 simple_lock(&sfi_lock
);
654 off_time_us
= sfi_classes
[class_id
].off_time_usecs
;
655 simple_unlock(&sfi_lock
);
659 *offtime_usecs
= off_time_us
;
661 return (KERN_SUCCESS
);
665 * sfi_thread_classify and sfi_processor_active_thread_classify perform the critical
666 * role of quickly categorizing a thread into its SFI class so that an AST_SFI can be
667 * set. As the thread is unwinding to userspace, sfi_ast() performs full locking
668 * and determines whether the thread should enter an SFI wait state. Because of
669 * the inherent races between the time the AST is set and when it is evaluated,
670 * thread classification can be inaccurate (but should always be safe). This is
671 * especially the case for sfi_processor_active_thread_classify, which must
672 * classify the active thread on a remote processor without taking the thread lock.
673 * When in doubt, classification should err on the side of *not* classifying a
674 * thread at all, and wait for the thread itself to either hit a quantum expiration
675 * or block inside the kernel.
679 * Thread must be locked. Ultimately, the real decision to enter
680 * SFI wait happens at the AST boundary.
682 sfi_class_id_t
sfi_thread_classify(thread_t thread
)
684 task_t task
= thread
->task
;
685 boolean_t is_kernel_thread
= (task
== kernel_task
);
686 sched_mode_t thmode
= thread
->sched_mode
;
687 int latency_qos
= proc_get_effective_task_policy(task
, TASK_POLICY_LATENCY_QOS
);
688 int task_role
= proc_get_effective_task_policy(task
, TASK_POLICY_ROLE
);
689 int thread_bg
= proc_get_effective_thread_policy(thread
, TASK_POLICY_DARWIN_BG
);
690 int managed_task
= proc_get_effective_task_policy(task
, TASK_POLICY_SFI_MANAGED
);
691 int thread_qos
= proc_get_effective_thread_policy(thread
, TASK_POLICY_QOS
);
692 boolean_t focal
= FALSE
;
694 /* kernel threads never reach the user AST boundary, and are in a separate world for SFI */
695 if (is_kernel_thread
) {
696 return SFI_CLASS_KERNEL
;
699 if (thread_qos
== THREAD_QOS_MAINTENANCE
)
700 return SFI_CLASS_MAINTENANCE
;
702 if (thread_bg
|| thread_qos
== THREAD_QOS_BACKGROUND
) {
703 return SFI_CLASS_DARWIN_BG
;
706 if (latency_qos
!= 0) {
707 int latency_qos_wtf
= latency_qos
- 1;
709 if ((latency_qos_wtf
>= 4) && (latency_qos_wtf
<= 5)) {
710 return SFI_CLASS_APP_NAP
;
715 * Realtime and fixed priority threads express their duty cycle constraints
716 * via other mechanisms, and are opted out of (most) forms of SFI
718 if (thmode
== TH_MODE_REALTIME
|| thmode
== TH_MODE_FIXED
|| task_role
== TASK_GRAPHICS_SERVER
) {
719 return SFI_CLASS_OPTED_OUT
;
723 * Threads with unspecified, legacy, or user-initiated QOS class can be individually managed.
727 case TASK_CONTROL_APPLICATION
:
728 case TASK_FOREGROUND_APPLICATION
:
732 case TASK_BACKGROUND_APPLICATION
:
733 case TASK_DEFAULT_APPLICATION
:
734 case TASK_UNSPECIFIED
:
735 /* Focal if in coalition with foreground app */
736 if (coalition_focal_task_count(thread
->task
->coalition
) > 0)
745 switch (thread_qos
) {
746 case THREAD_QOS_UNSPECIFIED
:
747 case THREAD_QOS_LEGACY
:
748 case THREAD_QOS_USER_INITIATED
:
750 return SFI_CLASS_MANAGED_FOCAL
;
752 return SFI_CLASS_MANAGED_NONFOCAL
;
758 if (thread_qos
== THREAD_QOS_UTILITY
)
759 return SFI_CLASS_UTILITY
;
762 * Classify threads in non-managed tasks
765 switch (thread_qos
) {
766 case THREAD_QOS_USER_INTERACTIVE
:
767 return SFI_CLASS_USER_INTERACTIVE_FOCAL
;
768 case THREAD_QOS_USER_INITIATED
:
769 return SFI_CLASS_USER_INITIATED_FOCAL
;
770 case THREAD_QOS_LEGACY
:
771 return SFI_CLASS_LEGACY_FOCAL
;
773 return SFI_CLASS_DEFAULT_FOCAL
;
776 switch (thread_qos
) {
777 case THREAD_QOS_USER_INTERACTIVE
:
778 return SFI_CLASS_USER_INTERACTIVE_NONFOCAL
;
779 case THREAD_QOS_USER_INITIATED
:
780 return SFI_CLASS_USER_INITIATED_NONFOCAL
;
781 case THREAD_QOS_LEGACY
:
782 return SFI_CLASS_LEGACY_NONFOCAL
;
784 return SFI_CLASS_DEFAULT_NONFOCAL
;
790 * pset must be locked.
792 sfi_class_id_t
sfi_processor_active_thread_classify(processor_t processor
)
794 return processor
->current_sfi_class
;
798 * thread must be locked. This is inherently racy, with the intent that
799 * at the AST boundary, it will be fully evaluated whether we need to
800 * perform an AST wait
802 ast_t
sfi_thread_needs_ast(thread_t thread
, sfi_class_id_t
*out_class
)
804 sfi_class_id_t class_id
;
806 class_id
= sfi_thread_classify(thread
);
809 *out_class
= class_id
;
811 /* No lock taken, so a stale value may be used. */
812 if (!sfi_classes
[class_id
].class_in_on_phase
)
819 * pset must be locked. We take the SFI class for
820 * the currently running thread which is cached on
821 * the processor_t, and assume it is accurate. In the
822 * worst case, the processor will get an IPI and be asked
823 * to evaluate if the current running thread at that
824 * later point in time should be in an SFI wait.
826 ast_t
sfi_processor_needs_ast(processor_t processor
)
828 sfi_class_id_t class_id
;
830 class_id
= sfi_processor_active_thread_classify(processor
);
832 /* No lock taken, so a stale value may be used. */
833 if (!sfi_classes
[class_id
].class_in_on_phase
)
840 static inline void _sfi_wait_cleanup(sched_call_t callback
) {
841 thread_t self
= current_thread();
842 sfi_class_id_t current_sfi_wait_class
= SFI_CLASS_UNSPECIFIED
;
843 int64_t sfi_wait_time
, sfi_wait_begin
= 0;
845 spl_t s
= splsched();
848 thread_sched_call(self
, callback
);
850 sfi_wait_begin
= self
->wait_sfi_begin_time
;
853 simple_lock(&sfi_lock
);
854 sfi_wait_time
= mach_absolute_time() - sfi_wait_begin
;
855 current_sfi_wait_class
= self
->sfi_wait_class
;
856 self
->sfi_wait_class
= SFI_CLASS_UNSPECIFIED
;
857 simple_unlock(&sfi_lock
);
859 assert(SFI_CLASS_UNSPECIFIED
< current_sfi_wait_class
< MAX_SFI_CLASS_ID
);
860 ledger_credit(self
->task
->ledger
, task_ledgers
.sfi_wait_times
[current_sfi_wait_class
], sfi_wait_time
);
864 * Called at AST context to fully evaluate if the current thread
865 * (which is obviously running) should instead block in an SFI wait.
866 * We must take the sfi_lock to check whether we are in the "off" period
867 * for the class, and if so, block.
869 void sfi_ast(thread_t thread
)
871 sfi_class_id_t class_id
;
873 struct sfi_class_state
*sfi_class
;
874 wait_result_t waitret
;
875 boolean_t did_wait
= FALSE
;
877 thread_continue_t continuation
;
878 sched_call_t workq_callback
= workqueue_get_sched_callback();
879 boolean_t did_clear_wq
= FALSE
;
883 simple_lock(&sfi_lock
);
885 if (!sfi_is_enabled
) {
887 * SFI is not enabled, or has recently been disabled.
888 * There is no point putting this thread on a deferred ready
889 * queue, even if it were classified as needing it, since
890 * SFI will truly be off at the next global off timer
892 simple_unlock(&sfi_lock
);
899 thread
->sfi_class
= class_id
= sfi_thread_classify(thread
);
900 tid
= thread_tid(thread
);
903 * Once the sfi_lock is taken and the thread's ->sfi_class field is updated, we
904 * are committed to transitioning to whatever state is indicated by "->class_in_on_phase".
905 * If another thread tries to call sfi_reevaluate() after this point, it will take the
906 * sfi_lock and see the thread in this wait state. If another thread calls
907 * sfi_reevaluate() before this point, it would see a runnable thread and at most
908 * attempt to send an AST to this processor, but we would have the most accurate
912 /* Optimistically clear workq callback while thread is already locked */
913 if (workq_callback
&& (thread
->sched_call
== workq_callback
)) {
914 thread_sched_call(thread
, NULL
);
917 thread_unlock(thread
);
919 sfi_class
= &sfi_classes
[class_id
];
920 if (!sfi_class
->class_in_on_phase
) {
921 /* Need to block thread in wait queue */
922 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_THREAD_DEFER
), tid
, class_id
, 0, 0, 0);
924 waitret
= wait_queue_assert_wait64(&sfi_class
->wait_queue
,
925 CAST_EVENT64_T(class_id
),
926 THREAD_INTERRUPTIBLE
,
928 if (waitret
== THREAD_WAITING
) {
929 thread
->sfi_wait_class
= class_id
;
931 continuation
= sfi_class
->continuation
;
933 /* thread may be exiting already, all other errors are unexpected */
934 assert(waitret
== THREAD_INTERRUPTED
);
937 simple_unlock(&sfi_lock
);
942 thread_block_reason(continuation
, did_clear_wq
? workq_callback
: NULL
, AST_SFI
);
947 thread_sched_call(thread
, workq_callback
);
948 thread_unlock(thread
);
955 * Thread must be unlocked
956 * May be called with coalition, task, or thread mutex held
958 void sfi_reevaluate(thread_t thread
)
962 sfi_class_id_t class_id
, current_class_id
;
967 simple_lock(&sfi_lock
);
970 sfi_ast
= sfi_thread_needs_ast(thread
, &class_id
);
971 thread
->sfi_class
= class_id
;
974 * This routine chiefly exists to boost threads out of an SFI wait
975 * if their classification changes before the "on" timer fires.
977 * If we calculate that a thread is in a different ->sfi_wait_class
978 * than we think it should be (including no-SFI-wait), we need to
981 * If the thread is in SFI wait and should not be (or should be waiting
982 * on a different class' "on" timer), we wake it up. If needed, the
983 * thread may immediately block again in the different SFI wait state.
985 * If the thread is not in an SFI wait state and it should be, we need
986 * to get that thread's attention, possibly by sending an AST to another
990 if ((current_class_id
= thread
->sfi_wait_class
) != SFI_CLASS_UNSPECIFIED
) {
992 thread_unlock(thread
); /* not needed anymore */
994 assert(current_class_id
< MAX_SFI_CLASS_ID
);
996 if ((sfi_ast
== AST_NONE
) || (class_id
!= current_class_id
)) {
997 struct sfi_class_state
*sfi_class
= &sfi_classes
[current_class_id
];
999 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI
, SFI_WAIT_CANCELED
), thread_tid(thread
), current_class_id
, class_id
, 0, 0);
1001 kret
= wait_queue_wakeup64_thread(&sfi_class
->wait_queue
,
1002 CAST_EVENT64_T(current_class_id
),
1005 assert(kret
== KERN_SUCCESS
|| kret
== KERN_NOT_WAITING
);
1009 * Thread's current SFI wait class is not set, and because we
1010 * have the sfi_lock, it won't get set.
1013 if ((thread
->state
& (TH_RUN
| TH_IDLE
)) == TH_RUN
) {
1014 if (sfi_ast
!= AST_NONE
) {
1015 if (thread
== current_thread())
1018 processor_t processor
= thread
->last_processor
;
1020 if (processor
!= PROCESSOR_NULL
&&
1021 processor
->state
== PROCESSOR_RUNNING
&&
1022 processor
->active_thread
== thread
) {
1023 cause_ast_check(processor
);
1026 * Runnable thread that's not on a CPU currently. When a processor
1027 * does context switch to it, the AST will get set based on whether
1028 * the thread is in its "off time".
1035 thread_unlock(thread
);
1038 simple_unlock(&sfi_lock
);