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