xref: /freebsd/sys/arm64/arm64/machdep.c (revision fa23bfb425d53a87064d86ec9ae0ae5e31aa5d5b)
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 cpu_feat_en
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 	if (ID_AA64MMFR1_PAN_VAL(id_aa64mfr1) == ID_AA64MMFR1_PAN_NONE)
183 		return (FEAT_ALWAYS_DISABLE);
184 
185 	return (FEAT_DEFAULT_ENABLE);
186 }
187 
188 static bool
pan_enable(const struct cpu_feat * feat __unused,cpu_feat_errata errata_status __unused,u_int * errata_list __unused,u_int errata_count __unused)189 pan_enable(const struct cpu_feat *feat __unused,
190     cpu_feat_errata errata_status __unused, u_int *errata_list __unused,
191     u_int errata_count __unused)
192 {
193 	has_pan = 1;
194 
195 	/*
196 	 * This sets the PAN bit, stopping the kernel from accessing
197 	 * memory when userspace can also access it unless the kernel
198 	 * uses the userspace load/store instructions.
199 	 */
200 	WRITE_SPECIALREG(sctlr_el1,
201 	    READ_SPECIALREG(sctlr_el1) & ~SCTLR_SPAN);
202 	__asm __volatile(
203 	    ".arch_extension pan	\n"
204 	    "msr pan, #1		\n"
205 	    ".arch_extension nopan	\n");
206 
207 	return (true);
208 }
209 
210 CPU_FEAT(feat_pan, "Privileged access never",
211     pan_check, NULL, pan_enable,
212     CPU_FEAT_EARLY_BOOT | CPU_FEAT_PER_CPU);
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 /* Late enough for cpu_feat to have completed */
268 SYSINIT(late_ifunc_resolve, SI_SUB_CONFIGURE, SI_ORDER_ANY,
269     late_ifunc_resolve, NULL);
270 
271 int
cpu_idle_wakeup(int cpu)272 cpu_idle_wakeup(int cpu)
273 {
274 
275 	return (0);
276 }
277 
278 void
cpu_idle(int busy)279 cpu_idle(int busy)
280 {
281 
282 	spinlock_enter();
283 	if (!busy)
284 		cpu_idleclock();
285 	if (!sched_runnable())
286 		__asm __volatile(
287 		    "dsb sy \n"
288 		    "wfi    \n");
289 	if (!busy)
290 		cpu_activeclock();
291 	spinlock_exit();
292 }
293 
294 void
cpu_halt(void)295 cpu_halt(void)
296 {
297 
298 	/* We should have shutdown by now, if not enter a low power sleep */
299 	intr_disable();
300 	while (1) {
301 		__asm __volatile("wfi");
302 	}
303 }
304 
305 /*
306  * Flush the D-cache for non-DMA I/O so that the I-cache can
307  * be made coherent later.
308  */
309 void
cpu_flush_dcache(void * ptr,size_t len)310 cpu_flush_dcache(void *ptr, size_t len)
311 {
312 
313 	/* ARM64TODO TBD */
314 }
315 
316 /* Get current clock frequency for the given CPU ID. */
317 int
cpu_est_clockrate(int cpu_id,uint64_t * rate)318 cpu_est_clockrate(int cpu_id, uint64_t *rate)
319 {
320 	struct pcpu *pc;
321 
322 	pc = pcpu_find(cpu_id);
323 	if (pc == NULL || rate == NULL)
324 		return (EINVAL);
325 
326 	if (pc->pc_clock == 0)
327 		return (EOPNOTSUPP);
328 
329 	*rate = pc->pc_clock;
330 	return (0);
331 }
332 
333 void
cpu_pcpu_init(struct pcpu * pcpu,int cpuid,size_t size)334 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
335 {
336 
337 	pcpu->pc_acpi_id = 0xffffffff;
338 	pcpu->pc_mpidr = UINT64_MAX;
339 }
340 
341 void
spinlock_enter(void)342 spinlock_enter(void)
343 {
344 	struct thread *td;
345 	register_t daif;
346 
347 	td = curthread;
348 	if (td->td_md.md_spinlock_count == 0) {
349 		daif = intr_disable();
350 		td->td_md.md_spinlock_count = 1;
351 		td->td_md.md_saved_daif = daif;
352 		critical_enter();
353 	} else
354 		td->td_md.md_spinlock_count++;
355 }
356 
357 void
spinlock_exit(void)358 spinlock_exit(void)
359 {
360 	struct thread *td;
361 	register_t daif;
362 
363 	td = curthread;
364 	daif = td->td_md.md_saved_daif;
365 	td->td_md.md_spinlock_count--;
366 	if (td->td_md.md_spinlock_count == 0) {
367 		critical_exit();
368 		intr_restore(daif);
369 	}
370 }
371 
372 /*
373  * Construct a PCB from a trapframe. This is called from kdb_trap() where
374  * we want to start a backtrace from the function that caused us to enter
375  * the debugger. We have the context in the trapframe, but base the trace
376  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
377  * enough for a backtrace.
378  */
379 void
makectx(struct trapframe * tf,struct pcb * pcb)380 makectx(struct trapframe *tf, struct pcb *pcb)
381 {
382 	int i;
383 
384 	/* NB: pcb_x[PCB_LR] is the PC, see PC_REGS() in db_machdep.h */
385 	for (i = 0; i < nitems(pcb->pcb_x); i++) {
386 		if (i == PCB_LR)
387 			pcb->pcb_x[i] = tf->tf_elr;
388 		else
389 			pcb->pcb_x[i] = tf->tf_x[i + PCB_X_START];
390 	}
391 
392 	pcb->pcb_sp = tf->tf_sp;
393 }
394 
395 static void
init_proc0(vm_offset_t kstack)396 init_proc0(vm_offset_t kstack)
397 {
398 	struct pcpu *pcpup;
399 
400 	pcpup = cpuid_to_pcpu[0];
401 	MPASS(pcpup != NULL);
402 
403 	proc_linkup0(&proc0, &thread0);
404 	thread0.td_kstack = kstack;
405 	thread0.td_kstack_pages = KSTACK_PAGES;
406 #if defined(PERTHREAD_SSP)
407 	thread0.td_md.md_canary = boot_canary;
408 #endif
409 	thread0.td_pcb = (struct pcb *)(thread0.td_kstack +
410 	    thread0.td_kstack_pages * PAGE_SIZE) - 1;
411 	thread0.td_pcb->pcb_flags = 0;
412 	thread0.td_pcb->pcb_fpflags = 0;
413 	thread0.td_pcb->pcb_fpusaved = &thread0.td_pcb->pcb_fpustate;
414 	thread0.td_pcb->pcb_vfpcpu = UINT_MAX;
415 	thread0.td_frame = &proc0_tf;
416 	ptrauth_thread0(&thread0);
417 	pcpup->pc_curpcb = thread0.td_pcb;
418 
419 	/*
420 	 * Unmask SError exceptions. They are used to signal a RAS failure,
421 	 * or other hardware error.
422 	 */
423 	serror_enable();
424 }
425 
426 /*
427  * Get an address to be used to write to kernel data that may be mapped
428  * read-only, e.g. to patch kernel code.
429  */
430 bool
arm64_get_writable_addr(void * addr,void ** out)431 arm64_get_writable_addr(void *addr, void **out)
432 {
433 	vm_paddr_t pa;
434 
435 	/* Check if the page is writable */
436 	if (PAR_SUCCESS(arm64_address_translate_s1e1w((vm_offset_t)addr))) {
437 		*out = addr;
438 		return (true);
439 	}
440 
441 	/*
442 	 * Find the physical address of the given page.
443 	 */
444 	if (!pmap_klookup((vm_offset_t)addr, &pa)) {
445 		return (false);
446 	}
447 
448 	/*
449 	 * If it is within the DMAP region and is writable use that.
450 	 */
451 	if (PHYS_IN_DMAP_RANGE(pa)) {
452 		addr = (void *)PHYS_TO_DMAP(pa);
453 		if (PAR_SUCCESS(arm64_address_translate_s1e1w(
454 		    (vm_offset_t)addr))) {
455 			*out = addr;
456 			return (true);
457 		}
458 	}
459 
460 	return (false);
461 }
462 
463 /*
464  * Map the passed in VA in EFI space to a void * using the efi memory table to
465  * find the PA and return it in the DMAP, if it exists. We're used between the
466  * calls to pmap_bootstrap() and physmem_init_kernel_globals() to parse CFG
467  * tables We assume that either the entry you are mapping fits within its page,
468  * or if it spills to the next page, that's contiguous in PA and in the DMAP.
469  * All observed tables obey the first part of this precondition.
470  */
471 struct early_map_data
472 {
473 	vm_offset_t va;
474 	vm_offset_t pa;
475 };
476 
477 static void
efi_early_map_entry(struct efi_md * p,void * argp)478 efi_early_map_entry(struct efi_md *p, void *argp)
479 {
480 	struct early_map_data *emdp = argp;
481 	vm_offset_t s, e;
482 
483 	if (emdp->pa != 0)
484 		return;
485 	if ((p->md_attr & EFI_MD_ATTR_RT) == 0)
486 		return;
487 	s = p->md_virt;
488 	e = p->md_virt + p->md_pages * EFI_PAGE_SIZE;
489 	if (emdp->va < s  || emdp->va >= e)
490 		return;
491 	emdp->pa = p->md_phys + (emdp->va - p->md_virt);
492 }
493 
494 static void *
efi_early_map(vm_offset_t va)495 efi_early_map(vm_offset_t va)
496 {
497 	struct early_map_data emd = { .va = va };
498 
499 	efi_map_foreach_entry(efihdr, efi_early_map_entry, &emd);
500 	if (emd.pa == 0)
501 		return NULL;
502 	return (void *)PHYS_TO_DMAP(emd.pa);
503 }
504 
505 
506 /*
507  * When booted via kexec from Linux, the prior kernel will pass in reserved
508  * memory areas in an EFI config table. We need to find that table and walk
509  * through it excluding the memory ranges in it. btw, this is called too early
510  * for the printf to do anything (unless EARLY_PRINTF is defined) since msgbufp
511  * isn't initialized, let alone a console, but breakpoints in printf help
512  * diagnose rare failures.
513  */
514 static void
exclude_efi_memreserve(vm_paddr_t efi_systbl_phys)515 exclude_efi_memreserve(vm_paddr_t efi_systbl_phys)
516 {
517 	struct efi_systbl *systbl;
518 	efi_guid_t efi_memreserve = LINUX_EFI_MEMRESERVE_TABLE;
519 
520 	systbl = (struct efi_systbl *)PHYS_TO_DMAP(efi_systbl_phys);
521 	if (systbl == NULL) {
522 		printf("can't map systbl\n");
523 		return;
524 	}
525 	if (systbl->st_hdr.th_sig != EFI_SYSTBL_SIG) {
526 		printf("Bad signature for systbl %#lx\n", systbl->st_hdr.th_sig);
527 		return;
528 	}
529 
530 	/*
531 	 * We don't yet have the pmap system booted enough to create a pmap for
532 	 * the efi firmware's preferred address space from the GetMemoryMap()
533 	 * table. The st_cfgtbl is a VA in this space, so we need to do the
534 	 * mapping ourselves to a kernel VA with efi_early_map. We assume that
535 	 * the cfgtbl entries don't span a page. Other pointers are PAs, as
536 	 * noted below.
537 	 */
538 	if (systbl->st_cfgtbl == 0)	/* Failsafe st_entries should == 0 in this case */
539 		return;
540 	for (int i = 0; i < systbl->st_entries; i++) {
541 		struct efi_cfgtbl *cfgtbl;
542 		struct linux_efi_memreserve *mr;
543 
544 		cfgtbl = efi_early_map(systbl->st_cfgtbl + i * sizeof(*cfgtbl));
545 		if (cfgtbl == NULL)
546 			panic("Can't map the config table entry %d\n", i);
547 		if (memcmp(&cfgtbl->ct_guid, &efi_memreserve, sizeof(efi_guid_t)) != 0)
548 			continue;
549 
550 		/*
551 		 * cfgtbl points are either VA or PA, depending on the GUID of
552 		 * the table. memreserve GUID pointers are PA and not converted
553 		 * after a SetVirtualAddressMap(). The list's mr_next pointer
554 		 * is also a PA.
555 		 */
556 		mr = (struct linux_efi_memreserve *)PHYS_TO_DMAP(
557 			(vm_offset_t)cfgtbl->ct_data);
558 		while (true) {
559 			for (int j = 0; j < mr->mr_count; j++) {
560 				struct linux_efi_memreserve_entry *mre;
561 
562 				mre = &mr->mr_entry[j];
563 				physmem_exclude_region(mre->mre_base, mre->mre_size,
564 				    EXFLAG_NODUMP | EXFLAG_NOALLOC);
565 			}
566 			if (mr->mr_next == 0)
567 				break;
568 			mr = (struct linux_efi_memreserve *)PHYS_TO_DMAP(mr->mr_next);
569 		};
570 	}
571 
572 }
573 
574 #ifdef FDT
575 static void
try_load_dtb(void)576 try_load_dtb(void)
577 {
578 	vm_offset_t dtbp;
579 
580 	dtbp = MD_FETCH(preload_kmdp, MODINFOMD_DTBP, vm_offset_t);
581 #if defined(FDT_DTB_STATIC)
582 	/*
583 	 * In case the device tree blob was not retrieved (from metadata) try
584 	 * to use the statically embedded one.
585 	 */
586 	if (dtbp == 0)
587 		dtbp = (vm_offset_t)&fdt_static_dtb;
588 #endif
589 
590 	if (dtbp == (vm_offset_t)NULL) {
591 #ifndef TSLOG
592 		printf("ERROR loading DTB\n");
593 #endif
594 		return;
595 	}
596 
597 	if (!OF_install(OFW_FDT, 0))
598 		panic("Cannot install FDT");
599 
600 	if (OF_init((void *)dtbp) != 0)
601 		panic("OF_init failed with the found device tree");
602 
603 	parse_fdt_bootargs();
604 }
605 #endif
606 
607 static bool
bus_probe(void)608 bus_probe(void)
609 {
610 	bool has_acpi, has_fdt;
611 	char *order, *env;
612 
613 	has_acpi = has_fdt = false;
614 
615 #ifdef FDT
616 	has_fdt = (OF_peer(0) != 0);
617 #endif
618 #ifdef DEV_ACPI
619 	has_acpi = (AcpiOsGetRootPointer() != 0);
620 #endif
621 
622 	env = kern_getenv("kern.cfg.order");
623 	if (env != NULL) {
624 		order = env;
625 		while (order != NULL) {
626 			if (has_acpi &&
627 			    strncmp(order, "acpi", 4) == 0 &&
628 			    (order[4] == ',' || order[4] == '\0')) {
629 				arm64_bus_method = ARM64_BUS_ACPI;
630 				break;
631 			}
632 			if (has_fdt &&
633 			    strncmp(order, "fdt", 3) == 0 &&
634 			    (order[3] == ',' || order[3] == '\0')) {
635 				arm64_bus_method = ARM64_BUS_FDT;
636 				break;
637 			}
638 			order = strchr(order, ',');
639 			if (order != NULL)
640 				order++;	/* Skip comma */
641 		}
642 		freeenv(env);
643 
644 		/* If we set the bus method it is valid */
645 		if (arm64_bus_method != ARM64_BUS_NONE)
646 			return (true);
647 	}
648 	/* If no order or an invalid order was set use the default */
649 	if (arm64_bus_method == ARM64_BUS_NONE) {
650 		if (has_acpi)
651 			arm64_bus_method = ARM64_BUS_ACPI;
652 		else if (has_fdt)
653 			arm64_bus_method = ARM64_BUS_FDT;
654 	}
655 
656 	/*
657 	 * If no option was set the default is valid, otherwise we are
658 	 * setting one to get cninit() working, then calling panic to tell
659 	 * the user about the invalid bus setup.
660 	 */
661 	return (env == NULL);
662 }
663 
664 static void
cache_setup(void)665 cache_setup(void)
666 {
667 	int dczva_line_shift;
668 	uint32_t dczid_el0;
669 
670 	identify_cache(READ_SPECIALREG(ctr_el0));
671 
672 	dczid_el0 = READ_SPECIALREG(dczid_el0);
673 
674 	/* Check if dc zva is not prohibited */
675 	if (dczid_el0 & DCZID_DZP)
676 		dczva_line_size = 0;
677 	else {
678 		/* Same as with above calculations */
679 		dczva_line_shift = DCZID_BS_SIZE(dczid_el0);
680 		dczva_line_size = sizeof(int) << dczva_line_shift;
681 
682 		/* Change pagezero function */
683 		pagezero = pagezero_cache;
684 	}
685 }
686 
687 int
memory_mapping_mode(vm_paddr_t pa)688 memory_mapping_mode(vm_paddr_t pa)
689 {
690 	struct efi_md *map, *p;
691 	size_t efisz;
692 	int ndesc, i;
693 
694 	if (efihdr == NULL)
695 		return (VM_MEMATTR_WRITE_BACK);
696 
697 	/*
698 	 * Memory map data provided by UEFI via the GetMemoryMap
699 	 * Boot Services API.
700 	 */
701 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
702 	map = (struct efi_md *)((uint8_t *)efihdr + efisz);
703 
704 	if (efihdr->descriptor_size == 0)
705 		return (VM_MEMATTR_WRITE_BACK);
706 	ndesc = efihdr->memory_size / efihdr->descriptor_size;
707 
708 	for (i = 0, p = map; i < ndesc; i++,
709 	    p = efi_next_descriptor(p, efihdr->descriptor_size)) {
710 		if (pa < p->md_phys ||
711 		    pa >= p->md_phys + p->md_pages * EFI_PAGE_SIZE)
712 			continue;
713 		if (p->md_type == EFI_MD_TYPE_IOMEM ||
714 		    p->md_type == EFI_MD_TYPE_IOPORT)
715 			return (VM_MEMATTR_DEVICE);
716 		else if ((p->md_attr & EFI_MD_ATTR_WB) != 0 ||
717 		    p->md_type == EFI_MD_TYPE_RECLAIM)
718 			return (VM_MEMATTR_WRITE_BACK);
719 		else if ((p->md_attr & EFI_MD_ATTR_WT) != 0)
720 			return (VM_MEMATTR_WRITE_THROUGH);
721 		else if ((p->md_attr & EFI_MD_ATTR_WC) != 0)
722 			return (VM_MEMATTR_WRITE_COMBINING);
723 		break;
724 	}
725 
726 	return (VM_MEMATTR_DEVICE);
727 }
728 
729 #ifdef FDT
730 static void
fdt_physmem_hardware_region_cb(const struct mem_region * mr,void * arg __unused)731 fdt_physmem_hardware_region_cb(const struct mem_region *mr, void *arg __unused)
732 {
733 	physmem_hardware_region(mr->mr_start, mr->mr_size);
734 }
735 
736 static void
fdt_physmem_exclude_region_cb(const struct mem_region * mr,void * arg __unused)737 fdt_physmem_exclude_region_cb(const struct mem_region *mr, void *arg __unused)
738 {
739 	physmem_exclude_region(mr->mr_start, mr->mr_size,
740 	    EXFLAG_NODUMP | EXFLAG_NOALLOC);
741 }
742 #endif
743 
744 void
initarm(struct arm64_bootparams * abp)745 initarm(struct arm64_bootparams *abp)
746 {
747 	struct efi_fb *efifb;
748 	struct pcpu *pcpup;
749 	char *env;
750 #ifdef FDT
751 	phandle_t root;
752 	char dts_version[255];
753 #endif
754 	vm_offset_t lastaddr;
755 	bool valid;
756 
757 	TSRAW(&thread0, TS_ENTER, __func__, NULL);
758 
759 	boot_el = abp->boot_el;
760 
761 	/* Parse loader or FDT boot parameters. Determine last used address. */
762 	lastaddr = parse_boot_param(abp);
763 
764 	identify_cpu(0);
765 	identify_hypervisor_smbios();
766 
767 	update_special_regs(0);
768 
769 	/* Set the pcpu data, this is needed by pmap_bootstrap */
770 	pcpup = &pcpu0;
771 	pcpu_init(pcpup, 0, sizeof(struct pcpu));
772 
773 	/*
774 	 * Set the pcpu pointer with a backup in tpidr_el1 to be
775 	 * loaded when entering the kernel from userland.
776 	 */
777 	__asm __volatile(
778 	    "mov x18, %0 \n"
779 	    "msr tpidr_el1, %0" :: "r"(pcpup));
780 
781 	/* locore.S sets sp_el0 to &thread0 so no need to set it here. */
782 	PCPU_SET(curthread, &thread0);
783 	PCPU_SET(midr, get_midr());
784 
785 	link_elf_ireloc();
786 #ifdef FDT
787 	try_load_dtb();
788 #endif
789 
790 	efi_systbl_phys = MD_FETCH(preload_kmdp, MODINFOMD_FW_HANDLE,
791 	    vm_paddr_t);
792 
793 	/* Load the physical memory ranges */
794 	efihdr = (struct efi_map_header *)preload_search_info(preload_kmdp,
795 	    MODINFO_METADATA | MODINFOMD_EFI_MAP);
796 	if (efihdr != NULL)
797 		efi_map_add_entries(efihdr);
798 #ifdef FDT
799 	else {
800 		/* Grab physical memory regions information from device tree. */
801 		if (fdt_foreach_mem_region(fdt_physmem_hardware_region_cb,
802 		    NULL) != 0)
803 			panic("Cannot get physical memory regions");
804 	}
805 	fdt_foreach_reserved_mem(fdt_physmem_exclude_region_cb, NULL);
806 #endif
807 
808 	/* Exclude the EFI framebuffer from our view of physical memory. */
809 	efifb = (struct efi_fb *)preload_search_info(preload_kmdp,
810 	    MODINFO_METADATA | MODINFOMD_EFI_FB);
811 	if (efifb != NULL)
812 		physmem_exclude_region(efifb->fb_addr, efifb->fb_size,
813 		    EXFLAG_NOALLOC);
814 
815 	/* Do basic tuning, hz etc */
816 	init_param1();
817 
818 	cache_setup();
819 
820 	/*
821 	 * Perform a staged bootstrap of virtual memory.
822 	 *
823 	 * - First we create the DMAP region. This allows it to be used in
824 	 *   later bootstrapping.
825 	 * - Next exclude memory that is needed in the DMAP region, but must
826 	 *   not be used by FreeBSD.
827 	 * - Lastly complete the bootstrapping. It may use the physical
828 	 *   memory map so any excluded memory must be marked as such before
829 	 *   pmap_bootstrap() is called.
830 	 */
831 	pmap_bootstrap_dmap(lastaddr - KERNBASE);
832 	/*
833 	 * Exclude EFI entries needed in the DMAP, e.g. EFI_MD_TYPE_RECLAIM
834 	 * may contain the ACPI tables but shouldn't be used by the kernel
835 	 */
836 	if (efihdr != NULL)
837 		efi_map_exclude_entries(efihdr);
838 	/*  Do the same for reserve entries in the EFI MEMRESERVE table */
839 	if (efi_systbl_phys != 0)
840 		exclude_efi_memreserve(efi_systbl_phys);
841 	/* Continue bootstrapping pmap */
842 	pmap_bootstrap();
843 
844 	/*
845 	 * We carefully bootstrap the sanitizer map after we've excluded
846 	 * absolutely everything else that could impact phys_avail.  There's not
847 	 * always enough room for the initial shadow map after the kernel, so
848 	 * we'll end up searching for segments that we can safely use.  Those
849 	 * segments also get excluded from phys_avail.
850 	 */
851 #if defined(KASAN) || defined(KMSAN)
852 	pmap_bootstrap_san();
853 #endif
854 
855 	physmem_init_kernel_globals();
856 
857 	valid = bus_probe();
858 
859 	cninit();
860 	set_ttbr0(abp->kern_ttbr0);
861 	pmap_s1_invalidate_all_kernel();
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