xref: /openbsd/sys/arch/armv7/armv7/armv7_machdep.c (revision 5a38ef86)
1 /*	$OpenBSD: armv7_machdep.c,v 1.64 2021/10/06 12:50:10 visa Exp $ */
2 /*	$NetBSD: lubbock_machdep.c,v 1.2 2003/07/15 00:25:06 lukem Exp $ */
3 
4 /*
5  * Copyright (c) 2002, 2003  Genetec Corporation.  All rights reserved.
6  * Written by Hiroyuki Bessho for Genetec Corporation.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of Genetec Corporation may not be used to endorse or
17  *    promote products derived from this software without specific prior
18  *    written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY GENETEC CORPORATION ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL GENETEC CORPORATION
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  *
32  * Machine dependant functions for kernel setup for
33  * Intel DBPXA250 evaluation board (a.k.a. Lubbock).
34  * Based on iq80310_machhdep.c
35  */
36 /*
37  * Copyright (c) 2001 Wasabi Systems, Inc.
38  * All rights reserved.
39  *
40  * Written by Jason R. Thorpe for Wasabi Systems, Inc.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *	This product includes software developed for the NetBSD Project by
53  *	Wasabi Systems, Inc.
54  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
55  *    or promote products derived from this software without specific prior
56  *    written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
60  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
61  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
62  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
63  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
65  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
66  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
67  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
68  * POSSIBILITY OF SUCH DAMAGE.
69  */
70 
71 /*
72  * Copyright (c) 1997,1998 Mark Brinicombe.
73  * Copyright (c) 1997,1998 Causality Limited.
74  * All rights reserved.
75  *
76  * Redistribution and use in source and binary forms, with or without
77  * modification, are permitted provided that the following conditions
78  * are met:
79  * 1. Redistributions of source code must retain the above copyright
80  *    notice, this list of conditions and the following disclaimer.
81  * 2. Redistributions in binary form must reproduce the above copyright
82  *    notice, this list of conditions and the following disclaimer in the
83  *    documentation and/or other materials provided with the distribution.
84  * 3. All advertising materials mentioning features or use of this software
85  *    must display the following acknowledgement:
86  *	This product includes software developed by Mark Brinicombe
87  *	for the NetBSD Project.
88  * 4. The name of the company nor the name of the author may be used to
89  *    endorse or promote products derived from this software without specific
90  *    prior written permission.
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
93  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
94  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
95  * IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
96  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
97  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
98  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
100  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
101  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
102  * SUCH DAMAGE.
103  *
104  * Machine dependant functions for kernel setup for ARMv7 boards using
105  * u-boot/EFI firmware.
106  */
107 
108 #include <sys/param.h>
109 #include <sys/systm.h>
110 #include <sys/proc.h>
111 #include <sys/reboot.h>
112 
113 #include <machine/db_machdep.h>
114 #include <machine/bootconfig.h>
115 #include <machine/machine_reg.h>
116 #include <machine/bus.h>
117 
118 #include <arm/undefined.h>
119 #include <arm/machdep.h>
120 #include <arm/armv7/armv7var.h>
121 #include <armv7/armv7/armv7_machdep.h>
122 
123 #include <dev/cons.h>
124 #include <dev/ofw/fdt.h>
125 #include <dev/ofw/openfirm.h>
126 #include <dev/acpi/efi.h>
127 
128 #include <net/if.h>
129 
130 #include <ddb/db_extern.h>
131 
132 /* Kernel text starts 2MB in from the bottom of the kernel address space. */
133 #define	KERNEL_TEXT_BASE	(KERNEL_BASE + 0x00000000)
134 #define	KERNEL_VM_BASE		(KERNEL_BASE + 0x04000000)
135 #define KERNEL_VM_SIZE		VM_KERNEL_SPACE_SIZE
136 
137 /*
138  * Address to call from cpu_reset() to reset the machine.
139  * This is machine architecture dependant as it varies depending
140  * on where the ROM appears when you turn the MMU off.
141  */
142 
143 /* Define various stack sizes in pages */
144 #define IRQ_STACK_SIZE	1
145 #define ABT_STACK_SIZE	1
146 #define UND_STACK_SIZE	1
147 
148 BootConfig bootconfig;		/* Boot config storage */
149 char *boot_args = NULL;
150 char *boot_file = "";
151 uint8_t *bootmac = NULL;
152 u_int cpu_reset_address = 0;
153 
154 vaddr_t physical_freestart;
155 int physmem;
156 
157 /*int debug_flags;*/
158 #ifndef PMAP_STATIC_L1S
159 int max_processes = 64;			/* Default number */
160 #endif	/* !PMAP_STATIC_L1S */
161 
162 /* Physical and virtual addresses for some global pages */
163 pv_addr_t systempage;
164 pv_addr_t irqstack;
165 pv_addr_t undstack;
166 pv_addr_t abtstack;
167 extern pv_addr_t kernelstack;
168 
169 vaddr_t msgbufphys;
170 
171 extern u_int data_abort_handler_address;
172 extern u_int prefetch_abort_handler_address;
173 extern u_int undefined_handler_address;
174 
175 #define KERNEL_PT_SYS		0	/* Page table for mapping proc0 zero page */
176 #define KERNEL_PT_KERNEL	1	/* Page table for mapping kernel */
177 #define	KERNEL_PT_KERNEL_NUM	32
178 #define KERNEL_PT_VMDATA	(KERNEL_PT_KERNEL+KERNEL_PT_KERNEL_NUM)
179 				        /* Page tables for mapping kernel VM */
180 #define	KERNEL_PT_VMDATA_NUM	8	/* start with 16MB of KVM */
181 #define NUM_KERNEL_PTS		(KERNEL_PT_VMDATA + KERNEL_PT_VMDATA_NUM)
182 
183 pv_addr_t kernel_pt_table[NUM_KERNEL_PTS];
184 
185 extern struct user *proc0paddr;
186 
187 /*
188  * safepri is a safe priority for sleep to set for a spin-wait
189  * during autoconfiguration or after a panic.
190  */
191 int   safepri = 0;
192 
193 /* Prototypes */
194 
195 int	bootstrap_bs_map(void *, uint64_t, bus_size_t, int,
196     bus_space_handle_t *);
197 void	collect_kernel_args(const char *);
198 void	process_kernel_args(void);
199 void	consinit(void);
200 
201 bs_protos(bs_notimpl);
202 
203 int stdout_node;
204 int stdout_speed;
205 
206 void (*cpuresetfn)(void);
207 void (*powerdownfn)(void);
208 
209 /*
210  * void boot(int howto, char *bootstr)
211  *
212  * Reboots the system
213  *
214  * Deal with any syncing, unmounting, dumping and shutdown hooks,
215  * then reset the CPU.
216  */
217 __dead void
218 boot(int howto)
219 {
220 	if ((howto & RB_RESET) != 0)
221 		goto doreset;
222 
223 	if (cold) {
224 		if ((howto & RB_USERREQ) == 0)
225 			howto |= RB_HALT;
226 		goto haltsys;
227 	}
228 
229 	/* Disable console buffering */
230 /*	cnpollc(1);*/
231 
232 	/*
233 	 * If RB_NOSYNC was not specified sync the discs.
234 	 * Note: Unless cold is set to 1 here, syslogd will die during the
235 	 * unmount.  It looks like syslogd is getting woken up only to find
236 	 * that it cannot page part of the binary in as the filesystem has
237 	 * been unmounted.
238 	 */
239 	if ((howto & RB_NOSYNC) == 0)
240 		bootsync(howto);
241 
242 	if_downall();
243 
244 	uvm_shutdown();
245 	splhigh();
246 	cold = 1;
247 
248 	if ((howto & (RB_DUMP | RB_HALT)) == RB_DUMP)
249 		dumpsys();
250 
251 haltsys:
252 	config_suspend_all(DVACT_POWERDOWN);
253 
254 	/* Make sure IRQ's are disabled */
255 	intr_disable();
256 
257 	if ((howto & RB_HALT) != 0) {
258 		if ((howto & RB_POWERDOWN) != 0) {
259 			printf("\nAttempting to power down...\n");
260 			delay(500000);
261 			if (powerdownfn)
262 				(*powerdownfn)();
263 		}
264 
265 		printf("The operating system has halted.\n");
266 		printf("Please press any key to reboot.\n\n");
267 		cngetc();
268 	}
269 
270 doreset:
271 	printf("rebooting...\n");
272 	delay(500000);
273 	if (cpuresetfn)
274 		(*cpuresetfn)();
275 	printf("reboot failed; spinning\n");
276 	for (;;)
277 		continue;
278 	/* NOTREACHED */
279 }
280 
281 static __inline
282 pd_entry_t *
283 read_ttb(void)
284 {
285   long ttb;
286 
287   __asm volatile("mrc	p15, 0, %0, c2, c0, 0" : "=r" (ttb));
288 
289 
290   return (pd_entry_t *)(ttb & ~((1<<14)-1));
291 }
292 
293 #define VERBOSE_INIT_ARM
294 
295 /*
296  * simple memory mapping function used in early bootstrap stage
297  * before pmap is initialized.
298  * ignores cacheability and does map the sections with nocache.
299  */
300 static vaddr_t section_free = 0xfd000000; /* XXX - huh */
301 
302 int
303 bootstrap_bs_map(void *t, uint64_t bpa, bus_size_t size,
304     int flags, bus_space_handle_t *bshp)
305 {
306 	u_long startpa, pa, endpa;
307 	vaddr_t va;
308 	pd_entry_t *pagedir = read_ttb();
309 	/* This assumes PA==VA for page directory */
310 
311 	va = section_free;
312 
313 	startpa = bpa & ~L1_S_OFFSET;
314 	endpa = (bpa + size) & ~L1_S_OFFSET;
315 	if ((bpa + size) & L1_S_OFFSET)
316 		endpa += L1_S_SIZE;
317 
318 	*bshp = (bus_space_handle_t)(va + (bpa - startpa));
319 
320 	for (pa = startpa; pa < endpa; pa += L1_S_SIZE, va += L1_S_SIZE)
321 		pmap_map_section((vaddr_t)pagedir, va, pa,
322 		    PROT_READ | PROT_WRITE, PTE_NOCACHE);
323 
324 	cpu_tlb_flushD();
325 
326 	section_free = va;
327 
328 	return 0;
329 }
330 
331 static void
332 copy_io_area_map(pd_entry_t *new_pd)
333 {
334 	pd_entry_t *cur_pd = read_ttb();
335 	vaddr_t va;
336 
337 	for (va = MACHINE_IO_AREA_VBASE;
338 	     (cur_pd[va>>L1_S_SHIFT] & L1_TYPE_MASK) == L1_TYPE_S;
339 	     va += L1_S_SIZE) {
340 
341 		new_pd[va>>L1_S_SHIFT] = cur_pd[va>>L1_S_SHIFT];
342 		if (va == (ARM_VECTORS_HIGH & ~(0x00400000 - 1)))
343 			break; /* STUPID */
344 
345 	}
346 }
347 
348 uint64_t mmap_start;
349 uint32_t mmap_size;
350 uint32_t mmap_desc_size;
351 uint32_t mmap_desc_ver;
352 
353 EFI_MEMORY_DESCRIPTOR *mmap;
354 
355 /*
356  * u_int initarm(...)
357  *
358  * Initial entry point on startup. This gets called before main() is
359  * entered.
360  * It should be responsible for setting up everything that must be
361  * in place when main is called.
362  * This includes
363  *   Taking a copy of the FDT.
364  *   Initialising the physical console so characters can be printed.
365  *   Setting up page tables for the kernel.
366  */
367 u_int
368 initarm(void *arg0, void *arg1, void *arg2, paddr_t loadaddr)
369 {
370 	int loop, loop1;
371 	u_int l1pagetable;
372 	pv_addr_t kernel_l1pt;
373 	pv_addr_t fdt, map;
374 	struct fdt_reg reg;
375 	paddr_t memstart, memend;
376 	void *config;
377 	size_t size;
378 	void *node;
379 	extern uint32_t esym; /* &_end if no symbols are loaded */
380 
381 	/* early bus_space_map support */
382 	struct bus_space tmp_bs_tag;
383 	int	(*map_func_save)(void *, uint64_t, bus_size_t, int,
384 	    bus_space_handle_t *);
385 
386 	if (arg0)
387 		esym = (uint32_t)arg0;
388 
389 	/*
390 	 * Heads up ... Setup the CPU / MMU / TLB functions
391 	 */
392 	if (set_cpufuncs())
393 		panic("cpu not recognized!");
394 
395 	/*
396 	 * Temporarily replace bus_space_map() functions so that
397 	 * console devices can get mapped.
398 	 */
399 	tmp_bs_tag = armv7_bs_tag;
400 	map_func_save = armv7_bs_tag.bs_map;
401 	armv7_bs_tag.bs_map = bootstrap_bs_map;
402 	tmp_bs_tag.bs_map = bootstrap_bs_map;
403 
404 	/*
405 	 * Now, map the FDT area.
406 	 *
407 	 * As we don't know the size of a possible FDT, map the size of a
408 	 * typical bootstrap bs map.  The FDT might not be aligned, so this
409 	 * might take up to two L1_S_SIZEd mappings.
410 	 *
411 	 * XXX: There's (currently) no way to unmap a bootstrap mapping, so
412 	 * we might lose a bit of the bootstrap address space.
413 	 */
414 	bootstrap_bs_map(NULL, (bus_addr_t)arg2, L1_S_SIZE, 0,
415 	    (bus_space_handle_t *)&config);
416 
417 	if (!fdt_init(config) || fdt_get_size(config) == 0)
418 		panic("initarm: no FDT");
419 
420 	node = fdt_find_node("/chosen");
421 	if (node != NULL) {
422 		char *prop;
423 		int len;
424 		static uint8_t lladdr[6];
425 
426 		len = fdt_node_property(node, "bootargs", &prop);
427 		if (len > 0)
428 			collect_kernel_args(prop);
429 
430 		len = fdt_node_property(node, "openbsd,boothowto", &prop);
431 		if (len == sizeof(boothowto))
432 			boothowto = bemtoh32((uint32_t *)prop);
433 
434 		len = fdt_node_property(node, "openbsd,bootduid", &prop);
435 		if (len == sizeof(bootduid))
436 			memcpy(bootduid, prop, sizeof(bootduid));
437 
438 		len = fdt_node_property(node, "openbsd,bootmac", &prop);
439 		if (len == sizeof(lladdr)) {
440 			memcpy(lladdr, prop, sizeof(lladdr));
441 			bootmac = lladdr;
442 		}
443 
444 		len = fdt_node_property(node, "openbsd,uefi-mmap-start", &prop);
445 		if (len == sizeof(mmap_start))
446 			mmap_start = bemtoh64((uint64_t *)prop);
447 		len = fdt_node_property(node, "openbsd,uefi-mmap-size", &prop);
448 		if (len == sizeof(mmap_size))
449 			mmap_size = bemtoh32((uint32_t *)prop);
450 		len = fdt_node_property(node, "openbsd,uefi-mmap-desc-size", &prop);
451 		if (len == sizeof(mmap_desc_size))
452 			mmap_desc_size = bemtoh32((uint32_t *)prop);
453 		len = fdt_node_property(node, "openbsd,uefi-mmap-desc-ver", &prop);
454 		if (len == sizeof(mmap_desc_ver))
455 			mmap_desc_ver = bemtoh32((uint32_t *)prop);
456 
457 		len = fdt_node_property(node, "openbsd,dma-constraint", &prop);
458 		if (len == sizeof(uint64_t[2])) {
459 			dma_constraint.ucr_low = bemtoh64((uint64_t *)prop);
460 			dma_constraint.ucr_high = bemtoh64((uint64_t *)prop + 1);
461 		}
462 	}
463 
464 	process_kernel_args();
465 
466 	if (mmap_start != 0)
467 		bootstrap_bs_map(NULL, mmap_start, mmap_size, 0,
468 		    (bus_space_handle_t *)&mmap);
469 
470 	platform_init();
471 
472 	/* setup a serial console for very early boot */
473 	consinit();
474 
475 	/* Talk to the user */
476 	printf("\nOpenBSD/armv7 booting ...\n");
477 
478 	printf("arg0 %p arg1 %p arg2 %p\n", arg0, arg1, arg2);
479 
480 #ifdef RAMDISK_HOOKS
481 	boothowto |= RB_DFLTROOT;
482 #endif /* RAMDISK_HOOKS */
483 
484 	physical_freestart = (((unsigned long)esym - KERNEL_TEXT_BASE + 0xfff) & ~0xfff) + loadaddr;
485 
486 	/* The bootloader has loaded us ubto a 32MB block. */
487 	memstart = loadaddr;
488 	memend = memstart + 32 * 1024 * 1024;
489 
490 	/*
491 	 * Okay, the kernel starts 2MB in from the bottom of physical
492 	 * memory.  We are going to allocate our bootstrap pages downwards
493 	 * from there.
494 	 *
495 	 * We need to allocate some fixed page tables to get the kernel
496 	 * going.  We allocate one page directory and a number of page
497 	 * tables and store the physical addresses in the kernel_pt_table
498 	 * array.
499 	 *
500 	 * The kernel page directory must be on a 16K boundary.  The page
501 	 * tables must be on 4K boundaries.  What we do is allocate the
502 	 * page directory on the first 16K boundary that we encounter, and
503 	 * the page tables on 4K boundaries otherwise.  Since we allocate
504 	 * at least 3 L2 page tables, we are guaranteed to encounter at
505 	 * least one 16K aligned region.
506 	 */
507 
508 #ifdef VERBOSE_INIT_ARM
509 	printf("Allocating page tables\n");
510 #endif
511 
512 	/* Define a macro to simplify memory allocation */
513 #define	valloc_pages(var, np)				\
514 	alloc_pages((var).pv_pa, (np));			\
515 	(var).pv_va = KERNEL_BASE + (var).pv_pa - loadaddr;
516 
517 #define alloc_pages(var, np)				\
518 	(var) = physical_freestart;			\
519 	physical_freestart += ((np) * PAGE_SIZE);	\
520 	if (physical_freestart > memend)		\
521 		panic("initarm: out of memory");	\
522 	memset((char *)(var), 0, ((np) * PAGE_SIZE));
523 
524 	loop1 = 0;
525 	kernel_l1pt.pv_pa = 0;
526 	for (loop = 0; loop <= NUM_KERNEL_PTS; ++loop) {
527 		/* Are we 16KB aligned for an L1 ? */
528 		if (((physical_freestart) & (L1_TABLE_SIZE - 1)) == 0
529 		    && kernel_l1pt.pv_pa == 0) {
530 			valloc_pages(kernel_l1pt, L1_TABLE_SIZE / PAGE_SIZE);
531 		} else {
532 			valloc_pages(kernel_pt_table[loop1],
533 			    L2_TABLE_SIZE / PAGE_SIZE);
534 			++loop1;
535 		}
536 	}
537 
538 	/* This should never be able to happen but better confirm that. */
539 	if (!kernel_l1pt.pv_pa || (kernel_l1pt.pv_pa & (L1_TABLE_SIZE-1)) != 0)
540 		panic("initarm: Failed to align the kernel page directory");
541 
542 	/*
543 	 * Allocate a page for the system page mapped to V0x00000000
544 	 * This page will just contain the system vectors and can be
545 	 * shared by all processes.
546 	 */
547 	vector_page = ARM_VECTORS_HIGH;
548 	alloc_pages(systempage.pv_pa, 1);
549 	systempage.pv_va = vector_page;
550 
551 	/* Allocate stacks for all modes */
552 	valloc_pages(irqstack, IRQ_STACK_SIZE);
553 	valloc_pages(abtstack, ABT_STACK_SIZE);
554 	valloc_pages(undstack, UND_STACK_SIZE);
555 	valloc_pages(kernelstack, UPAGES);
556 
557 	/* Allocate enough pages for cleaning the Mini-Data cache. */
558 
559 #ifdef VERBOSE_INIT_ARM
560 	printf("IRQ stack: p0x%08lx v0x%08lx\n", irqstack.pv_pa,
561 	    irqstack.pv_va);
562 	printf("ABT stack: p0x%08lx v0x%08lx\n", abtstack.pv_pa,
563 	    abtstack.pv_va);
564 	printf("UND stack: p0x%08lx v0x%08lx\n", undstack.pv_pa,
565 	    undstack.pv_va);
566 	printf("SVC stack: p0x%08lx v0x%08lx\n", kernelstack.pv_pa,
567 	    kernelstack.pv_va);
568 #endif
569 
570 	/* Relocate the FDT to safe memory. */
571 	size = fdt_get_size(config);
572 	valloc_pages(fdt, round_page(size) / PAGE_SIZE);
573 	memcpy((void *)fdt.pv_pa, config, size);
574 
575 	/* Relocate the EFI memory map too. */
576 	if (mmap_start != 0) {
577 		valloc_pages(map, round_page(mmap_size) / PAGE_SIZE);
578 		memcpy((void *)map.pv_pa, mmap, mmap_size);
579 	}
580 
581 	/*
582 	 * XXX Defer this to later so that we can reclaim the memory
583 	 */
584 	alloc_pages(msgbufphys, round_page(MSGBUFSIZE) / PAGE_SIZE);
585 
586 	/*
587 	 * Ok we have allocated physical pages for the primary kernel
588 	 * page tables
589 	 */
590 
591 #ifdef VERBOSE_INIT_ARM
592 	printf("Creating L1 page table at 0x%08lx\n", kernel_l1pt.pv_pa);
593 #endif
594 
595 	/*
596 	 * Now we start construction of the L1 page table
597 	 * We start by mapping the L2 page tables into the L1.
598 	 * This means that we can replace L1 mappings later on if necessary
599 	 */
600 	l1pagetable = kernel_l1pt.pv_pa;
601 
602 	/* Map the L2 pages tables in the L1 page table */
603 	pmap_link_l2pt(l1pagetable, vector_page & ~(0x00400000 - 1),
604 	    &kernel_pt_table[KERNEL_PT_SYS]);
605 
606 	for (loop = 0; loop < KERNEL_PT_KERNEL_NUM; loop++)
607 		pmap_link_l2pt(l1pagetable, KERNEL_BASE + loop * 0x00400000,
608 		    &kernel_pt_table[KERNEL_PT_KERNEL + loop]);
609 
610 	for (loop = 0; loop < KERNEL_PT_VMDATA_NUM; loop++)
611 		pmap_link_l2pt(l1pagetable, KERNEL_VM_BASE + loop * 0x00400000,
612 		    &kernel_pt_table[KERNEL_PT_VMDATA + loop]);
613 
614 	/* update the top of the kernel VM */
615 	pmap_curmaxkvaddr =
616 	    KERNEL_VM_BASE + (KERNEL_PT_VMDATA_NUM * 0x00400000);
617 
618 #ifdef VERBOSE_INIT_ARM
619 	printf("Mapping kernel\n");
620 #endif
621 
622 	/* Now we fill in the L2 pagetable for the kernel static code/data */
623 	{
624 		extern char __text_start[], _etext[];
625 		extern char __rodata_start[], _erodata[];
626 		size_t textsize = (u_int32_t) (_etext - __text_start);
627 		size_t rodatasize = (u_int32_t) (_erodata - __rodata_start);
628 		size_t totalsize = esym - (u_int32_t)__text_start;
629 		u_int logical;
630 
631 		textsize = (textsize + PGOFSET) & ~PGOFSET;
632 		rodatasize = (rodatasize + PGOFSET) & ~PGOFSET;
633 		totalsize = (totalsize + PGOFSET) & ~PGOFSET;
634 
635 		logical = 0x00300000;	/* offset of kernel in RAM */
636 
637 		logical += pmap_map_chunk(l1pagetable, KERNEL_BASE + logical,
638 		    loadaddr + logical, textsize,
639 		    PROT_READ | PROT_EXEC, PTE_CACHE);
640 		logical += pmap_map_chunk(l1pagetable, KERNEL_BASE + logical,
641 		    loadaddr + logical, rodatasize,
642 		    PROT_READ, PTE_CACHE);
643 		logical += pmap_map_chunk(l1pagetable, KERNEL_BASE + logical,
644 		    loadaddr + logical, totalsize - (textsize + rodatasize),
645 		    PROT_READ | PROT_WRITE, PTE_CACHE);
646 	}
647 
648 #ifdef VERBOSE_INIT_ARM
649 	printf("Constructing L2 page tables\n");
650 #endif
651 
652 	/* Map the stack pages */
653 	pmap_map_chunk(l1pagetable, irqstack.pv_va, irqstack.pv_pa,
654 	    IRQ_STACK_SIZE * PAGE_SIZE, PROT_READ | PROT_WRITE, PTE_CACHE);
655 	pmap_map_chunk(l1pagetable, abtstack.pv_va, abtstack.pv_pa,
656 	    ABT_STACK_SIZE * PAGE_SIZE, PROT_READ | PROT_WRITE, PTE_CACHE);
657 	pmap_map_chunk(l1pagetable, undstack.pv_va, undstack.pv_pa,
658 	    UND_STACK_SIZE * PAGE_SIZE, PROT_READ | PROT_WRITE, PTE_CACHE);
659 	pmap_map_chunk(l1pagetable, kernelstack.pv_va, kernelstack.pv_pa,
660 	    UPAGES * PAGE_SIZE, PROT_READ | PROT_WRITE, PTE_CACHE);
661 
662 	pmap_map_chunk(l1pagetable, kernel_l1pt.pv_va, kernel_l1pt.pv_pa,
663 	    L1_TABLE_SIZE, PROT_READ | PROT_WRITE, PTE_PAGETABLE);
664 
665 	for (loop = 0; loop < NUM_KERNEL_PTS; ++loop) {
666 		pmap_map_chunk(l1pagetable, kernel_pt_table[loop].pv_va,
667 		    kernel_pt_table[loop].pv_pa, L2_TABLE_SIZE,
668 		    PROT_READ | PROT_WRITE, PTE_PAGETABLE);
669 	}
670 
671 	/* Map the Mini-Data cache clean area. */
672 
673 	/* Map the vector page. */
674 	pmap_map_entry(l1pagetable, vector_page, systempage.pv_pa,
675 	    PROT_READ | PROT_WRITE, PTE_CACHE);
676 
677 	/* Map the FDT. */
678 	pmap_map_chunk(l1pagetable, fdt.pv_va, fdt.pv_pa,
679 	    round_page(fdt_get_size((void *)fdt.pv_pa)),
680 	    PROT_READ | PROT_WRITE, PTE_CACHE);
681 
682 	/* Map the EFI memory map. */
683 	if (mmap_start != 0) {
684 		pmap_map_chunk(l1pagetable, map.pv_va, map.pv_pa,
685 		    round_page(mmap_size),
686 		    PROT_READ | PROT_WRITE, PTE_CACHE);
687 		mmap = (void *)map.pv_va;
688 	}
689 
690 	/*
691 	 * map integrated peripherals at same address in l1pagetable
692 	 * so that we can continue to use console.
693 	 */
694 	copy_io_area_map((pd_entry_t *)l1pagetable);
695 
696 	/*
697 	 * Now we have the real page tables in place so we can switch to them.
698 	 * Once this is done we will be running with the REAL kernel page
699 	 * tables.
700 	 */
701 	setttb(kernel_l1pt.pv_pa);
702 	cpu_tlb_flushID();
703 
704 	/*
705 	 * Moved from cpu_startup() as data_abort_handler() references
706 	 * this during uvm init
707 	 */
708 	proc0paddr = (struct user *)kernelstack.pv_va;
709 	proc0.p_addr = proc0paddr;
710 
711 	arm32_vector_init(vector_page, ARM_VEC_ALL);
712 
713 	/*
714 	 * Pages were allocated during the secondary bootstrap for the
715 	 * stacks for different CPU modes.
716 	 * We must now set the r13 registers in the different CPU modes to
717 	 * point to these stacks.
718 	 * Since the ARM stacks use STMFD etc. we must set r13 to the top end
719 	 * of the stack memory.
720 	 */
721 
722 	set_stackptr(PSR_IRQ32_MODE,
723 	    irqstack.pv_va + IRQ_STACK_SIZE * PAGE_SIZE);
724 	set_stackptr(PSR_ABT32_MODE,
725 	    abtstack.pv_va + ABT_STACK_SIZE * PAGE_SIZE);
726 	set_stackptr(PSR_UND32_MODE,
727 	    undstack.pv_va + UND_STACK_SIZE * PAGE_SIZE);
728 
729 	/*
730 	 * Well we should set a data abort handler.
731 	 * Once things get going this will change as we will need a proper
732 	 * handler.
733 	 * Until then we will use a handler that just panics but tells us
734 	 * why.
735 	 * Initialisation of the vectors will just panic on a data abort.
736 	 * This just fills in a slightly better one.
737 	 */
738 
739 	data_abort_handler_address = (u_int)data_abort_handler;
740 	prefetch_abort_handler_address = (u_int)prefetch_abort_handler;
741 	undefined_handler_address = (u_int)undefinedinstruction_bounce;
742 
743 	/* Now we can reinit the FDT, using the virtual address. */
744 	fdt_init((void *)fdt.pv_va);
745 
746 	/* Initialise the undefined instruction handlers */
747 #ifdef VERBOSE_INIT_ARM
748 	printf("undefined ");
749 #endif
750 	undefined_init();
751 
752 	/* Load memory into UVM. */
753 #ifdef VERBOSE_INIT_ARM
754 	printf("page ");
755 #endif
756 	uvm_setpagesize();        /* initialize PAGE_SIZE-dependent variables */
757 
758 	/* Make what's left of the initial 32MB block available to UVM. */
759 	uvm_page_physload(atop(physical_freestart), atop(memend),
760 	    atop(physical_freestart), atop(memend), 0);
761 	physmem = atop(memend - memstart);
762 
763 	/* Make all other physical memory available to UVM. */
764 	if (mmap && mmap_desc_ver == EFI_MEMORY_DESCRIPTOR_VERSION) {
765 		EFI_MEMORY_DESCRIPTOR *desc = mmap;
766 		int i;
767 
768 		/*
769 		 * Load all memory marked as EfiConventionalMemory.
770 		 * Don't bother with blocks smaller than 64KB.  The
771 		 * initial 64MB memory block should be marked as
772 		 * EfiLoaderData so it won't be added again here.
773 		 */
774 		for (i = 0; i < mmap_size / mmap_desc_size; i++) {
775 			printf("type 0x%x pa 0x%llx va 0x%llx pages 0x%llx attr 0x%llx\n",
776 			    desc->Type, desc->PhysicalStart,
777 			    desc->VirtualStart, desc->NumberOfPages,
778 			    desc->Attribute);
779 			if (desc->Type == EfiConventionalMemory &&
780 			    desc->NumberOfPages >= 16) {
781 				uvm_page_physload(atop(desc->PhysicalStart),
782 				    atop(desc->PhysicalStart) +
783 				    desc->NumberOfPages,
784 				    atop(desc->PhysicalStart),
785 				    atop(desc->PhysicalStart) +
786 				    desc->NumberOfPages, 0);
787 				physmem += desc->NumberOfPages;
788 			}
789 			desc = NextMemoryDescriptor(desc, mmap_desc_size);
790 		}
791 	} else {
792 		paddr_t start, end;
793 		int i;
794 
795 		node = fdt_find_node("/memory");
796 		if (node == NULL)
797 			panic("%s: no memory specified", __func__);
798 
799 		for (i = 0; i < VM_PHYSSEG_MAX; i++) {
800 			if (fdt_get_reg(node, i, &reg))
801 				break;
802 			if (reg.size == 0)
803 				continue;
804 
805 			start = reg.addr;
806 			end = MIN(reg.addr + reg.size, (paddr_t)-PAGE_SIZE);
807 
808 			/*
809 			 * The initial 32MB block is not excluded, so we need
810 			 * to make sure we don't add it here.
811 			 */
812 			if (start < memend && end > memstart) {
813 				if (start < memstart) {
814 					uvm_page_physload(atop(start),
815 					    atop(memstart), atop(start),
816 					    atop(memstart), 0);
817 					physmem += atop(memstart - start);
818 				}
819 				if (end > memend) {
820 					uvm_page_physload(atop(memend),
821 					    atop(end), atop(memend),
822 					    atop(end), 0);
823 					physmem += atop(end - memend);
824 				}
825 			} else {
826 				uvm_page_physload(atop(start), atop(end),
827 				    atop(start), atop(end), 0);
828 				physmem += atop(end - start);
829 			}
830 		}
831 	}
832 
833 	/* Boot strap pmap telling it where the kernel page table is */
834 #ifdef VERBOSE_INIT_ARM
835 	printf("pmap ");
836 #endif
837 	pmap_bootstrap((pd_entry_t *)kernel_l1pt.pv_va, KERNEL_VM_BASE,
838 	    KERNEL_VM_BASE + KERNEL_VM_SIZE);
839 
840 	vector_page_setprot(PROT_READ | PROT_EXEC);
841 
842 	/*
843 	 * Restore proper bus_space operation, now that pmap is initialized.
844 	 */
845 	armv7_bs_tag.bs_map = map_func_save;
846 
847 #ifdef DDB
848 	db_machine_init();
849 
850 	/* Firmware doesn't load symbols. */
851 	ddb_init();
852 
853 	if (boothowto & RB_KDB)
854 		db_enter();
855 #endif
856 
857 	cpu_setup();
858 
859 	/* We return the new stack pointer address */
860 	return(kernelstack.pv_va + USPACE_SVC_STACK_TOP);
861 }
862 
863 char	bootargs[256];
864 
865 void
866 collect_kernel_args(const char *args)
867 {
868 	/* Make a local copy of the bootargs */
869 	strlcpy(bootargs, args, sizeof(bootargs));
870 }
871 
872 void
873 process_kernel_args(void)
874 {
875 	char *cp = bootargs;
876 
877 	if (*cp == 0)
878 		return;
879 
880 	boot_file = bootargs;
881 
882 	/* Skip the kernel image filename */
883 	while (*cp != ' ' && *cp != 0)
884 		cp++;
885 
886 	if (*cp != 0)
887 		*cp++ = 0;
888 
889 	while (*cp == ' ')
890 		cp++;
891 
892 	boot_args = cp;
893 
894 	printf("bootfile: %s\n", boot_file);
895 	printf("bootargs: %s\n", boot_args);
896 
897 	/* Setup pointer to boot flags */
898 	while (*cp != '-')
899 		if (*cp++ == '\0')
900 			return;
901 
902 	while (*cp != 0) {
903 		switch(*cp) {
904 		case 'a':
905 			boothowto |= RB_ASKNAME;
906 			break;
907 		case 'c':
908 			boothowto |= RB_CONFIG;
909 			break;
910 		case 'd':
911 			boothowto |= RB_KDB;
912 			break;
913 		case 's':
914 			boothowto |= RB_SINGLE;
915 			break;
916 		default:
917 			printf("unknown option `%c'\n", *cp);
918 			break;
919 		}
920 		cp++;
921 	}
922 }
923 
924 static int
925 atoi(const char *s)
926 {
927 	int n, neg;
928 
929 	n = 0;
930 	neg = 0;
931 
932 	while (*s == '-') {
933 		s++;
934 		neg = !neg;
935 	}
936 
937 	while (*s != '\0') {
938 		if (*s < '0' || *s > '9')
939 			break;
940 
941 		n = (10 * n) + (*s - '0');
942 		s++;
943 	}
944 
945 	return (neg ? -n : n);
946 }
947 
948 void *
949 fdt_find_cons(const char *name)
950 {
951 	char *alias = "serial0";
952 	char buf[128];
953 	char *stdout = NULL;
954 	char *p;
955 	void *node;
956 
957 	/* First check if "stdout-path" is set. */
958 	node = fdt_find_node("/chosen");
959 	if (node) {
960 		if (fdt_node_property(node, "stdout-path", &stdout) > 0) {
961 			if (strchr(stdout, ':') != NULL) {
962 				strlcpy(buf, stdout, sizeof(buf));
963 				if ((p = strchr(buf, ':')) != NULL) {
964 					*p++ = '\0';
965 					stdout_speed = atoi(p);
966 				}
967 				stdout = buf;
968 			}
969 			if (stdout[0] != '/') {
970 				/* It's an alias. */
971 				alias = stdout;
972 				stdout = NULL;
973 			}
974 		}
975 	}
976 
977 	/* Perform alias lookup if necessary. */
978 	if (stdout == NULL) {
979 		node = fdt_find_node("/aliases");
980 		if (node)
981 			fdt_node_property(node, alias, &stdout);
982 	}
983 
984 	/* Lookup the physical address of the interface. */
985 	if (stdout) {
986 		node = fdt_find_node(stdout);
987 		if (node && fdt_is_compatible(node, name)) {
988 			stdout_node = OF_finddevice(stdout);
989 			return (node);
990 		}
991 	}
992 
993 	return (NULL);
994 }
995 
996 void
997 consinit(void)
998 {
999 	static int consinit_called = 0;
1000 
1001 	if (consinit_called != 0)
1002 		return;
1003 
1004 	consinit_called = 1;
1005 
1006 	platform_init_cons();
1007 }
1008 
1009 void
1010 board_startup(void)
1011 {
1012         if (boothowto & RB_CONFIG) {
1013 #ifdef BOOT_CONFIG
1014 		user_config();
1015 #else
1016 		printf("kernel does not support -c; continuing..\n");
1017 #endif
1018 	}
1019 }
1020 
1021 unsigned int
1022 cpu_rnd_messybits(void)
1023 {
1024 	struct timespec ts;
1025 
1026 	nanotime(&ts);
1027 	return (ts.tv_nsec ^ (ts.tv_sec << 20));
1028 }
1029