]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm/arm/machdep.c
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303197, and update
[FreeBSD/FreeBSD.git] / sys / arm / arm / machdep.c
1 /*      $NetBSD: arm32_machdep.c,v 1.44 2004/03/24 15:34:47 atatat Exp $        */
2
3 /*-
4  * Copyright (c) 2004 Olivier Houchard
5  * Copyright (c) 1994-1998 Mark Brinicombe.
6  * Copyright (c) 1994 Brini.
7  * All rights reserved.
8  *
9  * This code is derived from software written for Brini by Mark Brinicombe
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by Mark Brinicombe
22  *      for the NetBSD Project.
23  * 4. The name of the company nor the name of the author may be used to
24  *    endorse or promote products derived from this software without specific
25  *    prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
28  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
29  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30  * IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
31  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
32  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
33  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  * Machine dependent functions for kernel setup
40  *
41  * Created      : 17/09/94
42  * Updated      : 18/04/01 updated for new wscons
43  */
44
45 #include "opt_compat.h"
46 #include "opt_ddb.h"
47 #include "opt_kstack_pages.h"
48 #include "opt_platform.h"
49 #include "opt_sched.h"
50 #include "opt_timer.h"
51
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
54
55 #include <sys/param.h>
56 #include <sys/buf.h>
57 #include <sys/bus.h>
58 #include <sys/cons.h>
59 #include <sys/cpu.h>
60 #include <sys/devmap.h>
61 #include <sys/efi.h>
62 #include <sys/imgact.h>
63 #include <sys/kdb.h>
64 #include <sys/kernel.h>
65 #include <sys/linker.h>
66 #include <sys/msgbuf.h>
67 #include <sys/rwlock.h>
68 #include <sys/sched.h>
69 #include <sys/syscallsubr.h>
70 #include <sys/sysent.h>
71 #include <sys/sysproto.h>
72 #include <sys/vmmeter.h>
73
74 #include <vm/vm_object.h>
75 #include <vm/vm_page.h>
76 #include <vm/vm_pager.h>
77
78 #include <machine/debug_monitor.h>
79 #include <machine/machdep.h>
80 #include <machine/metadata.h>
81 #include <machine/pcb.h>
82 #include <machine/physmem.h>
83 #include <machine/platform.h>
84 #include <machine/sysarch.h>
85 #include <machine/undefined.h>
86 #include <machine/vfp.h>
87 #include <machine/vmparam.h>
88
89 #ifdef FDT
90 #include <dev/fdt/fdt_common.h>
91 #include <machine/ofw_machdep.h>
92 #endif
93
94 #ifdef DEBUG
95 #define debugf(fmt, args...) printf(fmt, ##args)
96 #else
97 #define debugf(fmt, args...)
98 #endif
99
100 #if defined(COMPAT_FREEBSD4) || defined(COMPAT_FREEBSD5) || \
101     defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD7) || \
102     defined(COMPAT_FREEBSD9)
103 #error FreeBSD/arm doesn't provide compatibility with releases prior to 10
104 #endif
105
106 struct pcpu __pcpu[MAXCPU];
107 struct pcpu *pcpup = &__pcpu[0];
108
109 static struct trapframe proc0_tf;
110 uint32_t cpu_reset_address = 0;
111 int cold = 1;
112 vm_offset_t vector_page;
113
114 int (*_arm_memcpy)(void *, void *, int, int) = NULL;
115 int (*_arm_bzero)(void *, int, int) = NULL;
116 int _min_memcpy_size = 0;
117 int _min_bzero_size = 0;
118
119 extern int *end;
120
121 #ifdef FDT
122 vm_paddr_t pmap_pa;
123 #if __ARM_ARCH >= 6
124 vm_offset_t systempage;
125 vm_offset_t irqstack;
126 vm_offset_t undstack;
127 vm_offset_t abtstack;
128 #else
129 /*
130  * This is the number of L2 page tables required for covering max
131  * (hypothetical) memsize of 4GB and all kernel mappings (vectors, msgbuf,
132  * stacks etc.), uprounded to be divisible by 4.
133  */
134 #define KERNEL_PT_MAX   78
135 static struct pv_addr kernel_pt_table[KERNEL_PT_MAX];
136 struct pv_addr systempage;
137 static struct pv_addr msgbufpv;
138 struct pv_addr irqstack;
139 struct pv_addr undstack;
140 struct pv_addr abtstack;
141 static struct pv_addr kernelstack;
142 #endif /* __ARM_ARCH >= 6 */
143 #endif /* FDT */
144
145 #ifdef MULTIDELAY
146 static delay_func *delay_impl;
147 static void *delay_arg;
148 #endif
149
150 struct kva_md_info kmi;
151
152 /*
153  * arm32_vector_init:
154  *
155  *      Initialize the vector page, and select whether or not to
156  *      relocate the vectors.
157  *
158  *      NOTE: We expect the vector page to be mapped at its expected
159  *      destination.
160  */
161
162 extern unsigned int page0[], page0_data[];
163 void
164 arm_vector_init(vm_offset_t va, int which)
165 {
166         unsigned int *vectors = (int *) va;
167         unsigned int *vectors_data = vectors + (page0_data - page0);
168         int vec;
169
170         /*
171          * Loop through the vectors we're taking over, and copy the
172          * vector's insn and data word.
173          */
174         for (vec = 0; vec < ARM_NVEC; vec++) {
175                 if ((which & (1 << vec)) == 0) {
176                         /* Don't want to take over this vector. */
177                         continue;
178                 }
179                 vectors[vec] = page0[vec];
180                 vectors_data[vec] = page0_data[vec];
181         }
182
183         /* Now sync the vectors. */
184         icache_sync(va, (ARM_NVEC * 2) * sizeof(u_int));
185
186         vector_page = va;
187 #if __ARM_ARCH < 6
188         if (va == ARM_VECTORS_HIGH) {
189                 /*
190                  * Enable high vectors in the system control reg (SCTLR).
191                  *
192                  * Assume the MD caller knows what it's doing here, and really
193                  * does want the vector page relocated.
194                  *
195                  * Note: This has to be done here (and not just in
196                  * cpu_setup()) because the vector page needs to be
197                  * accessible *before* cpu_startup() is called.
198                  * Think ddb(9) ...
199                  */
200                 cpu_control(CPU_CONTROL_VECRELOC, CPU_CONTROL_VECRELOC);
201         }
202 #endif
203 }
204
205 static void
206 cpu_startup(void *dummy)
207 {
208         struct pcb *pcb = thread0.td_pcb;
209         const unsigned int mbyte = 1024 * 1024;
210 #if __ARM_ARCH < 6 && !defined(ARM_CACHE_LOCK_ENABLE)
211         vm_page_t m;
212 #endif
213
214         identify_arm_cpu();
215
216         vm_ksubmap_init(&kmi);
217
218         /*
219          * Display the RAM layout.
220          */
221         printf("real memory  = %ju (%ju MB)\n",
222             (uintmax_t)arm32_ptob(realmem),
223             (uintmax_t)arm32_ptob(realmem) / mbyte);
224         printf("avail memory = %ju (%ju MB)\n",
225             (uintmax_t)arm32_ptob(vm_cnt.v_free_count),
226             (uintmax_t)arm32_ptob(vm_cnt.v_free_count) / mbyte);
227         if (bootverbose) {
228                 arm_physmem_print_tables();
229                 devmap_print_table();
230         }
231
232         bufinit();
233         vm_pager_bufferinit();
234         pcb->pcb_regs.sf_sp = (u_int)thread0.td_kstack +
235             USPACE_SVC_STACK_TOP;
236         pmap_set_pcb_pagedir(kernel_pmap, pcb);
237 #if __ARM_ARCH < 6
238         vector_page_setprot(VM_PROT_READ);
239         pmap_postinit();
240 #ifdef ARM_CACHE_LOCK_ENABLE
241         pmap_kenter_user(ARM_TP_ADDRESS, ARM_TP_ADDRESS);
242         arm_lock_cache_line(ARM_TP_ADDRESS);
243 #else
244         m = vm_page_alloc(NULL, 0, VM_ALLOC_NOOBJ | VM_ALLOC_ZERO);
245         pmap_kenter_user(ARM_TP_ADDRESS, VM_PAGE_TO_PHYS(m));
246 #endif
247         *(uint32_t *)ARM_RAS_START = 0;
248         *(uint32_t *)ARM_RAS_END = 0xffffffff;
249 #endif
250 }
251
252 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
253
254 /*
255  * Flush the D-cache for non-DMA I/O so that the I-cache can
256  * be made coherent later.
257  */
258 void
259 cpu_flush_dcache(void *ptr, size_t len)
260 {
261
262         dcache_wb_poc((vm_offset_t)ptr, (vm_paddr_t)vtophys(ptr), len);
263 }
264
265 /* Get current clock frequency for the given cpu id. */
266 int
267 cpu_est_clockrate(int cpu_id, uint64_t *rate)
268 {
269
270         return (ENXIO);
271 }
272
273 void
274 cpu_idle(int busy)
275 {
276
277         CTR2(KTR_SPARE2, "cpu_idle(%d) at %d", busy, curcpu);
278         spinlock_enter();
279 #ifndef NO_EVENTTIMERS
280         if (!busy)
281                 cpu_idleclock();
282 #endif
283         if (!sched_runnable())
284                 cpu_sleep(0);
285 #ifndef NO_EVENTTIMERS
286         if (!busy)
287                 cpu_activeclock();
288 #endif
289         spinlock_exit();
290         CTR2(KTR_SPARE2, "cpu_idle(%d) at %d done", busy, curcpu);
291 }
292
293 int
294 cpu_idle_wakeup(int cpu)
295 {
296
297         return (0);
298 }
299
300 /*
301  * Most ARM platforms don't need to do anything special to init their clocks
302  * (they get intialized during normal device attachment), and by not defining a
303  * cpu_initclocks() function they get this generic one.  Any platform that needs
304  * to do something special can just provide their own implementation, which will
305  * override this one due to the weak linkage.
306  */
307 void
308 arm_generic_initclocks(void)
309 {
310
311 #ifndef NO_EVENTTIMERS
312 #ifdef SMP
313         if (PCPU_GET(cpuid) == 0)
314                 cpu_initclocks_bsp();
315         else
316                 cpu_initclocks_ap();
317 #else
318         cpu_initclocks_bsp();
319 #endif
320 #endif
321 }
322 __weak_reference(arm_generic_initclocks, cpu_initclocks);
323
324 #ifdef MULTIDELAY
325 void
326 arm_set_delay(delay_func *impl, void *arg)
327 {
328
329         KASSERT(impl != NULL, ("No DELAY implementation"));
330         delay_impl = impl;
331         delay_arg = arg;
332 }
333
334 void
335 DELAY(int usec)
336 {
337
338         delay_impl(usec, delay_arg);
339 }
340 #endif
341
342 void
343 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
344 {
345 }
346
347 void
348 spinlock_enter(void)
349 {
350         struct thread *td;
351         register_t cspr;
352
353         td = curthread;
354         if (td->td_md.md_spinlock_count == 0) {
355                 cspr = disable_interrupts(PSR_I | PSR_F);
356                 td->td_md.md_spinlock_count = 1;
357                 td->td_md.md_saved_cspr = cspr;
358         } else
359                 td->td_md.md_spinlock_count++;
360         critical_enter();
361 }
362
363 void
364 spinlock_exit(void)
365 {
366         struct thread *td;
367         register_t cspr;
368
369         td = curthread;
370         critical_exit();
371         cspr = td->td_md.md_saved_cspr;
372         td->td_md.md_spinlock_count--;
373         if (td->td_md.md_spinlock_count == 0)
374                 restore_interrupts(cspr);
375 }
376
377 /*
378  * Clear registers on exec
379  */
380 void
381 exec_setregs(struct thread *td, struct image_params *imgp, u_long stack)
382 {
383         struct trapframe *tf = td->td_frame;
384
385         memset(tf, 0, sizeof(*tf));
386         tf->tf_usr_sp = stack;
387         tf->tf_usr_lr = imgp->entry_addr;
388         tf->tf_svc_lr = 0x77777777;
389         tf->tf_pc = imgp->entry_addr;
390         tf->tf_spsr = PSR_USR32_MODE;
391 }
392
393
394 #ifdef VFP
395 /*
396  * Get machine VFP context.
397  */
398 static void
399 get_vfpcontext(struct thread *td, mcontext_vfp_t *vfp)
400 {
401         struct pcb *curpcb;
402
403         curpcb = curthread->td_pcb;
404         critical_enter();
405
406         vfp_store(&curpcb->pcb_vfpstate, false);
407         memcpy(vfp->mcv_reg, curpcb->pcb_vfpstate.reg,
408             sizeof(vfp->mcv_reg));
409         vfp->mcv_fpscr = curpcb->pcb_vfpstate.fpscr;
410
411         critical_exit();
412 }
413
414 /*
415  * Set machine VFP context.
416  */
417 static void
418 set_vfpcontext(struct thread *td, mcontext_vfp_t *vfp)
419 {
420         struct pcb *curpcb;
421
422         curpcb = curthread->td_pcb;
423         critical_enter();
424
425         vfp_discard(td);
426         memcpy(curpcb->pcb_vfpstate.reg, vfp->mcv_reg,
427             sizeof(curpcb->pcb_vfpstate.reg));
428         curpcb->pcb_vfpstate.fpscr = vfp->mcv_fpscr;
429
430         critical_exit();
431 }
432 #endif
433
434 /*
435  * Get machine context.
436  */
437 int
438 get_mcontext(struct thread *td, mcontext_t *mcp, int clear_ret)
439 {
440         struct trapframe *tf = td->td_frame;
441         __greg_t *gr = mcp->__gregs;
442
443         if (clear_ret & GET_MC_CLEAR_RET) {
444                 gr[_REG_R0] = 0;
445                 gr[_REG_CPSR] = tf->tf_spsr & ~PSR_C;
446         } else {
447                 gr[_REG_R0]   = tf->tf_r0;
448                 gr[_REG_CPSR] = tf->tf_spsr;
449         }
450         gr[_REG_R1]   = tf->tf_r1;
451         gr[_REG_R2]   = tf->tf_r2;
452         gr[_REG_R3]   = tf->tf_r3;
453         gr[_REG_R4]   = tf->tf_r4;
454         gr[_REG_R5]   = tf->tf_r5;
455         gr[_REG_R6]   = tf->tf_r6;
456         gr[_REG_R7]   = tf->tf_r7;
457         gr[_REG_R8]   = tf->tf_r8;
458         gr[_REG_R9]   = tf->tf_r9;
459         gr[_REG_R10]  = tf->tf_r10;
460         gr[_REG_R11]  = tf->tf_r11;
461         gr[_REG_R12]  = tf->tf_r12;
462         gr[_REG_SP]   = tf->tf_usr_sp;
463         gr[_REG_LR]   = tf->tf_usr_lr;
464         gr[_REG_PC]   = tf->tf_pc;
465
466         mcp->mc_vfp_size = 0;
467         mcp->mc_vfp_ptr = NULL;
468         memset(&mcp->mc_spare, 0, sizeof(mcp->mc_spare));
469
470         return (0);
471 }
472
473 /*
474  * Set machine context.
475  *
476  * However, we don't set any but the user modifiable flags, and we won't
477  * touch the cs selector.
478  */
479 int
480 set_mcontext(struct thread *td, mcontext_t *mcp)
481 {
482         mcontext_vfp_t mc_vfp, *vfp;
483         struct trapframe *tf = td->td_frame;
484         const __greg_t *gr = mcp->__gregs;
485
486 #ifdef WITNESS
487         if (mcp->mc_vfp_size != 0 && mcp->mc_vfp_size != sizeof(mc_vfp)) {
488                 printf("%s: %s: Malformed mc_vfp_size: %d (0x%08X)\n",
489                     td->td_proc->p_comm, __func__,
490                     mcp->mc_vfp_size, mcp->mc_vfp_size);
491         } else if (mcp->mc_vfp_size != 0 && mcp->mc_vfp_ptr == NULL) {
492                 printf("%s: %s: c_vfp_size != 0 but mc_vfp_ptr == NULL\n",
493                     td->td_proc->p_comm, __func__);
494         }
495 #endif
496
497         if (mcp->mc_vfp_size == sizeof(mc_vfp) && mcp->mc_vfp_ptr != NULL) {
498                 if (copyin(mcp->mc_vfp_ptr, &mc_vfp, sizeof(mc_vfp)) != 0)
499                         return (EFAULT);
500                 vfp = &mc_vfp;
501         } else {
502                 vfp = NULL;
503         }
504
505         tf->tf_r0 = gr[_REG_R0];
506         tf->tf_r1 = gr[_REG_R1];
507         tf->tf_r2 = gr[_REG_R2];
508         tf->tf_r3 = gr[_REG_R3];
509         tf->tf_r4 = gr[_REG_R4];
510         tf->tf_r5 = gr[_REG_R5];
511         tf->tf_r6 = gr[_REG_R6];
512         tf->tf_r7 = gr[_REG_R7];
513         tf->tf_r8 = gr[_REG_R8];
514         tf->tf_r9 = gr[_REG_R9];
515         tf->tf_r10 = gr[_REG_R10];
516         tf->tf_r11 = gr[_REG_R11];
517         tf->tf_r12 = gr[_REG_R12];
518         tf->tf_usr_sp = gr[_REG_SP];
519         tf->tf_usr_lr = gr[_REG_LR];
520         tf->tf_pc = gr[_REG_PC];
521         tf->tf_spsr = gr[_REG_CPSR];
522 #ifdef VFP
523         if (vfp != NULL)
524                 set_vfpcontext(td, vfp);
525 #endif
526         return (0);
527 }
528
529 void
530 sendsig(catcher, ksi, mask)
531         sig_t catcher;
532         ksiginfo_t *ksi;
533         sigset_t *mask;
534 {
535         struct thread *td;
536         struct proc *p;
537         struct trapframe *tf;
538         struct sigframe *fp, frame;
539         struct sigacts *psp;
540         struct sysentvec *sysent;
541         int onstack;
542         int sig;
543         int code;
544
545         td = curthread;
546         p = td->td_proc;
547         PROC_LOCK_ASSERT(p, MA_OWNED);
548         sig = ksi->ksi_signo;
549         code = ksi->ksi_code;
550         psp = p->p_sigacts;
551         mtx_assert(&psp->ps_mtx, MA_OWNED);
552         tf = td->td_frame;
553         onstack = sigonstack(tf->tf_usr_sp);
554
555         CTR4(KTR_SIG, "sendsig: td=%p (%s) catcher=%p sig=%d", td, p->p_comm,
556             catcher, sig);
557
558         /* Allocate and validate space for the signal handler context. */
559         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !(onstack) &&
560             SIGISMEMBER(psp->ps_sigonstack, sig)) {
561                 fp = (struct sigframe *)((uintptr_t)td->td_sigstk.ss_sp +
562                     td->td_sigstk.ss_size);
563 #if defined(COMPAT_43)
564                 td->td_sigstk.ss_flags |= SS_ONSTACK;
565 #endif
566         } else
567                 fp = (struct sigframe *)td->td_frame->tf_usr_sp;
568
569         /* make room on the stack */
570         fp--;
571
572         /* make the stack aligned */
573         fp = (struct sigframe *)STACKALIGN(fp);
574         /* Populate the siginfo frame. */
575         get_mcontext(td, &frame.sf_uc.uc_mcontext, 0);
576 #ifdef VFP
577         get_vfpcontext(td, &frame.sf_vfp);
578         frame.sf_uc.uc_mcontext.mc_vfp_size = sizeof(fp->sf_vfp);
579         frame.sf_uc.uc_mcontext.mc_vfp_ptr = &fp->sf_vfp;
580 #else
581         frame.sf_uc.uc_mcontext.mc_vfp_size = 0;
582         frame.sf_uc.uc_mcontext.mc_vfp_ptr = NULL;
583 #endif
584         frame.sf_si = ksi->ksi_info;
585         frame.sf_uc.uc_sigmask = *mask;
586         frame.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK )
587             ? ((onstack) ? SS_ONSTACK : 0) : SS_DISABLE;
588         frame.sf_uc.uc_stack = td->td_sigstk;
589         mtx_unlock(&psp->ps_mtx);
590         PROC_UNLOCK(td->td_proc);
591
592         /* Copy the sigframe out to the user's stack. */
593         if (copyout(&frame, fp, sizeof(*fp)) != 0) {
594                 /* Process has trashed its stack. Kill it. */
595                 CTR2(KTR_SIG, "sendsig: sigexit td=%p fp=%p", td, fp);
596                 PROC_LOCK(p);
597                 sigexit(td, SIGILL);
598         }
599
600         /*
601          * Build context to run handler in.  We invoke the handler
602          * directly, only returning via the trampoline.  Note the
603          * trampoline version numbers are coordinated with machine-
604          * dependent code in libc.
605          */
606
607         tf->tf_r0 = sig;
608         tf->tf_r1 = (register_t)&fp->sf_si;
609         tf->tf_r2 = (register_t)&fp->sf_uc;
610
611         /* the trampoline uses r5 as the uc address */
612         tf->tf_r5 = (register_t)&fp->sf_uc;
613         tf->tf_pc = (register_t)catcher;
614         tf->tf_usr_sp = (register_t)fp;
615         sysent = p->p_sysent;
616         if (sysent->sv_sigcode_base != 0)
617                 tf->tf_usr_lr = (register_t)sysent->sv_sigcode_base;
618         else
619                 tf->tf_usr_lr = (register_t)(sysent->sv_psstrings -
620                     *(sysent->sv_szsigcode));
621         /* Set the mode to enter in the signal handler */
622 #if __ARM_ARCH >= 7
623         if ((register_t)catcher & 1)
624                 tf->tf_spsr |= PSR_T;
625         else
626                 tf->tf_spsr &= ~PSR_T;
627 #endif
628
629         CTR3(KTR_SIG, "sendsig: return td=%p pc=%#x sp=%#x", td, tf->tf_usr_lr,
630             tf->tf_usr_sp);
631
632         PROC_LOCK(p);
633         mtx_lock(&psp->ps_mtx);
634 }
635
636 int
637 sys_sigreturn(td, uap)
638         struct thread *td;
639         struct sigreturn_args /* {
640                 const struct __ucontext *sigcntxp;
641         } */ *uap;
642 {
643         ucontext_t uc;
644         int spsr;
645
646         if (uap == NULL)
647                 return (EFAULT);
648         if (copyin(uap->sigcntxp, &uc, sizeof(uc)))
649                 return (EFAULT);
650         /*
651          * Make sure the processor mode has not been tampered with and
652          * interrupts have not been disabled.
653          */
654         spsr = uc.uc_mcontext.__gregs[_REG_CPSR];
655         if ((spsr & PSR_MODE) != PSR_USR32_MODE ||
656             (spsr & (PSR_I | PSR_F)) != 0)
657                 return (EINVAL);
658         /* Restore register context. */
659         set_mcontext(td, &uc.uc_mcontext);
660
661         /* Restore signal mask. */
662         kern_sigprocmask(td, SIG_SETMASK, &uc.uc_sigmask, NULL, 0);
663
664         return (EJUSTRETURN);
665 }
666
667 /*
668  * Construct a PCB from a trapframe. This is called from kdb_trap() where
669  * we want to start a backtrace from the function that caused us to enter
670  * the debugger. We have the context in the trapframe, but base the trace
671  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
672  * enough for a backtrace.
673  */
674 void
675 makectx(struct trapframe *tf, struct pcb *pcb)
676 {
677         pcb->pcb_regs.sf_r4 = tf->tf_r4;
678         pcb->pcb_regs.sf_r5 = tf->tf_r5;
679         pcb->pcb_regs.sf_r6 = tf->tf_r6;
680         pcb->pcb_regs.sf_r7 = tf->tf_r7;
681         pcb->pcb_regs.sf_r8 = tf->tf_r8;
682         pcb->pcb_regs.sf_r9 = tf->tf_r9;
683         pcb->pcb_regs.sf_r10 = tf->tf_r10;
684         pcb->pcb_regs.sf_r11 = tf->tf_r11;
685         pcb->pcb_regs.sf_r12 = tf->tf_r12;
686         pcb->pcb_regs.sf_pc = tf->tf_pc;
687         pcb->pcb_regs.sf_lr = tf->tf_usr_lr;
688         pcb->pcb_regs.sf_sp = tf->tf_usr_sp;
689 }
690
691 void
692 pcpu0_init(void)
693 {
694 #if __ARM_ARCH >= 6
695         set_curthread(&thread0);
696 #endif
697         pcpu_init(pcpup, 0, sizeof(struct pcpu));
698         PCPU_SET(curthread, &thread0);
699 }
700
701 /*
702  * Initialize proc0
703  */
704 void
705 init_proc0(vm_offset_t kstack)
706 {
707         proc_linkup0(&proc0, &thread0);
708         thread0.td_kstack = kstack;
709         thread0.td_pcb = (struct pcb *)
710                 (thread0.td_kstack + kstack_pages * PAGE_SIZE) - 1;
711         thread0.td_pcb->pcb_flags = 0;
712         thread0.td_pcb->pcb_vfpcpu = -1;
713         thread0.td_pcb->pcb_vfpstate.fpscr = VFPSCR_DN;
714         thread0.td_frame = &proc0_tf;
715         pcpup->pc_curpcb = thread0.td_pcb;
716 }
717
718 #if __ARM_ARCH >= 6
719 void
720 set_stackptrs(int cpu)
721 {
722
723         set_stackptr(PSR_IRQ32_MODE,
724             irqstack + ((IRQ_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
725         set_stackptr(PSR_ABT32_MODE,
726             abtstack + ((ABT_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
727         set_stackptr(PSR_UND32_MODE,
728             undstack + ((UND_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
729 }
730 #else
731 void
732 set_stackptrs(int cpu)
733 {
734
735         set_stackptr(PSR_IRQ32_MODE,
736             irqstack.pv_va + ((IRQ_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
737         set_stackptr(PSR_ABT32_MODE,
738             abtstack.pv_va + ((ABT_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
739         set_stackptr(PSR_UND32_MODE,
740             undstack.pv_va + ((UND_STACK_SIZE * PAGE_SIZE) * (cpu + 1)));
741 }
742 #endif
743
744
745 #ifdef FDT
746 #if __ARM_ARCH < 6
747 void *
748 initarm(struct arm_boot_params *abp)
749 {
750         struct mem_region mem_regions[FDT_MEM_REGIONS];
751         struct pv_addr kernel_l1pt;
752         struct pv_addr dpcpu;
753         vm_offset_t dtbp, freemempos, l2_start, lastaddr;
754         uint64_t memsize;
755         uint32_t l2size;
756         char *env;
757         void *kmdp;
758         u_int l1pagetable;
759         int i, j, err_devmap, mem_regions_sz;
760
761         lastaddr = parse_boot_param(abp);
762         arm_physmem_kernaddr = abp->abp_physaddr;
763
764         memsize = 0;
765
766         cpuinfo_init();
767         set_cpufuncs();
768
769         /*
770          * Find the dtb passed in by the boot loader.
771          */
772         kmdp = preload_search_by_type("elf kernel");
773         if (kmdp != NULL)
774                 dtbp = MD_FETCH(kmdp, MODINFOMD_DTBP, vm_offset_t);
775         else
776                 dtbp = (vm_offset_t)NULL;
777
778 #if defined(FDT_DTB_STATIC)
779         /*
780          * In case the device tree blob was not retrieved (from metadata) try
781          * to use the statically embedded one.
782          */
783         if (dtbp == (vm_offset_t)NULL)
784                 dtbp = (vm_offset_t)&fdt_static_dtb;
785 #endif
786
787         if (OF_install(OFW_FDT, 0) == FALSE)
788                 panic("Cannot install FDT");
789
790         if (OF_init((void *)dtbp) != 0)
791                 panic("OF_init failed with the found device tree");
792
793         /* Grab physical memory regions information from device tree. */
794         if (fdt_get_mem_regions(mem_regions, &mem_regions_sz, &memsize) != 0)
795                 panic("Cannot get physical memory regions");
796         arm_physmem_hardware_regions(mem_regions, mem_regions_sz);
797
798         /* Grab reserved memory regions information from device tree. */
799         if (fdt_get_reserved_regions(mem_regions, &mem_regions_sz) == 0)
800                 arm_physmem_exclude_regions(mem_regions, mem_regions_sz,
801                     EXFLAG_NODUMP | EXFLAG_NOALLOC);
802
803         /* Platform-specific initialisation */
804         platform_probe_and_attach();
805
806         pcpu0_init();
807
808         /* Do basic tuning, hz etc */
809         init_param1();
810
811         /* Calculate number of L2 tables needed for mapping vm_page_array */
812         l2size = (memsize / PAGE_SIZE) * sizeof(struct vm_page);
813         l2size = (l2size >> L1_S_SHIFT) + 1;
814
815         /*
816          * Add one table for end of kernel map, one for stacks, msgbuf and
817          * L1 and L2 tables map,  one for vectors map and two for
818          * l2 structures from pmap_bootstrap.
819          */
820         l2size += 5;
821
822         /* Make it divisible by 4 */
823         l2size = (l2size + 3) & ~3;
824
825         freemempos = (lastaddr + PAGE_MASK) & ~PAGE_MASK;
826
827         /* Define a macro to simplify memory allocation */
828 #define valloc_pages(var, np)                                           \
829         alloc_pages((var).pv_va, (np));                                 \
830         (var).pv_pa = (var).pv_va + (abp->abp_physaddr - KERNVIRTADDR);
831
832 #define alloc_pages(var, np)                                            \
833         (var) = freemempos;                                             \
834         freemempos += (np * PAGE_SIZE);                                 \
835         memset((char *)(var), 0, ((np) * PAGE_SIZE));
836
837         while (((freemempos - L1_TABLE_SIZE) & (L1_TABLE_SIZE - 1)) != 0)
838                 freemempos += PAGE_SIZE;
839         valloc_pages(kernel_l1pt, L1_TABLE_SIZE / PAGE_SIZE);
840
841         for (i = 0, j = 0; i < l2size; ++i) {
842                 if (!(i % (PAGE_SIZE / L2_TABLE_SIZE_REAL))) {
843                         valloc_pages(kernel_pt_table[i],
844                             L2_TABLE_SIZE / PAGE_SIZE);
845                         j = i;
846                 } else {
847                         kernel_pt_table[i].pv_va = kernel_pt_table[j].pv_va +
848                             L2_TABLE_SIZE_REAL * (i - j);
849                         kernel_pt_table[i].pv_pa =
850                             kernel_pt_table[i].pv_va - KERNVIRTADDR +
851                             abp->abp_physaddr;
852
853                 }
854         }
855         /*
856          * Allocate a page for the system page mapped to 0x00000000
857          * or 0xffff0000. This page will just contain the system vectors
858          * and can be shared by all processes.
859          */
860         valloc_pages(systempage, 1);
861
862         /* Allocate dynamic per-cpu area. */
863         valloc_pages(dpcpu, DPCPU_SIZE / PAGE_SIZE);
864         dpcpu_init((void *)dpcpu.pv_va, 0);
865
866         /* Allocate stacks for all modes */
867         valloc_pages(irqstack, IRQ_STACK_SIZE * MAXCPU);
868         valloc_pages(abtstack, ABT_STACK_SIZE * MAXCPU);
869         valloc_pages(undstack, UND_STACK_SIZE * MAXCPU);
870         valloc_pages(kernelstack, kstack_pages * MAXCPU);
871         valloc_pages(msgbufpv, round_page(msgbufsize) / PAGE_SIZE);
872
873         /*
874          * Now we start construction of the L1 page table
875          * We start by mapping the L2 page tables into the L1.
876          * This means that we can replace L1 mappings later on if necessary
877          */
878         l1pagetable = kernel_l1pt.pv_va;
879
880         /*
881          * Try to map as much as possible of kernel text and data using
882          * 1MB section mapping and for the rest of initial kernel address
883          * space use L2 coarse tables.
884          *
885          * Link L2 tables for mapping remainder of kernel (modulo 1MB)
886          * and kernel structures
887          */
888         l2_start = lastaddr & ~(L1_S_OFFSET);
889         for (i = 0 ; i < l2size - 1; i++)
890                 pmap_link_l2pt(l1pagetable, l2_start + i * L1_S_SIZE,
891                     &kernel_pt_table[i]);
892
893         pmap_curmaxkvaddr = l2_start + (l2size - 1) * L1_S_SIZE;
894
895         /* Map kernel code and data */
896         pmap_map_chunk(l1pagetable, KERNVIRTADDR, abp->abp_physaddr,
897            (((uint32_t)(lastaddr) - KERNVIRTADDR) + PAGE_MASK) & ~PAGE_MASK,
898             VM_PROT_READ|VM_PROT_WRITE, PTE_CACHE);
899
900         /* Map L1 directory and allocated L2 page tables */
901         pmap_map_chunk(l1pagetable, kernel_l1pt.pv_va, kernel_l1pt.pv_pa,
902             L1_TABLE_SIZE, VM_PROT_READ|VM_PROT_WRITE, PTE_PAGETABLE);
903
904         pmap_map_chunk(l1pagetable, kernel_pt_table[0].pv_va,
905             kernel_pt_table[0].pv_pa,
906             L2_TABLE_SIZE_REAL * l2size,
907             VM_PROT_READ|VM_PROT_WRITE, PTE_PAGETABLE);
908
909         /* Map allocated DPCPU, stacks and msgbuf */
910         pmap_map_chunk(l1pagetable, dpcpu.pv_va, dpcpu.pv_pa,
911             freemempos - dpcpu.pv_va,
912             VM_PROT_READ|VM_PROT_WRITE, PTE_CACHE);
913
914         /* Link and map the vector page */
915         pmap_link_l2pt(l1pagetable, ARM_VECTORS_HIGH,
916             &kernel_pt_table[l2size - 1]);
917         pmap_map_entry(l1pagetable, ARM_VECTORS_HIGH, systempage.pv_pa,
918             VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE, PTE_CACHE);
919
920         /* Establish static device mappings. */
921         err_devmap = platform_devmap_init();
922         devmap_bootstrap(l1pagetable, NULL);
923         vm_max_kernel_address = platform_lastaddr();
924
925         cpu_domains((DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2)) | DOMAIN_CLIENT);
926         pmap_pa = kernel_l1pt.pv_pa;
927         cpu_setttb(kernel_l1pt.pv_pa);
928         cpu_tlb_flushID();
929         cpu_domains(DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2));
930
931         /*
932          * Now that proper page tables are installed, call cpu_setup() to enable
933          * instruction and data caches and other chip-specific features.
934          */
935         cpu_setup();
936
937         /*
938          * Only after the SOC registers block is mapped we can perform device
939          * tree fixups, as they may attempt to read parameters from hardware.
940          */
941         OF_interpret("perform-fixup", 0);
942
943         platform_gpio_init();
944
945         cninit();
946
947         debugf("initarm: console initialized\n");
948         debugf(" arg1 kmdp = 0x%08x\n", (uint32_t)kmdp);
949         debugf(" boothowto = 0x%08x\n", boothowto);
950         debugf(" dtbp = 0x%08x\n", (uint32_t)dtbp);
951         arm_print_kenv();
952
953         env = kern_getenv("kernelname");
954         if (env != NULL) {
955                 strlcpy(kernelname, env, sizeof(kernelname));
956                 freeenv(env);
957         }
958
959         if (err_devmap != 0)
960                 printf("WARNING: could not fully configure devmap, error=%d\n",
961                     err_devmap);
962
963         platform_late_init();
964
965         /*
966          * Pages were allocated during the secondary bootstrap for the
967          * stacks for different CPU modes.
968          * We must now set the r13 registers in the different CPU modes to
969          * point to these stacks.
970          * Since the ARM stacks use STMFD etc. we must set r13 to the top end
971          * of the stack memory.
972          */
973         cpu_control(CPU_CONTROL_MMU_ENABLE, CPU_CONTROL_MMU_ENABLE);
974
975         set_stackptrs(0);
976
977         /*
978          * We must now clean the cache again....
979          * Cleaning may be done by reading new data to displace any
980          * dirty data in the cache. This will have happened in cpu_setttb()
981          * but since we are boot strapping the addresses used for the read
982          * may have just been remapped and thus the cache could be out
983          * of sync. A re-clean after the switch will cure this.
984          * After booting there are no gross relocations of the kernel thus
985          * this problem will not occur after initarm().
986          */
987         cpu_idcache_wbinv_all();
988
989         undefined_init();
990
991         init_proc0(kernelstack.pv_va);
992
993         arm_vector_init(ARM_VECTORS_HIGH, ARM_VEC_ALL);
994         pmap_bootstrap(freemempos, &kernel_l1pt);
995         msgbufp = (void *)msgbufpv.pv_va;
996         msgbufinit(msgbufp, msgbufsize);
997         mutex_init();
998
999         /*
1000          * Exclude the kernel (and all the things we allocated which immediately
1001          * follow the kernel) from the VM allocation pool but not from crash
1002          * dumps.  virtual_avail is a global variable which tracks the kva we've
1003          * "allocated" while setting up pmaps.
1004          *
1005          * Prepare the list of physical memory available to the vm subsystem.
1006          */
1007         arm_physmem_exclude_region(abp->abp_physaddr,
1008             (virtual_avail - KERNVIRTADDR), EXFLAG_NOALLOC);
1009         arm_physmem_init_kernel_globals();
1010
1011         init_param2(physmem);
1012         dbg_monitor_init();
1013         kdb_init();
1014
1015         return ((void *)(kernelstack.pv_va + USPACE_SVC_STACK_TOP -
1016             sizeof(struct pcb)));
1017 }
1018 #else /* __ARM_ARCH < 6 */
1019 void *
1020 initarm(struct arm_boot_params *abp)
1021 {
1022         struct mem_region mem_regions[FDT_MEM_REGIONS];
1023         vm_paddr_t lastaddr;
1024         vm_offset_t dtbp, kernelstack, dpcpu;
1025         char *env;
1026         void *kmdp;
1027         int err_devmap, mem_regions_sz;
1028 #ifdef EFI
1029         struct efi_map_header *efihdr;
1030 #endif
1031
1032         /* get last allocated physical address */
1033         arm_physmem_kernaddr = abp->abp_physaddr;
1034         lastaddr = parse_boot_param(abp) - KERNVIRTADDR + arm_physmem_kernaddr;
1035
1036         set_cpufuncs();
1037         cpuinfo_init();
1038
1039         /*
1040          * Find the dtb passed in by the boot loader.
1041          */
1042         kmdp = preload_search_by_type("elf kernel");
1043         dtbp = MD_FETCH(kmdp, MODINFOMD_DTBP, vm_offset_t);
1044 #if defined(FDT_DTB_STATIC)
1045         /*
1046          * In case the device tree blob was not retrieved (from metadata) try
1047          * to use the statically embedded one.
1048          */
1049         if (dtbp == (vm_offset_t)NULL)
1050                 dtbp = (vm_offset_t)&fdt_static_dtb;
1051 #endif
1052
1053         if (OF_install(OFW_FDT, 0) == FALSE)
1054                 panic("Cannot install FDT");
1055
1056         if (OF_init((void *)dtbp) != 0)
1057                 panic("OF_init failed with the found device tree");
1058
1059 #if defined(LINUX_BOOT_ABI)
1060         arm_parse_fdt_bootargs();
1061 #endif
1062
1063 #ifdef EFI
1064         efihdr = (struct efi_map_header *)preload_search_info(kmdp,
1065             MODINFO_METADATA | MODINFOMD_EFI_MAP);
1066         if (efihdr != NULL) {
1067                 arm_add_efi_map_entries(efihdr, mem_regions, &mem_regions_sz);
1068         } else
1069 #endif
1070         {
1071                 /* Grab physical memory regions information from device tree. */
1072                 if (fdt_get_mem_regions(mem_regions, &mem_regions_sz,NULL) != 0)
1073                         panic("Cannot get physical memory regions");
1074         }
1075         arm_physmem_hardware_regions(mem_regions, mem_regions_sz);
1076
1077         /* Grab reserved memory regions information from device tree. */
1078         if (fdt_get_reserved_regions(mem_regions, &mem_regions_sz) == 0)
1079                 arm_physmem_exclude_regions(mem_regions, mem_regions_sz,
1080                     EXFLAG_NODUMP | EXFLAG_NOALLOC);
1081
1082         /*
1083          * Set TEX remapping registers.
1084          * Setup kernel page tables and switch to kernel L1 page table.
1085          */
1086         pmap_set_tex();
1087         pmap_bootstrap_prepare(lastaddr);
1088
1089         /*
1090          * Now that proper page tables are installed, call cpu_setup() to enable
1091          * instruction and data caches and other chip-specific features.
1092          */
1093         cpu_setup();
1094
1095         /* Platform-specific initialisation */
1096         platform_probe_and_attach();
1097         pcpu0_init();
1098
1099         /* Do basic tuning, hz etc */
1100         init_param1();
1101
1102         /*
1103          * Allocate a page for the system page mapped to 0xffff0000
1104          * This page will just contain the system vectors and can be
1105          * shared by all processes.
1106          */
1107         systempage = pmap_preboot_get_pages(1);
1108
1109         /* Map the vector page. */
1110         pmap_preboot_map_pages(systempage, ARM_VECTORS_HIGH,  1);
1111         if (virtual_end >= ARM_VECTORS_HIGH)
1112                 virtual_end = ARM_VECTORS_HIGH - 1;
1113
1114         /* Allocate dynamic per-cpu area. */
1115         dpcpu = pmap_preboot_get_vpages(DPCPU_SIZE / PAGE_SIZE);
1116         dpcpu_init((void *)dpcpu, 0);
1117
1118         /* Allocate stacks for all modes */
1119         irqstack    = pmap_preboot_get_vpages(IRQ_STACK_SIZE * MAXCPU);
1120         abtstack    = pmap_preboot_get_vpages(ABT_STACK_SIZE * MAXCPU);
1121         undstack    = pmap_preboot_get_vpages(UND_STACK_SIZE * MAXCPU );
1122         kernelstack = pmap_preboot_get_vpages(kstack_pages * MAXCPU);
1123
1124         /* Allocate message buffer. */
1125         msgbufp = (void *)pmap_preboot_get_vpages(
1126             round_page(msgbufsize) / PAGE_SIZE);
1127
1128         /*
1129          * Pages were allocated during the secondary bootstrap for the
1130          * stacks for different CPU modes.
1131          * We must now set the r13 registers in the different CPU modes to
1132          * point to these stacks.
1133          * Since the ARM stacks use STMFD etc. we must set r13 to the top end
1134          * of the stack memory.
1135          */
1136         set_stackptrs(0);
1137         mutex_init();
1138
1139         /* Establish static device mappings. */
1140         err_devmap = platform_devmap_init();
1141         devmap_bootstrap(0, NULL);
1142         vm_max_kernel_address = platform_lastaddr();
1143
1144         /*
1145          * Only after the SOC registers block is mapped we can perform device
1146          * tree fixups, as they may attempt to read parameters from hardware.
1147          */
1148         OF_interpret("perform-fixup", 0);
1149         platform_gpio_init();
1150         cninit();
1151
1152         debugf("initarm: console initialized\n");
1153         debugf(" arg1 kmdp = 0x%08x\n", (uint32_t)kmdp);
1154         debugf(" boothowto = 0x%08x\n", boothowto);
1155         debugf(" dtbp = 0x%08x\n", (uint32_t)dtbp);
1156         debugf(" lastaddr1: 0x%08x\n", lastaddr);
1157         arm_print_kenv();
1158
1159         env = kern_getenv("kernelname");
1160         if (env != NULL)
1161                 strlcpy(kernelname, env, sizeof(kernelname));
1162
1163         if (err_devmap != 0)
1164                 printf("WARNING: could not fully configure devmap, error=%d\n",
1165                     err_devmap);
1166
1167         platform_late_init();
1168
1169         /*
1170          * We must now clean the cache again....
1171          * Cleaning may be done by reading new data to displace any
1172          * dirty data in the cache. This will have happened in cpu_setttb()
1173          * but since we are boot strapping the addresses used for the read
1174          * may have just been remapped and thus the cache could be out
1175          * of sync. A re-clean after the switch will cure this.
1176          * After booting there are no gross relocations of the kernel thus
1177          * this problem will not occur after initarm().
1178          */
1179         /* Set stack for exception handlers */
1180         undefined_init();
1181         init_proc0(kernelstack);
1182         arm_vector_init(ARM_VECTORS_HIGH, ARM_VEC_ALL);
1183         enable_interrupts(PSR_A);
1184         pmap_bootstrap(0);
1185
1186         /* Exclude the kernel (and all the things we allocated which immediately
1187          * follow the kernel) from the VM allocation pool but not from crash
1188          * dumps.  virtual_avail is a global variable which tracks the kva we've
1189          * "allocated" while setting up pmaps.
1190          *
1191          * Prepare the list of physical memory available to the vm subsystem.
1192          */
1193         arm_physmem_exclude_region(abp->abp_physaddr,
1194                 pmap_preboot_get_pages(0) - abp->abp_physaddr, EXFLAG_NOALLOC);
1195         arm_physmem_init_kernel_globals();
1196
1197         init_param2(physmem);
1198         /* Init message buffer. */
1199         msgbufinit(msgbufp, msgbufsize);
1200         dbg_monitor_init();
1201         kdb_init();
1202         return ((void *)STACKALIGN(thread0.td_pcb));
1203
1204 }
1205
1206 #endif /* __ARM_ARCH < 6 */
1207 #endif /* FDT */