1 /*
2 * Copyright (c) 2007-2021 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
29 #include <arm/machine_cpu.h>
30 #include <arm/cpu_internal.h>
31 #include <arm/cpuid.h>
32 #include <arm/cpuid_internal.h>
33 #include <arm/cpu_data.h>
34 #include <arm/cpu_data_internal.h>
35 #include <arm/misc_protos.h>
36 #include <arm/machdep_call.h>
37 #include <arm/machine_routines.h>
38 #include <arm/rtclock.h>
39 #include <kern/machine.h>
40 #include <kern/thread.h>
41 #include <kern/thread_group.h>
42 #include <kern/policy_internal.h>
43 #include <kern/sched_hygiene.h>
44 #include <kern/startup.h>
45 #include <machine/config.h>
46 #include <machine/atomic.h>
47 #include <pexpert/pexpert.h>
48 #include <pexpert/device_tree.h>
49
50 #if MONOTONIC
51 #include <kern/monotonic.h>
52 #include <machine/monotonic.h>
53 #endif /* MONOTONIC */
54
55 #include <mach/machine.h>
56 #include <mach/machine/sdt.h>
57
58 #if !HAS_CONTINUOUS_HWCLOCK
59 extern uint64_t mach_absolutetime_asleep;
60 #else
61 extern uint64_t wake_abstime;
62 static uint64_t wake_conttime = UINT64_MAX;
63 #endif
64
65 extern volatile uint32_t debug_enabled;
66 extern _Atomic unsigned int cluster_type_num_active_cpus[MAX_CPU_TYPES];
67 const char *cluster_type_names[MAX_CPU_TYPES] = {
68 [CLUSTER_TYPE_SMP] = "Standard",
69 [CLUSTER_TYPE_P] = "Performance",
70 [CLUSTER_TYPE_E] = "Efficiency",
71 };
72
73 static int max_cpus_initialized = 0;
74 #define MAX_CPUS_SET 0x1
75 #define MAX_CPUS_WAIT 0x2
76
77 LCK_GRP_DECLARE(max_cpus_grp, "max_cpus");
78 LCK_MTX_DECLARE(max_cpus_lock, &max_cpus_grp);
79 uint32_t lockdown_done = 0;
80 boolean_t is_clock_configured = FALSE;
81
82
83 static void
sched_perfcontrol_oncore_default(perfcontrol_state_t new_thread_state __unused,going_on_core_t on __unused)84 sched_perfcontrol_oncore_default(perfcontrol_state_t new_thread_state __unused, going_on_core_t on __unused)
85 {
86 }
87
88 static void
sched_perfcontrol_switch_default(perfcontrol_state_t old_thread_state __unused,perfcontrol_state_t new_thread_state __unused)89 sched_perfcontrol_switch_default(perfcontrol_state_t old_thread_state __unused, perfcontrol_state_t new_thread_state __unused)
90 {
91 }
92
93 static void
sched_perfcontrol_offcore_default(perfcontrol_state_t old_thread_state __unused,going_off_core_t off __unused,boolean_t thread_terminating __unused)94 sched_perfcontrol_offcore_default(perfcontrol_state_t old_thread_state __unused, going_off_core_t off __unused, boolean_t thread_terminating __unused)
95 {
96 }
97
98 static void
sched_perfcontrol_thread_group_default(thread_group_data_t data __unused)99 sched_perfcontrol_thread_group_default(thread_group_data_t data __unused)
100 {
101 }
102
103 static void
sched_perfcontrol_max_runnable_latency_default(perfcontrol_max_runnable_latency_t latencies __unused)104 sched_perfcontrol_max_runnable_latency_default(perfcontrol_max_runnable_latency_t latencies __unused)
105 {
106 }
107
108 static void
sched_perfcontrol_work_interval_notify_default(perfcontrol_state_t thread_state __unused,perfcontrol_work_interval_t work_interval __unused)109 sched_perfcontrol_work_interval_notify_default(perfcontrol_state_t thread_state __unused,
110 perfcontrol_work_interval_t work_interval __unused)
111 {
112 }
113
114 static void
sched_perfcontrol_work_interval_ctl_default(perfcontrol_state_t thread_state __unused,perfcontrol_work_interval_instance_t instance __unused)115 sched_perfcontrol_work_interval_ctl_default(perfcontrol_state_t thread_state __unused,
116 perfcontrol_work_interval_instance_t instance __unused)
117 {
118 }
119
120 static void
sched_perfcontrol_deadline_passed_default(__unused uint64_t deadline)121 sched_perfcontrol_deadline_passed_default(__unused uint64_t deadline)
122 {
123 }
124
125 static void
sched_perfcontrol_csw_default(__unused perfcontrol_event event,__unused uint32_t cpu_id,__unused uint64_t timestamp,__unused uint32_t flags,__unused struct perfcontrol_thread_data * offcore,__unused struct perfcontrol_thread_data * oncore,__unused struct perfcontrol_cpu_counters * cpu_counters,__unused void * unused)126 sched_perfcontrol_csw_default(
127 __unused perfcontrol_event event, __unused uint32_t cpu_id, __unused uint64_t timestamp,
128 __unused uint32_t flags, __unused struct perfcontrol_thread_data *offcore,
129 __unused struct perfcontrol_thread_data *oncore,
130 __unused struct perfcontrol_cpu_counters *cpu_counters, __unused void *unused)
131 {
132 }
133
134 static void
sched_perfcontrol_state_update_default(__unused perfcontrol_event event,__unused uint32_t cpu_id,__unused uint64_t timestamp,__unused uint32_t flags,__unused struct perfcontrol_thread_data * thr_data,__unused void * unused)135 sched_perfcontrol_state_update_default(
136 __unused perfcontrol_event event, __unused uint32_t cpu_id, __unused uint64_t timestamp,
137 __unused uint32_t flags, __unused struct perfcontrol_thread_data *thr_data,
138 __unused void *unused)
139 {
140 }
141
142 static void
sched_perfcontrol_thread_group_blocked_default(__unused thread_group_data_t blocked_tg,__unused thread_group_data_t blocking_tg,__unused uint32_t flags,__unused perfcontrol_state_t blocked_thr_state)143 sched_perfcontrol_thread_group_blocked_default(
144 __unused thread_group_data_t blocked_tg, __unused thread_group_data_t blocking_tg,
145 __unused uint32_t flags, __unused perfcontrol_state_t blocked_thr_state)
146 {
147 }
148
149 static void
sched_perfcontrol_thread_group_unblocked_default(__unused thread_group_data_t unblocked_tg,__unused thread_group_data_t unblocking_tg,__unused uint32_t flags,__unused perfcontrol_state_t unblocked_thr_state)150 sched_perfcontrol_thread_group_unblocked_default(
151 __unused thread_group_data_t unblocked_tg, __unused thread_group_data_t unblocking_tg,
152 __unused uint32_t flags, __unused perfcontrol_state_t unblocked_thr_state)
153 {
154 }
155
156 sched_perfcontrol_offcore_t sched_perfcontrol_offcore = sched_perfcontrol_offcore_default;
157 sched_perfcontrol_context_switch_t sched_perfcontrol_switch = sched_perfcontrol_switch_default;
158 sched_perfcontrol_oncore_t sched_perfcontrol_oncore = sched_perfcontrol_oncore_default;
159 sched_perfcontrol_thread_group_init_t sched_perfcontrol_thread_group_init = sched_perfcontrol_thread_group_default;
160 sched_perfcontrol_thread_group_deinit_t sched_perfcontrol_thread_group_deinit = sched_perfcontrol_thread_group_default;
161 sched_perfcontrol_thread_group_flags_update_t sched_perfcontrol_thread_group_flags_update = sched_perfcontrol_thread_group_default;
162 sched_perfcontrol_max_runnable_latency_t sched_perfcontrol_max_runnable_latency = sched_perfcontrol_max_runnable_latency_default;
163 sched_perfcontrol_work_interval_notify_t sched_perfcontrol_work_interval_notify = sched_perfcontrol_work_interval_notify_default;
164 sched_perfcontrol_work_interval_ctl_t sched_perfcontrol_work_interval_ctl = sched_perfcontrol_work_interval_ctl_default;
165 sched_perfcontrol_deadline_passed_t sched_perfcontrol_deadline_passed = sched_perfcontrol_deadline_passed_default;
166 sched_perfcontrol_csw_t sched_perfcontrol_csw = sched_perfcontrol_csw_default;
167 sched_perfcontrol_state_update_t sched_perfcontrol_state_update = sched_perfcontrol_state_update_default;
168 sched_perfcontrol_thread_group_blocked_t sched_perfcontrol_thread_group_blocked = sched_perfcontrol_thread_group_blocked_default;
169 sched_perfcontrol_thread_group_unblocked_t sched_perfcontrol_thread_group_unblocked = sched_perfcontrol_thread_group_unblocked_default;
170 boolean_t sched_perfcontrol_thread_shared_rsrc_flags_enabled = false;
171
172 void
sched_perfcontrol_register_callbacks(sched_perfcontrol_callbacks_t callbacks,unsigned long size_of_state)173 sched_perfcontrol_register_callbacks(sched_perfcontrol_callbacks_t callbacks, unsigned long size_of_state)
174 {
175 assert(callbacks == NULL || callbacks->version >= SCHED_PERFCONTROL_CALLBACKS_VERSION_2);
176
177 if (size_of_state > sizeof(struct perfcontrol_state)) {
178 panic("%s: Invalid required state size %lu", __FUNCTION__, size_of_state);
179 }
180
181 if (callbacks) {
182 #if CONFIG_THREAD_GROUPS
183 if (callbacks->version >= SCHED_PERFCONTROL_CALLBACKS_VERSION_3) {
184 if (callbacks->thread_group_init != NULL) {
185 sched_perfcontrol_thread_group_init = callbacks->thread_group_init;
186 } else {
187 sched_perfcontrol_thread_group_init = sched_perfcontrol_thread_group_default;
188 }
189 if (callbacks->thread_group_deinit != NULL) {
190 sched_perfcontrol_thread_group_deinit = callbacks->thread_group_deinit;
191 } else {
192 sched_perfcontrol_thread_group_deinit = sched_perfcontrol_thread_group_default;
193 }
194 // tell CLPC about existing thread groups
195 thread_group_resync(TRUE);
196 }
197
198 if (callbacks->version >= SCHED_PERFCONTROL_CALLBACKS_VERSION_6) {
199 if (callbacks->thread_group_flags_update != NULL) {
200 sched_perfcontrol_thread_group_flags_update = callbacks->thread_group_flags_update;
201 } else {
202 sched_perfcontrol_thread_group_flags_update = sched_perfcontrol_thread_group_default;
203 }
204 }
205
206 if (callbacks->version >= SCHED_PERFCONTROL_CALLBACKS_VERSION_8) {
207 if (callbacks->thread_group_blocked != NULL) {
208 sched_perfcontrol_thread_group_blocked = callbacks->thread_group_blocked;
209 } else {
210 sched_perfcontrol_thread_group_blocked = sched_perfcontrol_thread_group_blocked_default;
211 }
212
213 if (callbacks->thread_group_unblocked != NULL) {
214 sched_perfcontrol_thread_group_unblocked = callbacks->thread_group_unblocked;
215 } else {
216 sched_perfcontrol_thread_group_unblocked = sched_perfcontrol_thread_group_unblocked_default;
217 }
218 }
219 #endif
220 if (callbacks->version >= SCHED_PERFCONTROL_CALLBACKS_VERSION_9) {
221 sched_perfcontrol_thread_shared_rsrc_flags_enabled = true;
222 }
223
224 if (callbacks->version >= SCHED_PERFCONTROL_CALLBACKS_VERSION_7) {
225 if (callbacks->work_interval_ctl != NULL) {
226 sched_perfcontrol_work_interval_ctl = callbacks->work_interval_ctl;
227 } else {
228 sched_perfcontrol_work_interval_ctl = sched_perfcontrol_work_interval_ctl_default;
229 }
230 }
231
232 if (callbacks->version >= SCHED_PERFCONTROL_CALLBACKS_VERSION_5) {
233 if (callbacks->csw != NULL) {
234 sched_perfcontrol_csw = callbacks->csw;
235 } else {
236 sched_perfcontrol_csw = sched_perfcontrol_csw_default;
237 }
238
239 if (callbacks->state_update != NULL) {
240 sched_perfcontrol_state_update = callbacks->state_update;
241 } else {
242 sched_perfcontrol_state_update = sched_perfcontrol_state_update_default;
243 }
244 }
245
246 if (callbacks->version >= SCHED_PERFCONTROL_CALLBACKS_VERSION_4) {
247 if (callbacks->deadline_passed != NULL) {
248 sched_perfcontrol_deadline_passed = callbacks->deadline_passed;
249 } else {
250 sched_perfcontrol_deadline_passed = sched_perfcontrol_deadline_passed_default;
251 }
252 }
253
254 if (callbacks->offcore != NULL) {
255 sched_perfcontrol_offcore = callbacks->offcore;
256 } else {
257 sched_perfcontrol_offcore = sched_perfcontrol_offcore_default;
258 }
259
260 if (callbacks->context_switch != NULL) {
261 sched_perfcontrol_switch = callbacks->context_switch;
262 } else {
263 sched_perfcontrol_switch = sched_perfcontrol_switch_default;
264 }
265
266 if (callbacks->oncore != NULL) {
267 sched_perfcontrol_oncore = callbacks->oncore;
268 } else {
269 sched_perfcontrol_oncore = sched_perfcontrol_oncore_default;
270 }
271
272 if (callbacks->max_runnable_latency != NULL) {
273 sched_perfcontrol_max_runnable_latency = callbacks->max_runnable_latency;
274 } else {
275 sched_perfcontrol_max_runnable_latency = sched_perfcontrol_max_runnable_latency_default;
276 }
277
278 if (callbacks->work_interval_notify != NULL) {
279 sched_perfcontrol_work_interval_notify = callbacks->work_interval_notify;
280 } else {
281 sched_perfcontrol_work_interval_notify = sched_perfcontrol_work_interval_notify_default;
282 }
283 } else {
284 /* reset to defaults */
285 #if CONFIG_THREAD_GROUPS
286 thread_group_resync(FALSE);
287 #endif
288 sched_perfcontrol_offcore = sched_perfcontrol_offcore_default;
289 sched_perfcontrol_switch = sched_perfcontrol_switch_default;
290 sched_perfcontrol_oncore = sched_perfcontrol_oncore_default;
291 sched_perfcontrol_thread_group_init = sched_perfcontrol_thread_group_default;
292 sched_perfcontrol_thread_group_deinit = sched_perfcontrol_thread_group_default;
293 sched_perfcontrol_thread_group_flags_update = sched_perfcontrol_thread_group_default;
294 sched_perfcontrol_max_runnable_latency = sched_perfcontrol_max_runnable_latency_default;
295 sched_perfcontrol_work_interval_notify = sched_perfcontrol_work_interval_notify_default;
296 sched_perfcontrol_work_interval_ctl = sched_perfcontrol_work_interval_ctl_default;
297 sched_perfcontrol_csw = sched_perfcontrol_csw_default;
298 sched_perfcontrol_state_update = sched_perfcontrol_state_update_default;
299 sched_perfcontrol_thread_group_blocked = sched_perfcontrol_thread_group_blocked_default;
300 sched_perfcontrol_thread_group_unblocked = sched_perfcontrol_thread_group_unblocked_default;
301 }
302 }
303
304
305 static void
machine_switch_populate_perfcontrol_thread_data(struct perfcontrol_thread_data * data,thread_t thread,uint64_t same_pri_latency)306 machine_switch_populate_perfcontrol_thread_data(struct perfcontrol_thread_data *data,
307 thread_t thread,
308 uint64_t same_pri_latency)
309 {
310 bzero(data, sizeof(struct perfcontrol_thread_data));
311 data->perfctl_class = thread_get_perfcontrol_class(thread);
312 data->energy_estimate_nj = 0;
313 data->thread_id = thread->thread_id;
314 #if CONFIG_THREAD_GROUPS
315 struct thread_group *tg = thread_group_get(thread);
316 data->thread_group_id = thread_group_get_id(tg);
317 data->thread_group_data = thread_group_get_machine_data(tg);
318 #endif
319 data->scheduling_latency_at_same_basepri = same_pri_latency;
320 data->perfctl_state = FIND_PERFCONTROL_STATE(thread);
321 }
322
323 static void
machine_switch_populate_perfcontrol_cpu_counters(struct perfcontrol_cpu_counters * cpu_counters)324 machine_switch_populate_perfcontrol_cpu_counters(struct perfcontrol_cpu_counters *cpu_counters)
325 {
326 #if MONOTONIC
327 mt_perfcontrol(&cpu_counters->instructions, &cpu_counters->cycles);
328 #else /* MONOTONIC */
329 cpu_counters->instructions = 0;
330 cpu_counters->cycles = 0;
331 #endif /* !MONOTONIC */
332 }
333
334 int perfcontrol_callout_stats_enabled = 0;
335 static _Atomic uint64_t perfcontrol_callout_stats[PERFCONTROL_CALLOUT_MAX][PERFCONTROL_STAT_MAX];
336 static _Atomic uint64_t perfcontrol_callout_count[PERFCONTROL_CALLOUT_MAX];
337
338 #if MONOTONIC
339 static inline
340 bool
perfcontrol_callout_counters_begin(uint64_t * counters)341 perfcontrol_callout_counters_begin(uint64_t *counters)
342 {
343 if (!perfcontrol_callout_stats_enabled) {
344 return false;
345 }
346 mt_fixed_counts(counters);
347 return true;
348 }
349
350 static inline
351 void
perfcontrol_callout_counters_end(uint64_t * start_counters,perfcontrol_callout_type_t type)352 perfcontrol_callout_counters_end(uint64_t *start_counters,
353 perfcontrol_callout_type_t type)
354 {
355 uint64_t end_counters[MT_CORE_NFIXED];
356 mt_fixed_counts(end_counters);
357 os_atomic_add(&perfcontrol_callout_stats[type][PERFCONTROL_STAT_CYCLES],
358 end_counters[MT_CORE_CYCLES] - start_counters[MT_CORE_CYCLES], relaxed);
359 os_atomic_add(&perfcontrol_callout_stats[type][PERFCONTROL_STAT_INSTRS],
360 end_counters[MT_CORE_INSTRS] - start_counters[MT_CORE_INSTRS], relaxed);
361 os_atomic_inc(&perfcontrol_callout_count[type], relaxed);
362 }
363 #endif /* MONOTONIC */
364
365 uint64_t
perfcontrol_callout_stat_avg(perfcontrol_callout_type_t type,perfcontrol_callout_stat_t stat)366 perfcontrol_callout_stat_avg(perfcontrol_callout_type_t type,
367 perfcontrol_callout_stat_t stat)
368 {
369 if (!perfcontrol_callout_stats_enabled) {
370 return 0;
371 }
372 return os_atomic_load_wide(&perfcontrol_callout_stats[type][stat], relaxed) /
373 os_atomic_load_wide(&perfcontrol_callout_count[type], relaxed);
374 }
375
376
377 #if CONFIG_SCHED_EDGE
378
379 /*
380 * The Edge scheduler allows the performance controller to update properties about the
381 * threads as part of the callouts. These properties typically include shared cluster
382 * resource usage. This allows the scheduler to manage specific threads within the
383 * workload more optimally.
384 */
385 static void
sched_perfcontrol_thread_flags_update(thread_t thread,struct perfcontrol_thread_data * thread_data,shared_rsrc_policy_agent_t agent)386 sched_perfcontrol_thread_flags_update(thread_t thread,
387 struct perfcontrol_thread_data *thread_data,
388 shared_rsrc_policy_agent_t agent)
389 {
390 kern_return_t kr = KERN_SUCCESS;
391 if (thread_data->thread_flags_mask & PERFCTL_THREAD_FLAGS_MASK_CLUSTER_SHARED_RSRC_RR) {
392 if (thread_data->thread_flags & PERFCTL_THREAD_FLAGS_MASK_CLUSTER_SHARED_RSRC_RR) {
393 kr = thread_shared_rsrc_policy_set(thread, 0, CLUSTER_SHARED_RSRC_TYPE_RR, agent);
394 } else {
395 kr = thread_shared_rsrc_policy_clear(thread, CLUSTER_SHARED_RSRC_TYPE_RR, agent);
396 }
397 }
398 if (thread_data->thread_flags_mask & PERFCTL_THREAD_FLAGS_MASK_CLUSTER_SHARED_RSRC_NATIVE_FIRST) {
399 if (thread_data->thread_flags & PERFCTL_THREAD_FLAGS_MASK_CLUSTER_SHARED_RSRC_NATIVE_FIRST) {
400 kr = thread_shared_rsrc_policy_set(thread, 0, CLUSTER_SHARED_RSRC_TYPE_NATIVE_FIRST, agent);
401 } else {
402 kr = thread_shared_rsrc_policy_clear(thread, CLUSTER_SHARED_RSRC_TYPE_NATIVE_FIRST, agent);
403 }
404 }
405 /*
406 * The thread_shared_rsrc_policy_* routines only fail if the performance controller is
407 * attempting to double set/clear a policy on the thread.
408 */
409 assert(kr == KERN_SUCCESS);
410 }
411
412 #endif /* CONFIG_SCHED_EDGE */
413
414 void
machine_switch_perfcontrol_context(perfcontrol_event event,uint64_t timestamp,uint32_t flags,uint64_t new_thread_same_pri_latency,thread_t old,thread_t new)415 machine_switch_perfcontrol_context(perfcontrol_event event,
416 uint64_t timestamp,
417 uint32_t flags,
418 uint64_t new_thread_same_pri_latency,
419 thread_t old,
420 thread_t new)
421 {
422
423 if (sched_perfcontrol_switch != sched_perfcontrol_switch_default) {
424 perfcontrol_state_t old_perfcontrol_state = FIND_PERFCONTROL_STATE(old);
425 perfcontrol_state_t new_perfcontrol_state = FIND_PERFCONTROL_STATE(new);
426 sched_perfcontrol_switch(old_perfcontrol_state, new_perfcontrol_state);
427 }
428
429 if (sched_perfcontrol_csw != sched_perfcontrol_csw_default) {
430 uint32_t cpu_id = (uint32_t)cpu_number();
431 struct perfcontrol_cpu_counters cpu_counters;
432 struct perfcontrol_thread_data offcore, oncore;
433 machine_switch_populate_perfcontrol_thread_data(&offcore, old, 0);
434 machine_switch_populate_perfcontrol_thread_data(&oncore, new,
435 new_thread_same_pri_latency);
436 machine_switch_populate_perfcontrol_cpu_counters(&cpu_counters);
437
438 #if MONOTONIC
439 uint64_t counters[MT_CORE_NFIXED];
440 bool ctrs_enabled = perfcontrol_callout_counters_begin(counters);
441 #endif /* MONOTONIC */
442 sched_perfcontrol_csw(event, cpu_id, timestamp, flags,
443 &offcore, &oncore, &cpu_counters, NULL);
444 #if MONOTONIC
445 if (ctrs_enabled) {
446 perfcontrol_callout_counters_end(counters, PERFCONTROL_CALLOUT_CONTEXT);
447 }
448 #endif /* MONOTONIC */
449
450 recount_add_energy(old, get_threadtask(old),
451 offcore.energy_estimate_nj);
452
453 #if CONFIG_SCHED_EDGE
454 if (sched_perfcontrol_thread_shared_rsrc_flags_enabled) {
455 sched_perfcontrol_thread_flags_update(old, &offcore, SHARED_RSRC_POLICY_AGENT_PERFCTL_CSW);
456 }
457 #endif /* CONFIG_SCHED_EDGE */
458 }
459 }
460
461 void
machine_switch_perfcontrol_state_update(perfcontrol_event event,uint64_t timestamp,uint32_t flags,thread_t thread)462 machine_switch_perfcontrol_state_update(perfcontrol_event event,
463 uint64_t timestamp,
464 uint32_t flags,
465 thread_t thread)
466 {
467
468 if (sched_perfcontrol_state_update == sched_perfcontrol_state_update_default) {
469 return;
470 }
471 uint32_t cpu_id = (uint32_t)cpu_number();
472 struct perfcontrol_thread_data data;
473 machine_switch_populate_perfcontrol_thread_data(&data, thread, 0);
474
475 #if MONOTONIC
476 uint64_t counters[MT_CORE_NFIXED];
477 bool ctrs_enabled = perfcontrol_callout_counters_begin(counters);
478 #endif /* MONOTONIC */
479 sched_perfcontrol_state_update(event, cpu_id, timestamp, flags,
480 &data, NULL);
481 #if MONOTONIC
482 if (ctrs_enabled) {
483 perfcontrol_callout_counters_end(counters, PERFCONTROL_CALLOUT_STATE_UPDATE);
484 }
485 #endif /* MONOTONIC */
486
487 #if CONFIG_PERVASIVE_ENERGY
488 recount_add_energy(thread, get_threadtask(thread), data.energy_estimate_nj);
489 #endif /* CONFIG_PERVASIVE_ENERGY */
490
491 #if CONFIG_SCHED_EDGE
492 if (sched_perfcontrol_thread_shared_rsrc_flags_enabled && (event == QUANTUM_EXPIRY)) {
493 sched_perfcontrol_thread_flags_update(thread, &data, SHARED_RSRC_POLICY_AGENT_PERFCTL_QUANTUM);
494 } else {
495 assert(data.thread_flags_mask == 0);
496 }
497 #endif /* CONFIG_SCHED_EDGE */
498 }
499
500 void
machine_thread_going_on_core(thread_t new_thread,thread_urgency_t urgency,uint64_t sched_latency,uint64_t same_pri_latency,uint64_t timestamp)501 machine_thread_going_on_core(thread_t new_thread,
502 thread_urgency_t urgency,
503 uint64_t sched_latency,
504 uint64_t same_pri_latency,
505 uint64_t timestamp)
506 {
507 if (sched_perfcontrol_oncore == sched_perfcontrol_oncore_default) {
508 return;
509 }
510 struct going_on_core on_core;
511 perfcontrol_state_t state = FIND_PERFCONTROL_STATE(new_thread);
512
513 on_core.thread_id = new_thread->thread_id;
514 on_core.energy_estimate_nj = 0;
515 on_core.qos_class = (uint16_t)proc_get_effective_thread_policy(new_thread, TASK_POLICY_QOS);
516 on_core.urgency = (uint16_t)urgency;
517 on_core.is_32_bit = thread_is_64bit_data(new_thread) ? FALSE : TRUE;
518 on_core.is_kernel_thread = get_threadtask(new_thread) == kernel_task;
519 #if CONFIG_THREAD_GROUPS
520 struct thread_group *tg = thread_group_get(new_thread);
521 on_core.thread_group_id = thread_group_get_id(tg);
522 on_core.thread_group_data = thread_group_get_machine_data(tg);
523 #endif
524 on_core.scheduling_latency = sched_latency;
525 on_core.start_time = timestamp;
526 on_core.scheduling_latency_at_same_basepri = same_pri_latency;
527
528 #if MONOTONIC
529 uint64_t counters[MT_CORE_NFIXED];
530 bool ctrs_enabled = perfcontrol_callout_counters_begin(counters);
531 #endif /* MONOTONIC */
532 sched_perfcontrol_oncore(state, &on_core);
533 #if MONOTONIC
534 if (ctrs_enabled) {
535 perfcontrol_callout_counters_end(counters, PERFCONTROL_CALLOUT_ON_CORE);
536 }
537 #endif /* MONOTONIC */
538 }
539
540 void
machine_thread_going_off_core(thread_t old_thread,boolean_t thread_terminating,uint64_t last_dispatch,__unused boolean_t thread_runnable)541 machine_thread_going_off_core(thread_t old_thread, boolean_t thread_terminating,
542 uint64_t last_dispatch, __unused boolean_t thread_runnable)
543 {
544 if (sched_perfcontrol_offcore == sched_perfcontrol_offcore_default) {
545 return;
546 }
547 struct going_off_core off_core;
548 perfcontrol_state_t state = FIND_PERFCONTROL_STATE(old_thread);
549
550 off_core.thread_id = old_thread->thread_id;
551 off_core.energy_estimate_nj = 0;
552 off_core.end_time = last_dispatch;
553 #if CONFIG_THREAD_GROUPS
554 struct thread_group *tg = thread_group_get(old_thread);
555 off_core.thread_group_id = thread_group_get_id(tg);
556 off_core.thread_group_data = thread_group_get_machine_data(tg);
557 #endif
558
559 #if MONOTONIC
560 uint64_t counters[MT_CORE_NFIXED];
561 bool ctrs_enabled = perfcontrol_callout_counters_begin(counters);
562 #endif /* MONOTONIC */
563 sched_perfcontrol_offcore(state, &off_core, thread_terminating);
564 #if MONOTONIC
565 if (ctrs_enabled) {
566 perfcontrol_callout_counters_end(counters, PERFCONTROL_CALLOUT_OFF_CORE);
567 }
568 #endif /* MONOTONIC */
569 }
570
571 #if CONFIG_THREAD_GROUPS
572 void
machine_thread_group_init(struct thread_group * tg)573 machine_thread_group_init(struct thread_group *tg)
574 {
575 if (sched_perfcontrol_thread_group_init == sched_perfcontrol_thread_group_default) {
576 return;
577 }
578 struct thread_group_data data;
579 data.thread_group_id = thread_group_get_id(tg);
580 data.thread_group_data = thread_group_get_machine_data(tg);
581 data.thread_group_size = thread_group_machine_data_size();
582 data.thread_group_flags = thread_group_get_flags(tg);
583 sched_perfcontrol_thread_group_init(&data);
584 }
585
586 void
machine_thread_group_deinit(struct thread_group * tg)587 machine_thread_group_deinit(struct thread_group *tg)
588 {
589 if (sched_perfcontrol_thread_group_deinit == sched_perfcontrol_thread_group_default) {
590 return;
591 }
592 struct thread_group_data data;
593 data.thread_group_id = thread_group_get_id(tg);
594 data.thread_group_data = thread_group_get_machine_data(tg);
595 data.thread_group_size = thread_group_machine_data_size();
596 data.thread_group_flags = thread_group_get_flags(tg);
597 sched_perfcontrol_thread_group_deinit(&data);
598 }
599
600 void
machine_thread_group_flags_update(struct thread_group * tg,uint32_t flags)601 machine_thread_group_flags_update(struct thread_group *tg, uint32_t flags)
602 {
603 if (sched_perfcontrol_thread_group_flags_update == sched_perfcontrol_thread_group_default) {
604 return;
605 }
606 struct thread_group_data data;
607 data.thread_group_id = thread_group_get_id(tg);
608 data.thread_group_data = thread_group_get_machine_data(tg);
609 data.thread_group_size = thread_group_machine_data_size();
610 data.thread_group_flags = flags;
611 sched_perfcontrol_thread_group_flags_update(&data);
612 }
613
614 void
machine_thread_group_blocked(struct thread_group * blocked_tg,struct thread_group * blocking_tg,uint32_t flags,thread_t blocked_thread)615 machine_thread_group_blocked(struct thread_group *blocked_tg,
616 struct thread_group *blocking_tg,
617 uint32_t flags,
618 thread_t blocked_thread)
619 {
620 if (sched_perfcontrol_thread_group_blocked == sched_perfcontrol_thread_group_blocked_default) {
621 return;
622 }
623
624 spl_t s = splsched();
625
626 perfcontrol_state_t state = FIND_PERFCONTROL_STATE(blocked_thread);
627 struct thread_group_data blocked_data;
628 assert(blocked_tg != NULL);
629
630 blocked_data.thread_group_id = thread_group_get_id(blocked_tg);
631 blocked_data.thread_group_data = thread_group_get_machine_data(blocked_tg);
632 blocked_data.thread_group_size = thread_group_machine_data_size();
633
634 if (blocking_tg == NULL) {
635 /*
636 * For special cases such as the render server, the blocking TG is a
637 * well known TG. Only in that case, the blocking_tg should be NULL.
638 */
639 assert(flags & PERFCONTROL_CALLOUT_BLOCKING_TG_RENDER_SERVER);
640 sched_perfcontrol_thread_group_blocked(&blocked_data, NULL, flags, state);
641 } else {
642 struct thread_group_data blocking_data;
643 blocking_data.thread_group_id = thread_group_get_id(blocking_tg);
644 blocking_data.thread_group_data = thread_group_get_machine_data(blocking_tg);
645 blocking_data.thread_group_size = thread_group_machine_data_size();
646 sched_perfcontrol_thread_group_blocked(&blocked_data, &blocking_data, flags, state);
647 }
648 KDBG(MACHDBG_CODE(DBG_MACH_THREAD_GROUP, MACH_THREAD_GROUP_BLOCK) | DBG_FUNC_START,
649 thread_tid(blocked_thread), thread_group_get_id(blocked_tg),
650 blocking_tg ? thread_group_get_id(blocking_tg) : THREAD_GROUP_INVALID,
651 flags);
652
653 splx(s);
654 }
655
656 void
machine_thread_group_unblocked(struct thread_group * unblocked_tg,struct thread_group * unblocking_tg,uint32_t flags,thread_t unblocked_thread)657 machine_thread_group_unblocked(struct thread_group *unblocked_tg,
658 struct thread_group *unblocking_tg,
659 uint32_t flags,
660 thread_t unblocked_thread)
661 {
662 if (sched_perfcontrol_thread_group_unblocked == sched_perfcontrol_thread_group_unblocked_default) {
663 return;
664 }
665
666 spl_t s = splsched();
667
668 perfcontrol_state_t state = FIND_PERFCONTROL_STATE(unblocked_thread);
669 struct thread_group_data unblocked_data;
670 assert(unblocked_tg != NULL);
671
672 unblocked_data.thread_group_id = thread_group_get_id(unblocked_tg);
673 unblocked_data.thread_group_data = thread_group_get_machine_data(unblocked_tg);
674 unblocked_data.thread_group_size = thread_group_machine_data_size();
675
676 if (unblocking_tg == NULL) {
677 /*
678 * For special cases such as the render server, the unblocking TG is a
679 * well known TG. Only in that case, the unblocking_tg should be NULL.
680 */
681 assert(flags & PERFCONTROL_CALLOUT_BLOCKING_TG_RENDER_SERVER);
682 sched_perfcontrol_thread_group_unblocked(&unblocked_data, NULL, flags, state);
683 } else {
684 struct thread_group_data unblocking_data;
685 unblocking_data.thread_group_id = thread_group_get_id(unblocking_tg);
686 unblocking_data.thread_group_data = thread_group_get_machine_data(unblocking_tg);
687 unblocking_data.thread_group_size = thread_group_machine_data_size();
688 sched_perfcontrol_thread_group_unblocked(&unblocked_data, &unblocking_data, flags, state);
689 }
690 KDBG(MACHDBG_CODE(DBG_MACH_THREAD_GROUP, MACH_THREAD_GROUP_BLOCK) | DBG_FUNC_END,
691 thread_tid(unblocked_thread), thread_group_get_id(unblocked_tg),
692 unblocking_tg ? thread_group_get_id(unblocking_tg) : THREAD_GROUP_INVALID,
693 flags);
694
695 splx(s);
696 }
697
698 #endif /* CONFIG_THREAD_GROUPS */
699
700 void
machine_max_runnable_latency(uint64_t bg_max_latency,uint64_t default_max_latency,uint64_t realtime_max_latency)701 machine_max_runnable_latency(uint64_t bg_max_latency,
702 uint64_t default_max_latency,
703 uint64_t realtime_max_latency)
704 {
705 if (sched_perfcontrol_max_runnable_latency == sched_perfcontrol_max_runnable_latency_default) {
706 return;
707 }
708 struct perfcontrol_max_runnable_latency latencies = {
709 .max_scheduling_latencies = {
710 [THREAD_URGENCY_NONE] = 0,
711 [THREAD_URGENCY_BACKGROUND] = bg_max_latency,
712 [THREAD_URGENCY_NORMAL] = default_max_latency,
713 [THREAD_URGENCY_REAL_TIME] = realtime_max_latency
714 }
715 };
716
717 sched_perfcontrol_max_runnable_latency(&latencies);
718 }
719
720 void
machine_work_interval_notify(thread_t thread,struct kern_work_interval_args * kwi_args)721 machine_work_interval_notify(thread_t thread,
722 struct kern_work_interval_args* kwi_args)
723 {
724 if (sched_perfcontrol_work_interval_notify == sched_perfcontrol_work_interval_notify_default) {
725 return;
726 }
727 perfcontrol_state_t state = FIND_PERFCONTROL_STATE(thread);
728 struct perfcontrol_work_interval work_interval = {
729 .thread_id = thread->thread_id,
730 .qos_class = (uint16_t)proc_get_effective_thread_policy(thread, TASK_POLICY_QOS),
731 .urgency = kwi_args->urgency,
732 .flags = kwi_args->notify_flags,
733 .work_interval_id = kwi_args->work_interval_id,
734 .start = kwi_args->start,
735 .finish = kwi_args->finish,
736 .deadline = kwi_args->deadline,
737 .next_start = kwi_args->next_start,
738 .create_flags = kwi_args->create_flags,
739 };
740 #if CONFIG_THREAD_GROUPS
741 struct thread_group *tg;
742 tg = thread_group_get(thread);
743 work_interval.thread_group_id = thread_group_get_id(tg);
744 work_interval.thread_group_data = thread_group_get_machine_data(tg);
745 #endif
746 sched_perfcontrol_work_interval_notify(state, &work_interval);
747 }
748
749
750 void
machine_perfcontrol_deadline_passed(uint64_t deadline)751 machine_perfcontrol_deadline_passed(uint64_t deadline)
752 {
753 if (sched_perfcontrol_deadline_passed != sched_perfcontrol_deadline_passed_default) {
754 sched_perfcontrol_deadline_passed(deadline);
755 }
756 }
757
758 #if SCHED_HYGIENE_DEBUG
759
760 __options_decl(int_mask_hygiene_flags_t, uint8_t, {
761 INT_MASK_BASE = 0x00,
762 INT_MASK_FROM_HANDLER = 0x01,
763 INT_MASK_IS_STACKSHOT = 0x02,
764 });
765
766 /*
767 * ml_spin_debug_reset()
768 * Reset the timestamp on a thread that has been unscheduled
769 * to avoid false alarms. Alarm will go off if interrupts are held
770 * disabled for too long, starting from now.
771 *
772 * Call ml_get_timebase() directly to prevent extra overhead on newer
773 * platforms that's enabled in DEVELOPMENT kernel configurations.
774 */
775 void
ml_spin_debug_reset(thread_t thread)776 ml_spin_debug_reset(thread_t thread)
777 {
778 if (thread->machine.intmask_timestamp) {
779 thread->machine.intmask_timestamp = ml_get_sched_hygiene_timebase();
780 INTERRUPT_MASKED_DEBUG_CAPTURE_PMC(thread);
781 }
782 }
783
784 /*
785 * ml_spin_debug_clear()
786 * Clear the timestamp and cycle/instruction counts on a thread that
787 * has been unscheduled to avoid false alarms
788 */
789 void
ml_spin_debug_clear(thread_t thread)790 ml_spin_debug_clear(thread_t thread)
791 {
792 thread->machine.intmask_timestamp = 0;
793 thread->machine.intmask_cycles = 0;
794 thread->machine.intmask_instr = 0;
795 }
796
797 /*
798 * ml_spin_debug_clear_self()
799 * Clear the timestamp on the current thread to prevent
800 * false alarms
801 */
802 void
ml_spin_debug_clear_self(void)803 ml_spin_debug_clear_self(void)
804 {
805 ml_spin_debug_clear(current_thread());
806 }
807
808 #ifndef KASAN
809
810 /*
811 * Get a character representing the provided thread's kind of CPU.
812 */
813 #if !MONOTONIC
814 __unused
815 #endif // !MONOTONIC
816 static char
__ml_interrupts_disabled_cpu_kind(thread_t thread)817 __ml_interrupts_disabled_cpu_kind(thread_t thread)
818 {
819 #if __AMP__
820 processor_t processor = thread->last_processor;
821 if (!processor) {
822 return '!';
823 }
824
825 switch (processor->processor_set->pset_cluster_type) {
826 case PSET_AMP_P:
827 return 'P';
828 case PSET_AMP_E:
829 return 'E';
830 default:
831 return '?';
832 }
833 #else // __AMP__
834 #pragma unused(thread)
835 return '-';
836 #endif // !__AMP__
837 }
838
839 #define EXTRA_INFO_STRING_SIZE 256
840 #define LOW_FREQ_THRESHOLD_MHZ 500
841 #define HIGH_CPI_THRESHOLD 3
842
843 static void
__ml_trigger_interrupts_disabled_handle(thread_t thread,uint64_t start,uint64_t now,uint64_t timeout,int_mask_hygiene_flags_t flags)844 __ml_trigger_interrupts_disabled_handle(thread_t thread, uint64_t start, uint64_t now, uint64_t timeout, int_mask_hygiene_flags_t flags)
845 {
846 mach_timebase_info_data_t timebase;
847 clock_timebase_info(&timebase);
848 bool is_int_handler = flags & INT_MASK_FROM_HANDLER;
849 bool is_stackshot = flags & INT_MASK_IS_STACKSHOT;
850
851 const uint64_t time_elapsed = now - start;
852 const uint64_t time_elapsed_ns = (time_elapsed * timebase.numer) / timebase.denom;
853
854 uint64_t current_cycles = 0, current_instrs = 0;
855
856 #if MONOTONIC
857 if (sched_hygiene_debug_pmc) {
858 mt_cur_cpu_cycles_instrs_speculative(¤t_cycles, ¤t_instrs);
859 }
860 #endif // MONOTONIC
861
862 const uint64_t cycles_elapsed = current_cycles - thread->machine.intmask_cycles;
863 const uint64_t instrs_elapsed = current_instrs - thread->machine.intmask_instr;
864
865 if (interrupt_masked_debug_mode == SCHED_HYGIENE_MODE_PANIC) {
866 const uint64_t timeout_ns = ((timeout * debug_cpu_performance_degradation_factor) * timebase.numer) / timebase.denom;
867 char extra_info_string[EXTRA_INFO_STRING_SIZE] = { '\0' };
868 #if MONOTONIC
869 if (sched_hygiene_debug_pmc) {
870 const uint64_t time_elapsed_us = time_elapsed_ns / 1000;
871 const uint64_t average_freq_mhz = cycles_elapsed / time_elapsed_us;
872 const uint64_t average_cpi_whole = cycles_elapsed / instrs_elapsed;
873 const uint64_t average_cpi_fractional = ((cycles_elapsed * 100) / instrs_elapsed) % 100;
874 bool high_cpi = average_cpi_whole >= HIGH_CPI_THRESHOLD;
875 char core_kind = __ml_interrupts_disabled_cpu_kind(thread);
876 bool low_mhz = average_freq_mhz < LOW_FREQ_THRESHOLD_MHZ;
877
878 snprintf(extra_info_string, EXTRA_INFO_STRING_SIZE,
879 ", %sfreq = %llu MHz, %sCPI = %llu.%llu, CPU kind = %c",
880 low_mhz ? "low " : "",
881 average_freq_mhz,
882 high_cpi ? "high " : "",
883 average_cpi_whole,
884 average_cpi_fractional,
885 core_kind);
886 }
887 #endif // MONOTONIC
888
889 if (is_int_handler) {
890 panic("Processing of an interrupt (type = %u, handler address = %p, vector = %p) "
891 "took %llu nanoseconds (start = %llu, now = %llu, timeout = %llu ns%s)",
892 thread->machine.int_type, (void *)thread->machine.int_handler_addr, (void *)thread->machine.int_vector,
893 time_elapsed_ns, start, now, timeout_ns, extra_info_string);
894 } else {
895 panic("%s for %llu nanoseconds (start = %llu, now = %llu, timeout = %llu ns%s)",
896 is_stackshot ? "Stackshot disabled interrupts" : "Interrupts held disabled",
897 time_elapsed_ns, start, now, timeout_ns, extra_info_string);
898 }
899 } else if (interrupt_masked_debug_mode == SCHED_HYGIENE_MODE_TRACE) {
900 if (is_int_handler) {
901 static const uint32_t interrupt_handled_dbgid =
902 MACHDBG_CODE(DBG_MACH_SCHED, MACH_INT_HANDLED_EXPIRED);
903 DTRACE_SCHED3(interrupt_handled_dbgid, uint64_t, time_elapsed,
904 uint64_t, cycles_elapsed, uint64_t, instrs_elapsed);
905 KDBG(interrupt_handled_dbgid, time_elapsed,
906 cycles_elapsed, instrs_elapsed);
907 } else {
908 static const uint32_t interrupt_masked_dbgid =
909 MACHDBG_CODE(DBG_MACH_SCHED, MACH_INT_MASKED_EXPIRED);
910 DTRACE_SCHED3(interrupt_masked_dbgid, uint64_t, time_elapsed,
911 uint64_t, cycles_elapsed, uint64_t, instrs_elapsed);
912 KDBG(interrupt_masked_dbgid, time_elapsed,
913 cycles_elapsed, instrs_elapsed);
914 }
915 }
916 }
917 #endif // !defined(KASAN)
918
919 static inline void
__ml_handle_interrupts_disabled_duration(thread_t thread,uint64_t timeout,bool is_int_handler)920 __ml_handle_interrupts_disabled_duration(thread_t thread, uint64_t timeout, bool is_int_handler)
921 {
922 if (timeout == 0) {
923 return; // 0 means timeout disabled.
924 }
925 uint64_t start = is_int_handler ? thread->machine.inthandler_timestamp : thread->machine.intmask_timestamp;
926 if (start != 0) {
927 uint64_t now = ml_get_sched_hygiene_timebase();
928
929 if (interrupt_masked_debug_mode &&
930 ((now - start) > timeout * debug_cpu_performance_degradation_factor) &&
931 !thread->machine.inthandler_abandon) {
932 /*
933 * Disable the actual panic for KASAN due to the overhead of KASAN itself, leave the rest of the
934 * mechanism enabled so that KASAN can catch any bugs in the mechanism itself.
935 */
936 #ifndef KASAN
937 __ml_trigger_interrupts_disabled_handle(thread, start, now, timeout, is_int_handler);
938 #endif
939 }
940
941 if (is_int_handler) {
942 uint64_t const duration = now - start;
943 #if SCHED_HYGIENE_DEBUG
944 ml_adjust_preemption_disable_time(thread, duration);
945 #endif /* SCHED_HYGIENE_DEBUG */
946 /*
947 * No need for an atomic add, the only thread modifying
948 * this is ourselves. Other threads querying will just see
949 * either the old or the new value. (This will also just
950 * resolve to regular loads and stores on relevant
951 * platforms.)
952 */
953 uint64_t const old_duration = os_atomic_load_wide(&thread->machine.int_time_mt, relaxed);
954 os_atomic_store_wide(&thread->machine.int_time_mt, old_duration + duration, relaxed);
955 }
956 }
957 }
958
959 void
ml_handle_interrupts_disabled_duration(thread_t thread)960 ml_handle_interrupts_disabled_duration(thread_t thread)
961 {
962 __ml_handle_interrupts_disabled_duration(thread, os_atomic_load(&interrupt_masked_timeout, relaxed), INT_MASK_BASE);
963 }
964
965 void
ml_handle_stackshot_interrupt_disabled_duration(thread_t thread)966 ml_handle_stackshot_interrupt_disabled_duration(thread_t thread)
967 {
968 /* Use MAX() to let the user bump the timeout further if needed */
969 uint64_t stackshot_timeout = os_atomic_load(&stackshot_interrupt_masked_timeout, relaxed);
970 uint64_t normal_timeout = os_atomic_load(&interrupt_masked_timeout, relaxed);
971 uint64_t timeout = MAX(stackshot_timeout, normal_timeout);
972 __ml_handle_interrupts_disabled_duration(thread, timeout, INT_MASK_IS_STACKSHOT);
973 }
974
975 void
ml_handle_interrupt_handler_duration(thread_t thread)976 ml_handle_interrupt_handler_duration(thread_t thread)
977 {
978 __ml_handle_interrupts_disabled_duration(thread, os_atomic_load(&interrupt_masked_timeout, relaxed), INT_MASK_FROM_HANDLER);
979 }
980
981 #if SCHED_HYGIENE_DEBUG
982 void
ml_adjust_preemption_disable_time(thread_t thread,int64_t duration)983 ml_adjust_preemption_disable_time(thread_t thread, int64_t duration)
984 {
985 /* We don't want to count interrupt handler duration in preemption disable time. */
986 if (thread->machine.preemption_disable_mt != 0) {
987 /* We don't care *when* preemption was disabled, just for how
988 * long. So to exclude interrupt handling intervals, we
989 * adjust the start time forward. */
990 thread->machine.preemption_disable_adjust += duration;
991 }
992 }
993 #endif /* SCHED_HYGIENE_DEBUG */
994
995 void
ml_irq_debug_start(uintptr_t handler,uintptr_t vector)996 ml_irq_debug_start(uintptr_t handler, uintptr_t vector)
997 {
998 INTERRUPT_MASKED_DEBUG_START(handler, DBG_INTR_TYPE_OTHER);
999 current_thread()->machine.int_vector = (uintptr_t)VM_KERNEL_STRIP_PTR(vector);
1000 }
1001
1002 void
ml_irq_debug_end()1003 ml_irq_debug_end()
1004 {
1005 INTERRUPT_MASKED_DEBUG_END();
1006 }
1007
1008 /*
1009 * Abandon a potential timeout when handling an interrupt. It is important to
1010 * continue to keep track of the interrupt time so the time-stamp can't be
1011 * reset. (Interrupt time is subtracted from preemption time to maintain
1012 * accurate preemption time measurement).
1013 * When `inthandler_abandon` is true, a timeout will be ignored when the
1014 * interrupt handler finishes.
1015 */
1016 void
ml_irq_debug_abandon(void)1017 ml_irq_debug_abandon(void)
1018 {
1019 assert(!ml_get_interrupts_enabled());
1020
1021 thread_t t = current_thread();
1022 if (t->machine.inthandler_timestamp != 0) {
1023 t->machine.inthandler_abandon = true;
1024 }
1025 }
1026 #endif // SCHED_HYGIENE_DEBUG
1027
1028 #if SCHED_HYGIENE_DEBUG
1029 __attribute__((noinline))
1030 static void
ml_interrupt_masked_debug_timestamp(thread_t thread)1031 ml_interrupt_masked_debug_timestamp(thread_t thread)
1032 {
1033 thread->machine.intmask_timestamp = ml_get_sched_hygiene_timebase();
1034 INTERRUPT_MASKED_DEBUG_CAPTURE_PMC(thread);
1035 }
1036 #endif
1037
1038 boolean_t
ml_set_interrupts_enabled_with_debug(boolean_t enable,boolean_t __unused debug)1039 ml_set_interrupts_enabled_with_debug(boolean_t enable, boolean_t __unused debug)
1040 {
1041 thread_t thread;
1042 uint64_t state;
1043
1044 thread = current_thread();
1045
1046 state = __builtin_arm_rsr("DAIF");
1047
1048 if (enable && (state & DAIF_IRQF)) {
1049 assert(getCpuDatap()->cpu_int_state == NULL); // Make sure we're not enabling interrupts from primary interrupt context
1050 #if SCHED_HYGIENE_DEBUG
1051 if (__probable(debug && (interrupt_masked_debug_mode || sched_preemption_disable_debug_mode))) {
1052 // Interrupts are currently masked, we will enable them (after finishing this check)
1053 if (stackshot_active()) {
1054 ml_handle_stackshot_interrupt_disabled_duration(thread);
1055 } else {
1056 ml_handle_interrupts_disabled_duration(thread);
1057 }
1058 thread->machine.intmask_timestamp = 0;
1059 thread->machine.intmask_cycles = 0;
1060 thread->machine.intmask_instr = 0;
1061 }
1062 #endif // SCHED_HYGIENE_DEBUG
1063 if (get_preemption_level() == 0) {
1064 while (thread->machine.CpuDatap->cpu_pending_ast & AST_URGENT) {
1065 #if __ARM_USER_PROTECT__
1066 uintptr_t up = arm_user_protect_begin(thread);
1067 #endif
1068 ast_taken_kernel();
1069 #if __ARM_USER_PROTECT__
1070 arm_user_protect_end(thread, up, FALSE);
1071 #endif
1072 }
1073 }
1074 __builtin_arm_wsr("DAIFClr", DAIFSC_STANDARD_DISABLE);
1075 } else if (!enable && ((state & DAIF_IRQF) == 0)) {
1076 __builtin_arm_wsr("DAIFSet", DAIFSC_STANDARD_DISABLE);
1077
1078 #if SCHED_HYGIENE_DEBUG
1079 if (__probable(debug && (interrupt_masked_debug_mode || sched_preemption_disable_debug_mode))) {
1080 // Interrupts were enabled, we just masked them
1081 ml_interrupt_masked_debug_timestamp(thread);
1082 }
1083 #endif
1084 }
1085 return (state & DAIF_IRQF) == 0;
1086 }
1087
1088 boolean_t
ml_set_interrupts_enabled(boolean_t enable)1089 ml_set_interrupts_enabled(boolean_t enable)
1090 {
1091 return ml_set_interrupts_enabled_with_debug(enable, true);
1092 }
1093
1094 boolean_t
ml_early_set_interrupts_enabled(boolean_t enable)1095 ml_early_set_interrupts_enabled(boolean_t enable)
1096 {
1097 return ml_set_interrupts_enabled(enable);
1098 }
1099
1100 /*
1101 * Routine: ml_at_interrupt_context
1102 * Function: Check if running at interrupt context
1103 */
1104 boolean_t
ml_at_interrupt_context(void)1105 ml_at_interrupt_context(void)
1106 {
1107 /* Do not use a stack-based check here, as the top-level exception handler
1108 * is free to use some other stack besides the per-CPU interrupt stack.
1109 * Interrupts should always be disabled if we're at interrupt context.
1110 * Check that first, as we may be in a preemptible non-interrupt context, in
1111 * which case we could be migrated to a different CPU between obtaining
1112 * the per-cpu data pointer and loading cpu_int_state. We then might end
1113 * up checking the interrupt state of a different CPU, resulting in a false
1114 * positive. But if interrupts are disabled, we also know we cannot be
1115 * preempted. */
1116 return !ml_get_interrupts_enabled() && (getCpuDatap()->cpu_int_state != NULL);
1117 }
1118
1119 vm_offset_t
ml_stack_remaining(void)1120 ml_stack_remaining(void)
1121 {
1122 uintptr_t local = (uintptr_t) &local;
1123 vm_offset_t intstack_top_ptr;
1124
1125 /* Since this is a stack-based check, we don't need to worry about
1126 * preemption as we do in ml_at_interrupt_context(). If we are preemptible,
1127 * then the sp should never be within any CPU's interrupt stack unless
1128 * something has gone horribly wrong. */
1129 intstack_top_ptr = getCpuDatap()->intstack_top;
1130 if ((local < intstack_top_ptr) && (local > intstack_top_ptr - INTSTACK_SIZE)) {
1131 return local - (getCpuDatap()->intstack_top - INTSTACK_SIZE);
1132 } else {
1133 return local - current_thread()->kernel_stack;
1134 }
1135 }
1136
1137 static boolean_t ml_quiescing = FALSE;
1138
1139 void
ml_set_is_quiescing(boolean_t quiescing)1140 ml_set_is_quiescing(boolean_t quiescing)
1141 {
1142 ml_quiescing = quiescing;
1143 os_atomic_thread_fence(release);
1144 }
1145
1146 boolean_t
ml_is_quiescing(void)1147 ml_is_quiescing(void)
1148 {
1149 os_atomic_thread_fence(acquire);
1150 return ml_quiescing;
1151 }
1152
1153 uint64_t
ml_get_booter_memory_size(void)1154 ml_get_booter_memory_size(void)
1155 {
1156 uint64_t size;
1157 uint64_t roundsize = 512 * 1024 * 1024ULL;
1158 size = BootArgs->memSizeActual;
1159 if (!size) {
1160 size = BootArgs->memSize;
1161 if (size < (2 * roundsize)) {
1162 roundsize >>= 1;
1163 }
1164 size = (size + roundsize - 1) & ~(roundsize - 1);
1165 }
1166
1167 size -= BootArgs->memSize;
1168
1169 return size;
1170 }
1171
1172 uint64_t
ml_get_abstime_offset(void)1173 ml_get_abstime_offset(void)
1174 {
1175 return rtclock_base_abstime;
1176 }
1177
1178 uint64_t
ml_get_conttime_offset(void)1179 ml_get_conttime_offset(void)
1180 {
1181 #if HIBERNATION && HAS_CONTINUOUS_HWCLOCK
1182 return hwclock_conttime_offset;
1183 #elif HAS_CONTINUOUS_HWCLOCK
1184 return 0;
1185 #else
1186 return rtclock_base_abstime + mach_absolutetime_asleep;
1187 #endif
1188 }
1189
1190 uint64_t
ml_get_time_since_reset(void)1191 ml_get_time_since_reset(void)
1192 {
1193 #if HAS_CONTINUOUS_HWCLOCK
1194 if (wake_conttime == UINT64_MAX) {
1195 return UINT64_MAX;
1196 } else {
1197 return mach_continuous_time() - wake_conttime;
1198 }
1199 #else
1200 /* The timebase resets across S2R, so just return the raw value. */
1201 return ml_get_hwclock();
1202 #endif
1203 }
1204
1205 void
ml_set_reset_time(__unused uint64_t wake_time)1206 ml_set_reset_time(__unused uint64_t wake_time)
1207 {
1208 #if HAS_CONTINUOUS_HWCLOCK
1209 wake_conttime = wake_time;
1210 #endif
1211 }
1212
1213 uint64_t
ml_get_conttime_wake_time(void)1214 ml_get_conttime_wake_time(void)
1215 {
1216 #if HAS_CONTINUOUS_HWCLOCK
1217 /*
1218 * For now, we will reconstitute the timebase value from
1219 * cpu_timebase_init and use it as the wake time.
1220 */
1221 return wake_abstime - ml_get_abstime_offset();
1222 #else /* HAS_CONTINOUS_HWCLOCK */
1223 /* The wake time is simply our continuous time offset. */
1224 return ml_get_conttime_offset();
1225 #endif /* HAS_CONTINOUS_HWCLOCK */
1226 }
1227
1228 /*
1229 * ml_snoop_thread_is_on_core(thread_t thread)
1230 * Check if the given thread is currently on core. This function does not take
1231 * locks, disable preemption, or otherwise guarantee synchronization. The
1232 * result should be considered advisory.
1233 */
1234 bool
ml_snoop_thread_is_on_core(thread_t thread)1235 ml_snoop_thread_is_on_core(thread_t thread)
1236 {
1237 unsigned int cur_cpu_num = 0;
1238 const unsigned int max_cpu_id = ml_get_max_cpu_number();
1239
1240 for (cur_cpu_num = 0; cur_cpu_num <= max_cpu_id; cur_cpu_num++) {
1241 if (CpuDataEntries[cur_cpu_num].cpu_data_vaddr) {
1242 if (CpuDataEntries[cur_cpu_num].cpu_data_vaddr->cpu_active_thread == thread) {
1243 return true;
1244 }
1245 }
1246 }
1247
1248 return false;
1249 }
1250
1251 int
ml_early_cpu_max_number(void)1252 ml_early_cpu_max_number(void)
1253 {
1254 assert(startup_phase >= STARTUP_SUB_TUNABLES);
1255 return ml_get_max_cpu_number();
1256 }
1257
1258 void
ml_set_max_cpus(unsigned int max_cpus __unused)1259 ml_set_max_cpus(unsigned int max_cpus __unused)
1260 {
1261 lck_mtx_lock(&max_cpus_lock);
1262 if (max_cpus_initialized != MAX_CPUS_SET) {
1263 if (max_cpus_initialized == MAX_CPUS_WAIT) {
1264 thread_wakeup((event_t) &max_cpus_initialized);
1265 }
1266 max_cpus_initialized = MAX_CPUS_SET;
1267 }
1268 lck_mtx_unlock(&max_cpus_lock);
1269 }
1270
1271 unsigned int
ml_wait_max_cpus(void)1272 ml_wait_max_cpus(void)
1273 {
1274 assert(lockdown_done);
1275 lck_mtx_lock(&max_cpus_lock);
1276 while (max_cpus_initialized != MAX_CPUS_SET) {
1277 max_cpus_initialized = MAX_CPUS_WAIT;
1278 lck_mtx_sleep(&max_cpus_lock, LCK_SLEEP_DEFAULT, &max_cpus_initialized, THREAD_UNINT);
1279 }
1280 lck_mtx_unlock(&max_cpus_lock);
1281 return machine_info.max_cpus;
1282 }
1283
1284 void
ml_cpu_get_info_type(ml_cpu_info_t * ml_cpu_info,cluster_type_t cluster_type)1285 ml_cpu_get_info_type(ml_cpu_info_t * ml_cpu_info, cluster_type_t cluster_type)
1286 {
1287 cache_info_t *cpuid_cache_info;
1288
1289 cpuid_cache_info = cache_info_type(cluster_type);
1290 ml_cpu_info->vector_unit = 0;
1291 ml_cpu_info->cache_line_size = cpuid_cache_info->c_linesz;
1292 ml_cpu_info->l1_icache_size = cpuid_cache_info->c_isize;
1293 ml_cpu_info->l1_dcache_size = cpuid_cache_info->c_dsize;
1294
1295 #if (__ARM_ARCH__ >= 8)
1296 ml_cpu_info->l2_settings = 1;
1297 ml_cpu_info->l2_cache_size = cpuid_cache_info->c_l2size;
1298 #else
1299 #error Unsupported arch
1300 #endif
1301 ml_cpu_info->l3_settings = 0;
1302 ml_cpu_info->l3_cache_size = 0xFFFFFFFF;
1303 }
1304
1305 /*
1306 * Routine: ml_cpu_get_info
1307 * Function: Fill out the ml_cpu_info_t structure with parameters associated
1308 * with the boot cluster.
1309 */
1310 void
ml_cpu_get_info(ml_cpu_info_t * ml_cpu_info)1311 ml_cpu_get_info(ml_cpu_info_t * ml_cpu_info)
1312 {
1313 ml_cpu_get_info_type(ml_cpu_info, ml_get_topology_info()->boot_cpu->cluster_type);
1314 }
1315
1316 unsigned int
ml_get_cpu_number_type(cluster_type_t cluster_type,bool logical,bool available)1317 ml_get_cpu_number_type(cluster_type_t cluster_type, bool logical, bool available)
1318 {
1319 /*
1320 * At present no supported ARM system features SMT, so the "logical"
1321 * parameter doesn't have an impact on the result.
1322 */
1323 if (logical && available) {
1324 return os_atomic_load(&cluster_type_num_active_cpus[cluster_type], relaxed);
1325 } else if (logical && !available) {
1326 return ml_get_topology_info()->cluster_type_num_cpus[cluster_type];
1327 } else if (!logical && available) {
1328 return os_atomic_load(&cluster_type_num_active_cpus[cluster_type], relaxed);
1329 } else {
1330 return ml_get_topology_info()->cluster_type_num_cpus[cluster_type];
1331 }
1332 }
1333
1334 void
ml_get_cluster_type_name(cluster_type_t cluster_type,char * name,size_t name_size)1335 ml_get_cluster_type_name(cluster_type_t cluster_type, char *name, size_t name_size)
1336 {
1337 strlcpy(name, cluster_type_names[cluster_type], name_size);
1338 }
1339
1340 unsigned int
ml_get_cluster_number_type(cluster_type_t cluster_type)1341 ml_get_cluster_number_type(cluster_type_t cluster_type)
1342 {
1343 return ml_get_topology_info()->cluster_type_num_clusters[cluster_type];
1344 }
1345
1346 unsigned int
ml_cpu_cache_sharing(unsigned int level,cluster_type_t cluster_type,bool include_all_cpu_types __unused)1347 ml_cpu_cache_sharing(unsigned int level, cluster_type_t cluster_type, bool include_all_cpu_types __unused)
1348 {
1349 unsigned int cpu_number = 0, cluster_types = 0;
1350
1351 /*
1352 * Level 0 corresponds to main memory, which is shared across all cores.
1353 */
1354 if (level == 0) {
1355 return ml_get_topology_info()->num_cpus;
1356 }
1357
1358 /*
1359 * At present no supported ARM system features more than 2 levels of caches.
1360 */
1361 if (level > 2) {
1362 return 0;
1363 }
1364
1365 /*
1366 * L1 caches are always per core.
1367 */
1368 if (level == 1) {
1369 return 1;
1370 }
1371
1372 cluster_types = (1 << cluster_type);
1373
1374 /*
1375 * Traverse clusters until we find the one(s) of the desired type(s).
1376 */
1377 for (int i = 0; i < ml_get_topology_info()->num_clusters; i++) {
1378 ml_topology_cluster_t *cluster = &ml_get_topology_info()->clusters[i];
1379 if ((1 << cluster->cluster_type) & cluster_types) {
1380 cpu_number += cluster->num_cpus;
1381 cluster_types &= ~(1 << cluster->cluster_type);
1382 if (!cluster_types) {
1383 break;
1384 }
1385 }
1386 }
1387
1388 return cpu_number;
1389 }
1390
1391 unsigned int
ml_get_cpu_types(void)1392 ml_get_cpu_types(void)
1393 {
1394 return ml_get_topology_info()->cluster_types;
1395 }
1396
1397 void
machine_conf(void)1398 machine_conf(void)
1399 {
1400 /*
1401 * This is known to be inaccurate. mem_size should always be capped at 2 GB
1402 */
1403 machine_info.memory_size = (uint32_t)mem_size;
1404
1405 // rdar://problem/58285685: Userland expects _COMM_PAGE_LOGICAL_CPUS to report
1406 // (max_cpu_id+1) rather than a literal *count* of logical CPUs.
1407 unsigned int num_cpus = ml_get_topology_info()->max_cpu_id + 1;
1408 machine_info.max_cpus = num_cpus;
1409 machine_info.physical_cpu_max = num_cpus;
1410 machine_info.logical_cpu_max = num_cpus;
1411 }
1412
1413 void
machine_init(void)1414 machine_init(void)
1415 {
1416 debug_log_init();
1417 clock_config();
1418 is_clock_configured = TRUE;
1419 if (debug_enabled) {
1420 pmap_map_globals();
1421 }
1422 ml_lockdown_init();
1423 }
1424