// #===========================================================================
// #
// #    context.S
// #
// #    ARM context switch code
// #
// #===========================================================================
// ####ECOSGPLCOPYRIGHTBEGIN####                                            
// -------------------------------------------                              
// This file is part of eCos, the Embedded Configurable Operating System.   
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2005, 2007, 2008 Free Software Foundation, Inc.
// Copyright (C) 2005, 2007, 2008 eCosCentric Limited                       
//
// eCos is free software; you can redistribute it and/or modify it under    
// the terms of the GNU General Public License as published by the Free     
// Software Foundation; either version 2 or (at your option) any later      
// version.                                                                 
//
// eCos is distributed in the hope that it will be useful, but WITHOUT      
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or    
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License    
// for more details.                                                        
//
// You should have received a copy of the GNU General Public License        
// along with eCos; if not, write to the Free Software Foundation, Inc.,    
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.            
//
// As a special exception, if other files instantiate templates or use      
// macros or inline functions from this file, or you compile this file      
// and link it with other works to produce a work based on this file,       
// this file does not by itself cause the resulting work to be covered by   
// the GNU General Public License. However the source code for this file    
// must still be made available in accordance with section (3) of the GNU   
// General Public License v2.                                               
//
// This exception does not invalidate any other reasons why a work based    
// on this file might be covered by the GNU General Public License.         
// -------------------------------------------                              
// ####ECOSGPLCOPYRIGHTEND####                                              
// #===========================================================================
// ######DESCRIPTIONBEGIN####
// #
// # Author(s):    nickg, gthomas
// # Contributors: nickg, gthomas
// # Date:         1998-09-15
// # Purpose:      ARM context switch code
// # Description:  This file contains implementations of the thread context 
// #               switch routines. It also contains the longjmp() and setjmp()
// #               routines.
// #
// #####DESCRIPTIONEND####
// #
// #===========================================================================

#include <pkgconf/system.h>        
#include <pkgconf/hal.h>

#include "arm.inc"

        .text

// ----------------------------------------------------------------------------
//  function declaration macro (start body in ARM mode)
                
#ifdef __thumb__
#define FUNC_START_ARM(_name_, _r_)              \
        .section .text._name_                   ;\
        .type _name_, function                  ;\
        .code   16                              ;\
        .thumb_func                             ;\
        .globl _name_                           ;\
_name_:                                         ;\
        ldr     _r_,=_name_ ## _ARM             ;\
        bx      _r_                             ;\
        .code   32                              ;\
_name_ ## _ARM:

#else

#define FUNC_START_ARM(_name_, _r_) \
        .section .text._name_     ; \
        .type _name_, function    ; \
        .globl _name_             ; \
_name_: 
        
#endif
        
// ----------------------------------------------------------------------------
//  hal_thread_switch_context
//  Switch thread contexts
//  R0 = address of sp of next thread to execute
//  R1 = address of sp save location of current thread

// Need to save/restore R4..R12, R13 (sp), R14 (lr)

// Note: this is a little wasteful since r0..r3 don't need to be saved.
// They are saved here though so that the information can match the
// HAL_SavedRegisters
        
FUNC_START_ARM(hal_thread_switch_context, r2)
        mov     ip,sp
        sub     sp,sp,#(ARMREG_SIZE - armreg_lr - 4)    // skip svc_sp, svc_lr, vector, cpsr, and pc
        str     lr,[sp]                                 // copy LR to PC field, keeps GDB happy
        stmfd   sp!,{ip,lr}
        stmfd   sp!,{r0-r10,fp,ip}
        mrs     r2,cpsr
        str     r2,[sp,#armreg_cpsr]
        str     sp,[r1]                                 // return new stack pointer
#ifdef __thumb__
        b       hal_thread_load_context_ARM             // skip mode switch stuff
#endif

        // Now load the destination thread by dropping through
        // to hal_thread_load_context
        
// ----------------------------------------------------------------------------
//  hal_thread_load_context
//  Load thread context
//  R0 = address of sp of next thread to execute
//  Note that this function is also the second half of
//  hal_thread_switch_context and is simply dropped into from it.
        
FUNC_START_ARM(hal_thread_load_context, r2)
        ldr     fp,[r0]                 // get context to restore
        mrs     r0,cpsr                 // disable IRQ's
        orr     r0,r0,#CPSR_IRQ_DISABLE	//|CPSR_FIQ_DISABLE SBB 240211 - stop fiq disable
        msr     cpsr,r0
        ldr     r0,[fp,#armreg_cpsr]
        msr     spsr,r0
        ldmfd   fp,{r0-r10,fp,ip,sp,lr}
#ifdef __thumb__
        mrs     r1,spsr                 // r1 is scratch 
                                        // [r0 holds initial thread arg]
        msr     cpsr,r1                 // hopefully no mode switch here!
        bx      lr
#else
        movs    pc,lr                   // also restores saved PSR
#endif

// ----------------------------------------------------------------------------
//  HAL longjmp, setjmp implementations
//  hal_setjmp saves only to callee save registers 4-14
//  and lr into buffer supplied in r0[arg0]

FUNC_START_ARM(hal_setjmp, r2)
        stmea   r0,{r4-r14}
        mov     r0,#0
#ifdef __thumb__
        bx      lr
#else
        mov     pc,lr;          # return
#endif

//  hal_longjmp loads state from r0[arg0] and returns
        
FUNC_START_ARM(hal_longjmp, r2)
        ldmfd   r0,{r4-r14}
        mov     r0,r1;          # return [arg1]
#ifdef __thumb__
        bx      lr
#else
        mov     pc,lr
#endif

// ----------------------------------------------------------------------------
// Profiling support.
//
// When code is compiled with -pg the compiler inserts calls to mcount()
// at the start of each function. This can be used to build a callgraph
// of the application. mcount() is tied to the compiler internals and does
// not follow standard calling conventions. On the ARM we have the following
// sequence at the start of each function:              
//
//     .data
// .LP1:
//     .word    0
//     .text
//     mov      ip,lr
//     bl       mcount
//     .word    .LP
//
// So mcount is invoked with the caller address in ip and the callee
// address in lr. This sequence is used for both ARM and thumb. There are
// no spare registers so everything has to be saved before being used.      
// The goal of mcount() is to call __profile_mcount(caller,callee)
// with interrupts disabled. r4 is used to save the current interrupt
// status. Four words of padding are added to front and back so that
// with a default bucket size of 16 bytes the mcount() profile timer
// hits do not get assigned to neighbouring functions.
        
#ifdef CYGPKG_PROFILE_GPROF
        .section .text.mcount
_mcount_head_padding_ignore:
        .word   0,0,0,0
# if defined(__thumb) && !defined(__THUMB_INTERWORK__)
        .code   16
        .thumb_func
        .globl mcount
mcount:
        stmfd   sp!,{r0-r4,lr}
        // Must go into ARM mode before disabling interrupts
        ldr     r2,=mcount32
        bx      r2
        .code   32
mcount32:
        mrs     r4,cpsr
        mov     r3,r4
        orr     r3,r3,#0x00C0
        msr     cpsr,r3

        mov     r0,ip
        mov     r1,lr
        ldr     r2,=__profile_mcount+1
        mov     lr,pc
        bx      r2
        // Assume the called code has done a bx lr so we are back in ARM mode
        msr     cpsr,r4
        ldmfd   sp!,{r0-r4,lr}
        // Skip past the .word .LP
        add     lr,lr,#4
        bx      lr
# else
        .globl mcount
mcount:
        stmfd   sp!,{r0-r4,lr}
        mrs     r4,cpsr
        mov     r3,r4
        orr     r3,r3,#0x00C0
        msr     cpsr,r3

        mov     r0,ip
        mov     r1,lr
        bl      __profile_mcount
        msr     cpsr,r4
        ldmfd   sp!,{r0-r4,lr}
        // Skip past the .word .LP
        add     lr,lr,#4
#  if defined(__ARM_ARCH_1__) || defined(__ARM_ARCH_2__) ||       \
      defined(__ARM_ARCH_3__) || defined(__ARM_ARCH_3M__) ||      \
      defined(__ARM_ARCH_4__)
        mov     pc,lr
#  else
        bx      lr
#  endif
# endif        
_mcount_tail_padding_ignore:
        .word   0,0,0,0
#endif

// ----------------------------------------------------------------------------
// Synthesise a breakpoint for the gdb file I/O code.

        .section .text._gdb_hwdebug_breakpoint
#ifdef __thumb__
        .code   16
        .thumb_func
#endif
        .globl _gdb_hwdebug_breakpoint
        .type  _gdb_hwdebug_breakpoint, function
_gdb_hwdebug_breakpoint:
        
#if defined(__ARM_ARCH_1__) || defined(__ARM_ARCH_2__) ||       \
    defined(__ARM_ARCH_3__) || defined(__ARM_ARCH_3M__) ||      \
    defined(__ARM_ARCH_4__) || defined(__ARM_ARCH_4T__)
        // These architecture versions predate the 'bkpt' instruction
        // so we can only use an illegal instruction to try and halt
        // the target and enter debugging mode.
# ifdef __thumb__        
        .short HAL_BREAKINST_THUMB
# else
        .word HAL_BREAKINST_ARM
# endif
#else
        // Use the BKPT instruction, not an illegal instruction exception,
        // since BKPT is expected to interact with hardware debug units.
        // The same instruction is used for ARM and Thumb so there is
        // no need to worry about the current mode.
        bkpt 0
#endif
#ifdef __thumb__
        .code   16
        .thumb_func
#endif
        .globl _gdb_hwdebug_continue
        .type  _gdb_hwdebug_continue, function
_gdb_hwdebug_continue:
#if defined(__ARM_ARCH_1__) || defined(__ARM_ARCH_2__) ||       \
    defined(__ARM_ARCH_3__) || defined(__ARM_ARCH_3M__) ||      \
    defined(__ARM_ARCH_4__)
        mov     pc,lr
#else
        bx      lr
#endif        
       
// ----------------------------------------------------------------------------
//  end of context.S
