/*******************************************************************************
 * 
 *
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 *
 *
 *
 *
 ******************************************************************************/

#include <iop.h>
#include <string.h>
#include "diag.h"
#include "rvldv.h"
#include "iop.h"
#include "initvar.h"
#include "stress.h"

#include "stress_net.h"

#define PSEUDO_RAND
//#define STATIC_HOST
#ifdef STATIC_HOST
static u8 Host[4]        = {  10,   0,   0,  32 };
#endif

#define   MEM_ACCESS 
// unit in seconds
#define   TIMER_INTERVAL    60

#ifdef USE_NAPA
Module *mods[] = {  &modSha, /* &modFla, */ &modAes/* , &modSdi */};
#else
Module *mods[] = { &modFla, &modSha, &modAes, &modSdi, &modTcp, &modUdp, &modNewTcp, &modEs};
#endif

static  u32             config_mods;
static  u32             realMods = 0;
#define MAX_MOD         (sizeof(mods)/sizeof(mods[0]))
#define MSG_QUE         (MAX_MOD + 2)

static  u32  timerTicks;

#ifdef PSEUDO_RAND
static  u32  rand_state;
#endif

// default max time
#ifdef MODULE_CONCLUDE
IOSMessageQueueId stressMain = -1;
IOSMessage        stressQueue[MSG_QUE];
IOSTimerId        strTimer;
#endif
enum memArea memoryType;
u32 testThreshold = 0;
int D3Test = 1;

#ifdef MEM_ACCESS
#define           RDR_SIZE       128
IOSThreadId       strMemRead;
static u32        strRdrStack[RDR_SIZE] __attribute__ ((aligned(0x40)));
//static u32        strRdrBuffer[1024];

#define           MEM_CONVERT(x)  ((x+2) << 16)

static void
strMemRdr(void)
{
  int i;
  u32 addr/*  = (u32)strRdrBuffer */;
  
#ifdef USE_NAPA
  addr = MEM_CPU_ADDR;
#else
  addr = MEM_DDR_ADDR + MEM_CPU_ADDR;
#endif

  strPrint(STR_DEBUG_CRIT, "\nDefault memory access thread w/ priority %d and accessing 0x%08x\n", IOS_GetThreadPriority(0), addr);

  while (1) {
    for(i = 0; i < MEM_CLIENT_SIZE; i+=4) {
      busWrt32(addr + i, MEM_CONVERT(i));
    }
   
    IOS_FlushDCache((void *)addr, MEM_CLIENT_SIZE);
    
    for(i = 0; i < MEM_CLIENT_SIZE; i+=4) {
      if(MEM_CONVERT(i) != busRd32(addr+i)) {
        strPrint(STR_DEBUG_CRIT, "STR_memory:  reading 0x%08x did not provide expected output\n", addr+i);
      }
    }
  }

  return;
}
#endif

void 
doInitMods( void )
{
  int i;

  strPrint(STR_DEBUG_CRIT, "\nstress doInitMods()\n");
  
  // start up everything else
  for( i = 0 ; i < MAX_MOD ; i++ ) {
    if ( mods[i]->init ) {
      if(config_mods & mods[i]->test) {
        (mods[i]->init)();
        realMods ++;
      }
    }
  }
  
#ifdef MEM_ACCESS
  if (config_mods & CPU) {
    strMemRead = IOS_CreateThread((IOSEntryProc) strMemRdr,
                                  0,
                                  strRdrStack + RDR_SIZE,
                                  RDR_SIZE,
                                  IOS_GetThreadPriority(0) + PRIORITY_MOD - 2,
                                  IOS_THREAD_CREATE_DETACHED);
    if(strMemRead > 0)
      IOS_StartThread(strMemRead);
  }
#endif
}

void
doEndMods( void )
{
    int i;
 
    strPrint(STR_DEBUG_CRIT, "stress  doEndMods()\n");

    for( i = 0 ; i < MAX_MOD ; i++ ) {
        if ( mods[i]->end ) {
          if(config_mods & mods[i]->test) {
            (mods[i]->end)();
          }
        }
    }
#ifdef MEM_ACCESS
    IOS_DestroyThread(strMemRead, NULL);
#endif
}

void
doPrintStats( void )
{
  int i;
  for(i = 0; i < MAX_MOD; i ++) {
    if(mods[i]->stats) {
      if(config_mods & mods[i]->test) {
        (mods[i]->stats) ();
      }
    }
  }
  strPrint(STR_DEBUG_CRIT, "\n\n");
}

void
doNetworkInit( void )
{
  int rc;
#ifdef STATIC_HOST
  memcpy(&Config.addr,    Host,     4);
#endif
  memcpy(&Config.netmask, Netmask,    4);
  memcpy(&Config.router,  Gateway,    4);
  strPrint(STR_DEBUG_CRIT, "Stress %s: calling SOiStartup\n", __FUNCTION__); 
  rc = SOiStartup(&Config);
  strPrint(STR_DEBUG_DEBUG, "%s: SOiStartup return = %d\n", __FUNCTION__, rc);
  if (rc < 0) {
    strPrint(STR_DEBUG_CRIT, "%s: FAIL:  SOiStartup returned %d\n", __FUNCTION__, rc);
    return;
  }
  
  while (SOGetHostID() == 0) {
    if ((rc++)  % 2000 == 0)
      strPrint(STR_DEBUG_CRIT, ".");
    ;
  }
}

void
doStress( void )
{
  int timerCnt, modCtr;
  u32 currTime, oldTime;
  IOSMessage msg;

#ifdef AES_RESET
  config_mods = AES;
  doInitMods();
  strPrint(STR_DEBUG_CRIT, "Stress launched; please stop and relaunch stress_api.img\n");
  return; 
#endif

  config_mods = busRd32(STR_CONFIG); 
  if (config_mods & NETWORK) 
	  doNetworkInit();
  strPrint(STR_DEBUG_CRIT, "\n config using 0x%08x, read from 0x%08x\n", config_mods, STR_CONFIG);
  if (config_mods == 0x0)
    config_mods = 0xffffffff & ~(NEW_TCP);
  doInitMods();
  msg = timerCnt = modCtr = 0;

#ifdef MODULE_CONCLUDE
  stressMain = IOS_CreateMessageQueue(stressQueue, MSG_QUE);
  if(stressMain < 0) {
    strPrint(STR_DEBUG_CRIT, "Stress do:  msg queue cannot be created:  %d\n", stressMain);
    return;
  }

  strTimer = IOS_CreateTimer(0, TIMER_INTERVAL*1000*1000, stressMain, STR_TIMER);
  timerTicks = US_TO_TICKS_243(TIMER_INTERVAL*1000*1000);
  IOS_SetThreadPriority(0, IOS_GetThreadPriority(0)+4);

  if(strTimer >= 0) {
    strPrint(STR_DEBUG_CRIT, "Stress do:  %d out of %d (running @ priority %d)\n", modCtr, realMods, IOS_GetThreadPriority(0));
    while(modCtr < MAX_MOD) {
      oldTime = busGetTime();
      if(IOS_ReceiveMessage(stressMain, &msg, IOS_MESSAGE_BLOCK) == 0) {
        if(STR_DONE == msg) {
          strPrint(STR_DEBUG_CRIT, "Stress do:  %d out of %d\n", (++modCtr), MAX_MOD);
        }
        else if(STR_TIMER == msg) {
          currTime = busGetTime();
          strPrint(STR_DEBUG_CRIT, "\n\nTimer reached ... %4d ( * %d s; %d ticks; real interval:  %d)  ...\n", (++timerCnt), TIMER_INTERVAL, timerTicks, currTime - oldTime);
          doPrintStats();
        }
        else if(STR_FAIL == msg) {
          strPrint(STR_DEBUG_CRIT, "Stress do:  fail received, terminating all ...\n");
          break;
        }
      }
    }
  doEndMods();
  }

  IOS_DestroyMessageQueue(stressMain);
  IOS_DestroyTimer(strTimer);
#endif

}

void main( int argc, char * argv[] )
{
  strPrint(STR_DEBUG_CRIT, "stress running stress\n");

  /* Calculate which type of memory to be utilizing */

#ifdef USE_NAPA
  memoryType = NAPA;
#else
#ifdef USE_DDR
  memoryType = DDR;
#else
  memoryType = RAND;
#endif
#endif

#ifdef PSEUDO_RAND
  rand_state = busRd32(RAND_SEED_CFG);
  strPrint(STR_DEBUG_CRIT, "\nRANDOM generated with seed of 0x%08x\n", rand_state);
#endif

  doStress();
  
  strPrint(STR_DEBUG_CRIT, "stress terminating ...\n");
  IOS_DestroyThread(0, NULL);
  return;
}


#ifdef PSEUDO_RAND
u32 rand(int x) {
  u32 rem = (u32)RAND_M - ((u32)RAND_M % x);
  do {
    rand_state = (RAND_A * rand_state) + RAND_B;
  } while(rand_state >= rem);

  return rand_state % x;
}
#else
u32 rand(int x) {
  return (busRd32(SYS_TIMER_REG) % x);
}
#endif
