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