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_platform.h"
30 #include "opt_ddb.h"
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD: stable/12/sys/arm64/arm64/machdep.c 371211 2021-12-13 00:30:18Z emaste $");
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/buf.h>
38 #include <sys/bus.h>
39 #include <sys/cons.h>
40 #include <sys/cpu.h>
41 #include <sys/devmap.h>
42 #include <sys/efi.h>
43 #include <sys/exec.h>
44 #include <sys/imgact.h>
45 #include <sys/kdb.h>
46 #include <sys/kernel.h>
47 #include <sys/limits.h>
48 #include <sys/linker.h>
49 #include <sys/msgbuf.h>
50 #include <sys/pcpu.h>
51 #include <sys/physmem.h>
52 #include <sys/proc.h>
53 #include <sys/ptrace.h>
54 #include <sys/reboot.h>
55 #include <sys/rwlock.h>
56 #include <sys/sched.h>
57 #include <sys/signalvar.h>
58 #include <sys/syscallsubr.h>
59 #include <sys/sysent.h>
60 #include <sys/sysproto.h>
61 #include <sys/ucontext.h>
62 #include <sys/vdso.h>
63 #include <sys/vmmeter.h>
64 
65 #include <vm/vm.h>
66 #include <vm/vm_param.h>
67 #include <vm/vm_kern.h>
68 #include <vm/vm_object.h>
69 #include <vm/vm_page.h>
70 #include <vm/vm_phys.h>
71 #include <vm/pmap.h>
72 #include <vm/vm_map.h>
73 #include <vm/vm_pager.h>
74 
75 #include <machine/armreg.h>
76 #include <machine/cpu.h>
77 #include <machine/debug_monitor.h>
78 #include <machine/kdb.h>
79 #include <machine/machdep.h>
80 #include <machine/metadata.h>
81 #include <machine/md_var.h>
82 #include <machine/pcb.h>
83 #include <machine/reg.h>
84 #include <machine/undefined.h>
85 #include <machine/vmparam.h>
86 
87 #ifdef VFP
88 #include <machine/vfp.h>
89 #endif
90 
91 #ifdef DEV_ACPI
92 #include <contrib/dev/acpica/include/acpi.h>
93 #include <machine/acpica_machdep.h>
94 #endif
95 
96 #ifdef FDT
97 #include <dev/fdt/fdt_common.h>
98 #include <dev/ofw/openfirm.h>
99 #endif
100 
101 static void get_fpcontext(struct thread *td, mcontext_t *mcp);
102 static void set_fpcontext(struct thread *td, mcontext_t *mcp);
103 
104 enum arm64_bus arm64_bus_method = ARM64_BUS_NONE;
105 
106 struct pcpu __pcpu[MAXCPU];
107 
108 static struct trapframe proc0_tf;
109 
110 int early_boot = 1;
111 int cold = 1;
112 
113 struct kva_md_info kmi;
114 
115 int64_t dcache_line_size;	/* The minimum D cache line size */
116 int64_t icache_line_size;	/* The minimum I cache line size */
117 int64_t idcache_line_size;	/* The minimum cache line size */
118 int64_t dczva_line_size;	/* The size of cache line the dc zva zeroes */
119 int has_pan;
120 
121 /*
122  * Physical address of the EFI System Table. Stashed from the metadata hints
123  * passed into the kernel and used by the EFI code to call runtime services.
124  */
125 vm_paddr_t efi_systbl_phys;
126 
127 /* pagezero_* implementations are provided in support.S */
128 void pagezero_simple(void *);
129 void pagezero_cache(void *);
130 
131 /* pagezero_simple is default pagezero */
132 void (*pagezero)(void *p) = pagezero_simple;
133 
134 int (*apei_nmi)(void);
135 
136 static void
pan_setup(void)137 pan_setup(void)
138 {
139 	uint64_t id_aa64mfr1;
140 
141 	id_aa64mfr1 = READ_SPECIALREG(id_aa64mmfr1_el1);
142 	if (ID_AA64MMFR1_PAN(id_aa64mfr1) != ID_AA64MMFR1_PAN_NONE)
143 		has_pan = 1;
144 }
145 
146 void
pan_enable(void)147 pan_enable(void)
148 {
149 
150 	/*
151 	 * The LLVM integrated assembler doesn't understand the PAN
152 	 * PSTATE field. Because of this we need to manually create
153 	 * the instruction in an asm block. This is equivalent to:
154 	 * msr pan, #1
155 	 *
156 	 * This sets the PAN bit, stopping the kernel from accessing
157 	 * memory when userspace can also access it unless the kernel
158 	 * uses the userspace load/store instructions.
159 	 */
160 	if (has_pan) {
161 		WRITE_SPECIALREG(sctlr_el1,
162 		    READ_SPECIALREG(sctlr_el1) & ~SCTLR_SPAN);
163 		__asm __volatile(".inst 0xd500409f | (0x1 << 8)");
164 	}
165 }
166 
167 static void
cpu_startup(void * dummy)168 cpu_startup(void *dummy)
169 {
170 	vm_paddr_t size;
171 	int i;
172 
173 	printf("real memory  = %ju (%ju MB)\n", ptoa((uintmax_t)realmem),
174 	    ptoa((uintmax_t)realmem) / 1024 / 1024);
175 
176 	if (bootverbose) {
177 		printf("Physical memory chunk(s):\n");
178 		for (i = 0; phys_avail[i + 1] != 0; i += 2) {
179 			size = phys_avail[i + 1] - phys_avail[i];
180 			printf("%#016jx - %#016jx, %ju bytes (%ju pages)\n",
181 			    (uintmax_t)phys_avail[i],
182 			    (uintmax_t)phys_avail[i + 1] - 1,
183 			    (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
184 		}
185 	}
186 
187 	printf("avail memory = %ju (%ju MB)\n",
188 	    ptoa((uintmax_t)vm_free_count()),
189 	    ptoa((uintmax_t)vm_free_count()) / 1024 / 1024);
190 
191 	undef_init();
192 	identify_cpu();
193 	install_cpu_errata();
194 
195 	vm_ksubmap_init(&kmi);
196 	bufinit();
197 	vm_pager_bufferinit();
198 }
199 
200 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
201 
202 int
cpu_idle_wakeup(int cpu)203 cpu_idle_wakeup(int cpu)
204 {
205 
206 	return (0);
207 }
208 
209 int
fill_regs(struct thread * td,struct reg * regs)210 fill_regs(struct thread *td, struct reg *regs)
211 {
212 	struct trapframe *frame;
213 
214 	frame = td->td_frame;
215 	regs->sp = frame->tf_sp;
216 	regs->lr = frame->tf_lr;
217 	regs->elr = frame->tf_elr;
218 	regs->spsr = frame->tf_spsr;
219 
220 	memcpy(regs->x, frame->tf_x, sizeof(regs->x));
221 
222 	return (0);
223 }
224 
225 int
set_regs(struct thread * td,struct reg * regs)226 set_regs(struct thread *td, struct reg *regs)
227 {
228 	struct trapframe *frame;
229 
230 	frame = td->td_frame;
231 	frame->tf_sp = regs->sp;
232 	frame->tf_lr = regs->lr;
233 	frame->tf_elr = regs->elr;
234 	frame->tf_spsr &= ~PSR_FLAGS;
235 	frame->tf_spsr |= regs->spsr & PSR_FLAGS;
236 
237 	memcpy(frame->tf_x, regs->x, sizeof(frame->tf_x));
238 
239 	return (0);
240 }
241 
242 int
fill_fpregs(struct thread * td,struct fpreg * regs)243 fill_fpregs(struct thread *td, struct fpreg *regs)
244 {
245 #ifdef VFP
246 	struct pcb *pcb;
247 
248 	pcb = td->td_pcb;
249 	if ((pcb->pcb_fpflags & PCB_FP_STARTED) != 0) {
250 		/*
251 		 * If we have just been running VFP instructions we will
252 		 * need to save the state to memcpy it below.
253 		 */
254 		if (td == curthread)
255 			vfp_save_state(td, pcb);
256 
257 		KASSERT(pcb->pcb_fpusaved == &pcb->pcb_fpustate,
258 		    ("Called fill_fpregs while the kernel is using the VFP"));
259 		memcpy(regs->fp_q, pcb->pcb_fpustate.vfp_regs,
260 		    sizeof(regs->fp_q));
261 		regs->fp_cr = pcb->pcb_fpustate.vfp_fpcr;
262 		regs->fp_sr = pcb->pcb_fpustate.vfp_fpsr;
263 	} else
264 #endif
265 		memset(regs, 0, sizeof(*regs));
266 	return (0);
267 }
268 
269 int
set_fpregs(struct thread * td,struct fpreg * regs)270 set_fpregs(struct thread *td, struct fpreg *regs)
271 {
272 #ifdef VFP
273 	struct pcb *pcb;
274 
275 	pcb = td->td_pcb;
276 	KASSERT(pcb->pcb_fpusaved == &pcb->pcb_fpustate,
277 	    ("Called set_fpregs while the kernel is using the VFP"));
278 	memcpy(pcb->pcb_fpustate.vfp_regs, regs->fp_q, sizeof(regs->fp_q));
279 	pcb->pcb_fpustate.vfp_fpcr = regs->fp_cr;
280 	pcb->pcb_fpustate.vfp_fpsr = regs->fp_sr;
281 #endif
282 	return (0);
283 }
284 
285 int
fill_dbregs(struct thread * td,struct dbreg * regs)286 fill_dbregs(struct thread *td, struct dbreg *regs)
287 {
288 
289 	printf("ARM64TODO: fill_dbregs");
290 	return (EDOOFUS);
291 }
292 
293 int
set_dbregs(struct thread * td,struct dbreg * regs)294 set_dbregs(struct thread *td, struct dbreg *regs)
295 {
296 
297 	printf("ARM64TODO: set_dbregs");
298 	return (EDOOFUS);
299 }
300 
301 #ifdef COMPAT_FREEBSD32
302 int
fill_regs32(struct thread * td,struct reg32 * regs)303 fill_regs32(struct thread *td, struct reg32 *regs)
304 {
305 
306 	printf("ARM64TODO: fill_regs32");
307 	return (EDOOFUS);
308 }
309 
310 int
set_regs32(struct thread * td,struct reg32 * regs)311 set_regs32(struct thread *td, struct reg32 *regs)
312 {
313 
314 	printf("ARM64TODO: set_regs32");
315 	return (EDOOFUS);
316 }
317 
318 /* XXX fill/set dbregs/fpregs are stubbed on 32-bit arm. */
319 int
fill_fpregs32(struct thread * td,struct fpreg32 * regs)320 fill_fpregs32(struct thread *td, struct fpreg32 *regs)
321 {
322 
323 	memset(regs, 0, sizeof(*regs));
324 	return (0);
325 }
326 
327 int
set_fpregs32(struct thread * td,struct fpreg32 * regs)328 set_fpregs32(struct thread *td, struct fpreg32 *regs)
329 {
330 
331 	return (0);
332 }
333 
334 int
fill_dbregs32(struct thread * td,struct dbreg32 * regs)335 fill_dbregs32(struct thread *td, struct dbreg32 *regs)
336 {
337 
338 	memset(regs, 0, sizeof(*regs));
339 	return (0);
340 }
341 
342 int
set_dbregs32(struct thread * td,struct dbreg32 * regs)343 set_dbregs32(struct thread *td, struct dbreg32 *regs)
344 {
345 
346 	return (0);
347 }
348 #endif
349 
350 int
ptrace_set_pc(struct thread * td,u_long addr)351 ptrace_set_pc(struct thread *td, u_long addr)
352 {
353 
354 	printf("ARM64TODO: ptrace_set_pc");
355 	return (EDOOFUS);
356 }
357 
358 int
ptrace_single_step(struct thread * td)359 ptrace_single_step(struct thread *td)
360 {
361 
362 	td->td_frame->tf_spsr |= PSR_SS;
363 	td->td_pcb->pcb_flags |= PCB_SINGLE_STEP;
364 	return (0);
365 }
366 
367 int
ptrace_clear_single_step(struct thread * td)368 ptrace_clear_single_step(struct thread *td)
369 {
370 
371 	td->td_frame->tf_spsr &= ~PSR_SS;
372 	td->td_pcb->pcb_flags &= ~PCB_SINGLE_STEP;
373 	return (0);
374 }
375 
376 void
exec_setregs(struct thread * td,struct image_params * imgp,u_long stack)377 exec_setregs(struct thread *td, struct image_params *imgp, u_long stack)
378 {
379 	struct trapframe *tf = td->td_frame;
380 
381 	memset(tf, 0, sizeof(struct trapframe));
382 
383 	tf->tf_x[0] = stack;
384 	tf->tf_sp = STACKALIGN(stack);
385 	tf->tf_lr = imgp->entry_addr;
386 	tf->tf_elr = imgp->entry_addr;
387 }
388 
389 /* Sanity check these are the same size, they will be memcpy'd to and fro */
390 CTASSERT(sizeof(((struct trapframe *)0)->tf_x) ==
391     sizeof((struct gpregs *)0)->gp_x);
392 CTASSERT(sizeof(((struct trapframe *)0)->tf_x) ==
393     sizeof((struct reg *)0)->x);
394 
395 int
get_mcontext(struct thread * td,mcontext_t * mcp,int clear_ret)396 get_mcontext(struct thread *td, mcontext_t *mcp, int clear_ret)
397 {
398 	struct trapframe *tf = td->td_frame;
399 
400 	if (clear_ret & GET_MC_CLEAR_RET) {
401 		mcp->mc_gpregs.gp_x[0] = 0;
402 		mcp->mc_gpregs.gp_spsr = tf->tf_spsr & ~PSR_C;
403 	} else {
404 		mcp->mc_gpregs.gp_x[0] = tf->tf_x[0];
405 		mcp->mc_gpregs.gp_spsr = tf->tf_spsr;
406 	}
407 
408 	memcpy(&mcp->mc_gpregs.gp_x[1], &tf->tf_x[1],
409 	    sizeof(mcp->mc_gpregs.gp_x[1]) * (nitems(mcp->mc_gpregs.gp_x) - 1));
410 
411 	mcp->mc_gpregs.gp_sp = tf->tf_sp;
412 	mcp->mc_gpregs.gp_lr = tf->tf_lr;
413 	mcp->mc_gpregs.gp_elr = tf->tf_elr;
414 	get_fpcontext(td, mcp);
415 
416 	return (0);
417 }
418 
419 int
set_mcontext(struct thread * td,mcontext_t * mcp)420 set_mcontext(struct thread *td, mcontext_t *mcp)
421 {
422 	struct trapframe *tf = td->td_frame;
423 	uint32_t spsr;
424 
425 	spsr = mcp->mc_gpregs.gp_spsr;
426 	if ((spsr & PSR_M_MASK) != PSR_M_EL0t ||
427 	    (spsr & (PSR_AARCH32 | PSR_F | PSR_I | PSR_A | PSR_D)) != 0)
428 		return (EINVAL);
429 
430 	memcpy(tf->tf_x, mcp->mc_gpregs.gp_x, sizeof(tf->tf_x));
431 
432 	tf->tf_sp = mcp->mc_gpregs.gp_sp;
433 	tf->tf_lr = mcp->mc_gpregs.gp_lr;
434 	tf->tf_elr = mcp->mc_gpregs.gp_elr;
435 	tf->tf_spsr = mcp->mc_gpregs.gp_spsr;
436 	set_fpcontext(td, mcp);
437 
438 	return (0);
439 }
440 
441 static void
get_fpcontext(struct thread * td,mcontext_t * mcp)442 get_fpcontext(struct thread *td, mcontext_t *mcp)
443 {
444 #ifdef VFP
445 	struct pcb *curpcb;
446 
447 	critical_enter();
448 
449 	curpcb = curthread->td_pcb;
450 
451 	if ((curpcb->pcb_fpflags & PCB_FP_STARTED) != 0) {
452 		/*
453 		 * If we have just been running VFP instructions we will
454 		 * need to save the state to memcpy it below.
455 		 */
456 		vfp_save_state(td, curpcb);
457 
458 		KASSERT(curpcb->pcb_fpusaved == &curpcb->pcb_fpustate,
459 		    ("Called get_fpcontext while the kernel is using the VFP"));
460 		KASSERT((curpcb->pcb_fpflags & ~PCB_FP_USERMASK) == 0,
461 		    ("Non-userspace FPU flags set in get_fpcontext"));
462 		memcpy(mcp->mc_fpregs.fp_q, curpcb->pcb_fpustate.vfp_regs,
463 		    sizeof(mcp->mc_fpregs));
464 		mcp->mc_fpregs.fp_cr = curpcb->pcb_fpustate.vfp_fpcr;
465 		mcp->mc_fpregs.fp_sr = curpcb->pcb_fpustate.vfp_fpsr;
466 		mcp->mc_fpregs.fp_flags = curpcb->pcb_fpflags;
467 		mcp->mc_flags |= _MC_FP_VALID;
468 	}
469 
470 	critical_exit();
471 #endif
472 }
473 
474 static void
set_fpcontext(struct thread * td,mcontext_t * mcp)475 set_fpcontext(struct thread *td, mcontext_t *mcp)
476 {
477 #ifdef VFP
478 	struct pcb *curpcb;
479 
480 	critical_enter();
481 
482 	if ((mcp->mc_flags & _MC_FP_VALID) != 0) {
483 		curpcb = curthread->td_pcb;
484 
485 		/*
486 		 * Discard any vfp state for the current thread, we
487 		 * are about to override it.
488 		 */
489 		vfp_discard(td);
490 
491 		KASSERT(curpcb->pcb_fpusaved == &curpcb->pcb_fpustate,
492 		    ("Called set_fpcontext while the kernel is using the VFP"));
493 		memcpy(curpcb->pcb_fpustate.vfp_regs, mcp->mc_fpregs.fp_q,
494 		    sizeof(mcp->mc_fpregs));
495 		curpcb->pcb_fpustate.vfp_fpcr = mcp->mc_fpregs.fp_cr;
496 		curpcb->pcb_fpustate.vfp_fpsr = mcp->mc_fpregs.fp_sr;
497 		curpcb->pcb_fpflags = mcp->mc_fpregs.fp_flags & PCB_FP_USERMASK;
498 	}
499 
500 	critical_exit();
501 #endif
502 }
503 
504 void
cpu_idle(int busy)505 cpu_idle(int busy)
506 {
507 
508 	spinlock_enter();
509 	if (!busy)
510 		cpu_idleclock();
511 	if (!sched_runnable())
512 		__asm __volatile(
513 		    "dsb sy \n"
514 		    "wfi    \n");
515 	if (!busy)
516 		cpu_activeclock();
517 	spinlock_exit();
518 }
519 
520 void
cpu_halt(void)521 cpu_halt(void)
522 {
523 
524 	/* We should have shutdown by now, if not enter a low power sleep */
525 	intr_disable();
526 	while (1) {
527 		__asm __volatile("wfi");
528 	}
529 }
530 
531 /*
532  * Flush the D-cache for non-DMA I/O so that the I-cache can
533  * be made coherent later.
534  */
535 void
cpu_flush_dcache(void * ptr,size_t len)536 cpu_flush_dcache(void *ptr, size_t len)
537 {
538 
539 	/* ARM64TODO TBD */
540 }
541 
542 /* Get current clock frequency for the given CPU ID. */
543 int
cpu_est_clockrate(int cpu_id,uint64_t * rate)544 cpu_est_clockrate(int cpu_id, uint64_t *rate)
545 {
546 	struct pcpu *pc;
547 
548 	pc = pcpu_find(cpu_id);
549 	if (pc == NULL || rate == NULL)
550 		return (EINVAL);
551 
552 	if (pc->pc_clock == 0)
553 		return (EOPNOTSUPP);
554 
555 	*rate = pc->pc_clock;
556 	return (0);
557 }
558 
559 void
cpu_pcpu_init(struct pcpu * pcpu,int cpuid,size_t size)560 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
561 {
562 
563 	pcpu->pc_acpi_id = 0xffffffff;
564 }
565 
566 void
spinlock_enter(void)567 spinlock_enter(void)
568 {
569 	struct thread *td;
570 	register_t daif;
571 
572 	td = curthread;
573 	if (td->td_md.md_spinlock_count == 0) {
574 		daif = intr_disable();
575 		td->td_md.md_spinlock_count = 1;
576 		td->td_md.md_saved_daif = daif;
577 	} else
578 		td->td_md.md_spinlock_count++;
579 	critical_enter();
580 }
581 
582 void
spinlock_exit(void)583 spinlock_exit(void)
584 {
585 	struct thread *td;
586 	register_t daif;
587 
588 	td = curthread;
589 	critical_exit();
590 	daif = td->td_md.md_saved_daif;
591 	td->td_md.md_spinlock_count--;
592 	if (td->td_md.md_spinlock_count == 0)
593 		intr_restore(daif);
594 }
595 
596 #ifndef	_SYS_SYSPROTO_H_
597 struct sigreturn_args {
598 	ucontext_t *ucp;
599 };
600 #endif
601 
602 int
sys_sigreturn(struct thread * td,struct sigreturn_args * uap)603 sys_sigreturn(struct thread *td, struct sigreturn_args *uap)
604 {
605 	ucontext_t uc;
606 	int error;
607 
608 	if (copyin(uap->sigcntxp, &uc, sizeof(uc)))
609 		return (EFAULT);
610 
611 	error = set_mcontext(td, &uc.uc_mcontext);
612 	if (error != 0)
613 		return (error);
614 
615 	/* Restore signal mask. */
616 	kern_sigprocmask(td, SIG_SETMASK, &uc.uc_sigmask, NULL, 0);
617 
618 	return (EJUSTRETURN);
619 }
620 
621 /*
622  * Construct a PCB from a trapframe. This is called from kdb_trap() where
623  * we want to start a backtrace from the function that caused us to enter
624  * the debugger. We have the context in the trapframe, but base the trace
625  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
626  * enough for a backtrace.
627  */
628 void
makectx(struct trapframe * tf,struct pcb * pcb)629 makectx(struct trapframe *tf, struct pcb *pcb)
630 {
631 	int i;
632 
633 	for (i = 0; i < nitems(pcb->pcb_x); i++)
634 		pcb->pcb_x[i] = tf->tf_x[i];
635 
636 	/* NB: pcb_lr is the PC, see PC_REGS() in db_machdep.h */
637 	pcb->pcb_lr = tf->tf_elr;
638 	pcb->pcb_sp = tf->tf_sp;
639 }
640 
641 void
sendsig(sig_t catcher,ksiginfo_t * ksi,sigset_t * mask)642 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
643 {
644 	struct thread *td;
645 	struct proc *p;
646 	struct trapframe *tf;
647 	struct sigframe *fp, frame;
648 	struct sigacts *psp;
649 	struct sysentvec *sysent;
650 	int onstack, sig;
651 
652 	td = curthread;
653 	p = td->td_proc;
654 	PROC_LOCK_ASSERT(p, MA_OWNED);
655 
656 	sig = ksi->ksi_signo;
657 	psp = p->p_sigacts;
658 	mtx_assert(&psp->ps_mtx, MA_OWNED);
659 
660 	tf = td->td_frame;
661 	onstack = sigonstack(tf->tf_sp);
662 
663 	CTR4(KTR_SIG, "sendsig: td=%p (%s) catcher=%p sig=%d", td, p->p_comm,
664 	    catcher, sig);
665 
666 	/* Allocate and validate space for the signal handler context. */
667 	if ((td->td_pflags & TDP_ALTSTACK) != 0 && !onstack &&
668 	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
669 		fp = (struct sigframe *)((uintptr_t)td->td_sigstk.ss_sp +
670 		    td->td_sigstk.ss_size);
671 #if defined(COMPAT_43)
672 		td->td_sigstk.ss_flags |= SS_ONSTACK;
673 #endif
674 	} else {
675 		fp = (struct sigframe *)td->td_frame->tf_sp;
676 	}
677 
678 	/* Make room, keeping the stack aligned */
679 	fp--;
680 	fp = (struct sigframe *)STACKALIGN(fp);
681 
682 	/* Fill in the frame to copy out */
683 	bzero(&frame, sizeof(frame));
684 	get_mcontext(td, &frame.sf_uc.uc_mcontext, 0);
685 	frame.sf_si = ksi->ksi_info;
686 	frame.sf_uc.uc_sigmask = *mask;
687 	frame.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK) ?
688 	    ((onstack) ? SS_ONSTACK : 0) : SS_DISABLE;
689 	frame.sf_uc.uc_stack = td->td_sigstk;
690 	mtx_unlock(&psp->ps_mtx);
691 	PROC_UNLOCK(td->td_proc);
692 
693 	/* Copy the sigframe out to the user's stack. */
694 	if (copyout(&frame, fp, sizeof(*fp)) != 0) {
695 		/* Process has trashed its stack. Kill it. */
696 		CTR2(KTR_SIG, "sendsig: sigexit td=%p fp=%p", td, fp);
697 		PROC_LOCK(p);
698 		sigexit(td, SIGILL);
699 	}
700 
701 	tf->tf_x[0]= sig;
702 	tf->tf_x[1] = (register_t)&fp->sf_si;
703 	tf->tf_x[2] = (register_t)&fp->sf_uc;
704 
705 	tf->tf_elr = (register_t)catcher;
706 	tf->tf_sp = (register_t)fp;
707 	sysent = p->p_sysent;
708 	if (sysent->sv_sigcode_base != 0)
709 		tf->tf_lr = (register_t)sysent->sv_sigcode_base;
710 	else
711 		tf->tf_lr = (register_t)(sysent->sv_psstrings -
712 		    *(sysent->sv_szsigcode));
713 
714 	CTR3(KTR_SIG, "sendsig: return td=%p pc=%#x sp=%#x", td, tf->tf_elr,
715 	    tf->tf_sp);
716 
717 	PROC_LOCK(p);
718 	mtx_lock(&psp->ps_mtx);
719 }
720 
721 static void
init_proc0(vm_offset_t kstack)722 init_proc0(vm_offset_t kstack)
723 {
724 	struct pcpu *pcpup = &__pcpu[0];
725 
726 	proc_linkup0(&proc0, &thread0);
727 	thread0.td_kstack = kstack;
728 	thread0.td_kstack_pages = KSTACK_PAGES;
729 	thread0.td_pcb = (struct pcb *)(thread0.td_kstack +
730 	    thread0.td_kstack_pages * PAGE_SIZE) - 1;
731 	thread0.td_pcb->pcb_fpflags = 0;
732 	thread0.td_pcb->pcb_fpusaved = &thread0.td_pcb->pcb_fpustate;
733 	thread0.td_pcb->pcb_vfpcpu = UINT_MAX;
734 	thread0.td_frame = &proc0_tf;
735 	pcpup->pc_curpcb = thread0.td_pcb;
736 
737 	/* Set the base address of translation table 0. */
738 	thread0.td_proc->p_md.md_l0addr = READ_SPECIALREG(ttbr0_el1);
739 }
740 
741 typedef struct {
742 	uint32_t type;
743 	uint64_t phys_start;
744 	uint64_t virt_start;
745 	uint64_t num_pages;
746 	uint64_t attr;
747 } EFI_MEMORY_DESCRIPTOR;
748 
749 typedef void (*efi_map_entry_cb)(struct efi_md *);
750 
751 static void
foreach_efi_map_entry(struct efi_map_header * efihdr,efi_map_entry_cb cb)752 foreach_efi_map_entry(struct efi_map_header *efihdr, efi_map_entry_cb cb)
753 {
754 	struct efi_md *map, *p;
755 	size_t efisz;
756 	int ndesc, i;
757 
758 	/*
759 	 * Memory map data provided by UEFI via the GetMemoryMap
760 	 * Boot Services API.
761 	 */
762 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
763 	map = (struct efi_md *)((uint8_t *)efihdr + efisz);
764 
765 	if (efihdr->descriptor_size == 0)
766 		return;
767 	ndesc = efihdr->memory_size / efihdr->descriptor_size;
768 
769 	for (i = 0, p = map; i < ndesc; i++,
770 	    p = efi_next_descriptor(p, efihdr->descriptor_size)) {
771 		cb(p);
772 	}
773 }
774 
775 static void
exclude_efi_map_entry(struct efi_md * p)776 exclude_efi_map_entry(struct efi_md *p)
777 {
778 
779 	switch (p->md_type) {
780 	case EFI_MD_TYPE_CODE:
781 	case EFI_MD_TYPE_DATA:
782 	case EFI_MD_TYPE_BS_CODE:
783 	case EFI_MD_TYPE_BS_DATA:
784 	case EFI_MD_TYPE_FREE:
785 		/*
786 		 * We're allowed to use any entry with these types.
787 		 */
788 		break;
789 	default:
790 		physmem_exclude_region(p->md_phys, p->md_pages * PAGE_SIZE,
791 		    EXFLAG_NOALLOC);
792 	}
793 }
794 
795 static void
exclude_efi_map_entries(struct efi_map_header * efihdr)796 exclude_efi_map_entries(struct efi_map_header *efihdr)
797 {
798 
799 	foreach_efi_map_entry(efihdr, exclude_efi_map_entry);
800 }
801 
802 static void
add_efi_map_entry(struct efi_md * p)803 add_efi_map_entry(struct efi_md *p)
804 {
805 
806 	switch (p->md_type) {
807 	case EFI_MD_TYPE_RT_DATA:
808 		/*
809 		 * Runtime data will be excluded after the DMAP
810 		 * region is created to stop it from being added
811 		 * to phys_avail.
812 		 */
813 	case EFI_MD_TYPE_CODE:
814 	case EFI_MD_TYPE_DATA:
815 	case EFI_MD_TYPE_BS_CODE:
816 	case EFI_MD_TYPE_BS_DATA:
817 	case EFI_MD_TYPE_FREE:
818 		/*
819 		 * We're allowed to use any entry with these types.
820 		 */
821 		physmem_hardware_region(p->md_phys,
822 		    p->md_pages * PAGE_SIZE);
823 		break;
824 	}
825 }
826 
827 static void
add_efi_map_entries(struct efi_map_header * efihdr)828 add_efi_map_entries(struct efi_map_header *efihdr)
829 {
830 
831 	foreach_efi_map_entry(efihdr, add_efi_map_entry);
832 }
833 
834 static void
print_efi_map_entry(struct efi_md * p)835 print_efi_map_entry(struct efi_md *p)
836 {
837 	const char *type;
838 	static const char *types[] = {
839 		"Reserved",
840 		"LoaderCode",
841 		"LoaderData",
842 		"BootServicesCode",
843 		"BootServicesData",
844 		"RuntimeServicesCode",
845 		"RuntimeServicesData",
846 		"ConventionalMemory",
847 		"UnusableMemory",
848 		"ACPIReclaimMemory",
849 		"ACPIMemoryNVS",
850 		"MemoryMappedIO",
851 		"MemoryMappedIOPortSpace",
852 		"PalCode",
853 		"PersistentMemory"
854 	};
855 
856 	if (p->md_type < nitems(types))
857 		type = types[p->md_type];
858 	else
859 		type = "<INVALID>";
860 	printf("%23s %012lx %12p %08lx ", type, p->md_phys,
861 	    p->md_virt, p->md_pages);
862 	if (p->md_attr & EFI_MD_ATTR_UC)
863 		printf("UC ");
864 	if (p->md_attr & EFI_MD_ATTR_WC)
865 		printf("WC ");
866 	if (p->md_attr & EFI_MD_ATTR_WT)
867 		printf("WT ");
868 	if (p->md_attr & EFI_MD_ATTR_WB)
869 		printf("WB ");
870 	if (p->md_attr & EFI_MD_ATTR_UCE)
871 		printf("UCE ");
872 	if (p->md_attr & EFI_MD_ATTR_WP)
873 		printf("WP ");
874 	if (p->md_attr & EFI_MD_ATTR_RP)
875 		printf("RP ");
876 	if (p->md_attr & EFI_MD_ATTR_XP)
877 		printf("XP ");
878 	if (p->md_attr & EFI_MD_ATTR_NV)
879 		printf("NV ");
880 	if (p->md_attr & EFI_MD_ATTR_MORE_RELIABLE)
881 		printf("MORE_RELIABLE ");
882 	if (p->md_attr & EFI_MD_ATTR_RO)
883 		printf("RO ");
884 	if (p->md_attr & EFI_MD_ATTR_RT)
885 		printf("RUNTIME");
886 	printf("\n");
887 }
888 
889 static void
print_efi_map_entries(struct efi_map_header * efihdr)890 print_efi_map_entries(struct efi_map_header *efihdr)
891 {
892 
893 	printf("%23s %12s %12s %8s %4s\n",
894 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
895 	foreach_efi_map_entry(efihdr, print_efi_map_entry);
896 }
897 
898 #ifdef FDT
899 static void
try_load_dtb(caddr_t kmdp)900 try_load_dtb(caddr_t kmdp)
901 {
902 	vm_offset_t dtbp;
903 
904 	dtbp = MD_FETCH(kmdp, MODINFOMD_DTBP, vm_offset_t);
905 	if (dtbp == (vm_offset_t)NULL) {
906 		printf("ERROR loading DTB\n");
907 		return;
908 	}
909 
910 	if (OF_install(OFW_FDT, 0) == FALSE)
911 		panic("Cannot install FDT");
912 
913 	if (OF_init((void *)dtbp) != 0)
914 		panic("OF_init failed with the found device tree");
915 }
916 #endif
917 
918 static bool
bus_probe(void)919 bus_probe(void)
920 {
921 	bool has_acpi, has_fdt;
922 	char *order, *env;
923 
924 	has_acpi = has_fdt = false;
925 
926 #ifdef FDT
927 	has_fdt = (OF_peer(0) != 0);
928 #endif
929 #ifdef DEV_ACPI
930 	has_acpi = (acpi_find_table(ACPI_SIG_SPCR) != 0);
931 #endif
932 
933 	env = kern_getenv("kern.cfg.order");
934 	if (env != NULL) {
935 		order = env;
936 		while (order != NULL) {
937 			if (has_acpi &&
938 			    strncmp(order, "acpi", 4) == 0 &&
939 			    (order[4] == ',' || order[4] == '\0')) {
940 				arm64_bus_method = ARM64_BUS_ACPI;
941 				break;
942 			}
943 			if (has_fdt &&
944 			    strncmp(order, "fdt", 3) == 0 &&
945 			    (order[3] == ',' || order[3] == '\0')) {
946 				arm64_bus_method = ARM64_BUS_FDT;
947 				break;
948 			}
949 			order = strchr(order, ',');
950 		}
951 		freeenv(env);
952 
953 		/* If we set the bus method it is valid */
954 		if (arm64_bus_method != ARM64_BUS_NONE)
955 			return (true);
956 	}
957 	/* If no order or an invalid order was set use the default */
958 	if (arm64_bus_method == ARM64_BUS_NONE) {
959 		if (has_fdt)
960 			arm64_bus_method = ARM64_BUS_FDT;
961 		else if (has_acpi)
962 			arm64_bus_method = ARM64_BUS_ACPI;
963 	}
964 
965 	/*
966 	 * If no option was set the default is valid, otherwise we are
967 	 * setting one to get cninit() working, then calling panic to tell
968 	 * the user about the invalid bus setup.
969 	 */
970 	return (env == NULL);
971 }
972 
973 static void
cache_setup(void)974 cache_setup(void)
975 {
976 	int dcache_line_shift, icache_line_shift, dczva_line_shift;
977 	uint32_t ctr_el0;
978 	uint32_t dczid_el0;
979 
980 	ctr_el0 = READ_SPECIALREG(ctr_el0);
981 
982 	/* Read the log2 words in each D cache line */
983 	dcache_line_shift = CTR_DLINE_SIZE(ctr_el0);
984 	/* Get the D cache line size */
985 	dcache_line_size = sizeof(int) << dcache_line_shift;
986 
987 	/* And the same for the I cache */
988 	icache_line_shift = CTR_ILINE_SIZE(ctr_el0);
989 	icache_line_size = sizeof(int) << icache_line_shift;
990 
991 	idcache_line_size = MIN(dcache_line_size, icache_line_size);
992 
993 	dczid_el0 = READ_SPECIALREG(dczid_el0);
994 
995 	/* Check if dc zva is not prohibited */
996 	if (dczid_el0 & DCZID_DZP)
997 		dczva_line_size = 0;
998 	else {
999 		/* Same as with above calculations */
1000 		dczva_line_shift = DCZID_BS_SIZE(dczid_el0);
1001 		dczva_line_size = sizeof(int) << dczva_line_shift;
1002 
1003 		/* Change pagezero function */
1004 		pagezero = pagezero_cache;
1005 	}
1006 }
1007 
1008 void
initarm(struct arm64_bootparams * abp)1009 initarm(struct arm64_bootparams *abp)
1010 {
1011 	struct efi_fb *efifb;
1012 	struct efi_map_header *efihdr;
1013 	struct pcpu *pcpup;
1014 	char *env;
1015 #ifdef FDT
1016 	struct mem_region mem_regions[FDT_MEM_REGIONS];
1017 	int mem_regions_sz;
1018 #endif
1019 	vm_offset_t lastaddr;
1020 	caddr_t kmdp;
1021 	bool valid;
1022 
1023 	/* Set the module data location */
1024 	preload_metadata = (caddr_t)(uintptr_t)(abp->modulep);
1025 
1026 	/* Find the kernel address */
1027 	kmdp = preload_search_by_type("elf kernel");
1028 	if (kmdp == NULL)
1029 		kmdp = preload_search_by_type("elf64 kernel");
1030 
1031 	boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
1032 	init_static_kenv(MD_FETCH(kmdp, MODINFOMD_ENVP, char *), 0);
1033 	link_elf_ireloc(kmdp);
1034 
1035 #ifdef FDT
1036 	try_load_dtb(kmdp);
1037 #endif
1038 
1039 	efi_systbl_phys = MD_FETCH(kmdp, MODINFOMD_FW_HANDLE, vm_paddr_t);
1040 
1041 	/* Find the address to start allocating from */
1042 	lastaddr = MD_FETCH(kmdp, MODINFOMD_KERNEND, vm_offset_t);
1043 
1044 	/* Load the physical memory ranges */
1045 	efihdr = (struct efi_map_header *)preload_search_info(kmdp,
1046 	    MODINFO_METADATA | MODINFOMD_EFI_MAP);
1047 	if (efihdr != NULL)
1048 		add_efi_map_entries(efihdr);
1049 #ifdef FDT
1050 	else {
1051 		/* Grab physical memory regions information from device tree. */
1052 		if (fdt_get_mem_regions(mem_regions, &mem_regions_sz,
1053 		    NULL) != 0)
1054 			panic("Cannot get physical memory regions");
1055 		physmem_hardware_regions(mem_regions, mem_regions_sz);
1056 	}
1057 	if (fdt_get_reserved_mem(mem_regions, &mem_regions_sz) == 0)
1058 		physmem_exclude_regions(mem_regions, mem_regions_sz,
1059 		    EXFLAG_NODUMP | EXFLAG_NOALLOC);
1060 #endif
1061 
1062 	/* Exclude the EFI framebuffer from our view of physical memory. */
1063 	efifb = (struct efi_fb *)preload_search_info(kmdp,
1064 	    MODINFO_METADATA | MODINFOMD_EFI_FB);
1065 	if (efifb != NULL)
1066 		physmem_exclude_region(efifb->fb_addr, efifb->fb_size,
1067 		    EXFLAG_NOALLOC);
1068 
1069 	/* Set the pcpu data, this is needed by pmap_bootstrap */
1070 	pcpup = &__pcpu[0];
1071 	pcpu_init(pcpup, 0, sizeof(struct pcpu));
1072 
1073 	/*
1074 	 * Set the pcpu pointer with a backup in tpidr_el1 to be
1075 	 * loaded when entering the kernel from userland.
1076 	 */
1077 	__asm __volatile(
1078 	    "mov x18, %0 \n"
1079 	    "msr tpidr_el1, %0" :: "r"(pcpup));
1080 
1081 	PCPU_SET(curthread, &thread0);
1082 
1083 	/* Do basic tuning, hz etc */
1084 	init_param1();
1085 
1086 	cache_setup();
1087 	pan_setup();
1088 
1089 	/* Bootstrap enough of pmap  to enter the kernel proper */
1090 	pmap_bootstrap(abp->kern_l0pt, abp->kern_l1pt,
1091 	    KERNBASE - abp->kern_delta, lastaddr - KERNBASE);
1092 	/* Exclude entries neexed in teh DMAP region, but not phys_avail */
1093 	if (efihdr != NULL)
1094 		exclude_efi_map_entries(efihdr);
1095 	physmem_init_kernel_globals();
1096 
1097 	devmap_bootstrap(0, NULL);
1098 
1099 	valid = bus_probe();
1100 
1101 	cninit();
1102 
1103 	if (!valid)
1104 		panic("Invalid bus configuration: %s",
1105 		    kern_getenv("kern.cfg.order"));
1106 
1107 	init_proc0(abp->kern_stack);
1108 	msgbufinit(msgbufp, msgbufsize);
1109 	mutex_init();
1110 	init_param2(physmem);
1111 
1112 	dbg_init();
1113 	kdb_init();
1114 	pan_enable();
1115 
1116 	env = kern_getenv("kernelname");
1117 	if (env != NULL)
1118 		strlcpy(kernelname, env, sizeof(kernelname));
1119 
1120 	if (boothowto & RB_VERBOSE) {
1121 		if (efihdr != NULL)
1122 			print_efi_map_entries(efihdr);
1123 		physmem_print_tables();
1124 	}
1125 
1126 	early_boot = 0;
1127 }
1128 
1129 void
dbg_init(void)1130 dbg_init(void)
1131 {
1132 
1133 	/* Clear OS lock */
1134 	WRITE_SPECIALREG(OSLAR_EL1, 0);
1135 
1136 	/* This permits DDB to use debug registers for watchpoints. */
1137 	dbg_monitor_init();
1138 
1139 	/* TODO: Eventually will need to initialize debug registers here. */
1140 }
1141 
1142 #ifdef DDB
1143 #include <ddb/ddb.h>
1144 
DB_SHOW_COMMAND(specialregs,db_show_spregs)1145 DB_SHOW_COMMAND(specialregs, db_show_spregs)
1146 {
1147 #define	PRINT_REG(reg)	\
1148     db_printf(__STRING(reg) " = %#016lx\n", READ_SPECIALREG(reg))
1149 
1150 	PRINT_REG(actlr_el1);
1151 	PRINT_REG(afsr0_el1);
1152 	PRINT_REG(afsr1_el1);
1153 	PRINT_REG(aidr_el1);
1154 	PRINT_REG(amair_el1);
1155 	PRINT_REG(ccsidr_el1);
1156 	PRINT_REG(clidr_el1);
1157 	PRINT_REG(contextidr_el1);
1158 	PRINT_REG(cpacr_el1);
1159 	PRINT_REG(csselr_el1);
1160 	PRINT_REG(ctr_el0);
1161 	PRINT_REG(currentel);
1162 	PRINT_REG(daif);
1163 	PRINT_REG(dczid_el0);
1164 	PRINT_REG(elr_el1);
1165 	PRINT_REG(esr_el1);
1166 	PRINT_REG(far_el1);
1167 #if 0
1168 	/* ARM64TODO: Enable VFP before reading floating-point registers */
1169 	PRINT_REG(fpcr);
1170 	PRINT_REG(fpsr);
1171 #endif
1172 	PRINT_REG(id_aa64afr0_el1);
1173 	PRINT_REG(id_aa64afr1_el1);
1174 	PRINT_REG(id_aa64dfr0_el1);
1175 	PRINT_REG(id_aa64dfr1_el1);
1176 	PRINT_REG(id_aa64isar0_el1);
1177 	PRINT_REG(id_aa64isar1_el1);
1178 	PRINT_REG(id_aa64pfr0_el1);
1179 	PRINT_REG(id_aa64pfr1_el1);
1180 	PRINT_REG(id_afr0_el1);
1181 	PRINT_REG(id_dfr0_el1);
1182 	PRINT_REG(id_isar0_el1);
1183 	PRINT_REG(id_isar1_el1);
1184 	PRINT_REG(id_isar2_el1);
1185 	PRINT_REG(id_isar3_el1);
1186 	PRINT_REG(id_isar4_el1);
1187 	PRINT_REG(id_isar5_el1);
1188 	PRINT_REG(id_mmfr0_el1);
1189 	PRINT_REG(id_mmfr1_el1);
1190 	PRINT_REG(id_mmfr2_el1);
1191 	PRINT_REG(id_mmfr3_el1);
1192 #if 0
1193 	/* Missing from llvm */
1194 	PRINT_REG(id_mmfr4_el1);
1195 #endif
1196 	PRINT_REG(id_pfr0_el1);
1197 	PRINT_REG(id_pfr1_el1);
1198 	PRINT_REG(isr_el1);
1199 	PRINT_REG(mair_el1);
1200 	PRINT_REG(midr_el1);
1201 	PRINT_REG(mpidr_el1);
1202 	PRINT_REG(mvfr0_el1);
1203 	PRINT_REG(mvfr1_el1);
1204 	PRINT_REG(mvfr2_el1);
1205 	PRINT_REG(revidr_el1);
1206 	PRINT_REG(sctlr_el1);
1207 	PRINT_REG(sp_el0);
1208 	PRINT_REG(spsel);
1209 	PRINT_REG(spsr_el1);
1210 	PRINT_REG(tcr_el1);
1211 	PRINT_REG(tpidr_el0);
1212 	PRINT_REG(tpidr_el1);
1213 	PRINT_REG(tpidrro_el0);
1214 	PRINT_REG(ttbr0_el1);
1215 	PRINT_REG(ttbr1_el1);
1216 	PRINT_REG(vbar_el1);
1217 #undef PRINT_REG
1218 }
1219 
DB_SHOW_COMMAND(vtop,db_show_vtop)1220 DB_SHOW_COMMAND(vtop, db_show_vtop)
1221 {
1222 	uint64_t phys;
1223 
1224 	if (have_addr) {
1225 		phys = arm64_address_translate_s1e1r(addr);
1226 		db_printf("EL1 physical address reg (read):  0x%016lx\n", phys);
1227 		phys = arm64_address_translate_s1e1w(addr);
1228 		db_printf("EL1 physical address reg (write): 0x%016lx\n", phys);
1229 		phys = arm64_address_translate_s1e0r(addr);
1230 		db_printf("EL0 physical address reg (read):  0x%016lx\n", phys);
1231 		phys = arm64_address_translate_s1e0w(addr);
1232 		db_printf("EL0 physical address reg (write): 0x%016lx\n", phys);
1233 	} else
1234 		db_printf("show vtop <virt_addr>\n");
1235 }
1236 #endif
1237