Home | History | Annotate | Line # | Download | only in riscv
riscv_machdep.c revision 1.32
      1 /*	$NetBSD: riscv_machdep.c,v 1.32 2023/08/04 09:06:33 mrg Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2014, 2019, 2022 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Matt Thomas of 3am Software Foundry, and by Nick Hudson.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #include "opt_ddb.h"
     33 #include "opt_modular.h"
     34 #include "opt_multiprocessor.h"
     35 #include "opt_riscv_debug.h"
     36 
     37 #include <sys/cdefs.h>
     38 __RCSID("$NetBSD: riscv_machdep.c,v 1.32 2023/08/04 09:06:33 mrg Exp $");
     39 
     40 #include <sys/param.h>
     41 
     42 #include <sys/asan.h>
     43 #include <sys/boot_flag.h>
     44 #include <sys/cpu.h>
     45 #include <sys/exec.h>
     46 #include <sys/kmem.h>
     47 #include <sys/ktrace.h>
     48 #include <sys/lwp.h>
     49 #include <sys/module.h>
     50 #include <sys/mount.h>
     51 #include <sys/msgbuf.h>
     52 #include <sys/optstr.h>
     53 #include <sys/proc.h>
     54 #include <sys/reboot.h>
     55 #include <sys/syscall.h>
     56 #include <sys/sysctl.h>
     57 #include <sys/systm.h>
     58 
     59 #include <dev/cons.h>
     60 #include <uvm/uvm_extern.h>
     61 
     62 #include <riscv/frame.h>
     63 #include <riscv/locore.h>
     64 #include <riscv/machdep.h>
     65 #include <riscv/pte.h>
     66 #include <riscv/sbi.h>
     67 
     68 #include <libfdt.h>
     69 #include <dev/fdt/fdtvar.h>
     70 #include <dev/fdt/fdt_boot.h>
     71 #include <dev/fdt/fdt_memory.h>
     72 #include <dev/fdt/fdt_private.h>
     73 
     74 int cpu_printfataltraps = 1;
     75 char machine[] = MACHINE;
     76 char machine_arch[] = MACHINE_ARCH;
     77 
     78 #ifdef VERBOSE_INIT_RISCV
     79 #define	VPRINTF(...)	printf(__VA_ARGS__)
     80 #else
     81 #define	VPRINTF(...)	__nothing
     82 #endif
     83 
     84 /* 64 should be enough, even for a ZFS UUID */
     85 #define	MAX_BOOT_DEV_STR	64
     86 
     87 char bootdevstr[MAX_BOOT_DEV_STR] = "";
     88 char *boot_args = NULL;
     89 
     90 paddr_t physical_start;
     91 paddr_t physical_end;
     92 
     93 static void
     94 earlyconsputc(dev_t dev, int c)
     95 {
     96 	uartputc(c);
     97 }
     98 
     99 static int
    100 earlyconsgetc(dev_t dev)
    101 {
    102 	return uartgetc();
    103 }
    104 
    105 static struct consdev earlycons = {
    106 	.cn_putc = earlyconsputc,
    107 	.cn_getc = earlyconsgetc,
    108 	.cn_pollc = nullcnpollc,
    109 };
    110 
    111 struct vm_map *phys_map;
    112 
    113 struct trapframe cpu_ddb_regs;
    114 const pcu_ops_t * const pcu_ops_md_defs[PCU_UNIT_COUNT] = {
    115 #ifdef FPE
    116 	[PCU_FPU] = &pcu_fpu_ops,
    117 #endif
    118 };
    119 
    120 /*
    121  * Used by PHYSTOV and VTOPHYS -- Will be set be BSS is zeroed so
    122  * keep it in data
    123  */
    124 unsigned long kern_vtopdiff __attribute__((__section__(".data")));
    125 
    126 
    127 /*
    128  * machine dependent system variables.
    129  */
    130 SYSCTL_SETUP(sysctl_machdep_setup, "sysctl machdep subtree setup")
    131 {
    132 	sysctl_createv(clog, 0, NULL, NULL,
    133 	    CTLFLAG_PERMANENT,
    134 	    CTLTYPE_NODE, "machdep", NULL,
    135 	    NULL, 0, NULL, 0,
    136 	    CTL_MACHDEP, CTL_EOL);
    137 }
    138 
    139 void
    140 delay(unsigned long us)
    141 {
    142 	const uint32_t cycles_per_us = curcpu()->ci_data.cpu_cc_freq / 1000000;
    143 	const uint64_t cycles = (uint64_t)us * cycles_per_us;
    144 	const uint64_t finish = csr_cycle_read() + cycles;
    145 
    146 	while (csr_cycle_read() < finish) {
    147 		/* spin, baby spin */
    148 	}
    149 }
    150 
    151 #ifdef MODULAR
    152 /*
    153  * Push any modules loaded by the boot loader.
    154  */
    155 void
    156 module_init_md(void)
    157 {
    158 }
    159 #endif /* MODULAR */
    160 
    161 /*
    162  * Set registers on exec.
    163  * Clear all registers except sp, pc.
    164  * sp is set to the stack pointer passed in.  pc is set to the entry
    165  * point given by the exec_package passed in.
    166  */
    167 void
    168 setregs(struct lwp *l, struct exec_package *pack, vaddr_t stack)
    169 {
    170 	struct trapframe * const tf = l->l_md.md_utf;
    171 	struct proc * const p = l->l_proc;
    172 
    173 	memset(tf, 0, sizeof(*tf));
    174 	tf->tf_sp = (intptr_t)stack_align(stack);
    175 	tf->tf_pc = (intptr_t)pack->ep_entry & ~1;
    176 #ifdef _LP64
    177 	tf->tf_sr = (p->p_flag & PK_32) ? SR_USER32 : SR_USER64;
    178 #else
    179 	tf->tf_sr = SR_USER;
    180 #endif
    181 
    182 	// Set up arguments for ___start(cleanup, ps_strings)
    183 	tf->tf_a0 = 0;			// cleanup
    184 	tf->tf_a1 = p->p_psstrp;	// ps_strings
    185 
    186 	/*
    187 	 * Must have interrupts disabled for exception return.
    188 	 * Must be switching to user mode.
    189 	 * Must enable interrupts after sret.
    190 	 */
    191 	KASSERT(__SHIFTOUT(tf->tf_sr, SR_SIE) == 0);
    192 	KASSERT(__SHIFTOUT(tf->tf_sr, SR_SPP) == 0);
    193 	KASSERT(__SHIFTOUT(tf->tf_sr, SR_SPIE) != 0);
    194 }
    195 
    196 void
    197 md_child_return(struct lwp *l)
    198 {
    199 	struct trapframe * const tf = lwp_trapframe(l);
    200 
    201 	tf->tf_a0 = 0;
    202 	tf->tf_a1 = 1;
    203 #ifdef FPE
    204 	/* Disable FP as we can't be using it (yet). */
    205 	tf->tf_sr &= ~SR_FS;
    206 #endif
    207 
    208 	/*
    209 	 * Must have interrupts disabled for exception return.
    210 	 * Must be switching to user mode.
    211 	 * Must enable interrupts after sret.
    212 	 */
    213 
    214 	KASSERT(__SHIFTOUT(tf->tf_sr, SR_SIE) == 0);
    215 	KASSERT(__SHIFTOUT(tf->tf_sr, SR_SPP) == 0);
    216 	KASSERT(__SHIFTOUT(tf->tf_sr, SR_SPIE) != 0);
    217 
    218 	userret(l);
    219 }
    220 
    221 void
    222 cpu_spawn_return(struct lwp *l)
    223 {
    224 	userret(l);
    225 }
    226 
    227 /*
    228  * Start a new LWP
    229  */
    230 void
    231 startlwp(void *arg)
    232 {
    233 	ucontext_t * const uc = arg;
    234 	lwp_t * const l = curlwp;
    235 	int error __diagused;
    236 
    237 	error = cpu_setmcontext(l, &uc->uc_mcontext, uc->uc_flags);
    238 	KASSERT(error == 0);
    239 
    240 	kmem_free(uc, sizeof(*uc));
    241 	userret(l);
    242 }
    243 
    244 // We've worked hard to make sure struct reg and __gregset_t are the same.
    245 // Ditto for struct fpreg and fregset_t.
    246 
    247 #ifdef _LP64
    248 CTASSERT(sizeof(struct reg) == sizeof(__gregset_t));
    249 #endif
    250 CTASSERT(sizeof(struct fpreg) == sizeof(__fregset_t));
    251 
    252 void
    253 cpu_getmcontext(struct lwp *l, mcontext_t *mcp, unsigned int *flags)
    254 {
    255 	const struct trapframe * const tf = l->l_md.md_utf;
    256 
    257 	/* Save register context. */
    258 	*(struct reg *)mcp->__gregs = tf->tf_regs;
    259 
    260 	*flags |= _UC_CPU | _UC_TLSBASE;
    261 
    262 	/* Save floating point register context, if any. */
    263 	KASSERT(l == curlwp);
    264 	if (fpu_valid_p(l)) {
    265 		/*
    266 		 * If this process is the current FP owner, dump its
    267 		 * context to the PCB first.
    268 		 */
    269 		fpu_save(l);
    270 
    271 		struct pcb * const pcb = lwp_getpcb(l);
    272 		*(struct fpreg *)mcp->__fregs = pcb->pcb_fpregs;
    273 		*flags |= _UC_FPU;
    274 	}
    275 }
    276 
    277 int
    278 cpu_mcontext_validate(struct lwp *l, const mcontext_t *mcp)
    279 {
    280 	/*
    281 	 * Verify that at least the PC and SP are user addresses.
    282 	 */
    283 	if ((intptr_t) mcp->__gregs[_REG_PC] < 0
    284 	    || (intptr_t) mcp->__gregs[_REG_SP] < 0
    285 	    || (mcp->__gregs[_REG_PC] & 1))
    286 		return EINVAL;
    287 
    288 	return 0;
    289 }
    290 
    291 int
    292 cpu_setmcontext(struct lwp *l, const mcontext_t *mcp, unsigned int flags)
    293 {
    294 	struct trapframe * const tf = l->l_md.md_utf;
    295 	struct proc * const p = l->l_proc;
    296 	const __greg_t * const gr = mcp->__gregs;
    297 	int error;
    298 
    299 	/* Restore register context, if any. */
    300 	if (flags & _UC_CPU) {
    301 		error = cpu_mcontext_validate(l, mcp);
    302 		if (error)
    303 			return error;
    304 
    305 		/* Save register context. */
    306 		tf->tf_regs = *(const struct reg *)gr;
    307 	}
    308 
    309 	/* Restore the private thread context */
    310 	if (flags & _UC_TLSBASE) {
    311 		lwp_setprivate(l, (void *)(intptr_t)mcp->__gregs[_X_TP]);
    312 	}
    313 
    314 	/* Restore floating point register context, if any. */
    315 	if (flags & _UC_FPU) {
    316 		KASSERT(l == curlwp);
    317 		/* Tell PCU we are replacing the FPU contents. */
    318 		fpu_replace(l);
    319 
    320 		/*
    321 		 * The PCB FP regs struct includes the FP CSR, so use the
    322 		 * proper size of fpreg when copying.
    323 		 */
    324 		struct pcb * const pcb = lwp_getpcb(l);
    325 		pcb->pcb_fpregs = *(const struct fpreg *)mcp->__fregs;
    326 	}
    327 
    328 	mutex_enter(p->p_lock);
    329 	if (flags & _UC_SETSTACK)
    330 		l->l_sigstk.ss_flags |= SS_ONSTACK;
    331 	if (flags & _UC_CLRSTACK)
    332 		l->l_sigstk.ss_flags &= ~SS_ONSTACK;
    333 	mutex_exit(p->p_lock);
    334 
    335 	return 0;
    336 }
    337 
    338 void
    339 cpu_need_resched(struct cpu_info *ci, struct lwp *l, int flags)
    340 {
    341 	KASSERT(kpreempt_disabled());
    342 
    343 	if ((flags & RESCHED_KPREEMPT) != 0) {
    344 #ifdef __HAVE_PREEMPTION
    345 		if ((flags & RESCHED_REMOTE) != 0) {
    346 			cpu_send_ipi(ci, IPI_KPREEMPT);
    347 		} else {
    348 			softint_trigger(SOFTINT_KPREEMPT);
    349 		}
    350 #endif
    351 		return;
    352 	}
    353 	if ((flags & RESCHED_REMOTE) != 0) {
    354 #ifdef MULTIPROCESSOR
    355 		cpu_send_ipi(ci, IPI_AST);
    356 #endif
    357 	} else {
    358 		l->l_md.md_astpending = 1;	/* force call to ast() */
    359 	}
    360 }
    361 
    362 void
    363 cpu_signotify(struct lwp *l)
    364 {
    365 	KASSERT(kpreempt_disabled());
    366 #ifdef __HAVE_FAST_SOFTINTS
    367 	KASSERT(lwp_locked(l, NULL));
    368 #endif
    369 
    370 	if (l->l_cpu != curcpu()) {
    371 #ifdef MULTIPROCESSOR
    372 		cpu_send_ipi(l->l_cpu, IPI_AST);
    373 #endif
    374 	} else {
    375 		l->l_md.md_astpending = 1; 	/* force call to ast() */
    376 	}
    377 }
    378 
    379 void
    380 cpu_need_proftick(struct lwp *l)
    381 {
    382 	KASSERT(kpreempt_disabled());
    383 	KASSERT(l->l_cpu == curcpu());
    384 
    385 	l->l_pflag |= LP_OWEUPC;
    386 	l->l_md.md_astpending = 1;		/* force call to ast() */
    387 }
    388 
    389 
    390 /* Sync the discs, unmount the filesystems, and adjust the todr */
    391 static void
    392 bootsync(void)
    393 {
    394 	static bool bootsyncdone = false;
    395 
    396 	if (bootsyncdone)
    397 		return;
    398 
    399 	bootsyncdone = true;
    400 
    401 	/* Make sure we can still manage to do things */
    402 	if ((csr_sstatus_read() & SR_SIE) == 0) {
    403 		/*
    404 		 * If we get here then boot has been called without RB_NOSYNC
    405 		 * and interrupts were disabled. This means the boot() call
    406 		 * did not come from a user process e.g. shutdown, but must
    407 		 * have come from somewhere in the kernel.
    408 		 */
    409 		ENABLE_INTERRUPTS();
    410 		printf("Warning interrupts disabled during boot()\n");
    411 	}
    412 
    413 	vfs_shutdown();
    414 
    415 	resettodr();
    416 }
    417 
    418 
    419 void
    420 cpu_reboot(int howto, char *bootstr)
    421 {
    422 
    423 	/*
    424 	 * If RB_NOSYNC was not specified sync the discs.
    425 	 * Note: Unless cold is set to 1 here, syslogd will die during the
    426 	 * unmount.  It looks like syslogd is getting woken up only to find
    427 	 * that it cannot page part of the binary in as the filesystem has
    428 	 * been unmounted.
    429 	 */
    430 	if ((howto & RB_NOSYNC) == 0)
    431 		bootsync();
    432 
    433 #if 0
    434 	/* Disable interrupts. */
    435 	const int s = splhigh();
    436 
    437 	/* Do a dump if requested. */
    438 	if ((howto & (RB_DUMP | RB_HALT)) == RB_DUMP)
    439 		dumpsys();
    440 
    441 	splx(s);
    442 #endif
    443 
    444 	pmf_system_shutdown(boothowto);
    445 
    446 	/* Say NO to interrupts for good */
    447 	splhigh();
    448 
    449 	/* Run any shutdown hooks */
    450 	doshutdownhooks();
    451 
    452 	/* Make sure IRQ's are disabled */
    453 	DISABLE_INTERRUPTS();
    454 
    455 	if (howto & RB_HALT) {
    456 		printf("\n");
    457 		printf("The operating system has halted.\n");
    458 		printf("Please press any key to reboot.\n\n");
    459 		cnpollc(1);	/* for proper keyboard command handling */
    460 		if (cngetc() == 0) {
    461 			/* no console attached, so just hlt */
    462 			printf("No keyboard - cannot reboot after all.\n");
    463 			goto spin;
    464 		}
    465 		cnpollc(0);
    466 	}
    467 
    468 	printf("rebooting...\n");
    469 
    470 	sbi_system_reset(SBI_RESET_TYPE_COLDREBOOT, SBI_RESET_REASON_NONE);
    471 spin:
    472 	for (;;) {
    473 		asm volatile("wfi" ::: "memory");
    474 	}
    475 	/* NOTREACHED */
    476 }
    477 
    478 void
    479 cpu_dumpconf(void)
    480 {
    481 	// TBD!!
    482 }
    483 
    484 
    485 int
    486 cpu_lwp_setprivate(lwp_t *l, void *addr)
    487 {
    488 	struct trapframe * const tf = lwp_trapframe(l);
    489 
    490 	tf->tf_reg[_REG_TP] = (register_t)addr;
    491 
    492 	return 0;
    493 }
    494 
    495 
    496 void
    497 cpu_startup(void)
    498 {
    499 	vaddr_t minaddr, maxaddr;
    500 	char pbuf[10];	/* "999999 MB" -- But Sv39 is max 512GB */
    501 
    502 	/*
    503 	 * Good {morning,afternoon,evening,night}.
    504 	 */
    505 	printf("%s%s", copyright, version);
    506 	format_bytes(pbuf, sizeof(pbuf), ctob(physmem));
    507 	printf("total memory = %s\n", pbuf);
    508 
    509 	minaddr = 0;
    510 	/*
    511 	 * Allocate a submap for physio.
    512 	 */
    513 	phys_map = uvm_km_suballoc(kernel_map, &minaddr, &maxaddr,
    514 	    VM_PHYS_SIZE, 0, FALSE, NULL);
    515 
    516 	format_bytes(pbuf, sizeof(pbuf), ptoa(uvm_availmem(false)));
    517 	printf("avail memory = %s\n", pbuf);
    518 
    519 #ifdef MULTIPROCESSOR
    520 	kcpuset_create(&cpus_halted, true);
    521 	KASSERT(cpus_halted != NULL);
    522 
    523 	kcpuset_create(&cpus_hatched, true);
    524 	KASSERT(cpus_hatched != NULL);
    525 
    526 	kcpuset_create(&cpus_paused, true);
    527 	KASSERT(cpus_paused != NULL);
    528 
    529 	kcpuset_create(&cpus_resumed, true);
    530 	KASSERT(cpus_resumed != NULL);
    531 
    532 	kcpuset_create(&cpus_running, true);
    533 	KASSERT(cpus_running != NULL);
    534 
    535 	kcpuset_set(cpus_hatched, cpu_number());
    536 	kcpuset_set(cpus_running, cpu_number());
    537 #endif
    538 
    539 	fdtbus_intr_init();
    540 
    541 	fdt_setup_rndseed();
    542 	fdt_setup_efirng();
    543 }
    544 
    545 static void
    546 riscv_add_memory(const struct fdt_memory *m, void *arg)
    547 {
    548 	paddr_t first = atop(m->start);
    549 	paddr_t last = atop(m->end);
    550 	int freelist = VM_FREELIST_DEFAULT;
    551 
    552 	VPRINTF("adding %#16" PRIxPADDR " - %#16" PRIxPADDR"  to freelist %d\n",
    553 	    m->start, m->end, freelist);
    554 
    555 	uvm_page_physload(first, last, first, last, freelist);
    556 	physmem += last - first;
    557 }
    558 
    559 
    560 static void
    561 cpu_kernel_vm_init(paddr_t memory_start, paddr_t memory_end)
    562 {
    563 	extern char __kernel_text[];
    564 	extern char _end[];
    565 
    566 	vaddr_t kernstart = trunc_page((vaddr_t)__kernel_text);
    567 	vaddr_t kernend = round_page((vaddr_t)_end);
    568 	paddr_t kernstart_phys = KERN_VTOPHYS(kernstart);
    569 	paddr_t kernend_phys = KERN_VTOPHYS(kernend);
    570 
    571 	VPRINTF("%s: kernel phys start %#" PRIxPADDR " end %#" PRIxPADDR "\n",
    572 	    __func__, kernstart_phys, kernend_phys);
    573 	fdt_memory_remove_range(kernstart_phys,
    574 	    kernend_phys - kernstart_phys);
    575 
    576 	/*
    577 	 * Don't give these pages to UVM.
    578 	 *
    579 	 * cpu_kernel_vm_init need to create proper tables then the following
    580 	 * will be true.
    581 	 *
    582 	 * Now we have APs started the pages used for stacks and L1PT can
    583 	 * be given to uvm
    584 	 */
    585 	extern char const __start__init_memory[];
    586 	extern char const __stop__init_memory[] __weak;
    587 	if (&__start__init_memory[0] != &__stop__init_memory[0]) {
    588 		const paddr_t spa = KERN_VTOPHYS((vaddr_t)__start__init_memory);
    589 		const paddr_t epa = KERN_VTOPHYS((vaddr_t)__stop__init_memory);
    590 
    591 		VPRINTF("%s: init   phys start %#" PRIxPADDR
    592 		    " end %#" PRIxPADDR "\n", __func__, spa, epa);
    593 		fdt_memory_remove_range(spa, epa - spa);
    594 	}
    595 
    596 #ifdef _LP64
    597 	paddr_t pa = memory_start & ~XSEGOFSET;
    598 	pmap_direct_base = RISCV_DIRECTMAP_START;
    599 	extern pd_entry_t l2_pte[PAGE_SIZE / sizeof(pd_entry_t)];
    600 
    601 
    602 	const vsize_t vshift = XSEGSHIFT;
    603 	const vaddr_t pdetab_mask = PMAP_PDETABSIZE - 1;
    604 	const vsize_t inc = 1UL << vshift;
    605 
    606 	const vaddr_t sva = RISCV_DIRECTMAP_START + pa;
    607 	const vaddr_t eva = RISCV_DIRECTMAP_END;
    608 	const size_t sidx = (sva >> vshift) & pdetab_mask;
    609 	const size_t eidx = (eva >> vshift) & pdetab_mask;
    610 
    611 	/* Allocate gigapages covering all physical memory in the direct map. */
    612 	for (size_t i = sidx; i < eidx && pa < memory_end; i++, pa += inc) {
    613 		l2_pte[i] = PA_TO_PTE(pa) | PTE_KERN | PTE_HARDWIRED | PTE_RW;
    614 		VPRINTF("dm:   %p :  %#" PRIxPADDR "\n", &l2_pte[i], l2_pte[i]);
    615 	}
    616 #endif
    617 //	pt_dump(printf);
    618 }
    619 
    620 static void
    621 riscv_init_lwp0_uarea(void)
    622 {
    623 	extern char lwp0uspace[];
    624 
    625 	uvm_lwp_setuarea(&lwp0, (vaddr_t)lwp0uspace);
    626 	memset(&lwp0.l_md, 0, sizeof(lwp0.l_md));
    627 	memset(lwp_getpcb(&lwp0), 0, sizeof(struct pcb));
    628 
    629 	struct trapframe *tf = (struct trapframe *)(lwp0uspace + USPACE) - 1;
    630 	memset(tf, 0, sizeof(*tf));
    631 
    632 	lwp0.l_md.md_utf = lwp0.l_md.md_ktf = tf;
    633 }
    634 
    635 
    636 static void
    637 riscv_print_memory(const struct fdt_memory *m, void *arg)
    638 {
    639 
    640 	VPRINTF("FDT /memory @ 0x%" PRIx64 " size 0x%" PRIx64 "\n",
    641 	    m->start, m->end - m->start);
    642 }
    643 
    644 
    645 static void
    646 parse_mi_bootargs(char *args)
    647 {
    648 	int howto;
    649 	bool found, start, skipping;
    650 
    651 	if (args == NULL)
    652 		return;
    653 
    654 	start = true;
    655 	skipping = false;
    656 	for (char *cp = args; *cp; cp++) {
    657 		/* check for "words" starting with a "-" only */
    658 		if (start) {
    659 			if (*cp == '-') {
    660 				skipping = false;
    661 			} else {
    662 				skipping = true;
    663 			}
    664 			start = false;
    665 			continue;
    666 		}
    667 
    668 		if (*cp == ' ') {
    669 			start = true;
    670 			skipping = false;
    671 			continue;
    672 		}
    673 
    674 		if (skipping) {
    675 			continue;
    676 		}
    677 
    678 		/* Check valid boot flags */
    679 		howto = 0;
    680 		BOOT_FLAG(*cp, howto);
    681 		if (!howto)
    682 			printf("bootflag '%c' not recognised\n", *cp);
    683 		else
    684 			boothowto |= howto;
    685 	}
    686 
    687 	found = optstr_get(args, "root", bootdevstr, sizeof(bootdevstr));
    688 	if (found) {
    689 		bootspec = bootdevstr;
    690 	}
    691 }
    692 
    693 
    694 void
    695 init_riscv(register_t hartid, paddr_t dtb)
    696 {
    697 
    698 	/* set temporally to work printf()/panic() even before consinit() */
    699 	cn_tab = &earlycons;
    700 
    701 	/* Load FDT */
    702 	const vaddr_t dtbva = VM_KERNEL_DTB_BASE + (dtb & (NBSEG - 1));
    703 	void *fdt_data = (void *)dtbva;
    704 	int error = fdt_check_header(fdt_data);
    705 	if (error != 0)
    706 	    panic("fdt_check_header failed: %s", fdt_strerror(error));
    707 
    708 	fdtbus_init(fdt_data);
    709 
    710 	/* Lookup platform specific backend */
    711 	const struct fdt_platform * const plat = fdt_platform_find();
    712 	if (plat == NULL)
    713 		panic("Kernel does not support this device");
    714 
    715 	/* Early console may be available, announce ourselves. */
    716 	VPRINTF("FDT<%p>\n", fdt_data);
    717 
    718 	boot_args = fdt_get_bootargs();
    719 
    720 	VPRINTF("devmap %p\n", plat->fp_devmap());
    721 	pmap_devmap_bootstrap(0, plat->fp_devmap());
    722 
    723 	VPRINTF("bootstrap\n");
    724 	plat->fp_bootstrap();
    725 
    726 	/*
    727 	 * If stdout-path is specified on the command line, override the
    728 	 * value in /chosen/stdout-path before initializing console.
    729 	 */
    730 	VPRINTF("stdout\n");
    731 	fdt_update_stdout_path(fdt_data, boot_args);
    732 
    733 	/*
    734 	 * Done making changes to the FDT.
    735 	 */
    736 	fdt_pack(fdt_data);
    737 
    738 	const uint32_t dtbsize = round_page(fdt_totalsize(fdt_data));
    739 
    740 	VPRINTF("fdt size %x/%x\n", dtbsize, fdt_totalsize(fdt_data));
    741 
    742 	VPRINTF("consinit ");
    743 	consinit();
    744 	VPRINTF("ok\n");
    745 
    746 	/* Talk to the user */
    747 	printf("NetBSD/riscv (fdt) booting ...\n");
    748 
    749 #ifdef BOOT_ARGS
    750 	char mi_bootargs[] = BOOT_ARGS;
    751 	parse_mi_bootargs(mi_bootargs);
    752 #endif
    753 
    754 	uint64_t memory_start, memory_end;
    755 	fdt_memory_get(&memory_start, &memory_end);
    756 	physical_start = memory_start;
    757 	physical_end = memory_end;
    758 
    759 	fdt_memory_foreach(riscv_print_memory, NULL);
    760 
    761 	/* Cannot map memory above largest page number */
    762 	const uint64_t maxppn = __SHIFTOUT_MASK(PTE_PPN) - 1;
    763 	const uint64_t memory_limit = ptoa(maxppn);
    764 
    765 	if (memory_end > memory_limit) {
    766 		fdt_memory_remove_range(memory_limit, memory_end);
    767 		memory_end = memory_limit;
    768 	}
    769 
    770 	uint64_t memory_size __unused = memory_end - memory_start;
    771 
    772 	VPRINTF("%s: memory start %" PRIx64 " end %" PRIx64 " (len %"
    773 	    PRIx64 ")\n", __func__, memory_start, memory_end, memory_size);
    774 
    775 	/* Parse ramdisk, rndseed, and firmware's RNG from EFI */
    776 	fdt_probe_initrd();
    777 	fdt_probe_rndseed();
    778 	fdt_probe_efirng();
    779 
    780 	fdt_memory_remove_reserved(memory_start, memory_end);
    781 
    782 	fdt_memory_remove_range(dtb, dtbsize);
    783 	fdt_reserve_initrd();
    784 	fdt_reserve_rndseed();
    785 	fdt_reserve_efirng();
    786 
    787 	/* Perform PT build and VM init */
    788 	cpu_kernel_vm_init(memory_start, memory_end);
    789 
    790 	VPRINTF("bootargs: %s\n", boot_args);
    791 
    792 	parse_mi_bootargs(boot_args);
    793 
    794 #ifdef DDB
    795 	if (boothowto & RB_KDB) {
    796 		printf("Entering DDB...\n");
    797 		cpu_Debugger();
    798 	}
    799 #endif
    800 
    801 	extern char __kernel_text[];
    802 	extern char _end[];
    803 //	extern char __data_start[];
    804 //	extern char __rodata_start[];
    805 
    806 	vaddr_t kernstart = trunc_page((vaddr_t)__kernel_text);
    807 	vaddr_t kernend = round_page((vaddr_t)_end);
    808 	paddr_t kernstart_phys __unused = KERN_VTOPHYS(kernstart);
    809 	paddr_t kernend_phys __unused = KERN_VTOPHYS(kernend);
    810 
    811 	vaddr_t kernelvmstart;
    812 
    813 	vaddr_t kernstart_mega __unused = MEGAPAGE_TRUNC(kernstart);
    814 	vaddr_t kernend_mega = MEGAPAGE_ROUND(kernend);
    815 
    816 	kernelvmstart = kernend_mega;
    817 
    818 #if 0
    819 #ifdef MODULAR
    820 #define MODULE_RESERVED_MAX	(1024 * 1024 * 128)
    821 #define MODULE_RESERVED_SIZE	(1024 * 1024 * 32)	/* good enough? */
    822 	module_start = kernelvmstart;
    823 	module_end = kernend_mega + MODULE_RESERVED_SIZE;
    824 	if (module_end >= kernstart_mega + MODULE_RESERVED_MAX)
    825 		module_end = kernstart_mega + MODULE_RESERVED_MAX;
    826 	KASSERT(module_end > kernend_mega);
    827 	kernelvmstart = module_end;
    828 #endif /* MODULAR */
    829 #endif
    830 	KASSERT(kernelvmstart < VM_KERNEL_VM_BASE);
    831 
    832 	kernelvmstart = VM_KERNEL_VM_BASE;
    833 
    834 	/*
    835 	 * msgbuf is allocated from the top of the last biggest memory block.
    836 	 */
    837 	paddr_t msgbufaddr = 0;
    838 
    839 #ifdef _LP64
    840 	/* XXX check all ranges for last one with a big enough hole */
    841 	msgbufaddr = memory_end - MSGBUFSIZE;
    842 	KASSERT(msgbufaddr != 0);	/* no space for msgbuf */
    843 	fdt_memory_remove_range(msgbufaddr, msgbufaddr + MSGBUFSIZE);
    844 	msgbufaddr = RISCV_PA_TO_KVA(msgbufaddr);
    845 	VPRINTF("msgbufaddr = %#lx\n", msgbufaddr);
    846 	initmsgbuf((void *)msgbufaddr, MSGBUFSIZE);
    847 #endif
    848 
    849 	KASSERT(msgbufaddr != 0);	/* no space for msgbuf */
    850 #ifdef _LP64
    851 	initmsgbuf((void *)RISCV_PA_TO_KVA(msgbufaddr), MSGBUFSIZE);
    852 #endif
    853 
    854 #define	DPRINTF(v)	VPRINTF("%24s = 0x%16lx\n", #v, (unsigned long)v);
    855 
    856 	VPRINTF("------------------------------------------\n");
    857 	DPRINTF(kern_vtopdiff);
    858 	DPRINTF(memory_start);
    859 	DPRINTF(memory_end);
    860 	DPRINTF(memory_size);
    861 	DPRINTF(kernstart_phys);
    862 	DPRINTF(kernend_phys)
    863 	DPRINTF(msgbufaddr);
    864 //	DPRINTF(physical_end);
    865 	DPRINTF(VM_MIN_KERNEL_ADDRESS);
    866 	DPRINTF(kernstart_mega);
    867 	DPRINTF(kernstart);
    868 	DPRINTF(kernend);
    869 	DPRINTF(kernend_mega);
    870 #if 0
    871 #ifdef MODULAR
    872 	DPRINTF(module_start);
    873 	DPRINTF(module_end);
    874 #endif
    875 #endif
    876 	DPRINTF(VM_MAX_KERNEL_ADDRESS);
    877 #ifdef _LP64
    878 	DPRINTF(pmap_direct_base);
    879 #endif
    880 	VPRINTF("------------------------------------------\n");
    881 
    882 #undef DPRINTF
    883 
    884 	uvm_md_init();
    885 
    886 	/*
    887 	 * pass memory pages to uvm
    888 	 */
    889 	physmem = 0;
    890 	fdt_memory_foreach(riscv_add_memory, NULL);
    891 
    892 	pmap_bootstrap(kernelvmstart, VM_MAX_KERNEL_ADDRESS);
    893 
    894 	kasan_init();
    895 
    896 	/* Finish setting up lwp0 on our end before we call main() */
    897 	riscv_init_lwp0_uarea();
    898 
    899 
    900 	error = 0;
    901 	if ((boothowto & RB_MD1) == 0) {
    902 		VPRINTF("mpstart\n");
    903 		if (plat->fp_mpstart)
    904 			error = plat->fp_mpstart();
    905 	}
    906 	if (error)
    907 		printf("AP startup problems\n");
    908 }
    909 
    910 
    911 #ifdef _LP64
    912 static void
    913 pte_bits(void (*pr)(const char *, ...), pt_entry_t pte)
    914 {
    915 	(*pr)("%c%c%c%c%c%c%c%c",
    916 	    (pte & PTE_D) ? 'D' : '.',
    917 	    (pte & PTE_A) ? 'A' : '.',
    918 	    (pte & PTE_G) ? 'G' : '.',
    919 	    (pte & PTE_U) ? 'U' : '.',
    920 	    (pte & PTE_X) ? 'X' : '.',
    921 	    (pte & PTE_W) ? 'W' : '.',
    922 	    (pte & PTE_R) ? 'R' : '.',
    923 	    (pte & PTE_V) ? 'V' : '.');
    924 }
    925 
    926 static void
    927 dump_ln_table(paddr_t pdp_pa, int topbit, int level, vaddr_t va,
    928     void (*pr)(const char *, ...) __printflike(1, 2))
    929 {
    930 	pd_entry_t *pdp = (void *)PMAP_DIRECT_MAP(pdp_pa);
    931 
    932 	(*pr)("l%u     @  pa %#16" PRIxREGISTER "\n", level, pdp_pa);
    933 	for (size_t i = 0; i < PAGE_SIZE / sizeof(pd_entry_t); i++) {
    934 		pd_entry_t entry = pdp[i];
    935 
    936 		if (topbit) {
    937 			va = i << (PGSHIFT + level * SEGLENGTH);
    938 			if (va & __BIT(topbit)) {
    939 				va |= __BITS(63, topbit);
    940 			}
    941 		}
    942 		if (entry != 0) {
    943 			paddr_t pa = __SHIFTOUT(entry, PTE_PPN) << PGSHIFT;
    944 			// check level PPN bits.
    945 			if (PTE_ISLEAF_P(entry)) {
    946 				(*pr)("l%u %3zu    va 0x%016lx  pa 0x%012lx - ",
    947 				      level, i, va, pa);
    948 				pte_bits(pr, entry);
    949 				(*pr)("\n");
    950 			} else {
    951 				(*pr)("l%u %3zu    va 0x%016lx  -> 0x%012lx - ",
    952 				      level, i, va, pa);
    953 				pte_bits(pr, entry);
    954 				(*pr)("\n");
    955 				if (level == 0) {
    956 					(*pr)("wtf\n");
    957 					continue;
    958 				}
    959 				if (pte_pde_valid_p(entry))
    960 					dump_ln_table(pa, 0, level - 1, va, pr);
    961 			}
    962 		}
    963 		va += 1UL << (PGSHIFT + level * SEGLENGTH);
    964 	}
    965 }
    966 
    967 void
    968 pt_dump(void (*pr)(const char *, ...) __printflike(1, 2))
    969 {
    970 	const register_t satp = csr_satp_read();
    971 	size_t topbit = sizeof(long) * NBBY - 1;
    972 
    973 #ifdef _LP64
    974 	const paddr_t satp_pa = __SHIFTOUT(satp, SATP_PPN) << PGSHIFT;
    975 	const uint8_t mode = __SHIFTOUT(satp, SATP_MODE);
    976 	u_int level = 1;
    977 
    978 	switch (mode) {
    979 	case SATP_MODE_SV39:
    980 	case SATP_MODE_SV48:
    981 		topbit = (39 - 1) + (mode - 8) * SEGLENGTH;
    982 		level = mode - 6;
    983 		break;
    984 	}
    985 #endif
    986 	(*pr)("topbit = %zu\n", topbit);
    987 
    988 	(*pr)("satp   = 0x%" PRIxREGISTER "\n", satp);
    989 #ifdef _LP64
    990 	dump_ln_table(satp_pa, topbit, level, 0, pr);
    991 #endif
    992 }
    993 #endif
    994 
    995 void
    996 consinit(void)
    997 {
    998 	static bool initialized = false;
    999 	const struct fdt_console *cons = fdtbus_get_console();
   1000 	const struct fdt_platform *plat = fdt_platform_find();
   1001 
   1002 	if (initialized || cons == NULL)
   1003 		return;
   1004 
   1005 	u_int uart_freq = 0;
   1006 	extern struct bus_space riscv_generic_bs_tag;
   1007 	struct fdt_attach_args faa = {
   1008 		.faa_bst = &riscv_generic_bs_tag,
   1009 	};
   1010 
   1011 	faa.faa_phandle = fdtbus_get_stdout_phandle();
   1012 	if (plat->fp_uart_freq != NULL)
   1013 		uart_freq = plat->fp_uart_freq();
   1014 
   1015 	cons->consinit(&faa, uart_freq);
   1016 
   1017 	initialized = true;
   1018 }
   1019