/* Simple Cache Testing */

#include "iop.h"

#define u32 unsigned int
#define busRd32(addr) (*(volatile u32 *)(addr))
#define busWrt32(addr, val) (*(volatile u32 *)(addr)) = (val)

#define MAX_DATA   100000
#define CTR_RUNS   1
#define ADDR_SPACE 0x00001000

u32     writeTime, readTime, tempTime;
u32     addr = ADDR_SPACE;

static void read(int size);
static void write(int size);
static void start();
static void stop(u32 *time);

u32 i, j;

void main(void)
{
  writeTime = readTime = tempTime = 0;
  u32 totalWrite=0, totalRead = 0, k;
  int x;
  char *loc = 0;
  
#ifdef DDR3
  loc = "DDR3";
#endif

#ifdef NAPA
  loc = "NAPA";
#endif

#ifdef SRAM
  loc = "SRAM";
#endif

  if(loc != 0)
    busPrintf("TIMING test running from %s Location.  Each test runs for %d iterations\n", loc, CTR_RUNS);
  else
    return;

  busPrintf("BTW, PREFETCH_REG = 0x%08x", busRd32(PHYS_TO_PROTECTED(AHM_BASE+AHMPREFC)));
  for(x = 0; x < 3; x ++) {
    busPrintf("\nTIMING test with addr==0x%08x\n", addr);
    
    busPrintf("Blocks\t\t|\tWrite\t\t|\tRead\t\t|\tTotal");
    
    for(i = 1; i <= MAX_DATA; i *= 10) {
      totalWrite = totalRead = 0;
      for(k = 0; k < CTR_RUNS; k ++) {
        write(i);
        read(i);
        totalWrite += writeTime;
        totalRead += readTime;
      }
      totalWrite /= CTR_RUNS;
      totalRead /= CTR_RUNS;
      busPrintf("%6d\t\t|\t%8d\t|\t%8d\t|\t%8d", i, totalWrite, totalRead, totalWrite+totalRead);
      writeTime = readTime = 0;
    }
    busPrintf("----------------------\n");
    
    if(0 == x)
      addr = (DDR_BASE | ADDR_SPACE);
#ifndef DDR3
    else
      addr = (SRN_SRAM_BASE | ADDR_SPACE);
#else
    else
      x = 4;
#endif
  }

  busPrintf("================================================\n");
  return;
}


static void read(int size)
{
  start();
  for(j = 0; j < size; j++)
    busRd32((addr + j*4));
  stop(&readTime);
}

static void write(int size)
{
  start();
  for(j = 0; j < size; j ++)
    busWrt32((addr+j*4), j);
  stop(&writeTime);
}

static void start()
{
  tempTime = busRd32(SYS_TIMER_REG);
}

static void stop(u32 *time)
{
  *time = busRd32(SYS_TIMER_REG) - tempTime;
}
