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