code:
/*	$OpenBSD: cpuswitch.S,v 1.14 2013/09/12 11:43:51 patrick Exp $	*/
/*	$NetBSD: cpuswitch.S,v 1.41 2003/11/15 08:44:18 scw Exp $	*/

/*
 * Copyright 2003 Wasabi Systems, Inc.
 * All rights reserved.
 *
 * Written by Steve C. Woodford for Wasabi Systems, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed for the NetBSD Project by
 *      Wasabi Systems, Inc.
 * 4. The name of Wasabi Systems, Inc. may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * Copyright (c) 1994-1998 Mark Brinicombe.
 * Copyright (c) 1994 Brini.
 * All rights reserved.
 *
 * This code is derived from software written for Brini by Mark Brinicombe
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Brini.
 * 4. The name of the company nor the name of the author may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY BRINI ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL BRINI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * RiscBSD kernel project
 *
 * cpuswitch.S
 *
 * cpu switching functions
 *
 * Created      : 15/10/94
 */

#include "assym.h"
#include <machine/cpu.h>
#include <machine/frame.h>
#include <machine/intr.h>
#include <machine/asm.h>

/* LINTSTUB: include <sys/param.h> */

/*
 * These are used for switching the translation table/DACR.
 * Since the vector page can be invalid for a short time, we must
 * disable both regular IRQs *and* FIQs.
 *
 * XXX: This is not necessary if the vector table is relocated.
 */
#define IRQdisableALL \
	mrs	r14, cpsr ; \
	orr	r14, r14, #(I32_bit | F32_bit) ; \
	msr	cpsr_c, r14

#define IRQenableALL \
	mrs	r14, cpsr ; \
	bic	r14, r14, #(I32_bit | F32_bit) ; \
	msr	cpsr_c, r14

	.text

.Lcpu_info_primary:
	.word	_C_LABEL(cpu_info_primary)
.Lcurproc:
	.word	_C_LABEL(cpu_info_primary) + CI_CURPROC
.Lcurpcb:
	.word	_C_LABEL(cpu_info_primary) + CI_CURPCB

.Lcpufuncs:
	.word	_C_LABEL(cpufuncs)

.Lcpu_do_powersave:
	.word	_C_LABEL(cpu_do_powersave)

.Lpmap_kernel_cstate:
	.word	(kernel_pmap_store + PMAP_CSTATE)

.Llast_cache_state_ptr:
	.word	_C_LABEL(pmap_cache_state)

/*
 * Idle loop, exercised while waiting for a process to wake up.
 */
ENTRY(cpu_idle_enter)
	mov	pc, lr

ENTRY(cpu_idle_cycle)
	stmfd	sp!, {r6, lr}

	ldr	r6, .Lcpu_do_powersave
	ldr	r6, [r6]		/* r6 = cpu_do_powersave */

	teq	r6, #0			/* cpu_do_powersave non zero? */
	ldrne	r6, .Lcpufuncs
	ldrne	r6, [r6, #(CF_SLEEP)]

	teq	r6, #0			/* Powersave idle? */
	beq	.Lidle_return		/* Nope. Just continue. */

	/*
	 * Before going into powersave idle mode, disable interrupts.
	 */
	IRQdisableALL
	mov	lr, pc
	mov	pc, r6			/* If so, do powersave idle */
	IRQenableALL

.Lidle_return:
	ldmfd	sp!, {r6, pc}

ENTRY(cpu_idle_leave)
	mov	pc, lr

/*
 * cpu_switchto(struct proc *oldproc, struct proc *newproc)
 *
 * Performs a process context switch from oldproc (which may be NULL)
 * to newproc.
 *
 * Arguments:
 *	r0	'struct proc *' of the context to switch from
 *	r1	'struct proc *' of the context to switch to
 */

ENTRY(cpu_switchto)
	stmfd	sp!, {r4-r7, lr}

#ifdef MULTIPROCESSOR
	/* XXX use curcpu() */
	ldr	r2, .Lcpu_info_primary
	str	r2, [r1, #(P_CPU)]
#else
	/* p->p_cpu initialized in fork1() for single-processor */
#endif

	/* Process is now on a processor. */
	mov	r2, #SONPROC			/* p->p_stat = SONPROC */
	strb	r2, [r1, #(P_STAT)]

	/* We have a new curproc now so make a note it */
	ldr	r7, .Lcurproc
	str	r1, [r7]

	/* Hook in a new pcb */
	ldr	r7, .Lcurpcb
	ldr	r6, [r7]			/* Remember the old PCB */
	ldr	r2, [r1, #(P_ADDR)]
	str	r2, [r7]

	/*
	 * If the old proc on entry to cpu_switch was zero then the
	 * process that called it was exiting. This means that we do
	 * not need to save the current context (we nevertheless need
	 * to clear the cache and TLB).
	 */
	teq	r0, #0x00000000
	beq	.Lswitch_exited

	/* Stage two: Save old context */

	/* Save all the registers in the old proc's pcb */
#ifndef __XSCALE__
	add	r7, r6, #(PCB_R8)
	stmia	r7, {r8-r13}
#else
	strd	r8, [r6, #(PCB_R8)]
	strd	r10, [r6, #(PCB_R10)]
	strd	r12, [r6, #(PCB_R12)]
#endif

.Lswitch_exited:
	/*
	 * NOTE: We can now use r8-r13 until it is time to restore
	 * them for the new process.
	 */

	/* Remember the old PCB. */
	mov	r8, r6

	/* Save new proc in r6 now. */
	mov	r6, r1

	/* Get the user structure for the new process in r9 */
	ldr	r9, [r6, #(P_ADDR)]

	/*
	 * This can be optimised... We know we want to go from SVC32
	 * mode to UND32 mode
	 */
        mrs	r3, cpsr
	bic	r2, r3, #(PSR_MODE)
	orr	r2, r2, #(PSR_UND32_MODE | I32_bit)
        msr	cpsr_c, r2

#ifdef notworthit
	teq	r0, #0x00000000
	strne	sp, [r8, #(PCB_UND_SP)]
#else
	str	sp, [r8, #(PCB_UND_SP)]
#endif

        msr	cpsr_c, r3		/* Restore the old mode */

	/* rem: r0 = old proc */
	/* rem: r1 = r6 = new process */
	/* rem: r8 = old PCB */
	/* rem: r9 = new PCB */

	/* What else needs to be saved  Only FPA stuff when that is supported */

	/* Third phase: restore saved context */

	/*
	 * Get the new L1 table pointer into r11.  If we're switching to
	 * an LWP with the same address space as the outgoing one, we can
	 * skip the cache purge and the TTB load.
	 *
	 * To avoid data dep stalls that would happen anyway, we try
	 * and get some useful work done in the mean time.
	 */
	ldr	r10, [r8, #(PCB_PAGEDIR)]	/* r10 = old L1 */
	ldr	r11, [r9, #(PCB_PAGEDIR)]	/* r11 = new L1 */

	ldr	r0, [r8, #(PCB_DACR)]		/* r0 = old DACR */
	ldr	r1, [r9, #(PCB_DACR)]		/* r1 = new DACR */
	ldr	r8, [r9, #(PCB_CSTATE)]		/* r8 = &new_pmap->pm_cstate */
	ldr	r5, .Llast_cache_state_ptr	/* Previous proc's cstate */

	teq	r10, r11			/* Same L1? */
	ldr	r5, [r5]
	cmpeq	r0, r1				/* Same DACR? */
	beq	.Lcs_context_switched		/* yes! */

	mov	r12, #0
	cmp	r5, #0				/* No last vm? (switch_exit) */
	beq	.Lcs_cache_purge_skipped	/* No, we can skip cache flsh */

	mov	r2, #DOMAIN_CLIENT
	cmp	r1, r2, lsl #(PMAP_DOMAIN_KERNEL * 2) /* Sw to kernel thread? */
	beq	.Lcs_cache_purge_skipped	/* Yup. Don't flush cache */

	cmp	r5, r8				/* Same userland VM space? */
	ldrneb	r12, [r5, #(CS_CACHE_ID)]	/* Last VM space cache state */

	/*
	 * We're definately switching to a new userland VM space,
	 * and the previous userland VM space has yet to be flushed
	 * from the cache/tlb.
	 *
	 * r12 holds the previous VM space's cs_cache_id state
	 */
	tst	r12, #0xff			/* Test cs_cache_id */
	beq	.Lcs_cache_purge_skipped	/* VM space is not in cache */

	/*
	 * Definitely need to flush the cache.
	 * Mark the old VM space as NOT being resident in the cache.
	 */
	mov	r2, #0x00000000
	strb	r2, [r5, #(CS_CACHE_ID)]
	strb	r2, [r5, #(CS_CACHE_D)]

	stmfd	sp!, {r0-r3}
	ldr	r1, .Lcpufuncs
	mov	lr, pc
	ldr	pc, [r1, #CF_IDCACHE_WBINV_ALL]
	ldmfd	sp!, {r0-r3}

.Lcs_cache_purge_skipped:
	/* rem: r1 = new DACR */
	/* rem: r5 = &old_pmap->pm_cstate (or NULL) */
	/* rem: r6 = new proc */
	/* rem: r8 = &new_pmap->pm_cstate */
	/* rem: r9 = new PCB */
	/* rem: r10 = old L1 */
	/* rem: r11 = new L1 */

	ldr	r7, [r9, #(PCB_PL1VEC)]

	/*
	 * At this point we need to kill IRQ's again.
	 *
	 * XXXSCW: Don't need to block FIQs if vectors have been relocated
	 */
	IRQdisableALL

	/*
	 * Ensure the vector table is accessible by fixing up the L1
	 */
	cmp	r7, #0			/* No need to fixup vector table? */
	ldrne	r2, [r7]		/* But if yes, fetch current value */
	ldrne	r0, [r9, #(PCB_L1VEC)]	/* Fetch new vector_page value */
	mcr	p15, 0, r1, c3, c0, 0	/* Update DACR for new context */
	cmpne	r2, r0			/* Stuffing the same value? */
#ifndef PMAP_INCLUDE_PTE_SYNC
	strne	r0, [r7]		/* Nope, update it */
#else
	beq	.Lcs_same_vector
	str	r0, [r7]		/* Otherwise, update it */

	/*
	 * Need to sync the cache to make sure that last store is
	 * visible to the MMU.
	 */
	ldr	r2, .Lcpufuncs
	mov	r0, r7
	mov	r1, #4
	mov	lr, pc
	ldr	pc, [r2, #CF_DCACHE_WB_RANGE]

.Lcs_same_vector:
#endif /* PMAP_INCLUDE_PTE_SYNC */

	cmp	r10, r11		/* Switching to the same L1? */
	ldr	r10, .Lcpufuncs
	beq	.Lcs_same_l1		/* Yup. */

	/*
	 * Do a full context switch, including full TLB flush.
	 */
	mov	r0, r11
	mov	lr, pc
	ldr	pc, [r10, #CF_CONTEXT_SWITCH]

	/*
	 * Mark the old VM space as NOT being resident in the TLB
	 */
	mov	r2, #0x00000000
	cmp	r5, #0
	strneh	r2, [r5, #(CS_TLB_ID)]
	b	.Lcs_context_switched

	/*
	 * We're switching to a different process in the same L1.
	 * In this situation, we only need to flush the TLB for the
	 * vector_page mapping, and even then only if r7 is non-NULL.
	 */
.Lcs_same_l1:
	cmp	r7, #0
	movne	r0, #0			/* We *know* vector_page's VA is 0x0 */
	movne	lr, pc
	ldrne	pc, [r10, #CF_TLB_FLUSHID_SE]

.Lcs_context_switched:
	/* rem: r8 = &new_pmap->pm_cstate */

	/* XXXSCW: Safe to re-enable FIQs here */

	/*
	 * The new VM space is live in the cache and TLB.
	 * Update its cache/tlb state, and if it's not the kernel
	 * pmap, update the 'last cache state' pointer.
	 */
	mov	r2, #-1
	ldr	r5, .Lpmap_kernel_cstate
	ldr	r0, .Llast_cache_state_ptr
	str	r2, [r8, #(CS_ALL)]
	cmp	r5, r8
	strne	r8, [r0]

	/* rem: r6 = new proc */
	/* rem: r9 = new PCB */

	/*
	 * This can be optimised... We know we want to go from SVC32
	 * mode to UND32 mode
	 */
        mrs	r3, cpsr
	bic	r2, r3, #(PSR_MODE)
	orr	r2, r2, #(PSR_UND32_MODE)
        msr	cpsr_c, r2

	ldr	sp, [r9, #(PCB_UND_SP)]

        msr	cpsr_c, r3		/* Restore the old mode */

	/* Restore all the save registers */
#ifndef __XSCALE__
	add	r7, r9, #PCB_R8
	ldmia	r7, {r8-r13}

	sub	r7, r7, #PCB_R8		/* restore PCB pointer */
#else
	mov	r7, r9
	ldr	r8, [r7, #(PCB_R8)]
	ldr	r9, [r7, #(PCB_R9)]
	ldr	r10, [r7, #(PCB_R10)]
	ldr	r11, [r7, #(PCB_R11)]
	ldr	r12, [r7, #(PCB_R12)]
	ldr	r13, [r7, #(PCB_SP)]
#endif

	/* rem: r6 = new proc */
	/* rem: r7 = new pcb */

	/* We can enable interrupts again */
	IRQenableALL

	/* rem: r6 = new proc */
	/* rem: r7 = new PCB */

.Lswitch_return:
	/*
	 * Pull the registers that got pushed when either savectx() or
	 * cpu_switch() was called and return.
	 */
	ldmfd	sp!, {r4-r7, pc}

/* LINTSTUB: Func: void savectx(struct pcb *pcb) */
ENTRY(savectx)
	/*
	 * r0 = pcb
	 */

	/* Push registers.*/
	stmfd	sp!, {r4-r7, lr}

	/* Store all the registers in the process's pcb */
#ifndef __XSCALE__
	add	r2, r0, #(PCB_R8)
	stmia	r2, {r8-r13}
#else
	strd	r8, [r0, #(PCB_R8)]
	strd	r10, [r0, #(PCB_R10)]
	strd	r12, [r0, #(PCB_R12)]
#endif

	/* Pull the regs of the stack */
	ldmfd	sp!, {r4-r7, pc}

ENTRY(proc_trampoline)
	mov	r0, #(IPL_NONE)
	bl	_C_LABEL(_spllower)

#ifdef MULTIPROCESSOR
	bl	_C_LABEL(proc_trampoline_mp)
#endif
	mov	r0, r5
	mov	r1, sp
	mov	lr, pc
	mov	pc, r4

	/* Kill irq's */
        mrs     r0, cpsr
        orr     r0, r0, #(I32_bit)
        msr     cpsr_c, r0

	PULLFRAME

	movs	pc, lr			/* Exit */


code:
/*	$OpenBSD: cpuswitch7.S,v 1.3 2013/09/12 11:43:51 patrick Exp $	*/
/*	$NetBSD: cpuswitch.S,v 1.41 2003/11/15 08:44:18 scw Exp $	*/

/*
 * Copyright 2003 Wasabi Systems, Inc.
 * All rights reserved.
 *
 * Written by Steve C. Woodford for Wasabi Systems, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed for the NetBSD Project by
 *      Wasabi Systems, Inc.
 * 4. The name of Wasabi Systems, Inc. may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * Copyright (c) 1994-1998 Mark Brinicombe.
 * Copyright (c) 1994 Brini.
 * All rights reserved.
 *
 * This code is derived from software written for Brini by Mark Brinicombe
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Brini.
 * 4. The name of the company nor the name of the author may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY BRINI ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL BRINI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * RiscBSD kernel project
 *
 * cpuswitch.S
 *
 * cpu switching functions
 *
 * Created      : 15/10/94
 */

#include "assym.h"
#include <machine/cpu.h>
#include <machine/frame.h>
#include <machine/intr.h>
#include <machine/asm.h>

/* LINTSTUB: include <sys/param.h> */

/*
 * These are used for switching the translation table/DACR.
 * Since the vector page can be invalid for a short time, we must
 * disable both regular IRQs *and* FIQs.
 *
 * XXX: This is not necessary if the vector table is relocated.
 */
#define IRQdisableALL \
	mrs	r14, cpsr ; \
	orr	r14, r14, #(I32_bit | F32_bit) ; \
	msr	cpsr_c, r14

#define IRQenableALL \
	mrs	r14, cpsr ; \
	bic	r14, r14, #(I32_bit | F32_bit) ; \
	msr	cpsr_c, r14

	.text

.Lcpu_info_primary:
	.word	_C_LABEL(cpu_info_primary)
.Lcurproc:
	.word	_C_LABEL(cpu_info_primary) + CI_CURPROC
.Lcurpcb:
	.word	_C_LABEL(cpu_info_primary) + CI_CURPCB

.Lcpufuncs:
	.word	_C_LABEL(cpufuncs)

.Lcpu_do_powersave:
	.word	_C_LABEL(cpu_do_powersave)

/*
 * Idle loop, exercised while waiting for a process to wake up.
 */
ENTRY(cpu_idle_enter)
	mov	pc, lr

ENTRY(cpu_idle_cycle)
	stmfd	sp!, {r6, lr}

	ldr	r6, .Lcpu_do_powersave
	ldr	r6, [r6]		/* r6 = cpu_do_powersave */

	teq	r6, #0			/* cpu_do_powersave non zero? */
	ldrne	r6, .Lcpufuncs
	ldrne	r6, [r6, #(CF_SLEEP)]

	teq	r6, #0			/* Powersave idle? */
	beq	.Lidle_return		/* Nope. Just continue. */

	/*
	 * Before going into powersave idle mode, disable interrupts.
	 */
	IRQdisableALL
	mov	lr, pc
	mov	pc, r6			/* If so, do powersave idle */
	IRQenableALL

.Lidle_return:
	ldmfd	sp!, {r6, pc}

ENTRY(cpu_idle_leave)
	mov	pc, lr

/*
 * cpu_switchto(struct proc *oldproc, struct proc *newproc)
 *
 * Performs a process context switch from oldproc (which may be NULL)
 * to newproc.
 *
 * Arguments:
 *	r0	'struct proc *' of the context to switch from
 *	r1	'struct proc *' of the context to switch to
 */

ENTRY(cpu_switchto)
	stmfd	sp!, {r4-r7, lr}

#ifdef MULTIPROCESSOR
	/* XXX use curcpu() */
	ldr	r2, .Lcpu_info_primary
	str	r2, [r1, #(P_CPU)]
#else
	/* p->p_cpu initialized in fork1() for single-processor */
#endif

	/* Process is now on a processor. */
	mov	r2, #SONPROC			/* p->p_stat = SONPROC */
	strb	r2, [r1, #(P_STAT)]

	/* We have a new curproc now so make a note it */
	ldr	r7, .Lcurproc
	str	r1, [r7]

	/* Hook in a new pcb */
	ldr	r7, .Lcurpcb
	ldr	r6, [r7]			/* Remember the old PCB */
	ldr	r2, [r1, #(P_ADDR)]
	str	r2, [r7]

	/*
	 * If the old proc on entry to cpu_switch was zero then the
	 * process that called it was exiting. This means that we do
	 * not need to save the current context (we nevertheless need
	 * to clear the cache and TLB).
	 */
	teq	r0, #0x00000000
	beq	.Lswitch_exited

	/* Stage two: Save old context */

	/* Save all the registers in the old proc's pcb */
#ifndef __XSCALE__
	add	r7, r6, #(PCB_R8)
	stmia	r7, {r8-r13}
#else
	strd	r8, [r6, #(PCB_R8)]
	strd	r10, [r6, #(PCB_R10)]
	strd	r12, [r6, #(PCB_R12)]
#endif

.Lswitch_exited:
	/*
	 * NOTE: We can now use r8-r13 until it is time to restore
	 * them for the new process.
	 */

	/* Remember the old PCB. */
	mov	r8, r6

	/* Save new proc in r6 now. */
	mov	r6, r1

	/* Get the user structure for the new process in r9 */
	ldr	r9, [r6, #(P_ADDR)]

	/*
	 * This can be optimised... We know we want to go from SVC32
	 * mode to UND32 mode
	 */
        mrs	r3, cpsr
	bic	r2, r3, #(PSR_MODE)
	orr	r2, r2, #(PSR_UND32_MODE | I32_bit)
        msr	cpsr_c, r2

#ifdef notworthit
	teq	r0, #0x00000000
	strne	sp, [r8, #(PCB_UND_SP)]
#else
	str	sp, [r8, #(PCB_UND_SP)]
#endif

        msr	cpsr_c, r3		/* Restore the old mode */

	/* rem: r0 = old proc */
	/* rem: r1 = r6 = new process */
	/* rem: r8 = old PCB */
	/* rem: r9 = new PCB */

	/* What else needs to be saved  Only FPA stuff when that is supported */

	/* Third phase: restore saved context */

	/*
	 * Get the new L1 table pointer into r11.  If we're switching to
	 * an LWP with the same address space as the outgoing one, we can
	 * skip the cache purge and the TTB load.
	 *
	 * To avoid data dep stalls that would happen anyway, we try
	 * and get some useful work done in the mean time.
	 */
	ldr	r10, [r8, #(PCB_PAGEDIR)]	/* r10 = old L1 */
	ldr	r11, [r9, #(PCB_PAGEDIR)]	/* r11 = new L1 */

	ldr	r0, [r8, #(PCB_DACR)]		/* r0 = old DACR */
	ldr	r1, [r9, #(PCB_DACR)]		/* r1 = new DACR */

	teq	r10, r11			/* Same L1? */
	cmpeq	r0, r1				/* Same DACR? */
	beq	.Lcs_context_switched		/* yes! */

	mov	r2, #DOMAIN_CLIENT
	cmp	r1, r2, lsl #(PMAP_DOMAIN_KERNEL * 2) /* Sw to kernel thread? */
	beq	.Lcs_cache_purge_skipped	/* Yup. Don't flush cache */

	stmfd	sp!, {r0-r3}
	ldr	r1, .Lcpufuncs
	mov	lr, pc
	ldr	pc, [r1, #CF_ICACHE_SYNC_ALL]
	ldmfd	sp!, {r0-r3}

.Lcs_cache_purge_skipped:
	/* rem: r1 = new DACR */
	/* rem: r6 = new proc */
	/* rem: r9 = new PCB */
	/* rem: r10 = old L1 */
	/* rem: r11 = new L1 */

	ldr	r7, [r9, #(PCB_PL1VEC)]

	/*
	 * At this point we need to kill IRQ's again.
	 *
	 * XXXSCW: Don't need to block FIQs if vectors have been relocated
	 */
	IRQdisableALL

	/*
	 * Ensure the vector table is accessible by fixing up the L1
	 */
	cmp	r7, #0			/* No need to fixup vector table? */
	ldrne	r2, [r7]		/* But if yes, fetch current value */
	ldrne	r0, [r9, #(PCB_L1VEC)]	/* Fetch new vector_page value */
	mcr	p15, 0, r1, c3, c0, 0	/* Update DACR for new context */
	cmpne	r2, r0			/* Stuffing the same value? */
#ifndef PMAP_INCLUDE_PTE_SYNC
	strne	r0, [r7]		/* Nope, update it */
#else
	beq	.Lcs_same_vector
	str	r0, [r7]		/* Otherwise, update it */

	/*
	 * Need to sync the cache to make sure that last store is
	 * visible to the MMU.
	 */
	ldr	r2, .Lcpufuncs
	mov	r0, r7
	mov	r1, #4
	mov	lr, pc
	ldr	pc, [r2, #CF_DCACHE_WB_RANGE]

.Lcs_same_vector:
#endif /* PMAP_INCLUDE_PTE_SYNC */

	cmp	r10, r11		/* Switching to the same L1? */
	ldr	r10, .Lcpufuncs
	beq	.Lcs_same_l1		/* Yup. */

	/*
	 * Do a full context switch, including full TLB flush.
	 */
	mov	r0, r11
	mov	lr, pc
	ldr	pc, [r10, #CF_CONTEXT_SWITCH]

	b	.Lcs_context_switched

	/*
	 * We're switching to a different process in the same L1.
	 * In this situation, we only need to flush the TLB for the
	 * vector_page mapping, and even then only if r7 is non-NULL.
	 */
.Lcs_same_l1:
	cmp	r7, #0
	movne	r0, #0			/* We *know* vector_page's VA is 0x0 */
	movne	lr, pc
	ldrne	pc, [r10, #CF_TLB_FLUSHID_SE]

.Lcs_context_switched:

	/* XXXSCW: Safe to re-enable FIQs here */

	/* rem: r6 = new proc */
	/* rem: r9 = new PCB */

	/*
	 * This can be optimised... We know we want to go from SVC32
	 * mode to UND32 mode
	 */
        mrs	r3, cpsr
	bic	r2, r3, #(PSR_MODE)
	orr	r2, r2, #(PSR_UND32_MODE)
        msr	cpsr_c, r2

	ldr	sp, [r9, #(PCB_UND_SP)]

        msr	cpsr_c, r3		/* Restore the old mode */

	/* Restore all the save registers */
#ifndef __XSCALE__
	add	r7, r9, #PCB_R8
	ldmia	r7, {r8-r13}

	sub	r7, r7, #PCB_R8		/* restore PCB pointer */
#else
	mov	r7, r9
	ldr	r8, [r7, #(PCB_R8)]
	ldr	r9, [r7, #(PCB_R9)]
	ldr	r10, [r7, #(PCB_R10)]
	ldr	r11, [r7, #(PCB_R11)]
	ldr	r12, [r7, #(PCB_R12)]
	ldr	r13, [r7, #(PCB_SP)]
#endif

	/* rem: r6 = new proc */
	/* rem: r7 = new pcb */

	/* We can enable interrupts again */
	IRQenableALL

	/* rem: r6 = new proc */
	/* rem: r7 = new PCB */

.Lswitch_return:
	/*
	 * Pull the registers that got pushed when either savectx() or
	 * cpu_switch() was called and return.
	 */
	ldmfd	sp!, {r4-r7, pc}

/* LINTSTUB: Func: void savectx(struct pcb *pcb) */
ENTRY(savectx)
	/*
	 * r0 = pcb
	 */

	/* Push registers.*/
	stmfd	sp!, {r4-r7, lr}

	/* Store all the registers in the process's pcb */
#ifndef __XSCALE__
	add	r2, r0, #(PCB_R8)
	stmia	r2, {r8-r13}
#else
	strd	r8, [r0, #(PCB_R8)]
	strd	r10, [r0, #(PCB_R10)]
	strd	r12, [r0, #(PCB_R12)]
#endif

	/* Pull the regs of the stack */
	ldmfd	sp!, {r4-r7, pc}

ENTRY(proc_trampoline)
	mov	r0, #(IPL_NONE)
	bl	_C_LABEL(_spllower)

#ifdef MULTIPROCESSOR
	bl	_C_LABEL(proc_trampoline_mp)
#endif
	mov	r0, r5
	mov	r1, sp
	mov	lr, pc
	mov	pc, r4

	/* Kill irq's */
        mrs     r0, cpsr
        orr     r0, r0, #(I32_bit)
        msr     cpsr_c, r0

	PULLFRAME

	movs	pc, lr			/* Exit */

license: unknown


code:
/*	$OpenBSD: db_disasm.c,v 1.1 2004/02/01 05:09:48 drahn Exp $	*/
/*	$NetBSD: db_disasm.c,v 1.4 2003/07/15 00:24:38 lukem Exp $	*/

/*
 * Copyright (c) 1996 Mark Brinicombe.
 * Copyright (c) 1996 Brini.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Brini.
 * 4. The name of the company nor the name of the author may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY BRINI ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL BRINI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/param.h>
#include <machine/db_machdep.h>
#include <ddb/db_interface.h>
#include <ddb/db_sym.h>
#include <ddb/db_output.h>
#include <ddb/db_access.h>

#include <arch/arm/arm/disassem.h>

/* Glue code to interface db_disasm to the generic ARM disassembler */

static db_expr_t db_disasm_read_word(db_expr_t);
static void db_disasm_printaddr(db_expr_t);

static const disasm_interface_t db_disasm_interface = {
	db_disasm_read_word, db_disasm_printaddr, db_printf
};

static db_expr_t
db_disasm_read_word(db_expr_t address)
{

	return db_get_value(address, 4, 0);
}

static void
db_disasm_printaddr(db_expr_t address)
{

	db_printsym((db_addr_t)address, DB_STGY_ANY, db_printf);
}

vaddr_t
db_disasm(vaddr_t loc, boolean_t altfmt)
{

	return disasm(&db_disasm_interface, loc, altfmt);
}

/* End of db_disasm.c */


code:
/*	$OpenBSD: db_interface.c,v 1.9 2014/11/16 12:30:56 deraadt Exp $	*/
/*	$NetBSD: db_interface.c,v 1.34 2003/10/26 23:11:15 chris Exp $	*/

/*
 * Copyright (c) 1996 Scott K. Stevens
 *
 * Mach Operating System
 * Copyright (c) 1991,1990 Carnegie Mellon University
 * All Rights Reserved.
 *
 * Permission to use, copy, modify and distribute this software and its
 * documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * Carnegie Mellon requests users of this software to return to
 *
 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
 *  School of Computer Science
 *  Carnegie Mellon University
 *  Pittsburgh PA 15213-3890
 *
 * any improvements or extensions that they make and grant Carnegie the
 * rights to redistribute these changes.
 *
 *	From: db_interface.c,v 2.4 1991/02/05 17:11:13 mrt (CMU)
 */

/*
 * Interface to new debugger.
 */
#include <sys/param.h>
#include <sys/proc.h>
#include <sys/reboot.h>
#include <sys/systm.h>	/* just for boothowto */
#include <sys/exec.h>

#include <uvm/uvm_extern.h>

#include <arm/db_machdep.h>
#include <machine/pmap.h>
#include <arm/undefined.h>
#include <ddb/db_access.h>
#include <ddb/db_command.h>
#include <ddb/db_output.h>
#include <ddb/db_variables.h>
#include <ddb/db_sym.h>
#include <ddb/db_extern.h>
#include <ddb/db_interface.h>
#include <dev/cons.h>

static long nil;

int db_access_und_sp (struct db_variable *, db_expr_t *, int);
int db_access_abt_sp (struct db_variable *, db_expr_t *, int);
int db_access_irq_sp (struct db_variable *, db_expr_t *, int);
u_int db_fetch_reg (int, db_regs_t *);

int db_trapper (u_int, u_int, trapframe_t *, int);

struct db_variable db_regs[] = {
	{ "spsr", (long *)&DDB_REGS->tf_spsr, FCN_NULL, },
	{ "r0", (long *)&DDB_REGS->tf_r0, FCN_NULL, },
	{ "r1", (long *)&DDB_REGS->tf_r1, FCN_NULL, },
	{ "r2", (long *)&DDB_REGS->tf_r2, FCN_NULL, },
	{ "r3", (long *)&DDB_REGS->tf_r3, FCN_NULL, },
	{ "r4", (long *)&DDB_REGS->tf_r4, FCN_NULL, },
	{ "r5", (long *)&DDB_REGS->tf_r5, FCN_NULL, },
	{ "r6", (long *)&DDB_REGS->tf_r6, FCN_NULL, },
	{ "r7", (long *)&DDB_REGS->tf_r7, FCN_NULL, },
	{ "r8", (long *)&DDB_REGS->tf_r8, FCN_NULL, },
	{ "r9", (long *)&DDB_REGS->tf_r9, FCN_NULL, },
	{ "r10", (long *)&DDB_REGS->tf_r10, FCN_NULL, },
	{ "r11", (long *)&DDB_REGS->tf_r11, FCN_NULL, },
	{ "r12", (long *)&DDB_REGS->tf_r12, FCN_NULL, },
	{ "usr_sp", (long *)&DDB_REGS->tf_usr_sp, FCN_NULL, },
	{ "usr_lr", (long *)&DDB_REGS->tf_usr_lr, FCN_NULL, },
	{ "svc_sp", (long *)&DDB_REGS->tf_svc_sp, FCN_NULL, },
	{ "svc_lr", (long *)&DDB_REGS->tf_svc_lr, FCN_NULL, },
	{ "pc", (long *)&DDB_REGS->tf_pc, FCN_NULL, },
	{ "und_sp", (long *)&nil, db_access_und_sp, },
	{ "abt_sp", (long *)&nil, db_access_abt_sp, },
	{ "irq_sp", (long *)&nil, db_access_irq_sp, },
};

extern label_t       *db_recover;

struct db_variable * db_eregs = db_regs + nitems(db_regs);

int	db_active = 0;

int
db_access_und_sp(struct db_variable *vp, db_expr_t *valp, int rw)
{

	if (rw == DB_VAR_GET)
		*valp = get_stackptr(PSR_UND32_MODE);
	return(0);
}

int
db_access_abt_sp(struct db_variable *vp, db_expr_t *valp, int rw)
{

	if (rw == DB_VAR_GET)
		*valp = get_stackptr(PSR_ABT32_MODE);
	return(0);
}

int
db_access_irq_sp(struct db_variable *vp, db_expr_t *valp, int rw)
{

	if (rw == DB_VAR_GET)
		*valp = get_stackptr(PSR_IRQ32_MODE);
	return(0);
}

#ifdef DDB
/*
 *  kdb_trap - field a TRACE or BPT trap
 */
int
kdb_trap(int type, db_regs_t *regs)
{
	int s;

	switch (type) {
	case T_BREAKPOINT:	/* breakpoint */
	case -1:		/* keyboard interrupt */
		break;
	default:
		if (db_recover != 0) {
			/* This will longjmp back into db_command_loop() */
			db_error("Faulted in DDB; continuing...\n");
			/*NOTREACHED*/
		}
	}

	/* Should switch to kdb`s own stack here. */

	ddb_regs = *regs;

	s = splhigh();
	db_active++;
	cnpollc(TRUE);
	db_trap(type, 0/*code*/);
	cnpollc(FALSE);
	db_active--;
	splx(s);

	*regs = ddb_regs;

	return (1);
}
#endif

static int db_validate_address(vaddr_t addr);

static int
db_validate_address(vaddr_t addr)
{
	struct proc *p = curproc;
	struct pmap *pmap;

	if (!p || !p->p_vmspace || !p->p_vmspace->vm_map.pmap ||
#ifndef ARM32_NEW_VM_LAYOUT
	    addr >= VM_MAXUSER_ADDRESS
#else
	    addr >= VM_MIN_KERNEL_ADDRESS
#endif
	    )
		pmap = pmap_kernel();
	else
		pmap = p->p_vmspace->vm_map.pmap;

	return (pmap_extract(pmap, addr, NULL) == FALSE);
}

/*
 * Read bytes from kernel address space for debugger.
 */
void
db_read_bytes(addr, size, data)
	vaddr_t	addr;
	size_t	size;
	char	*data;
{
	char	*src = (char *)addr;

	if (db_validate_address((u_int)src)) {
		db_printf("address %p is invalid\n", src);
		return;
	}

	if (size == 4 && (addr & 3) == 0 && ((u_int32_t)data & 3) == 0) {
		*((int*)data) = *((int*)src);
		return;
	}

	if (size == 2 && (addr & 1) == 0 && ((u_int32_t)data & 1) == 0) {
		*((short*)data) = *((short*)src);
		return;
	}

	while (size-- > 0) {
		if (db_validate_address((u_int)src)) {
			db_printf("address %p is invalid\n", src);
			return;
		}
		*data++ = *src++;
	}
}

static void
db_write_text(vaddr_t addr, size_t size, char *data)
{
	struct pmap *pmap = pmap_kernel();
	pd_entry_t *pde, oldpde, tmppde;
	pt_entry_t *pte, oldpte, tmppte;
	vaddr_t pgva;
	size_t limit, savesize;
	char *dst;

	/* XXX: gcc */
	oldpte = 0;

	if ((savesize = size) == 0)
		return;

	dst = (char *) addr;

	do {
		/* Get the PDE of the current VA. */
		if (pmap_get_pde_pte(pmap, (vaddr_t) dst, &pde, &pte) == FALSE)
			goto no_mapping;
		switch ((oldpde = *pde) & L1_TYPE_MASK) {
		case L1_TYPE_S:
			pgva = (vaddr_t)dst & L1_S_FRAME;
			limit = L1_S_SIZE - ((vaddr_t)dst & L1_S_OFFSET);

			tmppde = oldpde | L1_S_PROT(PTE_KERNEL, PROT_WRITE);
			*pde = tmppde;
			PTE_SYNC(pde);
			break;

		case L1_TYPE_C:
			pgva = (vaddr_t)dst & L2_S_FRAME;
			limit = L2_S_SIZE - ((vaddr_t)dst & L2_S_OFFSET);

			if (pte == NULL)
				goto no_mapping;
			oldpte = *pte;
			tmppte = oldpte | L2_S_PROT(PTE_KERNEL, PROT_WRITE);
			*pte = tmppte;
			PTE_SYNC(pte);
			break;

		default:
		no_mapping:
			printf(" address 0x%08lx not a valid page\n",
			    (vaddr_t) dst);
			return;
		}
		cpu_tlb_flushD_SE(pgva);
		cpu_cpwait();

		if (limit > size)
			limit = size;
		size -= limit;

		/*
		 * Page is now writable.  Do as much access as we
		 * can in this page.
		 */
		for (; limit > 0; limit--)
			*dst++ = *data++;

		/*
		 * Restore old mapping permissions.
		 */
		switch (oldpde & L1_TYPE_MASK) {
		case L1_TYPE_S:
			*pde = oldpde;
			PTE_SYNC(pde);
			break;

		case L1_TYPE_C:
			*pte = oldpte;
			PTE_SYNC(pte);
			break;
		}
		cpu_tlb_flushD_SE(pgva);
		cpu_cpwait();

	} while (size != 0);

	/* Sync the I-cache. */
	cpu_icache_sync_range(addr, savesize);
}

/*
 * Write bytes to kernel address space for debugger.
 */
void
db_write_bytes(vaddr_t addr, size_t size, char *data)
{
	extern char etext[];
	extern char kernel_text[];
	char *dst;
	size_t loop;

	/* If any part is in kernel text, use db_write_text() */
	if (addr >= (vaddr_t) kernel_text && addr < (vaddr_t) etext) {
		db_write_text(addr, size, data);
		return;
	}

	dst = (char *)addr;
	loop = size;
	while (loop-- > 0) {
		if (db_validate_address((u_int)dst)) {
			db_printf("address %p is invalid\n", dst);
			return;
		}
		*dst++ = *data++;
	}
	/* make sure the caches and memory are in sync */
	cpu_icache_sync_range(addr, size);

	/* In case the current page tables have been modified ... */
	cpu_tlb_flushID();
	cpu_cpwait();
}

void
Debugger(void)
{
	asm(".word	0xe7ffffff");
}

struct db_command db_machine_command_table[] = {
	{ "frame",	db_show_frame_cmd,	0, NULL },
#ifdef ARM32_DB_COMMANDS
	ARM32_DB_COMMANDS,
#endif
	{ NULL, 	NULL, 			0, NULL }
};

int
db_trapper(u_int addr, u_int inst, trapframe_t *frame, int fault_code)
{

	if (fault_code == 0) {
		if ((inst & ~INSN_COND_MASK) == (BKPT_INST & ~INSN_COND_MASK)) {
			kdb_trap(T_BREAKPOINT, frame);
			frame->tf_pc += INSN_SIZE;
		} else
			kdb_trap(-1, frame);
	} else
		return (1);
	return (0);
}

extern u_int esym;
extern u_int end;

static struct undefined_handler db_uh;

void
db_machine_init(void)
{
	/*
	 * We get called before malloc() is available, so supply a static
	 * struct undefined_handler.
	 */
	db_uh.uh_handler = db_trapper;
	install_coproc_handler_static(0, &db_uh);

	db_machine_commands_install(db_machine_command_table);
}

u_int
db_fetch_reg(int reg, db_regs_t *db_regs)
{

	switch (reg) {
	case 0:
		return (db_regs->tf_r0);
	case 1:
		return (db_regs->tf_r1);
	case 2:
		return (db_regs->tf_r2);
	case 3:
		return (db_regs->tf_r3);
	case 4:
		return (db_regs->tf_r4);
	case 5:
		return (db_regs->tf_r5);
	case 6:
		return (db_regs->tf_r6);
	case 7:
		return (db_regs->tf_r7);
	case 8:
		return (db_regs->tf_r8);
	case 9:
		return (db_regs->tf_r9);
	case 10:
		return (db_regs->tf_r10);
	case 11:
		return (db_regs->tf_r11);
	case 12:
		return (db_regs->tf_r12);
	case 13:
		return (db_regs->tf_svc_sp);
	case 14:
		return (db_regs->tf_svc_lr);
	case 15:
		return (db_regs->tf_pc);
	default:
		panic("db_fetch_reg: botch");
	}
}

db_addr_t
db_branch_taken(u_int insn, db_addr_t pc, db_regs_t *db_regs)
{
	u_int addr, nregs;

	switch ((insn >> 24) & 0xf) {
	case 0xa:	/* b ... */
	case 0xb:	/* bl ... */
		addr = ((insn << 2) & 0x03ffffff);
		if (addr & 0x02000000)
			addr |= 0xfc000000;
		return (pc + 8 + addr);
	case 0x7:	/* ldr pc, [pc, reg, lsl #2] */
		addr = db_fetch_reg(insn & 0xf, db_regs);
		addr = pc + 8 + (addr << 2);
		db_read_bytes(addr, 4, (char *)&addr);
		return (addr);
	case 0x1:	/* mov pc, reg */
		addr = db_fetch_reg(insn & 0xf, db_regs);
		return (addr);
	case 0x8:	/* ldmxx reg, {..., pc} */
	case 0x9:
		addr = db_fetch_reg((insn >> 16) & 0xf, db_regs);
		nregs = (insn  & 0x5555) + ((insn  >> 1) & 0x5555);
		nregs = (nregs & 0x3333) + ((nregs >> 2) & 0x3333);
		nregs = (nregs + (nregs >> 4)) & 0x0f0f;
		nregs = (nregs + (nregs >> 8)) & 0x001f;
		switch ((insn >> 23) & 0x3) {
		case 0x0:	/* ldmda */
			addr = addr - 0;
			break;
		case 0x1:	/* ldmia */
			addr = addr + 0 + ((nregs - 1) << 2);
			break;
		case 0x2:	/* ldmdb */
			addr = addr - 4;
			break;
		case 0x3:	/* ldmib */
			addr = addr + 4 + ((nregs - 1) << 2);
			break;
		}
		db_read_bytes(addr, 4, (char *)&addr);
		return (addr);
	default:
		panic("branch_taken: botch");
	}
}


code:
/*	$OpenBSD: db_machdep.c,v 1.5 2014/05/08 21:17:00 miod Exp $	*/
/*	$NetBSD: db_machdep.c,v 1.8 2003/07/15 00:24:41 lukem Exp $	*/

/*
 * Copyright (c) 1996 Mark Brinicombe
 *
 * Mach Operating System
 * Copyright (c) 1991,1990 Carnegie Mellon University
 * All Rights Reserved.
 *
 * Permission to use, copy, modify and distribute this software and its
 * documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * Carnegie Mellon requests users of this software to return to
 *
 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
 *  School of Computer Science
 *  Carnegie Mellon University
 *  Pittsburgh PA 15213-3890
 *
 * any improvements or extensions that they make and grant Carnegie the
 * rights to redistribute these changes.
 */

#include <sys/param.h>
#include <sys/proc.h>
#include <sys/vnode.h>
#include <sys/systm.h>

#include <arm/db_machdep.h>

#include <ddb/db_access.h>
#include <ddb/db_sym.h>
#include <ddb/db_output.h>

void
db_show_frame_cmd(db_expr_t addr, int have_addr, db_expr_t count, char *modif)
{
	struct trapframe *frame;

	if (!have_addr) {
		db_printf("frame address must be specified\n");
		return;
	}

	frame = (struct trapframe *)addr;

	db_printf("frame address = %08x  ", (u_int)frame);
	db_printf("spsr=%08lx\n", frame->tf_spsr);
	db_printf("r0 =%08lx r1 =%08lx r2 =%08lx r3 =%08lx\n",
	    frame->tf_r0, frame->tf_r1, frame->tf_r2, frame->tf_r3);
	db_printf("r4 =%08lx r5 =%08lx r6 =%08lx r7 =%08lx\n",
	    frame->tf_r4, frame->tf_r5, frame->tf_r6, frame->tf_r7);
	db_printf("r8 =%08lx r9 =%08lx r10=%08lx r11=%08lx\n",
	    frame->tf_r8, frame->tf_r9, frame->tf_r10, frame->tf_r11);
	db_printf("r12=%08lx r13=%08lx r14=%08lx r15=%08lx\n",
	    frame->tf_r12, frame->tf_usr_sp, frame->tf_usr_lr, frame->tf_pc);
	db_printf("slr=%08lx\n", frame->tf_svc_lr);
}


code:
/*	$OpenBSD: db_trace.c,v 1.5 2011/09/20 22:02:10 miod Exp $	*/
/*	$NetBSD: db_trace.c,v 1.8 2003/01/17 22:28:48 thorpej Exp $	*/

/*
 * Copyright (c) 2000, 2001 Ben Harris
 * Copyright (c) 1996 Scott K. Stevens
 *
 * Mach Operating System
 * Copyright (c) 1991,1990 Carnegie Mellon University
 * All Rights Reserved.
 *
 * Permission to use, copy, modify and distribute this software and its
 * documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * Carnegie Mellon requests users of this software to return to
 *
 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
 *  School of Computer Science
 *  Carnegie Mellon University
 *  Pittsburgh PA 15213-3890
 *
 * any improvements or extensions that they make and grant Carnegie the
 * rights to redistribute these changes.
 */

#include <sys/param.h>

#include <sys/proc.h>
#include <sys/user.h>
#include <arm/armreg.h>
#include <arm/cpufunc.h>
#include <machine/db_machdep.h>

#include <ddb/db_access.h>
#include <ddb/db_interface.h>
#include <ddb/db_sym.h>
#include <ddb/db_output.h>

db_regs_t ddb_regs;

#define INKERNEL(va)	(((vaddr_t)(va)) >= VM_MIN_KERNEL_ADDRESS)

/*
 * APCS stack frames are awkward beasts, so I don't think even trying to use
 * a structure to represent them is a good idea.
 *
 * Here's the diagram from the APCS.  Increasing address is _up_ the page.
 *
 *          save code pointer       [fp]        <- fp points to here
 *          return link value       [fp, #-4]
 *          return sp value         [fp, #-8]
 *          return fp value         [fp, #-12]
 *          [saved v7 value]
 *          [saved v6 value]
 *          [saved v5 value]
 *          [saved v4 value]
 *          [saved v3 value]
 *          [saved v2 value]
 *          [saved v1 value]
 *          [saved a4 value]
 *          [saved a3 value]
 *          [saved a2 value]
 *          [saved a1 value]
 *
 * The save code pointer points twelve bytes beyond the start of the
 * code sequence (usually a single STM) that created the stack frame.
 * We have to disassemble it if we want to know which of the optional
 * fields are actually present.
 */

#define FR_SCP	(0)
#define FR_RLV	(-1)
#define FR_RSP	(-2)
#define FR_RFP	(-3)

void
db_stack_trace_print(addr, have_addr, count, modif, pr)
	db_expr_t       addr;
	int             have_addr;
	db_expr_t       count;
	char            *modif;
	int		(*pr) (const char *, ...);
{
	u_int32_t	*frame, *lastframe;
	char c, *cp = modif;
	boolean_t	kernel_only = TRUE;
	boolean_t	trace_thread = FALSE;
	int	scp_offset;

	while ((c = *cp++) != 0) {
		if (c == 'u')
			kernel_only = FALSE;
		if (c == 't')
			trace_thread = TRUE;
	}

	if (!have_addr)
		frame = (u_int32_t *)(DDB_REGS->tf_r11);
	else {
		if (trace_thread) {
			struct proc *p;
			struct user *u;
			(*pr) ("trace: pid %d ", (int)addr);
			p = pfind(addr);
			if (p == NULL) {
				(*pr)("not found\n");
				return;
			}
			u = p->p_addr;
			frame = (u_int32_t *)(u->u_pcb.pcb_un.un_32.pcb32_r11);
			(*pr)("at %p\n", frame);
		} else
			frame = (u_int32_t *)(addr);
	}
	lastframe = NULL;
	scp_offset = -(get_pc_str_offset() >> 2);

	while (count-- && frame != NULL) {
		db_addr_t	scp;
		u_int32_t	savecode;
		int		r, n;
		u_int32_t	*rp;
		const char	*sep;

		/*
		 * In theory, the SCP isn't guaranteed to be in the function
		 * that generated the stack frame.  We hope for the best.
		 */
		scp = frame[FR_SCP];

		db_printsym(scp, DB_STGY_PROC, pr);
		(*pr)("\n\tscp=0x%08x rlv=0x%08x (", scp, frame[FR_RLV]);
		db_printsym(frame[FR_RLV], DB_STGY_PROC, pr);
		(*pr)(")\n\trsp=0x%08x rfp=0x%08x",
		    frame[FR_RSP], frame[FR_RFP]);

		savecode = ((u_int32_t *)scp)[scp_offset];
		if ((savecode & 0x0e100000) == 0x08000000) {
			/* Looks like an STM */
			rp = frame - 4;
			n = 0;
			for (r = 10; r >= 0; r--) {
				if (savecode & (1 << r)) {
					sep = n++ % 4 == 0 ? "\n\t" : " ";
					(*pr)("%sr%d=0x%08x", sep, r, *rp--);
				}
			}
		}

		(*pr)("\n");

		/*
		 * Switch to next frame up
		 */
		if (frame[FR_RFP] == 0)
			break; /* Top of stack */

		lastframe = frame;
		frame = (u_int32_t *)(frame[FR_RFP]);

		if (INKERNEL((int)frame)) {
			/* staying in kernel */
			if (frame <= lastframe) {
				(*pr)("Bad frame pointer: %p\n", frame);
				break;
			}
		} else if (INKERNEL((int)lastframe)) {
			/* switch from user to kernel */
			if (kernel_only)
				break;	/* kernel stack only */
		} else {
			/* in user */
			if (frame <= lastframe) {
				(*pr)("Bad user frame pointer: %p\n",
					  frame);
				break;
			}
		}
	}
}


code:
/*	$OpenBSD: disassem.c,v 1.3 2014/05/08 21:17:00 miod Exp $	*/
/*	$NetBSD: disassem.c,v 1.14 2003/03/27 16:58:36 mycroft Exp $	*/

/*
 * Copyright (c) 1996 Mark Brinicombe.
 * Copyright (c) 1996 Brini.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Brini.
 * 4. The name of the company nor the name of the author may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY BRINI ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL BRINI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * RiscBSD kernel project
 *
 * db_disasm.c
 *
 * Kernel disassembler
 *
 * Created      : 10/02/96
 *
 * Structured after the sparc/sparc/db_disasm.c by David S. Miller &
 * Paul Kranenburg
 *
 * This code is not complete. Not all instructions are disassembled.
 */

#include <sys/param.h>

#include <sys/systm.h>
#include <machine/db_machdep.h>
#include <ddb/db_access.h>
#include <ddb/db_sym.h>
#include <ddb/db_variables.h>
#include <ddb/db_interface.h>
#include <ddb/db_output.h>
#include <arch/arm/arm/disassem.h>

/*
 * General instruction format
 *
 *	insn[cc][mod]	[operands]
 *
 * Those fields with an uppercase format code indicate that the field
 * follows directly after the instruction before the separator i.e.
 * they modify the instruction rather than just being an operand to
 * the instruction. The only exception is the writeback flag which
 * follows a operand.
 *
 *
 * 2 - print Operand 2 of a data processing instruction
 * d - destination register (bits 12-15)
 * n - n register (bits 16-19)
 * s - s register (bits 8-11)
 * o - indirect register rn (bits 16-19) (used by swap)
 * m - m register (bits 0-3)
 * a - address operand of ldr/str instruction
 * l - register list for ldm/stm instruction
 * f - 1st fp operand (register) (bits 12-14)
 * g - 2nd fp operand (register) (bits 16-18)
 * h - 3rd fp operand (register/immediate) (bits 0-4)
 * b - branch address
 * t - thumb branch address (bits 24, 0-23)
 * k - breakpoint comment (bits 0-3, 8-19)
 * X - block transfer type
 * Y - block transfer type (r13 base)
 * c - comment field bits(0-23)
 * p - saved or current status register
 * F - PSR transfer fields
 * D - destination-is-r15 (P) flag on TST, TEQ, CMP, CMN
 * L - co-processor transfer size
 * S - set status flag
 * P - fp precision
 * Q - fp precision (for ldf/stf)
 * R - fp rounding
 * v - co-processor data transfer registers + addressing mode
 * W - writeback flag
 * x - instruction in hex
 * # - co-processor number
 * y - co-processor data processing registers
 * z - co-processor register transfer registers
 */

struct arm32_insn {
	u_int mask;
	u_int pattern;
	char* name;
	char* format;
};

static const struct arm32_insn arm32_i[] = {
    { 0x0fffffff, 0x0ff00000, "imb",	"c" },		/* Before swi */
    { 0x0fffffff, 0x0ff00001, "imbrange",	"c" },	/* Before swi */
    { 0x0f000000, 0x0f000000, "swi",	"c" },
    { 0xfe000000, 0xfa000000, "blx",	"t" },		/* Before b and bl */
    { 0x0f000000, 0x0a000000, "b",	"b" },
    { 0x0f000000, 0x0b000000, "bl",	"b" },
    { 0x0fe000f0, 0x00000090, "mul",	"Snms" },
    { 0x0fe000f0, 0x00200090, "mla",	"Snmsd" },
    { 0x0fe000f0, 0x00800090, "umull",	"Sdnms" },
    { 0x0fe000f0, 0x00c00090, "smull",	"Sdnms" },
    { 0x0fe000f0, 0x00a00090, "umlal",	"Sdnms" },
    { 0x0fe000f0, 0x00e00090, "smlal",	"Sdnms" },
    { 0x0d700000, 0x04200000, "strt",	"daW" },
    { 0x0d700000, 0x04300000, "ldrt",	"daW" },
    { 0x0d700000, 0x04600000, "strbt",	"daW" },
    { 0x0d700000, 0x04700000, "ldrbt",	"daW" },
    { 0xfffffff0, 0xf57ff040, "dsb",    "" },
    { 0xfffffff0, 0xf57ff060, "isb",    "" },
    { 0x0c500000, 0x04000000, "str",	"daW" },
    { 0x0c500000, 0x04100000, "ldr",	"daW" },
    { 0x0c500000, 0x04400000, "strb",	"daW" },
    { 0x0c500000, 0x04500000, "ldrb",	"daW" },
    { 0x0e1f0000, 0x080d0000, "stm",	"YnWl" },/* separate out r13 base */
    { 0x0e1f0000, 0x081d0000, "ldm",	"YnWl" },/* separate out r13 base */
    { 0x0e100000, 0x08000000, "stm",	"XnWl" },
    { 0x0e100000, 0x08100000, "ldm",	"XnWl" },
    { 0x0e1000f0, 0x00100090, "ldrb",	"de" },
    { 0x0e1000f0, 0x00000090, "strb",	"de" },
    { 0x0e1000f0, 0x001000d0, "ldrsb",	"de" },
    { 0x0e1000f0, 0x001000b0, "ldrh",	"de" },
    { 0x0e1000f0, 0x000000b0, "strh",	"de" },
    { 0x0e1000f0, 0x001000f0, "ldrsh",	"de" },
    { 0x0f200090, 0x00200090, "und",	"x" },	/* Before data processing */
    { 0x0e1000d0, 0x000000d0, "und",	"x" },	/* Before data processing */
    { 0x0ff00ff0, 0x01000090, "swp",	"dmo" },
    { 0x0ff00ff0, 0x01400090, "swpb",	"dmo" },
    { 0x0fbf0fff, 0x010f0000, "mrs",	"dp" },	/* Before data processing */
    { 0x0fff00ff, 0x03200000, "nop",	"" },
    { 0x0fff00ff, 0x03200001, "yield",	"" },
    { 0x0fff00ff, 0x03200002, "wfe",	"" },
    { 0x0fff00ff, 0x03200003, "wfi",	"" },
    { 0x0fff00ff, 0x03200004, "sev",	"" },
    { 0x0fff00f0, 0x032000f0, "dbg",	"" },
    { 0x0fb0fff0, 0x0120f000, "msr",	"pFm" },/* Before data processing */
    { 0x0fb0f000, 0x0320f000, "msr",	"pF2" },/* Before data processing */
    { 0x0ffffff0, 0x012fff10, "bx",	"m" },
    { 0x0fff0ff0, 0x016f0f10, "clz",	"dm" },
    { 0x0ffffff0, 0x012fff30, "blx",	"m" },
    { 0xfff000f0, 0xe1200070, "bkpt",	"k" },
    { 0x0de00000, 0x00000000, "and",	"Sdn2" },
    { 0x0de00000, 0x00200000, "eor",	"Sdn2" },
    { 0x0de00000, 0x00400000, "sub",	"Sdn2" },
    { 0x0de00000, 0x00600000, "rsb",	"Sdn2" },
    { 0x0de00000, 0x00800000, "add",	"Sdn2" },
    { 0x0de00000, 0x00a00000, "adc",	"Sdn2" },
    { 0x0de00000, 0x00c00000, "sbc",	"Sdn2" },
    { 0x0de00000, 0x00e00000, "rsc",	"Sdn2" },
    { 0x0df00000, 0x01100000, "tst",	"Dn2" },
    { 0x0df00000, 0x01300000, "teq",	"Dn2" },
    { 0x0de00000, 0x01400000, "cmp",	"Dn2" },
    { 0x0de00000, 0x01600000, "cmn",	"Dn2" },
    { 0x0de00000, 0x01800000, "orr",	"Sdn2" },
    { 0x0de00000, 0x01a00000, "mov",	"Sd2" },
    { 0x0de00000, 0x01c00000, "bic",	"Sdn2" },
    { 0x0de00000, 0x01e00000, "mvn",	"Sd2" },
    { 0x0ff08f10, 0x0e000100, "adf",	"PRfgh" },
    { 0x0ff08f10, 0x0e100100, "muf",	"PRfgh" },
    { 0x0ff08f10, 0x0e200100, "suf",	"PRfgh" },
    { 0x0ff08f10, 0x0e300100, "rsf",	"PRfgh" },
    { 0x0ff08f10, 0x0e400100, "dvf",	"PRfgh" },
    { 0x0ff08f10, 0x0e500100, "rdf",	"PRfgh" },
    { 0x0ff08f10, 0x0e600100, "pow",	"PRfgh" },
    { 0x0ff08f10, 0x0e700100, "rpw",	"PRfgh" },
    { 0x0ff08f10, 0x0e800100, "rmf",	"PRfgh" },
    { 0x0ff08f10, 0x0e900100, "fml",	"PRfgh" },
    { 0x0ff08f10, 0x0ea00100, "fdv",	"PRfgh" },
    { 0x0ff08f10, 0x0eb00100, "frd",	"PRfgh" },
    { 0x0ff08f10, 0x0ec00100, "pol",	"PRfgh" },
    { 0x0f008f10, 0x0e000100, "fpbop",	"PRfgh" },
    { 0x0ff08f10, 0x0e008100, "mvf",	"PRfh" },
    { 0x0ff08f10, 0x0e108100, "mnf",	"PRfh" },
    { 0x0ff08f10, 0x0e208100, "abs",	"PRfh" },
    { 0x0ff08f10, 0x0e308100, "rnd",	"PRfh" },
    { 0x0ff08f10, 0x0e408100, "sqt",	"PRfh" },
    { 0x0ff08f10, 0x0e508100, "log",	"PRfh" },
    { 0x0ff08f10, 0x0e608100, "lgn",	"PRfh" },
    { 0x0ff08f10, 0x0e708100, "exp",	"PRfh" },
    { 0x0ff08f10, 0x0e808100, "sin",	"PRfh" },
    { 0x0ff08f10, 0x0e908100, "cos",	"PRfh" },
    { 0x0ff08f10, 0x0ea08100, "tan",	"PRfh" },
    { 0x0ff08f10, 0x0eb08100, "asn",	"PRfh" },
    { 0x0ff08f10, 0x0ec08100, "acs",	"PRfh" },
    { 0x0ff08f10, 0x0ed08100, "atn",	"PRfh" },
    { 0x0f008f10, 0x0e008100, "fpuop",	"PRfh" },
    { 0x0e100f00, 0x0c000100, "stf",	"QLv" },
    { 0x0e100f00, 0x0c100100, "ldf",	"QLv" },
    { 0x0ff00f10, 0x0e000110, "flt",	"PRgd" },
    { 0x0ff00f10, 0x0e100110, "fix",	"PRdh" },
    { 0x0ff00f10, 0x0e200110, "wfs",	"d" },
    { 0x0ff00f10, 0x0e300110, "rfs",	"d" },
    { 0x0ff00f10, 0x0e400110, "wfc",	"d" },
    { 0x0ff00f10, 0x0e500110, "rfc",	"d" },
    { 0x0ff0ff10, 0x0e90f110, "cmf",	"PRgh" },
    { 0x0ff0ff10, 0x0eb0f110, "cnf",	"PRgh" },
    { 0x0ff0ff10, 0x0ed0f110, "cmfe",	"PRgh" },
    { 0x0ff0ff10, 0x0ef0f110, "cnfe",	"PRgh" },
    { 0xff100010, 0xfe000010, "mcr2",	"#z" },
    { 0x0f100010, 0x0e000010, "mcr",	"#z" },
    { 0xff100010, 0xfe100010, "mrc2",	"#z" },
    { 0x0f100010, 0x0e100010, "mrc",	"#z" },
    { 0xff000010, 0xfe000000, "cdp2",	"#y" },
    { 0x0f000010, 0x0e000000, "cdp",	"#y" },
    { 0xfe100090, 0xfc100000, "ldc2",	"L#v" },
    { 0x0e100090, 0x0c100000, "ldc",	"L#v" },
    { 0xfe100090, 0xfc000000, "stc2",	"L#v" },
    { 0x0e100090, 0x0c000000, "stc",	"L#v" },
    { 0x00000000, 0x00000000, NULL,	NULL }
};

static char const arm32_insn_conditions[][4] = {
	"eq", "ne", "cs", "cc",
	"mi", "pl", "vs", "vc",
	"hi", "ls", "ge", "lt",
	"gt", "le", "",   "nv"
};

static char const insn_block_transfers[][4] = {
	"da", "ia", "db", "ib"
};

static char const insn_stack_block_transfers[][4] = {
	"ed", "ea", "fd", "fa"
};

static char const op_shifts[][4] = {
	"lsl", "lsr", "asr", "ror"
};

static char const insn_fpa_rounding[][2] = {
	"", "p", "m", "z"
};

static char const insn_fpa_precision[][2] = {
	"s", "d", "e", "p"
};

static char const insn_fpaconstants[][8] = {
	"0.0", "1.0", "2.0", "3.0",
	"4.0", "5.0", "0.5", "10.0"
};

#define insn_condition(x)	arm32_insn_conditions[(x >> 28) & 0x0f]
#define insn_blktrans(x)	insn_block_transfers[(x >> 23) & 3]
#define insn_stkblktrans(x)	insn_stack_block_transfers[(x >> 23) & 3]
#define op2_shift(x)		op_shifts[(x >> 5) & 3]
#define insn_fparnd(x)		insn_fpa_rounding[(x >> 5) & 0x03]
#define insn_fpaprec(x)		insn_fpa_precision[(((x >> 18) & 2)|(x >> 7)) & 1]
#define insn_fpaprect(x)	insn_fpa_precision[(((x >> 21) & 2)|(x >> 15)) & 1]
#define insn_fpaimm(x)		insn_fpaconstants[x & 0x07]

/* Local prototypes */
static void disasm_register_shift(const disasm_interface_t *di, u_int insn);
static void disasm_print_reglist(const disasm_interface_t *di, u_int insn);
static void disasm_insn_ldrstr(const disasm_interface_t *di, u_int insn,
    u_int loc);
static void disasm_insn_ldrhstrh(const disasm_interface_t *di, u_int insn,
    u_int loc);
static void disasm_insn_ldcstc(const disasm_interface_t *di, u_int insn,
    u_int loc);
static db_expr_t disassemble_readword(db_expr_t address);
static void disassemble_printaddr(db_expr_t address);

vaddr_t
disasm(const disasm_interface_t *di, vaddr_t loc, int altfmt)
{
	struct arm32_insn *i_ptr = (struct arm32_insn *)&arm32_i;

	u_int insn;
	int matchp;
	int branch;
	char* f_ptr;
	int fmt;

	fmt = 0;
	matchp = 0;
	insn = di->di_readword(loc);

/*	di->di_printf("loc=%08x insn=%08x : ", loc, insn);*/

	while (i_ptr->name) {
		if ((insn & i_ptr->mask) ==  i_ptr->pattern) {
			matchp = 1;
			break;
		}
		i_ptr++;
	}

	if (!matchp) {
		di->di_printf("und%s\t%08x\n", insn_condition(insn), insn);
		return(loc + INSN_SIZE);
	}

	/* If instruction forces condition code, don't print it. */
	if ((i_ptr->mask & 0xf0000000) == 0xf0000000)
		di->di_printf("%s", i_ptr->name);
	else
		di->di_printf("%s%s", i_ptr->name, insn_condition(insn));

	f_ptr = i_ptr->format;

	/* Insert tab if there are no instruction modifiers */

	if (*(f_ptr) < 'A' || *(f_ptr) > 'Z') {
		++fmt;
		di->di_printf("\t");
	}

	while (*f_ptr) {
		switch (*f_ptr) {
		/* 2 - print Operand 2 of a data processing instruction */
		case '2':
			if (insn & 0x02000000) {
				int rotate= ((insn >> 7) & 0x1e);

				di->di_printf("#0x%08x",
					      (insn & 0xff) << (32 - rotate) |
					      (insn & 0xff) >> rotate);
			} else {
				disasm_register_shift(di, insn);
			}
			break;
		/* d - destination register (bits 12-15) */
		case 'd':
			di->di_printf("r%d", ((insn >> 12) & 0x0f));
			break;
		/* D - insert 'p' if Rd is R15 */
		case 'D':
			if (((insn >> 12) & 0x0f) == 15)
				di->di_printf("p");
			break;
		/* n - n register (bits 16-19) */
		case 'n':
			di->di_printf("r%d", ((insn >> 16) & 0x0f));
			break;
		/* s - s register (bits 8-11) */
		case 's':
			di->di_printf("r%d", ((insn >> 8) & 0x0f));
			break;
		/* o - indirect register rn (bits 16-19) (used by swap) */
		case 'o':
			di->di_printf("[r%d]", ((insn >> 16) & 0x0f));
			break;
		/* m - m register (bits 0-4) */
		case 'm':
			di->di_printf("r%d", ((insn >> 0) & 0x0f));
			break;
		/* a - address operand of ldr/str instruction */
		case 'a':
			disasm_insn_ldrstr(di, insn, loc);
			break;
		/* e - address operand of ldrh/strh instruction */
		case 'e':
			disasm_insn_ldrhstrh(di, insn, loc);
			break;
		/* l - register list for ldm/stm instruction */
		case 'l':
			disasm_print_reglist(di, insn);
			break;
		/* f - 1st fp operand (register) (bits 12-14) */
		case 'f':
			di->di_printf("f%d", (insn >> 12) & 7);
			break;
		/* g - 2nd fp operand (register) (bits 16-18) */
		case 'g':
			di->di_printf("f%d", (insn >> 16) & 7);
			break;
		/* h - 3rd fp operand (register/immediate) (bits 0-4) */
		case 'h':
			if (insn & (1 << 3))
				di->di_printf("#%s", insn_fpaimm(insn));
			else
				di->di_printf("f%d", insn & 7);
			break;
		/* b - branch address */
		case 'b':
			branch = ((insn << 2) & 0x03ffffff);
			if (branch & 0x02000000)
				branch |= 0xfc000000;
			di->di_printaddr(loc + 8 + branch);
			break;
		/* t - blx address */
		case 't':
			branch = ((insn << 2) & 0x03ffffff) |
			    (insn >> 23 & 0x00000002);
			if (branch & 0x02000000)
				branch |= 0xfc000000;
			di->di_printaddr(loc + 8 + branch);
			break;
		/* X - block transfer type */
		case 'X':
			di->di_printf("%s", insn_blktrans(insn));
			break;
		/* Y - block transfer type (r13 base) */
		case 'Y':
			di->di_printf("%s", insn_stkblktrans(insn));
			break;
		/* c - comment field bits(0-23) */
		case 'c':
			di->di_printf("0x%08x", (insn & 0x00ffffff));
			break;
		/* k - breakpoint comment (bits 0-3, 8-19) */
		case 'k':
			di->di_printf("0x%04x",
			    (insn & 0x000fff00) >> 4 | (insn & 0x0000000f));
			break;
		/* p - saved or current status register */
		case 'p':
			if (insn & 0x00400000)
				di->di_printf("spsr");
			else
				di->di_printf("cpsr");
			break;
		/* F - PSR transfer fields */
		case 'F':
			di->di_printf("_");
			if (insn & (1 << 16))
				di->di_printf("c");
			if (insn & (1 << 17))
				di->di_printf("x");
			if (insn & (1 << 18))
				di->di_printf("s");
			if (insn & (1 << 19))
				di->di_printf("f");
			break;
		/* B - byte transfer flag */
		case 'B':
			if (insn & 0x00400000)
				di->di_printf("b");
			break;
		/* L - co-processor transfer size */
		case 'L':
			if (insn & (1 << 22))
				di->di_printf("l");
			break;
		/* S - set status flag */
		case 'S':
			if (insn & 0x00100000)
				di->di_printf("s");
			break;
		/* P - fp precision */
		case 'P':
			di->di_printf("%s", insn_fpaprec(insn));
			break;
		/* Q - fp precision (for ldf/stf) */
		case 'Q':
			break;
		/* R - fp rounding */
		case 'R':
			di->di_printf("%s", insn_fparnd(insn));
			break;
		/* W - writeback flag */
		case 'W':
			if (insn & (1 << 21))
				di->di_printf("!");
			break;
		/* # - co-processor number */
		case '#':
			di->di_printf("p%d", (insn >> 8) & 0x0f);
			break;
		/* v - co-processor data transfer registers+addressing mode */
		case 'v':
			disasm_insn_ldcstc(di, insn, loc);
			break;
		/* x - instruction in hex */
		case 'x':
			di->di_printf("0x%08x", insn);
			break;
		/* y - co-processor data processing registers */
		case 'y':
			di->di_printf("%d, ", (insn >> 20) & 0x0f);

			di->di_printf("c%d, c%d, c%d", (insn >> 12) & 0x0f,
			    (insn >> 16) & 0x0f, insn & 0x0f);

			di->di_printf(", %d", (insn >> 5) & 0x07);
			break;
		/* z - co-processor register transfer registers */
		case 'z':
			di->di_printf("%d, ", (insn >> 21) & 0x07);
			di->di_printf("r%d, c%d, c%d, %d",
			    (insn >> 12) & 0x0f, (insn >> 16) & 0x0f,
			    insn & 0x0f, (insn >> 5) & 0x07);

/*			if (((insn >> 5) & 0x07) != 0)
				di->di_printf(", %d", (insn >> 5) & 0x07);*/
			break;
		default:
			di->di_printf("[%c - unknown]", *f_ptr);
			break;
		}
		if (*(f_ptr+1) >= 'A' && *(f_ptr+1) <= 'Z')
			++f_ptr;
		else if (*(++f_ptr)) {
			++fmt;
			if (fmt == 1)
				di->di_printf("\t");
			else
				di->di_printf(", ");
		}
	};

	di->di_printf("\n");

	return(loc + INSN_SIZE);
}

static void
disasm_register_shift(const disasm_interface_t *di, u_int insn)
{
	di->di_printf("r%d", (insn & 0x0f));
	if ((insn & 0x00000ff0) == 0)
		;
	else if ((insn & 0x00000ff0) == 0x00000060)
		di->di_printf(", rrx");
	else {
		if (insn & 0x10)
			di->di_printf(", %s r%d", op2_shift(insn),
			    (insn >> 8) & 0x0f);
		else
			di->di_printf(", %s #%d", op2_shift(insn),
			    (insn >> 7) & 0x1f);
	}
}

static void
disasm_print_reglist(const disasm_interface_t *di, u_int insn)
{
	int loop;
	int start;
	int comma;

	di->di_printf("{");
	start = -1;
	comma = 0;

	for (loop = 0; loop < 17; ++loop) {
		if (start != -1) {
			if (loop == 16 || !(insn & (1 << loop))) {
				if (comma)
					di->di_printf(", ");
				else
					comma = 1;
        			if (start == loop - 1)
        				di->di_printf("r%d", start);
        			else
        				di->di_printf("r%d-r%d", start, loop - 1);
        			start = -1;
        		}
        	} else {
        		if (insn & (1 << loop))
        			start = loop;
        	}
        }
	di->di_printf("}");

	if (insn & (1 << 22))
		di->di_printf("^");
}

static void
disasm_insn_ldrstr(const disasm_interface_t *di, u_int insn, u_int loc)
{
	int offset;

	offset = insn & 0xfff;
	if ((insn & 0x032f0000) == 0x010f0000) {
		/* rA = pc, immediate index */
		if (insn & 0x00800000)
			loc += offset;
		else
			loc -= offset;
		di->di_printaddr(loc + 8);
 	} else {
		di->di_printf("[r%d", (insn >> 16) & 0x0f);
		if ((insn & 0x03000fff) != 0x01000000) {
			di->di_printf("%s, ", (insn & (1 << 24)) ? "" : "]");
			if (!(insn & 0x00800000))
				di->di_printf("-");
			if (insn & (1 << 25))
				disasm_register_shift(di, insn);
			else
				di->di_printf("#0x%03x", offset);
		}
		if (insn & (1 << 24))
			di->di_printf("]");
	}
}

static void
disasm_insn_ldrhstrh(const disasm_interface_t *di, u_int insn, u_int loc)
{
	int offset;

	offset = ((insn & 0xf00) >> 4) | (insn & 0xf);
	if ((insn & 0x004f0000) == 0x004f0000) {
		/* rA = pc, immediate index */
		if (insn & 0x00800000)
			loc += offset;
		else
			loc -= offset;
		di->di_printaddr(loc + 8);
 	} else {
		di->di_printf("[r%d", (insn >> 16) & 0x0f);
		if ((insn & 0x01400f0f) != 0x01400000) {
			di->di_printf("%s, ", (insn & (1 << 24)) ? "" : "]");
			if (!(insn & 0x00800000))
				di->di_printf("-");
			if (insn & (1 << 22))
				di->di_printf("#0x%02x", offset);
			else
				di->di_printf("r%d", (insn & 0x0f));
		}
		if (insn & (1 << 24))
			di->di_printf("]");
	}
}

static void
disasm_insn_ldcstc(const disasm_interface_t *di, u_int insn, u_int loc)
{
	if (((insn >> 8) & 0xf) == 1)
		di->di_printf("f%d, ", (insn >> 12) & 0x07);
	else
		di->di_printf("c%d, ", (insn >> 12) & 0x0f);

	di->di_printf("[r%d", (insn >> 16) & 0x0f);

	di->di_printf("%s, ", (insn & (1 << 24)) ? "" : "]");

	if (!(insn & (1 << 23)))
		di->di_printf("-");

	di->di_printf("#0x%03x", (insn & 0xff) << 2);

	if (insn & (1 << 24))
		di->di_printf("]");

	if (insn & (1 << 21))
		di->di_printf("!");
}

static db_expr_t
disassemble_readword(db_expr_t address)
{
	return(*((u_int *)address));
}

static void
disassemble_printaddr(db_expr_t address)
{
	db_printf("0x%08lx", address);
}

static const disasm_interface_t disassemble_di = {
	disassemble_readword, disassemble_printaddr, db_printf
};

void
disassemble(u_int address)
{

	(void)disasm(&disassemble_di, address, 0);
}

/* End of disassem.c */


code:
/*	$OpenBSD: disassem.h,v 1.2 2012/01/17 18:50:57 miod Exp $	*/
/*	$NetBSD: disassem.h,v 1.4 2001/03/04 04:15:58 matt Exp $	*/

/*
 * Copyright (c) 1997 Mark Brinicombe.
 * Copyright (c) 1997 Causality Limited.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Mark Brinicombe.
 * 4. The name of the company nor the name of the author may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Define the interface structure required by the disassembler.
 */

typedef struct {
	db_expr_t	(*di_readword)(db_expr_t);
	void	(*di_printaddr)(db_expr_t);
	int	(*di_printf)(const char *, ...)
	    __attribute__((__format__(__kprintf__,1,2)));
} disasm_interface_t;

/* Prototypes for callable functions */

vaddr_t disasm(const disasm_interface_t *, vaddr_t, int);
void disassemble(u_int);


code:
/*	$OpenBSD: disksubr.c,v 1.59 2013/10/19 09:32:12 krw Exp $	*/
/*	$NetBSD: disksubr.c,v 1.21 1996/05/03 19:42:03 christos Exp $	*/

/*
 * Copyright (c) 1996 Theo de Raadt
 * Copyright (c) 1982, 1986, 1988 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/buf.h>
#include <sys/disklabel.h>
#include <sys/disk.h>

/*
 * Attempt to read a disk label from a device
 * using the indicated strategy routine.
 * The label must be partly set up before this:
 * secpercyl, secsize and anything required for a block i/o read
 * operation in the driver's strategy/start routines
 * must be filled in before calling us.
 *
 * If dos partition table requested, attempt to load it and
 * find disklabel inside a DOS partition.
 *
 * We would like to check if each MBR has a valid DOSMBR_SIGNATURE, but
 * we cannot because it doesn't always exist. So.. we assume the
 * MBR is valid.
 */
int
readdisklabel(dev_t dev, void (*strat)(struct buf *),
    struct disklabel *lp, int spoofonly)
{
	struct buf *bp = NULL;
	int error;

	if ((error = initdisklabel(lp)))
		goto done;

	/* get a buffer and initialize it */
	bp = geteblk((int)lp->d_secsize);
	bp->b_dev = dev;

	error = readdoslabel(bp, strat, lp, NULL, spoofonly);
	if (error == 0)
		goto done;

#if defined(CD9660)
	error = iso_disklabelspoof(dev, strat, lp);
	if (error == 0)
		goto done;
#endif
#if defined(UDF)
	error = udf_disklabelspoof(dev, strat, lp);
	if (error == 0)
		goto done;
#endif

done:
	if (bp) {
		bp->b_flags |= B_INVAL;
		brelse(bp);
	}
	disk_change = 1;
	return (error);
}

/*
 * Write disk label back to device after modification.
 */
int
writedisklabel(dev_t dev, void (*strat)(struct buf *), struct disklabel *lp)
{
	daddr_t partoff = -1;
	int error = EIO;
	int offset;
	struct disklabel *dlp;
	struct buf *bp = NULL;

	/* get a buffer and initialize it */
	bp = geteblk((int)lp->d_secsize);
	bp->b_dev = dev;

	if (readdoslabel(bp, strat, lp, &partoff, 1) != 0)
		goto done;

	/* Read it in, slap the new label in, and write it back out */
	bp->b_blkno = DL_BLKTOSEC(lp, partoff + DOS_LABELSECTOR) *
	    DL_BLKSPERSEC(lp);
	offset = DL_BLKOFFSET(lp, partoff + DOS_LABELSECTOR);
	bp->b_bcount = lp->d_secsize;
	CLR(bp->b_flags, B_READ | B_WRITE | B_DONE);
	SET(bp->b_flags, B_BUSY | B_READ | B_RAW);
	(*strat)(bp);
	if ((error = biowait(bp)) != 0)
		goto done;

	dlp = (struct disklabel *)(bp->b_data + offset);
	*dlp = *lp;
	CLR(bp->b_flags, B_READ | B_WRITE | B_DONE);
	SET(bp->b_flags, B_BUSY | B_WRITE | B_RAW);
	(*strat)(bp);
	error = biowait(bp);

done:
	if (bp) {
		bp->b_flags |= B_INVAL;
		brelse(bp);
	}
	disk_change = 1;
	return (error);
}


code:
/*	$OpenBSD: exception.S,v 1.5 2015/01/18 12:03:11 jsg Exp $	*/
/*	$NetBSD: exception.S,v 1.13 2003/10/31 16:30:15 scw Exp $	*/

/*
 * Copyright (c) 1994-1997 Mark Brinicombe.
 * Copyright (c) 1994 Brini.
 * All rights reserved.
 *
 * This code is derived from software written for Brini by Mark Brinicombe
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Brini.
 * 4. The name of the company nor the name of the author may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY BRINI ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL BRINI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * RiscBSD kernel project
 *
 * exception.S
 *
 * Low level handlers for exception vectors
 *
 * Created      : 24/09/94
 *
 * Based on kate/display/abort.s
 */

#include <machine/asm.h>
#include <machine/cpu.h>
#include <machine/frame.h>
#include "assym.h"

	.text
	.align	0

AST_LOCALS

/*
 * reset_entry:
 *
 *	Handler for Reset exception.
 */
ASENTRY_NP(reset_entry)
	adr	r0, Lreset_panicmsg
	mov	r1, lr
	bl	_C_LABEL(panic)
	/* NOTREACHED */
Lreset_panicmsg:
	.asciz	"Reset vector called, LR = 0x%08x"
	.balign	4

/*
 * swi_entry
 *
 *	Handler for the Software Interrupt exception.
 */
ASENTRY_NP(swi_entry)
	PUSHFRAME

	mov	r0, sp			/* Pass the frame to any function */
	bl	_C_LABEL(swi_handler)	/* It's a SWI ! */

	DO_AST
	PULLFRAME
	movs	pc, lr			/* Exit */

/*
 * prefetch_abort_entry:
 *
 *	Handler for the Prefetch Abort exception.
 */
ASENTRY_NP(prefetch_abort_entry)
#ifdef __XSCALE__
	nop				/* Make absolutely sure any pending */
	nop				/* imprecise aborts have occurred. */
#endif
        sub     lr, lr, #0x00000004     /* Adjust the lr */

	PUSHFRAMEINSVC

	ldr	r1, Lprefetch_abort_handler_address
	adr	lr, exception_exit
 	mov	r0, sp			/* pass the stack pointer as r0 */
	ldr	pc, [r1]

Lprefetch_abort_handler_address:
	.word	_C_LABEL(prefetch_abort_handler_address)

	.data
	.global	_C_LABEL(prefetch_abort_handler_address)

_C_LABEL(prefetch_abort_handler_address):
	.word	abortprefetch

	.text
abortprefetch:
        adr     r0, abortprefetchmsg
	b	_C_LABEL(panic)

abortprefetchmsg:
        .asciz  "abortprefetch"
        .align  0

/*
 * data_abort_entry:
 *
 *	Handler for the Data Abort exception.
 */
ASENTRY_NP(data_abort_entry)
#ifdef __XSCALE__
	nop				/* Make absolutely sure any pending */
	nop				/* imprecise aborts have occurred. */
#endif
        sub     lr, lr, #0x00000008     /* Adjust the lr */

	PUSHFRAMEINSVC			/* Push trap frame and switch */
					/* to SVC32 mode */

	ldr	r1, Ldata_abort_handler_address
	adr	lr, exception_exit
	mov	r0, sp			/* pass the stack pointer as r0 */
	ldr	pc, [r1]

Ldata_abort_handler_address:
	.word	_C_LABEL(data_abort_handler_address)

	.data
	.global	_C_LABEL(data_abort_handler_address)
_C_LABEL(data_abort_handler_address):
	.word	abortdata

	.text
abortdata:
        adr     r0, abortdatamsg
	b	_C_LABEL(panic)

abortdatamsg:
        .asciz  "abortdata"
        .align  0

/*
 * address_exception_entry:
 *
 *	Handler for the Address Exception exception.
 *
 *	NOTE: This exception isn't really used on arm32.  We
 *	print a warning message to the console and then treat
 *	it like a Data Abort.
 */
ASENTRY_NP(address_exception_entry)
	mrs	r1, cpsr
	mrs	r2, spsr
	mov	r3, lr
	adr	r0, Laddress_exception_msg
	bl	_C_LABEL(printf)	/* XXX CLOBBERS LR!! */
	b	data_abort_entry
Laddress_exception_msg:
	.asciz	"Address Exception CPSR=0x%08x SPSR=0x%08x LR=0x%08x\n"
	.balign	4

/*
 * General exception exit handler
 * (Placed here to be within range of all the references to it)
 *
 * It exits straight away if not returning to USR mode.
 * This loops around delivering any pending ASTs.
 * Interrupts are disabled at suitable points to avoid ASTs
 * being posted between testing and exit to user mode.
 *
 * This function uses PULLFRAMEFROMSVCANDEXIT and DO_AST thus should
 * only be called if the exception handler used PUSHFRAMEINSVC.
 */

exception_exit:
	DO_AST
	PULLFRAMEFROMSVCANDEXIT

/*
 * undefined_entry:
 *
 *	Handler for the Undefined Instruction exception.
 *
 *	We indirect the undefined vector via the handler address
 *	in the data area.  Entry to the undefined handler must
 *	look like direct entry from the vector.
 */
ASENTRY_NP(undefined_entry)
	stmfd	sp!, {r0, r1}
	ldr	r0, Lundefined_handler_indirection
	ldr	r1, [sp], #0x0004
	str	r1, [r0, #0x0000]
	ldr	r1, [sp], #0x0004
	str	r1, [r0, #0x0004]
	ldmia	r0, {r0, r1, pc}

Lundefined_handler_indirection:
	.word	Lundefined_handler_indirection_data

/*
 * assembly bounce code for calling the kernel
 * undefined instruction handler. This uses
 * a standard trap frame and is called in SVC mode.
 */

ENTRY_NP(undefinedinstruction_bounce)
	PUSHFRAMEINSVC

	mov	r0, sp
	adr	lr, exception_exit
	b	_C_LABEL(undefinedinstruction)

	.data
	.align	0

/*
 * Indirection data
 * 2 words use for preserving r0 and r1
 * 3rd word contains the undefined handler address.
 */

Lundefined_handler_indirection_data:
	.word	0
	.word	0

	.global	_C_LABEL(undefined_handler_address)
_C_LABEL(undefined_handler_address):
	.word	_C_LABEL(undefinedinstruction_bounce)