]> git.saurik.com Git - apple/xnu.git/blob - osfmk/kern/sfi.c
725164c77c311d009a3af2106aaab9e63121e3fb
[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 boolean_t on_timer_programmed;
166
167 boolean_t class_sfi_is_enabled;
168 volatile boolean_t class_in_on_phase;
169
170 struct wait_queue wait_queue; /* threads in ready state */
171 thread_continue_t continuation;
172
173 const char * class_name;
174 const char * class_ledger_name;
175 };
176
177 /* Static configuration performed in sfi_early_init() */
178 struct sfi_class_state sfi_classes[MAX_SFI_CLASS_ID];
179
180 int sfi_enabled_class_count;
181
182 static void sfi_timer_global_off(
183 timer_call_param_t param0,
184 timer_call_param_t param1);
185
186 static void sfi_timer_per_class_on(
187 timer_call_param_t param0,
188 timer_call_param_t param1);
189
190 static sfi_class_registration_t *
191 sfi_get_registration_data(unsigned long *count)
192 {
193 unsigned long sectlen = 0;
194 void *sectdata;
195
196 sectdata = getsectdatafromheader(&_mh_execute_header, "__DATA", "__sfi_class_reg", &sectlen);
197 if (sectdata) {
198
199 if (sectlen % sizeof(sfi_class_registration_t) != 0) {
200 /* corrupt data? */
201 panic("__sfi_class_reg section has invalid size %lu", sectlen);
202 __builtin_unreachable();
203 }
204
205 *count = sectlen / sizeof(sfi_class_registration_t);
206 return (sfi_class_registration_t *)sectdata;
207 } else {
208 panic("__sfi_class_reg section not found");
209 __builtin_unreachable();
210 }
211 }
212
213 /* Called early in boot, when kernel is single-threaded */
214 void sfi_early_init(void)
215 {
216 unsigned long i, count;
217 sfi_class_registration_t *registrations;
218
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;
222
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);
227 }
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;
233 }
234 }
235 }
236
237 void sfi_init(void)
238 {
239 sfi_class_id_t i;
240 kern_return_t kret;
241
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;
247
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;
253
254 kret = wait_queue_init(&sfi_classes[i].wait_queue, SYNC_POLICY_FIFO);
255 assert(kret == KERN_SUCCESS);
256 } else {
257 /* The only allowed gap is for SFI_CLASS_UNSPECIFIED */
258 if(i != SFI_CLASS_UNSPECIFIED) {
259 panic("Gap in registered SFI classes");
260 }
261 }
262 }
263 }
264
265 /* Can be called before sfi_init() by task initialization, but after sfi_early_init() */
266 sfi_class_id_t
267 sfi_get_ledger_alias_for_class(sfi_class_id_t class_id)
268 {
269 sfi_class_id_t i;
270 const char *ledger_name = NULL;
271
272 ledger_name = sfi_classes[class_id].class_ledger_name;
273
274 /* Find the first class in the registration table with this ledger name */
275 if (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);
279 return i;
280 }
281 }
282
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;
286 }
287
288 /* We are permissive on SFI class lookup failures. In sfi_init(), we assert more */
289 return SFI_CLASS_UNSPECIFIED;
290 }
291
292 int
293 sfi_ledger_entry_add(ledger_template_t template, sfi_class_id_t class_id)
294 {
295 const char *ledger_name = NULL;
296
297 ledger_name = sfi_classes[class_id].class_ledger_name;
298
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");
301 }
302
303 static void sfi_timer_global_off(
304 timer_call_param_t param0 __unused,
305 timer_call_param_t param1 __unused)
306 {
307 uint64_t now = mach_absolute_time();
308 sfi_class_id_t i;
309 processor_set_t pset, nset;
310 processor_t processor;
311 uint32_t needs_cause_ast_mask = 0x0;
312 spl_t s;
313
314 s = splsched();
315
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);
320
321 simple_unlock(&sfi_lock);
322 splx(s);
323 return;
324 }
325
326 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_OFF_TIMER) | DBG_FUNC_START, 0, 0, 0, 0, 0);
327
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;
332
333 sfi_classes[i].class_in_on_phase = FALSE;
334 sfi_classes[i].on_timer_programmed = TRUE;
335
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);
339 } else {
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);
345 }
346 }
347 }
348 simple_unlock(&sfi_lock);
349
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;
353
354 pset_lock(pset);
355
356 do {
357 nset = processor->processor_set;
358 if (nset != pset) {
359 pset_unlock(pset);
360 pset = nset;
361 pset_lock(pset);
362 }
363
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);
368 }
369 }
370 } while ((processor = processor->processor_list) != NULL);
371
372 pset_unlock(pset);
373
374 processor = processor_list;
375 do {
376 if (needs_cause_ast_mask & (1U << processor->cpu_id)) {
377 if (processor == current_processor())
378 ast_on(AST_SFI);
379 else
380 cause_ast_check(processor);
381 }
382 } while ((processor = processor->processor_list) != NULL);
383
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,
388 now,
389 &sfi_next_off_deadline);
390 timer_call_enter1(&sfi_timer_call_entry,
391 NULL,
392 sfi_next_off_deadline,
393 TIMER_CALL_SYS_CRITICAL);
394 }
395
396 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_OFF_TIMER) | DBG_FUNC_END, 0, 0, 0, 0, 0);
397
398 simple_unlock(&sfi_lock);
399
400 splx(s);
401 }
402
403 static void sfi_timer_per_class_on(
404 timer_call_param_t param0,
405 timer_call_param_t param1 __unused)
406 {
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];
409 kern_return_t kret;
410 spl_t s;
411
412 s = splsched();
413
414 simple_lock(&sfi_lock);
415
416 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_ON_TIMER) | DBG_FUNC_START, sfi_class_id, 0, 0, 0, 0);
417
418 /*
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.
422 */
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),
426 THREAD_AWAKENED);
427 assert(kret == KERN_SUCCESS || kret == KERN_NOT_WAITING);
428
429 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_ON_TIMER) | DBG_FUNC_END, 0, 0, 0, 0, 0);
430
431 simple_unlock(&sfi_lock);
432
433 splx(s);
434 }
435
436
437 kern_return_t sfi_set_window(uint64_t window_usecs)
438 {
439 uint64_t interval, deadline;
440 uint64_t now = mach_absolute_time();
441 sfi_class_id_t i;
442 spl_t s;
443 uint64_t largest_class_off_interval = 0;
444
445 if (window_usecs < MIN_SFI_WINDOW_USEC)
446 window_usecs = MIN_SFI_WINDOW_USEC;
447
448 if (window_usecs > UINT32_MAX)
449 return (KERN_INVALID_ARGUMENT);
450
451 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_SET_WINDOW), window_usecs, 0, 0, 0, 0);
452
453 clock_interval_to_absolutetime_interval((uint32_t)window_usecs, NSEC_PER_USEC, &interval);
454 deadline = now + interval;
455
456 s = splsched();
457
458 simple_lock(&sfi_lock);
459
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);
464 }
465 }
466
467 /*
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.
470 */
471 if (interval <= largest_class_off_interval) {
472 simple_unlock(&sfi_lock);
473 splx(s);
474 return (KERN_INVALID_ARGUMENT);
475 }
476
477 /*
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.
483 */
484 sfi_window_usecs = window_usecs;
485 sfi_window_interval = interval;
486 sfi_window_is_set = TRUE;
487
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,
494 NULL,
495 sfi_next_off_deadline,
496 TIMER_CALL_SYS_CRITICAL);
497 } else if (deadline >= sfi_next_off_deadline) {
498 sfi_next_off_deadline = deadline;
499 } else {
500 sfi_next_off_deadline = deadline;
501 timer_call_enter1(&sfi_timer_call_entry,
502 NULL,
503 sfi_next_off_deadline,
504 TIMER_CALL_SYS_CRITICAL);
505 }
506
507 simple_unlock(&sfi_lock);
508 splx(s);
509
510 return (KERN_SUCCESS);
511 }
512
513 kern_return_t sfi_window_cancel(void)
514 {
515 spl_t s;
516
517 s = splsched();
518
519 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_CANCEL_WINDOW), 0, 0, 0, 0, 0);
520
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);
529
530 splx(s);
531
532 return (KERN_SUCCESS);
533 }
534
535
536 kern_return_t sfi_get_window(uint64_t *window_usecs)
537 {
538 spl_t s;
539 uint64_t off_window_us;
540
541 s = splsched();
542 simple_lock(&sfi_lock);
543
544 off_window_us = sfi_window_usecs;
545
546 simple_unlock(&sfi_lock);
547 splx(s);
548
549 *window_usecs = off_window_us;
550
551 return (KERN_SUCCESS);
552 }
553
554
555 kern_return_t sfi_set_class_offtime(sfi_class_id_t class_id, uint64_t offtime_usecs)
556 {
557 uint64_t interval;
558 spl_t s;
559 uint64_t off_window_interval;
560
561 if (offtime_usecs < MIN_SFI_WINDOW_USEC)
562 offtime_usecs = MIN_SFI_WINDOW_USEC;
563
564 if (class_id == SFI_CLASS_UNSPECIFIED || class_id >= MAX_SFI_CLASS_ID)
565 return (KERN_INVALID_ARGUMENT);
566
567 if (offtime_usecs > UINT32_MAX)
568 return (KERN_INVALID_ARGUMENT);
569
570 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_SET_CLASS_OFFTIME), offtime_usecs, class_id, 0, 0, 0);
571
572 clock_interval_to_absolutetime_interval((uint32_t)offtime_usecs, NSEC_PER_USEC, &interval);
573
574 s = splsched();
575
576 simple_lock(&sfi_lock);
577 off_window_interval = sfi_window_interval;
578
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);
582 splx(s);
583 return (KERN_INVALID_ARGUMENT);
584 }
585
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++;
589 }
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;
593
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,
599 NULL,
600 sfi_next_off_deadline,
601 TIMER_CALL_SYS_CRITICAL);
602 }
603
604 simple_unlock(&sfi_lock);
605
606 splx(s);
607
608 return (KERN_SUCCESS);
609 }
610
611 kern_return_t sfi_class_offtime_cancel(sfi_class_id_t class_id)
612 {
613 spl_t s;
614
615 if (class_id == SFI_CLASS_UNSPECIFIED || class_id >= MAX_SFI_CLASS_ID)
616 return (KERN_INVALID_ARGUMENT);
617
618 s = splsched();
619
620 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_CANCEL_CLASS_OFFTIME), class_id, 0, 0, 0, 0);
621
622 simple_lock(&sfi_lock);
623
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--;
627 }
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;
631
632 if (sfi_enabled_class_count == 0) {
633 sfi_is_enabled = FALSE;
634 }
635
636 simple_unlock(&sfi_lock);
637
638 splx(s);
639
640 return (KERN_SUCCESS);
641 }
642
643 kern_return_t sfi_get_class_offtime(sfi_class_id_t class_id, uint64_t *offtime_usecs)
644 {
645 uint64_t off_time_us;
646 spl_t s;
647
648 if (class_id == SFI_CLASS_UNSPECIFIED || class_id >= MAX_SFI_CLASS_ID)
649 return (0);
650
651 s = splsched();
652
653 simple_lock(&sfi_lock);
654 off_time_us = sfi_classes[class_id].off_time_usecs;
655 simple_unlock(&sfi_lock);
656
657 splx(s);
658
659 *offtime_usecs = off_time_us;
660
661 return (KERN_SUCCESS);
662 }
663
664 /*
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.
676 */
677
678 /*
679 * Thread must be locked. Ultimately, the real decision to enter
680 * SFI wait happens at the AST boundary.
681 */
682 sfi_class_id_t sfi_thread_classify(thread_t thread)
683 {
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;
693
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;
697 }
698
699 if (thread_qos == THREAD_QOS_MAINTENANCE)
700 return SFI_CLASS_MAINTENANCE;
701
702 if (thread_bg || thread_qos == THREAD_QOS_BACKGROUND) {
703 return SFI_CLASS_DARWIN_BG;
704 }
705
706 if (latency_qos != 0) {
707 int latency_qos_wtf = latency_qos - 1;
708
709 if ((latency_qos_wtf >= 4) && (latency_qos_wtf <= 5)) {
710 return SFI_CLASS_APP_NAP;
711 }
712 }
713
714 /*
715 * Realtime and fixed priority threads express their duty cycle constraints
716 * via other mechanisms, and are opted out of (most) forms of SFI
717 */
718 if (thmode == TH_MODE_REALTIME || thmode == TH_MODE_FIXED || task_role == TASK_GRAPHICS_SERVER) {
719 return SFI_CLASS_OPTED_OUT;
720 }
721
722 /*
723 * Threads with unspecified, legacy, or user-initiated QOS class can be individually managed.
724 */
725
726 switch (task_role) {
727 case TASK_CONTROL_APPLICATION:
728 case TASK_FOREGROUND_APPLICATION:
729 focal = TRUE;
730 break;
731
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)
737 focal = TRUE;
738 break;
739
740 default:
741 break;
742 }
743
744 if (managed_task) {
745 switch (thread_qos) {
746 case THREAD_QOS_UNSPECIFIED:
747 case THREAD_QOS_LEGACY:
748 case THREAD_QOS_USER_INITIATED:
749 if (focal)
750 return SFI_CLASS_MANAGED_FOCAL;
751 else
752 return SFI_CLASS_MANAGED_NONFOCAL;
753 default:
754 break;
755 }
756 }
757
758 if (thread_qos == THREAD_QOS_UTILITY)
759 return SFI_CLASS_UTILITY;
760
761 /*
762 * Classify threads in non-managed tasks
763 */
764 if (focal) {
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;
772 default:
773 return SFI_CLASS_DEFAULT_FOCAL;
774 }
775 } else {
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;
783 default:
784 return SFI_CLASS_DEFAULT_NONFOCAL;
785 }
786 }
787 }
788
789 /*
790 * pset must be locked.
791 */
792 sfi_class_id_t sfi_processor_active_thread_classify(processor_t processor)
793 {
794 return processor->current_sfi_class;
795 }
796
797 /*
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
801 */
802 ast_t sfi_thread_needs_ast(thread_t thread, sfi_class_id_t *out_class)
803 {
804 sfi_class_id_t class_id;
805
806 class_id = sfi_thread_classify(thread);
807
808 if (out_class)
809 *out_class = class_id;
810
811 /* No lock taken, so a stale value may be used. */
812 if (!sfi_classes[class_id].class_in_on_phase)
813 return AST_SFI;
814 else
815 return AST_NONE;
816 }
817
818 /*
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.
825 */
826 ast_t sfi_processor_needs_ast(processor_t processor)
827 {
828 sfi_class_id_t class_id;
829
830 class_id = sfi_processor_active_thread_classify(processor);
831
832 /* No lock taken, so a stale value may be used. */
833 if (!sfi_classes[class_id].class_in_on_phase)
834 return AST_SFI;
835 else
836 return AST_NONE;
837
838 }
839
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;
844
845 spl_t s = splsched();
846 thread_lock(self);
847 if (callback) {
848 thread_sched_call(self, callback);
849 }
850 sfi_wait_begin = self->wait_sfi_begin_time;
851 thread_unlock(self);
852
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);
858 splx(s);
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);
861 }
862
863 /*
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.
868 */
869 void sfi_ast(thread_t thread)
870 {
871 sfi_class_id_t class_id;
872 spl_t s;
873 struct sfi_class_state *sfi_class;
874 wait_result_t waitret;
875 boolean_t did_wait = FALSE;
876 uint64_t tid;
877 thread_continue_t continuation;
878 sched_call_t workq_callback = workqueue_get_sched_callback();
879 boolean_t did_clear_wq = FALSE;
880
881 s = splsched();
882
883 simple_lock(&sfi_lock);
884
885 if (!sfi_is_enabled) {
886 /*
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
891 */
892 simple_unlock(&sfi_lock);
893 splx(s);
894
895 return;
896 }
897
898 thread_lock(thread);
899 thread->sfi_class = class_id = sfi_thread_classify(thread);
900 tid = thread_tid(thread);
901
902 /*
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
909 * classification.
910 */
911
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);
915 did_clear_wq = TRUE;
916 }
917 thread_unlock(thread);
918
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);
923
924 waitret = wait_queue_assert_wait64(&sfi_class->wait_queue,
925 CAST_EVENT64_T(class_id),
926 THREAD_INTERRUPTIBLE,
927 0);
928 if (waitret == THREAD_WAITING) {
929 thread->sfi_wait_class = class_id;
930 did_wait = TRUE;
931 continuation = sfi_class->continuation;
932 } else {
933 /* thread may be exiting already, all other errors are unexpected */
934 assert(waitret == THREAD_INTERRUPTED);
935 }
936 }
937 simple_unlock(&sfi_lock);
938
939 splx(s);
940
941 if (did_wait) {
942 thread_block_reason(continuation, did_clear_wq ? workq_callback : NULL, AST_SFI);
943 } else {
944 if (did_clear_wq) {
945 s = splsched();
946 thread_lock(thread);
947 thread_sched_call(thread, workq_callback);
948 thread_unlock(thread);
949 splx(s);
950 }
951 }
952 }
953
954 /*
955 * Thread must be unlocked
956 * May be called with coalition, task, or thread mutex held
957 */
958 void sfi_reevaluate(thread_t thread)
959 {
960 kern_return_t kret;
961 spl_t s;
962 sfi_class_id_t class_id, current_class_id;
963 ast_t sfi_ast;
964
965 s = splsched();
966
967 simple_lock(&sfi_lock);
968
969 thread_lock(thread);
970 sfi_ast = sfi_thread_needs_ast(thread, &class_id);
971 thread->sfi_class = class_id;
972
973 /*
974 * This routine chiefly exists to boost threads out of an SFI wait
975 * if their classification changes before the "on" timer fires.
976 *
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
979 * correct that:
980 *
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.
984 *
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
987 * processor.
988 */
989
990 if ((current_class_id = thread->sfi_wait_class) != SFI_CLASS_UNSPECIFIED) {
991
992 thread_unlock(thread); /* not needed anymore */
993
994 assert(current_class_id < MAX_SFI_CLASS_ID);
995
996 if ((sfi_ast == AST_NONE) || (class_id != current_class_id)) {
997 struct sfi_class_state *sfi_class = &sfi_classes[current_class_id];
998
999 KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SFI, SFI_WAIT_CANCELED), thread_tid(thread), current_class_id, class_id, 0, 0);
1000
1001 kret = wait_queue_wakeup64_thread(&sfi_class->wait_queue,
1002 CAST_EVENT64_T(current_class_id),
1003 thread,
1004 THREAD_AWAKENED);
1005 assert(kret == KERN_SUCCESS || kret == KERN_NOT_WAITING);
1006 }
1007 } else {
1008 /*
1009 * Thread's current SFI wait class is not set, and because we
1010 * have the sfi_lock, it won't get set.
1011 */
1012
1013 if ((thread->state & (TH_RUN | TH_IDLE)) == TH_RUN) {
1014 if (sfi_ast != AST_NONE) {
1015 if (thread == current_thread())
1016 ast_on(sfi_ast);
1017 else {
1018 processor_t processor = thread->last_processor;
1019
1020 if (processor != PROCESSOR_NULL &&
1021 processor->state == PROCESSOR_RUNNING &&
1022 processor->active_thread == thread) {
1023 cause_ast_check(processor);
1024 } else {
1025 /*
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".
1029 */
1030 }
1031 }
1032 }
1033 }
1034
1035 thread_unlock(thread);
1036 }
1037
1038 simple_unlock(&sfi_lock);
1039 splx(s);
1040 }