xref: /freebsd/sys/arm64/arm64/machdep.c (revision 32bb6a6925c02e26cbb113789280ebb4bff54dd2)
1 /*-
2  * Copyright (c) 2014 Andrew Turner
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  */
27 
28 #include "opt_acpi.h"
29 #include "opt_kstack_pages.h"
30 #include "opt_platform.h"
31 #include "opt_ddb.h"
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/asan.h>
36 #include <sys/buf.h>
37 #include <sys/bus.h>
38 #include <sys/cons.h>
39 #include <sys/cpu.h>
40 #include <sys/csan.h>
41 #include <sys/devmap.h>
42 #include <sys/efi.h>
43 #include <sys/efi_map.h>
44 #include <sys/exec.h>
45 #include <sys/imgact.h>
46 #include <sys/kdb.h>
47 #include <sys/kernel.h>
48 #include <sys/ktr.h>
49 #include <sys/limits.h>
50 #include <sys/linker.h>
51 #include <sys/msan.h>
52 #include <sys/msgbuf.h>
53 #include <sys/pcpu.h>
54 #include <sys/physmem.h>
55 #include <sys/proc.h>
56 #include <sys/ptrace.h>
57 #include <sys/reboot.h>
58 #include <sys/reg.h>
59 #include <sys/rwlock.h>
60 #include <sys/sched.h>
61 #include <sys/signalvar.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/sysent.h>
64 #include <sys/sysproto.h>
65 #include <sys/ucontext.h>
66 #include <sys/vdso.h>
67 #include <sys/vmmeter.h>
68 
69 #include <vm/vm.h>
70 #include <vm/vm_param.h>
71 #include <vm/vm_kern.h>
72 #include <vm/vm_object.h>
73 #include <vm/vm_page.h>
74 #include <vm/vm_phys.h>
75 #include <vm/pmap.h>
76 #include <vm/vm_map.h>
77 #include <vm/vm_pager.h>
78 
79 #include <machine/armreg.h>
80 #include <machine/cpu.h>
81 #include <machine/cpu_feat.h>
82 #include <machine/debug_monitor.h>
83 #include <machine/hypervisor.h>
84 #include <machine/kdb.h>
85 #include <machine/machdep.h>
86 #include <machine/metadata.h>
87 #include <machine/md_var.h>
88 #include <machine/pcb.h>
89 #include <machine/undefined.h>
90 #include <machine/vmparam.h>
91 
92 #ifdef VFP
93 #include <machine/vfp.h>
94 #endif
95 
96 #ifdef DEV_ACPI
97 #include <contrib/dev/acpica/include/acpi.h>
98 #include <machine/acpica_machdep.h>
99 #endif
100 
101 #ifdef FDT
102 #include <dev/fdt/fdt_common.h>
103 #include <dev/ofw/openfirm.h>
104 #endif
105 
106 #include <dev/smbios/smbios.h>
107 
108 _Static_assert(sizeof(struct pcb) == 1248, "struct pcb is incorrect size");
109 _Static_assert(offsetof(struct pcb, pcb_fpusaved) == 136,
110     "pcb_fpusaved changed offset");
111 _Static_assert(offsetof(struct pcb, pcb_fpustate) == 192,
112     "pcb_fpustate changed offset");
113 
114 enum arm64_bus arm64_bus_method = ARM64_BUS_NONE;
115 
116 /*
117  * XXX: The .bss is assumed to be in the boot CPU NUMA domain. If not we
118  * could relocate this, but will need to keep the same virtual address as
119  * it's reverenced by the EARLY_COUNTER macro.
120  */
121 struct pcpu pcpu0;
122 
123 #if defined(PERTHREAD_SSP)
124 /*
125  * The boot SSP canary. Will be replaced with a per-thread canary when
126  * scheduling has started.
127  */
128 uintptr_t boot_canary = 0x49a2d892bc05a0b1ul;
129 #endif
130 
131 static struct trapframe proc0_tf;
132 
133 int early_boot = 1;
134 int cold = 1;
135 static int boot_el;
136 
137 struct kva_md_info kmi;
138 
139 int64_t dczva_line_size;	/* The size of cache line the dc zva zeroes */
140 int has_pan;
141 
142 #if defined(SOCDEV_PA)
143 /*
144  * This is the virtual address used to access SOCDEV_PA. As it's set before
145  * .bss is cleared we need to ensure it's preserved. To do this use
146  * __read_mostly as it's only ever set once but read in the putc functions.
147  */
148 uintptr_t socdev_va __read_mostly;
149 #endif
150 
151 /*
152  * Physical address of the EFI System Table. Stashed from the metadata hints
153  * passed into the kernel and used by the EFI code to call runtime services.
154  */
155 vm_paddr_t efi_systbl_phys;
156 static struct efi_map_header *efihdr;
157 
158 /* pagezero_* implementations are provided in support.S */
159 void pagezero_simple(void *);
160 void pagezero_cache(void *);
161 
162 /* pagezero_simple is default pagezero */
163 void (*pagezero)(void *p) = pagezero_simple;
164 
165 int (*apei_nmi)(void);
166 
167 #if defined(PERTHREAD_SSP_WARNING)
168 static void
print_ssp_warning(void * data __unused)169 print_ssp_warning(void *data __unused)
170 {
171 	printf("WARNING: Per-thread SSP is enabled but the compiler is too old to support it\n");
172 }
173 SYSINIT(ssp_warn, SI_SUB_COPYRIGHT, SI_ORDER_ANY, print_ssp_warning, NULL);
174 SYSINIT(ssp_warn2, SI_SUB_LAST, SI_ORDER_ANY, print_ssp_warning, NULL);
175 #endif
176 
177 static bool
pan_check(const struct cpu_feat * feat __unused,u_int midr __unused)178 pan_check(const struct cpu_feat *feat __unused, u_int midr __unused)
179 {
180 	uint64_t id_aa64mfr1;
181 
182 	id_aa64mfr1 = READ_SPECIALREG(id_aa64mmfr1_el1);
183 	return (ID_AA64MMFR1_PAN_VAL(id_aa64mfr1) != ID_AA64MMFR1_PAN_NONE);
184 }
185 
186 static void
pan_enable(const struct cpu_feat * feat __unused,cpu_feat_errata errata_status __unused,u_int * errata_list __unused,u_int errata_count __unused)187 pan_enable(const struct cpu_feat *feat __unused,
188     cpu_feat_errata errata_status __unused, u_int *errata_list __unused,
189     u_int errata_count __unused)
190 {
191 	has_pan = 1;
192 
193 	/*
194 	 * This sets the PAN bit, stopping the kernel from accessing
195 	 * memory when userspace can also access it unless the kernel
196 	 * uses the userspace load/store instructions.
197 	 */
198 	WRITE_SPECIALREG(sctlr_el1,
199 	    READ_SPECIALREG(sctlr_el1) & ~SCTLR_SPAN);
200 	__asm __volatile(
201 	    ".arch_extension pan	\n"
202 	    "msr pan, #1		\n"
203 	    ".arch_extension nopan	\n");
204 }
205 
206 static struct cpu_feat feat_pan = {
207 	.feat_name		= "FEAT_PAN",
208 	.feat_check		= pan_check,
209 	.feat_enable		= pan_enable,
210 	.feat_flags		= CPU_FEAT_EARLY_BOOT | CPU_FEAT_PER_CPU,
211 };
212 DATA_SET(cpu_feat_set, feat_pan);
213 
214 bool
has_hyp(void)215 has_hyp(void)
216 {
217 	return (boot_el == CURRENTEL_EL_EL2);
218 }
219 
220 bool
in_vhe(void)221 in_vhe(void)
222 {
223 	/* If we are currently in EL2 then must be in VHE */
224 	return ((READ_SPECIALREG(CurrentEL) & CURRENTEL_EL_MASK) ==
225 	    CURRENTEL_EL_EL2);
226 }
227 
228 static void
cpu_startup(void * dummy)229 cpu_startup(void *dummy)
230 {
231 	vm_paddr_t size;
232 	int i;
233 
234 	printf("real memory  = %ju (%ju MB)\n", ptoa((uintmax_t)realmem),
235 	    ptoa((uintmax_t)realmem) / 1024 / 1024);
236 
237 	if (bootverbose) {
238 		printf("Physical memory chunk(s):\n");
239 		for (i = 0; phys_avail[i + 1] != 0; i += 2) {
240 			size = phys_avail[i + 1] - phys_avail[i];
241 			printf("%#016jx - %#016jx, %ju bytes (%ju pages)\n",
242 			    (uintmax_t)phys_avail[i],
243 			    (uintmax_t)phys_avail[i + 1] - 1,
244 			    (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
245 		}
246 	}
247 
248 	printf("avail memory = %ju (%ju MB)\n",
249 	    ptoa((uintmax_t)vm_free_count()),
250 	    ptoa((uintmax_t)vm_free_count()) / 1024 / 1024);
251 
252 	undef_init();
253 	install_cpu_errata();
254 
255 	vm_ksubmap_init(&kmi);
256 	bufinit();
257 	vm_pager_bufferinit();
258 }
259 
260 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
261 
262 static void
late_ifunc_resolve(void * dummy __unused)263 late_ifunc_resolve(void *dummy __unused)
264 {
265 	link_elf_late_ireloc();
266 }
267 SYSINIT(late_ifunc_resolve, SI_SUB_CPU, SI_ORDER_ANY, late_ifunc_resolve, NULL);
268 
269 int
cpu_idle_wakeup(int cpu)270 cpu_idle_wakeup(int cpu)
271 {
272 
273 	return (0);
274 }
275 
276 void
cpu_idle(int busy)277 cpu_idle(int busy)
278 {
279 
280 	spinlock_enter();
281 	if (!busy)
282 		cpu_idleclock();
283 	if (!sched_runnable())
284 		__asm __volatile(
285 		    "dsb sy \n"
286 		    "wfi    \n");
287 	if (!busy)
288 		cpu_activeclock();
289 	spinlock_exit();
290 }
291 
292 void
cpu_halt(void)293 cpu_halt(void)
294 {
295 
296 	/* We should have shutdown by now, if not enter a low power sleep */
297 	intr_disable();
298 	while (1) {
299 		__asm __volatile("wfi");
300 	}
301 }
302 
303 /*
304  * Flush the D-cache for non-DMA I/O so that the I-cache can
305  * be made coherent later.
306  */
307 void
cpu_flush_dcache(void * ptr,size_t len)308 cpu_flush_dcache(void *ptr, size_t len)
309 {
310 
311 	/* ARM64TODO TBD */
312 }
313 
314 /* Get current clock frequency for the given CPU ID. */
315 int
cpu_est_clockrate(int cpu_id,uint64_t * rate)316 cpu_est_clockrate(int cpu_id, uint64_t *rate)
317 {
318 	struct pcpu *pc;
319 
320 	pc = pcpu_find(cpu_id);
321 	if (pc == NULL || rate == NULL)
322 		return (EINVAL);
323 
324 	if (pc->pc_clock == 0)
325 		return (EOPNOTSUPP);
326 
327 	*rate = pc->pc_clock;
328 	return (0);
329 }
330 
331 void
cpu_pcpu_init(struct pcpu * pcpu,int cpuid,size_t size)332 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
333 {
334 
335 	pcpu->pc_acpi_id = 0xffffffff;
336 	pcpu->pc_mpidr = UINT64_MAX;
337 }
338 
339 void
spinlock_enter(void)340 spinlock_enter(void)
341 {
342 	struct thread *td;
343 	register_t daif;
344 
345 	td = curthread;
346 	if (td->td_md.md_spinlock_count == 0) {
347 		daif = intr_disable();
348 		td->td_md.md_spinlock_count = 1;
349 		td->td_md.md_saved_daif = daif;
350 		critical_enter();
351 	} else
352 		td->td_md.md_spinlock_count++;
353 }
354 
355 void
spinlock_exit(void)356 spinlock_exit(void)
357 {
358 	struct thread *td;
359 	register_t daif;
360 
361 	td = curthread;
362 	daif = td->td_md.md_saved_daif;
363 	td->td_md.md_spinlock_count--;
364 	if (td->td_md.md_spinlock_count == 0) {
365 		critical_exit();
366 		intr_restore(daif);
367 	}
368 }
369 
370 /*
371  * Construct a PCB from a trapframe. This is called from kdb_trap() where
372  * we want to start a backtrace from the function that caused us to enter
373  * the debugger. We have the context in the trapframe, but base the trace
374  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
375  * enough for a backtrace.
376  */
377 void
makectx(struct trapframe * tf,struct pcb * pcb)378 makectx(struct trapframe *tf, struct pcb *pcb)
379 {
380 	int i;
381 
382 	/* NB: pcb_x[PCB_LR] is the PC, see PC_REGS() in db_machdep.h */
383 	for (i = 0; i < nitems(pcb->pcb_x); i++) {
384 		if (i == PCB_LR)
385 			pcb->pcb_x[i] = tf->tf_elr;
386 		else
387 			pcb->pcb_x[i] = tf->tf_x[i + PCB_X_START];
388 	}
389 
390 	pcb->pcb_sp = tf->tf_sp;
391 }
392 
393 static void
init_proc0(vm_offset_t kstack)394 init_proc0(vm_offset_t kstack)
395 {
396 	struct pcpu *pcpup;
397 
398 	pcpup = cpuid_to_pcpu[0];
399 	MPASS(pcpup != NULL);
400 
401 	proc_linkup0(&proc0, &thread0);
402 	thread0.td_kstack = kstack;
403 	thread0.td_kstack_pages = KSTACK_PAGES;
404 #if defined(PERTHREAD_SSP)
405 	thread0.td_md.md_canary = boot_canary;
406 #endif
407 	thread0.td_pcb = (struct pcb *)(thread0.td_kstack +
408 	    thread0.td_kstack_pages * PAGE_SIZE) - 1;
409 	thread0.td_pcb->pcb_flags = 0;
410 	thread0.td_pcb->pcb_fpflags = 0;
411 	thread0.td_pcb->pcb_fpusaved = &thread0.td_pcb->pcb_fpustate;
412 	thread0.td_pcb->pcb_vfpcpu = UINT_MAX;
413 	thread0.td_frame = &proc0_tf;
414 	ptrauth_thread0(&thread0);
415 	pcpup->pc_curpcb = thread0.td_pcb;
416 
417 	/*
418 	 * Unmask SError exceptions. They are used to signal a RAS failure,
419 	 * or other hardware error.
420 	 */
421 	serror_enable();
422 }
423 
424 /*
425  * Get an address to be used to write to kernel data that may be mapped
426  * read-only, e.g. to patch kernel code.
427  */
428 bool
arm64_get_writable_addr(void * addr,void ** out)429 arm64_get_writable_addr(void *addr, void **out)
430 {
431 	vm_paddr_t pa;
432 
433 	/* Check if the page is writable */
434 	if (PAR_SUCCESS(arm64_address_translate_s1e1w((vm_offset_t)addr))) {
435 		*out = addr;
436 		return (true);
437 	}
438 
439 	/*
440 	 * Find the physical address of the given page.
441 	 */
442 	if (!pmap_klookup((vm_offset_t)addr, &pa)) {
443 		return (false);
444 	}
445 
446 	/*
447 	 * If it is within the DMAP region and is writable use that.
448 	 */
449 	if (PHYS_IN_DMAP_RANGE(pa)) {
450 		addr = (void *)PHYS_TO_DMAP(pa);
451 		if (PAR_SUCCESS(arm64_address_translate_s1e1w(
452 		    (vm_offset_t)addr))) {
453 			*out = addr;
454 			return (true);
455 		}
456 	}
457 
458 	return (false);
459 }
460 
461 /*
462  * Map the passed in VA in EFI space to a void * using the efi memory table to
463  * find the PA and return it in the DMAP, if it exists. We're used between the
464  * calls to pmap_bootstrap() and physmem_init_kernel_globals() to parse CFG
465  * tables We assume that either the entry you are mapping fits within its page,
466  * or if it spills to the next page, that's contiguous in PA and in the DMAP.
467  * All observed tables obey the first part of this precondition.
468  */
469 struct early_map_data
470 {
471 	vm_offset_t va;
472 	vm_offset_t pa;
473 };
474 
475 static void
efi_early_map_entry(struct efi_md * p,void * argp)476 efi_early_map_entry(struct efi_md *p, void *argp)
477 {
478 	struct early_map_data *emdp = argp;
479 	vm_offset_t s, e;
480 
481 	if (emdp->pa != 0)
482 		return;
483 	if ((p->md_attr & EFI_MD_ATTR_RT) == 0)
484 		return;
485 	s = p->md_virt;
486 	e = p->md_virt + p->md_pages * EFI_PAGE_SIZE;
487 	if (emdp->va < s  || emdp->va >= e)
488 		return;
489 	emdp->pa = p->md_phys + (emdp->va - p->md_virt);
490 }
491 
492 static void *
efi_early_map(vm_offset_t va)493 efi_early_map(vm_offset_t va)
494 {
495 	struct early_map_data emd = { .va = va };
496 
497 	efi_map_foreach_entry(efihdr, efi_early_map_entry, &emd);
498 	if (emd.pa == 0)
499 		return NULL;
500 	return (void *)PHYS_TO_DMAP(emd.pa);
501 }
502 
503 
504 /*
505  * When booted via kexec from Linux, the prior kernel will pass in reserved
506  * memory areas in an EFI config table. We need to find that table and walk
507  * through it excluding the memory ranges in it. btw, this is called too early
508  * for the printf to do anything (unless EARLY_PRINTF is defined) since msgbufp
509  * isn't initialized, let alone a console, but breakpoints in printf help
510  * diagnose rare failures.
511  */
512 static void
exclude_efi_memreserve(vm_paddr_t efi_systbl_phys)513 exclude_efi_memreserve(vm_paddr_t efi_systbl_phys)
514 {
515 	struct efi_systbl *systbl;
516 	struct uuid efi_memreserve = LINUX_EFI_MEMRESERVE_TABLE;
517 
518 	systbl = (struct efi_systbl *)PHYS_TO_DMAP(efi_systbl_phys);
519 	if (systbl == NULL) {
520 		printf("can't map systbl\n");
521 		return;
522 	}
523 	if (systbl->st_hdr.th_sig != EFI_SYSTBL_SIG) {
524 		printf("Bad signature for systbl %#lx\n", systbl->st_hdr.th_sig);
525 		return;
526 	}
527 
528 	/*
529 	 * We don't yet have the pmap system booted enough to create a pmap for
530 	 * the efi firmware's preferred address space from the GetMemoryMap()
531 	 * table. The st_cfgtbl is a VA in this space, so we need to do the
532 	 * mapping ourselves to a kernel VA with efi_early_map. We assume that
533 	 * the cfgtbl entries don't span a page. Other pointers are PAs, as
534 	 * noted below.
535 	 */
536 	if (systbl->st_cfgtbl == 0)	/* Failsafe st_entries should == 0 in this case */
537 		return;
538 	for (int i = 0; i < systbl->st_entries; i++) {
539 		struct efi_cfgtbl *cfgtbl;
540 		struct linux_efi_memreserve *mr;
541 
542 		cfgtbl = efi_early_map(systbl->st_cfgtbl + i * sizeof(*cfgtbl));
543 		if (cfgtbl == NULL)
544 			panic("Can't map the config table entry %d\n", i);
545 		if (memcmp(&cfgtbl->ct_uuid, &efi_memreserve, sizeof(struct uuid)) != 0)
546 			continue;
547 
548 		/*
549 		 * cfgtbl points are either VA or PA, depending on the GUID of
550 		 * the table. memreserve GUID pointers are PA and not converted
551 		 * after a SetVirtualAddressMap(). The list's mr_next pointer
552 		 * is also a PA.
553 		 */
554 		mr = (struct linux_efi_memreserve *)PHYS_TO_DMAP(
555 			(vm_offset_t)cfgtbl->ct_data);
556 		while (true) {
557 			for (int j = 0; j < mr->mr_count; j++) {
558 				struct linux_efi_memreserve_entry *mre;
559 
560 				mre = &mr->mr_entry[j];
561 				physmem_exclude_region(mre->mre_base, mre->mre_size,
562 				    EXFLAG_NODUMP | EXFLAG_NOALLOC);
563 			}
564 			if (mr->mr_next == 0)
565 				break;
566 			mr = (struct linux_efi_memreserve *)PHYS_TO_DMAP(mr->mr_next);
567 		};
568 	}
569 
570 }
571 
572 #ifdef FDT
573 static void
try_load_dtb(void)574 try_load_dtb(void)
575 {
576 	vm_offset_t dtbp;
577 
578 	dtbp = MD_FETCH(preload_kmdp, MODINFOMD_DTBP, vm_offset_t);
579 #if defined(FDT_DTB_STATIC)
580 	/*
581 	 * In case the device tree blob was not retrieved (from metadata) try
582 	 * to use the statically embedded one.
583 	 */
584 	if (dtbp == 0)
585 		dtbp = (vm_offset_t)&fdt_static_dtb;
586 #endif
587 
588 	if (dtbp == (vm_offset_t)NULL) {
589 #ifndef TSLOG
590 		printf("ERROR loading DTB\n");
591 #endif
592 		return;
593 	}
594 
595 	if (!OF_install(OFW_FDT, 0))
596 		panic("Cannot install FDT");
597 
598 	if (OF_init((void *)dtbp) != 0)
599 		panic("OF_init failed with the found device tree");
600 
601 	parse_fdt_bootargs();
602 }
603 #endif
604 
605 static bool
bus_probe(void)606 bus_probe(void)
607 {
608 	bool has_acpi, has_fdt;
609 	char *order, *env;
610 
611 	has_acpi = has_fdt = false;
612 
613 #ifdef FDT
614 	has_fdt = (OF_peer(0) != 0);
615 #endif
616 #ifdef DEV_ACPI
617 	has_acpi = (AcpiOsGetRootPointer() != 0);
618 #endif
619 
620 	env = kern_getenv("kern.cfg.order");
621 	if (env != NULL) {
622 		order = env;
623 		while (order != NULL) {
624 			if (has_acpi &&
625 			    strncmp(order, "acpi", 4) == 0 &&
626 			    (order[4] == ',' || order[4] == '\0')) {
627 				arm64_bus_method = ARM64_BUS_ACPI;
628 				break;
629 			}
630 			if (has_fdt &&
631 			    strncmp(order, "fdt", 3) == 0 &&
632 			    (order[3] == ',' || order[3] == '\0')) {
633 				arm64_bus_method = ARM64_BUS_FDT;
634 				break;
635 			}
636 			order = strchr(order, ',');
637 			if (order != NULL)
638 				order++;	/* Skip comma */
639 		}
640 		freeenv(env);
641 
642 		/* If we set the bus method it is valid */
643 		if (arm64_bus_method != ARM64_BUS_NONE)
644 			return (true);
645 	}
646 	/* If no order or an invalid order was set use the default */
647 	if (arm64_bus_method == ARM64_BUS_NONE) {
648 		if (has_acpi)
649 			arm64_bus_method = ARM64_BUS_ACPI;
650 		else if (has_fdt)
651 			arm64_bus_method = ARM64_BUS_FDT;
652 	}
653 
654 	/*
655 	 * If no option was set the default is valid, otherwise we are
656 	 * setting one to get cninit() working, then calling panic to tell
657 	 * the user about the invalid bus setup.
658 	 */
659 	return (env == NULL);
660 }
661 
662 static void
cache_setup(void)663 cache_setup(void)
664 {
665 	int dczva_line_shift;
666 	uint32_t dczid_el0;
667 
668 	identify_cache(READ_SPECIALREG(ctr_el0));
669 
670 	dczid_el0 = READ_SPECIALREG(dczid_el0);
671 
672 	/* Check if dc zva is not prohibited */
673 	if (dczid_el0 & DCZID_DZP)
674 		dczva_line_size = 0;
675 	else {
676 		/* Same as with above calculations */
677 		dczva_line_shift = DCZID_BS_SIZE(dczid_el0);
678 		dczva_line_size = sizeof(int) << dczva_line_shift;
679 
680 		/* Change pagezero function */
681 		pagezero = pagezero_cache;
682 	}
683 }
684 
685 int
memory_mapping_mode(vm_paddr_t pa)686 memory_mapping_mode(vm_paddr_t pa)
687 {
688 	struct efi_md *map, *p;
689 	size_t efisz;
690 	int ndesc, i;
691 
692 	if (efihdr == NULL)
693 		return (VM_MEMATTR_WRITE_BACK);
694 
695 	/*
696 	 * Memory map data provided by UEFI via the GetMemoryMap
697 	 * Boot Services API.
698 	 */
699 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
700 	map = (struct efi_md *)((uint8_t *)efihdr + efisz);
701 
702 	if (efihdr->descriptor_size == 0)
703 		return (VM_MEMATTR_WRITE_BACK);
704 	ndesc = efihdr->memory_size / efihdr->descriptor_size;
705 
706 	for (i = 0, p = map; i < ndesc; i++,
707 	    p = efi_next_descriptor(p, efihdr->descriptor_size)) {
708 		if (pa < p->md_phys ||
709 		    pa >= p->md_phys + p->md_pages * EFI_PAGE_SIZE)
710 			continue;
711 		if (p->md_type == EFI_MD_TYPE_IOMEM ||
712 		    p->md_type == EFI_MD_TYPE_IOPORT)
713 			return (VM_MEMATTR_DEVICE);
714 		else if ((p->md_attr & EFI_MD_ATTR_WB) != 0 ||
715 		    p->md_type == EFI_MD_TYPE_RECLAIM)
716 			return (VM_MEMATTR_WRITE_BACK);
717 		else if ((p->md_attr & EFI_MD_ATTR_WT) != 0)
718 			return (VM_MEMATTR_WRITE_THROUGH);
719 		else if ((p->md_attr & EFI_MD_ATTR_WC) != 0)
720 			return (VM_MEMATTR_WRITE_COMBINING);
721 		break;
722 	}
723 
724 	return (VM_MEMATTR_DEVICE);
725 }
726 
727 #ifdef FDT
728 static void
fdt_physmem_hardware_region_cb(const struct mem_region * mr,void * arg __unused)729 fdt_physmem_hardware_region_cb(const struct mem_region *mr, void *arg __unused)
730 {
731 	physmem_hardware_region(mr->mr_start, mr->mr_size);
732 }
733 
734 static void
fdt_physmem_exclude_region_cb(const struct mem_region * mr,void * arg __unused)735 fdt_physmem_exclude_region_cb(const struct mem_region *mr, void *arg __unused)
736 {
737 	physmem_exclude_region(mr->mr_start, mr->mr_size,
738 	    EXFLAG_NODUMP | EXFLAG_NOALLOC);
739 }
740 #endif
741 
742 void
initarm(struct arm64_bootparams * abp)743 initarm(struct arm64_bootparams *abp)
744 {
745 	struct efi_fb *efifb;
746 	struct pcpu *pcpup;
747 	char *env;
748 #ifdef FDT
749 	phandle_t root;
750 	char dts_version[255];
751 #endif
752 	vm_offset_t lastaddr;
753 	bool valid;
754 
755 	TSRAW(&thread0, TS_ENTER, __func__, NULL);
756 
757 	boot_el = abp->boot_el;
758 
759 	/* Parse loader or FDT boot parameters. Determine last used address. */
760 	lastaddr = parse_boot_param(abp);
761 
762 	identify_cpu(0);
763 	identify_hypervisor_smbios();
764 
765 	update_special_regs(0);
766 
767 	/* Set the pcpu data, this is needed by pmap_bootstrap */
768 	pcpup = &pcpu0;
769 	pcpu_init(pcpup, 0, sizeof(struct pcpu));
770 
771 	/*
772 	 * Set the pcpu pointer with a backup in tpidr_el1 to be
773 	 * loaded when entering the kernel from userland.
774 	 */
775 	__asm __volatile(
776 	    "mov x18, %0 \n"
777 	    "msr tpidr_el1, %0" :: "r"(pcpup));
778 
779 	/* locore.S sets sp_el0 to &thread0 so no need to set it here. */
780 	PCPU_SET(curthread, &thread0);
781 	PCPU_SET(midr, get_midr());
782 
783 	link_elf_ireloc();
784 #ifdef FDT
785 	try_load_dtb();
786 #endif
787 
788 	efi_systbl_phys = MD_FETCH(preload_kmdp, MODINFOMD_FW_HANDLE,
789 	    vm_paddr_t);
790 
791 	/* Load the physical memory ranges */
792 	efihdr = (struct efi_map_header *)preload_search_info(preload_kmdp,
793 	    MODINFO_METADATA | MODINFOMD_EFI_MAP);
794 	if (efihdr != NULL)
795 		efi_map_add_entries(efihdr);
796 #ifdef FDT
797 	else {
798 		/* Grab physical memory regions information from device tree. */
799 		if (fdt_foreach_mem_region(fdt_physmem_hardware_region_cb,
800 		    NULL) != 0)
801 			panic("Cannot get physical memory regions");
802 	}
803 	fdt_foreach_reserved_mem(fdt_physmem_exclude_region_cb, NULL);
804 #endif
805 
806 	/* Exclude the EFI framebuffer from our view of physical memory. */
807 	efifb = (struct efi_fb *)preload_search_info(preload_kmdp,
808 	    MODINFO_METADATA | MODINFOMD_EFI_FB);
809 	if (efifb != NULL)
810 		physmem_exclude_region(efifb->fb_addr, efifb->fb_size,
811 		    EXFLAG_NOALLOC);
812 
813 	/* Do basic tuning, hz etc */
814 	init_param1();
815 
816 	cache_setup();
817 
818 	/*
819 	 * Perform a staged bootstrap of virtual memory.
820 	 *
821 	 * - First we create the DMAP region. This allows it to be used in
822 	 *   later bootstrapping.
823 	 * - Next exclude memory that is needed in the DMAP region, but must
824 	 *   not be used by FreeBSD.
825 	 * - Lastly complete the bootstrapping. It may use the physical
826 	 *   memory map so any excluded memory must be marked as such before
827 	 *   pmap_bootstrap() is called.
828 	 */
829 	pmap_bootstrap_dmap(lastaddr - KERNBASE);
830 	/*
831 	 * Exclude EFI entries needed in the DMAP, e.g. EFI_MD_TYPE_RECLAIM
832 	 * may contain the ACPI tables but shouldn't be used by the kernel
833 	 */
834 	if (efihdr != NULL)
835 		efi_map_exclude_entries(efihdr);
836 	/*  Do the same for reserve entries in the EFI MEMRESERVE table */
837 	if (efi_systbl_phys != 0)
838 		exclude_efi_memreserve(efi_systbl_phys);
839 	/* Continue bootstrapping pmap */
840 	pmap_bootstrap();
841 
842 	/*
843 	 * We carefully bootstrap the sanitizer map after we've excluded
844 	 * absolutely everything else that could impact phys_avail.  There's not
845 	 * always enough room for the initial shadow map after the kernel, so
846 	 * we'll end up searching for segments that we can safely use.  Those
847 	 * segments also get excluded from phys_avail.
848 	 */
849 #if defined(KASAN) || defined(KMSAN)
850 	pmap_bootstrap_san();
851 #endif
852 
853 	physmem_init_kernel_globals();
854 
855 	devmap_bootstrap();
856 
857 	valid = bus_probe();
858 
859 	cninit();
860 	set_ttbr0(abp->kern_ttbr0);
861 	cpu_tlb_flushID();
862 
863 	if (!valid)
864 		panic("Invalid bus configuration: %s",
865 		    kern_getenv("kern.cfg.order"));
866 
867 	/* Detect early CPU feature support */
868 	enable_cpu_feat(CPU_FEAT_EARLY_BOOT);
869 
870 	/*
871 	 * Dump the boot metadata. We have to wait for cninit() since console
872 	 * output is required. If it's grossly incorrect the kernel will never
873 	 * make it this far.
874 	 */
875 	if (getenv_is_true("debug.dump_modinfo_at_boot"))
876 		preload_dump();
877 
878 	init_proc0(abp->kern_stack);
879 	msgbufinit(msgbufp, msgbufsize);
880 	mutex_init();
881 	init_param2(physmem);
882 
883 	dbg_init();
884 	kdb_init();
885 #ifdef KDB
886 	if ((boothowto & RB_KDB) != 0)
887 		kdb_enter(KDB_WHY_BOOTFLAGS, "Boot flags requested debugger");
888 #endif
889 
890 	kcsan_cpu_init(0);
891 	kasan_init();
892 	kmsan_init();
893 
894 	env = kern_getenv("kernelname");
895 	if (env != NULL)
896 		strlcpy(kernelname, env, sizeof(kernelname));
897 
898 #ifdef FDT
899 	if (arm64_bus_method == ARM64_BUS_FDT) {
900 		root = OF_finddevice("/");
901 		if (OF_getprop(root, "freebsd,dts-version", dts_version, sizeof(dts_version)) > 0) {
902 			if (strcmp(LINUX_DTS_VERSION, dts_version) != 0)
903 				printf("WARNING: DTB version is %s while kernel expects %s, "
904 				    "please update the DTB in the ESP\n",
905 				    dts_version,
906 				    LINUX_DTS_VERSION);
907 		} else {
908 			printf("WARNING: Cannot find freebsd,dts-version property, "
909 			    "cannot check DTB compliance\n");
910 		}
911 	}
912 #endif
913 
914 	if (boothowto & RB_VERBOSE) {
915 		if (efihdr != NULL)
916 			efi_map_print_entries(efihdr);
917 		physmem_print_tables();
918 	}
919 
920 	early_boot = 0;
921 
922 	if (bootverbose && kstack_pages != KSTACK_PAGES)
923 		printf("kern.kstack_pages = %d ignored for thread0\n",
924 		    kstack_pages);
925 
926 	TSEXIT();
927 }
928 
929 void
dbg_init(void)930 dbg_init(void)
931 {
932 
933 	/* Clear OS lock */
934 	WRITE_SPECIALREG(oslar_el1, 0);
935 
936 	/* This permits DDB to use debug registers for watchpoints. */
937 	dbg_monitor_init();
938 
939 	/* TODO: Eventually will need to initialize debug registers here. */
940 }
941 
942 #ifdef DDB
943 #include <ddb/ddb.h>
944 
DB_SHOW_COMMAND(specialregs,db_show_spregs)945 DB_SHOW_COMMAND(specialregs, db_show_spregs)
946 {
947 #define	PRINT_REG(reg)	\
948     db_printf(__STRING(reg) " = %#016lx\n", READ_SPECIALREG(reg))
949 
950 	PRINT_REG(actlr_el1);
951 	PRINT_REG(afsr0_el1);
952 	PRINT_REG(afsr1_el1);
953 	PRINT_REG(aidr_el1);
954 	PRINT_REG(amair_el1);
955 	PRINT_REG(ccsidr_el1);
956 	PRINT_REG(clidr_el1);
957 	PRINT_REG(contextidr_el1);
958 	PRINT_REG(cpacr_el1);
959 	PRINT_REG(csselr_el1);
960 	PRINT_REG(ctr_el0);
961 	PRINT_REG(currentel);
962 	PRINT_REG(daif);
963 	PRINT_REG(dczid_el0);
964 	PRINT_REG(elr_el1);
965 	PRINT_REG(esr_el1);
966 	PRINT_REG(far_el1);
967 #if 0
968 	/* ARM64TODO: Enable VFP before reading floating-point registers */
969 	PRINT_REG(fpcr);
970 	PRINT_REG(fpsr);
971 #endif
972 	PRINT_REG(id_aa64afr0_el1);
973 	PRINT_REG(id_aa64afr1_el1);
974 	PRINT_REG(id_aa64dfr0_el1);
975 	PRINT_REG(id_aa64dfr1_el1);
976 	PRINT_REG(id_aa64isar0_el1);
977 	PRINT_REG(id_aa64isar1_el1);
978 	PRINT_REG(id_aa64pfr0_el1);
979 	PRINT_REG(id_aa64pfr1_el1);
980 	PRINT_REG(id_afr0_el1);
981 	PRINT_REG(id_dfr0_el1);
982 	PRINT_REG(id_isar0_el1);
983 	PRINT_REG(id_isar1_el1);
984 	PRINT_REG(id_isar2_el1);
985 	PRINT_REG(id_isar3_el1);
986 	PRINT_REG(id_isar4_el1);
987 	PRINT_REG(id_isar5_el1);
988 	PRINT_REG(id_mmfr0_el1);
989 	PRINT_REG(id_mmfr1_el1);
990 	PRINT_REG(id_mmfr2_el1);
991 	PRINT_REG(id_mmfr3_el1);
992 #if 0
993 	/* Missing from llvm */
994 	PRINT_REG(id_mmfr4_el1);
995 #endif
996 	PRINT_REG(id_pfr0_el1);
997 	PRINT_REG(id_pfr1_el1);
998 	PRINT_REG(isr_el1);
999 	PRINT_REG(mair_el1);
1000 	PRINT_REG(midr_el1);
1001 	PRINT_REG(mpidr_el1);
1002 	PRINT_REG(mvfr0_el1);
1003 	PRINT_REG(mvfr1_el1);
1004 	PRINT_REG(mvfr2_el1);
1005 	PRINT_REG(revidr_el1);
1006 	PRINT_REG(sctlr_el1);
1007 	PRINT_REG(sp_el0);
1008 	PRINT_REG(spsel);
1009 	PRINT_REG(spsr_el1);
1010 	PRINT_REG(tcr_el1);
1011 	PRINT_REG(tpidr_el0);
1012 	PRINT_REG(tpidr_el1);
1013 	PRINT_REG(tpidrro_el0);
1014 	PRINT_REG(ttbr0_el1);
1015 	PRINT_REG(ttbr1_el1);
1016 	PRINT_REG(vbar_el1);
1017 #undef PRINT_REG
1018 }
1019 
DB_SHOW_COMMAND(vtop,db_show_vtop)1020 DB_SHOW_COMMAND(vtop, db_show_vtop)
1021 {
1022 	uint64_t phys;
1023 
1024 	if (have_addr) {
1025 		phys = arm64_address_translate_s1e1r(addr);
1026 		db_printf("EL1 physical address reg (read):  0x%016lx\n", phys);
1027 		phys = arm64_address_translate_s1e1w(addr);
1028 		db_printf("EL1 physical address reg (write): 0x%016lx\n", phys);
1029 		phys = arm64_address_translate_s1e0r(addr);
1030 		db_printf("EL0 physical address reg (read):  0x%016lx\n", phys);
1031 		phys = arm64_address_translate_s1e0w(addr);
1032 		db_printf("EL0 physical address reg (write): 0x%016lx\n", phys);
1033 	} else
1034 		db_printf("show vtop <virt_addr>\n");
1035 }
1036 #endif
1037