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