]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/arm/machdep.c
Make kstack_pages a tunable on arm, x86, and powepc. On i386, the
[FreeBSD/FreeBSD.git] / sys / arm / arm / machdep.c
1 /*      $NetBSD: arm32_machdep.c,v 1.44 2004/03/24 15:34:47 atatat Exp $        */
2
3 /*-
4  * Copyright (c) 2004 Olivier Houchard
5  * Copyright (c) 1994-1998 Mark Brinicombe.
6  * Copyright (c) 1994 Brini.
7  * All rights reserved.
8  *
9  * This code is derived from software written for Brini by Mark Brinicombe
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by Mark Brinicombe
22  *      for the NetBSD Project.
23  * 4. The name of the company nor the name of the author may be used to
24  *    endorse or promote products derived from this software without specific
25  *    prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
28  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
29  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30  * IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
31  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
32  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
33  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  * Machine dependant functions for kernel setup
40  *
41  * Created      : 17/09/94
42  * Updated      : 18/04/01 updated for new wscons
43  */
44
45 #include "opt_compat.h"
46 #include "opt_ddb.h"
47 #include "opt_kstack_pages.h"
48 #include "opt_platform.h"
49 #include "opt_sched.h"
50 #include "opt_timer.h"
51
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
54
55 #include <sys/param.h>
56 #include <sys/proc.h>
57 #include <sys/systm.h>
58 #include <sys/bio.h>
59 #include <sys/buf.h>
60 #include <sys/bus.h>
61 #include <sys/cons.h>
62 #include <sys/cpu.h>
63 #include <sys/efi.h>
64 #include <sys/exec.h>
65 #include <sys/imgact.h>
66 #include <sys/kdb.h>
67 #include <sys/kernel.h>
68 #include <sys/ktr.h>
69 #include <sys/linker.h>
70 #include <sys/lock.h>
71 #include <sys/malloc.h>
72 #include <sys/msgbuf.h>
73 #include <sys/mutex.h>
74 #include <sys/pcpu.h>
75 #include <sys/ptrace.h>
76 #include <sys/reboot.h>
77 #include <sys/rwlock.h>
78 #include <sys/sched.h>
79 #include <sys/signalvar.h>
80 #include <sys/syscallsubr.h>
81 #include <sys/sysctl.h>
82 #include <sys/sysent.h>
83 #include <sys/sysproto.h>
84 #include <sys/uio.h>
85
86 #include <vm/vm.h>
87 #include <vm/pmap.h>
88 #include <vm/vm_map.h>
89 #include <vm/vm_object.h>
90 #include <vm/vm_page.h>
91 #include <vm/vm_pager.h>
92
93 #include <machine/acle-compat.h>
94 #include <machine/armreg.h>
95 #include <machine/atags.h>
96 #include <machine/cpu.h>
97 #include <machine/cpuinfo.h>
98 #include <machine/devmap.h>
99 #include <machine/frame.h>
100 #include <machine/intr.h>
101 #include <machine/machdep.h>
102 #include <machine/md_var.h>
103 #include <machine/metadata.h>
104 #include <machine/pcb.h>
105 #include <machine/physmem.h>
106 #include <machine/platform.h>
107 #include <machine/reg.h>
108 #include <machine/trap.h>
109 #include <machine/undefined.h>
110 #include <machine/vfp.h>
111 #include <machine/vmparam.h>
112 #include <machine/sysarch.h>
113
114 #ifdef FDT
115 #include <dev/fdt/fdt_common.h>
116 #include <dev/ofw/openfirm.h>
117 #endif
118
119 #ifdef DDB
120 #include <ddb/ddb.h>
121
122 #if __ARM_ARCH >= 6
123 #include <machine/cpu-v6.h>
124
125 DB_SHOW_COMMAND(cp15, db_show_cp15)
126 {
127         u_int reg;
128
129         reg = cp15_midr_get();
130         db_printf("Cpu ID: 0x%08x\n", reg);
131         reg = cp15_ctr_get();
132         db_printf("Current Cache Lvl ID: 0x%08x\n",reg);
133
134         reg = cp15_sctlr_get();
135         db_printf("Ctrl: 0x%08x\n",reg);
136         reg = cp15_actlr_get();
137         db_printf("Aux Ctrl: 0x%08x\n",reg);
138
139         reg = cp15_id_pfr0_get();
140         db_printf("Processor Feat 0: 0x%08x\n", reg);
141         reg = cp15_id_pfr1_get();
142         db_printf("Processor Feat 1: 0x%08x\n", reg);
143         reg = cp15_id_dfr0_get();
144         db_printf("Debug Feat 0: 0x%08x\n", reg);
145         reg = cp15_id_afr0_get();
146         db_printf("Auxiliary Feat 0: 0x%08x\n", reg);
147         reg = cp15_id_mmfr0_get();
148         db_printf("Memory Model Feat 0: 0x%08x\n", reg);
149         reg = cp15_id_mmfr1_get();
150         db_printf("Memory Model Feat 1: 0x%08x\n", reg);
151         reg = cp15_id_mmfr2_get();
152         db_printf("Memory Model Feat 2: 0x%08x\n", reg);
153         reg = cp15_id_mmfr3_get();
154         db_printf("Memory Model Feat 3: 0x%08x\n", reg);
155         reg = cp15_ttbr_get();
156         db_printf("TTB0: 0x%08x\n", reg);
157 }
158
159 DB_SHOW_COMMAND(vtop, db_show_vtop)
160 {
161         u_int reg;
162
163         if (have_addr) {
164                 cp15_ats1cpr_set(addr);
165                 reg = cp15_par_get();
166                 db_printf("Physical address reg: 0x%08x\n",reg);
167         } else
168                 db_printf("show vtop <virt_addr>\n");
169 }
170 #endif /* __ARM_ARCH >= 6 */
171 #endif /* DDB */
172
173 #ifdef DEBUG
174 #define debugf(fmt, args...) printf(fmt, ##args)
175 #else
176 #define debugf(fmt, args...)
177 #endif
178
179 struct pcpu __pcpu[MAXCPU];
180 struct pcpu *pcpup = &__pcpu[0];
181
182 static struct trapframe proc0_tf;
183 uint32_t cpu_reset_address = 0;
184 int cold = 1;
185 vm_offset_t vector_page;
186
187 int (*_arm_memcpy)(void *, void *, int, int) = NULL;
188 int (*_arm_bzero)(void *, int, int) = NULL;
189 int _min_memcpy_size = 0;
190 int _min_bzero_size = 0;
191
192 extern int *end;
193
194 #ifdef FDT
195 vm_paddr_t pmap_pa;
196
197 #ifdef ARM_NEW_PMAP
198 vm_offset_t systempage;
199 vm_offset_t irqstack;
200 vm_offset_t undstack;
201 vm_offset_t abtstack;
202 #else
203 /*
204  * This is the number of L2 page tables required for covering max
205  * (hypothetical) memsize of 4GB and all kernel mappings (vectors, msgbuf,
206  * stacks etc.), uprounded to be divisible by 4.
207  */
208 #define KERNEL_PT_MAX   78
209
210 static struct pv_addr kernel_pt_table[KERNEL_PT_MAX];
211
212 struct pv_addr systempage;
213 static struct pv_addr msgbufpv;
214 struct pv_addr irqstack;
215 struct pv_addr undstack;
216 struct pv_addr abtstack;
217 static struct pv_addr kernelstack;
218 #endif
219 #endif
220
221 #if defined(LINUX_BOOT_ABI)
222 #define LBABI_MAX_BANKS 10
223
224 uint32_t board_id;
225 struct arm_lbabi_tag *atag_list;
226 char linux_command_line[LBABI_MAX_COMMAND_LINE + 1];
227 char atags[LBABI_MAX_COMMAND_LINE * 2];
228 uint32_t memstart[LBABI_MAX_BANKS];
229 uint32_t memsize[LBABI_MAX_BANKS];
230 uint32_t membanks;
231 #endif
232
233 static uint32_t board_revision;
234 /* hex representation of uint64_t */
235 static char board_serial[32];
236
237 SYSCTL_NODE(_hw, OID_AUTO, board, CTLFLAG_RD, 0, "Board attributes");
238 SYSCTL_UINT(_hw_board, OID_AUTO, revision, CTLFLAG_RD,
239     &board_revision, 0, "Board revision");
240 SYSCTL_STRING(_hw_board, OID_AUTO, serial, CTLFLAG_RD,
241     board_serial, 0, "Board serial");
242
243 int vfp_exists;
244 SYSCTL_INT(_hw, HW_FLOATINGPT, floatingpoint, CTLFLAG_RD,
245     &vfp_exists, 0, "Floating point support enabled");
246
247 void
248 board_set_serial(uint64_t serial)
249 {
250
251         snprintf(board_serial, sizeof(board_serial)-1,
252                     "%016jx", serial);
253 }
254
255 void
256 board_set_revision(uint32_t revision)
257 {
258
259         board_revision = revision;
260 }
261
262 void
263 sendsig(catcher, ksi, mask)
264         sig_t catcher;
265         ksiginfo_t *ksi;
266         sigset_t *mask;
267 {
268         struct thread *td;
269         struct proc *p;
270         struct trapframe *tf;
271         struct sigframe *fp, frame;
272         struct sigacts *psp;
273         int onstack;
274         int sig;
275         int code;
276
277         td = curthread;
278         p = td->td_proc;
279         PROC_LOCK_ASSERT(p, MA_OWNED);
280         sig = ksi->ksi_signo;
281         code = ksi->ksi_code;
282         psp = p->p_sigacts;
283         mtx_assert(&psp->ps_mtx, MA_OWNED);
284         tf = td->td_frame;
285         onstack = sigonstack(tf->tf_usr_sp);
286
287         CTR4(KTR_SIG, "sendsig: td=%p (%s) catcher=%p sig=%d", td, p->p_comm,
288             catcher, sig);
289
290         /* Allocate and validate space for the signal handler context. */
291         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !(onstack) &&
292             SIGISMEMBER(psp->ps_sigonstack, sig)) {
293                 fp = (struct sigframe *)(td->td_sigstk.ss_sp +
294                     td->td_sigstk.ss_size);
295 #if defined(COMPAT_43)
296                 td->td_sigstk.ss_flags |= SS_ONSTACK;
297 #endif
298         } else
299                 fp = (struct sigframe *)td->td_frame->tf_usr_sp;
300
301         /* make room on the stack */
302         fp--;
303
304         /* make the stack aligned */
305         fp = (struct sigframe *)STACKALIGN(fp);
306         /* Populate the siginfo frame. */
307         get_mcontext(td, &frame.sf_uc.uc_mcontext, 0);
308         frame.sf_si = ksi->ksi_info;
309         frame.sf_uc.uc_sigmask = *mask;
310         frame.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK )
311             ? ((onstack) ? SS_ONSTACK : 0) : SS_DISABLE;
312         frame.sf_uc.uc_stack = td->td_sigstk;
313         mtx_unlock(&psp->ps_mtx);
314         PROC_UNLOCK(td->td_proc);
315
316         /* Copy the sigframe out to the user's stack. */
317         if (copyout(&frame, fp, sizeof(*fp)) != 0) {
318                 /* Process has trashed its stack. Kill it. */
319                 CTR2(KTR_SIG, "sendsig: sigexit td=%p fp=%p", td, fp);
320                 PROC_LOCK(p);
321                 sigexit(td, SIGILL);
322         }
323
324         /*
325          * Build context to run handler in.  We invoke the handler
326          * directly, only returning via the trampoline.  Note the
327          * trampoline version numbers are coordinated with machine-
328          * dependent code in libc.
329          */
330
331         tf->tf_r0 = sig;
332         tf->tf_r1 = (register_t)&fp->sf_si;
333         tf->tf_r2 = (register_t)&fp->sf_uc;
334
335         /* the trampoline uses r5 as the uc address */
336         tf->tf_r5 = (register_t)&fp->sf_uc;
337         tf->tf_pc = (register_t)catcher;
338         tf->tf_usr_sp = (register_t)fp;
339         tf->tf_usr_lr = (register_t)(PS_STRINGS - *(p->p_sysent->sv_szsigcode));
340         /* Set the mode to enter in the signal handler */
341 #if __ARM_ARCH >= 7
342         if ((register_t)catcher & 1)
343                 tf->tf_spsr |= PSR_T;
344         else
345                 tf->tf_spsr &= ~PSR_T;
346 #endif
347
348         CTR3(KTR_SIG, "sendsig: return td=%p pc=%#x sp=%#x", td, tf->tf_usr_lr,
349             tf->tf_usr_sp);
350
351         PROC_LOCK(p);
352         mtx_lock(&psp->ps_mtx);
353 }
354
355 struct kva_md_info kmi;
356
357 /*
358  * arm32_vector_init:
359  *
360  *      Initialize the vector page, and select whether or not to
361  *      relocate the vectors.
362  *
363  *      NOTE: We expect the vector page to be mapped at its expected
364  *      destination.
365  */
366
367 extern unsigned int page0[], page0_data[];
368 void
369 arm_vector_init(vm_offset_t va, int which)
370 {
371         unsigned int *vectors = (int *) va;
372         unsigned int *vectors_data = vectors + (page0_data - page0);
373         int vec;
374
375         /*
376          * Loop through the vectors we're taking over, and copy the
377          * vector's insn and data word.
378          */
379         for (vec = 0; vec < ARM_NVEC; vec++) {
380                 if ((which & (1 << vec)) == 0) {
381                         /* Don't want to take over this vector. */
382                         continue;
383                 }
384                 vectors[vec] = page0[vec];
385                 vectors_data[vec] = page0_data[vec];
386         }
387
388         /* Now sync the vectors. */
389         cpu_icache_sync_range(va, (ARM_NVEC * 2) * sizeof(u_int));
390
391         vector_page = va;
392
393         if (va == ARM_VECTORS_HIGH) {
394                 /*
395                  * Assume the MD caller knows what it's doing here, and
396                  * really does want the vector page relocated.
397                  *
398                  * Note: This has to be done here (and not just in
399                  * cpu_setup()) because the vector page needs to be
400                  * accessible *before* cpu_startup() is called.
401                  * Think ddb(9) ...
402                  *
403                  * NOTE: If the CPU control register is not readable,
404                  * this will totally fail!  We'll just assume that
405                  * any system that has high vector support has a
406                  * readable CPU control register, for now.  If we
407                  * ever encounter one that does not, we'll have to
408                  * rethink this.
409                  */
410                 cpu_control(CPU_CONTROL_VECRELOC, CPU_CONTROL_VECRELOC);
411         }
412 }
413
414 static void
415 cpu_startup(void *dummy)
416 {
417         struct pcb *pcb = thread0.td_pcb;
418         const unsigned int mbyte = 1024 * 1024;
419 #ifdef ARM_TP_ADDRESS
420 #ifndef ARM_CACHE_LOCK_ENABLE
421         vm_page_t m;
422 #endif
423 #endif
424
425         identify_arm_cpu();
426
427         vm_ksubmap_init(&kmi);
428
429         /*
430          * Display the RAM layout.
431          */
432         printf("real memory  = %ju (%ju MB)\n",
433             (uintmax_t)arm32_ptob(realmem),
434             (uintmax_t)arm32_ptob(realmem) / mbyte);
435         printf("avail memory = %ju (%ju MB)\n",
436             (uintmax_t)arm32_ptob(vm_cnt.v_free_count),
437             (uintmax_t)arm32_ptob(vm_cnt.v_free_count) / mbyte);
438         if (bootverbose) {
439                 arm_physmem_print_tables();
440                 arm_devmap_print_table();
441         }
442
443         bufinit();
444         vm_pager_bufferinit();
445         pcb->pcb_regs.sf_sp = (u_int)thread0.td_kstack +
446             USPACE_SVC_STACK_TOP;
447         pmap_set_pcb_pagedir(pmap_kernel(), pcb);
448 #ifndef ARM_NEW_PMAP
449         vector_page_setprot(VM_PROT_READ);
450         pmap_postinit();
451 #endif
452 #ifdef ARM_TP_ADDRESS
453 #ifdef ARM_CACHE_LOCK_ENABLE
454         pmap_kenter_user(ARM_TP_ADDRESS, ARM_TP_ADDRESS);
455         arm_lock_cache_line(ARM_TP_ADDRESS);
456 #else
457         m = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ | VM_ALLOC_ZERO);
458         pmap_kenter_user(ARM_TP_ADDRESS, VM_PAGE_TO_PHYS(m));
459 #endif
460         *(uint32_t *)ARM_RAS_START = 0;
461         *(uint32_t *)ARM_RAS_END = 0xffffffff;
462 #endif
463 }
464
465 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
466
467 /*
468  * Flush the D-cache for non-DMA I/O so that the I-cache can
469  * be made coherent later.
470  */
471 void
472 cpu_flush_dcache(void *ptr, size_t len)
473 {
474
475         cpu_dcache_wb_range((uintptr_t)ptr, len);
476 #ifdef ARM_L2_PIPT
477         cpu_l2cache_wb_range((uintptr_t)vtophys(ptr), len);
478 #else
479         cpu_l2cache_wb_range((uintptr_t)ptr, len);
480 #endif
481 }
482
483 /* Get current clock frequency for the given cpu id. */
484 int
485 cpu_est_clockrate(int cpu_id, uint64_t *rate)
486 {
487
488         return (ENXIO);
489 }
490
491 void
492 cpu_idle(int busy)
493 {
494
495         CTR2(KTR_SPARE2, "cpu_idle(%d) at %d", busy, curcpu);
496         spinlock_enter();
497 #ifndef NO_EVENTTIMERS
498         if (!busy)
499                 cpu_idleclock();
500 #endif
501         if (!sched_runnable())
502                 cpu_sleep(0);
503 #ifndef NO_EVENTTIMERS
504         if (!busy)
505                 cpu_activeclock();
506 #endif
507         spinlock_exit();
508         CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done", busy, curcpu);
509 }
510
511 int
512 cpu_idle_wakeup(int cpu)
513 {
514
515         return (0);
516 }
517
518 /*
519  * Most ARM platforms don't need to do anything special to init their clocks
520  * (they get intialized during normal device attachment), and by not defining a
521  * cpu_initclocks() function they get this generic one.  Any platform that needs
522  * to do something special can just provide their own implementation, which will
523  * override this one due to the weak linkage.
524  */
525 void
526 arm_generic_initclocks(void)
527 {
528
529 #ifndef NO_EVENTTIMERS
530 #ifdef SMP
531         if (PCPU_GET(cpuid) == 0)
532                 cpu_initclocks_bsp();
533         else
534                 cpu_initclocks_ap();
535 #else
536         cpu_initclocks_bsp();
537 #endif
538 #endif
539 }
540 __weak_reference(arm_generic_initclocks, cpu_initclocks);
541
542 int
543 fill_regs(struct thread *td, struct reg *regs)
544 {
545         struct trapframe *tf = td->td_frame;
546         bcopy(&tf->tf_r0, regs->r, sizeof(regs->r));
547         regs->r_sp = tf->tf_usr_sp;
548         regs->r_lr = tf->tf_usr_lr;
549         regs->r_pc = tf->tf_pc;
550         regs->r_cpsr = tf->tf_spsr;
551         return (0);
552 }
553 int
554 fill_fpregs(struct thread *td, struct fpreg *regs)
555 {
556         bzero(regs, sizeof(*regs));
557         return (0);
558 }
559
560 int
561 set_regs(struct thread *td, struct reg *regs)
562 {
563         struct trapframe *tf = td->td_frame;
564
565         bcopy(regs->r, &tf->tf_r0, sizeof(regs->r));
566         tf->tf_usr_sp = regs->r_sp;
567         tf->tf_usr_lr = regs->r_lr;
568         tf->tf_pc = regs->r_pc;
569         tf->tf_spsr &=  ~PSR_FLAGS;
570         tf->tf_spsr |= regs->r_cpsr & PSR_FLAGS;
571         return (0);
572 }
573
574 int
575 set_fpregs(struct thread *td, struct fpreg *regs)
576 {
577         return (0);
578 }
579
580 int
581 fill_dbregs(struct thread *td, struct dbreg *regs)
582 {
583         return (0);
584 }
585 int
586 set_dbregs(struct thread *td, struct dbreg *regs)
587 {
588         return (0);
589 }
590
591
592 static int
593 ptrace_read_int(struct thread *td, vm_offset_t addr, u_int32_t *v)
594 {
595         struct iovec iov;
596         struct uio uio;
597
598         PROC_LOCK_ASSERT(td->td_proc, MA_NOTOWNED);
599         iov.iov_base = (caddr_t) v;
600         iov.iov_len = sizeof(u_int32_t);
601         uio.uio_iov = &iov;
602         uio.uio_iovcnt = 1;
603         uio.uio_offset = (off_t)addr;
604         uio.uio_resid = sizeof(u_int32_t);
605         uio.uio_segflg = UIO_SYSSPACE;
606         uio.uio_rw = UIO_READ;
607         uio.uio_td = td;
608         return proc_rwmem(td->td_proc, &uio);
609 }
610
611 static int
612 ptrace_write_int(struct thread *td, vm_offset_t addr, u_int32_t v)
613 {
614         struct iovec iov;
615         struct uio uio;
616
617         PROC_LOCK_ASSERT(td->td_proc, MA_NOTOWNED);
618         iov.iov_base = (caddr_t) &v;
619         iov.iov_len = sizeof(u_int32_t);
620         uio.uio_iov = &iov;
621         uio.uio_iovcnt = 1;
622         uio.uio_offset = (off_t)addr;
623         uio.uio_resid = sizeof(u_int32_t);
624         uio.uio_segflg = UIO_SYSSPACE;
625         uio.uio_rw = UIO_WRITE;
626         uio.uio_td = td;
627         return proc_rwmem(td->td_proc, &uio);
628 }
629
630 int
631 ptrace_single_step(struct thread *td)
632 {
633         struct proc *p;
634         int error;
635
636         /* TODO: This needs to be updated for Thumb-2 */
637         if ((td->td_frame->tf_spsr & PSR_T) != 0)
638                 return (EINVAL);
639
640         KASSERT(td->td_md.md_ptrace_instr == 0,
641          ("Didn't clear single step"));
642         p = td->td_proc;
643         PROC_UNLOCK(p);
644         error = ptrace_read_int(td, td->td_frame->tf_pc + 4,
645             &td->td_md.md_ptrace_instr);
646         if (error)
647                 goto out;
648         error = ptrace_write_int(td, td->td_frame->tf_pc + 4,
649             PTRACE_BREAKPOINT);
650         if (error)
651                 td->td_md.md_ptrace_instr = 0;
652         td->td_md.md_ptrace_addr = td->td_frame->tf_pc + 4;
653 out:
654         PROC_LOCK(p);
655         return (error);
656 }
657
658 int
659 ptrace_clear_single_step(struct thread *td)
660 {
661         struct proc *p;
662
663         /* TODO: This needs to be updated for Thumb-2 */
664         if ((td->td_frame->tf_spsr & PSR_T) != 0)
665                 return (EINVAL);
666
667         if (td->td_md.md_ptrace_instr) {
668                 p = td->td_proc;
669                 PROC_UNLOCK(p);
670                 ptrace_write_int(td, td->td_md.md_ptrace_addr,
671                     td->td_md.md_ptrace_instr);
672                 PROC_LOCK(p);
673                 td->td_md.md_ptrace_instr = 0;
674         }
675         return (0);
676 }
677
678 int
679 ptrace_set_pc(struct thread *td, unsigned long addr)
680 {
681         td->td_frame->tf_pc = addr;
682         return (0);
683 }
684
685 void
686 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
687 {
688 }
689
690 void
691 spinlock_enter(void)
692 {
693         struct thread *td;
694         register_t cspr;
695
696         td = curthread;
697         if (td->td_md.md_spinlock_count == 0) {
698                 cspr = disable_interrupts(PSR_I | PSR_F);
699                 td->td_md.md_spinlock_count = 1;
700                 td->td_md.md_saved_cspr = cspr;
701         } else
702                 td->td_md.md_spinlock_count++;
703         critical_enter();
704 }
705
706 void
707 spinlock_exit(void)
708 {
709         struct thread *td;
710         register_t cspr;
711
712         td = curthread;
713         critical_exit();
714         cspr = td->td_md.md_saved_cspr;
715         td->td_md.md_spinlock_count--;
716         if (td->td_md.md_spinlock_count == 0)
717                 restore_interrupts(cspr);
718 }
719
720 /*
721  * Clear registers on exec
722  */
723 void
724 exec_setregs(struct thread *td, struct image_params *imgp, u_long stack)
725 {
726         struct trapframe *tf = td->td_frame;
727
728         memset(tf, 0, sizeof(*tf));
729         tf->tf_usr_sp = stack;
730         tf->tf_usr_lr = imgp->entry_addr;
731         tf->tf_svc_lr = 0x77777777;
732         tf->tf_pc = imgp->entry_addr;
733         tf->tf_spsr = PSR_USR32_MODE;
734 }
735
736 /*
737  * Get machine context.
738  */
739 int
740 get_mcontext(struct thread *td, mcontext_t *mcp, int clear_ret)
741 {
742         struct trapframe *tf = td->td_frame;
743         __greg_t *gr = mcp->__gregs;
744
745         if (clear_ret & GET_MC_CLEAR_RET) {
746                 gr[_REG_R0] = 0;
747                 gr[_REG_CPSR] = tf->tf_spsr & ~PSR_C;
748         } else {
749                 gr[_REG_R0]   = tf->tf_r0;
750                 gr[_REG_CPSR] = tf->tf_spsr;
751         }
752         gr[_REG_R1]   = tf->tf_r1;
753         gr[_REG_R2]   = tf->tf_r2;
754         gr[_REG_R3]   = tf->tf_r3;
755         gr[_REG_R4]   = tf->tf_r4;
756         gr[_REG_R5]   = tf->tf_r5;
757         gr[_REG_R6]   = tf->tf_r6;
758         gr[_REG_R7]   = tf->tf_r7;
759         gr[_REG_R8]   = tf->tf_r8;
760         gr[_REG_R9]   = tf->tf_r9;
761         gr[_REG_R10]  = tf->tf_r10;
762         gr[_REG_R11]  = tf->tf_r11;
763         gr[_REG_R12]  = tf->tf_r12;
764         gr[_REG_SP]   = tf->tf_usr_sp;
765         gr[_REG_LR]   = tf->tf_usr_lr;
766         gr[_REG_PC]   = tf->tf_pc;
767
768         return (0);
769 }
770
771 /*
772  * Set machine context.
773  *
774  * However, we don't set any but the user modifiable flags, and we won't
775  * touch the cs selector.
776  */
777 int
778 set_mcontext(struct thread *td, mcontext_t *mcp)
779 {
780         struct trapframe *tf = td->td_frame;
781         const __greg_t *gr = mcp->__gregs;
782
783         tf->tf_r0 = gr[_REG_R0];
784         tf->tf_r1 = gr[_REG_R1];
785         tf->tf_r2 = gr[_REG_R2];
786         tf->tf_r3 = gr[_REG_R3];
787         tf->tf_r4 = gr[_REG_R4];
788         tf->tf_r5 = gr[_REG_R5];
789         tf->tf_r6 = gr[_REG_R6];
790         tf->tf_r7 = gr[_REG_R7];
791         tf->tf_r8 = gr[_REG_R8];
792         tf->tf_r9 = gr[_REG_R9];
793         tf->tf_r10 = gr[_REG_R10];
794         tf->tf_r11 = gr[_REG_R11];
795         tf->tf_r12 = gr[_REG_R12];
796         tf->tf_usr_sp = gr[_REG_SP];
797         tf->tf_usr_lr = gr[_REG_LR];
798         tf->tf_pc = gr[_REG_PC];
799         tf->tf_spsr = gr[_REG_CPSR];
800
801         return (0);
802 }
803
804 /*
805  * MPSAFE
806  */
807 int
808 sys_sigreturn(td, uap)
809         struct thread *td;
810         struct sigreturn_args /* {
811                 const struct __ucontext *sigcntxp;
812         } */ *uap;
813 {
814         ucontext_t uc;
815         int spsr;
816
817         if (uap == NULL)
818                 return (EFAULT);
819         if (copyin(uap->sigcntxp, &uc, sizeof(uc)))
820                 return (EFAULT);
821         /*
822          * Make sure the processor mode has not been tampered with and
823          * interrupts have not been disabled.
824          */
825         spsr = uc.uc_mcontext.__gregs[_REG_CPSR];
826         if ((spsr & PSR_MODE) != PSR_USR32_MODE ||
827             (spsr & (PSR_I | PSR_F)) != 0)
828                 return (EINVAL);
829                 /* Restore register context. */
830         set_mcontext(td, &uc.uc_mcontext);
831
832         /* Restore signal mask. */
833         kern_sigprocmask(td, SIG_SETMASK, &uc.uc_sigmask, NULL, 0);
834
835         return (EJUSTRETURN);
836 }
837
838
839 /*
840  * Construct a PCB from a trapframe. This is called from kdb_trap() where
841  * we want to start a backtrace from the function that caused us to enter
842  * the debugger. We have the context in the trapframe, but base the trace
843  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
844  * enough for a backtrace.
845  */
846 void
847 makectx(struct trapframe *tf, struct pcb *pcb)
848 {
849         pcb->pcb_regs.sf_r4 = tf->tf_r4;
850         pcb->pcb_regs.sf_r5 = tf->tf_r5;
851         pcb->pcb_regs.sf_r6 = tf->tf_r6;
852         pcb->pcb_regs.sf_r7 = tf->tf_r7;
853         pcb->pcb_regs.sf_r8 = tf->tf_r8;
854         pcb->pcb_regs.sf_r9 = tf->tf_r9;
855         pcb->pcb_regs.sf_r10 = tf->tf_r10;
856         pcb->pcb_regs.sf_r11 = tf->tf_r11;
857         pcb->pcb_regs.sf_r12 = tf->tf_r12;
858         pcb->pcb_regs.sf_pc = tf->tf_pc;
859         pcb->pcb_regs.sf_lr = tf->tf_usr_lr;
860         pcb->pcb_regs.sf_sp = tf->tf_usr_sp;
861 }
862
863 /*
864  * Fake up a boot descriptor table
865  */
866 vm_offset_t
867 fake_preload_metadata(struct arm_boot_params *abp __unused)
868 {
869 #ifdef DDB
870         vm_offset_t zstart = 0, zend = 0;
871 #endif
872         vm_offset_t lastaddr;
873         int i = 0;
874         static uint32_t fake_preload[35];
875
876         fake_preload[i++] = MODINFO_NAME;
877         fake_preload[i++] = strlen("kernel") + 1;
878         strcpy((char*)&fake_preload[i++], "kernel");
879         i += 1;
880         fake_preload[i++] = MODINFO_TYPE;
881         fake_preload[i++] = strlen("elf kernel") + 1;
882         strcpy((char*)&fake_preload[i++], "elf kernel");
883         i += 2;
884         fake_preload[i++] = MODINFO_ADDR;
885         fake_preload[i++] = sizeof(vm_offset_t);
886         fake_preload[i++] = KERNVIRTADDR;
887         fake_preload[i++] = MODINFO_SIZE;
888         fake_preload[i++] = sizeof(uint32_t);
889         fake_preload[i++] = (uint32_t)&end - KERNVIRTADDR;
890 #ifdef DDB
891         if (*(uint32_t *)KERNVIRTADDR == MAGIC_TRAMP_NUMBER) {
892                 fake_preload[i++] = MODINFO_METADATA|MODINFOMD_SSYM;
893                 fake_preload[i++] = sizeof(vm_offset_t);
894                 fake_preload[i++] = *(uint32_t *)(KERNVIRTADDR + 4);
895                 fake_preload[i++] = MODINFO_METADATA|MODINFOMD_ESYM;
896                 fake_preload[i++] = sizeof(vm_offset_t);
897                 fake_preload[i++] = *(uint32_t *)(KERNVIRTADDR + 8);
898                 lastaddr = *(uint32_t *)(KERNVIRTADDR + 8);
899                 zend = lastaddr;
900                 zstart = *(uint32_t *)(KERNVIRTADDR + 4);
901                 db_fetch_ksymtab(zstart, zend);
902         } else
903 #endif
904                 lastaddr = (vm_offset_t)&end;
905         fake_preload[i++] = 0;
906         fake_preload[i] = 0;
907         preload_metadata = (void *)fake_preload;
908
909         return (lastaddr);
910 }
911
912 void
913 pcpu0_init(void)
914 {
915 #if __ARM_ARCH >= 6
916         set_curthread(&thread0);
917 #endif
918         pcpu_init(pcpup, 0, sizeof(struct pcpu));
919         PCPU_SET(curthread, &thread0);
920 }
921
922 #if defined(LINUX_BOOT_ABI)
923 vm_offset_t
924 linux_parse_boot_param(struct arm_boot_params *abp)
925 {
926         struct arm_lbabi_tag *walker;
927         uint32_t revision;
928         uint64_t serial;
929
930         /*
931          * Linux boot ABI: r0 = 0, r1 is the board type (!= 0) and r2
932          * is atags or dtb pointer.  If all of these aren't satisfied,
933          * then punt.
934          */
935         if (!(abp->abp_r0 == 0 && abp->abp_r1 != 0 && abp->abp_r2 != 0))
936                 return 0;
937
938         board_id = abp->abp_r1;
939         walker = (struct arm_lbabi_tag *)
940             (abp->abp_r2 + KERNVIRTADDR - abp->abp_physaddr);
941
942         /* xxx - Need to also look for binary device tree */
943         if (ATAG_TAG(walker) != ATAG_CORE)
944                 return 0;
945
946         atag_list = walker;
947         while (ATAG_TAG(walker) != ATAG_NONE) {
948                 switch (ATAG_TAG(walker)) {
949                 case ATAG_CORE:
950                         break;
951                 case ATAG_MEM:
952                         arm_physmem_hardware_region(walker->u.tag_mem.start,
953                             walker->u.tag_mem.size);
954                         break;
955                 case ATAG_INITRD2:
956                         break;
957                 case ATAG_SERIAL:
958                         serial = walker->u.tag_sn.low |
959                             ((uint64_t)walker->u.tag_sn.high << 32);
960                         board_set_serial(serial);
961                         break;
962                 case ATAG_REVISION:
963                         revision = walker->u.tag_rev.rev;
964                         board_set_revision(revision);
965                         break;
966                 case ATAG_CMDLINE:
967                         /* XXX open question: Parse this for boothowto? */
968                         bcopy(walker->u.tag_cmd.command, linux_command_line,
969                               ATAG_SIZE(walker));
970                         break;
971                 default:
972                         break;
973                 }
974                 walker = ATAG_NEXT(walker);
975         }
976
977         /* Save a copy for later */
978         bcopy(atag_list, atags,
979             (char *)walker - (char *)atag_list + ATAG_SIZE(walker));
980
981         return fake_preload_metadata(abp);
982 }
983 #endif
984
985 #if defined(FREEBSD_BOOT_LOADER)
986 vm_offset_t
987 freebsd_parse_boot_param(struct arm_boot_params *abp)
988 {
989         vm_offset_t lastaddr = 0;
990         void *mdp;
991         void *kmdp;
992 #ifdef DDB
993         vm_offset_t ksym_start;
994         vm_offset_t ksym_end;
995 #endif
996
997         /*
998          * Mask metadata pointer: it is supposed to be on page boundary. If
999          * the first argument (mdp) doesn't point to a valid address the
1000          * bootloader must have passed us something else than the metadata
1001          * ptr, so we give up.  Also give up if we cannot find metadta section
1002          * the loader creates that we get all this data out of.
1003          */
1004
1005         if ((mdp = (void *)(abp->abp_r0 & ~PAGE_MASK)) == NULL)
1006                 return 0;
1007         preload_metadata = mdp;
1008         kmdp = preload_search_by_type("elf kernel");
1009         if (kmdp == NULL)
1010                 return 0;
1011
1012         boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
1013         kern_envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *);
1014         lastaddr = MD_FETCH(kmdp, MODINFOMD_KERNEND, vm_offset_t);
1015 #ifdef DDB
1016         ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
1017         ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
1018         db_fetch_ksymtab(ksym_start, ksym_end);
1019 #endif
1020         return lastaddr;
1021 }
1022 #endif
1023
1024 vm_offset_t
1025 default_parse_boot_param(struct arm_boot_params *abp)
1026 {
1027         vm_offset_t lastaddr;
1028
1029 #if defined(LINUX_BOOT_ABI)
1030         if ((lastaddr = linux_parse_boot_param(abp)) != 0)
1031                 return lastaddr;
1032 #endif
1033 #if defined(FREEBSD_BOOT_LOADER)
1034         if ((lastaddr = freebsd_parse_boot_param(abp)) != 0)
1035                 return lastaddr;
1036 #endif
1037         /* Fall back to hardcoded metadata. */
1038         lastaddr = fake_preload_metadata(abp);
1039
1040         return lastaddr;
1041 }
1042
1043 /*
1044  * Stub version of the boot parameter parsing routine.  We are
1045  * called early in initarm, before even VM has been initialized.
1046  * This routine needs to preserve any data that the boot loader
1047  * has passed in before the kernel starts to grow past the end
1048  * of the BSS, traditionally the place boot-loaders put this data.
1049  *
1050  * Since this is called so early, things that depend on the vm system
1051  * being setup (including access to some SoC's serial ports), about
1052  * all that can be done in this routine is to copy the arguments.
1053  *
1054  * This is the default boot parameter parsing routine.  Individual
1055  * kernels/boards can override this weak function with one of their
1056  * own.  We just fake metadata...
1057  */
1058 __weak_reference(default_parse_boot_param, parse_boot_param);
1059
1060 /*
1061  * Initialize proc0
1062  */
1063 void
1064 init_proc0(vm_offset_t kstack)
1065 {
1066         proc_linkup0(&proc0, &thread0);
1067         thread0.td_kstack = kstack;
1068         thread0.td_pcb = (struct pcb *)
1069                 (thread0.td_kstack + kstack_pages * PAGE_SIZE) - 1;
1070         thread0.td_pcb->pcb_flags = 0;
1071         thread0.td_pcb->pcb_vfpcpu = -1;
1072         thread0.td_pcb->pcb_vfpstate.fpscr = VFPSCR_DN | VFPSCR_FZ;
1073         thread0.td_frame = &proc0_tf;
1074         pcpup->pc_curpcb = thread0.td_pcb;
1075 }
1076
1077 #ifdef ARM_NEW_PMAP
1078 void
1079 set_stackptrs(int cpu)
1080 {
1081
1082         set_stackptr(PSR_IRQ32_MODE,
1083             irqstack + ((IRQ_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
1084         set_stackptr(PSR_ABT32_MODE,
1085             abtstack + ((ABT_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
1086         set_stackptr(PSR_UND32_MODE,
1087             undstack + ((UND_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
1088 }
1089 #else
1090 void
1091 set_stackptrs(int cpu)
1092 {
1093
1094         set_stackptr(PSR_IRQ32_MODE,
1095             irqstack.pv_va + ((IRQ_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
1096         set_stackptr(PSR_ABT32_MODE,
1097             abtstack.pv_va + ((ABT_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
1098         set_stackptr(PSR_UND32_MODE,
1099             undstack.pv_va + ((UND_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
1100 }
1101 #endif
1102
1103 #ifdef EFI
1104 #define efi_next_descriptor(ptr, size) \
1105         ((struct efi_md *)(((uint8_t *) ptr) + size))
1106
1107 static void
1108 add_efi_map_entries(struct efi_map_header *efihdr, struct mem_region *mr,
1109     int *mrcnt, uint32_t *memsize)
1110 {
1111         struct efi_md *map, *p;
1112         const char *type;
1113         size_t efisz, memory_size;
1114         int ndesc, i, j;
1115
1116         static const char *types[] = {
1117                 "Reserved",
1118                 "LoaderCode",
1119                 "LoaderData",
1120                 "BootServicesCode",
1121                 "BootServicesData",
1122                 "RuntimeServicesCode",
1123                 "RuntimeServicesData",
1124                 "ConventionalMemory",
1125                 "UnusableMemory",
1126                 "ACPIReclaimMemory",
1127                 "ACPIMemoryNVS",
1128                 "MemoryMappedIO",
1129                 "MemoryMappedIOPortSpace",
1130                 "PalCode"
1131         };
1132
1133         *mrcnt = 0;
1134         *memsize = 0;
1135
1136         /*
1137          * Memory map data provided by UEFI via the GetMemoryMap
1138          * Boot Services API.
1139          */
1140         efisz = roundup2(sizeof(struct efi_map_header), 0x10);
1141         map = (struct efi_md *)((uint8_t *)efihdr + efisz);
1142
1143         if (efihdr->descriptor_size == 0)
1144                 return;
1145         ndesc = efihdr->memory_size / efihdr->descriptor_size;
1146
1147         if (boothowto & RB_VERBOSE)
1148                 printf("%23s %12s %12s %8s %4s\n",
1149                     "Type", "Physical", "Virtual", "#Pages", "Attr");
1150
1151         memory_size = 0;
1152         for (i = 0, j = 0, p = map; i < ndesc; i++,
1153             p = efi_next_descriptor(p, efihdr->descriptor_size)) {
1154                 if (boothowto & RB_VERBOSE) {
1155                         if (p->md_type <= EFI_MD_TYPE_PALCODE)
1156                                 type = types[p->md_type];
1157                         else
1158                                 type = "<INVALID>";
1159                         printf("%23s %012llx %12p %08llx ", type, p->md_phys,
1160                             p->md_virt, p->md_pages);
1161                         if (p->md_attr & EFI_MD_ATTR_UC)
1162                                 printf("UC ");
1163                         if (p->md_attr & EFI_MD_ATTR_WC)
1164                                 printf("WC ");
1165                         if (p->md_attr & EFI_MD_ATTR_WT)
1166                                 printf("WT ");
1167                         if (p->md_attr & EFI_MD_ATTR_WB)
1168                                 printf("WB ");
1169                         if (p->md_attr & EFI_MD_ATTR_UCE)
1170                                 printf("UCE ");
1171                         if (p->md_attr & EFI_MD_ATTR_WP)
1172                                 printf("WP ");
1173                         if (p->md_attr & EFI_MD_ATTR_RP)
1174                                 printf("RP ");
1175                         if (p->md_attr & EFI_MD_ATTR_XP)
1176                                 printf("XP ");
1177                         if (p->md_attr & EFI_MD_ATTR_RT)
1178                                 printf("RUNTIME");
1179                         printf("\n");
1180                 }
1181
1182                 switch (p->md_type) {
1183                 case EFI_MD_TYPE_CODE:
1184                 case EFI_MD_TYPE_DATA:
1185                 case EFI_MD_TYPE_BS_CODE:
1186                 case EFI_MD_TYPE_BS_DATA:
1187                 case EFI_MD_TYPE_FREE:
1188                         /*
1189                          * We're allowed to use any entry with these types.
1190                          */
1191                         break;
1192                 default:
1193                         continue;
1194                 }
1195
1196                 j++;
1197                 if (j >= FDT_MEM_REGIONS)
1198                         break;
1199
1200                 mr[j].mr_start = p->md_phys;
1201                 mr[j].mr_size = p->md_pages * PAGE_SIZE;
1202                 memory_size += mr[j].mr_size;
1203         }
1204
1205         *mrcnt = j;
1206         *memsize = memory_size;
1207 }
1208 #endif /* EFI */
1209
1210 #ifdef FDT
1211 static char *
1212 kenv_next(char *cp)
1213 {
1214
1215         if (cp != NULL) {
1216                 while (*cp != 0)
1217                         cp++;
1218                 cp++;
1219                 if (*cp == 0)
1220                         cp = NULL;
1221         }
1222         return (cp);
1223 }
1224
1225 static void
1226 print_kenv(void)
1227 {
1228         char *cp;
1229
1230         debugf("loader passed (static) kenv:\n");
1231         if (kern_envp == NULL) {
1232                 debugf(" no env, null ptr\n");
1233                 return;
1234         }
1235         debugf(" kern_envp = 0x%08x\n", (uint32_t)kern_envp);
1236
1237         for (cp = kern_envp; cp != NULL; cp = kenv_next(cp))
1238                 debugf(" %x %s\n", (uint32_t)cp, cp);
1239 }
1240
1241 #ifndef ARM_NEW_PMAP
1242 void *
1243 initarm(struct arm_boot_params *abp)
1244 {
1245         struct mem_region mem_regions[FDT_MEM_REGIONS];
1246         struct pv_addr kernel_l1pt;
1247         struct pv_addr dpcpu;
1248         vm_offset_t dtbp, freemempos, l2_start, lastaddr;
1249         uint32_t memsize, l2size;
1250         char *env;
1251         void *kmdp;
1252         u_int l1pagetable;
1253         int i, j, err_devmap, mem_regions_sz;
1254
1255         lastaddr = parse_boot_param(abp);
1256         arm_physmem_kernaddr = abp->abp_physaddr;
1257
1258         memsize = 0;
1259
1260         cpuinfo_init();
1261         set_cpufuncs();
1262
1263         /*
1264          * Find the dtb passed in by the boot loader.
1265          */
1266         kmdp = preload_search_by_type("elf kernel");
1267         if (kmdp != NULL)
1268                 dtbp = MD_FETCH(kmdp, MODINFOMD_DTBP, vm_offset_t);
1269         else
1270                 dtbp = (vm_offset_t)NULL;
1271
1272 #if defined(FDT_DTB_STATIC)
1273         /*
1274          * In case the device tree blob was not retrieved (from metadata) try
1275          * to use the statically embedded one.
1276          */
1277         if (dtbp == (vm_offset_t)NULL)
1278                 dtbp = (vm_offset_t)&fdt_static_dtb;
1279 #endif
1280
1281         if (OF_install(OFW_FDT, 0) == FALSE)
1282                 panic("Cannot install FDT");
1283
1284         if (OF_init((void *)dtbp) != 0)
1285                 panic("OF_init failed with the found device tree");
1286
1287         /* Grab physical memory regions information from device tree. */
1288         if (fdt_get_mem_regions(mem_regions, &mem_regions_sz, &memsize) != 0)
1289                 panic("Cannot get physical memory regions");
1290         arm_physmem_hardware_regions(mem_regions, mem_regions_sz);
1291
1292         /* Grab reserved memory regions information from device tree. */
1293         if (fdt_get_reserved_regions(mem_regions, &mem_regions_sz) == 0)
1294                 arm_physmem_exclude_regions(mem_regions, mem_regions_sz,
1295                     EXFLAG_NODUMP | EXFLAG_NOALLOC);
1296
1297         /* Platform-specific initialisation */
1298         platform_probe_and_attach();
1299
1300         pcpu0_init();
1301
1302         /* Do basic tuning, hz etc */
1303         init_param1();
1304
1305         /* Calculate number of L2 tables needed for mapping vm_page_array */
1306         l2size = (memsize / PAGE_SIZE) * sizeof(struct vm_page);
1307         l2size = (l2size >> L1_S_SHIFT) + 1;
1308
1309         /*
1310          * Add one table for end of kernel map, one for stacks, msgbuf and
1311          * L1 and L2 tables map and one for vectors map.
1312          */
1313         l2size += 3;
1314
1315         /* Make it divisible by 4 */
1316         l2size = (l2size + 3) & ~3;
1317
1318         freemempos = (lastaddr + PAGE_MASK) & ~PAGE_MASK;
1319
1320         /* Define a macro to simplify memory allocation */
1321 #define valloc_pages(var, np)                                           \
1322         alloc_pages((var).pv_va, (np));                                 \
1323         (var).pv_pa = (var).pv_va + (abp->abp_physaddr - KERNVIRTADDR);
1324
1325 #define alloc_pages(var, np)                                            \
1326         (var) = freemempos;                                             \
1327         freemempos += (np * PAGE_SIZE);                                 \
1328         memset((char *)(var), 0, ((np) * PAGE_SIZE));
1329
1330         while (((freemempos - L1_TABLE_SIZE) & (L1_TABLE_SIZE - 1)) != 0)
1331                 freemempos += PAGE_SIZE;
1332         valloc_pages(kernel_l1pt, L1_TABLE_SIZE / PAGE_SIZE);
1333
1334         for (i = 0, j = 0; i < l2size; ++i) {
1335                 if (!(i % (PAGE_SIZE / L2_TABLE_SIZE_REAL))) {
1336                         valloc_pages(kernel_pt_table[i],
1337                             L2_TABLE_SIZE / PAGE_SIZE);
1338                         j = i;
1339                 } else {
1340                         kernel_pt_table[i].pv_va = kernel_pt_table[j].pv_va +
1341                             L2_TABLE_SIZE_REAL * (i - j);
1342                         kernel_pt_table[i].pv_pa =
1343                             kernel_pt_table[i].pv_va - KERNVIRTADDR +
1344                             abp->abp_physaddr;
1345
1346                 }
1347         }
1348         /*
1349          * Allocate a page for the system page mapped to 0x00000000
1350          * or 0xffff0000. This page will just contain the system vectors
1351          * and can be shared by all processes.
1352          */
1353         valloc_pages(systempage, 1);
1354
1355         /* Allocate dynamic per-cpu area. */
1356         valloc_pages(dpcpu, DPCPU_SIZE / PAGE_SIZE);
1357         dpcpu_init((void *)dpcpu.pv_va, 0);
1358
1359         /* Allocate stacks for all modes */
1360         valloc_pages(irqstack, IRQ_STACK_SIZE * MAXCPU);
1361         valloc_pages(abtstack, ABT_STACK_SIZE * MAXCPU);
1362         valloc_pages(undstack, UND_STACK_SIZE * MAXCPU);
1363         valloc_pages(kernelstack, kstack_pages * MAXCPU);
1364         valloc_pages(msgbufpv, round_page(msgbufsize) / PAGE_SIZE);
1365
1366         /*
1367          * Now we start construction of the L1 page table
1368          * We start by mapping the L2 page tables into the L1.
1369          * This means that we can replace L1 mappings later on if necessary
1370          */
1371         l1pagetable = kernel_l1pt.pv_va;
1372
1373         /*
1374          * Try to map as much as possible of kernel text and data using
1375          * 1MB section mapping and for the rest of initial kernel address
1376          * space use L2 coarse tables.
1377          *
1378          * Link L2 tables for mapping remainder of kernel (modulo 1MB)
1379          * and kernel structures
1380          */
1381         l2_start = lastaddr & ~(L1_S_OFFSET);
1382         for (i = 0 ; i < l2size - 1; i++)
1383                 pmap_link_l2pt(l1pagetable, l2_start + i * L1_S_SIZE,
1384                     &kernel_pt_table[i]);
1385
1386         pmap_curmaxkvaddr = l2_start + (l2size - 1) * L1_S_SIZE;
1387
1388         /* Map kernel code and data */
1389         pmap_map_chunk(l1pagetable, KERNVIRTADDR, abp->abp_physaddr,
1390            (((uint32_t)(lastaddr) - KERNVIRTADDR) + PAGE_MASK) & ~PAGE_MASK,
1391             VM_PROT_READ|VM_PROT_WRITE, PTE_CACHE);
1392
1393         /* Map L1 directory and allocated L2 page tables */
1394         pmap_map_chunk(l1pagetable, kernel_l1pt.pv_va, kernel_l1pt.pv_pa,
1395             L1_TABLE_SIZE, VM_PROT_READ|VM_PROT_WRITE, PTE_PAGETABLE);
1396
1397         pmap_map_chunk(l1pagetable, kernel_pt_table[0].pv_va,
1398             kernel_pt_table[0].pv_pa,
1399             L2_TABLE_SIZE_REAL * l2size,
1400             VM_PROT_READ|VM_PROT_WRITE, PTE_PAGETABLE);
1401
1402         /* Map allocated DPCPU, stacks and msgbuf */
1403         pmap_map_chunk(l1pagetable, dpcpu.pv_va, dpcpu.pv_pa,
1404             freemempos - dpcpu.pv_va,
1405             VM_PROT_READ|VM_PROT_WRITE, PTE_CACHE);
1406
1407         /* Link and map the vector page */
1408         pmap_link_l2pt(l1pagetable, ARM_VECTORS_HIGH,
1409             &kernel_pt_table[l2size - 1]);
1410         pmap_map_entry(l1pagetable, ARM_VECTORS_HIGH, systempage.pv_pa,
1411             VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE, PTE_CACHE);
1412
1413         /* Establish static device mappings. */
1414         err_devmap = platform_devmap_init();
1415         arm_devmap_bootstrap(l1pagetable, NULL);
1416         vm_max_kernel_address = platform_lastaddr();
1417
1418         cpu_domains((DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2)) | DOMAIN_CLIENT);
1419         pmap_pa = kernel_l1pt.pv_pa;
1420         setttb(kernel_l1pt.pv_pa);
1421         cpu_tlb_flushID();
1422         cpu_domains(DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2));
1423
1424         /*
1425          * Now that proper page tables are installed, call cpu_setup() to enable
1426          * instruction and data caches and other chip-specific features.
1427          */
1428         cpu_setup();
1429
1430         /*
1431          * Only after the SOC registers block is mapped we can perform device
1432          * tree fixups, as they may attempt to read parameters from hardware.
1433          */
1434         OF_interpret("perform-fixup", 0);
1435
1436         platform_gpio_init();
1437
1438         cninit();
1439
1440         debugf("initarm: console initialized\n");
1441         debugf(" arg1 kmdp = 0x%08x\n", (uint32_t)kmdp);
1442         debugf(" boothowto = 0x%08x\n", boothowto);
1443         debugf(" dtbp = 0x%08x\n", (uint32_t)dtbp);
1444         print_kenv();
1445
1446         env = kern_getenv("kernelname");
1447         if (env != NULL) {
1448                 strlcpy(kernelname, env, sizeof(kernelname));
1449                 freeenv(env);
1450         }
1451
1452         if (err_devmap != 0)
1453                 printf("WARNING: could not fully configure devmap, error=%d\n",
1454                     err_devmap);
1455
1456         platform_late_init();
1457
1458         /*
1459          * Pages were allocated during the secondary bootstrap for the
1460          * stacks for different CPU modes.
1461          * We must now set the r13 registers in the different CPU modes to
1462          * point to these stacks.
1463          * Since the ARM stacks use STMFD etc. we must set r13 to the top end
1464          * of the stack memory.
1465          */
1466         cpu_control(CPU_CONTROL_MMU_ENABLE, CPU_CONTROL_MMU_ENABLE);
1467
1468         set_stackptrs(0);
1469
1470         /*
1471          * We must now clean the cache again....
1472          * Cleaning may be done by reading new data to displace any
1473          * dirty data in the cache. This will have happened in setttb()
1474          * but since we are boot strapping the addresses used for the read
1475          * may have just been remapped and thus the cache could be out
1476          * of sync. A re-clean after the switch will cure this.
1477          * After booting there are no gross relocations of the kernel thus
1478          * this problem will not occur after initarm().
1479          */
1480         cpu_idcache_wbinv_all();
1481
1482         undefined_init();
1483
1484         init_proc0(kernelstack.pv_va);
1485
1486         arm_vector_init(ARM_VECTORS_HIGH, ARM_VEC_ALL);
1487         pmap_bootstrap(freemempos, &kernel_l1pt);
1488         msgbufp = (void *)msgbufpv.pv_va;
1489         msgbufinit(msgbufp, msgbufsize);
1490         mutex_init();
1491
1492         /*
1493          * Exclude the kernel (and all the things we allocated which immediately
1494          * follow the kernel) from the VM allocation pool but not from crash
1495          * dumps.  virtual_avail is a global variable which tracks the kva we've
1496          * "allocated" while setting up pmaps.
1497          *
1498          * Prepare the list of physical memory available to the vm subsystem.
1499          */
1500         arm_physmem_exclude_region(abp->abp_physaddr,
1501             (virtual_avail - KERNVIRTADDR), EXFLAG_NOALLOC);
1502         arm_physmem_init_kernel_globals();
1503
1504         init_param2(physmem);
1505         kdb_init();
1506
1507         return ((void *)(kernelstack.pv_va + USPACE_SVC_STACK_TOP -
1508             sizeof(struct pcb)));
1509 }
1510 #else /* !ARM_NEW_PMAP */
1511 void *
1512 initarm(struct arm_boot_params *abp)
1513 {
1514         struct mem_region mem_regions[FDT_MEM_REGIONS];
1515         vm_paddr_t lastaddr;
1516         vm_offset_t dtbp, kernelstack, dpcpu;
1517         uint32_t memsize;
1518         char *env;
1519         void *kmdp;
1520         int err_devmap, mem_regions_sz;
1521 #ifdef EFI
1522         struct efi_map_header *efihdr;
1523 #endif
1524
1525         /* get last allocated physical address */
1526         arm_physmem_kernaddr = abp->abp_physaddr;
1527         lastaddr = parse_boot_param(abp) - KERNVIRTADDR + arm_physmem_kernaddr;
1528
1529         memsize = 0;
1530         set_cpufuncs();
1531         cpuinfo_init();
1532
1533         /*
1534          * Find the dtb passed in by the boot loader.
1535          */
1536         kmdp = preload_search_by_type("elf kernel");
1537         if (kmdp != NULL)
1538                 dtbp = MD_FETCH(kmdp, MODINFOMD_DTBP, vm_offset_t);
1539         else
1540                 dtbp = (vm_offset_t)NULL;
1541 #if defined(FDT_DTB_STATIC)
1542         /*
1543          * In case the device tree blob was not retrieved (from metadata) try
1544          * to use the statically embedded one.
1545          */
1546         if (dtbp == (vm_offset_t)NULL)
1547                 dtbp = (vm_offset_t)&fdt_static_dtb;
1548 #endif
1549
1550         if (OF_install(OFW_FDT, 0) == FALSE)
1551                 panic("Cannot install FDT");
1552
1553         if (OF_init((void *)dtbp) != 0)
1554                 panic("OF_init failed with the found device tree");
1555
1556 #ifdef EFI
1557         efihdr = (struct efi_map_header *)preload_search_info(kmdp,
1558             MODINFO_METADATA | MODINFOMD_EFI_MAP);
1559         if (efihdr != NULL) {
1560                 add_efi_map_entries(efihdr, mem_regions, &mem_regions_sz,
1561                    &memsize);
1562         } else
1563 #endif
1564         {
1565                 /* Grab physical memory regions information from device tree. */
1566                 if (fdt_get_mem_regions(mem_regions, &mem_regions_sz,
1567                     &memsize) != 0)
1568                         panic("Cannot get physical memory regions");
1569         }
1570         arm_physmem_hardware_regions(mem_regions, mem_regions_sz);
1571
1572         /* Grab reserved memory regions information from device tree. */
1573         if (fdt_get_reserved_regions(mem_regions, &mem_regions_sz) == 0)
1574                 arm_physmem_exclude_regions(mem_regions, mem_regions_sz,
1575                     EXFLAG_NODUMP | EXFLAG_NOALLOC);
1576
1577         /*
1578          * Set TEX remapping registers.
1579          * Setup kernel page tables and switch to kernel L1 page table.
1580          */
1581         pmap_set_tex();
1582         pmap_bootstrap_prepare(lastaddr);
1583
1584         /*
1585          * Now that proper page tables are installed, call cpu_setup() to enable
1586          * instruction and data caches and other chip-specific features.
1587          */
1588         cpu_setup();
1589
1590         /* Platform-specific initialisation */
1591         platform_probe_and_attach();
1592         pcpu0_init();
1593
1594         /* Do basic tuning, hz etc */
1595         init_param1();
1596
1597         /*
1598          * Allocate a page for the system page mapped to 0xffff0000
1599          * This page will just contain the system vectors and can be
1600          * shared by all processes.
1601          */
1602         systempage = pmap_preboot_get_pages(1);
1603
1604         /* Map the vector page. */
1605         pmap_preboot_map_pages(systempage, ARM_VECTORS_HIGH,  1);
1606         if (virtual_end >= ARM_VECTORS_HIGH)
1607                 virtual_end = ARM_VECTORS_HIGH - 1;
1608
1609         /* Allocate dynamic per-cpu area. */
1610         dpcpu = pmap_preboot_get_vpages(DPCPU_SIZE / PAGE_SIZE);
1611         dpcpu_init((void *)dpcpu, 0);
1612
1613         /* Allocate stacks for all modes */
1614         irqstack    = pmap_preboot_get_vpages(IRQ_STACK_SIZE * MAXCPU);
1615         abtstack    = pmap_preboot_get_vpages(ABT_STACK_SIZE * MAXCPU);
1616         undstack    = pmap_preboot_get_vpages(UND_STACK_SIZE * MAXCPU );
1617         kernelstack = pmap_preboot_get_vpages(kstack_pages * MAXCPU);
1618
1619         /* Allocate message buffer. */
1620         msgbufp = (void *)pmap_preboot_get_vpages(
1621             round_page(msgbufsize) / PAGE_SIZE);
1622
1623         /*
1624          * Pages were allocated during the secondary bootstrap for the
1625          * stacks for different CPU modes.
1626          * We must now set the r13 registers in the different CPU modes to
1627          * point to these stacks.
1628          * Since the ARM stacks use STMFD etc. we must set r13 to the top end
1629          * of the stack memory.
1630          */
1631         set_stackptrs(0);
1632         mutex_init();
1633
1634         /* Establish static device mappings. */
1635         err_devmap = platform_devmap_init();
1636         arm_devmap_bootstrap(0, NULL);
1637         vm_max_kernel_address = platform_lastaddr();
1638
1639         /*
1640          * Only after the SOC registers block is mapped we can perform device
1641          * tree fixups, as they may attempt to read parameters from hardware.
1642          */
1643         OF_interpret("perform-fixup", 0);
1644         platform_gpio_init();
1645         cninit();
1646
1647         debugf("initarm: console initialized\n");
1648         debugf(" arg1 kmdp = 0x%08x\n", (uint32_t)kmdp);
1649         debugf(" boothowto = 0x%08x\n", boothowto);
1650         debugf(" dtbp = 0x%08x\n", (uint32_t)dtbp);
1651         debugf(" lastaddr1: 0x%08x\n", lastaddr);
1652         print_kenv();
1653
1654         env = kern_getenv("kernelname");
1655         if (env != NULL)
1656                 strlcpy(kernelname, env, sizeof(kernelname));
1657
1658         if (err_devmap != 0)
1659                 printf("WARNING: could not fully configure devmap, error=%d\n",
1660                     err_devmap);
1661
1662         platform_late_init();
1663
1664         /*
1665          * We must now clean the cache again....
1666          * Cleaning may be done by reading new data to displace any
1667          * dirty data in the cache. This will have happened in setttb()
1668          * but since we are boot strapping the addresses used for the read
1669          * may have just been remapped and thus the cache could be out
1670          * of sync. A re-clean after the switch will cure this.
1671          * After booting there are no gross relocations of the kernel thus
1672          * this problem will not occur after initarm().
1673          */
1674         /* Set stack for exception handlers */
1675         undefined_init();
1676         init_proc0(kernelstack);
1677         arm_vector_init(ARM_VECTORS_HIGH, ARM_VEC_ALL);
1678         enable_interrupts(PSR_A);
1679         pmap_bootstrap(0);
1680
1681         /* Exclude the kernel (and all the things we allocated which immediately
1682          * follow the kernel) from the VM allocation pool but not from crash
1683          * dumps.  virtual_avail is a global variable which tracks the kva we've
1684          * "allocated" while setting up pmaps.
1685          *
1686          * Prepare the list of physical memory available to the vm subsystem.
1687          */
1688         arm_physmem_exclude_region(abp->abp_physaddr,
1689                 pmap_preboot_get_pages(0) - abp->abp_physaddr, EXFLAG_NOALLOC);
1690         arm_physmem_init_kernel_globals();
1691
1692         init_param2(physmem);
1693         /* Init message buffer. */
1694         msgbufinit(msgbufp, msgbufsize);
1695         kdb_init();
1696         return ((void *)STACKALIGN(thread0.td_pcb));
1697
1698 }
1699
1700 #endif /* !ARM_NEW_PMAP */
1701 #endif /* FDT */