// 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 <targets/ADuC7020.h>
#include "ctl_api.h"

typedef volatile unsigned int *reg32_t;
#define INTERRUPT_SOURCE_COUNT 24

static CTL_ISR_FN_t vectors[INTERRUPT_SOURCE_COUNT];

static void
irq_handler2(void)
{
  unsigned int status = IRQSTA;
  int i;
  for (i = 1; i <= INTERRUPT_SOURCE_COUNT; ++i)
    {
      status >>= 1;
      if (status & 1)
        {
          IRQCLR = 1 << i;
          vectors[i - 1]();
          IRQEN = 1 << i;
          break;
        }
    }
}

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

void
irq_handler(void)
{
  asm("stmfd sp!, {r0-r12, lr}");
  asm("mrs r0, spsr");
  asm("stmfd sp!, {r0}");
  ctl_interrupt_count++;
  irq_handler2();
  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 (vector == 0 || vector > INTERRUPT_SOURCE_COUNT)
    return 0;
  if (oldisr)
    *oldisr = vectors[vector - 1];
  vectors[vector - 1] = isr;
  return 1;
}

int
ctl_unmask_isr(unsigned int vector)
{
  IRQEN = 1 << vector;
  return 1;
}

int
ctl_mask_isr(unsigned int vector)
{
  IRQCLR = 1 << vector;
  return 1;
}

