/*
 SLAVE FIFO initialization and reset functions
 
 EP2(out) - control for all cycles, data for FPGA bus write cycles
 EP6(in)  - data for FPGA bus read cycles
 
 Copyright (c) 2008-2011 Dimtel, Inc., All Rights Reserved

 $Id: fifo.c,v 1.2 2013/06/06 04:35:11 dim Exp $
 $Date: 2013/06/06 04:35:11 $
 $Author: dim $
 $Revision: 1.2 $
 $Log: fifo.c,v $
 Revision 1.2  2013/06/06 04:35:11  dim
 Added EP8 OUT to interface 0 for fast JTAG block loading

 Revision 1.1  2012/11/11 01:24:32  dim
 Moved from BxB, adapted to compile for both LLRF4 and IGP12

 Revision 1.1  2011/12/27 19:31:45  dim
 Updated to remove deprecated constructs (at, sfr, xdata, sbit)


*/

#include "common.h"
#include "fx2regs.h"

void fifo_init(void)
{
  FIFORESET = bmNAKALL; /* Reset the FIFO */
  SYNCDELAY;
  FIFORESET = 0x02;
  SYNCDELAY;
  FIFORESET = 0x04;
  SYNCDELAY;
  FIFORESET = 0x06;
  SYNCDELAY;
  FIFORESET = 0x08;
  SYNCDELAY;
  FIFORESET = 0x00;
  SYNCDELAY;

  /* Flags and polarities */
  PINFLAGSAB = 0xe8;   /* Flag A - EP2 empty, Flag B - EP6 full */
  SYNCDELAY;
  FIFOPINPOLAR = 0x00; /* All interface pins active low */
  SYNCDELAY;

  /* IN endpoint setup (EP6):
     16-bit bus
     auto-in
     allow zero-length packets */
  EP6FIFOCFG = bmAUTOIN | bmZEROLENIN | bmWORDWIDE; 
  SYNCDELAY;
  if (USBCS & bmHSM)
  {
    EP6AUTOINLENH = 2;
    SYNCDELAY;
    EP6AUTOINLENL = 0;
  }
  else
  {
    EP6AUTOINLENH = 0;
    SYNCDELAY;
    EP6AUTOINLENL = 64;
  }
  SYNCDELAY;

  /* OUT endpoint setup (EP2):
     16-bit bus
     auto-out
  */
  EP2FIFOCFG = 0;
  SYNCDELAY;
  FIFORESET = bmNAKALL; // Reset the FIFO
  SYNCDELAY;
  FIFORESET = 0x02;
  SYNCDELAY;
  FIFORESET = 0x00;
  SYNCDELAY;
  OUTPKTEND = 0x82;
  SYNCDELAY;
  OUTPKTEND = 0x82;
  SYNCDELAY;
  EP2FIFOCFG = bmAUTOOUT | bmWORDWIDE;
  
  /* OUT endpoint setup (EP8):
     no auto-out
  */
  EP8FIFOCFG = 0;
  SYNCDELAY;
  FIFORESET = bmNAKALL; // Reset the FIFO
  SYNCDELAY;
  FIFORESET = 0x08;
  SYNCDELAY;
  FIFORESET = 0x00;
  SYNCDELAY;
  OUTPKTEND = 0x88;
  SYNCDELAY;
  OUTPKTEND = 0x88;
  SYNCDELAY;
  EP8FIFOCFG = bmWORDWIDE;
}
