Home | History | Annotate | Line # | Download | only in fdt
fdt_machdep.c revision 1.99
      1 /* $NetBSD: fdt_machdep.c,v 1.99 2022/11/04 10:51:17 jmcneill Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 2015-2017 Jared McNeill <jmcneill (at) invisible.ca>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     22  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  */
     28 
     29 #include <sys/cdefs.h>
     30 __KERNEL_RCSID(0, "$NetBSD: fdt_machdep.c,v 1.99 2022/11/04 10:51:17 jmcneill Exp $");
     31 
     32 #include "opt_arm_debug.h"
     33 #include "opt_bootconfig.h"
     34 #include "opt_cpuoptions.h"
     35 #include "opt_ddb.h"
     36 #include "opt_efi.h"
     37 #include "opt_machdep.h"
     38 #include "opt_md.h"
     39 #include "opt_multiprocessor.h"
     40 
     41 #include "genfb.h"
     42 #include "ukbd.h"
     43 #include "wsdisplay.h"
     44 
     45 #include <sys/param.h>
     46 #include <sys/types.h>
     47 
     48 #include <sys/atomic.h>
     49 #include <sys/bootblock.h>
     50 #include <sys/bus.h>
     51 #include <sys/conf.h>
     52 #include <sys/cpu.h>
     53 #include <sys/device.h>
     54 #include <sys/disk.h>
     55 #include <sys/disklabel.h>
     56 #include <sys/endian.h>
     57 #include <sys/exec.h>
     58 #include <sys/fcntl.h>
     59 #include <sys/kauth.h>
     60 #include <sys/kernel.h>
     61 #include <sys/kmem.h>
     62 #include <sys/ksyms.h>
     63 #include <sys/md5.h>
     64 #include <sys/msgbuf.h>
     65 #include <sys/proc.h>
     66 #include <sys/pserialize.h>
     67 #include <sys/reboot.h>
     68 #include <sys/rnd.h>
     69 #include <sys/rndsource.h>
     70 #include <sys/systm.h>
     71 #include <sys/termios.h>
     72 #include <sys/vnode.h>
     73 #include <sys/uuid.h>
     74 
     75 #include <net/if.h>
     76 #include <net/if_dl.h>
     77 
     78 #include <dev/cons.h>
     79 #include <uvm/uvm_extern.h>
     80 
     81 #include <machine/db_machdep.h>
     82 #include <ddb/db_sym.h>
     83 #include <ddb/db_extern.h>
     84 
     85 #include <machine/bootconfig.h>
     86 #include <arm/armreg.h>
     87 
     88 #include <arm/cpufunc.h>
     89 
     90 #include <evbarm/include/autoconf.h>
     91 #include <evbarm/fdt/machdep.h>
     92 #include <evbarm/fdt/platform.h>
     93 
     94 #include <arm/fdt/arm_fdtvar.h>
     95 #include <dev/fdt/fdt_private.h>
     96 #include <dev/fdt/fdt_memory.h>
     97 
     98 #ifdef EFI_RUNTIME
     99 #include <arm/arm/efi_runtime.h>
    100 #endif
    101 
    102 #if NWSDISPLAY > 0 && NGENFB > 0
    103 #include <arm/fdt/arm_simplefb.h>
    104 #endif
    105 
    106 #if NUKBD > 0
    107 #include <dev/usb/ukbdvar.h>
    108 #endif
    109 #if NWSDISPLAY > 0
    110 #include <dev/wscons/wsdisplayvar.h>
    111 #endif
    112 
    113 #ifdef MEMORY_DISK_DYNAMIC
    114 #include <dev/md.h>
    115 #endif
    116 
    117 #ifndef FDT_MAX_BOOT_STRING
    118 #define FDT_MAX_BOOT_STRING 1024
    119 #endif
    120 
    121 BootConfig bootconfig;
    122 char bootargs[FDT_MAX_BOOT_STRING] = "";
    123 char *boot_args = NULL;
    124 
    125 /* filled in before cleaning bss. keep in .data */
    126 u_long uboot_args[4] __attribute__((__section__(".data")));
    127 const uint8_t *fdt_addr_r __attribute__((__section__(".data")));
    128 
    129 static uint64_t initrd_start, initrd_end;
    130 static uint64_t rndseed_start, rndseed_end; /* our on-disk seed */
    131 static uint64_t efirng_start, efirng_end;   /* firmware's EFI RNG output */
    132 
    133 #include <libfdt.h>
    134 #include <dev/fdt/fdtvar.h>
    135 #define FDT_BUF_SIZE	(512*1024)
    136 static uint8_t fdt_data[FDT_BUF_SIZE];
    137 
    138 extern char KERNEL_BASE_phys[];
    139 #define KERNEL_BASE_PHYS ((paddr_t)KERNEL_BASE_phys)
    140 
    141 static void fdt_update_stdout_path(void);
    142 static void fdt_device_register(device_t, void *);
    143 static void fdt_device_register_post_config(device_t, void *);
    144 static void fdt_cpu_rootconf(void);
    145 static void fdt_reset(void);
    146 static void fdt_powerdown(void);
    147 
    148 #if BYTE_ORDER == BIG_ENDIAN
    149 static void fdt_update_fb_format(void);
    150 #endif
    151 
    152 static void
    153 earlyconsputc(dev_t dev, int c)
    154 {
    155 	uartputc(c);
    156 }
    157 
    158 static int
    159 earlyconsgetc(dev_t dev)
    160 {
    161 	return -1;
    162 }
    163 
    164 static struct consdev earlycons = {
    165 	.cn_putc = earlyconsputc,
    166 	.cn_getc = earlyconsgetc,
    167 	.cn_pollc = nullcnpollc,
    168 };
    169 
    170 #ifdef VERBOSE_INIT_ARM
    171 #define VPRINTF(...)	printf(__VA_ARGS__)
    172 #else
    173 #define VPRINTF(...)	__nothing
    174 #endif
    175 
    176 static void
    177 fdt_add_dram_blocks(const struct fdt_memory *m, void *arg)
    178 {
    179 	BootConfig *bc = arg;
    180 
    181 	VPRINTF("  %" PRIx64 " - %" PRIx64 "\n", m->start, m->end - 1);
    182 	bc->dram[bc->dramblocks].address = m->start;
    183 	bc->dram[bc->dramblocks].pages =
    184 	    (m->end - m->start) / PAGE_SIZE;
    185 	bc->dramblocks++;
    186 }
    187 
    188 static int nfdt_physmem = 0;
    189 static struct boot_physmem fdt_physmem[FDT_MEMORY_RANGES];
    190 
    191 static void
    192 fdt_add_boot_physmem(const struct fdt_memory *m, void *arg)
    193 {
    194 	const paddr_t saddr = round_page(m->start);
    195 	const paddr_t eaddr = trunc_page(m->end);
    196 
    197 	VPRINTF("  %" PRIx64 " - %" PRIx64, m->start, m->end - 1);
    198 	if (saddr >= eaddr) {
    199 		VPRINTF(" skipped\n");
    200 		return;
    201 	}
    202 	VPRINTF("\n");
    203 
    204 	struct boot_physmem *bp = &fdt_physmem[nfdt_physmem++];
    205 
    206 	KASSERT(nfdt_physmem <= FDT_MEMORY_RANGES);
    207 
    208 	bp->bp_start = atop(saddr);
    209 	bp->bp_pages = atop(eaddr) - bp->bp_start;
    210 	bp->bp_freelist = VM_FREELIST_DEFAULT;
    211 
    212 #ifdef PMAP_NEED_ALLOC_POOLPAGE
    213 	const uint64_t memory_size = *(uint64_t *)arg;
    214 	if (atop(memory_size) > bp->bp_pages) {
    215 		arm_poolpage_vmfreelist = VM_FREELIST_DIRECTMAP;
    216 		bp->bp_freelist = VM_FREELIST_DIRECTMAP;
    217 	}
    218 #endif
    219 }
    220 
    221 
    222 static void
    223 fdt_print_memory(const struct fdt_memory *m, void *arg)
    224 {
    225 
    226 	VPRINTF("FDT /memory @ 0x%" PRIx64 " size 0x%" PRIx64 "\n",
    227 	    m->start, m->end - m->start);
    228 }
    229 
    230 
    231 /*
    232  * Define usable memory regions.
    233  */
    234 static void
    235 fdt_build_bootconfig(uint64_t mem_start, uint64_t mem_end)
    236 {
    237 	BootConfig *bc = &bootconfig;
    238 
    239 	uint64_t addr, size;
    240 	int index;
    241 
    242 	const uint64_t initrd_size =
    243 	    round_page(initrd_end) - trunc_page(initrd_start);
    244 	if (initrd_size > 0)
    245 		fdt_memory_remove_range(trunc_page(initrd_start), initrd_size);
    246 
    247 	const uint64_t rndseed_size =
    248 	    round_page(rndseed_end) - trunc_page(rndseed_start);
    249 	if (rndseed_size > 0)
    250 		fdt_memory_remove_range(trunc_page(rndseed_start),
    251 		    rndseed_size);
    252 
    253 	const uint64_t efirng_size =
    254 	    round_page(efirng_end) - trunc_page(efirng_start);
    255 	if (efirng_size > 0)
    256 		fdt_memory_remove_range(trunc_page(efirng_start), efirng_size);
    257 
    258 	const int framebuffer = OF_finddevice("/chosen/framebuffer");
    259 	if (framebuffer >= 0) {
    260 		for (index = 0;
    261 		     fdtbus_get_reg64(framebuffer, index, &addr, &size) == 0;
    262 		     index++) {
    263 			fdt_memory_remove_range(addr, size);
    264 		}
    265 	}
    266 
    267 	VPRINTF("Usable memory:\n");
    268 	bc->dramblocks = 0;
    269 	fdt_memory_foreach(fdt_add_dram_blocks, bc);
    270 }
    271 
    272 static void
    273 fdt_probe_range(const char *startname, const char *endname,
    274     uint64_t *pstart, uint64_t *pend)
    275 {
    276 	int chosen, len;
    277 	const void *start_data, *end_data;
    278 
    279 	*pstart = *pend = 0;
    280 
    281 	chosen = OF_finddevice("/chosen");
    282 	if (chosen < 0)
    283 		return;
    284 
    285 	start_data = fdtbus_get_prop(chosen, startname, &len);
    286 	end_data = fdtbus_get_prop(chosen, endname, NULL);
    287 	if (start_data == NULL || end_data == NULL)
    288 		return;
    289 
    290 	switch (len) {
    291 	case 4:
    292 		*pstart = be32dec(start_data);
    293 		*pend = be32dec(end_data);
    294 		break;
    295 	case 8:
    296 		*pstart = be64dec(start_data);
    297 		*pend = be64dec(end_data);
    298 		break;
    299 	default:
    300 		printf("Unsupported len %d for /chosen `%s'\n",
    301 		    len, startname);
    302 		return;
    303 	}
    304 }
    305 
    306 static void *
    307 fdt_map_range(uint64_t start, uint64_t end, uint64_t *psize,
    308     const char *purpose)
    309 {
    310 	const paddr_t startpa = trunc_page(start);
    311 	const paddr_t endpa = round_page(end);
    312 	paddr_t pa;
    313 	vaddr_t va;
    314 	void *ptr;
    315 
    316 	*psize = end - start;
    317 	if (*psize == 0)
    318 		return NULL;
    319 
    320 	const vaddr_t voff = start & PAGE_MASK;
    321 
    322 	va = uvm_km_alloc(kernel_map, *psize, 0, UVM_KMF_VAONLY | UVM_KMF_NOWAIT);
    323 	if (va == 0) {
    324 		printf("Failed to allocate VA for %s\n", purpose);
    325 		return NULL;
    326 	}
    327 	ptr = (void *)(va + voff);
    328 
    329 	for (pa = startpa; pa < endpa; pa += PAGE_SIZE, va += PAGE_SIZE)
    330 		pmap_kenter_pa(va, pa, VM_PROT_READ | VM_PROT_WRITE, 0);
    331 	pmap_update(pmap_kernel());
    332 
    333 	return ptr;
    334 }
    335 
    336 static void
    337 fdt_unmap_range(void *ptr, uint64_t size)
    338 {
    339 	const char *start = ptr, *end = start + size;
    340 	const vaddr_t startva = trunc_page((vaddr_t)(uintptr_t)start);
    341 	const vaddr_t endva = round_page((vaddr_t)(uintptr_t)end);
    342 	const vsize_t sz = endva - startva;
    343 
    344 	pmap_kremove(startva, sz);
    345 	pmap_update(pmap_kernel());
    346 
    347 	uvm_km_free(kernel_map, startva, sz, UVM_KMF_VAONLY);
    348 }
    349 
    350 static void
    351 fdt_probe_initrd(uint64_t *pstart, uint64_t *pend)
    352 {
    353 	*pstart = *pend = 0;
    354 
    355 #ifdef MEMORY_DISK_DYNAMIC
    356 	fdt_probe_range("linux,initrd-start", "linux,initrd-end", pstart, pend);
    357 #endif
    358 }
    359 
    360 static void
    361 fdt_setup_initrd(void)
    362 {
    363 #ifdef MEMORY_DISK_DYNAMIC
    364 	void *md_start;
    365 	uint64_t initrd_size;
    366 
    367 	md_start = fdt_map_range(initrd_start, initrd_end, &initrd_size,
    368 	    "initrd");
    369 	if (md_start == NULL)
    370 		return;
    371 	md_root_setconf(md_start, initrd_size);
    372 #endif
    373 }
    374 
    375 static void
    376 fdt_probe_rndseed(uint64_t *pstart, uint64_t *pend)
    377 {
    378 
    379 	fdt_probe_range("netbsd,rndseed-start", "netbsd,rndseed-end",
    380 	    pstart, pend);
    381 }
    382 
    383 static void
    384 fdt_setup_rndseed(void)
    385 {
    386 	uint64_t rndseed_size;
    387 	void *rndseed;
    388 
    389 	rndseed = fdt_map_range(rndseed_start, rndseed_end, &rndseed_size,
    390 	    "rndseed");
    391 	if (rndseed == NULL)
    392 		return;
    393 	rnd_seed(rndseed, rndseed_size);
    394 	fdt_unmap_range(rndseed, rndseed_size);
    395 }
    396 
    397 static void
    398 fdt_probe_efirng(uint64_t *pstart, uint64_t *pend)
    399 {
    400 
    401 	fdt_probe_range("netbsd,efirng-start", "netbsd,efirng-end",
    402 	    pstart, pend);
    403 }
    404 
    405 static struct krndsource efirng_source;
    406 
    407 static void
    408 fdt_setup_efirng(void)
    409 {
    410 	uint64_t efirng_size;
    411 	void *efirng;
    412 
    413 	efirng = fdt_map_range(efirng_start, efirng_end, &efirng_size,
    414 	    "efirng");
    415 	if (efirng == NULL)
    416 		return;
    417 
    418 	rnd_attach_source(&efirng_source, "efirng", RND_TYPE_RNG,
    419 	    RND_FLAG_DEFAULT);
    420 
    421 	/*
    422 	 * We don't really have specific information about the physical
    423 	 * process underlying the data provided by the firmware via the
    424 	 * EFI RNG API, so the entropy estimate here is heuristic.
    425 	 * What efiboot provides us is up to 4096 bytes of data from
    426 	 * the EFI RNG API, although in principle it may return short.
    427 	 *
    428 	 * The UEFI Specification (2.8 Errata A, February 2020[1]) says
    429 	 *
    430 	 *	When a Deterministic Random Bit Generator (DRBG) is
    431 	 *	used on the output of a (raw) entropy source, its
    432 	 *	security level must be at least 256 bits.
    433 	 *
    434 	 * It's not entirely clear whether `it' refers to the DRBG or
    435 	 * the entropy source; if it refers to the DRBG, it's not
    436 	 * entirely clear how ANSI X9.31 3DES, one of the options for
    437 	 * DRBG in the UEFI spec, can provide a `256-bit security
    438 	 * level' because it has only 232 bits of inputs (three 56-bit
    439 	 * keys and one 64-bit block).  That said, even if it provides
    440 	 * only 232 bits of entropy, that's enough to prevent all
    441 	 * attacks and we probably get a few more bits from sampling
    442 	 * the clock anyway.
    443 	 *
    444 	 * In the event we get raw samples, e.g. the bits sampled by a
    445 	 * ring oscillator, we hope that the samples have at least half
    446 	 * a bit of entropy per bit of data -- and efiboot tries to
    447 	 * draw 4096 bytes to provide plenty of slop.  Hence we divide
    448 	 * the total number of bits by two and clamp at 256.  There are
    449 	 * ways this could go wrong, but on most machines it should
    450 	 * behave reasonably.
    451 	 *
    452 	 * [1] https://uefi.org/sites/default/files/resources/UEFI_Spec_2_8_A_Feb14.pdf
    453 	 */
    454 	rnd_add_data(&efirng_source, efirng, efirng_size,
    455 	    MIN(256, efirng_size*NBBY/2));
    456 
    457 	explicit_memset(efirng, 0, efirng_size);
    458 	fdt_unmap_range(efirng, efirng_size);
    459 }
    460 
    461 #ifdef EFI_RUNTIME
    462 static void
    463 fdt_map_efi_runtime(const char *prop, enum arm_efirt_mem_type type)
    464 {
    465 	int len;
    466 
    467 	const int chosen_off = fdt_path_offset(fdt_data, "/chosen");
    468 	if (chosen_off < 0)
    469 		return;
    470 
    471 	const uint64_t *map = fdt_getprop(fdt_data, chosen_off, prop, &len);
    472 	if (map == NULL)
    473 		return;
    474 
    475 	while (len >= 24) {
    476 		const paddr_t pa = be64toh(map[0]);
    477 		const vaddr_t va = be64toh(map[1]);
    478 		const size_t sz = be64toh(map[2]);
    479 		VPRINTF("%s: %s %#" PRIxPADDR "-%#" PRIxVADDR " (%#" PRIxVADDR
    480 		    "-%#" PRIxVSIZE ")\n", __func__, prop, pa, pa + sz - 1,
    481 		    va, va + sz - 1);
    482 		arm_efirt_md_map_range(va, pa, sz, type);
    483 		map += 3;
    484 		len -= 24;
    485 	}
    486 }
    487 #endif
    488 
    489 vaddr_t
    490 initarm(void *arg)
    491 {
    492 	const struct arm_platform *plat;
    493 	uint64_t memory_start, memory_end;
    494 
    495 	/* set temporally to work printf()/panic() even before consinit() */
    496 	cn_tab = &earlycons;
    497 
    498 	/* Load FDT */
    499 	int error = fdt_check_header(fdt_addr_r);
    500 	if (error != 0)
    501 		panic("fdt_check_header failed: %s", fdt_strerror(error));
    502 
    503 	/* If the DTB is too big, try to pack it in place first. */
    504 	if (fdt_totalsize(fdt_addr_r) > sizeof(fdt_data))
    505 		(void)fdt_pack(__UNCONST(fdt_addr_r));
    506 
    507 	error = fdt_open_into(fdt_addr_r, fdt_data, sizeof(fdt_data));
    508 	if (error != 0)
    509 		panic("fdt_move failed: %s", fdt_strerror(error));
    510 
    511 	fdtbus_init(fdt_data);
    512 
    513 	/* Lookup platform specific backend */
    514 	plat = arm_fdt_platform();
    515 	if (plat == NULL)
    516 		panic("Kernel does not support this device");
    517 
    518 	/* Early console may be available, announce ourselves. */
    519 	VPRINTF("FDT<%p>\n", fdt_addr_r);
    520 
    521 	const int chosen = OF_finddevice("/chosen");
    522 	if (chosen >= 0)
    523 		OF_getprop(chosen, "bootargs", bootargs, sizeof(bootargs));
    524 	boot_args = bootargs;
    525 
    526 	/* Heads up ... Setup the CPU / MMU / TLB functions. */
    527 	VPRINTF("cpufunc\n");
    528 	if (set_cpufuncs())
    529 		panic("cpu not recognized!");
    530 
    531 	/*
    532 	 * Memory is still identity/flat mapped this point so using ttbr for
    533 	 * l1pt VA is fine
    534 	 */
    535 
    536 	VPRINTF("devmap %p\n", plat->ap_devmap());
    537 	extern char ARM_BOOTSTRAP_LxPT[];
    538 	pmap_devmap_bootstrap((vaddr_t)ARM_BOOTSTRAP_LxPT, plat->ap_devmap());
    539 
    540 	VPRINTF("bootstrap\n");
    541 	plat->ap_bootstrap();
    542 
    543 	/*
    544 	 * If stdout-path is specified on the command line, override the
    545 	 * value in /chosen/stdout-path before initializing console.
    546 	 */
    547 	VPRINTF("stdout\n");
    548 	fdt_update_stdout_path();
    549 
    550 #if BYTE_ORDER == BIG_ENDIAN
    551 	/*
    552 	 * Most boards are configured to little-endian mode initially, and
    553 	 * switched to big-endian mode after kernel is loaded. In this case,
    554 	 * framebuffer seems byte-swapped to CPU. Override FDT to let
    555 	 * drivers know.
    556 	 */
    557 	VPRINTF("fb_format\n");
    558 	fdt_update_fb_format();
    559 #endif
    560 
    561 	/*
    562 	 * Done making changes to the FDT.
    563 	 */
    564 	fdt_pack(fdt_data);
    565 
    566 	VPRINTF("consinit ");
    567 	consinit();
    568 	VPRINTF("ok\n");
    569 
    570 	VPRINTF("uboot: args %#lx, %#lx, %#lx, %#lx\n",
    571 	    uboot_args[0], uboot_args[1], uboot_args[2], uboot_args[3]);
    572 
    573 	cpu_reset_address = fdt_reset;
    574 	cpu_powerdown_address = fdt_powerdown;
    575 	evbarm_device_register = fdt_device_register;
    576 	evbarm_device_register_post_config = fdt_device_register_post_config;
    577 	evbarm_cpu_rootconf = fdt_cpu_rootconf;
    578 
    579 	/* Talk to the user */
    580 	printf("NetBSD/evbarm (fdt) booting ...\n");
    581 
    582 #ifdef BOOT_ARGS
    583 	char mi_bootargs[] = BOOT_ARGS;
    584 	parse_mi_bootargs(mi_bootargs);
    585 #endif
    586 
    587 	fdt_memory_get(&memory_start, &memory_end);
    588 
    589 	fdt_memory_foreach(fdt_print_memory, NULL);
    590 
    591 #if !defined(_LP64)
    592 	/* Cannot map memory above 4GB (remove last page as well) */
    593 	const uint64_t memory_limit = 0x100000000ULL - PAGE_SIZE;
    594 	if (memory_end > memory_limit) {
    595 		fdt_memory_remove_range(memory_limit , memory_end);
    596 		memory_end = memory_limit;
    597 	}
    598 #endif
    599 	uint64_t memory_size = memory_end - memory_start;
    600 
    601 	VPRINTF("%s: memory start %" PRIx64 " end %" PRIx64 " (len %"
    602 	    PRIx64 ")\n", __func__, memory_start, memory_end, memory_size);
    603 
    604 	/* Parse ramdisk info */
    605 	fdt_probe_initrd(&initrd_start, &initrd_end);
    606 
    607 	/* Parse our on-disk rndseed and the firmware's RNG from EFI */
    608 	fdt_probe_rndseed(&rndseed_start, &rndseed_end);
    609 	fdt_probe_efirng(&efirng_start, &efirng_end);
    610 
    611 	fdt_memory_remove_reserved(memory_start, memory_end);
    612 
    613 	/*
    614 	 * Populate bootconfig structure for the benefit of dodumpsys
    615 	 */
    616 	VPRINTF("%s: fdt_build_bootconfig\n", __func__);
    617 	fdt_build_bootconfig(memory_start, memory_end);
    618 
    619 	/* Perform PT build and VM init */
    620 	cpu_kernel_vm_init(memory_start, memory_size);
    621 
    622 	VPRINTF("bootargs: %s\n", bootargs);
    623 
    624 	parse_mi_bootargs(boot_args);
    625 
    626 	VPRINTF("Memory regions:\n");
    627 
    628 	/* Populate fdt_physmem / nfdt_physmem for initarm_common */
    629 	fdt_memory_foreach(fdt_add_boot_physmem, &memory_size);
    630 
    631 	vaddr_t sp = initarm_common(KERNEL_VM_BASE, KERNEL_VM_SIZE, fdt_physmem,
    632 	     nfdt_physmem);
    633 
    634 	/*
    635 	 * initarm_common flushes cache if required before AP start
    636 	 */
    637 	error = 0;
    638 	if ((boothowto & RB_MD1) == 0) {
    639 		VPRINTF("mpstart\n");
    640 		if (plat->ap_mpstart)
    641 			error = plat->ap_mpstart();
    642 	}
    643 
    644 	if (error)
    645 		return sp;
    646 
    647 	/*
    648 	 * Now we have APs started the pages used for stacks and L1PT can
    649 	 * be given to uvm
    650 	 */
    651 	extern char const __start__init_memory[];
    652 	extern char const __stop__init_memory[] __weak;
    653 
    654 	if (__start__init_memory != __stop__init_memory) {
    655 		const paddr_t spa = KERN_VTOPHYS((vaddr_t)__start__init_memory);
    656 		const paddr_t epa = KERN_VTOPHYS((vaddr_t)__stop__init_memory);
    657 		const paddr_t spg = atop(spa);
    658 		const paddr_t epg = atop(epa);
    659 
    660 		VPRINTF("         start %08lx  end %08lx... "
    661 		    "loading in freelist %d\n", spa, epa, VM_FREELIST_DEFAULT);
    662 
    663 		uvm_page_physload(spg, epg, spg, epg, VM_FREELIST_DEFAULT);
    664 	}
    665 
    666 	return sp;
    667 }
    668 
    669 static void
    670 fdt_update_stdout_path(void)
    671 {
    672 	char *stdout_path, *ep;
    673 	int stdout_path_len;
    674 	char buf[256];
    675 
    676 	const int chosen_off = fdt_path_offset(fdt_data, "/chosen");
    677 	if (chosen_off == -1)
    678 		return;
    679 
    680 	if (get_bootconf_option(boot_args, "stdout-path",
    681 	    BOOTOPT_TYPE_STRING, &stdout_path) == 0)
    682 		return;
    683 
    684 	ep = strchr(stdout_path, ' ');
    685 	stdout_path_len = ep ? (ep - stdout_path) : strlen(stdout_path);
    686 	if (stdout_path_len >= sizeof(buf))
    687 		return;
    688 
    689 	strncpy(buf, stdout_path, stdout_path_len);
    690 	buf[stdout_path_len] = '\0';
    691 	fdt_setprop(fdt_data, chosen_off, "stdout-path",
    692 	    buf, stdout_path_len + 1);
    693 }
    694 
    695 void
    696 consinit(void)
    697 {
    698 	static bool initialized = false;
    699 	const struct arm_platform *plat = arm_fdt_platform();
    700 	const struct fdt_console *cons = fdtbus_get_console();
    701 	struct fdt_attach_args faa;
    702 	u_int uart_freq = 0;
    703 
    704 	if (initialized || cons == NULL)
    705 		return;
    706 
    707 	plat->ap_init_attach_args(&faa);
    708 	faa.faa_phandle = fdtbus_get_stdout_phandle();
    709 
    710 	if (plat->ap_uart_freq != NULL)
    711 		uart_freq = plat->ap_uart_freq();
    712 
    713 	cons->consinit(&faa, uart_freq);
    714 
    715 	initialized = true;
    716 }
    717 
    718 void
    719 cpu_startup_hook(void)
    720 {
    721 #ifdef EFI_RUNTIME
    722 	fdt_map_efi_runtime("netbsd,uefi-runtime-code", ARM_EFIRT_MEM_CODE);
    723 	fdt_map_efi_runtime("netbsd,uefi-runtime-data", ARM_EFIRT_MEM_DATA);
    724 	fdt_map_efi_runtime("netbsd,uefi-runtime-mmio", ARM_EFIRT_MEM_MMIO);
    725 #endif
    726 
    727 	fdtbus_intr_init();
    728 
    729 	fdt_setup_rndseed();
    730 	fdt_setup_efirng();
    731 }
    732 
    733 void
    734 delay(u_int us)
    735 {
    736 	const struct arm_platform *plat = arm_fdt_platform();
    737 
    738 	plat->ap_delay(us);
    739 }
    740 
    741 static void
    742 fdt_detect_root_device(device_t dev)
    743 {
    744 	struct mbr_sector mbr;
    745 	uint8_t buf[DEV_BSIZE];
    746 	uint8_t hash[16];
    747 	const uint8_t *rhash;
    748 	char rootarg[64];
    749 	struct vnode *vp;
    750 	MD5_CTX md5ctx;
    751 	int error, len;
    752 	size_t resid;
    753 	u_int part;
    754 
    755 	const int chosen = OF_finddevice("/chosen");
    756 	if (chosen < 0)
    757 		return;
    758 
    759 	if (of_hasprop(chosen, "netbsd,mbr") &&
    760 	    of_hasprop(chosen, "netbsd,partition")) {
    761 
    762 		/*
    763 		 * The bootloader has passed in a partition index and MD5 hash
    764 		 * of the MBR sector. Read the MBR of this device, calculate the
    765 		 * hash, and compare it with the value passed in.
    766 		 */
    767 		rhash = fdtbus_get_prop(chosen, "netbsd,mbr", &len);
    768 		if (rhash == NULL || len != 16)
    769 			return;
    770 		of_getprop_uint32(chosen, "netbsd,partition", &part);
    771 		if (part >= MAXPARTITIONS)
    772 			return;
    773 
    774 		vp = opendisk(dev);
    775 		if (!vp)
    776 			return;
    777 		error = vn_rdwr(UIO_READ, vp, buf, sizeof(buf), 0, UIO_SYSSPACE,
    778 		    IO_NODELOCKED, NOCRED, &resid, NULL);
    779 		VOP_CLOSE(vp, FREAD, NOCRED);
    780 		vput(vp);
    781 
    782 		if (error != 0)
    783 			return;
    784 
    785 		memcpy(&mbr, buf, sizeof(mbr));
    786 		MD5Init(&md5ctx);
    787 		MD5Update(&md5ctx, (void *)&mbr, sizeof(mbr));
    788 		MD5Final(hash, &md5ctx);
    789 
    790 		if (memcmp(rhash, hash, 16) != 0)
    791 			return;
    792 
    793 		snprintf(rootarg, sizeof(rootarg), " root=%s%c", device_xname(dev), part + 'a');
    794 		strcat(boot_args, rootarg);
    795 	}
    796 
    797 	if (of_hasprop(chosen, "netbsd,gpt-guid")) {
    798 		char guidbuf[UUID_STR_LEN];
    799 		const struct uuid *guid = fdtbus_get_prop(chosen, "netbsd,gpt-guid", &len);
    800 		if (guid == NULL || len != 16)
    801 			return;
    802 
    803 		uuid_snprintf(guidbuf, sizeof(guidbuf), guid);
    804 		snprintf(rootarg, sizeof(rootarg), " root=wedge:%s", guidbuf);
    805 		strcat(boot_args, rootarg);
    806 	}
    807 
    808 	if (of_hasprop(chosen, "netbsd,gpt-label")) {
    809 		const char *label = fdtbus_get_string(chosen, "netbsd,gpt-label");
    810 		if (label == NULL || *label == '\0')
    811 			return;
    812 
    813 		device_t dv = dkwedge_find_by_wname(label);
    814 		if (dv != NULL)
    815 			booted_device = dv;
    816 	}
    817 
    818 	if (of_hasprop(chosen, "netbsd,booted-mac-address")) {
    819 		const uint8_t *macaddr = fdtbus_get_prop(chosen, "netbsd,booted-mac-address", &len);
    820 		if (macaddr == NULL || len != 6)
    821 			return;
    822 		int s = pserialize_read_enter();
    823 		struct ifnet *ifp;
    824 		IFNET_READER_FOREACH(ifp) {
    825 			if (memcmp(macaddr, CLLADDR(ifp->if_sadl), len) == 0) {
    826 				device_t dv = device_find_by_xname(ifp->if_xname);
    827 				if (dv != NULL)
    828 					booted_device = dv;
    829 				break;
    830 			}
    831 		}
    832 		pserialize_read_exit(s);
    833 	}
    834 }
    835 
    836 static void
    837 fdt_device_register(device_t self, void *aux)
    838 {
    839 	const struct arm_platform *plat = arm_fdt_platform();
    840 
    841 	if (device_is_a(self, "armfdt")) {
    842 		fdt_setup_initrd();
    843 
    844 #if NWSDISPLAY > 0 && NGENFB > 0
    845 		/*
    846 		 * Setup framebuffer console, if present.
    847 		 */
    848 		arm_simplefb_preattach();
    849 #endif
    850 	}
    851 
    852 #if NWSDISPLAY > 0 && NGENFB > 0
    853 	if (device_is_a(self, "genfb")) {
    854 		prop_dictionary_t dict = device_properties(self);
    855 		prop_dictionary_set_uint64(dict,
    856 		    "simplefb-physaddr", arm_simplefb_physaddr());
    857 	}
    858 #endif
    859 
    860 	if (plat && plat->ap_device_register)
    861 		plat->ap_device_register(self, aux);
    862 }
    863 
    864 static void
    865 fdt_device_register_post_config(device_t self, void *aux)
    866 {
    867 #if NUKBD > 0 && NWSDISPLAY > 0
    868 	if (device_is_a(self, "wsdisplay")) {
    869 		struct wsdisplay_softc *sc = device_private(self);
    870 		if (wsdisplay_isconsole(sc))
    871 			ukbd_cnattach();
    872 	}
    873 #endif
    874 }
    875 
    876 static void
    877 fdt_cpu_rootconf(void)
    878 {
    879 	device_t dev;
    880 	deviter_t di;
    881 	char *ptr;
    882 
    883 	if (booted_device != NULL)
    884 		return;
    885 
    886 	for (dev = deviter_first(&di, 0); dev; dev = deviter_next(&di)) {
    887 		if (device_class(dev) != DV_DISK)
    888 			continue;
    889 
    890 		if (get_bootconf_option(boot_args, "root", BOOTOPT_TYPE_STRING, &ptr) != 0)
    891 			break;
    892 
    893 		if (device_is_a(dev, "ld") || device_is_a(dev, "sd") || device_is_a(dev, "wd"))
    894 			fdt_detect_root_device(dev);
    895 	}
    896 	deviter_release(&di);
    897 }
    898 
    899 static void
    900 fdt_reset(void)
    901 {
    902 	const struct arm_platform *plat = arm_fdt_platform();
    903 
    904 	fdtbus_power_reset();
    905 
    906 	if (plat && plat->ap_reset)
    907 		plat->ap_reset();
    908 }
    909 
    910 static void
    911 fdt_powerdown(void)
    912 {
    913 	fdtbus_power_poweroff();
    914 }
    915 
    916 #if BYTE_ORDER == BIG_ENDIAN
    917 static void
    918 fdt_update_fb_format(void)
    919 {
    920 	int off, len;
    921 	const char *format, *replace;
    922 
    923 	off = fdt_path_offset(fdt_data, "/chosen");
    924 	if (off < 0)
    925 		return;
    926 
    927 	for (;;) {
    928 		off = fdt_node_offset_by_compatible(fdt_data, off,
    929 		    "simple-framebuffer");
    930 		if (off < 0)
    931 			return;
    932 
    933 		format = fdt_getprop(fdt_data, off, "format", &len);
    934 		if (format == NULL)
    935 			continue;
    936 
    937 		replace = NULL;
    938 		if (strcmp(format, "a8b8g8r8") == 0)
    939 			replace = "r8g8b8a8";
    940 		else if (strcmp(format, "x8r8g8b8") == 0)
    941 			replace = "b8g8r8x8";
    942 		if (replace != NULL)
    943 			fdt_setprop(fdt_data, off, "format", replace,
    944 			    strlen(replace) + 1);
    945 	}
    946 }
    947 #endif
    948