/*==========================================================================
//
//      timer_pit.c
//
//      HAL timer code using the Periodic Interval Timer
//
//==========================================================================
// ####ECOSGPLCOPYRIGHTBEGIN####                                            
// -------------------------------------------                              
// This file is part of eCos, the Embedded Configurable Operating System.   
// Copyright (C) 2006 Free Software Foundation, Inc.                        
// Copyright (C) 2006 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):    asl, Oliver Munz
// Contributors: asl, Oliver Munz
// Date:         2006-02-12
// Purpose:      Clock support using the PIT
// Description:  
//
//####DESCRIPTIONEND####
//
//========================================================================*/

#include <pkgconf/hal.h>

#include <cyg/infra/cyg_type.h>         // base types
#include <cyg/infra/cyg_ass.h>          // assertion macros

#include <cyg/hal/hal_io.h>             // IO macros
#include <cyg/hal/hal_intr.h>           // Interrupt names

// -------------------------------------------------------------------------
// Define some aliases for the PIT code.

#define _PITC_PIMR              (AT91_PITC + AT91_PITC_PIMR)
#define _PITC_PISR              (AT91_PITC + AT91_PITC_PISR)
#define _PITC_PIVR              (AT91_PITC + AT91_PITC_PIVR)
#define _PITC_PIIR              (AT91_PITC + AT91_PITC_PIIR)
#define _PITC_PIMR_PITEN        AT91_PITC_PIMR_PITEN
#define _PITC_PIMR_PITIEN       AT91_PITC_PIMR_PITIEN

// -------------------------------------------------------------------------
// Use PIT as system clock

void
hal_clock_initialize(cyg_uint32 period)
{
  cyg_uint32 pivr, pimr, piv;

  CYG_ASSERT(period <= AT91_PITC_VALUE_MASK, "Invalid HAL clock configuration");

  // The PITC has an annoying design flaw - it cannot be reset
  // once enabled. And if you need to reduce the period from
  // its earlier value, and the current timer value is above
  // that period, then the timer has to go right to the top and
  // wrap before anything will happen.
  // It also causes problems in hal_if.c's delay_us function because
  // you get returned clock values way in excess of the period.
  // The solution is for the first programming of the period here,
  // to set the clock to trigger effectively straight away so it
  // resets to 0.

  piv = period-1;

  // First we note whether the timer had already been enabled or not.
  HAL_READ_UINT32(_PITC_PIMR, pimr);

  // Now disable timer so that it can't wrap without us noticing.
  // But to make things nicer against the hardware, we may as well
  // use the correct desired period so that it can stop there if
  // it's close.
  HAL_WRITE_UINT32(_PITC_PIMR, piv);

  // Had timer been enabled before?
  if ( pimr & _PITC_PIMR_PITEN )
  {
      CYG_INTERRUPT_STATE intstate;

      // It was, so let's read the value and check against the period.
      // We disable interrupts to guarantee our calculations don't
      // get ruined.

      HAL_DISABLE_INTERRUPTS(intstate);

      HAL_READ_UINT32(_PITC_PIVR, pivr);
      if ((pivr & AT91_PITC_VALUE_MASK) >= piv)
      {
          cyg_uint32 fake_piv;

          // So this *is* the bad case to handle specially.

          fake_piv = (pivr&AT91_PITC_VALUE_MASK)+20; // 20 extra ticks includes a decent margin.

          // Set this new PIV, and let it get hit, after which it gets disabled.
          HAL_WRITE_UINT32(_PITC_PIMR, fake_piv);

          // We can re-enable ints while we wait, even though it isn't long.
          HAL_RESTORE_INTERRUPTS(intstate);

          do {
              HAL_READ_UINT32(_PITC_PIVR, pivr);
          } while ((pivr & AT91_PITC_VALUE_MASK) >= piv);
      } else {
          HAL_RESTORE_INTERRUPTS(intstate);
      }
  }


  /* Can now correctly set Period Interval timer and enable interrupt */
  HAL_WRITE_UINT32(_PITC_PIMR, 
                   piv |  
                   _PITC_PIMR_PITEN |
                   _PITC_PIMR_PITIEN);
  
  // Read the value from the PIVR register to clear any pending interrupt
  HAL_READ_UINT32(_PITC_PIVR, pivr);
}

// This routine is called during a clock interrupt.
void
hal_clock_reset(cyg_uint32 vector, cyg_uint32 period)
{
  cyg_uint32 reg;
  
  CYG_ASSERT(period <= AT91_PITC_VALUE_MASK, "Invalid HAL clock configuration");
  
  // Check that the PIT has the right period.
  HAL_READ_UINT32(_PITC_PIMR, reg);
  if ((reg & AT91_PITC_VALUE_MASK) != (period - 1)){
    HAL_WRITE_UINT32(_PITC_PIMR, 
                     (period - 1) |  
                     _PITC_PIMR_PITEN |
                     _PITC_PIMR_PITIEN);
  }

  /* Read the value register so that we clear the interrupt */
  HAL_READ_UINT32(_PITC_PIVR, reg);
}

// Read the current value of the clock, returning the number of hardware
// "ticks" that have occurred (i.e. how far away the current value is from
// the start)
void
hal_clock_read(cyg_uint32 *pvalue)
{
  cyg_uint32 ir;
  
  HAL_READ_UINT32(_PITC_PIIR, ir);
  *pvalue = ir & AT91_PITC_VALUE_MASK;
}

// -------------------------------------------------------------------------
//
// Delay for some number of micro-seconds
// PIT is clocked at MCLK / 16
//
void hal_delay_us(cyg_int32 usecs)
{
  cyg_int64 ticks;
  cyg_uint32 val1, val2;
  cyg_uint32 piv;
  
  // Calculate how many PIT ticks the required number of microseconds
  // equate to. We do this calculation in 64 bit arithmetic to avoid
  // overflow.
  ticks = (((cyg_uint64)usecs) * 
           ((cyg_uint64)CYGNUM_HAL_ARM_AT91_CLOCK_SPEED))/16/1000000LL;
  
  // Calculate the wrap around period. 
  HAL_READ_UINT32(AT91_PITC + AT91_PITC_PIMR, piv);
  piv = (piv & AT91_PITC_VALUE_MASK) - 1; 
  
  hal_clock_read(&val1);
  while (ticks > 0) {
    hal_clock_read(&val2);
    if (val2 < val1)
      ticks -= ((piv + val2) - val1); //overflow occurred
    else 
      ticks -= (val2 - val1);
    val1 = val2;
  }
}

// ----------------------------------------------------------------------------
// Profiling timer

#ifdef CYGPKG_PROFILE_GPROF
#include <cyg/profile/profile.h>
#include <cyg/hal/hal_arch.h>
#include <cyg/hal/hal_intr.h>
#include <cyg/hal/drv_api.h>

// Use TC0 by default. Change these defines to use a different timer.
#define AT91_TC_TC                      AT91_TC_TC0
#define CYGNUM_HAL_INTERRUPT_TIMER      CYGNUM_HAL_INTERRUPT_TC0
#define AT91_PMC_PCER_TC                AT91_PMC_PCER_TC0


static cyg_interrupt    profile_interrupt;
static cyg_handle_t     profile_handle;

static  void
profile_dsr(cyg_vector_t vector, cyg_ucount32 count, cyg_addrword_t data)
{
    CYG_UNUSED_PARAM(cyg_vector_t, vector);
    CYG_UNUSED_PARAM(cyg_ucount32, count);
    CYG_UNUSED_PARAM(cyg_addrword_t, data);
}

static cyg_uint32
profile_isr(cyg_vector_t vector, cyg_addrword_t data, HAL_SavedRegisters* regs)
{
    cyg_uint32  sr;
    HAL_READ_UINT32(AT91_TC + AT91_TC_TC + AT91_TC_SR, sr);
    __profile_hit(regs->pc);
    HAL_INTERRUPT_ACKNOWLEDGE(vector);
    return CYG_ISR_HANDLED;
}

int
hal_enable_profile_timer(int resolution)
{
    // The requested resolution is in microseconds. We take the system
    // clock CYGNUM_HAL_ARM_AT91_CLOCK_SPEED, typically something like
    // 32MHz, and divide by 32 to get an approximate MHz clock. Each
    // clock offers 16-bit resolution so that makes a maximum clock
    // interval of 65ms. The exact resolution is up to the application
    // but the docs suggest a value of the order of 3ms.

    cyg_uint32  tc_rc   = (cyg_uint32)(((long long) resolution * (long long)CYGNUM_HAL_ARM_AT91_CLOCK_SPEED) / 32000000LL);
    
    // Limit the profiling timer to a 16-bit counter.
    if (tc_rc > 65535) {
        tc_rc = 65535;
    }
    // Work out the actual resolution, allowing for rounding.
    resolution          = (cyg_uint32)(((long long) tc_rc * 32000000LL) / (long long)CYGNUM_HAL_ARM_AT91_CLOCK_SPEED);
      
    cyg_drv_interrupt_create( CYGNUM_HAL_INTERRUPT_TIMER, 1, 0, (cyg_ISR_t*) &profile_isr, &profile_dsr, &profile_handle, &profile_interrupt);
    cyg_drv_interrupt_attach(profile_handle);

    // Enable peripheral clock for the selected timer
    HAL_WRITE_UINT32(AT91_PMC+AT91_PMC_PCER, AT91_PMC_PCER_TC );
    
    // Initialize the timer
    HAL_WRITE_UINT32(AT91_TC + AT91_TC_TC + AT91_TC_CCR, AT91_TC_CCR_CLKDIS);
    HAL_WRITE_UINT32(AT91_TC + AT91_TC_TC + AT91_TC_CMR, AT91_TC_CMR_CPCTRG | AT91_TC_CMR_CLKS_MCK32);
    HAL_WRITE_UINT32(AT91_TC + AT91_TC_TC + AT91_TC_RC, tc_rc);
    HAL_WRITE_UINT32(AT91_TC + AT91_TC_TC + AT91_TC_CCR, AT91_TC_CCR_TRIG | AT91_TC_CCR_CLKEN);
    HAL_WRITE_UINT32(AT91_TC + AT91_TC_TC + AT91_TC_IER, AT91_TC_IER_CPC);
    
    cyg_drv_interrupt_unmask(CYGNUM_HAL_INTERRUPT_TIMER);
    return resolution;
}
#endif

// ----------------------------------------------------------------------------
// timer_pit.c
