xref: /xnu-8019.80.24/osfmk/arm64/machine_routines.c (revision a325d9c4a84054e40bbe985afedcb50ab80993ea)
1 /*
2  * Copyright (c) 2007-2017 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 <arm64/machine_machdep.h>
30 #include <arm64/proc_reg.h>
31 #include <arm/machine_cpu.h>
32 #include <arm/cpu_internal.h>
33 #include <arm/cpuid.h>
34 #include <arm/io_map_entries.h>
35 #include <arm/cpu_data.h>
36 #include <arm/cpu_data_internal.h>
37 #include <arm/caches_internal.h>
38 #include <arm/misc_protos.h>
39 #include <arm/machdep_call.h>
40 #include <arm/machine_routines.h>
41 #include <arm/rtclock.h>
42 #include <arm/cpuid_internal.h>
43 #include <arm/cpu_capabilities.h>
44 #include <console/serial_protos.h>
45 #include <kern/machine.h>
46 #include <kern/misc_protos.h>
47 #include <prng/random.h>
48 #include <kern/startup.h>
49 #include <kern/thread.h>
50 #include <kern/timer_queue.h>
51 #include <mach/machine.h>
52 #include <machine/atomic.h>
53 #include <machine/config.h>
54 #include <vm/pmap.h>
55 #include <vm/vm_page.h>
56 #include <vm/vm_shared_region.h>
57 #include <vm/vm_map.h>
58 #include <sys/codesign.h>
59 #include <sys/kdebug.h>
60 #include <kern/coalition.h>
61 #include <pexpert/device_tree.h>
62 
63 #include <IOKit/IOPlatformExpert.h>
64 #if HIBERNATION
65 #include <IOKit/IOHibernatePrivate.h>
66 #endif /* HIBERNATION */
67 
68 #if defined(KERNEL_INTEGRITY_KTRR) || defined(KERNEL_INTEGRITY_CTRR)
69 #include <arm64/amcc_rorgn.h>
70 #endif
71 
72 
73 #include <libkern/section_keywords.h>
74 
75 /**
76  * On supported hardware, debuggable builds make the HID bits read-only
77  * without locking them.  This lets people manually modify HID bits while
78  * debugging, since they can use a debugging tool to first reset the HID
79  * bits back to read/write.  However it will still catch xnu changes that
80  * accidentally write to HID bits after they've been made read-only.
81  */
82 
83 #if KPC
84 #include <kern/kpc.h>
85 #endif
86 
87 #define MPIDR_CPU_ID(mpidr_el1_val)             (((mpidr_el1_val) & MPIDR_AFF0_MASK) >> MPIDR_AFF0_SHIFT)
88 #define MPIDR_CLUSTER_ID(mpidr_el1_val)         (((mpidr_el1_val) & MPIDR_AFF1_MASK) >> MPIDR_AFF1_SHIFT)
89 
90 #if HAS_CLUSTER
91 static uint8_t cluster_initialized = 0;
92 #endif
93 
94 MACHINE_TIMEOUT32_WRITEABLE(LockTimeOut, "lock", 6e6 /* 0.25s */, MACHINE_TIMEOUT_UNIT_TIMEBASE, NULL);
95 machine_timeout32_t LockTimeOutUsec; // computed in ml_init_lock_timeout
96 
97 MACHINE_TIMEOUT_WRITEABLE(TLockTimeOut, "ticket-lock", 3e6 /* 0.125s */, MACHINE_TIMEOUT_UNIT_TIMEBASE, NULL);
98 
99 MACHINE_TIMEOUT32_WRITEABLE(MutexSpin, "mutex-spin", 240 /* 10us */, MACHINE_TIMEOUT_UNIT_TIMEBASE, NULL);
100 
101 uint64_t low_MutexSpin;
102 int64_t high_MutexSpin;
103 
104 
105 
106 static uint64_t ml_wfe_hint_max_interval;
107 #define MAX_WFE_HINT_INTERVAL_US (500ULL)
108 
109 /* Must be less than cpu_idle_latency to ensure ml_delay_should_spin is true */
110 TUNABLE(uint32_t, yield_delay_us, "yield_delay_us", 0);
111 
112 extern vm_offset_t   segLOWEST;
113 extern vm_offset_t   segLOWESTTEXT;
114 extern vm_offset_t   segLASTB;
115 extern unsigned long segSizeLAST;
116 
117 /* ARM64 specific bounds; used to test for presence in the kernelcache. */
118 extern vm_offset_t   vm_kernelcache_base;
119 extern vm_offset_t   vm_kernelcache_top;
120 
121 #if defined(HAS_IPI)
122 unsigned int gFastIPI = 1;
123 #define kDeferredIPITimerDefault (64 * NSEC_PER_USEC) /* in nanoseconds */
124 static TUNABLE_WRITEABLE(uint64_t, deferred_ipi_timer_ns, "fastipitimeout",
125     kDeferredIPITimerDefault);
126 #endif /* defined(HAS_IPI) */
127 
128 thread_t Idle_context(void);
129 
130 SECURITY_READ_ONLY_LATE(bool) cpu_config_correct = true;
131 
132 SECURITY_READ_ONLY_LATE(static ml_topology_cpu_t) topology_cpu_array[MAX_CPUS];
133 SECURITY_READ_ONLY_LATE(static ml_topology_cluster_t) topology_cluster_array[MAX_CPU_CLUSTERS];
134 SECURITY_READ_ONLY_LATE(static ml_topology_info_t) topology_info = {
135 	.version = CPU_TOPOLOGY_VERSION,
136 	.cpus = topology_cpu_array,
137 	.clusters = topology_cluster_array,
138 };
139 
140 _Atomic unsigned int cluster_type_num_active_cpus[MAX_CPU_TYPES];
141 
142 /**
143  * Represents the offset of each cluster within a hypothetical array of MAX_CPUS
144  * entries of an arbitrary data type.  This is intended for use by specialized consumers
145  * that must quickly access per-CPU data using only the physical CPU ID (MPIDR_EL1),
146  * as follows:
147  *	hypothetical_array[cluster_offsets[AFF1] + AFF0]
148  * Most consumers should instead use general-purpose facilities such as PERCPU or
149  * ml_get_cpu_number().
150  */
151 SECURITY_READ_ONLY_LATE(int64_t) cluster_offsets[MAX_CPU_CLUSTER_PHY_ID + 1];
152 
153 SECURITY_READ_ONLY_LATE(static uint32_t) arm64_eventi = UINT32_MAX;
154 
155 extern uint32_t lockdown_done;
156 
157 /**
158  * Represents regions of virtual address space that should be reserved
159  * (pre-mapped) in each user address space.
160  */
161 SECURITY_READ_ONLY_LATE(static struct vm_reserved_region) vm_reserved_regions[] = {
162 	{
163 		.vmrr_name = "GPU Carveout",
164 		.vmrr_addr = MACH_VM_MIN_GPU_CARVEOUT_ADDRESS,
165 		.vmrr_size = (vm_map_size_t)(MACH_VM_MAX_GPU_CARVEOUT_ADDRESS - MACH_VM_MIN_GPU_CARVEOUT_ADDRESS)
166 	},
167 	/*
168 	 * Reserve the virtual memory space representing the commpage nesting region
169 	 * to prevent user processes from allocating memory within it. The actual
170 	 * page table entries for the commpage are inserted by vm_commpage_enter().
171 	 * This vm_map_enter() just prevents userspace from allocating/deallocating
172 	 * anything within the entire commpage nested region.
173 	 */
174 	{
175 		.vmrr_name = "commpage nesting",
176 		.vmrr_addr = _COMM_PAGE64_NESTING_START,
177 		.vmrr_size = _COMM_PAGE64_NESTING_SIZE
178 	}
179 };
180 
181 uint32_t get_arm_cpu_version(void);
182 
183 #if defined(HAS_IPI)
184 static inline void
ml_cpu_signal_type(unsigned int cpu_mpidr,uint32_t type)185 ml_cpu_signal_type(unsigned int cpu_mpidr, uint32_t type)
186 {
187 #if HAS_CLUSTER
188 	uint64_t local_mpidr;
189 	/* NOTE: this logic expects that we are called in a non-preemptible
190 	 * context, or at least one in which the calling thread is bound
191 	 * to a single CPU.  Otherwise we may migrate between choosing which
192 	 * IPI mechanism to use and issuing the IPI. */
193 	MRS(local_mpidr, "MPIDR_EL1");
194 	if (MPIDR_CLUSTER_ID(local_mpidr) == MPIDR_CLUSTER_ID(cpu_mpidr)) {
195 		uint64_t x = type | MPIDR_CPU_ID(cpu_mpidr);
196 		MSR("S3_5_C15_C0_0", x);
197 	} else {
198 		#define IPI_RR_TARGET_CLUSTER_SHIFT 16
199 		uint64_t x = type | (MPIDR_CLUSTER_ID(cpu_mpidr) << IPI_RR_TARGET_CLUSTER_SHIFT) | MPIDR_CPU_ID(cpu_mpidr);
200 		MSR("S3_5_C15_C0_1", x);
201 	}
202 #else
203 	uint64_t x = type | MPIDR_CPU_ID(cpu_mpidr);
204 	MSR("S3_5_C15_C0_1", x);
205 #endif
206 }
207 #endif
208 
209 #if !defined(HAS_IPI)
210 __dead2
211 #endif
212 void
ml_cpu_signal(unsigned int cpu_mpidr __unused)213 ml_cpu_signal(unsigned int cpu_mpidr __unused)
214 {
215 #if defined(HAS_IPI)
216 	ml_cpu_signal_type(cpu_mpidr, ARM64_REG_IPI_RR_TYPE_IMMEDIATE);
217 #else
218 	panic("Platform does not support ACC Fast IPI");
219 #endif
220 }
221 
222 #if !defined(HAS_IPI)
223 __dead2
224 #endif
225 void
ml_cpu_signal_deferred_adjust_timer(uint64_t nanosecs)226 ml_cpu_signal_deferred_adjust_timer(uint64_t nanosecs)
227 {
228 #if defined(HAS_IPI)
229 	/* adjust IPI_CR timer countdown value for deferred IPI
230 	 * accepts input in nanosecs, convert to absolutetime (REFCLK ticks),
231 	 * clamp maximum REFCLK ticks to 0xFFFF (16 bit field)
232 	 *
233 	 * global register, should only require a single write to update all
234 	 * CPU cores: from Skye ACC user spec section 5.7.3.3
235 	 *
236 	 * IPICR is a global register but there are two copies in ACC: one at pBLK and one at eBLK.
237 	 * IPICR write SPR token also traverses both pCPM and eCPM rings and updates both copies.
238 	 */
239 	uint64_t abstime;
240 
241 	nanoseconds_to_absolutetime(nanosecs, &abstime);
242 
243 	abstime = MIN(abstime, 0xFFFF);
244 
245 	/* update deferred_ipi_timer_ns with the new clamped value */
246 	absolutetime_to_nanoseconds(abstime, &deferred_ipi_timer_ns);
247 
248 	MSR("S3_5_C15_C3_1", abstime);
249 #else
250 	(void)nanosecs;
251 	panic("Platform does not support ACC Fast IPI");
252 #endif
253 }
254 
255 uint64_t
ml_cpu_signal_deferred_get_timer()256 ml_cpu_signal_deferred_get_timer()
257 {
258 #if defined(HAS_IPI)
259 	return deferred_ipi_timer_ns;
260 #else
261 	return 0;
262 #endif
263 }
264 
265 #if !defined(HAS_IPI)
266 __dead2
267 #endif
268 void
ml_cpu_signal_deferred(unsigned int cpu_mpidr __unused)269 ml_cpu_signal_deferred(unsigned int cpu_mpidr __unused)
270 {
271 #if defined(HAS_IPI)
272 	ml_cpu_signal_type(cpu_mpidr, ARM64_REG_IPI_RR_TYPE_DEFERRED);
273 #else
274 	panic("Platform does not support ACC Fast IPI deferral");
275 #endif
276 }
277 
278 #if !defined(HAS_IPI)
279 __dead2
280 #endif
281 void
ml_cpu_signal_retract(unsigned int cpu_mpidr __unused)282 ml_cpu_signal_retract(unsigned int cpu_mpidr __unused)
283 {
284 #if defined(HAS_IPI)
285 	ml_cpu_signal_type(cpu_mpidr, ARM64_REG_IPI_RR_TYPE_RETRACT);
286 #else
287 	panic("Platform does not support ACC Fast IPI retraction");
288 #endif
289 }
290 
291 extern uint32_t idle_proximate_io_wfe_unmasked;
292 
293 #define CPUPM_IDLE_WFE 0x5310300
294 static bool
wfe_process_recommendation(void)295 wfe_process_recommendation(void)
296 {
297 	bool ipending = false;
298 	if (__probable(idle_proximate_io_wfe_unmasked == 1)) {
299 		/* Check for an active perf. controller generated
300 		 * WFE recommendation for this cluster.
301 		 */
302 		cpu_data_t *cdp = getCpuDatap();
303 		uint32_t cid = cdp->cpu_cluster_id;
304 		uint64_t wfe_ttd = 0;
305 		uint64_t wfe_deadline = 0;
306 
307 		if ((wfe_ttd = ml_cluster_wfe_timeout(cid)) != 0) {
308 			wfe_deadline = mach_absolute_time() + wfe_ttd;
309 		}
310 
311 		if (wfe_deadline != 0) {
312 			/* Poll issuing event-bounded WFEs until an interrupt
313 			 * arrives or the WFE recommendation expires
314 			 */
315 #if DEVELOPMENT || DEBUG
316 			uint64_t wc = cdp->wfe_count;
317 			KDBG(CPUPM_IDLE_WFE | DBG_FUNC_START, ipending, wc, wfe_ttd, cdp->cpu_stat.irq_ex_cnt_wake);
318 #endif
319 			/* Issue WFE until the recommendation expires,
320 			 * with IRQs unmasked.
321 			 */
322 			ipending = wfe_to_deadline_or_interrupt(cid, wfe_deadline, cdp, true);
323 #if DEVELOPMENT || DEBUG
324 			KDBG(CPUPM_IDLE_WFE | DBG_FUNC_END, ipending, cdp->wfe_count - wc, wfe_deadline, cdp->cpu_stat.irq_ex_cnt_wake);
325 #endif
326 		}
327 	}
328 	return ipending;
329 }
330 
331 void
machine_idle(void)332 machine_idle(void)
333 {
334 	/* Interrupts are expected to be masked on entry or re-entry via
335 	 * Idle_load_context()
336 	 */
337 	assert((__builtin_arm_rsr("DAIF") & (DAIF_IRQF | DAIF_FIQF)) == (DAIF_IRQF | DAIF_FIQF));
338 	/* Check for, and act on, a WFE recommendation.
339 	 * Bypasses context spill/fill for a minor perf. increment.
340 	 * May unmask and restore IRQ+FIQ mask.
341 	 */
342 	if (wfe_process_recommendation() == false) {
343 		/* If WFE recommendation absent, or WFE deadline
344 		 * arrived with no interrupt pending/processed,
345 		 * fall back to WFI.
346 		 */
347 		Idle_context();
348 	}
349 	__builtin_arm_wsr("DAIFClr", (DAIFSC_IRQF | DAIFSC_FIQF));
350 }
351 
352 void
OSSynchronizeIO(void)353 OSSynchronizeIO(void)
354 {
355 	__builtin_arm_dsb(DSB_SY);
356 }
357 
358 uint64_t
get_aux_control(void)359 get_aux_control(void)
360 {
361 	uint64_t        value;
362 
363 	MRS(value, "ACTLR_EL1");
364 	return value;
365 }
366 
367 uint64_t
get_mmu_control(void)368 get_mmu_control(void)
369 {
370 	uint64_t        value;
371 
372 	MRS(value, "SCTLR_EL1");
373 	return value;
374 }
375 
376 uint64_t
get_tcr(void)377 get_tcr(void)
378 {
379 	uint64_t        value;
380 
381 	MRS(value, "TCR_EL1");
382 	return value;
383 }
384 
385 boolean_t
ml_get_interrupts_enabled(void)386 ml_get_interrupts_enabled(void)
387 {
388 	uint64_t        value;
389 
390 	MRS(value, "DAIF");
391 	if (value & DAIF_IRQF) {
392 		return FALSE;
393 	}
394 	return TRUE;
395 }
396 
397 pmap_paddr_t
get_mmu_ttb(void)398 get_mmu_ttb(void)
399 {
400 	pmap_paddr_t    value;
401 
402 	MRS(value, "TTBR0_EL1");
403 	return value;
404 }
405 
406 uint32_t
get_arm_cpu_version(void)407 get_arm_cpu_version(void)
408 {
409 	uint32_t value = machine_read_midr();
410 
411 	/* Compose the register values into 8 bits; variant[7:4], revision[3:0]. */
412 	return ((value & MIDR_EL1_REV_MASK) >> MIDR_EL1_REV_SHIFT) | ((value & MIDR_EL1_VAR_MASK) >> (MIDR_EL1_VAR_SHIFT - 4));
413 }
414 
415 bool
ml_feature_supported(uint32_t feature_bit)416 ml_feature_supported(uint32_t feature_bit)
417 {
418 	uint64_t aidr_el1_value = 0;
419 
420 	MRS(aidr_el1_value, "AIDR_EL1");
421 
422 
423 	return aidr_el1_value & feature_bit;
424 }
425 
426 /*
427  * user_cont_hwclock_allowed()
428  *
429  * Indicates whether we allow EL0 to read the virtual timebase (CNTVCT_EL0)
430  * as a continuous time source (e.g. from mach_continuous_time)
431  */
432 boolean_t
user_cont_hwclock_allowed(void)433 user_cont_hwclock_allowed(void)
434 {
435 #if HAS_CONTINUOUS_HWCLOCK
436 	return TRUE;
437 #else
438 	return FALSE;
439 #endif
440 }
441 
442 /*
443  * user_timebase_type()
444  *
445  * Indicates type of EL0 virtual timebase read (CNTVCT_EL0).
446  *
447  * USER_TIMEBASE_NONE: EL0 has no access to timebase register
448  * USER_TIMEBASE_SPEC: EL0 has access to speculative timebase reads (CNTVCT_EL0)
449  * USER_TIMEBASE_NOSPEC: EL0 has access to non speculative timebase reads (CNTVCTSS_EL0)
450  *
451  */
452 
453 uint8_t
user_timebase_type(void)454 user_timebase_type(void)
455 {
456 	return USER_TIMEBASE_SPEC;
457 }
458 
459 void
machine_startup(__unused boot_args * args)460 machine_startup(__unused boot_args * args)
461 {
462 #if defined(HAS_IPI) && (DEVELOPMENT || DEBUG)
463 	if (!PE_parse_boot_argn("fastipi", &gFastIPI, sizeof(gFastIPI))) {
464 		gFastIPI = 1;
465 	}
466 #endif /* defined(HAS_IPI) && (DEVELOPMENT || DEBUG)*/
467 
468 
469 	machine_conf();
470 
471 
472 	/*
473 	 * Kick off the kernel bootstrap.
474 	 */
475 	kernel_bootstrap();
476 	/* NOTREACHED */
477 }
478 
479 typedef void (*invalidate_fn_t)(void);
480 
481 static SECURITY_READ_ONLY_LATE(invalidate_fn_t) invalidate_hmac_function = NULL;
482 
483 void set_invalidate_hmac_function(invalidate_fn_t fn);
484 
485 void
set_invalidate_hmac_function(invalidate_fn_t fn)486 set_invalidate_hmac_function(invalidate_fn_t fn)
487 {
488 	if (NULL != invalidate_hmac_function) {
489 		panic("Invalidate HMAC function already set");
490 	}
491 
492 	invalidate_hmac_function = fn;
493 }
494 
495 void
machine_lockdown(void)496 machine_lockdown(void)
497 {
498 	arm_vm_prot_finalize(PE_state.bootArgs);
499 
500 #if CONFIG_KERNEL_INTEGRITY
501 #if KERNEL_INTEGRITY_WT
502 	/* Watchtower
503 	 *
504 	 * Notify the monitor about the completion of early kernel bootstrap.
505 	 * From this point forward it will enforce the integrity of kernel text,
506 	 * rodata and page tables.
507 	 */
508 
509 #ifdef MONITOR
510 	monitor_call(MONITOR_LOCKDOWN, 0, 0, 0);
511 #endif
512 #endif /* KERNEL_INTEGRITY_WT */
513 
514 #if XNU_MONITOR
515 	pmap_lockdown_ppl();
516 #endif
517 
518 #if defined(KERNEL_INTEGRITY_KTRR) || defined(KERNEL_INTEGRITY_CTRR)
519 	/* KTRR
520 	 *
521 	 * Lock physical KTRR region. KTRR region is read-only. Memory outside
522 	 * the region is not executable at EL1.
523 	 */
524 
525 	rorgn_lockdown();
526 #endif /* defined(KERNEL_INTEGRITY_KTRR) || defined(KERNEL_INTEGRITY_CTRR) */
527 
528 
529 #endif /* CONFIG_KERNEL_INTEGRITY */
530 
531 
532 	if (NULL != invalidate_hmac_function) {
533 		invalidate_hmac_function();
534 	}
535 
536 	lockdown_done = 1;
537 }
538 
539 
540 char           *
machine_boot_info(__unused char * buf,__unused vm_size_t size)541 machine_boot_info(
542 	__unused char *buf,
543 	__unused vm_size_t size)
544 {
545 	return PE_boot_args();
546 }
547 
548 void
slave_machine_init(__unused void * param)549 slave_machine_init(__unused void *param)
550 {
551 	cpu_machine_init();     /* Initialize the processor */
552 	clock_init();           /* Init the clock */
553 }
554 
555 /*
556  *	Routine:        machine_processor_shutdown
557  *	Function:
558  */
559 thread_t
machine_processor_shutdown(__unused thread_t thread,void (* doshutdown)(processor_t),processor_t processor)560 machine_processor_shutdown(
561 	__unused thread_t thread,
562 	void (*doshutdown)(processor_t),
563 	processor_t processor)
564 {
565 	return Shutdown_context(doshutdown, processor);
566 }
567 
568 /*
569  *      Routine:        ml_init_lock_timeout
570  *      Function:
571  */
572 void
ml_init_lock_timeout(void)573 ml_init_lock_timeout(void)
574 {
575 	/*
576 	 * This function is called after STARUP_SUB_TIMEOUTS
577 	 * initialization, so using the "legacy" boot-args here overrides
578 	 * the ml-timeout-...  configuration. (Given that these boot-args
579 	 * here are usually explicitly specified, this makes sense by
580 	 * overriding ml-timeout-..., which may come from the device tree.
581 	 */
582 
583 	uint64_t lto_timeout_ns;
584 	uint64_t lto_abstime;
585 	uint32_t slto;
586 
587 	if (PE_parse_boot_argn("slto_us", &slto, sizeof(slto))) {
588 		lto_timeout_ns = slto * NSEC_PER_USEC;
589 		nanoseconds_to_absolutetime(lto_timeout_ns, &lto_abstime);
590 		os_atomic_store(&LockTimeOut, lto_abstime, relaxed);
591 	} else {
592 		lto_abstime = os_atomic_load(&LockTimeOut, relaxed);
593 		absolutetime_to_nanoseconds(lto_abstime, &lto_timeout_ns);
594 	}
595 
596 	os_atomic_store(&LockTimeOutUsec, lto_timeout_ns / NSEC_PER_USEC, relaxed);
597 
598 	if (PE_parse_boot_argn("tlto_us", &slto, sizeof(slto))) {
599 		nanoseconds_to_absolutetime(slto * NSEC_PER_USEC, &lto_abstime);
600 		os_atomic_store(&TLockTimeOut, lto_abstime, relaxed);
601 	} else if (lto_abstime != 0) {
602 		os_atomic_store(&TLockTimeOut, lto_abstime >> 1, relaxed);
603 	} // else take default from MACHINE_TIMEOUT.
604 
605 	uint64_t mtxspin;
606 	uint64_t mtx_abstime;
607 	if (PE_parse_boot_argn("mtxspin", &mtxspin, sizeof(mtxspin))) {
608 		if (mtxspin > USEC_PER_SEC >> 4) {
609 			mtxspin =  USEC_PER_SEC >> 4;
610 		}
611 		nanoseconds_to_absolutetime(mtxspin * NSEC_PER_USEC, &mtx_abstime);
612 		os_atomic_store(&MutexSpin, mtx_abstime, relaxed);
613 	} else {
614 		mtx_abstime = os_atomic_load(&MutexSpin, relaxed);
615 	}
616 
617 	low_MutexSpin = os_atomic_load(&MutexSpin, relaxed);
618 	/*
619 	 * high_MutexSpin should be initialized as low_MutexSpin * real_ncpus, but
620 	 * real_ncpus is not set at this time
621 	 *
622 	 * NOTE: active spinning is disabled in arm. It can be activated
623 	 * by setting high_MutexSpin through the sysctl.
624 	 */
625 	high_MutexSpin = low_MutexSpin;
626 
627 	uint64_t maxwfeus = MAX_WFE_HINT_INTERVAL_US;
628 	PE_parse_boot_argn("max_wfe_us", &maxwfeus, sizeof(maxwfeus));
629 	nanoseconds_to_absolutetime(maxwfeus * NSEC_PER_USEC, &ml_wfe_hint_max_interval);
630 }
631 
632 /*
633  * This is called when all of the ml_processor_info_t structures have been
634  * initialized and all the processors have been started through processor_start().
635  *
636  * Required by the scheduler subsystem.
637  */
638 void
ml_cpu_init_completed(void)639 ml_cpu_init_completed(void)
640 {
641 	if (SCHED(cpu_init_completed) != NULL) {
642 		SCHED(cpu_init_completed)();
643 	}
644 }
645 
646 /*
647  * This is called from the machine-independent routine cpu_up()
648  * to perform machine-dependent info updates.
649  */
650 void
ml_cpu_up(void)651 ml_cpu_up(void)
652 {
653 	ml_topology_cpu_t *cpu = &ml_get_topology_info()->cpus[ml_get_cpu_number_local()];
654 
655 	os_atomic_inc(&cluster_type_num_active_cpus[cpu->cluster_type], relaxed);
656 
657 	os_atomic_inc(&machine_info.physical_cpu, relaxed);
658 	os_atomic_inc(&machine_info.logical_cpu, relaxed);
659 }
660 
661 /*
662  * This is called from the machine-independent routine cpu_down()
663  * to perform machine-dependent info updates.
664  */
665 void
ml_cpu_down(void)666 ml_cpu_down(void)
667 {
668 	cpu_data_t      *cpu_data_ptr;
669 	ml_topology_cpu_t *cpu = &ml_get_topology_info()->cpus[ml_get_cpu_number_local()];
670 
671 	os_atomic_dec(&cluster_type_num_active_cpus[cpu->cluster_type], relaxed);
672 
673 	os_atomic_dec(&machine_info.physical_cpu, relaxed);
674 	os_atomic_dec(&machine_info.logical_cpu, relaxed);
675 
676 	/*
677 	 * If we want to deal with outstanding IPIs, we need to
678 	 * do relatively early in the processor_doshutdown path,
679 	 * as we pend decrementer interrupts using the IPI
680 	 * mechanism if we cannot immediately service them (if
681 	 * IRQ is masked).  Do so now.
682 	 *
683 	 * We aren't on the interrupt stack here; would it make
684 	 * more sense to disable signaling and then enable
685 	 * interrupts?  It might be a bit cleaner.
686 	 */
687 	cpu_data_ptr = getCpuDatap();
688 	cpu_data_ptr->cpu_running = FALSE;
689 
690 	if (cpu_data_ptr != &BootCpuData) {
691 		/*
692 		 * Move all of this cpu's timers to the master/boot cpu,
693 		 * and poke it in case there's a sooner deadline for it to schedule.
694 		 */
695 		timer_queue_shutdown(&cpu_data_ptr->rtclock_timer.queue);
696 		cpu_xcall(BootCpuData.cpu_number, &timer_queue_expire_local, NULL);
697 	}
698 
699 	cpu_signal_handler_internal(TRUE);
700 }
701 
702 unsigned int
ml_get_machine_mem(void)703 ml_get_machine_mem(void)
704 {
705 	return machine_info.memory_size;
706 }
707 
708 __attribute__((noreturn))
709 void
halt_all_cpus(boolean_t reboot)710 halt_all_cpus(boolean_t reboot)
711 {
712 	if (reboot) {
713 		printf("MACH Reboot\n");
714 		PEHaltRestart(kPERestartCPU);
715 	} else {
716 		printf("CPU halted\n");
717 		PEHaltRestart(kPEHaltCPU);
718 	}
719 	while (1) {
720 		;
721 	}
722 }
723 
724 __attribute__((noreturn))
725 void
halt_cpu(void)726 halt_cpu(void)
727 {
728 	halt_all_cpus(FALSE);
729 }
730 
731 /*
732  *	Routine:        machine_signal_idle
733  *	Function:
734  */
735 void
machine_signal_idle(processor_t processor)736 machine_signal_idle(
737 	processor_t processor)
738 {
739 	cpu_signal(processor_to_cpu_datap(processor), SIGPnop, (void *)NULL, (void *)NULL);
740 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_REMOTE_AST), processor->cpu_id, 0 /* nop */, 0, 0, 0);
741 }
742 
743 void
machine_signal_idle_deferred(processor_t processor)744 machine_signal_idle_deferred(
745 	processor_t processor)
746 {
747 	cpu_signal_deferred(processor_to_cpu_datap(processor));
748 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_REMOTE_DEFERRED_AST), processor->cpu_id, 0 /* nop */, 0, 0, 0);
749 }
750 
751 void
machine_signal_idle_cancel(processor_t processor)752 machine_signal_idle_cancel(
753 	processor_t processor)
754 {
755 	cpu_signal_cancel(processor_to_cpu_datap(processor));
756 	KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_REMOTE_CANCEL_AST), processor->cpu_id, 0 /* nop */, 0, 0, 0);
757 }
758 
759 /*
760  *	Routine:        ml_install_interrupt_handler
761  *	Function:	Initialize Interrupt Handler
762  */
763 void
ml_install_interrupt_handler(void * nub,int source,void * target,IOInterruptHandler handler,void * refCon)764 ml_install_interrupt_handler(
765 	void *nub,
766 	int source,
767 	void *target,
768 	IOInterruptHandler handler,
769 	void *refCon)
770 {
771 	cpu_data_t     *cpu_data_ptr;
772 	boolean_t       current_state;
773 
774 	current_state = ml_set_interrupts_enabled(FALSE);
775 	cpu_data_ptr = getCpuDatap();
776 
777 	cpu_data_ptr->interrupt_nub = nub;
778 	cpu_data_ptr->interrupt_source = source;
779 	cpu_data_ptr->interrupt_target = target;
780 	cpu_data_ptr->interrupt_handler = handler;
781 	cpu_data_ptr->interrupt_refCon = refCon;
782 
783 	(void) ml_set_interrupts_enabled(current_state);
784 }
785 
786 /*
787  *	Routine:        ml_init_interrupt
788  *	Function:	Initialize Interrupts
789  */
790 void
ml_init_interrupt(void)791 ml_init_interrupt(void)
792 {
793 #if defined(HAS_IPI)
794 	/*
795 	 * ml_init_interrupt will get called once for each CPU, but this is redundant
796 	 * because there is only one global copy of the register for skye. do it only
797 	 * on the bootstrap cpu
798 	 */
799 	if (getCpuDatap()->cluster_master) {
800 		ml_cpu_signal_deferred_adjust_timer(deferred_ipi_timer_ns);
801 	}
802 #endif
803 }
804 
805 /*
806  *	Routine:        ml_init_timebase
807  *	Function:	register and setup Timebase, Decremeter services
808  */
809 void
ml_init_timebase(void * args,tbd_ops_t tbd_funcs,vm_offset_t int_address,vm_offset_t int_value __unused)810 ml_init_timebase(
811 	void            *args,
812 	tbd_ops_t       tbd_funcs,
813 	vm_offset_t     int_address,
814 	vm_offset_t     int_value __unused)
815 {
816 	cpu_data_t     *cpu_data_ptr;
817 
818 	cpu_data_ptr = (cpu_data_t *)args;
819 
820 	if ((cpu_data_ptr == &BootCpuData)
821 	    && (rtclock_timebase_func.tbd_fiq_handler == (void *)NULL)) {
822 		rtclock_timebase_func = *tbd_funcs;
823 		rtclock_timebase_addr = int_address;
824 	}
825 }
826 
827 #define ML_READPROP_MANDATORY UINT64_MAX
828 
829 static uint64_t
ml_readprop(const DTEntry entry,const char * propertyName,uint64_t default_value)830 ml_readprop(const DTEntry entry, const char *propertyName, uint64_t default_value)
831 {
832 	void const *prop;
833 	unsigned int propSize;
834 
835 	if (SecureDTGetProperty(entry, propertyName, &prop, &propSize) == kSuccess) {
836 		if (propSize == sizeof(uint8_t)) {
837 			return *((uint8_t const *)prop);
838 		} else if (propSize == sizeof(uint16_t)) {
839 			return *((uint16_t const *)prop);
840 		} else if (propSize == sizeof(uint32_t)) {
841 			return *((uint32_t const *)prop);
842 		} else if (propSize == sizeof(uint64_t)) {
843 			return *((uint64_t const *)prop);
844 		} else {
845 			panic("CPU property '%s' has bad size %u", propertyName, propSize);
846 		}
847 	} else {
848 		if (default_value == ML_READPROP_MANDATORY) {
849 			panic("Missing mandatory property '%s'", propertyName);
850 		}
851 		return default_value;
852 	}
853 }
854 
855 static boolean_t
ml_read_reg_range(const DTEntry entry,const char * propertyName,uint64_t * pa_ptr,uint64_t * len_ptr)856 ml_read_reg_range(const DTEntry entry, const char *propertyName, uint64_t *pa_ptr, uint64_t *len_ptr)
857 {
858 	uint64_t const *prop;
859 	unsigned int propSize;
860 
861 	if (SecureDTGetProperty(entry, propertyName, (void const **)&prop, &propSize) != kSuccess) {
862 		return FALSE;
863 	}
864 
865 	if (propSize != sizeof(uint64_t) * 2) {
866 		panic("Wrong property size for %s", propertyName);
867 	}
868 
869 	*pa_ptr = prop[0];
870 	*len_ptr = prop[1];
871 	return TRUE;
872 }
873 
874 static boolean_t
ml_is_boot_cpu(const DTEntry entry)875 ml_is_boot_cpu(const DTEntry entry)
876 {
877 	void const *prop;
878 	unsigned int propSize;
879 
880 	if (SecureDTGetProperty(entry, "state", &prop, &propSize) != kSuccess) {
881 		panic("unable to retrieve state for cpu");
882 	}
883 
884 	if (strncmp((char const *)prop, "running", propSize) == 0) {
885 		return TRUE;
886 	} else {
887 		return FALSE;
888 	}
889 }
890 
891 static void
ml_read_chip_revision(unsigned int * rev __unused)892 ml_read_chip_revision(unsigned int *rev __unused)
893 {
894 	// The CPU_VERSION_* macros are only defined on APPLE_ARM64_ARCH_FAMILY builds
895 #ifdef APPLE_ARM64_ARCH_FAMILY
896 	DTEntry         entryP;
897 
898 	if ((SecureDTFindEntry("name", "arm-io", &entryP) == kSuccess)) {
899 		*rev = (unsigned int)ml_readprop(entryP, "chip-revision", CPU_VERSION_UNKNOWN);
900 	} else {
901 		*rev = CPU_VERSION_UNKNOWN;
902 	}
903 #endif
904 }
905 
906 void
ml_parse_cpu_topology(void)907 ml_parse_cpu_topology(void)
908 {
909 	DTEntry entry, child __unused;
910 	OpaqueDTEntryIterator iter;
911 	uint32_t cpu_boot_arg = MAX_CPUS;
912 	uint64_t cpumask_boot_arg = ULLONG_MAX;
913 	int err;
914 
915 	int64_t cluster_phys_to_logical[MAX_CPU_CLUSTER_PHY_ID + 1];
916 	int64_t cluster_max_cpu_phys_id[MAX_CPU_CLUSTER_PHY_ID + 1];
917 	const boolean_t cpus_boot_arg_present = PE_parse_boot_argn("cpus", &cpu_boot_arg, sizeof(cpu_boot_arg));
918 	const boolean_t cpumask_boot_arg_present = PE_parse_boot_argn("cpumask", &cpumask_boot_arg, sizeof(cpumask_boot_arg));
919 
920 	// The cpus=N and cpumask=N boot args cannot be used simultaneously. Flag this
921 	// so that we trigger a panic later in the boot process, once serial is enabled.
922 	if (cpus_boot_arg_present && cpumask_boot_arg_present) {
923 		cpu_config_correct = false;
924 	}
925 
926 	err = SecureDTLookupEntry(NULL, "/cpus", &entry);
927 	assert(err == kSuccess);
928 
929 	err = SecureDTInitEntryIterator(entry, &iter);
930 	assert(err == kSuccess);
931 
932 	for (int i = 0; i <= MAX_CPU_CLUSTER_PHY_ID; i++) {
933 		cluster_offsets[i] = -1;
934 		cluster_phys_to_logical[i] = -1;
935 		cluster_max_cpu_phys_id[i] = 0;
936 	}
937 
938 	while (kSuccess == SecureDTIterateEntries(&iter, &child)) {
939 		boolean_t is_boot_cpu = ml_is_boot_cpu(child);
940 		boolean_t cpu_enabled = cpumask_boot_arg & 1;
941 		cpumask_boot_arg >>= 1;
942 
943 		// Boot CPU disabled in cpumask. Flag this so that we trigger a panic
944 		// later in the boot process, once serial is enabled.
945 		if (is_boot_cpu && !cpu_enabled) {
946 			cpu_config_correct = false;
947 		}
948 
949 		// Ignore this CPU if it has been disabled by the cpumask= boot-arg.
950 		if (!is_boot_cpu && !cpu_enabled) {
951 			continue;
952 		}
953 
954 		// If the number of CPUs is constrained by the cpus= boot-arg, and the boot CPU hasn't
955 		// been added to the topology struct yet, and we only have one slot left, then skip
956 		// every other non-boot CPU in order to leave room for the boot CPU.
957 		//
958 		// e.g. if the boot-args say "cpus=3" and CPU4 is the boot CPU, then the cpus[]
959 		// array will list CPU0, CPU1, and CPU4.  CPU2-CPU3 and CPU5-CPUn will be omitted.
960 		if (topology_info.num_cpus >= (cpu_boot_arg - 1) && topology_info.boot_cpu == NULL && !is_boot_cpu) {
961 			continue;
962 		}
963 		if (topology_info.num_cpus >= cpu_boot_arg) {
964 			break;
965 		}
966 
967 		ml_topology_cpu_t *cpu = &topology_info.cpus[topology_info.num_cpus];
968 
969 		cpu->cpu_id = topology_info.num_cpus++;
970 		assert(cpu->cpu_id < MAX_CPUS);
971 		topology_info.max_cpu_id = MAX(topology_info.max_cpu_id, cpu->cpu_id);
972 
973 		cpu->reserved = 0;
974 		topology_info.reserved = 0;
975 
976 		cpu->phys_id = (uint32_t)ml_readprop(child, "reg", ML_READPROP_MANDATORY);
977 
978 		cpu->l2_access_penalty = (uint32_t)ml_readprop(child, "l2-access-penalty", 0);
979 		cpu->l2_cache_size = (uint32_t)ml_readprop(child, "l2-cache-size", 0);
980 		cpu->l2_cache_id = (uint32_t)ml_readprop(child, "l2-cache-id", 0);
981 		cpu->l3_cache_size = (uint32_t)ml_readprop(child, "l3-cache-size", 0);
982 		cpu->l3_cache_id = (uint32_t)ml_readprop(child, "l3-cache-id", 0);
983 
984 		ml_read_reg_range(child, "cpu-uttdbg-reg", &cpu->cpu_UTTDBG_pa, &cpu->cpu_UTTDBG_len);
985 		ml_read_reg_range(child, "cpu-impl-reg", &cpu->cpu_IMPL_pa, &cpu->cpu_IMPL_len);
986 		ml_read_reg_range(child, "coresight-reg", &cpu->coresight_pa, &cpu->coresight_len);
987 		cpu->cluster_type = CLUSTER_TYPE_SMP;
988 
989 		int cluster_type = (int)ml_readprop(child, "cluster-type", 0);
990 		if (cluster_type == 'E') {
991 			cpu->cluster_type = CLUSTER_TYPE_E;
992 		} else if (cluster_type == 'P') {
993 			cpu->cluster_type = CLUSTER_TYPE_P;
994 		}
995 
996 		topology_info.cluster_type_num_cpus[cpu->cluster_type]++;
997 
998 		/*
999 		 * Since we want to keep a linear cluster ID space, we cannot just rely
1000 		 * on the value provided by EDT. Instead, use the MPIDR value to see if we have
1001 		 * seen this exact cluster before. If so, then reuse that cluster ID for this CPU.
1002 		 */
1003 #if HAS_CLUSTER
1004 		uint32_t phys_cluster_id = MPIDR_CLUSTER_ID(cpu->phys_id);
1005 #else
1006 		uint32_t phys_cluster_id = (cpu->cluster_type == CLUSTER_TYPE_P);
1007 #endif
1008 		assert(phys_cluster_id <= MAX_CPU_CLUSTER_PHY_ID);
1009 		cpu->cluster_id = ((cluster_phys_to_logical[phys_cluster_id] == -1) ?
1010 		    topology_info.num_clusters : cluster_phys_to_logical[phys_cluster_id]);
1011 
1012 		assert(cpu->cluster_id < MAX_CPU_CLUSTERS);
1013 
1014 		ml_topology_cluster_t *cluster = &topology_info.clusters[cpu->cluster_id];
1015 		if (cluster->num_cpus == 0) {
1016 			assert(topology_info.num_clusters < MAX_CPU_CLUSTERS);
1017 
1018 			topology_info.num_clusters++;
1019 			topology_info.max_cluster_id = MAX(topology_info.max_cluster_id, cpu->cluster_id);
1020 			topology_info.cluster_types |= (1 << cpu->cluster_type);
1021 
1022 			cluster->cluster_id = cpu->cluster_id;
1023 			cluster->cluster_type = cpu->cluster_type;
1024 			cluster->first_cpu_id = cpu->cpu_id;
1025 			assert(cluster_phys_to_logical[phys_cluster_id] == -1);
1026 			cluster_phys_to_logical[phys_cluster_id] = cpu->cluster_id;
1027 
1028 			// Since we don't have a per-cluster EDT node, this is repeated in each CPU node.
1029 			// If we wind up with a bunch of these, we might want to create separate per-cluster
1030 			// EDT nodes and have the CPU nodes reference them through a phandle.
1031 			ml_read_reg_range(child, "acc-impl-reg", &cluster->acc_IMPL_pa, &cluster->acc_IMPL_len);
1032 			ml_read_reg_range(child, "cpm-impl-reg", &cluster->cpm_IMPL_pa, &cluster->cpm_IMPL_len);
1033 		}
1034 
1035 #if HAS_CLUSTER
1036 		if (MPIDR_CPU_ID(cpu->phys_id) > cluster_max_cpu_phys_id[phys_cluster_id]) {
1037 			cluster_max_cpu_phys_id[phys_cluster_id] = MPIDR_CPU_ID(cpu->phys_id);
1038 		}
1039 #endif
1040 
1041 		cpu->die_cluster_id = (int)ml_readprop(child, "die-cluster-id", MPIDR_CLUSTER_ID(cpu->phys_id));
1042 		cpu->cluster_core_id = (int)ml_readprop(child, "cluster-core-id", MPIDR_CPU_ID(cpu->phys_id));
1043 
1044 		cluster->num_cpus++;
1045 		cluster->cpu_mask |= 1ULL << cpu->cpu_id;
1046 
1047 		if (is_boot_cpu) {
1048 			assert(topology_info.boot_cpu == NULL);
1049 			topology_info.boot_cpu = cpu;
1050 			topology_info.boot_cluster = cluster;
1051 		}
1052 	}
1053 
1054 #if HAS_CLUSTER
1055 	/*
1056 	 * Build the cluster offset array, ensuring that the region reserved
1057 	 * for each physical cluster contains enough entries to be indexed
1058 	 * by the maximum physical CPU ID (AFF0) within the cluster.
1059 	 */
1060 	unsigned int cur_cluster_offset = 0;
1061 	for (int i = 0; i <= MAX_CPU_CLUSTER_PHY_ID; i++) {
1062 		if (cluster_phys_to_logical[i] != -1) {
1063 			cluster_offsets[i] = cur_cluster_offset;
1064 			cur_cluster_offset += (cluster_max_cpu_phys_id[i] + 1);
1065 		}
1066 	}
1067 	assert(cur_cluster_offset <= MAX_CPUS);
1068 #else
1069 	/*
1070 	 * For H10, there are really 2 physical clusters, but they are not separated
1071 	 * into distinct ACCs.  AFF1 therefore always reports 0, and AFF0 numbering
1072 	 * is linear across both clusters.   For the purpose of MPIDR_EL1-based indexing,
1073 	 * treat H10 and earlier devices as though they contain a single cluster.
1074 	 */
1075 	cluster_offsets[0] = 0;
1076 #endif
1077 	assert(topology_info.boot_cpu != NULL);
1078 	ml_read_chip_revision(&topology_info.chip_revision);
1079 
1080 	/*
1081 	 * Set TPIDR_EL0 to indicate the correct cpu number, as we may
1082 	 * not be booting from cpu 0.  Userspace will consume the current
1083 	 * CPU number through this register.  For non-boot cores, this is
1084 	 * done in start.s (start_cpu) using the cpu_number field of the
1085 	 * per-cpu data object.
1086 	 */
1087 	uint64_t cpuid = topology_info.boot_cpu->cpu_id;
1088 
1089 	__builtin_arm_wsr64("TPIDR_EL0", cpuid & MACHDEP_TPIDR_CPUNUM_MASK);
1090 	assert((cpuid & MACHDEP_TPIDR_CPUNUM_MASK) == cpuid);
1091 	__builtin_arm_wsr64("TPIDRRO_EL0", 0);
1092 }
1093 
1094 const ml_topology_info_t *
ml_get_topology_info(void)1095 ml_get_topology_info(void)
1096 {
1097 	return &topology_info;
1098 }
1099 
1100 void
ml_map_cpu_pio(void)1101 ml_map_cpu_pio(void)
1102 {
1103 	unsigned int i;
1104 
1105 	for (i = 0; i < topology_info.num_cpus; i++) {
1106 		ml_topology_cpu_t *cpu = &topology_info.cpus[i];
1107 		if (cpu->cpu_IMPL_pa) {
1108 			cpu->cpu_IMPL_regs = (vm_offset_t)ml_io_map(cpu->cpu_IMPL_pa, cpu->cpu_IMPL_len);
1109 			cpu->coresight_regs = (vm_offset_t)ml_io_map(cpu->coresight_pa, cpu->coresight_len);
1110 		}
1111 		if (cpu->cpu_UTTDBG_pa) {
1112 			cpu->cpu_UTTDBG_regs = (vm_offset_t)ml_io_map(cpu->cpu_UTTDBG_pa, cpu->cpu_UTTDBG_len);
1113 		}
1114 	}
1115 
1116 	for (i = 0; i < topology_info.num_clusters; i++) {
1117 		ml_topology_cluster_t *cluster = &topology_info.clusters[i];
1118 		if (cluster->acc_IMPL_pa) {
1119 			cluster->acc_IMPL_regs = (vm_offset_t)ml_io_map(cluster->acc_IMPL_pa, cluster->acc_IMPL_len);
1120 		}
1121 		if (cluster->cpm_IMPL_pa) {
1122 			cluster->cpm_IMPL_regs = (vm_offset_t)ml_io_map(cluster->cpm_IMPL_pa, cluster->cpm_IMPL_len);
1123 		}
1124 	}
1125 }
1126 
1127 unsigned int
ml_get_cpu_count(void)1128 ml_get_cpu_count(void)
1129 {
1130 	return topology_info.num_cpus;
1131 }
1132 
1133 unsigned int
ml_get_cluster_count(void)1134 ml_get_cluster_count(void)
1135 {
1136 	return topology_info.num_clusters;
1137 }
1138 
1139 int
ml_get_boot_cpu_number(void)1140 ml_get_boot_cpu_number(void)
1141 {
1142 	return topology_info.boot_cpu->cpu_id;
1143 }
1144 
1145 cluster_type_t
ml_get_boot_cluster_type(void)1146 ml_get_boot_cluster_type(void)
1147 {
1148 	return topology_info.boot_cluster->cluster_type;
1149 }
1150 
1151 int
ml_get_cpu_number(uint32_t phys_id)1152 ml_get_cpu_number(uint32_t phys_id)
1153 {
1154 	phys_id &= MPIDR_AFF1_MASK | MPIDR_AFF0_MASK;
1155 
1156 	for (unsigned i = 0; i < topology_info.num_cpus; i++) {
1157 		if (topology_info.cpus[i].phys_id == phys_id) {
1158 			return i;
1159 		}
1160 	}
1161 
1162 	return -1;
1163 }
1164 
1165 int
ml_get_cluster_number(uint32_t phys_id)1166 ml_get_cluster_number(uint32_t phys_id)
1167 {
1168 	int cpu_id = ml_get_cpu_number(phys_id);
1169 	if (cpu_id < 0) {
1170 		return -1;
1171 	}
1172 
1173 	ml_topology_cpu_t *cpu = &topology_info.cpus[cpu_id];
1174 
1175 	return cpu->cluster_id;
1176 }
1177 
1178 unsigned int
ml_get_cpu_number_local(void)1179 ml_get_cpu_number_local(void)
1180 {
1181 	uint64_t mpidr_el1_value = 0;
1182 	unsigned cpu_id;
1183 
1184 	/* We identify the CPU based on the constant bits of MPIDR_EL1. */
1185 	MRS(mpidr_el1_value, "MPIDR_EL1");
1186 	cpu_id = ml_get_cpu_number((uint32_t)mpidr_el1_value);
1187 
1188 	assert(cpu_id <= (unsigned int)ml_get_max_cpu_number());
1189 
1190 	return cpu_id;
1191 }
1192 
1193 int
ml_get_cluster_number_local()1194 ml_get_cluster_number_local()
1195 {
1196 	uint64_t mpidr_el1_value = 0;
1197 	unsigned cluster_id;
1198 
1199 	/* We identify the cluster based on the constant bits of MPIDR_EL1. */
1200 	MRS(mpidr_el1_value, "MPIDR_EL1");
1201 	cluster_id = ml_get_cluster_number((uint32_t)mpidr_el1_value);
1202 
1203 	assert(cluster_id <= (unsigned int)ml_get_max_cluster_number());
1204 
1205 	return cluster_id;
1206 }
1207 
1208 int
ml_get_max_cpu_number(void)1209 ml_get_max_cpu_number(void)
1210 {
1211 	return topology_info.max_cpu_id;
1212 }
1213 
1214 int
ml_get_max_cluster_number(void)1215 ml_get_max_cluster_number(void)
1216 {
1217 	return topology_info.max_cluster_id;
1218 }
1219 
1220 unsigned int
ml_get_first_cpu_id(unsigned int cluster_id)1221 ml_get_first_cpu_id(unsigned int cluster_id)
1222 {
1223 	return topology_info.clusters[cluster_id].first_cpu_id;
1224 }
1225 
1226 
1227 void
ml_lockdown_init()1228 ml_lockdown_init()
1229 {
1230 #if defined(KERNEL_INTEGRITY_KTRR) || defined(KERNEL_INTEGRITY_CTRR)
1231 	rorgn_stash_range();
1232 #endif
1233 }
1234 
1235 kern_return_t
ml_lockdown_handler_register(lockdown_handler_t f,void * this)1236 ml_lockdown_handler_register(lockdown_handler_t f, void *this)
1237 {
1238 	if (!f) {
1239 		return KERN_FAILURE;
1240 	}
1241 
1242 	assert(lockdown_done);
1243 	f(this); // XXX: f this whole function
1244 
1245 	return KERN_SUCCESS;
1246 }
1247 
1248 kern_return_t
ml_processor_register(ml_processor_info_t * in_processor_info,processor_t * processor_out,ipi_handler_t * ipi_handler_out,perfmon_interrupt_handler_func * pmi_handler_out)1249 ml_processor_register(ml_processor_info_t *in_processor_info,
1250     processor_t *processor_out, ipi_handler_t *ipi_handler_out,
1251     perfmon_interrupt_handler_func *pmi_handler_out)
1252 {
1253 	cpu_data_t *this_cpu_datap;
1254 	processor_set_t pset;
1255 	boolean_t  is_boot_cpu;
1256 	static unsigned int reg_cpu_count = 0;
1257 
1258 	if (in_processor_info->log_id > (uint32_t)ml_get_max_cpu_number()) {
1259 		return KERN_FAILURE;
1260 	}
1261 
1262 	if ((unsigned)OSIncrementAtomic((SInt32*)&reg_cpu_count) >= topology_info.num_cpus) {
1263 		return KERN_FAILURE;
1264 	}
1265 
1266 	if (in_processor_info->log_id != (uint32_t)ml_get_boot_cpu_number()) {
1267 		is_boot_cpu = FALSE;
1268 		this_cpu_datap = cpu_data_alloc(FALSE);
1269 		cpu_data_init(this_cpu_datap);
1270 	} else {
1271 		this_cpu_datap = &BootCpuData;
1272 		is_boot_cpu = TRUE;
1273 	}
1274 
1275 	assert(in_processor_info->log_id <= (uint32_t)ml_get_max_cpu_number());
1276 
1277 	this_cpu_datap->cpu_id = in_processor_info->cpu_id;
1278 
1279 	if (!is_boot_cpu) {
1280 		this_cpu_datap->cpu_number = (unsigned short)(in_processor_info->log_id);
1281 
1282 		if (cpu_data_register(this_cpu_datap) != KERN_SUCCESS) {
1283 			goto processor_register_error;
1284 		}
1285 		assert((this_cpu_datap->cpu_number & MACHDEP_TPIDR_CPUNUM_MASK) == this_cpu_datap->cpu_number);
1286 	}
1287 
1288 	this_cpu_datap->cpu_idle_notify = in_processor_info->processor_idle;
1289 	this_cpu_datap->cpu_cache_dispatch = (cache_dispatch_t)in_processor_info->platform_cache_dispatch;
1290 	nanoseconds_to_absolutetime((uint64_t) in_processor_info->powergate_latency, &this_cpu_datap->cpu_idle_latency);
1291 	this_cpu_datap->cpu_reset_assist = kvtophys(in_processor_info->powergate_stub_addr);
1292 
1293 	this_cpu_datap->idle_timer_notify = in_processor_info->idle_timer;
1294 	this_cpu_datap->idle_timer_refcon = in_processor_info->idle_timer_refcon;
1295 
1296 	this_cpu_datap->platform_error_handler = in_processor_info->platform_error_handler;
1297 	this_cpu_datap->cpu_regmap_paddr = in_processor_info->regmap_paddr;
1298 	this_cpu_datap->cpu_phys_id = in_processor_info->phys_id;
1299 	this_cpu_datap->cpu_l2_access_penalty = in_processor_info->l2_access_penalty;
1300 
1301 	this_cpu_datap->cpu_cluster_type = in_processor_info->cluster_type;
1302 	this_cpu_datap->cpu_cluster_id = in_processor_info->cluster_id;
1303 	this_cpu_datap->cpu_l2_id = in_processor_info->l2_cache_id;
1304 	this_cpu_datap->cpu_l2_size = in_processor_info->l2_cache_size;
1305 	this_cpu_datap->cpu_l3_id = in_processor_info->l3_cache_id;
1306 	this_cpu_datap->cpu_l3_size = in_processor_info->l3_cache_size;
1307 
1308 #if HAS_CLUSTER
1309 	this_cpu_datap->cluster_master = !OSTestAndSet(this_cpu_datap->cpu_cluster_id, &cluster_initialized);
1310 #else /* HAS_CLUSTER */
1311 	this_cpu_datap->cluster_master = is_boot_cpu;
1312 #endif /* HAS_CLUSTER */
1313 	pset = pset_find(in_processor_info->cluster_id, NULL);
1314 	if (pset == NULL) {
1315 #if __AMP__
1316 		pset_cluster_type_t pset_cluster_type = this_cpu_datap->cpu_cluster_type == CLUSTER_TYPE_E ? PSET_AMP_E : PSET_AMP_P;
1317 		pset = pset_create(ml_get_boot_cluster_type() == this_cpu_datap->cpu_cluster_type ? &pset_node0 : &pset_node1, pset_cluster_type, this_cpu_datap->cpu_cluster_id, this_cpu_datap->cpu_cluster_id);
1318 		assert(pset != PROCESSOR_SET_NULL);
1319 #else /* __AMP__ */
1320 		pset_cluster_type_t pset_cluster_type = PSET_SMP;
1321 		pset = pset_create(&pset_node0, pset_cluster_type, this_cpu_datap->cpu_cluster_id, this_cpu_datap->cpu_cluster_id);
1322 		assert(pset != PROCESSOR_SET_NULL);
1323 #endif /* __AMP__ */
1324 	}
1325 	kprintf("%s>cpu_id %p cluster_id %d cpu_number %d is type %d\n", __FUNCTION__, in_processor_info->cpu_id, in_processor_info->cluster_id, this_cpu_datap->cpu_number, in_processor_info->cluster_type);
1326 
1327 	processor_t processor = PERCPU_GET_RELATIVE(processor, cpu_data, this_cpu_datap);
1328 	if (!is_boot_cpu) {
1329 		processor_init(processor, this_cpu_datap->cpu_number, pset);
1330 
1331 		if (this_cpu_datap->cpu_l2_access_penalty) {
1332 			/*
1333 			 * Cores that have a non-zero L2 access penalty compared
1334 			 * to the boot processor should be de-prioritized by the
1335 			 * scheduler, so that threads use the cores with better L2
1336 			 * preferentially.
1337 			 */
1338 			processor_set_primary(processor, master_processor);
1339 		}
1340 	}
1341 
1342 	*processor_out = processor;
1343 	*ipi_handler_out = cpu_signal_handler;
1344 #if CPMU_AIC_PMI && MONOTONIC
1345 	*pmi_handler_out = mt_cpmu_aic_pmi;
1346 #else
1347 	*pmi_handler_out = NULL;
1348 #endif /* CPMU_AIC_PMI && MONOTONIC */
1349 	if (in_processor_info->idle_tickle != (idle_tickle_t *) NULL) {
1350 		*in_processor_info->idle_tickle = (idle_tickle_t) cpu_idle_tickle;
1351 	}
1352 
1353 #if KPC
1354 	if (kpc_register_cpu(this_cpu_datap) != TRUE) {
1355 		goto processor_register_error;
1356 	}
1357 #endif /* KPC */
1358 
1359 	if (!is_boot_cpu) {
1360 		random_cpu_init(this_cpu_datap->cpu_number);
1361 		// now let next CPU register itself
1362 		OSIncrementAtomic((SInt32*)&real_ncpus);
1363 	}
1364 
1365 	return KERN_SUCCESS;
1366 
1367 processor_register_error:
1368 #if KPC
1369 	kpc_unregister_cpu(this_cpu_datap);
1370 #endif /* KPC */
1371 	if (!is_boot_cpu) {
1372 		cpu_data_free(this_cpu_datap);
1373 	}
1374 
1375 	return KERN_FAILURE;
1376 }
1377 
1378 void
ml_init_arm_debug_interface(void * in_cpu_datap,vm_offset_t virt_address)1379 ml_init_arm_debug_interface(
1380 	void * in_cpu_datap,
1381 	vm_offset_t virt_address)
1382 {
1383 	((cpu_data_t *)in_cpu_datap)->cpu_debug_interface_map = virt_address;
1384 	do_debugid();
1385 }
1386 
1387 /*
1388  *	Routine:        init_ast_check
1389  *	Function:
1390  */
1391 void
init_ast_check(__unused processor_t processor)1392 init_ast_check(
1393 	__unused processor_t processor)
1394 {
1395 }
1396 
1397 /*
1398  *	Routine:        cause_ast_check
1399  *	Function:
1400  */
1401 void
cause_ast_check(processor_t processor)1402 cause_ast_check(
1403 	processor_t processor)
1404 {
1405 	if (current_processor() != processor) {
1406 		cpu_signal(processor_to_cpu_datap(processor), SIGPast, (void *)NULL, (void *)NULL);
1407 		KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_REMOTE_AST), processor->cpu_id, 1 /* ast */, 0, 0, 0);
1408 	}
1409 }
1410 
1411 extern uint32_t cpu_idle_count;
1412 
1413 void
ml_get_power_state(boolean_t * icp,boolean_t * pidlep)1414 ml_get_power_state(boolean_t *icp, boolean_t *pidlep)
1415 {
1416 	*icp = ml_at_interrupt_context();
1417 	*pidlep = (cpu_idle_count == real_ncpus);
1418 }
1419 
1420 /*
1421  *	Routine:        ml_cause_interrupt
1422  *	Function:	Generate a fake interrupt
1423  */
1424 void
ml_cause_interrupt(void)1425 ml_cause_interrupt(void)
1426 {
1427 	return;                 /* BS_XXX */
1428 }
1429 
1430 /* Map memory map IO space */
1431 vm_offset_t
ml_io_map(vm_offset_t phys_addr,vm_size_t size)1432 ml_io_map(
1433 	vm_offset_t phys_addr,
1434 	vm_size_t size)
1435 {
1436 	return io_map(phys_addr, size, VM_WIMG_IO);
1437 }
1438 
1439 /* Map memory map IO space (with protections specified) */
1440 vm_offset_t
ml_io_map_with_prot(vm_offset_t phys_addr,vm_size_t size,vm_prot_t prot)1441 ml_io_map_with_prot(
1442 	vm_offset_t phys_addr,
1443 	vm_size_t size,
1444 	vm_prot_t prot)
1445 {
1446 	return io_map_with_prot(phys_addr, size, VM_WIMG_IO, prot);
1447 }
1448 
1449 vm_offset_t
ml_io_map_wcomb(vm_offset_t phys_addr,vm_size_t size)1450 ml_io_map_wcomb(
1451 	vm_offset_t phys_addr,
1452 	vm_size_t size)
1453 {
1454 	return io_map(phys_addr, size, VM_WIMG_WCOMB);
1455 }
1456 
1457 void
ml_io_unmap(vm_offset_t addr,vm_size_t sz)1458 ml_io_unmap(vm_offset_t addr, vm_size_t sz)
1459 {
1460 	pmap_remove(kernel_pmap, addr, addr + sz);
1461 	kmem_free(kernel_map, addr, sz);
1462 }
1463 
1464 /* boot memory allocation */
1465 vm_offset_t
ml_static_malloc(__unused vm_size_t size)1466 ml_static_malloc(
1467 	__unused vm_size_t size)
1468 {
1469 	return (vm_offset_t) NULL;
1470 }
1471 
1472 vm_map_address_t
ml_map_high_window(vm_offset_t phys_addr,vm_size_t len)1473 ml_map_high_window(
1474 	vm_offset_t     phys_addr,
1475 	vm_size_t       len)
1476 {
1477 	return pmap_map_high_window_bd(phys_addr, len, VM_PROT_READ | VM_PROT_WRITE);
1478 }
1479 
1480 vm_offset_t
ml_static_ptovirt(vm_offset_t paddr)1481 ml_static_ptovirt(
1482 	vm_offset_t paddr)
1483 {
1484 	return phystokv(paddr);
1485 }
1486 
1487 vm_offset_t
ml_static_slide(vm_offset_t vaddr)1488 ml_static_slide(
1489 	vm_offset_t vaddr)
1490 {
1491 	vm_offset_t slid_vaddr = vaddr + vm_kernel_slide;
1492 
1493 	if ((slid_vaddr < vm_kernelcache_base) || (slid_vaddr >= vm_kernelcache_top)) {
1494 		/* This is only intended for use on kernelcache addresses. */
1495 		return 0;
1496 	}
1497 
1498 	/*
1499 	 * Because the address is in the kernelcache, we can do a simple
1500 	 * slide calculation.
1501 	 */
1502 	return slid_vaddr;
1503 }
1504 
1505 vm_offset_t
ml_static_unslide(vm_offset_t vaddr)1506 ml_static_unslide(
1507 	vm_offset_t vaddr)
1508 {
1509 	if ((vaddr < vm_kernelcache_base) || (vaddr >= vm_kernelcache_top)) {
1510 		/* This is only intended for use on kernelcache addresses. */
1511 		return 0;
1512 	}
1513 
1514 	return vaddr - vm_kernel_slide;
1515 }
1516 
1517 extern tt_entry_t *arm_kva_to_tte(vm_offset_t va);
1518 
1519 kern_return_t
ml_static_protect(vm_offset_t vaddr,vm_size_t size,vm_prot_t new_prot)1520 ml_static_protect(
1521 	vm_offset_t vaddr, /* kernel virtual address */
1522 	vm_size_t size,
1523 	vm_prot_t new_prot)
1524 {
1525 	pt_entry_t    arm_prot = 0;
1526 	pt_entry_t    arm_block_prot = 0;
1527 	vm_offset_t   vaddr_cur;
1528 	ppnum_t       ppn;
1529 	kern_return_t result = KERN_SUCCESS;
1530 
1531 	if (vaddr < VM_MIN_KERNEL_ADDRESS) {
1532 		panic("ml_static_protect(): %p < %p", (void *) vaddr, (void *) VM_MIN_KERNEL_ADDRESS);
1533 		return KERN_FAILURE;
1534 	}
1535 
1536 	assert((vaddr & (PAGE_SIZE - 1)) == 0); /* must be page aligned */
1537 
1538 	if ((new_prot & VM_PROT_WRITE) && (new_prot & VM_PROT_EXECUTE)) {
1539 		panic("ml_static_protect(): WX request on %p", (void *) vaddr);
1540 	}
1541 	if (lockdown_done && (new_prot & VM_PROT_EXECUTE)) {
1542 		panic("ml_static_protect(): attempt to inject executable mapping on %p", (void *) vaddr);
1543 	}
1544 
1545 	/* Set up the protection bits, and block bits so we can validate block mappings. */
1546 	if (new_prot & VM_PROT_WRITE) {
1547 		arm_prot |= ARM_PTE_AP(AP_RWNA);
1548 		arm_block_prot |= ARM_TTE_BLOCK_AP(AP_RWNA);
1549 	} else {
1550 		arm_prot |= ARM_PTE_AP(AP_RONA);
1551 		arm_block_prot |= ARM_TTE_BLOCK_AP(AP_RONA);
1552 	}
1553 
1554 	arm_prot |= ARM_PTE_NX;
1555 	arm_block_prot |= ARM_TTE_BLOCK_NX;
1556 
1557 	if (!(new_prot & VM_PROT_EXECUTE)) {
1558 		arm_prot |= ARM_PTE_PNX;
1559 		arm_block_prot |= ARM_TTE_BLOCK_PNX;
1560 	}
1561 
1562 	for (vaddr_cur = vaddr;
1563 	    vaddr_cur < trunc_page_64(vaddr + size);
1564 	    vaddr_cur += PAGE_SIZE) {
1565 		ppn = pmap_find_phys(kernel_pmap, vaddr_cur);
1566 		if (ppn != (vm_offset_t) NULL) {
1567 			tt_entry_t      *tte2;
1568 			pt_entry_t      *pte_p;
1569 			pt_entry_t      ptmp;
1570 
1571 #if XNU_MONITOR
1572 			assert(!pmap_is_monitor(ppn));
1573 			assert(!TEST_PAGE_RATIO_4);
1574 #endif
1575 
1576 			tte2 = arm_kva_to_tte(vaddr_cur);
1577 
1578 			if (((*tte2) & ARM_TTE_TYPE_MASK) != ARM_TTE_TYPE_TABLE) {
1579 				if ((((*tte2) & ARM_TTE_TYPE_MASK) == ARM_TTE_TYPE_BLOCK) &&
1580 				    ((*tte2 & (ARM_TTE_BLOCK_NXMASK | ARM_TTE_BLOCK_PNXMASK | ARM_TTE_BLOCK_APMASK)) == arm_block_prot)) {
1581 					/*
1582 					 * We can support ml_static_protect on a block mapping if the mapping already has
1583 					 * the desired protections.  We still want to run checks on a per-page basis.
1584 					 */
1585 					continue;
1586 				}
1587 
1588 				result = KERN_FAILURE;
1589 				break;
1590 			}
1591 
1592 			pte_p = (pt_entry_t *)&((tt_entry_t*)(phystokv((*tte2) & ARM_TTE_TABLE_MASK)))[(((vaddr_cur) & ARM_TT_L3_INDEX_MASK) >> ARM_TT_L3_SHIFT)];
1593 			ptmp = *pte_p;
1594 
1595 			if ((ptmp & ARM_PTE_HINT_MASK) && ((ptmp & (ARM_PTE_APMASK | ARM_PTE_PNXMASK | ARM_PTE_NXMASK)) != arm_prot)) {
1596 				/*
1597 				 * The contiguous hint is similar to a block mapping for ml_static_protect; if the existing
1598 				 * protections do not match the desired protections, then we will fail (as we cannot update
1599 				 * this mapping without updating other mappings as well).
1600 				 */
1601 				result = KERN_FAILURE;
1602 				break;
1603 			}
1604 
1605 			__unreachable_ok_push
1606 			if (TEST_PAGE_RATIO_4) {
1607 				{
1608 					unsigned int    i;
1609 					pt_entry_t      *ptep_iter;
1610 
1611 					ptep_iter = pte_p;
1612 					for (i = 0; i < 4; i++, ptep_iter++) {
1613 						/* Note that there is a hole in the HINT sanity checking here. */
1614 						ptmp = *ptep_iter;
1615 
1616 						/* We only need to update the page tables if the protections do not match. */
1617 						if ((ptmp & (ARM_PTE_APMASK | ARM_PTE_PNXMASK | ARM_PTE_NXMASK)) != arm_prot) {
1618 							ptmp = (ptmp & ~(ARM_PTE_APMASK | ARM_PTE_PNXMASK | ARM_PTE_NXMASK)) | arm_prot;
1619 							*ptep_iter = ptmp;
1620 						}
1621 					}
1622 				}
1623 			} else {
1624 				ptmp = *pte_p;
1625 				/* We only need to update the page tables if the protections do not match. */
1626 				if ((ptmp & (ARM_PTE_APMASK | ARM_PTE_PNXMASK | ARM_PTE_NXMASK)) != arm_prot) {
1627 					ptmp = (ptmp & ~(ARM_PTE_APMASK | ARM_PTE_PNXMASK | ARM_PTE_NXMASK)) | arm_prot;
1628 					*pte_p = ptmp;
1629 				}
1630 			}
1631 			__unreachable_ok_pop
1632 		}
1633 	}
1634 
1635 	if (vaddr_cur > vaddr) {
1636 		assert(((vaddr_cur - vaddr) & 0xFFFFFFFF00000000ULL) == 0);
1637 		flush_mmu_tlb_region(vaddr, (uint32_t)(vaddr_cur - vaddr));
1638 	}
1639 
1640 
1641 	return result;
1642 }
1643 
1644 /*
1645  *	Routine:        ml_static_mfree
1646  *	Function:
1647  */
1648 void
ml_static_mfree(vm_offset_t vaddr,vm_size_t size)1649 ml_static_mfree(
1650 	vm_offset_t vaddr,
1651 	vm_size_t   size)
1652 {
1653 	vm_offset_t vaddr_cur;
1654 	ppnum_t     ppn;
1655 	uint32_t    freed_pages = 0;
1656 	uint32_t    bad_page_cnt = 0;
1657 	uint32_t    freed_kernelcache_pages = 0;
1658 
1659 #if defined(__arm64__) && (DEVELOPMENT || DEBUG)
1660 	/* For testing hitting a bad ram page */
1661 	static int count = 0;
1662 	static int bad_at_cnt = -1;
1663 	static bool first = true;
1664 
1665 	if (first) {
1666 		(void)PE_parse_boot_argn("bad_static_mfree", &bad_at_cnt, sizeof(bad_at_cnt));
1667 		first = false;
1668 	}
1669 #endif /* defined(__arm64__) && (DEVELOPMENT || DEBUG) */
1670 
1671 	/* It is acceptable (if bad) to fail to free. */
1672 	if (vaddr < VM_MIN_KERNEL_ADDRESS) {
1673 		return;
1674 	}
1675 
1676 	assert((vaddr & (PAGE_SIZE - 1)) == 0); /* must be page aligned */
1677 
1678 	for (vaddr_cur = vaddr;
1679 	    vaddr_cur < trunc_page_64(vaddr + size);
1680 	    vaddr_cur += PAGE_SIZE) {
1681 		ppn = pmap_find_phys(kernel_pmap, vaddr_cur);
1682 		if (ppn != (vm_offset_t) NULL) {
1683 			/*
1684 			 * It is not acceptable to fail to update the protections on a page
1685 			 * we will release to the VM.  We need to either panic or continue.
1686 			 * For now, we'll panic (to help flag if there is memory we can
1687 			 * reclaim).
1688 			 */
1689 			if (ml_static_protect(vaddr_cur, PAGE_SIZE, VM_PROT_WRITE | VM_PROT_READ) != KERN_SUCCESS) {
1690 				panic("Failed ml_static_mfree on %p", (void *) vaddr_cur);
1691 			}
1692 
1693 #if defined(__arm64__)
1694 			bool is_bad = pmap_is_bad_ram(ppn);
1695 #if DEVELOPMENT || DEBUG
1696 			is_bad |= (count++ == bad_at_cnt);
1697 #endif /* DEVELOPMENT || DEBUG */
1698 
1699 			if (is_bad) {
1700 				++bad_page_cnt;
1701 				vm_page_create_retired(ppn);
1702 				continue;
1703 			}
1704 #endif /* defined(__arm64__) */
1705 
1706 			vm_page_create(ppn, (ppn + 1));
1707 			freed_pages++;
1708 			if (vaddr_cur >= segLOWEST && vaddr_cur < end_kern) {
1709 				freed_kernelcache_pages++;
1710 			}
1711 		}
1712 	}
1713 	vm_page_lockspin_queues();
1714 	vm_page_wire_count -= freed_pages;
1715 	vm_page_wire_count_initial -= freed_pages;
1716 	vm_page_kernelcache_count -= freed_kernelcache_pages;
1717 	vm_page_unlock_queues();
1718 #if     DEBUG
1719 	kprintf("ml_static_mfree: Released 0x%x pages at VA %p, size:0x%llx, last ppn: 0x%x, +%d bad\n", freed_pages, (void *)vaddr, (uint64_t)size, ppn, bad_page_cnt);
1720 #endif
1721 }
1722 
1723 
1724 /* virtual to physical on wired pages */
1725 vm_offset_t
ml_vtophys(vm_offset_t vaddr)1726 ml_vtophys(vm_offset_t vaddr)
1727 {
1728 	return kvtophys(vaddr);
1729 }
1730 
1731 /*
1732  * Routine: ml_nofault_copy
1733  * Function: Perform a physical mode copy if the source and destination have
1734  * valid translations in the kernel pmap. If translations are present, they are
1735  * assumed to be wired; e.g., no attempt is made to guarantee that the
1736  * translations obtained remain valid for the duration of the copy process.
1737  */
1738 vm_size_t
ml_nofault_copy(vm_offset_t virtsrc,vm_offset_t virtdst,vm_size_t size)1739 ml_nofault_copy(vm_offset_t virtsrc, vm_offset_t virtdst, vm_size_t size)
1740 {
1741 	addr64_t        cur_phys_dst, cur_phys_src;
1742 	vm_size_t       count, nbytes = 0;
1743 
1744 	while (size > 0) {
1745 		if (!(cur_phys_src = kvtophys(virtsrc))) {
1746 			break;
1747 		}
1748 		if (!(cur_phys_dst = kvtophys(virtdst))) {
1749 			break;
1750 		}
1751 		if (!pmap_valid_address(trunc_page_64(cur_phys_dst)) ||
1752 		    !pmap_valid_address(trunc_page_64(cur_phys_src))) {
1753 			break;
1754 		}
1755 		count = PAGE_SIZE - (cur_phys_src & PAGE_MASK);
1756 		if (count > (PAGE_SIZE - (cur_phys_dst & PAGE_MASK))) {
1757 			count = PAGE_SIZE - (cur_phys_dst & PAGE_MASK);
1758 		}
1759 		if (count > size) {
1760 			count = size;
1761 		}
1762 
1763 		bcopy_phys(cur_phys_src, cur_phys_dst, count);
1764 
1765 		nbytes += count;
1766 		virtsrc += count;
1767 		virtdst += count;
1768 		size -= count;
1769 	}
1770 
1771 	return nbytes;
1772 }
1773 
1774 /*
1775  *	Routine:        ml_validate_nofault
1776  *	Function: Validate that ths address range has a valid translations
1777  *			in the kernel pmap.  If translations are present, they are
1778  *			assumed to be wired; i.e. no attempt is made to guarantee
1779  *			that the translation persist after the check.
1780  *  Returns: TRUE if the range is mapped and will not cause a fault,
1781  *			FALSE otherwise.
1782  */
1783 
1784 boolean_t
ml_validate_nofault(vm_offset_t virtsrc,vm_size_t size)1785 ml_validate_nofault(
1786 	vm_offset_t virtsrc, vm_size_t size)
1787 {
1788 	addr64_t cur_phys_src;
1789 	uint32_t count;
1790 
1791 	while (size > 0) {
1792 		if (!(cur_phys_src = kvtophys(virtsrc))) {
1793 			return FALSE;
1794 		}
1795 		if (!pmap_valid_address(trunc_page_64(cur_phys_src))) {
1796 			return FALSE;
1797 		}
1798 		count = (uint32_t)(PAGE_SIZE - (cur_phys_src & PAGE_MASK));
1799 		if (count > size) {
1800 			count = (uint32_t)size;
1801 		}
1802 
1803 		virtsrc += count;
1804 		size -= count;
1805 	}
1806 
1807 	return TRUE;
1808 }
1809 
1810 void
ml_get_bouncepool_info(vm_offset_t * phys_addr,vm_size_t * size)1811 ml_get_bouncepool_info(vm_offset_t * phys_addr, vm_size_t * size)
1812 {
1813 	*phys_addr = 0;
1814 	*size = 0;
1815 }
1816 
1817 void
active_rt_threads(__unused boolean_t active)1818 active_rt_threads(__unused boolean_t active)
1819 {
1820 }
1821 
1822 static void
cpu_qos_cb_default(__unused int urgency,__unused uint64_t qos_param1,__unused uint64_t qos_param2)1823 cpu_qos_cb_default(__unused int urgency, __unused uint64_t qos_param1, __unused uint64_t qos_param2)
1824 {
1825 	return;
1826 }
1827 
1828 cpu_qos_update_t cpu_qos_update = cpu_qos_cb_default;
1829 
1830 void
cpu_qos_update_register(cpu_qos_update_t cpu_qos_cb)1831 cpu_qos_update_register(cpu_qos_update_t cpu_qos_cb)
1832 {
1833 	if (cpu_qos_cb != NULL) {
1834 		cpu_qos_update = cpu_qos_cb;
1835 	} else {
1836 		cpu_qos_update = cpu_qos_cb_default;
1837 	}
1838 }
1839 
1840 void
thread_tell_urgency(thread_urgency_t urgency,uint64_t rt_period,uint64_t rt_deadline,uint64_t sched_latency __unused,__unused thread_t nthread)1841 thread_tell_urgency(thread_urgency_t urgency, uint64_t rt_period, uint64_t rt_deadline, uint64_t sched_latency __unused, __unused thread_t nthread)
1842 {
1843 	SCHED_DEBUG_PLATFORM_KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_URGENCY) | DBG_FUNC_START, urgency, rt_period, rt_deadline, sched_latency, 0);
1844 
1845 	cpu_qos_update((int)urgency, rt_period, rt_deadline);
1846 
1847 	SCHED_DEBUG_PLATFORM_KERNEL_DEBUG_CONSTANT(MACHDBG_CODE(DBG_MACH_SCHED, MACH_URGENCY) | DBG_FUNC_END, urgency, rt_period, rt_deadline, 0, 0);
1848 }
1849 
1850 void
machine_run_count(__unused uint32_t count)1851 machine_run_count(__unused uint32_t count)
1852 {
1853 }
1854 
1855 processor_t
machine_choose_processor(__unused processor_set_t pset,processor_t processor)1856 machine_choose_processor(__unused processor_set_t pset, processor_t processor)
1857 {
1858 	return processor;
1859 }
1860 
1861 #if KASAN
1862 vm_offset_t ml_stack_base(void);
1863 vm_size_t ml_stack_size(void);
1864 
1865 vm_offset_t
ml_stack_base(void)1866 ml_stack_base(void)
1867 {
1868 	uintptr_t local = (uintptr_t) &local;
1869 	vm_offset_t     intstack_top_ptr;
1870 
1871 	intstack_top_ptr = getCpuDatap()->intstack_top;
1872 	if ((local < intstack_top_ptr) && (local > intstack_top_ptr - INTSTACK_SIZE)) {
1873 		return intstack_top_ptr - INTSTACK_SIZE;
1874 	} else {
1875 		return current_thread()->kernel_stack;
1876 	}
1877 }
1878 vm_size_t
ml_stack_size(void)1879 ml_stack_size(void)
1880 {
1881 	uintptr_t local = (uintptr_t) &local;
1882 	vm_offset_t     intstack_top_ptr;
1883 
1884 	intstack_top_ptr = getCpuDatap()->intstack_top;
1885 	if ((local < intstack_top_ptr) && (local > intstack_top_ptr - INTSTACK_SIZE)) {
1886 		return INTSTACK_SIZE;
1887 	} else {
1888 		return kernel_stack_size;
1889 	}
1890 }
1891 #endif
1892 
1893 #ifdef CONFIG_KCOV
1894 
1895 kcov_cpu_data_t *
current_kcov_data(void)1896 current_kcov_data(void)
1897 {
1898 	return &current_cpu_datap()->cpu_kcov_data;
1899 }
1900 
1901 kcov_cpu_data_t *
cpu_kcov_data(int cpuid)1902 cpu_kcov_data(int cpuid)
1903 {
1904 	return &cpu_datap(cpuid)->cpu_kcov_data;
1905 }
1906 
1907 #endif /* CONFIG_KCOV */
1908 
1909 boolean_t
machine_timeout_suspended(void)1910 machine_timeout_suspended(void)
1911 {
1912 	return FALSE;
1913 }
1914 
1915 kern_return_t
ml_interrupt_prewarm(__unused uint64_t deadline)1916 ml_interrupt_prewarm(__unused uint64_t deadline)
1917 {
1918 	return KERN_FAILURE;
1919 }
1920 
1921 /*
1922  * Assumes fiq, irq disabled.
1923  */
1924 void
ml_set_decrementer(uint32_t dec_value)1925 ml_set_decrementer(uint32_t dec_value)
1926 {
1927 	cpu_data_t      *cdp = getCpuDatap();
1928 
1929 	assert(ml_get_interrupts_enabled() == FALSE);
1930 	cdp->cpu_decrementer = dec_value;
1931 
1932 	if (cdp->cpu_set_decrementer_func) {
1933 		cdp->cpu_set_decrementer_func(dec_value);
1934 	} else {
1935 		__builtin_arm_wsr64("CNTV_TVAL_EL0", (uint64_t)dec_value);
1936 	}
1937 }
1938 
1939 
1940 uint64_t
ml_get_hwclock()1941 ml_get_hwclock()
1942 {
1943 	uint64_t timebase;
1944 
1945 	// ISB required by ARMV7C.b section B8.1.2 & ARMv8 section D6.1.2
1946 	// "Reads of CNT[PV]CT[_EL0] can occur speculatively and out of order relative
1947 	// to other instructions executed on the same processor."
1948 	__builtin_arm_isb(ISB_SY);
1949 	timebase = __builtin_arm_rsr64("CNTVCT_EL0");
1950 
1951 	return timebase;
1952 }
1953 
1954 uint64_t
ml_get_timebase()1955 ml_get_timebase()
1956 {
1957 	uint64_t clock, timebase;
1958 
1959 	//the retry is for the case where S2R catches us in the middle of this. see rdar://77019633
1960 	do {
1961 		timebase = getCpuDatap()->cpu_base_timebase;
1962 		os_compiler_barrier();
1963 		clock = ml_get_hwclock();
1964 		os_compiler_barrier();
1965 	} while (getCpuDatap()->cpu_base_timebase != timebase);
1966 
1967 	return clock + timebase;
1968 }
1969 
1970 /*
1971  * Get the speculative timebase without an ISB.
1972  */
1973 uint64_t
ml_get_speculative_timebase()1974 ml_get_speculative_timebase()
1975 {
1976 	uint64_t clock, timebase;
1977 
1978 	//the retry is for the case where S2R catches us in the middle of this. see rdar://77019633&77697482
1979 	do {
1980 		timebase = getCpuDatap()->cpu_base_timebase;
1981 		os_compiler_barrier();
1982 		clock = __builtin_arm_rsr64("CNTVCT_EL0");
1983 
1984 		os_compiler_barrier();
1985 	} while (getCpuDatap()->cpu_base_timebase != timebase);
1986 
1987 	return clock + timebase;
1988 }
1989 
1990 uint64_t
ml_get_timebase_entropy(void)1991 ml_get_timebase_entropy(void)
1992 {
1993 	return ml_get_speculative_timebase();
1994 }
1995 
1996 uint32_t
ml_get_decrementer()1997 ml_get_decrementer()
1998 {
1999 	cpu_data_t *cdp = getCpuDatap();
2000 	uint32_t dec;
2001 
2002 	assert(ml_get_interrupts_enabled() == FALSE);
2003 
2004 	if (cdp->cpu_get_decrementer_func) {
2005 		dec = cdp->cpu_get_decrementer_func();
2006 	} else {
2007 		uint64_t wide_val;
2008 
2009 		wide_val = __builtin_arm_rsr64("CNTV_TVAL_EL0");
2010 		dec = (uint32_t)wide_val;
2011 		assert(wide_val == (uint64_t)dec);
2012 	}
2013 
2014 	return dec;
2015 }
2016 
2017 boolean_t
ml_get_timer_pending()2018 ml_get_timer_pending()
2019 {
2020 	uint64_t cntv_ctl = __builtin_arm_rsr64("CNTV_CTL_EL0");
2021 	return ((cntv_ctl & CNTV_CTL_EL0_ISTATUS) != 0) ? TRUE : FALSE;
2022 }
2023 
2024 __attribute__((noreturn))
2025 void
platform_syscall(arm_saved_state_t * state)2026 platform_syscall(arm_saved_state_t *state)
2027 {
2028 	uint32_t code;
2029 
2030 #define platform_syscall_kprintf(x...) /* kprintf("platform_syscall: " x) */
2031 
2032 	code = (uint32_t)get_saved_state_reg(state, 3);
2033 
2034 	KDBG(MACHDBG_CODE(DBG_MACH_MACHDEP_EXCP_SC_ARM, code) | DBG_FUNC_START,
2035 	    get_saved_state_reg(state, 0),
2036 	    get_saved_state_reg(state, 1),
2037 	    get_saved_state_reg(state, 2));
2038 
2039 	switch (code) {
2040 	case 2:
2041 		/* set cthread */
2042 		platform_syscall_kprintf("set cthread self.\n");
2043 		thread_set_cthread_self(get_saved_state_reg(state, 0));
2044 		break;
2045 	case 3:
2046 		/* get cthread */
2047 		platform_syscall_kprintf("get cthread self.\n");
2048 		set_saved_state_reg(state, 0, thread_get_cthread_self());
2049 		break;
2050 	case 0: /* I-Cache flush (removed) */
2051 	case 1: /* D-Cache flush (removed) */
2052 	default:
2053 		platform_syscall_kprintf("unknown: %d\n", code);
2054 		break;
2055 	}
2056 
2057 	KDBG(MACHDBG_CODE(DBG_MACH_MACHDEP_EXCP_SC_ARM, code) | DBG_FUNC_END,
2058 	    get_saved_state_reg(state, 0));
2059 
2060 	thread_exception_return();
2061 }
2062 
2063 static void
_enable_timebase_event_stream(uint32_t bit_index)2064 _enable_timebase_event_stream(uint32_t bit_index)
2065 {
2066 	uint64_t cntkctl; /* One wants to use 32 bits, but "mrs" prefers it this way */
2067 
2068 	if (bit_index >= 64) {
2069 		panic("%s: invalid bit index (%u)", __FUNCTION__, bit_index);
2070 	}
2071 
2072 	__asm__ volatile ("mrs	%0, CNTKCTL_EL1" : "=r"(cntkctl));
2073 
2074 	cntkctl |= (bit_index << CNTKCTL_EL1_EVENTI_SHIFT);
2075 	cntkctl |= CNTKCTL_EL1_EVNTEN;
2076 	cntkctl |= CNTKCTL_EL1_EVENTDIR; /* 1->0; why not? */
2077 
2078 	/*
2079 	 * If the SOC supports it (and it isn't broken), enable
2080 	 * EL0 access to the timebase registers.
2081 	 */
2082 	if (user_timebase_type() != USER_TIMEBASE_NONE) {
2083 		cntkctl |= (CNTKCTL_EL1_PL0PCTEN | CNTKCTL_EL1_PL0VCTEN);
2084 	}
2085 
2086 	__builtin_arm_wsr64("CNTKCTL_EL1", cntkctl);
2087 }
2088 
2089 /*
2090  * Turn timer on, unmask that interrupt.
2091  */
2092 static void
_enable_virtual_timer(void)2093 _enable_virtual_timer(void)
2094 {
2095 	uint64_t cntvctl = CNTV_CTL_EL0_ENABLE; /* One wants to use 32 bits, but "mrs" prefers it this way */
2096 
2097 	__builtin_arm_wsr64("CNTV_CTL_EL0", cntvctl);
2098 	/* disable the physical timer as a precaution, as its registers reset to architecturally unknown values */
2099 	__builtin_arm_wsr64("CNTP_CTL_EL0", CNTP_CTL_EL0_IMASKED);
2100 }
2101 
2102 void
fiq_context_init(boolean_t enable_fiq __unused)2103 fiq_context_init(boolean_t enable_fiq __unused)
2104 {
2105 	/* Interrupts still disabled. */
2106 	assert(ml_get_interrupts_enabled() == FALSE);
2107 	_enable_virtual_timer();
2108 }
2109 
2110 void
wfe_timeout_init(void)2111 wfe_timeout_init(void)
2112 {
2113 	_enable_timebase_event_stream(arm64_eventi);
2114 }
2115 
2116 /**
2117  * Configures, but does not enable, the WFE event stream. The event stream
2118  * generates an event at a set interval to act as a timeout for WFEs.
2119  *
2120  * This function sets the static global variable arm64_eventi to be the proper
2121  * bit index for the CNTKCTL_EL1.EVENTI field to generate events at the correct
2122  * period (1us unless specified by the "wfe_events_sec" boot-arg). arm64_eventi
2123  * is used by wfe_timeout_init to actually poke the registers and enable the
2124  * event stream.
2125  *
2126  * The CNTKCTL_EL1.EVENTI field contains the index of the bit of CNTVCT_EL0 that
2127  * is the trigger for the system to generate an event. The trigger can occur on
2128  * either the rising or falling edge of the bit depending on the value of
2129  * CNTKCTL_EL1.EVNTDIR. This is arbitrary for our purposes, so we use the
2130  * falling edge (1->0) transition to generate events.
2131  */
2132 void
wfe_timeout_configure(void)2133 wfe_timeout_configure(void)
2134 {
2135 	/* Could fill in our own ops here, if we needed them */
2136 	uint64_t        ticks_per_sec, ticks_per_event, events_per_sec = 0;
2137 	uint32_t        bit_index;
2138 
2139 	if (PE_parse_boot_argn("wfe_events_sec", &events_per_sec, sizeof(events_per_sec))) {
2140 		if (events_per_sec <= 0) {
2141 			events_per_sec = 1;
2142 		} else if (events_per_sec > USEC_PER_SEC) {
2143 			events_per_sec = USEC_PER_SEC;
2144 		}
2145 	} else {
2146 		events_per_sec = USEC_PER_SEC;
2147 	}
2148 	ticks_per_sec = gPEClockFrequencyInfo.timebase_frequency_hz;
2149 	ticks_per_event = ticks_per_sec / events_per_sec;
2150 
2151 	/* Bit index of next power of two greater than ticks_per_event */
2152 	bit_index = flsll(ticks_per_event) - 1;
2153 	/* Round up to next power of two if ticks_per_event is initially power of two */
2154 	if ((ticks_per_event & ((1 << bit_index) - 1)) != 0) {
2155 		bit_index++;
2156 	}
2157 
2158 	/*
2159 	 * The timer can only trigger on rising or falling edge, not both; we don't
2160 	 * care which we trigger on, but we do need to adjust which bit we are
2161 	 * interested in to account for this.
2162 	 *
2163 	 * In particular, we set CNTKCTL_EL1.EVENTDIR to trigger events on the
2164 	 * falling edge of the given bit. Therefore, we must decrement the bit index
2165 	 * by one as when the bit before the one we care about makes a 1 -> 0
2166 	 * transition, the bit we care about makes a 0 -> 1 transition.
2167 	 *
2168 	 * For example if we want an event generated every 8 ticks (if we calculated
2169 	 * a bit_index of 3), we would want the event to be generated whenever the
2170 	 * lower four bits of the counter transition from 0b0111 -> 0b1000. We can
2171 	 * see that the bit at index 2 makes a falling transition in this scenario,
2172 	 * so we would want EVENTI to be 2 instead of 3.
2173 	 */
2174 	if (bit_index != 0) {
2175 		bit_index--;
2176 	}
2177 
2178 	arm64_eventi = bit_index;
2179 }
2180 
2181 boolean_t
ml_delay_should_spin(uint64_t interval)2182 ml_delay_should_spin(uint64_t interval)
2183 {
2184 	cpu_data_t     *cdp = getCpuDatap();
2185 
2186 	if (cdp->cpu_idle_latency) {
2187 		return (interval < cdp->cpu_idle_latency) ? TRUE : FALSE;
2188 	} else {
2189 		/*
2190 		 * Early boot, latency is unknown. Err on the side of blocking,
2191 		 * which should always be safe, even if slow
2192 		 */
2193 		return FALSE;
2194 	}
2195 }
2196 
2197 boolean_t
ml_thread_is64bit(thread_t thread)2198 ml_thread_is64bit(thread_t thread)
2199 {
2200 	return thread_is_64bit_addr(thread);
2201 }
2202 
2203 void
ml_delay_on_yield(void)2204 ml_delay_on_yield(void)
2205 {
2206 #if DEVELOPMENT || DEBUG
2207 	if (yield_delay_us) {
2208 		delay(yield_delay_us);
2209 	}
2210 #endif
2211 }
2212 
2213 void
ml_timer_evaluate(void)2214 ml_timer_evaluate(void)
2215 {
2216 }
2217 
2218 boolean_t
ml_timer_forced_evaluation(void)2219 ml_timer_forced_evaluation(void)
2220 {
2221 	return FALSE;
2222 }
2223 
2224 uint64_t
ml_energy_stat(thread_t t)2225 ml_energy_stat(thread_t t)
2226 {
2227 	return t->machine.energy_estimate_nj;
2228 }
2229 
2230 
2231 void
ml_gpu_stat_update(__unused uint64_t gpu_ns_delta)2232 ml_gpu_stat_update(__unused uint64_t gpu_ns_delta)
2233 {
2234 	/*
2235 	 * For now: update the resource coalition stats of the
2236 	 * current thread's coalition
2237 	 */
2238 	task_coalition_update_gpu_stats(current_task(), gpu_ns_delta);
2239 }
2240 
2241 uint64_t
ml_gpu_stat(__unused thread_t t)2242 ml_gpu_stat(__unused thread_t t)
2243 {
2244 	return 0;
2245 }
2246 
2247 #if !CONFIG_SKIP_PRECISE_USER_KERNEL_TIME || HAS_FAST_CNTVCT
2248 
2249 static void
timer_state_event(boolean_t switch_to_kernel)2250 timer_state_event(boolean_t switch_to_kernel)
2251 {
2252 	thread_t thread = current_thread();
2253 	if (!thread->precise_user_kernel_time) {
2254 		return;
2255 	}
2256 
2257 	processor_t pd = current_processor();
2258 	uint64_t now = ml_get_speculative_timebase();
2259 
2260 	timer_stop(pd->current_state, now);
2261 	pd->current_state = (switch_to_kernel) ? &pd->system_state : &pd->user_state;
2262 	timer_start(pd->current_state, now);
2263 
2264 	timer_stop(pd->thread_timer, now);
2265 	pd->thread_timer = (switch_to_kernel) ? &thread->system_timer : &thread->user_timer;
2266 	timer_start(pd->thread_timer, now);
2267 }
2268 
2269 void
timer_state_event_user_to_kernel(void)2270 timer_state_event_user_to_kernel(void)
2271 {
2272 	timer_state_event(TRUE);
2273 }
2274 
2275 void
timer_state_event_kernel_to_user(void)2276 timer_state_event_kernel_to_user(void)
2277 {
2278 	timer_state_event(FALSE);
2279 }
2280 #endif /* !CONFIG_SKIP_PRECISE_USER_KERNEL_TIME || HAS_FAST_CNTVCT */
2281 
2282 thread_t
current_thread(void)2283 current_thread(void)
2284 {
2285 	return current_thread_fast();
2286 }
2287 
2288 typedef struct{
2289 	ex_cb_t         cb;
2290 	void            *refcon;
2291 }
2292 ex_cb_info_t;
2293 
2294 ex_cb_info_t ex_cb_info[EXCB_CLASS_MAX];
2295 
2296 /*
2297  * Callback registration
2298  * Currently we support only one registered callback per class but
2299  * it should be possible to support more callbacks
2300  */
2301 kern_return_t
ex_cb_register(ex_cb_class_t cb_class,ex_cb_t cb,void * refcon)2302 ex_cb_register(
2303 	ex_cb_class_t   cb_class,
2304 	ex_cb_t                 cb,
2305 	void                    *refcon)
2306 {
2307 	ex_cb_info_t *pInfo = &ex_cb_info[cb_class];
2308 
2309 	if ((NULL == cb) || (cb_class >= EXCB_CLASS_MAX)) {
2310 		return KERN_INVALID_VALUE;
2311 	}
2312 
2313 	if (NULL == pInfo->cb) {
2314 		pInfo->cb = cb;
2315 		pInfo->refcon = refcon;
2316 		return KERN_SUCCESS;
2317 	}
2318 	return KERN_FAILURE;
2319 }
2320 
2321 /*
2322  * Called internally by platform kernel to invoke the registered callback for class
2323  */
2324 ex_cb_action_t
ex_cb_invoke(ex_cb_class_t cb_class,vm_offset_t far)2325 ex_cb_invoke(
2326 	ex_cb_class_t   cb_class,
2327 	vm_offset_t             far)
2328 {
2329 	ex_cb_info_t *pInfo = &ex_cb_info[cb_class];
2330 	ex_cb_state_t state = {far};
2331 
2332 	if (cb_class >= EXCB_CLASS_MAX) {
2333 		panic("Invalid exception callback class 0x%x", cb_class);
2334 	}
2335 
2336 	if (pInfo->cb) {
2337 		return pInfo->cb(cb_class, pInfo->refcon, &state);
2338 	}
2339 	return EXCB_ACTION_NONE;
2340 }
2341 
2342 #if defined(HAS_APPLE_PAC)
2343 void
ml_task_set_disable_user_jop(task_t task,uint8_t disable_user_jop)2344 ml_task_set_disable_user_jop(task_t task, uint8_t disable_user_jop)
2345 {
2346 	assert(task);
2347 	task->disable_user_jop = disable_user_jop;
2348 }
2349 
2350 void
ml_thread_set_disable_user_jop(thread_t thread,uint8_t disable_user_jop)2351 ml_thread_set_disable_user_jop(thread_t thread, uint8_t disable_user_jop)
2352 {
2353 	assert(thread);
2354 	thread->machine.disable_user_jop = disable_user_jop;
2355 }
2356 
2357 void
ml_task_set_rop_pid(task_t task,task_t parent_task,boolean_t inherit)2358 ml_task_set_rop_pid(task_t task, task_t parent_task, boolean_t inherit)
2359 {
2360 	if (inherit) {
2361 		task->rop_pid = parent_task->rop_pid;
2362 	} else {
2363 		task->rop_pid = early_random();
2364 	}
2365 }
2366 
2367 /**
2368  * jop_pid may be inherited from the parent task or generated inside the shared
2369  * region.  Unfortunately these two parameters are available at very different
2370  * times during task creation, so we need to split this into two steps.
2371  */
2372 void
ml_task_set_jop_pid(task_t task,task_t parent_task,boolean_t inherit)2373 ml_task_set_jop_pid(task_t task, task_t parent_task, boolean_t inherit)
2374 {
2375 	if (inherit) {
2376 		task->jop_pid = parent_task->jop_pid;
2377 	} else {
2378 		task->jop_pid = ml_default_jop_pid();
2379 	}
2380 }
2381 
2382 void
ml_task_set_jop_pid_from_shared_region(task_t task)2383 ml_task_set_jop_pid_from_shared_region(task_t task)
2384 {
2385 	vm_shared_region_t sr = vm_shared_region_get(task);
2386 	/*
2387 	 * If there's no shared region, we can assign the key arbitrarily.  This
2388 	 * typically happens when Mach-O image activation failed part of the way
2389 	 * through, and this task is in the middle of dying with SIGKILL anyway.
2390 	 */
2391 	if (__improbable(!sr)) {
2392 		task->jop_pid = early_random();
2393 		return;
2394 	}
2395 	vm_shared_region_deallocate(sr);
2396 
2397 	/*
2398 	 * Similarly we have to worry about jetsam having killed the task and
2399 	 * already cleared the shared_region_id.
2400 	 */
2401 	task_lock(task);
2402 	if (task->shared_region_id != NULL) {
2403 		task->jop_pid = shared_region_find_key(task->shared_region_id);
2404 	} else {
2405 		task->jop_pid = early_random();
2406 	}
2407 	task_unlock(task);
2408 }
2409 
2410 void
ml_thread_set_jop_pid(thread_t thread,task_t task)2411 ml_thread_set_jop_pid(thread_t thread, task_t task)
2412 {
2413 	thread->machine.jop_pid = task->jop_pid;
2414 }
2415 #endif /* defined(HAS_APPLE_PAC) */
2416 
2417 #if defined(HAS_APPLE_PAC)
2418 #define _ml_auth_ptr_unchecked(_ptr, _suffix, _modifier) \
2419 	asm volatile ("aut" #_suffix " %[ptr], %[modifier]" : [ptr] "+r"(_ptr) : [modifier] "r"(_modifier));
2420 
2421 /**
2422  * Authenticates a signed pointer without trapping on failure.
2423  *
2424  * @warning This function must be called with interrupts disabled.
2425  *
2426  * @warning Pointer authentication failure should normally be treated as a fatal
2427  * error.  This function is intended for a handful of callers that cannot panic
2428  * on failure, and that understand the risks in handling a poisoned return
2429  * value.  Other code should generally use the trapping variant
2430  * ptrauth_auth_data() instead.
2431  *
2432  * @param ptr the pointer to authenticate
2433  * @param key which key to use for authentication
2434  * @param modifier a modifier to mix into the key
2435  * @return an authenticated version of ptr, possibly with poison bits set
2436  */
2437 void *
ml_auth_ptr_unchecked(void * ptr,ptrauth_key key,uint64_t modifier)2438 ml_auth_ptr_unchecked(void *ptr, ptrauth_key key, uint64_t modifier)
2439 {
2440 	switch (key & 0x3) {
2441 	case ptrauth_key_asia:
2442 		_ml_auth_ptr_unchecked(ptr, ia, modifier);
2443 		break;
2444 	case ptrauth_key_asib:
2445 		_ml_auth_ptr_unchecked(ptr, ib, modifier);
2446 		break;
2447 	case ptrauth_key_asda:
2448 		_ml_auth_ptr_unchecked(ptr, da, modifier);
2449 		break;
2450 	case ptrauth_key_asdb:
2451 		_ml_auth_ptr_unchecked(ptr, db, modifier);
2452 		break;
2453 	}
2454 
2455 	return ptr;
2456 }
2457 #endif /* defined(HAS_APPLE_PAC) */
2458 
2459 #ifdef CONFIG_XNUPOST
2460 void
ml_expect_fault_begin(expected_fault_handler_t expected_fault_handler,uintptr_t expected_fault_addr)2461 ml_expect_fault_begin(expected_fault_handler_t expected_fault_handler, uintptr_t expected_fault_addr)
2462 {
2463 	thread_t thread = current_thread();
2464 	thread->machine.expected_fault_handler = expected_fault_handler;
2465 	thread->machine.expected_fault_addr = expected_fault_addr;
2466 }
2467 
2468 void
ml_expect_fault_end(void)2469 ml_expect_fault_end(void)
2470 {
2471 	thread_t thread = current_thread();
2472 	thread->machine.expected_fault_handler = NULL;
2473 	thread->machine.expected_fault_addr = 0;
2474 }
2475 #endif /* CONFIG_XNUPOST */
2476 
2477 void
ml_hibernate_active_pre(void)2478 ml_hibernate_active_pre(void)
2479 {
2480 #if HIBERNATION
2481 	if (kIOHibernateStateWakingFromHibernate == gIOHibernateState) {
2482 
2483 		hibernate_rebuild_vm_structs();
2484 	}
2485 #endif /* HIBERNATION */
2486 }
2487 
2488 void
ml_hibernate_active_post(void)2489 ml_hibernate_active_post(void)
2490 {
2491 #if HIBERNATION
2492 	if (kIOHibernateStateWakingFromHibernate == gIOHibernateState) {
2493 		hibernate_machine_init();
2494 		hibernate_vm_lock_end();
2495 		current_cpu_datap()->cpu_hibernate = 0;
2496 	}
2497 #endif /* HIBERNATION */
2498 }
2499 
2500 /**
2501  * Return back a machine-dependent array of address space regions that should be
2502  * reserved by the VM (pre-mapped in the address space). This will prevent user
2503  * processes from allocating or deallocating from within these regions.
2504  *
2505  * @param vm_is64bit True if the process has a 64-bit address space.
2506  * @param regions An out parameter representing an array of regions to reserve.
2507  *
2508  * @return The number of reserved regions returned through `regions`.
2509  */
2510 size_t
ml_get_vm_reserved_regions(bool vm_is64bit,struct vm_reserved_region ** regions)2511 ml_get_vm_reserved_regions(bool vm_is64bit, struct vm_reserved_region **regions)
2512 {
2513 	assert(regions != NULL);
2514 
2515 	/**
2516 	 * Reserved regions only apply to 64-bit address spaces. This is because
2517 	 * we only expect to grow the maximum user VA address on 64-bit address spaces
2518 	 * (we've essentially already reached the max for 32-bit spaces). The reserved
2519 	 * regions should safely fall outside of the max user VA for 32-bit processes.
2520 	 */
2521 	if (vm_is64bit) {
2522 		*regions = vm_reserved_regions;
2523 		return ARRAY_COUNT(vm_reserved_regions);
2524 	} else {
2525 		/* Don't reserve any VA regions on arm64_32 processes. */
2526 		*regions = NULL;
2527 		return 0;
2528 	}
2529 }
2530 /* These WFE recommendations are expected to be updated on a relatively
2531  * infrequent cadence, possibly from a different cluster, hence
2532  * false cacheline sharing isn't expected to be material
2533  */
2534 static uint64_t arm64_cluster_wfe_recs[MAX_CPU_CLUSTERS];
2535 
2536 uint32_t
ml_update_cluster_wfe_recommendation(uint32_t wfe_cluster_id,uint64_t wfe_timeout_abstime_interval,__unused uint64_t wfe_hint_flags)2537 ml_update_cluster_wfe_recommendation(uint32_t wfe_cluster_id, uint64_t wfe_timeout_abstime_interval, __unused uint64_t wfe_hint_flags)
2538 {
2539 	assert(wfe_cluster_id < MAX_CPU_CLUSTERS);
2540 	assert(wfe_timeout_abstime_interval <= ml_wfe_hint_max_interval);
2541 	os_atomic_store(&arm64_cluster_wfe_recs[wfe_cluster_id], wfe_timeout_abstime_interval, relaxed);
2542 	return 0; /* Success */
2543 }
2544 
2545 #if DEVELOPMENT || DEBUG
2546 int wfe_rec_max = 0;
2547 int wfe_rec_none = 0;
2548 uint64_t wfe_rec_override_mat = 0;
2549 uint64_t wfe_rec_clamp = 0;
2550 #endif
2551 
2552 uint64_t
ml_cluster_wfe_timeout(uint32_t wfe_cluster_id)2553 ml_cluster_wfe_timeout(uint32_t wfe_cluster_id)
2554 {
2555 	/* This and its consumer does not synchronize vis-a-vis updates
2556 	 * of the recommendation; races are acceptable.
2557 	 */
2558 	uint64_t wfet = os_atomic_load(&arm64_cluster_wfe_recs[wfe_cluster_id], relaxed);
2559 #if DEVELOPMENT || DEBUG
2560 	if (wfe_rec_clamp) {
2561 		wfet = MIN(wfe_rec_clamp, wfet);
2562 	}
2563 
2564 	if (wfe_rec_max) {
2565 		for (int i = 0; i < MAX_CPU_CLUSTERS; i++) {
2566 			if (arm64_cluster_wfe_recs[i] > wfet) {
2567 				wfet = arm64_cluster_wfe_recs[i];
2568 			}
2569 		}
2570 	}
2571 
2572 	if (wfe_rec_none) {
2573 		wfet = 0;
2574 	}
2575 
2576 	if (wfe_rec_override_mat) {
2577 		wfet = wfe_rec_override_mat;
2578 	}
2579 #endif
2580 	return wfet;
2581 }
2582