/*
 * Copyright (c) 2014, SICS Swedish ICT.
 * 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 Institute 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 INSTITUTE 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 INSTITUTE 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.
 *
 * This file is part of the Contiki operating system.
 *
 */

/**
 * \file
 *         RTIMER for NXP jn516x: 32 kHz mode
 * \author
 *         Atis Elsts <atis.elsts@sics.se>
 */

#include "sys/rtimer.h"
#include "sys/clock.h"
#include <AppHardwareApi.h>
#include <PeripheralRegs.h>
#include <MicroSpecific.h>
#include "dev/watchdog.h"
#include "sys/energest.h"
#include "sys/process.h"

#if RTIMER_USE_32KHZ

#define DEBUG 0
#if DEBUG
#include <stdio.h>
#define PRINTF(...) printf(__VA_ARGS__)
#else
#define PRINTF(...)
#endif

#define RTIMER_TIMER_ISR_DEV  E_AHI_DEVICE_SYSCTRL
/* 1.5 days wraparound time */
#define MAX_VALUE         0xFFFFFFFF
/* make this small to more easily detect wraparound bugs */
#define START_VALUE       (60 * RTIMER_ARCH_SECOND)
#define WRAPAROUND_VALUE  ((uint64_t)0x1FFFFFFFFFF)

static volatile rtimer_clock_t scheduled_time;
static volatile uint8_t has_next;

/*---------------------------------------------------------------------------*/
static void
timerISR(uint32 u32Device, uint32 u32ItemBitmap)
{
  PRINTF("\ntimer isr %u %u\n", u32Device, u32ItemBitmap);
  if(u32Device != RTIMER_TIMER_ISR_DEV) {
    return;
  }

  ENERGEST_ON(ENERGEST_TYPE_IRQ);

  if(u32ItemBitmap & TICK_TIMER_MASK) {
    /* 32-bit overflow happened; restart the timer */
    uint32_t ticks_late = WRAPAROUND_VALUE - u64AHI_WakeTimerReadLarge(TICK_TIMER);

    PRINTF("\nrtimer oflw, missed ticks %u\n", ticks_late);
    
    vAHI_WakeTimerStartLarge(TICK_TIMER, MAX_VALUE - ticks_late);
  }

  if(u32ItemBitmap & WAKEUP_TIMER_MASK) {
    PRINTF("\nrtimer fire @ %u\n", rtimer_arch_now());

    /* Compare with the current time, as after sleep there is
     * a fake interrupt generated 10ms earlier to wake up & reinitialize
     * the system before the actual rtimer fires.
     */
    rtimer_clock_t now = rtimer_arch_now();
    if(RTIMER_CLOCK_LT(now + 1, scheduled_time)) {
      vAHI_WakeTimerEnable(WAKEUP_TIMER, TRUE);
      vAHI_WakeTimerStartLarge(WAKEUP_TIMER, scheduled_time - now);
    } else {
      has_next = 0;
      watchdog_start();
      rtimer_run_next();
      process_nevents();
    }
  }

  ENERGEST_OFF(ENERGEST_TYPE_IRQ);
}
/*---------------------------------------------------------------------------*/
void
rtimer_arch_init(void)
{
  /* Initialise tick timer to run continuously */
  vAHI_TickTimerIntEnable(0);
  vAHI_TickTimerConfigure(E_AHI_TICK_TIMER_DISABLE);
  vAHI_TickTimerWrite(0);
  vAHI_TickTimerConfigure(E_AHI_TICK_TIMER_CONT);

  vAHI_SysCtrlRegisterCallback(timerISR);
  /* set the highest priority for the rtimer interrupt */
  vAHI_InterruptSetPriority(MICRO_ISR_MASK_SYSCTRL, 15);
  /* enable interrupt on a rtimer */
  vAHI_WakeTimerEnable(WAKEUP_TIMER, TRUE);
  /* enable interrupt on 32-bit overflow */
  vAHI_WakeTimerEnable(TICK_TIMER, TRUE);
  /* count down from START_VALUE */
  vAHI_WakeTimerStartLarge(TICK_TIMER, START_VALUE);

  (void)u32AHI_Init();
}
/*---------------------------------------------------------------------------*/
void
rtimer_arch_reinit(rtimer_clock_t sleep_start, rtimer_clock_t sleep_ticks)
{
  uint64_t t;

  uint32_t wakeup_time = sleep_start + (uint64_t)sleep_ticks * (F_CPU / 2) / RTIMER_SECOND;

  /* Initialise tick timer to run continuously */
  vAHI_TickTimerConfigure(E_AHI_TICK_TIMER_DISABLE);
  vAHI_TickTimerIntEnable(0);
  WAIT_FOR_EDGE(t);
  vAHI_TickTimerWrite(wakeup_time);
  vAHI_TickTimerConfigure(E_AHI_TICK_TIMER_CONT);

  /* call pending interrupts */
  (void)u32AHI_Init();

  if(has_next) {
    /* reschedule the timer */
    rtimer_arch_schedule(scheduled_time);
  }
}
/*---------------------------------------------------------------------------*/
rtimer_clock_t
rtimer_arch_now(void)
{
  return START_VALUE - (rtimer_clock_t)u64AHI_WakeTimerReadLarge(TICK_TIMER);
}
/*---------------------------------------------------------------------------*/
void
rtimer_arch_schedule(rtimer_clock_t t)
{
  PRINTF("rtimer_arch_schedule time %lu\n", t);
  vAHI_WakeTimerEnable(WAKEUP_TIMER, TRUE);
  vAHI_WakeTimerStartLarge(WAKEUP_TIMER, t - rtimer_arch_now());
  scheduled_time = t;
  has_next = 1;
}
/*---------------------------------------------------------------------------*/
rtimer_clock_t
rtimer_arch_time_to_rtimer(void)
{
  rtimer_clock_t now = RTIMER_NOW();
  if(has_next) {
    return scheduled_time >= now ? scheduled_time - now : 0;
  }
  /* if no wakeup is scheduled yet return maximum time */
  return (rtimer_clock_t)-1;
}
/*---------------------------------------------------------------------------*/
#endif /* RTIMER_USE_32KHZ */