// CrossWorks Tasking Library.
//
// Copyright (c) 2004 Rowley Associates Limited.
//
// This file may be distributed under the terms of the License Agreement
// provided with this software.
//
// THIS FILE IS PROVIDED AS IS WITH NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

#include "ctl_api.h"
#include <targets/STA2051.h>

#define INTERRUPT_SOURCE_COUNT 32

static unsigned int currentVector;

void irq_handler(void) __attribute__((naked));

#define SIR(n) (*(&SIR0 + n))

void
irq_handler(void)
{
  asm("stmfd sp!, {r0-r12, lr}"); 
  asm("mrs r0, spsr");
  asm("stmfd sp!, {r0}");
  ctl_interrupt_count++;
  /* Call ISR */
  ((CTL_ISR_FN_t)IVR)();
  /* Signal EOI */
  IPR0 = 1 << CICR;
  asm("mov r0, sp");
  asm("ldr r1, =ctl_exit_isr");
  asm("bx r1");
}

int
ctl_set_isr(unsigned int vector, unsigned int priority, CTL_ISR_TRIGGER_t trigger, CTL_ISR_FN_t isr, CTL_ISR_FN_t *oldisr)
{
  if (oldisr)
    *oldisr = (CTL_ISR_FN_t)((IVR & 0xFFFF0000) | (SIR(vector) >> 16));
  SIR(vector) = ((unsigned int)isr << 16) | (priority & 0xF);
  IVR = (unsigned int)isr & 0xFFFF0000;
  return 1;
}

int
ctl_unmask_isr(unsigned int vector)
{
  IER0 |= 1 << vector; /* Enable interrupt vector */
  ICR |= 1; /* Enable global interrupts */
  return 1;
}

int
ctl_mask_isr(unsigned int vector)
{
  IER0 &= ~(1 << vector);
  return 1;
}
