]> git.saurik.com Git - apple/xnu.git/blob - osfmk/kern/sfi.c
819c6c686fc583cb0d67d3d2d82763a8c5ba340f
[apple/xnu.git] / osfmk / kern / sfi.c
1 /*
2 * Copyright (c) 2013 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 #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>
40 #include <kern/sfi.h>
41 #include <kern/timer_call.h>
42 #include <kern/wait_queue.h>
43 #include <kern/ledger.h>
44 #include <kern/coalition.h>
45
46 #include <pexpert/pexpert.h>
47
48 #include <libkern/kernel_mach_header.h>
49
50 #include <sys/kdebug.h>
51
52 #define SFI_DEBUG 0
53
54 #if SFI_DEBUG
55 #define dprintf(...) kprintf(__VA_ARGS__)
56 #else
57 #define dprintf(...) do { } while(0)
58 #endif
59
60 #ifdef MACH_BSD
61 extern sched_call_t workqueue_get_sched_callback(void);
62 #endif /* MACH_BSD */
63
64 /*
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.
73 */
74
75 /*
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.
83 *
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.
88 *
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.
93 *
94 * The pset lock may also be taken, but not while any other locks are held.
95 *
96 * splsched ---> sfi_lock ---> wait_queue ---> thread_lock
97 * \ \ \__ thread_lock (*)
98 * \ \__ pset_lock
99 * \
100 * \__ thread_lock
101 */
102
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;
106
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;
111
112 typedef struct {
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;
118
119 /*
120 * To add a new SFI class:
121 *
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
127 */
128
129 static inline void _sfi_wait_cleanup(sched_call_t callback);
130
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) \
135 { \
136 _sfi_wait_cleanup(callback); \
137 thread_exception_return(); \
138 } \
139 \
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 };
141
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)
159
160 struct sfi_class_state {
161 uint64_t off_time_usecs;
162 uint64_t off_time_interval;
163
164 timer_call_data_t on_timer;
165 uint64_t on_timer_deadline;
166 boolean_t on_timer_programmed;
167
168 boolean_t class_sfi_is_enabled;
169 volatile boolean_t class_in_on_phase;
170
171 struct wait_queue wait_queue; /* threads in ready state */
172 thread_continue_t continuation;
173
174 const char * class_name;
175 const char * class_ledger_name;
176 };
177
178 /* Static configuration performed in sfi_early_init() */
179 struct sfi_class_state sfi_classes[MAX_SFI_CLASS_ID];
180
181 int sfi_enabled_class_count;
182
183 static void sfi_timer_global_off(
184 timer_call_param_t param0,
185 timer_call_param_t param1);
186
187 static void sfi_timer_per_class_on(
188 timer_call_param_t param0,
189 timer_call_param_t param1);
190
191 static sfi_class_registration_t *
192 sfi_get_registration_data(unsigned long *count)
193 {
194 unsigned long sectlen = 0;
195 void *sectdata;
196
197 sectdata = getsectdatafromheader(&_mh_execute_header, "__DATA", "__sfi_class_reg", &sectlen);
198 if (sectdata) {
199
200 if (sectlen % sizeof(sfi_class_registration_t) != 0) {
201 /* corrupt data? */
202 panic("__sfi_class_reg section has invalid size %lu", sectlen);
203 __builtin_unreachable();
204 }
205
206 *count = sectlen / sizeof(sfi_class_registration_t);
207 return (sfi_class_registration_t *)sectdata;
208 } else {
209 panic("__sfi_class_reg section not found");
210 __builtin_unreachable();
211 }
212 }
213
214 /* Called early in boot, when kernel is single-threaded */
215 void sfi_early_init(void)
216 {
217 unsigned long i, count;
218 sfi_class_registration_t *registrations;
219
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;
223
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);
228 }
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;
234 }
235 }
236 }
237
238 void sfi_init(void)
239 {
240 sfi_class_id_t i;
241 kern_return_t kret;
242
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;
248
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;
254
255 kret = wait_queue_init(&sfi_classes[i].wait_queue, SYNC_POLICY_FIFO);
256 assert(kret == KERN_SUCCESS);
257 } else {
258 /* The only allowed gap is for SFI_CLASS_UNSPECIFIED */
259 if(i != SFI_CLASS_UNSPECIFIED) {
260 panic("Gap in registered SFI classes");
261 }
262 }
263 }
264 }
265
266 /* Can be called before sfi_init() by task initialization, but after sfi_early_init() */
267 sfi_class_id_t
268 sfi_get_ledger_alias_for_class(sfi_class_id_t class_id)
269 {
270 sfi_class_id_t i;
271 const char *ledger_name = NULL;
272
273 ledger_name = sfi_classes[class_id].class_ledger_name;
274
275 /* Find the first class in the registration table with this ledger name */
276 if (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);
280 return i;
281 }
282 }
283
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;
287 }
288
289 /* We are permissive on SFI class lookup failures. In sfi_init(), we assert more */
290 return SFI_CLASS_UNSPECIFIED;
291 }
292
293 int
294 sfi_ledger_entry_add(ledger_template_t template, sfi_class_id_t class_id)
295 {
296 const char *ledger_name = NULL;
297
298 ledger_name = sfi_classes[class_id].class_ledger_name;
299
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");
302 }
303
304 static void sfi_timer_global_off(
305 timer_call_param_t param0 __unused,
306 timer_call_param_t param1 __unused)
307 {
308 uint64_t now = mach_absolute_time();
309 sfi_class_id_t i;
310 processor_set_t pset, nset;
311 processor_t processor;
312 uint32_t needs_cause_ast_mask = 0x0;
313 spl_t s;
314
315 s = splsched();
316
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);
321
322 simple_unlock(&sfi_lock);
323 splx(s);
324 return;
325 }
326
327 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_OFF_TIMER) | DBG_FUNC_START, 0, 0, 0, 0, 0);
328
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;
333
334 sfi_classes[i].class_in_on_phase = FALSE;
335 sfi_classes[i].on_timer_programmed = TRUE;
336
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;
340
341 timer_call_enter1(&sfi_classes[i].on_timer, NULL, on_timer_deadline, TIMER_CALL_SYS_CRITICAL);
342 } else {
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);
349 }
350 }
351 }
352 simple_unlock(&sfi_lock);
353
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;
357
358 pset_lock(pset);
359
360 do {
361 nset = processor->processor_set;
362 if (nset != pset) {
363 pset_unlock(pset);
364 pset = nset;
365 pset_lock(pset);
366 }
367
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);
372 }
373 }
374 } while ((processor = processor->processor_list) != NULL);
375
376 pset_unlock(pset);
377
378 processor = processor_list;
379 do {
380 if (needs_cause_ast_mask & (1U << processor->cpu_id)) {
381 if (processor == current_processor())
382 ast_on(AST_SFI);
383 else
384 cause_ast_check(processor);
385 }
386 } while ((processor = processor->processor_list) != NULL);
387
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,
392 now,
393 &sfi_next_off_deadline);
394 timer_call_enter1(&sfi_timer_call_entry,
395 NULL,
396 sfi_next_off_deadline,
397 TIMER_CALL_SYS_CRITICAL);
398 }
399
400 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_OFF_TIMER) | DBG_FUNC_END, 0, 0, 0, 0, 0);
401
402 simple_unlock(&sfi_lock);
403
404 splx(s);
405 }
406
407 static void sfi_timer_per_class_on(
408 timer_call_param_t param0,
409 timer_call_param_t param1 __unused)
410 {
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];
413 kern_return_t kret;
414 spl_t s;
415
416 s = splsched();
417
418 simple_lock(&sfi_lock);
419
420 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_ON_TIMER) | DBG_FUNC_START, sfi_class_id, 0, 0, 0, 0);
421
422 /*
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.
426 */
427
428 sfi_class->class_in_on_phase = TRUE;
429 sfi_class->on_timer_programmed = FALSE;
430
431 kret = wait_queue_wakeup64_all(&sfi_class->wait_queue,
432 CAST_EVENT64_T(sfi_class_id),
433 THREAD_AWAKENED);
434 assert(kret == KERN_SUCCESS || kret == KERN_NOT_WAITING);
435
436 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_ON_TIMER) | DBG_FUNC_END, 0, 0, 0, 0, 0);
437
438 simple_unlock(&sfi_lock);
439
440 splx(s);
441 }
442
443
444 kern_return_t sfi_set_window(uint64_t window_usecs)
445 {
446 uint64_t interval, deadline;
447 uint64_t now = mach_absolute_time();
448 sfi_class_id_t i;
449 spl_t s;
450 uint64_t largest_class_off_interval = 0;
451
452 if (window_usecs < MIN_SFI_WINDOW_USEC)
453 window_usecs = MIN_SFI_WINDOW_USEC;
454
455 if (window_usecs > UINT32_MAX)
456 return (KERN_INVALID_ARGUMENT);
457
458 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_SET_WINDOW), window_usecs, 0, 0, 0, 0);
459
460 clock_interval_to_absolutetime_interval((uint32_t)window_usecs, NSEC_PER_USEC, &interval);
461 deadline = now + interval;
462
463 s = splsched();
464
465 simple_lock(&sfi_lock);
466
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);
471 }
472 }
473
474 /*
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.
477 */
478 if (interval <= largest_class_off_interval) {
479 simple_unlock(&sfi_lock);
480 splx(s);
481 return (KERN_INVALID_ARGUMENT);
482 }
483
484 /*
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.
490 */
491 sfi_window_usecs = window_usecs;
492 sfi_window_interval = interval;
493 sfi_window_is_set = TRUE;
494
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,
501 NULL,
502 sfi_next_off_deadline,
503 TIMER_CALL_SYS_CRITICAL);
504 } else if (deadline >= sfi_next_off_deadline) {
505 sfi_next_off_deadline = deadline;
506 } else {
507 sfi_next_off_deadline = deadline;
508 timer_call_enter1(&sfi_timer_call_entry,
509 NULL,
510 sfi_next_off_deadline,
511 TIMER_CALL_SYS_CRITICAL);
512 }
513
514 simple_unlock(&sfi_lock);
515 splx(s);
516
517 return (KERN_SUCCESS);
518 }
519
520 kern_return_t sfi_window_cancel(void)
521 {
522 spl_t s;
523
524 s = splsched();
525
526 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_CANCEL_WINDOW), 0, 0, 0, 0, 0);
527
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);
536
537 splx(s);
538
539 return (KERN_SUCCESS);
540 }
541
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.
548 */
549
550 kern_return_t sfi_defer(uint64_t sfi_defer_matus)
551 {
552 spl_t s;
553 kern_return_t kr = KERN_FAILURE;
554 s = splsched();
555
556 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_GLOBAL_DEFER), sfi_defer_matus, 0, 0, 0, 0);
557
558 simple_lock(&sfi_lock);
559 if (!sfi_is_enabled) {
560 goto sfi_defer_done;
561 }
562
563 assert(sfi_next_off_deadline != 0);
564
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);
567
568 int i;
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);
575 }
576 }
577 }
578
579 kr = KERN_SUCCESS;
580 sfi_defer_done:
581 simple_unlock(&sfi_lock);
582
583 splx(s);
584
585 return (kr);
586 }
587
588
589 kern_return_t sfi_get_window(uint64_t *window_usecs)
590 {
591 spl_t s;
592 uint64_t off_window_us;
593
594 s = splsched();
595 simple_lock(&sfi_lock);
596
597 off_window_us = sfi_window_usecs;
598
599 simple_unlock(&sfi_lock);
600 splx(s);
601
602 *window_usecs = off_window_us;
603
604 return (KERN_SUCCESS);
605 }
606
607
608 kern_return_t sfi_set_class_offtime(sfi_class_id_t class_id, uint64_t offtime_usecs)
609 {
610 uint64_t interval;
611 spl_t s;
612 uint64_t off_window_interval;
613
614 if (offtime_usecs < MIN_SFI_WINDOW_USEC)
615 offtime_usecs = MIN_SFI_WINDOW_USEC;
616
617 if (class_id == SFI_CLASS_UNSPECIFIED || class_id >= MAX_SFI_CLASS_ID)
618 return (KERN_INVALID_ARGUMENT);
619
620 if (offtime_usecs > UINT32_MAX)
621 return (KERN_INVALID_ARGUMENT);
622
623 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_SET_CLASS_OFFTIME), offtime_usecs, class_id, 0, 0, 0);
624
625 clock_interval_to_absolutetime_interval((uint32_t)offtime_usecs, NSEC_PER_USEC, &interval);
626
627 s = splsched();
628
629 simple_lock(&sfi_lock);
630 off_window_interval = sfi_window_interval;
631
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);
635 splx(s);
636 return (KERN_INVALID_ARGUMENT);
637 }
638
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++;
642 }
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;
646
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,
652 NULL,
653 sfi_next_off_deadline,
654 TIMER_CALL_SYS_CRITICAL);
655 }
656
657 simple_unlock(&sfi_lock);
658
659 splx(s);
660
661 return (KERN_SUCCESS);
662 }
663
664 kern_return_t sfi_class_offtime_cancel(sfi_class_id_t class_id)
665 {
666 spl_t s;
667
668 if (class_id == SFI_CLASS_UNSPECIFIED || class_id >= MAX_SFI_CLASS_ID)
669 return (KERN_INVALID_ARGUMENT);
670
671 s = splsched();
672
673 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_CANCEL_CLASS_OFFTIME), class_id, 0, 0, 0, 0);
674
675 simple_lock(&sfi_lock);
676
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--;
680 }
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;
684
685 if (sfi_enabled_class_count == 0) {
686 sfi_is_enabled = FALSE;
687 }
688
689 simple_unlock(&sfi_lock);
690
691 splx(s);
692
693 return (KERN_SUCCESS);
694 }
695
696 kern_return_t sfi_get_class_offtime(sfi_class_id_t class_id, uint64_t *offtime_usecs)
697 {
698 uint64_t off_time_us;
699 spl_t s;
700
701 if (class_id == SFI_CLASS_UNSPECIFIED || class_id >= MAX_SFI_CLASS_ID)
702 return (0);
703
704 s = splsched();
705
706 simple_lock(&sfi_lock);
707 off_time_us = sfi_classes[class_id].off_time_usecs;
708 simple_unlock(&sfi_lock);
709
710 splx(s);
711
712 *offtime_usecs = off_time_us;
713
714 return (KERN_SUCCESS);
715 }
716
717 /*
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.
729 */
730
731 /*
732 * Thread must be locked. Ultimately, the real decision to enter
733 * SFI wait happens at the AST boundary.
734 */
735 sfi_class_id_t sfi_thread_classify(thread_t thread)
736 {
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;
746
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;
750 }
751
752 if (thread_qos == THREAD_QOS_MAINTENANCE)
753 return SFI_CLASS_MAINTENANCE;
754
755 if (thread_bg || thread_qos == THREAD_QOS_BACKGROUND) {
756 return SFI_CLASS_DARWIN_BG;
757 }
758
759 if (latency_qos != 0) {
760 int latency_qos_wtf = latency_qos - 1;
761
762 if ((latency_qos_wtf >= 4) && (latency_qos_wtf <= 5)) {
763 return SFI_CLASS_APP_NAP;
764 }
765 }
766
767 /*
768 * Realtime and fixed priority threads express their duty cycle constraints
769 * via other mechanisms, and are opted out of (most) forms of SFI
770 */
771 if (thmode == TH_MODE_REALTIME || thmode == TH_MODE_FIXED || task_role == TASK_GRAPHICS_SERVER) {
772 return SFI_CLASS_OPTED_OUT;
773 }
774
775 /*
776 * Threads with unspecified, legacy, or user-initiated QOS class can be individually managed.
777 */
778
779 switch (task_role) {
780 case TASK_CONTROL_APPLICATION:
781 case TASK_FOREGROUND_APPLICATION:
782 focal = TRUE;
783 break;
784
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)
790 focal = TRUE;
791 break;
792
793 default:
794 break;
795 }
796
797 if (managed_task) {
798 switch (thread_qos) {
799 case THREAD_QOS_UNSPECIFIED:
800 case THREAD_QOS_LEGACY:
801 case THREAD_QOS_USER_INITIATED:
802 if (focal)
803 return SFI_CLASS_MANAGED_FOCAL;
804 else
805 return SFI_CLASS_MANAGED_NONFOCAL;
806 default:
807 break;
808 }
809 }
810
811 if (thread_qos == THREAD_QOS_UTILITY)
812 return SFI_CLASS_UTILITY;
813
814 /*
815 * Classify threads in non-managed tasks
816 */
817 if (focal) {
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;
825 default:
826 return SFI_CLASS_DEFAULT_FOCAL;
827 }
828 } else {
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;
836 default:
837 return SFI_CLASS_DEFAULT_NONFOCAL;
838 }
839 }
840 }
841
842 /*
843 * pset must be locked.
844 */
845 sfi_class_id_t sfi_processor_active_thread_classify(processor_t processor)
846 {
847 return processor->current_sfi_class;
848 }
849
850 /*
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
854 */
855 ast_t sfi_thread_needs_ast(thread_t thread, sfi_class_id_t *out_class)
856 {
857 sfi_class_id_t class_id;
858
859 class_id = sfi_thread_classify(thread);
860
861 if (out_class)
862 *out_class = class_id;
863
864 /* No lock taken, so a stale value may be used. */
865 if (!sfi_classes[class_id].class_in_on_phase)
866 return AST_SFI;
867 else
868 return AST_NONE;
869 }
870
871 /*
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.
878 */
879 ast_t sfi_processor_needs_ast(processor_t processor)
880 {
881 sfi_class_id_t class_id;
882
883 class_id = sfi_processor_active_thread_classify(processor);
884
885 /* No lock taken, so a stale value may be used. */
886 if (!sfi_classes[class_id].class_in_on_phase)
887 return AST_SFI;
888 else
889 return AST_NONE;
890
891 }
892
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;
897
898 spl_t s = splsched();
899 thread_lock(self);
900 if (callback) {
901 thread_sched_call(self, callback);
902 }
903 sfi_wait_begin = self->wait_sfi_begin_time;
904 thread_unlock(self);
905
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);
911 splx(s);
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);
914 }
915
916 /*
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.
921 */
922 void sfi_ast(thread_t thread)
923 {
924 sfi_class_id_t class_id;
925 spl_t s;
926 struct sfi_class_state *sfi_class;
927 wait_result_t waitret;
928 boolean_t did_wait = FALSE;
929 uint64_t tid;
930 thread_continue_t continuation;
931 sched_call_t workq_callback = workqueue_get_sched_callback();
932 boolean_t did_clear_wq = FALSE;
933
934 s = splsched();
935
936 simple_lock(&sfi_lock);
937
938 if (!sfi_is_enabled) {
939 /*
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
944 */
945 simple_unlock(&sfi_lock);
946 splx(s);
947
948 return;
949 }
950
951 thread_lock(thread);
952 thread->sfi_class = class_id = sfi_thread_classify(thread);
953 tid = thread_tid(thread);
954
955 /*
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
962 * classification.
963 */
964
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);
968 did_clear_wq = TRUE;
969 }
970 thread_unlock(thread);
971
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);
976
977 waitret = wait_queue_assert_wait64(&sfi_class->wait_queue,
978 CAST_EVENT64_T(class_id),
979 THREAD_INTERRUPTIBLE,
980 0);
981 if (waitret == THREAD_WAITING) {
982 thread->sfi_wait_class = class_id;
983 did_wait = TRUE;
984 continuation = sfi_class->continuation;
985 } else {
986 /* thread may be exiting already, all other errors are unexpected */
987 assert(waitret == THREAD_INTERRUPTED);
988 }
989 }
990 simple_unlock(&sfi_lock);
991
992 splx(s);
993
994 if (did_wait) {
995 thread_block_reason(continuation, did_clear_wq ? workq_callback : NULL, AST_SFI);
996 } else {
997 if (did_clear_wq) {
998 s = splsched();
999 thread_lock(thread);
1000 thread_sched_call(thread, workq_callback);
1001 thread_unlock(thread);
1002 splx(s);
1003 }
1004 }
1005 }
1006
1007 /*
1008 * Thread must be unlocked
1009 * May be called with coalition, task, or thread mutex held
1010 */
1011 void sfi_reevaluate(thread_t thread)
1012 {
1013 kern_return_t kret;
1014 spl_t s;
1015 sfi_class_id_t class_id, current_class_id;
1016 ast_t sfi_ast;
1017
1018 s = splsched();
1019
1020 simple_lock(&sfi_lock);
1021
1022 thread_lock(thread);
1023 sfi_ast = sfi_thread_needs_ast(thread, &class_id);
1024 thread->sfi_class = class_id;
1025
1026 /*
1027 * This routine chiefly exists to boost threads out of an SFI wait
1028 * if their classification changes before the "on" timer fires.
1029 *
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
1032 * correct that:
1033 *
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.
1037 *
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
1040 * processor.
1041 */
1042
1043 if ((current_class_id = thread->sfi_wait_class) != SFI_CLASS_UNSPECIFIED) {
1044
1045 thread_unlock(thread); /* not needed anymore */
1046
1047 assert(current_class_id < MAX_SFI_CLASS_ID);
1048
1049 if ((sfi_ast == AST_NONE) || (class_id != current_class_id)) {
1050 struct sfi_class_state *sfi_class = &sfi_classes[current_class_id];
1051
1052 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_WAIT_CANCELED), thread_tid(thread), current_class_id, class_id, 0, 0);
1053
1054 kret = wait_queue_wakeup64_thread(&sfi_class->wait_queue,
1055 CAST_EVENT64_T(current_class_id),
1056 thread,
1057 THREAD_AWAKENED);
1058 assert(kret == KERN_SUCCESS || kret == KERN_NOT_WAITING);
1059 }
1060 } else {
1061 /*
1062 * Thread's current SFI wait class is not set, and because we
1063 * have the sfi_lock, it won't get set.
1064 */
1065
1066 if ((thread->state & (TH_RUN | TH_IDLE)) == TH_RUN) {
1067 if (sfi_ast != AST_NONE) {
1068 if (thread == current_thread())
1069 ast_on(sfi_ast);
1070 else {
1071 processor_t processor = thread->last_processor;
1072
1073 if (processor != PROCESSOR_NULL &&
1074 processor->state == PROCESSOR_RUNNING &&
1075 processor->active_thread == thread) {
1076 cause_ast_check(processor);
1077 } else {
1078 /*
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".
1082 */
1083 }
1084 }
1085 }
1086 }
1087
1088 thread_unlock(thread);
1089 }
1090
1091 simple_unlock(&sfi_lock);
1092 splx(s);
1093 }