]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/arm/arm/machdep.c
MFC r258392, r258412:
[FreeBSD/stable/10.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_platform.h"
48 #include "opt_sched.h"
49 #include "opt_timer.h"
50
51 #include <sys/cdefs.h>
52 __FBSDID("$FreeBSD$");
53
54 #include <sys/param.h>
55 #include <sys/proc.h>
56 #include <sys/systm.h>
57 #include <sys/bio.h>
58 #include <sys/buf.h>
59 #include <sys/bus.h>
60 #include <sys/cons.h>
61 #include <sys/cpu.h>
62 #include <sys/exec.h>
63 #include <sys/imgact.h>
64 #include <sys/kdb.h>
65 #include <sys/kernel.h>
66 #include <sys/ktr.h>
67 #include <sys/linker.h>
68 #include <sys/lock.h>
69 #include <sys/malloc.h>
70 #include <sys/msgbuf.h>
71 #include <sys/mutex.h>
72 #include <sys/pcpu.h>
73 #include <sys/ptrace.h>
74 #include <sys/rwlock.h>
75 #include <sys/sched.h>
76 #include <sys/signalvar.h>
77 #include <sys/syscallsubr.h>
78 #include <sys/sysctl.h>
79 #include <sys/sysent.h>
80 #include <sys/sysproto.h>
81 #include <sys/uio.h>
82
83 #include <vm/vm.h>
84 #include <vm/pmap.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_object.h>
87 #include <vm/vm_page.h>
88 #include <vm/vm_pager.h>
89
90 #include <machine/armreg.h>
91 #include <machine/atags.h>
92 #include <machine/cpu.h>
93 #include <machine/devmap.h>
94 #include <machine/frame.h>
95 #include <machine/machdep.h>
96 #include <machine/md_var.h>
97 #include <machine/metadata.h>
98 #include <machine/pcb.h>
99 #include <machine/reg.h>
100 #include <machine/trap.h>
101 #include <machine/undefined.h>
102 #include <machine/vmparam.h>
103 #include <machine/sysarch.h>
104
105 #ifdef FDT
106 #include <dev/fdt/fdt_common.h>
107 #include <dev/ofw/openfirm.h>
108 #endif
109
110 #ifdef DEBUG
111 #define debugf(fmt, args...) printf(fmt, ##args)
112 #else
113 #define debugf(fmt, args...)
114 #endif
115
116 struct pcpu __pcpu[MAXCPU];
117 struct pcpu *pcpup = &__pcpu[0];
118
119 static struct trapframe proc0_tf;
120 uint32_t cpu_reset_address = 0;
121 int cold = 1;
122 vm_offset_t vector_page;
123
124 long realmem = 0;
125
126 int (*_arm_memcpy)(void *, void *, int, int) = NULL;
127 int (*_arm_bzero)(void *, int, int) = NULL;
128 int _min_memcpy_size = 0;
129 int _min_bzero_size = 0;
130
131 extern int *end;
132 #ifdef DDB
133 extern vm_offset_t ksym_start, ksym_end;
134 #endif
135
136 #ifdef FDT
137 /*
138  * This is the number of L2 page tables required for covering max
139  * (hypothetical) memsize of 4GB and all kernel mappings (vectors, msgbuf,
140  * stacks etc.), uprounded to be divisible by 4.
141  */
142 #define KERNEL_PT_MAX   78
143
144 static struct pv_addr kernel_pt_table[KERNEL_PT_MAX];
145
146 vm_paddr_t phys_avail[10];
147 vm_paddr_t dump_avail[4];
148
149 extern u_int data_abort_handler_address;
150 extern u_int prefetch_abort_handler_address;
151 extern u_int undefined_handler_address;
152
153 vm_paddr_t pmap_pa;
154
155 struct pv_addr systempage;
156 static struct pv_addr msgbufpv;
157 struct pv_addr irqstack;
158 struct pv_addr undstack;
159 struct pv_addr abtstack;
160 static struct pv_addr kernelstack;
161
162 #endif
163
164 #if defined(LINUX_BOOT_ABI)
165 #define LBABI_MAX_BANKS 10
166
167 uint32_t board_id;
168 struct arm_lbabi_tag *atag_list;
169 char linux_command_line[LBABI_MAX_COMMAND_LINE + 1];
170 char atags[LBABI_MAX_COMMAND_LINE * 2];
171 uint32_t memstart[LBABI_MAX_BANKS];
172 uint32_t memsize[LBABI_MAX_BANKS];
173 uint32_t membanks;
174 #endif
175
176 static uint32_t board_revision;
177 /* hex representation of uint64_t */
178 static char board_serial[32];
179
180 SYSCTL_NODE(_hw, OID_AUTO, board, CTLFLAG_RD, 0, "Board attributes");
181 SYSCTL_UINT(_hw_board, OID_AUTO, revision, CTLFLAG_RD,
182     &board_revision, 0, "Board revision");
183 SYSCTL_STRING(_hw_board, OID_AUTO, serial, CTLFLAG_RD,
184     board_serial, 0, "Board serial");
185
186 int vfp_exists;
187 SYSCTL_INT(_hw, HW_FLOATINGPT, floatingpoint, CTLFLAG_RD,
188     &vfp_exists, 0, "Floating point support enabled");
189
190 void
191 board_set_serial(uint64_t serial)
192 {
193
194         snprintf(board_serial, sizeof(board_serial)-1, 
195                     "%016jx", serial);
196 }
197
198 void
199 board_set_revision(uint32_t revision)
200 {
201
202         board_revision = revision;
203 }
204
205 void
206 sendsig(catcher, ksi, mask)
207         sig_t catcher;
208         ksiginfo_t *ksi;
209         sigset_t *mask;
210 {
211         struct thread *td;
212         struct proc *p;
213         struct trapframe *tf;
214         struct sigframe *fp, frame;
215         struct sigacts *psp;
216         int onstack;
217         int sig;
218         int code;
219
220         td = curthread;
221         p = td->td_proc;
222         PROC_LOCK_ASSERT(p, MA_OWNED);
223         sig = ksi->ksi_signo;
224         code = ksi->ksi_code;
225         psp = p->p_sigacts;
226         mtx_assert(&psp->ps_mtx, MA_OWNED);
227         tf = td->td_frame;
228         onstack = sigonstack(tf->tf_usr_sp);
229
230         CTR4(KTR_SIG, "sendsig: td=%p (%s) catcher=%p sig=%d", td, p->p_comm,
231             catcher, sig);
232
233         /* Allocate and validate space for the signal handler context. */
234         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !(onstack) &&
235             SIGISMEMBER(psp->ps_sigonstack, sig)) {
236                 fp = (struct sigframe *)(td->td_sigstk.ss_sp +
237                     td->td_sigstk.ss_size);
238 #if defined(COMPAT_43)
239                 td->td_sigstk.ss_flags |= SS_ONSTACK;
240 #endif
241         } else
242                 fp = (struct sigframe *)td->td_frame->tf_usr_sp;
243
244         /* make room on the stack */
245         fp--;
246         
247         /* make the stack aligned */
248         fp = (struct sigframe *)STACKALIGN(fp);
249         /* Populate the siginfo frame. */
250         get_mcontext(td, &frame.sf_uc.uc_mcontext, 0);
251         frame.sf_si = ksi->ksi_info;
252         frame.sf_uc.uc_sigmask = *mask;
253         frame.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK )
254             ? ((onstack) ? SS_ONSTACK : 0) : SS_DISABLE;
255         frame.sf_uc.uc_stack = td->td_sigstk;
256         mtx_unlock(&psp->ps_mtx);
257         PROC_UNLOCK(td->td_proc);
258
259         /* Copy the sigframe out to the user's stack. */
260         if (copyout(&frame, fp, sizeof(*fp)) != 0) {
261                 /* Process has trashed its stack. Kill it. */
262                 CTR2(KTR_SIG, "sendsig: sigexit td=%p fp=%p", td, fp);
263                 PROC_LOCK(p);
264                 sigexit(td, SIGILL);
265         }
266
267         /* Translate the signal if appropriate. */
268         if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
269                 sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
270
271         /*
272          * Build context to run handler in.  We invoke the handler
273          * directly, only returning via the trampoline.  Note the
274          * trampoline version numbers are coordinated with machine-
275          * dependent code in libc.
276          */
277         
278         tf->tf_r0 = sig;
279         tf->tf_r1 = (register_t)&fp->sf_si;
280         tf->tf_r2 = (register_t)&fp->sf_uc;
281
282         /* the trampoline uses r5 as the uc address */
283         tf->tf_r5 = (register_t)&fp->sf_uc;
284         tf->tf_pc = (register_t)catcher;
285         tf->tf_usr_sp = (register_t)fp;
286         tf->tf_usr_lr = (register_t)(PS_STRINGS - *(p->p_sysent->sv_szsigcode));
287
288         CTR3(KTR_SIG, "sendsig: return td=%p pc=%#x sp=%#x", td, tf->tf_usr_lr,
289             tf->tf_usr_sp);
290
291         PROC_LOCK(p);
292         mtx_lock(&psp->ps_mtx);
293 }
294
295 struct kva_md_info kmi;
296
297 /*
298  * arm32_vector_init:
299  *
300  *      Initialize the vector page, and select whether or not to
301  *      relocate the vectors.
302  *
303  *      NOTE: We expect the vector page to be mapped at its expected
304  *      destination.
305  */
306
307 extern unsigned int page0[], page0_data[];
308 void
309 arm_vector_init(vm_offset_t va, int which)
310 {
311         unsigned int *vectors = (int *) va;
312         unsigned int *vectors_data = vectors + (page0_data - page0);
313         int vec;
314
315         /*
316          * Loop through the vectors we're taking over, and copy the
317          * vector's insn and data word.
318          */
319         for (vec = 0; vec < ARM_NVEC; vec++) {
320                 if ((which & (1 << vec)) == 0) {
321                         /* Don't want to take over this vector. */
322                         continue;
323                 }
324                 vectors[vec] = page0[vec];
325                 vectors_data[vec] = page0_data[vec];
326         }
327
328         /* Now sync the vectors. */
329         cpu_icache_sync_range(va, (ARM_NVEC * 2) * sizeof(u_int));
330
331         vector_page = va;
332
333         if (va == ARM_VECTORS_HIGH) {
334                 /*
335                  * Assume the MD caller knows what it's doing here, and
336                  * really does want the vector page relocated.
337                  *
338                  * Note: This has to be done here (and not just in
339                  * cpu_setup()) because the vector page needs to be
340                  * accessible *before* cpu_startup() is called.
341                  * Think ddb(9) ...
342                  *
343                  * NOTE: If the CPU control register is not readable,
344                  * this will totally fail!  We'll just assume that
345                  * any system that has high vector support has a
346                  * readable CPU control register, for now.  If we
347                  * ever encounter one that does not, we'll have to
348                  * rethink this.
349                  */
350                 cpu_control(CPU_CONTROL_VECRELOC, CPU_CONTROL_VECRELOC);
351         }
352 }
353
354 static void
355 cpu_startup(void *dummy)
356 {
357         struct pcb *pcb = thread0.td_pcb;
358 #ifdef ARM_TP_ADDRESS
359 #ifndef ARM_CACHE_LOCK_ENABLE
360         vm_page_t m;
361 #endif
362 #endif
363
364         identify_arm_cpu();
365
366         printf("real memory  = %ju (%ju MB)\n", (uintmax_t)ptoa(physmem),
367             (uintmax_t)ptoa(physmem) / 1048576);
368         realmem = physmem;
369
370         /*
371          * Display the RAM layout.
372          */
373         if (bootverbose) {
374                 int indx;
375
376                 printf("Physical memory chunk(s):\n");
377                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
378                         vm_paddr_t size;
379
380                         size = phys_avail[indx + 1] - phys_avail[indx];
381                         printf("%#08jx - %#08jx, %ju bytes (%ju pages)\n",
382                             (uintmax_t)phys_avail[indx],
383                             (uintmax_t)phys_avail[indx + 1] - 1,
384                             (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
385                 }
386         }
387
388         vm_ksubmap_init(&kmi);
389
390         printf("avail memory = %ju (%ju MB)\n",
391             (uintmax_t)ptoa(cnt.v_free_count),
392             (uintmax_t)ptoa(cnt.v_free_count) / 1048576);
393
394         bufinit();
395         vm_pager_bufferinit();
396         pcb->un_32.pcb32_und_sp = (u_int)thread0.td_kstack +
397             USPACE_UNDEF_STACK_TOP;
398         pcb->un_32.pcb32_sp = (u_int)thread0.td_kstack +
399             USPACE_SVC_STACK_TOP;
400         vector_page_setprot(VM_PROT_READ);
401         pmap_set_pcb_pagedir(pmap_kernel(), pcb);
402         pmap_postinit();
403 #ifdef ARM_TP_ADDRESS
404 #ifdef ARM_CACHE_LOCK_ENABLE
405         pmap_kenter_user(ARM_TP_ADDRESS, ARM_TP_ADDRESS);
406         arm_lock_cache_line(ARM_TP_ADDRESS);
407 #else
408         m = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ | VM_ALLOC_ZERO);
409         pmap_kenter_user(ARM_TP_ADDRESS, VM_PAGE_TO_PHYS(m));
410 #endif
411         *(uint32_t *)ARM_RAS_START = 0;
412         *(uint32_t *)ARM_RAS_END = 0xffffffff;
413 #endif
414 }
415
416 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
417
418 /*
419  * Flush the D-cache for non-DMA I/O so that the I-cache can
420  * be made coherent later.
421  */
422 void
423 cpu_flush_dcache(void *ptr, size_t len)
424 {
425
426         cpu_dcache_wb_range((uintptr_t)ptr, len);
427         cpu_l2cache_wb_range((uintptr_t)ptr, len);
428 }
429
430 /* Get current clock frequency for the given cpu id. */
431 int
432 cpu_est_clockrate(int cpu_id, uint64_t *rate)
433 {
434
435         return (ENXIO);
436 }
437
438 void
439 cpu_idle(int busy)
440 {
441         
442         CTR2(KTR_SPARE2, "cpu_idle(%d) at %d",
443             busy, curcpu);
444 #ifndef NO_EVENTTIMERS
445         if (!busy) {
446                 critical_enter();
447                 cpu_idleclock();
448         }
449 #endif
450         if (!sched_runnable())
451                 cpu_sleep(0);
452 #ifndef NO_EVENTTIMERS
453         if (!busy) {
454                 cpu_activeclock();
455                 critical_exit();
456         }
457 #endif
458         CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done",
459             busy, curcpu);
460 }
461
462 int
463 cpu_idle_wakeup(int cpu)
464 {
465
466         return (0);
467 }
468
469 int
470 fill_regs(struct thread *td, struct reg *regs)
471 {
472         struct trapframe *tf = td->td_frame;
473         bcopy(&tf->tf_r0, regs->r, sizeof(regs->r));
474         regs->r_sp = tf->tf_usr_sp;
475         regs->r_lr = tf->tf_usr_lr;
476         regs->r_pc = tf->tf_pc;
477         regs->r_cpsr = tf->tf_spsr;
478         return (0);
479 }
480 int
481 fill_fpregs(struct thread *td, struct fpreg *regs)
482 {
483         bzero(regs, sizeof(*regs));
484         return (0);
485 }
486
487 int
488 set_regs(struct thread *td, struct reg *regs)
489 {
490         struct trapframe *tf = td->td_frame;
491         
492         bcopy(regs->r, &tf->tf_r0, sizeof(regs->r));
493         tf->tf_usr_sp = regs->r_sp;
494         tf->tf_usr_lr = regs->r_lr;
495         tf->tf_pc = regs->r_pc;
496         tf->tf_spsr &=  ~PSR_FLAGS;
497         tf->tf_spsr |= regs->r_cpsr & PSR_FLAGS;
498         return (0);                                                             
499 }
500
501 int
502 set_fpregs(struct thread *td, struct fpreg *regs)
503 {
504         return (0);
505 }
506
507 int
508 fill_dbregs(struct thread *td, struct dbreg *regs)
509 {
510         return (0);
511 }
512 int
513 set_dbregs(struct thread *td, struct dbreg *regs)
514 {
515         return (0);
516 }
517
518
519 static int
520 ptrace_read_int(struct thread *td, vm_offset_t addr, u_int32_t *v)
521 {
522         struct iovec iov;
523         struct uio uio;
524
525         PROC_LOCK_ASSERT(td->td_proc, MA_NOTOWNED);
526         iov.iov_base = (caddr_t) v;
527         iov.iov_len = sizeof(u_int32_t);
528         uio.uio_iov = &iov;
529         uio.uio_iovcnt = 1;
530         uio.uio_offset = (off_t)addr;
531         uio.uio_resid = sizeof(u_int32_t);
532         uio.uio_segflg = UIO_SYSSPACE;
533         uio.uio_rw = UIO_READ;
534         uio.uio_td = td;
535         return proc_rwmem(td->td_proc, &uio);
536 }
537
538 static int
539 ptrace_write_int(struct thread *td, vm_offset_t addr, u_int32_t v)
540 {
541         struct iovec iov;
542         struct uio uio;
543
544         PROC_LOCK_ASSERT(td->td_proc, MA_NOTOWNED);
545         iov.iov_base = (caddr_t) &v;
546         iov.iov_len = sizeof(u_int32_t);
547         uio.uio_iov = &iov;
548         uio.uio_iovcnt = 1;
549         uio.uio_offset = (off_t)addr;
550         uio.uio_resid = sizeof(u_int32_t);
551         uio.uio_segflg = UIO_SYSSPACE;
552         uio.uio_rw = UIO_WRITE;
553         uio.uio_td = td;
554         return proc_rwmem(td->td_proc, &uio);
555 }
556
557 int
558 ptrace_single_step(struct thread *td)
559 {
560         struct proc *p;
561         int error;
562         
563         KASSERT(td->td_md.md_ptrace_instr == 0,
564          ("Didn't clear single step"));
565         p = td->td_proc;
566         PROC_UNLOCK(p);
567         error = ptrace_read_int(td, td->td_frame->tf_pc + 4,
568             &td->td_md.md_ptrace_instr);
569         if (error)
570                 goto out;
571         error = ptrace_write_int(td, td->td_frame->tf_pc + 4,
572             PTRACE_BREAKPOINT);
573         if (error)
574                 td->td_md.md_ptrace_instr = 0;
575         td->td_md.md_ptrace_addr = td->td_frame->tf_pc + 4;
576 out:
577         PROC_LOCK(p);
578         return (error);
579 }
580
581 int
582 ptrace_clear_single_step(struct thread *td)
583 {
584         struct proc *p;
585
586         if (td->td_md.md_ptrace_instr) {
587                 p = td->td_proc;
588                 PROC_UNLOCK(p);
589                 ptrace_write_int(td, td->td_md.md_ptrace_addr,
590                     td->td_md.md_ptrace_instr);
591                 PROC_LOCK(p);
592                 td->td_md.md_ptrace_instr = 0;
593         }
594         return (0);
595 }
596
597 int
598 ptrace_set_pc(struct thread *td, unsigned long addr)
599 {
600         td->td_frame->tf_pc = addr;
601         return (0);
602 }
603
604 void
605 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
606 {
607 }
608
609 void
610 spinlock_enter(void)
611 {
612         struct thread *td;
613         register_t cspr;
614
615         td = curthread;
616         if (td->td_md.md_spinlock_count == 0) {
617                 cspr = disable_interrupts(I32_bit | F32_bit);
618                 td->td_md.md_spinlock_count = 1;
619                 td->td_md.md_saved_cspr = cspr;
620         } else
621                 td->td_md.md_spinlock_count++;
622         critical_enter();
623 }
624
625 void
626 spinlock_exit(void)
627 {
628         struct thread *td;
629         register_t cspr;
630
631         td = curthread;
632         critical_exit();
633         cspr = td->td_md.md_saved_cspr;
634         td->td_md.md_spinlock_count--;
635         if (td->td_md.md_spinlock_count == 0)
636                 restore_interrupts(cspr);
637 }
638
639 /*
640  * Clear registers on exec
641  */
642 void
643 exec_setregs(struct thread *td, struct image_params *imgp, u_long stack)
644 {
645         struct trapframe *tf = td->td_frame;
646
647         memset(tf, 0, sizeof(*tf));
648         tf->tf_usr_sp = stack;
649         tf->tf_usr_lr = imgp->entry_addr;
650         tf->tf_svc_lr = 0x77777777;
651         tf->tf_pc = imgp->entry_addr;
652         tf->tf_spsr = PSR_USR32_MODE;
653 }
654
655 /*
656  * Get machine context.
657  */
658 int
659 get_mcontext(struct thread *td, mcontext_t *mcp, int clear_ret)
660 {
661         struct trapframe *tf = td->td_frame;
662         __greg_t *gr = mcp->__gregs;
663
664         if (clear_ret & GET_MC_CLEAR_RET)
665                 gr[_REG_R0] = 0;
666         else
667                 gr[_REG_R0]   = tf->tf_r0;
668         gr[_REG_R1]   = tf->tf_r1;
669         gr[_REG_R2]   = tf->tf_r2;
670         gr[_REG_R3]   = tf->tf_r3;
671         gr[_REG_R4]   = tf->tf_r4;
672         gr[_REG_R5]   = tf->tf_r5;
673         gr[_REG_R6]   = tf->tf_r6;
674         gr[_REG_R7]   = tf->tf_r7;
675         gr[_REG_R8]   = tf->tf_r8;
676         gr[_REG_R9]   = tf->tf_r9;
677         gr[_REG_R10]  = tf->tf_r10;
678         gr[_REG_R11]  = tf->tf_r11;
679         gr[_REG_R12]  = tf->tf_r12;
680         gr[_REG_SP]   = tf->tf_usr_sp;
681         gr[_REG_LR]   = tf->tf_usr_lr;
682         gr[_REG_PC]   = tf->tf_pc;
683         gr[_REG_CPSR] = tf->tf_spsr;
684
685         return (0);
686 }
687
688 /*
689  * Set machine context.
690  *
691  * However, we don't set any but the user modifiable flags, and we won't
692  * touch the cs selector.
693  */
694 int
695 set_mcontext(struct thread *td, const mcontext_t *mcp)
696 {
697         struct trapframe *tf = td->td_frame;
698         const __greg_t *gr = mcp->__gregs;
699
700         tf->tf_r0 = gr[_REG_R0];
701         tf->tf_r1 = gr[_REG_R1];
702         tf->tf_r2 = gr[_REG_R2];
703         tf->tf_r3 = gr[_REG_R3];
704         tf->tf_r4 = gr[_REG_R4];
705         tf->tf_r5 = gr[_REG_R5];
706         tf->tf_r6 = gr[_REG_R6];
707         tf->tf_r7 = gr[_REG_R7];
708         tf->tf_r8 = gr[_REG_R8];
709         tf->tf_r9 = gr[_REG_R9];
710         tf->tf_r10 = gr[_REG_R10];
711         tf->tf_r11 = gr[_REG_R11];
712         tf->tf_r12 = gr[_REG_R12];
713         tf->tf_usr_sp = gr[_REG_SP];
714         tf->tf_usr_lr = gr[_REG_LR];
715         tf->tf_pc = gr[_REG_PC];
716         tf->tf_spsr = gr[_REG_CPSR];
717
718         return (0);
719 }
720
721 /*
722  * MPSAFE
723  */
724 int
725 sys_sigreturn(td, uap)
726         struct thread *td;
727         struct sigreturn_args /* {
728                 const struct __ucontext *sigcntxp;
729         } */ *uap;
730 {
731         struct sigframe sf;
732         struct trapframe *tf;
733         int spsr;
734         
735         if (uap == NULL)
736                 return (EFAULT);
737         if (copyin(uap->sigcntxp, &sf, sizeof(sf)))
738                 return (EFAULT);
739         /*
740          * Make sure the processor mode has not been tampered with and
741          * interrupts have not been disabled.
742          */
743         spsr = sf.sf_uc.uc_mcontext.__gregs[_REG_CPSR];
744         if ((spsr & PSR_MODE) != PSR_USR32_MODE ||
745             (spsr & (I32_bit | F32_bit)) != 0)
746                 return (EINVAL);
747                 /* Restore register context. */
748         tf = td->td_frame;
749         set_mcontext(td, &sf.sf_uc.uc_mcontext);
750
751         /* Restore signal mask. */
752         kern_sigprocmask(td, SIG_SETMASK, &sf.sf_uc.uc_sigmask, NULL, 0);
753
754         return (EJUSTRETURN);
755 }
756
757
758 /*
759  * Construct a PCB from a trapframe. This is called from kdb_trap() where
760  * we want to start a backtrace from the function that caused us to enter
761  * the debugger. We have the context in the trapframe, but base the trace
762  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
763  * enough for a backtrace.
764  */
765 void
766 makectx(struct trapframe *tf, struct pcb *pcb)
767 {
768         pcb->un_32.pcb32_r8 = tf->tf_r8;
769         pcb->un_32.pcb32_r9 = tf->tf_r9;
770         pcb->un_32.pcb32_r10 = tf->tf_r10;
771         pcb->un_32.pcb32_r11 = tf->tf_r11;
772         pcb->un_32.pcb32_r12 = tf->tf_r12;
773         pcb->un_32.pcb32_pc = tf->tf_pc;
774         pcb->un_32.pcb32_lr = tf->tf_usr_lr;
775         pcb->un_32.pcb32_sp = tf->tf_usr_sp;
776 }
777
778 /*
779  * Make a standard dump_avail array.  Can't make the phys_avail
780  * since we need to do that after we call pmap_bootstrap, but this
781  * is needed before pmap_boostrap.
782  *
783  * ARM_USE_SMALL_ALLOC uses dump_avail, so it must be filled before
784  * calling pmap_bootstrap.
785  */
786 void
787 arm_dump_avail_init(vm_offset_t ramsize, size_t max)
788 {
789 #ifdef LINUX_BOOT_ABI
790         /*
791          * Linux boot loader passes us the actual banks of memory, so use them
792          * to construct the dump_avail array.
793          */
794         if (membanks > 0) 
795         {
796                 int i, j;
797
798                 if (max < (membanks + 1) * 2)
799                         panic("dump_avail[%d] too small for %d banks\n",
800                             max, membanks);
801                 for (j = 0, i = 0; i < membanks; i++) {
802                         dump_avail[j++] = round_page(memstart[i]);
803                         dump_avail[j++] = trunc_page(memstart[i] + memsize[i]);
804                 }
805                 dump_avail[j++] = 0;
806                 dump_avail[j++] = 0;
807                 return;
808         }
809 #endif
810         if (max < 4)
811                 panic("dump_avail too small\n");
812
813         dump_avail[0] = round_page(PHYSADDR);
814         dump_avail[1] = trunc_page(PHYSADDR + ramsize);
815         dump_avail[2] = 0;
816         dump_avail[3] = 0;
817 }
818
819 /*
820  * Fake up a boot descriptor table
821  */
822 vm_offset_t
823 fake_preload_metadata(struct arm_boot_params *abp __unused)
824 {
825 #ifdef DDB
826         vm_offset_t zstart = 0, zend = 0;
827 #endif
828         vm_offset_t lastaddr;
829         int i = 0;
830         static uint32_t fake_preload[35];
831
832         fake_preload[i++] = MODINFO_NAME;
833         fake_preload[i++] = strlen("kernel") + 1;
834         strcpy((char*)&fake_preload[i++], "kernel");
835         i += 1;
836         fake_preload[i++] = MODINFO_TYPE;
837         fake_preload[i++] = strlen("elf kernel") + 1;
838         strcpy((char*)&fake_preload[i++], "elf kernel");
839         i += 2;
840         fake_preload[i++] = MODINFO_ADDR;
841         fake_preload[i++] = sizeof(vm_offset_t);
842         fake_preload[i++] = KERNVIRTADDR;
843         fake_preload[i++] = MODINFO_SIZE;
844         fake_preload[i++] = sizeof(uint32_t);
845         fake_preload[i++] = (uint32_t)&end - KERNVIRTADDR;
846 #ifdef DDB
847         if (*(uint32_t *)KERNVIRTADDR == MAGIC_TRAMP_NUMBER) {
848                 fake_preload[i++] = MODINFO_METADATA|MODINFOMD_SSYM;
849                 fake_preload[i++] = sizeof(vm_offset_t);
850                 fake_preload[i++] = *(uint32_t *)(KERNVIRTADDR + 4);
851                 fake_preload[i++] = MODINFO_METADATA|MODINFOMD_ESYM;
852                 fake_preload[i++] = sizeof(vm_offset_t);
853                 fake_preload[i++] = *(uint32_t *)(KERNVIRTADDR + 8);
854                 lastaddr = *(uint32_t *)(KERNVIRTADDR + 8);
855                 zend = lastaddr;
856                 zstart = *(uint32_t *)(KERNVIRTADDR + 4);
857                 ksym_start = zstart;
858                 ksym_end = zend;
859         } else
860 #endif
861                 lastaddr = (vm_offset_t)&end;
862         fake_preload[i++] = 0;
863         fake_preload[i] = 0;
864         preload_metadata = (void *)fake_preload;
865
866         return (lastaddr);
867 }
868
869 void
870 pcpu0_init(void)
871 {
872 #if ARM_ARCH_6 || ARM_ARCH_7A || defined(CPU_MV_PJ4B)
873         set_pcpu(pcpup);
874 #endif
875         pcpu_init(pcpup, 0, sizeof(struct pcpu));
876         PCPU_SET(curthread, &thread0);
877 #ifdef VFP
878         PCPU_SET(cpu, 0);
879 #endif
880 }
881
882 #if defined(LINUX_BOOT_ABI)
883 vm_offset_t
884 linux_parse_boot_param(struct arm_boot_params *abp)
885 {
886         struct arm_lbabi_tag *walker;
887         uint32_t revision;
888         uint64_t serial;
889
890         /*
891          * Linux boot ABI: r0 = 0, r1 is the board type (!= 0) and r2
892          * is atags or dtb pointer.  If all of these aren't satisfied,
893          * then punt.
894          */
895         if (!(abp->abp_r0 == 0 && abp->abp_r1 != 0 && abp->abp_r2 != 0))
896                 return 0;
897
898         board_id = abp->abp_r1;
899         walker = (struct arm_lbabi_tag *)
900             (abp->abp_r2 + KERNVIRTADDR - KERNPHYSADDR);
901
902         /* xxx - Need to also look for binary device tree */
903         if (ATAG_TAG(walker) != ATAG_CORE)
904                 return 0;
905
906         atag_list = walker;
907         while (ATAG_TAG(walker) != ATAG_NONE) {
908                 switch (ATAG_TAG(walker)) {
909                 case ATAG_CORE:
910                         break;
911                 case ATAG_MEM:
912                         if (membanks < LBABI_MAX_BANKS) {
913                                 memstart[membanks] = walker->u.tag_mem.start;
914                                 memsize[membanks] = walker->u.tag_mem.size;
915                         }
916                         membanks++;
917                         break;
918                 case ATAG_INITRD2:
919                         break;
920                 case ATAG_SERIAL:
921                         serial = walker->u.tag_sn.low |
922                             ((uint64_t)walker->u.tag_sn.high << 32);
923                         board_set_serial(serial);
924                         break;
925                 case ATAG_REVISION:
926                         revision = walker->u.tag_rev.rev;
927                         board_set_revision(revision);
928                         break;
929                 case ATAG_CMDLINE:
930                         /* XXX open question: Parse this for boothowto? */
931                         bcopy(walker->u.tag_cmd.command, linux_command_line,
932                               ATAG_SIZE(walker));
933                         break;
934                 default:
935                         break;
936                 }
937                 walker = ATAG_NEXT(walker);
938         }
939
940         /* Save a copy for later */
941         bcopy(atag_list, atags,
942             (char *)walker - (char *)atag_list + ATAG_SIZE(walker));
943
944         return fake_preload_metadata(abp);
945 }
946 #endif
947
948 #if defined(FREEBSD_BOOT_LOADER)
949 vm_offset_t
950 freebsd_parse_boot_param(struct arm_boot_params *abp)
951 {
952         vm_offset_t lastaddr = 0;
953         void *mdp;
954         void *kmdp;
955
956         /*
957          * Mask metadata pointer: it is supposed to be on page boundary. If
958          * the first argument (mdp) doesn't point to a valid address the
959          * bootloader must have passed us something else than the metadata
960          * ptr, so we give up.  Also give up if we cannot find metadta section
961          * the loader creates that we get all this data out of.
962          */
963
964         if ((mdp = (void *)(abp->abp_r0 & ~PAGE_MASK)) == NULL)
965                 return 0;
966         preload_metadata = mdp;
967         kmdp = preload_search_by_type("elf kernel");
968         if (kmdp == NULL)
969                 return 0;
970
971         boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
972         kern_envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *);
973         lastaddr = MD_FETCH(kmdp, MODINFOMD_KERNEND, vm_offset_t);
974 #ifdef DDB
975         ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
976         ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
977 #endif
978         preload_addr_relocate = KERNVIRTADDR - KERNPHYSADDR;
979         return lastaddr;
980 }
981 #endif
982
983 vm_offset_t
984 default_parse_boot_param(struct arm_boot_params *abp)
985 {
986         vm_offset_t lastaddr;
987
988 #if defined(LINUX_BOOT_ABI)
989         if ((lastaddr = linux_parse_boot_param(abp)) != 0)
990                 return lastaddr;
991 #endif
992 #if defined(FREEBSD_BOOT_LOADER)
993         if ((lastaddr = freebsd_parse_boot_param(abp)) != 0)
994                 return lastaddr;
995 #endif
996         /* Fall back to hardcoded metadata. */
997         lastaddr = fake_preload_metadata(abp);
998
999         return lastaddr;
1000 }
1001
1002 /*
1003  * Stub version of the boot parameter parsing routine.  We are
1004  * called early in initarm, before even VM has been initialized.
1005  * This routine needs to preserve any data that the boot loader
1006  * has passed in before the kernel starts to grow past the end
1007  * of the BSS, traditionally the place boot-loaders put this data.
1008  *
1009  * Since this is called so early, things that depend on the vm system
1010  * being setup (including access to some SoC's serial ports), about
1011  * all that can be done in this routine is to copy the arguments.
1012  *
1013  * This is the default boot parameter parsing routine.  Individual
1014  * kernels/boards can override this weak function with one of their
1015  * own.  We just fake metadata...
1016  */
1017 __weak_reference(default_parse_boot_param, parse_boot_param);
1018
1019 /*
1020  * Initialize proc0
1021  */
1022 void
1023 init_proc0(vm_offset_t kstack)
1024 {
1025         proc_linkup0(&proc0, &thread0);
1026         thread0.td_kstack = kstack;
1027         thread0.td_pcb = (struct pcb *)
1028                 (thread0.td_kstack + KSTACK_PAGES * PAGE_SIZE) - 1;
1029         thread0.td_pcb->pcb_flags = 0;
1030         thread0.td_frame = &proc0_tf;
1031         pcpup->pc_curpcb = thread0.td_pcb;
1032 }
1033
1034 void
1035 set_stackptrs(int cpu)
1036 {
1037
1038         set_stackptr(PSR_IRQ32_MODE,
1039             irqstack.pv_va + ((IRQ_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
1040         set_stackptr(PSR_ABT32_MODE,
1041             abtstack.pv_va + ((ABT_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
1042         set_stackptr(PSR_UND32_MODE,
1043             undstack.pv_va + ((UND_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
1044 }
1045
1046 #ifdef FDT
1047 static char *
1048 kenv_next(char *cp)
1049 {
1050
1051         if (cp != NULL) {
1052                 while (*cp != 0)
1053                         cp++;
1054                 cp++;
1055                 if (*cp == 0)
1056                         cp = NULL;
1057         }
1058         return (cp);
1059 }
1060
1061 static void
1062 print_kenv(void)
1063 {
1064         int len;
1065         char *cp;
1066
1067         debugf("loader passed (static) kenv:\n");
1068         if (kern_envp == NULL) {
1069                 debugf(" no env, null ptr\n");
1070                 return;
1071         }
1072         debugf(" kern_envp = 0x%08x\n", (uint32_t)kern_envp);
1073
1074         len = 0;
1075         for (cp = kern_envp; cp != NULL; cp = kenv_next(cp))
1076                 debugf(" %x %s\n", (uint32_t)cp, cp);
1077 }
1078
1079 static void
1080 physmap_init(struct mem_region *availmem_regions, int availmem_regions_sz)
1081 {
1082         int i, j, cnt;
1083         vm_offset_t phys_kernelend, kernload;
1084         uint32_t s, e, sz;
1085         struct mem_region *mp, *mp1;
1086
1087         phys_kernelend = KERNPHYSADDR + (virtual_avail - KERNVIRTADDR);
1088         kernload = KERNPHYSADDR;
1089
1090         /*
1091          * Remove kernel physical address range from avail
1092          * regions list. Page align all regions.
1093          * Non-page aligned memory isn't very interesting to us.
1094          * Also, sort the entries for ascending addresses.
1095          */
1096         sz = 0;
1097         cnt = availmem_regions_sz;
1098         debugf("processing avail regions:\n");
1099         for (mp = availmem_regions; mp->mr_size; mp++) {
1100                 s = mp->mr_start;
1101                 e = mp->mr_start + mp->mr_size;
1102                 debugf(" %08x-%08x -> ", s, e);
1103                 /* Check whether this region holds all of the kernel. */
1104                 if (s < kernload && e > phys_kernelend) {
1105                         availmem_regions[cnt].mr_start = phys_kernelend;
1106                         availmem_regions[cnt++].mr_size = e - phys_kernelend;
1107                         e = kernload;
1108                 }
1109                 /* Look whether this regions starts within the kernel. */
1110                 if (s >= kernload && s < phys_kernelend) {
1111                         if (e <= phys_kernelend)
1112                                 goto empty;
1113                         s = phys_kernelend;
1114                 }
1115                 /* Now look whether this region ends within the kernel. */
1116                 if (e > kernload && e <= phys_kernelend) {
1117                         if (s >= kernload) {
1118                                 goto empty;
1119                         }
1120                         e = kernload;
1121                 }
1122                 /* Now page align the start and size of the region. */
1123                 s = round_page(s);
1124                 e = trunc_page(e);
1125                 if (e < s)
1126                         e = s;
1127                 sz = e - s;
1128                 debugf("%08x-%08x = %x\n", s, e, sz);
1129
1130                 /* Check whether some memory is left here. */
1131                 if (sz == 0) {
1132                 empty:
1133                         printf("skipping\n");
1134                         bcopy(mp + 1, mp,
1135                             (cnt - (mp - availmem_regions)) * sizeof(*mp));
1136                         cnt--;
1137                         mp--;
1138                         continue;
1139                 }
1140
1141                 /* Do an insertion sort. */
1142                 for (mp1 = availmem_regions; mp1 < mp; mp1++)
1143                         if (s < mp1->mr_start)
1144                                 break;
1145                 if (mp1 < mp) {
1146                         bcopy(mp1, mp1 + 1, (char *)mp - (char *)mp1);
1147                         mp1->mr_start = s;
1148                         mp1->mr_size = sz;
1149                 } else {
1150                         mp->mr_start = s;
1151                         mp->mr_size = sz;
1152                 }
1153         }
1154         availmem_regions_sz = cnt;
1155
1156         /* Fill in phys_avail table, based on availmem_regions */
1157         debugf("fill in phys_avail:\n");
1158         for (i = 0, j = 0; i < availmem_regions_sz; i++, j += 2) {
1159
1160                 debugf(" region: 0x%08x - 0x%08x (0x%08x)\n",
1161                     availmem_regions[i].mr_start,
1162                     availmem_regions[i].mr_start + availmem_regions[i].mr_size,
1163                     availmem_regions[i].mr_size);
1164
1165                 /*
1166                  * We should not map the page at PA 0x0000000, the VM can't
1167                  * handle it, as pmap_extract() == 0 means failure.
1168                  */
1169                 if (availmem_regions[i].mr_start > 0 ||
1170                     availmem_regions[i].mr_size > PAGE_SIZE) {
1171                         phys_avail[j] = availmem_regions[i].mr_start;
1172                         if (phys_avail[j] == 0)
1173                                 phys_avail[j] += PAGE_SIZE;
1174                         phys_avail[j + 1] = availmem_regions[i].mr_start +
1175                             availmem_regions[i].mr_size;
1176                 } else
1177                         j -= 2;
1178         }
1179         phys_avail[j] = 0;
1180         phys_avail[j + 1] = 0;
1181 }
1182
1183 void *
1184 initarm(struct arm_boot_params *abp)
1185 {
1186         struct mem_region memory_regions[FDT_MEM_REGIONS];
1187         struct mem_region availmem_regions[FDT_MEM_REGIONS];
1188         struct mem_region reserved_regions[FDT_MEM_REGIONS];
1189         struct pv_addr kernel_l1pt;
1190         struct pv_addr dpcpu;
1191         vm_offset_t dtbp, freemempos, l2_start, lastaddr;
1192         uint32_t memsize, l2size;
1193         char *env;
1194         void *kmdp;
1195         u_int l1pagetable;
1196         int i = 0, j = 0, err_devmap = 0;
1197         int memory_regions_sz;
1198         int availmem_regions_sz;
1199         int reserved_regions_sz;
1200         vm_offset_t start, end;
1201         vm_offset_t rstart, rend;
1202         int curr;
1203
1204         lastaddr = parse_boot_param(abp);
1205         memsize = 0;
1206         set_cpufuncs();
1207
1208         /*
1209          * Find the dtb passed in by the boot loader.
1210          */
1211         kmdp = preload_search_by_type("elf kernel");
1212         if (kmdp != NULL)
1213                 dtbp = MD_FETCH(kmdp, MODINFOMD_DTBP, vm_offset_t);
1214         else
1215                 dtbp = (vm_offset_t)NULL;
1216
1217 #if defined(FDT_DTB_STATIC)
1218         /*
1219          * In case the device tree blob was not retrieved (from metadata) try
1220          * to use the statically embedded one.
1221          */
1222         if (dtbp == (vm_offset_t)NULL)
1223                 dtbp = (vm_offset_t)&fdt_static_dtb;
1224 #endif
1225
1226         if (OF_install(OFW_FDT, 0) == FALSE)
1227                 while (1);
1228
1229         if (OF_init((void *)dtbp) != 0)
1230                 while (1);
1231
1232         /* Grab physical memory regions information from device tree. */
1233         if (fdt_get_mem_regions(memory_regions, &memory_regions_sz,
1234             &memsize) != 0)
1235                 while(1);
1236
1237         /* Grab physical memory regions information from device tree. */
1238         if (fdt_get_reserved_regions(reserved_regions, &reserved_regions_sz) != 0)
1239                 reserved_regions_sz = 0;
1240                 
1241         /*
1242          * Now exclude all the reserved regions
1243          */
1244         curr = 0;
1245         for (i = 0; i < memory_regions_sz; i++) {
1246                 start = memory_regions[i].mr_start;
1247                 end = start + memory_regions[i].mr_size;
1248                 for (j = 0; j < reserved_regions_sz; j++) {
1249                         rstart = reserved_regions[j].mr_start;
1250                         rend = rstart + reserved_regions[j].mr_size;
1251                         /* 
1252                          * Restricted region is before available
1253                          * Skip restricted region
1254                          */
1255                         if (rend <= start)
1256                                 continue;
1257                         /* 
1258                          * Restricted region is behind available
1259                          * No  further processing required
1260                          */
1261                         if (rstart >= end)
1262                                 break;
1263                         /*
1264                          * Restricted region includes memory region
1265                          * skip available region
1266                          */
1267                         if ((start >= rstart) && (rend >= end)) {
1268                                 start = rend;
1269                                 end = rend;
1270                                 break;
1271                         }
1272                         /*
1273                          * Memory region includes restricted region
1274                          */
1275                         if ((rstart > start) && (end > rend)) {
1276                                 availmem_regions[curr].mr_start = start;
1277                                 availmem_regions[curr++].mr_size = rstart - start;
1278                                 start = rend;
1279                                 break;
1280                         }
1281                         /*
1282                          * Memory region partially overlaps with restricted
1283                          */
1284                         if ((rstart >= start) && (rstart <= end)) {
1285                                 end = rstart;
1286                         }
1287                         else if ((rend >= start) && (rend <= end)) {
1288                                 start = rend;
1289                         }
1290                 }
1291
1292                 if (end > start) {
1293                         availmem_regions[curr].mr_start = start;
1294                         availmem_regions[curr++].mr_size = end - start;
1295                 }
1296         }
1297
1298         availmem_regions_sz = curr;
1299
1300         /* Platform-specific initialisation */
1301         initarm_early_init();
1302
1303         pcpu0_init();
1304
1305         /* Do basic tuning, hz etc */
1306         init_param1();
1307
1308         /* Calculate number of L2 tables needed for mapping vm_page_array */
1309         l2size = (memsize / PAGE_SIZE) * sizeof(struct vm_page);
1310         l2size = (l2size >> L1_S_SHIFT) + 1;
1311
1312         /*
1313          * Add one table for end of kernel map, one for stacks, msgbuf and
1314          * L1 and L2 tables map and one for vectors map.
1315          */
1316         l2size += 3;
1317
1318         /* Make it divisible by 4 */
1319         l2size = (l2size + 3) & ~3;
1320
1321         freemempos = (lastaddr + PAGE_MASK) & ~PAGE_MASK;
1322
1323         /* Define a macro to simplify memory allocation */
1324 #define valloc_pages(var, np)                                           \
1325         alloc_pages((var).pv_va, (np));                                 \
1326         (var).pv_pa = (var).pv_va + (KERNPHYSADDR - KERNVIRTADDR);
1327
1328 #define alloc_pages(var, np)                                            \
1329         (var) = freemempos;                                             \
1330         freemempos += (np * PAGE_SIZE);                                 \
1331         memset((char *)(var), 0, ((np) * PAGE_SIZE));
1332
1333         while (((freemempos - L1_TABLE_SIZE) & (L1_TABLE_SIZE - 1)) != 0)
1334                 freemempos += PAGE_SIZE;
1335         valloc_pages(kernel_l1pt, L1_TABLE_SIZE / PAGE_SIZE);
1336
1337         for (i = 0; i < l2size; ++i) {
1338                 if (!(i % (PAGE_SIZE / L2_TABLE_SIZE_REAL))) {
1339                         valloc_pages(kernel_pt_table[i],
1340                             L2_TABLE_SIZE / PAGE_SIZE);
1341                         j = i;
1342                 } else {
1343                         kernel_pt_table[i].pv_va = kernel_pt_table[j].pv_va +
1344                             L2_TABLE_SIZE_REAL * (i - j);
1345                         kernel_pt_table[i].pv_pa =
1346                             kernel_pt_table[i].pv_va - KERNVIRTADDR +
1347                             KERNPHYSADDR;
1348
1349                 }
1350         }
1351         /*
1352          * Allocate a page for the system page mapped to 0x00000000
1353          * or 0xffff0000. This page will just contain the system vectors
1354          * and can be shared by all processes.
1355          */
1356         valloc_pages(systempage, 1);
1357
1358         /* Allocate dynamic per-cpu area. */
1359         valloc_pages(dpcpu, DPCPU_SIZE / PAGE_SIZE);
1360         dpcpu_init((void *)dpcpu.pv_va, 0);
1361
1362         /* Allocate stacks for all modes */
1363         valloc_pages(irqstack, IRQ_STACK_SIZE * MAXCPU);
1364         valloc_pages(abtstack, ABT_STACK_SIZE * MAXCPU);
1365         valloc_pages(undstack, UND_STACK_SIZE * MAXCPU);
1366         valloc_pages(kernelstack, KSTACK_PAGES * MAXCPU);
1367         valloc_pages(msgbufpv, round_page(msgbufsize) / PAGE_SIZE);
1368
1369         /*
1370          * Now we start construction of the L1 page table
1371          * We start by mapping the L2 page tables into the L1.
1372          * This means that we can replace L1 mappings later on if necessary
1373          */
1374         l1pagetable = kernel_l1pt.pv_va;
1375
1376         /*
1377          * Try to map as much as possible of kernel text and data using
1378          * 1MB section mapping and for the rest of initial kernel address
1379          * space use L2 coarse tables.
1380          *
1381          * Link L2 tables for mapping remainder of kernel (modulo 1MB)
1382          * and kernel structures
1383          */
1384         l2_start = lastaddr & ~(L1_S_OFFSET);
1385         for (i = 0 ; i < l2size - 1; i++)
1386                 pmap_link_l2pt(l1pagetable, l2_start + i * L1_S_SIZE,
1387                     &kernel_pt_table[i]);
1388
1389         pmap_curmaxkvaddr = l2_start + (l2size - 1) * L1_S_SIZE;
1390
1391         /* Map kernel code and data */
1392         pmap_map_chunk(l1pagetable, KERNVIRTADDR, KERNPHYSADDR,
1393            (((uint32_t)(lastaddr) - KERNVIRTADDR) + PAGE_MASK) & ~PAGE_MASK,
1394             VM_PROT_READ|VM_PROT_WRITE, PTE_CACHE);
1395
1396
1397         /* Map L1 directory and allocated L2 page tables */
1398         pmap_map_chunk(l1pagetable, kernel_l1pt.pv_va, kernel_l1pt.pv_pa,
1399             L1_TABLE_SIZE, VM_PROT_READ|VM_PROT_WRITE, PTE_PAGETABLE);
1400
1401         pmap_map_chunk(l1pagetable, kernel_pt_table[0].pv_va,
1402             kernel_pt_table[0].pv_pa,
1403             L2_TABLE_SIZE_REAL * l2size,
1404             VM_PROT_READ|VM_PROT_WRITE, PTE_PAGETABLE);
1405
1406         /* Map allocated DPCPU, stacks and msgbuf */
1407         pmap_map_chunk(l1pagetable, dpcpu.pv_va, dpcpu.pv_pa,
1408             freemempos - dpcpu.pv_va,
1409             VM_PROT_READ|VM_PROT_WRITE, PTE_CACHE);
1410
1411         /* Link and map the vector page */
1412         pmap_link_l2pt(l1pagetable, ARM_VECTORS_HIGH,
1413             &kernel_pt_table[l2size - 1]);
1414         pmap_map_entry(l1pagetable, ARM_VECTORS_HIGH, systempage.pv_pa,
1415             VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE, PTE_CACHE);
1416
1417         /* Establish static device mappings. */
1418         err_devmap = initarm_devmap_init();
1419         arm_devmap_bootstrap(l1pagetable, NULL);
1420         vm_max_kernel_address = initarm_lastaddr();
1421
1422         cpu_domains((DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2)) | DOMAIN_CLIENT);
1423         pmap_pa = kernel_l1pt.pv_pa;
1424         setttb(kernel_l1pt.pv_pa);
1425         cpu_tlb_flushID();
1426         cpu_domains(DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2));
1427
1428         /*
1429          * Now that proper page tables are installed, call cpu_setup() to enable
1430          * instruction and data caches and other chip-specific features.
1431          */
1432         cpu_setup("");
1433
1434         /*
1435          * Only after the SOC registers block is mapped we can perform device
1436          * tree fixups, as they may attempt to read parameters from hardware.
1437          */
1438         OF_interpret("perform-fixup", 0);
1439
1440         initarm_gpio_init();
1441
1442         cninit();
1443
1444         physmem = memsize / PAGE_SIZE;
1445
1446         debugf("initarm: console initialized\n");
1447         debugf(" arg1 kmdp = 0x%08x\n", (uint32_t)kmdp);
1448         debugf(" boothowto = 0x%08x\n", boothowto);
1449         debugf(" dtbp = 0x%08x\n", (uint32_t)dtbp);
1450         print_kenv();
1451
1452         env = getenv("kernelname");
1453         if (env != NULL)
1454                 strlcpy(kernelname, env, sizeof(kernelname));
1455
1456         if (err_devmap != 0)
1457                 printf("WARNING: could not fully configure devmap, error=%d\n",
1458                     err_devmap);
1459
1460         initarm_late_init();
1461
1462         /*
1463          * Pages were allocated during the secondary bootstrap for the
1464          * stacks for different CPU modes.
1465          * We must now set the r13 registers in the different CPU modes to
1466          * point to these stacks.
1467          * Since the ARM stacks use STMFD etc. we must set r13 to the top end
1468          * of the stack memory.
1469          */
1470         cpu_control(CPU_CONTROL_MMU_ENABLE, CPU_CONTROL_MMU_ENABLE);
1471
1472         set_stackptrs(0);
1473
1474         /*
1475          * We must now clean the cache again....
1476          * Cleaning may be done by reading new data to displace any
1477          * dirty data in the cache. This will have happened in setttb()
1478          * but since we are boot strapping the addresses used for the read
1479          * may have just been remapped and thus the cache could be out
1480          * of sync. A re-clean after the switch will cure this.
1481          * After booting there are no gross relocations of the kernel thus
1482          * this problem will not occur after initarm().
1483          */
1484         cpu_idcache_wbinv_all();
1485
1486         /* Set stack for exception handlers */
1487         data_abort_handler_address = (u_int)data_abort_handler;
1488         prefetch_abort_handler_address = (u_int)prefetch_abort_handler;
1489         undefined_handler_address = (u_int)undefinedinstruction_bounce;
1490         undefined_init();
1491
1492         init_proc0(kernelstack.pv_va);
1493
1494         arm_intrnames_init();
1495         arm_vector_init(ARM_VECTORS_HIGH, ARM_VEC_ALL);
1496         arm_dump_avail_init(memsize, sizeof(dump_avail) / sizeof(dump_avail[0]));
1497         pmap_bootstrap(freemempos, &kernel_l1pt);
1498         msgbufp = (void *)msgbufpv.pv_va;
1499         msgbufinit(msgbufp, msgbufsize);
1500         mutex_init();
1501
1502         /*
1503          * Prepare map of physical memory regions available to vm subsystem.
1504          */
1505         physmap_init(availmem_regions, availmem_regions_sz);
1506
1507         init_param2(physmem);
1508         kdb_init();
1509
1510         return ((void *)(kernelstack.pv_va + USPACE_SVC_STACK_TOP -
1511             sizeof(struct pcb)));
1512 }
1513 #endif