#include "archinc.h"
#include "cli.h"
#include "clichar.h"
#include "zarlink.h"

#include <stdio.h>
#include <stdlib.h>

#ifdef CONFIG_INCLUDE_ZARLINK

static unsigned char initialMacAddr[6] = {0x00, 0x00, 0x01, 0x6a, 0x0c, 0x00};

int zarlinkInit(void)
{
  lpc210x_reg dummy;
  int i;
  int bufLen;
  char * pOutBuf;
  unsigned char probeVal;

  pOutBuf = clicharGetOutputBuffer(&bufLen);

  probeVal = zarlinkIndexedRead(0xfff);

  if (probeVal != 0xda) {
    sprintf(pOutBuf, "\r\nzarlinkInit: ZL50409 not found, dareg[%02x]\r\n",probeVal);
    clicharSendOutputBuffer(pOutBuf, bufLen);
    return -1;
    }

  // magic write to keep switch from resetting if TSTOUT12 is high
  zarlinkIndexedWrite(0xe10, 0x07);

  // set one microsecond divider to 50 for 50MHz clock
  zarlinkIndexedWrite(0x609, 0x50);

  // reset all ports
  for(i=0;i<6;i++) {
    zarlinkIndexedWrite((0x81+(2*i)), 0x98);
    }

  // read an RTC register for some delay
  for(i=0;i<10;i++)
    dummy = CTIME0;

  // enable all ports
  for(i=0;i<6;i++) {
    zarlinkIndexedWrite((0x81+(2*i)), 0x18);
    }

  // enable receive of runt packets (<64b)
  for(i=0;i<6;i++) {
    zarlinkIndexedWrite((0x80+(2*i)), 0x01);
    }

  // force all fiber ports to 100BaseT, FDX
  for(i=0;i<4;i++) {
    zarlinkIndexedWrite((2*i), 0xd9);
    }

  zarlinkIndexedWrite(0x602, 0x11);

  // enable statistics engine, support multicast
  zarlinkIndexedWrite(0x602, 0x01);

  // support multicast
  zarlinkIndexedWrite(0x170, 0x40);

  // set a default mac address
  zarlinkCpuMacAddrSet(initialMacAddr);

  // tell the switch to start
  zarlinkIndexedWrite(0xf00, 0x10);

  return 0;
}

#endif /* CONFIG_INCLUDE_ZARLINK */

