/*=============================================================================
 
  Name: drvPnet.c
        pnetInitialize - hardware initialisation
        pnetReport     - driver report
        pnetISR        - interrupt service routine
        pnetTask       - high priority pnet processing task
        pnetRecord     - high priority record processing task

  Abs:  Driver support for VME PNET Receiver module. 
  
  Refs: See list of docs under the heading "VME PNET Module" on page:
        http://www.slac.stanford.edu/grp/lcls/controls/global/subsystems/timing

  Compiler Flags:
  DEBUG_PRINT - To define debug flag. 

  Auth: 07-jul-2005, Dayle Kotturi (dayle):
  Rev:  13-mar-2007, S. Allison (saa)

-----------------------------------------------------------------------------*/

#include "copyright_SLAC.h"	/* SLAC copyright comments */
 
/*-----------------------------------------------------------------------------
 
  Mod:  (newest to oldest)  
        DD-MMM-YYYY, My Name:
           Changed such and such to so and so. etc. etc.
        DD-MMM-YYYY, Your Name:
           More changes ... The ordering of the revision history 
           should be such that the NEWEST changes are at the HEAD of
           the list.
 
=============================================================================*/

#include "drvSup.h" 		/* for DRVSUPFN */
#ifdef __rtems__
#include "devLib.h"		/* for dev*routines, atVMEA16 */
#include "basicIoOps.h"         /* for in_be32 */
#include <bsp/gt_timer.h>       /* for BSP timer */
#endif
#include "errlog.h"		/* for errlogPrintf */
#include "epicsExport.h" 	/* for epicsExportAddress */
#include "epicsEvent.h" 	/* for epicsEvent* */
#include "epicsThread.h" 	/* for epicsThreadCreate */
#include "epicsTypes.h"
#include "debugPrint.h"		/* for DEBUGPRINT */
#include "evrMessage.h"		/* for evrMessage* protos */
#include "evrTime.h"		/* for evrTime proto */
#include "evrPattern.h"     /* for timeslot related definitions */
#include "mpgPattern.h"		/* for mpgPattern proto */
#include "mpgEvent.h"		/* for mpgEvent proto */
#include "bsa.h"		/* for bsa_init proto */
#include "mpsCommunication.h"	/* for mpsCommunication proto */
#include "devGenVar.h"
#include "dbAccess.h"
#include "alarm.h"
#include "initHooks.h"

#include <time.h>

/* NOTE: If drvPnet is ever thrown out completely then
 *       a new mini-driver must be created:
 *
 *       - install VMTG ISR (signals a epicsEvent)
 *       - create task that loops waiting for epicsEvent and
 *         executin mpgPattern.
 */
#ifdef HAVE_VMTG
#include <drvVMTG.h>
#endif

#define PNET_IRQ_LEVEL 		(1)	/* PNET interrupt level */
#define VMTG_IRQ_LEVEL 		(2)	/* VMTG interrupt level */
#define PNET_IRQ_VECTOR 	(0xAA)	/* PNET interrupt vector */
#define PNET_DEF_BASE_ADDRESS   (0x110) /* PNET default base address */
#define PNET_TIMEOUT            (0.05)  /* Timeout in sec waiting for 360hz input. */
#define PNET_HW_TIMER_ID        (0)     /* HW timer ID */
#define PNET_HW_TIMER_DELAY     (150)   /* delay in usec */

static int pnetReport();
static int pnetInitialize();
struct drvet drvPnet = {
  2,
  (DRVSUPFUN) pnetReport, 	/* subroutine defined in this file */
  (DRVSUPFUN) pnetInitialize 	/* subroutine defined in this file */
};
epicsExportAddress(drvet, drvPnet);

#ifdef DEBUG_PRINT
  /* ENUM with values: DP_FATAL, DP_ERROR, DP_WARN, DP_INFO, DP_DEBUG
     Anything less than or equal to drvPnetFlag gets printed out. Can
     be set to 0 here and altered via prompt or in st.cmd file */
int drvPnetFlag = 0;
#endif

int                     pnetDoFiducial = 1;
int                     pnetDelayTicks = 0;
static int              intrEnabled = 0;
static int              readyForPnet = 1;   /* pnetTask ready for new data */
static unsigned long    vmePnetAddr = PNET_DEF_BASE_ADDRESS; /* base addr of PNET */
static unsigned long   *pLocalBuf   = NULL; /* keep pLocalBuf a ptr for devRegAddr */
static epicsEventId     pnetTaskEventSem   = NULL;  /* pnet task semaphore  */
static epicsEventId     pnetRecordEventSem = NULL;  /* pnet record task sem */
volatile unsigned       pnetIRQs   = 0;
volatile unsigned       vmtgIRQs   = 0;
volatile epicsInt32     vmtgDiffUs = 0;
#define TSDIFF_INVAL 1111
#define TS_MAX          6
volatile epicsUInt32    vmtgTSDiff = TSDIFF_INVAL;
volatile int            pnetSeen   = 0;
volatile initHookState  pnetIocState = initHookAtIocBuild;

unsigned                pnetTimeNs = 0;

static DevGenVarRec     gv_tsdiff, gv_irqdel;

/*=============================================================================

  Name: pnetReport

  Abs: Driver support registered function for reporting system info

=============================================================================*/
static int pnetReport( int interest )
{
  if (interest > 0) {
    printf ("PNET Card Address = %8.8x,  Vector = %3.3X,  Level = %d, %s\n",
            (unsigned int)pLocalBuf, PNET_IRQ_VECTOR, PNET_IRQ_LEVEL,
            intrEnabled? "Enabled" : "Disabled");
    evrMessageReport(EVR_MESSAGE_PNET, EVR_MESSAGE_PNET_NAME, interest);
    if (pnetDoFiducial) {
      evrMessageReport(EVR_MESSAGE_FIDUCIAL, EVR_MESSAGE_FIDUCIAL_NAME,
                       interest);
    }
  }
  return interest;
}

/*=============================================================================
 
  Name: pnetTimerDone

  Abs: Wakes up pnetTask.

  Rem: None.

=============================================================================*/

static void pnetTimerDone (void *arg)
{
  if (pnetDoFiducial) evrMessageStart(EVR_MESSAGE_FIDUCIAL);
  epicsEventSignal(pnetTaskEventSem);
}

#ifdef HAVE_VMTG
static uint16_t
vmtg_handler(uint16_t irqs_pending, void *uarg)
{
struct timespec now;

  vmtgIRQs++;

  if ( pnetSeen ) {
	/* we don't care if a concurrent pnetISR intercepts the -- op */
    pnetSeen--;
	/* can only scan once the IOC is up; otherwise we lose early
	 * state changes of vmtgTSDiff
	 */
	if ( ! pnetSeen && pnetIocState >= initHookAfterIocRunning ) {
      vmtgTSDiff     = TSDIFF_INVAL;
      gv_tsdiff.stat = READ_ALARM;
      gv_tsdiff.sevr = INVALID_ALARM;

      vmtgDiffUs     = 2778;
      gv_irqdel.stat = READ_ALARM;
      gv_irqdel.sevr = INVALID_ALARM;

      devGenVarScan( &gv_tsdiff );
    }
  }

  clock_gettime( CLOCK_REALTIME, &now );
  if ( now.tv_nsec < pnetTimeNs ) {
    now.tv_nsec += 1000000000L;
  }
  vmtgDiffUs = (now.tv_nsec - pnetTimeNs)/1000;
  /* convert to +/- range around 0 */
  if ( vmtgDiffUs > 2778/2 )
	vmtgDiffUs -= 2778;

  if ( (irqs_pending &= REG_IRQ_CTRL_EI) )
	pnetTimerDone( 0 );
  return irqs_pending;
}
#endif

/*=============================================================================
 
  Name: pnetISR

  Abs: Process interrupts at PNET_IRQ_LEVEL - record start time and wake
       up pnetTask.  This routine also called by the simulator which is why
       it is not static.

  Rem: Strategy 1: read the entire buffer in before incrementing the pointer.
       This way the pointer always points to a complete buffer and so there
       is no chance of reading a partial buffer.

       Strategy 2: keep this routine to a minimum, so that CPU not blocked 
       too long processing each interrupt. Some lessons learned about what 
       can't be in an ISR, for the record.
        - no printfs
        - no floating point calculations
        - no calls to epicsTimeGetCurrent (while it's true that an epicsTime-
          stamp variable only contains longs, there is some sys call deep
          down that uses f.p. and throws the ISR into this error:
 
          rtems-4.6.2(PowerPC/PowerPC 7455/mvme5500)
          FATAL ERROR:
          Internal error: No
          Environment: RTEMS Core
            Error occurred in a Thread Dispatching DISABLED context (level 1)
            Error occurred from ISR context (ISR nest level 1)
          Error 18: INTERNAL_ERROR_CALLED_FROM_WRONG_ENVIRONMENT
          Stack Trace:

          0x000B9D2C--> 0x000B9D2C--> 0x000DE6B8--> 0x001103CC--> 0x01F3798C
          0x01F36EEC--> 0x01DA63B8--> 0x01D011A4--> 0x000BF460--> 0x000B8AA0
          0x000B8844--> 0x000B8ED8

=============================================================================*/
void pnetISR (void *arg)
{
struct timespec now;
#ifdef HAVE_VMTG
int             tsdiff;
#endif
  pnetIRQs++;
  pnetSeen = 10;
  clock_gettime( CLOCK_REALTIME, &now );
  pnetTimeNs = now.tv_nsec;
  evrMessageStart(EVR_MESSAGE_PNET);
#ifdef __rtems__
  if (arg) {
    unsigned long *buffer_a = (unsigned long *)arg;
    unsigned long ii;
    evrMessage_tu message_u;
    for (ii=0; ii<EVR_PNET_MODIFIER_MAX; ii++) {
      message_u.pnet_s.modifier_a[ii] =
        in_be32((volatile void *)&(buffer_a[ii]));
    }
#ifdef HAVE_VMTG
	/* VMTG timeslot counter is incremented at the same time
	 * the VMTG interrupt is asserted. Hence, at this point
	 * we get one timeslot ahead of the one the pabig will
	 * see when it runs for the next time.
	 * OTOH, during the next pabig cycle, THIS pnet pattern
	 * will be processed. Hence we increment the TS by one
	 * here for our diagnostic.
	 */
	tsdiff = vmtgGetTS() + 1;
	if ( TS_MAX < tsdiff )
		tsdiff = 1;
	/* subtract PNET timeslot */
	tsdiff    -= TIMESLOT(message_u.pnet_s.modifier_a); //((message_u.pnet_s.modifier_a[3]>>29) & 7);
	if ( tsdiff < 0 )
		tsdiff += TS_MAX;
	/* can only scan once the IOC is up; otherwise we lose early
	 * state changes of vmtgTSDiff
	 */
	if ( tsdiff != vmtgTSDiff && pnetIocState >= initHookAfterIocRunning ) {
		vmtgTSDiff = tsdiff;
        gv_tsdiff.stat = NO_ALARM;
        gv_tsdiff.sevr = NO_ALARM;
        devGenVarScan( &gv_tsdiff );
	}
#endif
    evrMessageWrite(EVR_MESSAGE_PNET, &message_u);
  }
#endif
  if (readyForPnet) {
    readyForPnet = 0;
#ifndef HAVE_VMTG
#ifdef __rtems__
    /* Delay for MPS input from the 2nd ethernet port.
       Sometimes MPS comes a little late.  pnetDelayTicks is made global
       so it can be tuned from Cexp if necessary. */
   if ((pnetDelayTicks == 0) ||
        (BSP_timer_start(PNET_HW_TIMER_ID, pnetDelayTicks)))
#endif
      pnetTimerDone(0);
#endif
  } else if (pnetDoFiducial) {
    evrMessageNoDataError(EVR_MESSAGE_FIDUCIAL);
  }
}

/*=============================================================================
                                                                                
  Name: pnetTask
                                                                                
  Abs:  This task performs record processing.                                                                         
  Rem:  It's started by pnetInitialize after the PNET module is configured. 
    
=============================================================================*/
static int pnetTask()
{
  epicsEventWaitStatus status;
  epicsUInt32          mpsModifier = 0;

  if (evrTimeInit(0,0)) {
    errlogPrintf("pnetTask: Exit due to bad status from evrTimeInit\n");
    return -1;
  }
  if (mpgPatternInit()) {
    errlogPrintf("pnetTask: Exit due to bad status from mpgPatternInit\n");
    return -1;
  }
  if (mpgEventSeqInit()) {
    errlogPrintf("pnetTask: Exit due to bad status from mpgEventSeqInit\n");
    return -1;
  }
  for (;;)
  {
    readyForPnet = 1;
    status = epicsEventWaitWithTimeout(pnetTaskEventSem, PNET_TIMEOUT);
    /* If data is available, advance the pipeline and then process the data */
    if (status == epicsEventWaitOK) {
      /* Get MPS data */
      if (mpsCommunicationGet(pnetDoFiducial?evrTimeNext1:evrTimeCurrent,
                              &mpsModifier)) mpsModifier = 0;
      if (pnetDoFiducial) evrTime(mpsModifier);    /* Move pipeline */
      mpgPattern(0, mpsModifier);
      mpgEventSeq();
      if (pnetDoFiducial) evrMessageEnd(EVR_MESSAGE_FIDUCIAL);
    /* If timeout, process the data which will result in bad status since there is
       nothing to do.  Then advance the pipeline so that the bad status makes it
       from N-3 to N-2 then to N-2 and then to N. Set MPS modifier to invalid. */
    } else {
      readyForPnet = 0;
      mpsModifier  = 0;
      mpgPattern(1, mpsModifier);  /* N-3 */
      if (pnetDoFiducial) {
        evrTime(mpsModifier);      /* N-2 */
        evrTime(mpsModifier);      /* N-1 */
        evrTime(mpsModifier);      /* N   */
      }
      mpgEventSeq();
      if (status != epicsEventWaitTimeout) {
        errlogPrintf("pnetTask: Exit due to bad status from epicsEventWaitWithTimeout\n");
        return -1;
      }
    }
    /* Now do record processing */
    epicsEventSignal(pnetRecordEventSem);
  }
  return 0;
}

/*=============================================================================
                                                         
  Name: pnetRecord

  Abs:  This task performs record processing for the fiducial and data.
  
  Rem:  It's started by pnetInitialize after the EVG module is configured. 
    
=============================================================================*/
static int pnetRecord()
{  
  for (;;)
  {
    if (epicsEventWait(pnetRecordEventSem)) {
      errlogPrintf("pnetRecord: Exit due to bad status from epicsEventWait\n");
      return -1;
    }
    evrMessageProcess(EVR_MESSAGE_PNET);
    if (pnetDoFiducial) evrMessageProcess(EVR_MESSAGE_FIDUCIAL);
    evrMessageEnd(EVR_MESSAGE_PNET);
  }
  return 0;
}

/*=============================================================================
 
  Name: pnetSetBaseAddress

  Abs:  Changes the base address of the PNET VME receiver board

  Rem:  Here's how to use it: 
        Call this in st.cmd prior to iocInit if you want to change 
        from the default base address which is the address to the start
        of the header (16 Bytes long), which is followed by 16 Bytes
        of data. 
 
=============================================================================*/
int pnetSetBaseAddress(unsigned long addr) {
  vmePnetAddr = addr;
  return 0;
}
int pnetEnableIntr() {

  if (!intrEnabled ) { /* only enable it once, even with recurring calls */
    
#ifdef __rtems__
      /* enable the interrupt. Note: if this code is executed, the LED on the 
         PNET board starts flashing */
      int rc = devEnableInterruptLevelVME(PNET_IRQ_LEVEL);
      if (rc != 0) {
        errlogPrintf("pnetEnableIntr: unable to enable the interrupt. rc = %d\n",
                     rc);
        return -1;
      }
#endif  /* ifdef __rtems__ */
      intrEnabled = 1;     
  }
  return 0;
}

int pnetDisableIntr() {

#ifdef __rtems__
  /* disable the interrupt. Note: if this code is executed, the LED on the 
     PNET board starts flashing */
  int rc = devDisableInterruptLevelVME(PNET_IRQ_LEVEL);
  if (rc != 0) {
    errlogPrintf("pnetDisableIntr: unable to disable the interrupt. rc = %d\n",
                 rc);
    return -1;
  }
#endif  /* ifdef __rtems__ */
  intrEnabled = 0;
  return 0;
}

static void recordStateHook(initHookState state)
{
	/* EPICS has no call to obtain the current IOC state :-( */
	pnetIocState = state;
}

static int pnetInitialize() {

  int rc;
  int pnetExists = 1;

  /* Initialize BSA */
  if (bsaInit()) return -1;

  initHookRegister( recordStateHook );

  devGenVarInitScanPvt( &gv_tsdiff, 1 );
  gv_tsdiff.data_p = &vmtgTSDiff;
  gv_tsdiff.dbr_t  = DBR_ULONG;

  devGenVarRegister("vmtgTSDiff", &gv_tsdiff, 1);

  devGenVarInit( &gv_irqdel, 1 );
  gv_irqdel.data_p = &vmtgDiffUs;
  gv_irqdel.dbr_t  = DBR_LONG;
  devGenVarRegister("vmtgIRQDel", &gv_irqdel, 1);


  /* Create space for the fiducial + diagnostics */
  if (pnetDoFiducial) {
    rc = evrMessageCreate(EVR_MESSAGE_FIDUCIAL_NAME, 0);
    if (rc != EVR_MESSAGE_FIDUCIAL) return -1;
  }
  /* Create space for the PNET message + diagnostics */
  rc = evrMessageCreate(EVR_MESSAGE_PNET_NAME, sizeof(evrMessagePnet_ts));
  if (rc != EVR_MESSAGE_PNET) return -1;
  /* Create the semaphore used by the ISR to wake up the pnet task */
  pnetTaskEventSem = epicsEventMustCreate(epicsEventEmpty);
  if (!pnetTaskEventSem) {
    errlogPrintf("pnetInitialize: unable to create the PNET task semaphore\n");
    return -1;
  }  
  pnetRecordEventSem = epicsEventMustCreate(epicsEventEmpty);
  if (!pnetRecordEventSem) {
    errlogPrintf("pnetInitialize: unable to create the PNET record task semaphore\n");
    return -1;
  }
  /* Create the tasks to process the fiducial and message */
  if (!epicsThreadCreate("pnetTask", epicsThreadPriorityMax+1,
                         epicsThreadGetStackSize(epicsThreadStackMedium),
                         (EPICSTHREADFUNC)pnetTask, 0)) {
    errlogPrintf("pnetInitialize: unable to create the PNET task\n");
    return -1;
  }
  if (!epicsThreadCreate("pnetRecord", epicsThreadPriorityHigh,
                         epicsThreadGetStackSize(epicsThreadStackMedium),
                         (EPICSTHREADFUNC)pnetRecord, 0)) {
    errlogPrintf("pnetInitialize: unable to create the PNET record task\n");
    return -1;
  }
  
#ifdef __rtems__

#ifndef HAVE_VMTG
  if (BSP_timer_setup(PNET_HW_TIMER_ID, pnetTimerDone, NULL, 0)) {
    errlogPrintf("pnetInitialize: unable to create the HW timer\n");
    return -1;
  }
  pnetDelayTicks = (unsigned int) 
    (((double)PNET_HW_TIMER_DELAY/(double)1E6) *
     (double)BSP_timer_clock_get(PNET_HW_TIMER_ID));
#endif

  /* Notes:
     - vmePnetAddr was set to default at boot but could have been changed by
     invoking pnetSetBaseAddress() prior to iocInit during startup. 
     - no volatile typecast on (void**) &pLocalBuf because pnetBackplane_t i
     is volatile 
     - last arg is ptr to a ptr - really. you get a warning re: incompatible 
     ptr type, but without '&', you only read zeroes (and you STILL have 
     the warning 
   */
  rc = devRegisterAddress( "pnet", atVMEA24, vmePnetAddr,
                           sizeof(unsigned long)*EVR_PNET_MODIFIER_MAX,
                           (void*)&pLocalBuf); 
  if (rc != 0) {
#ifndef HAVE_VMTG
    errlogPrintf("pnetInitialize: unable to register VME/A24 address 0x%08x\n",
                 (int) vmePnetAddr);
    return -1;
#endif
#ifdef HAVE_VMTG
    errlogPrintf("pnetInitialize: unable to register VME/A24 address 0x%08x\nbut, can keep going with the VMTG.\n",
                 (int) vmePnetAddr);
    pnetExists=0;
#endif

  }
  DEBUGPRINT(DP_INFO, drvPnetFlag,
             ("pnetInitialize: hardware registered at 0x%08x\n",
              (int) vmePnetAddr));
  

  /* connect up the interrupt vector with the interrupt service routine */
  if (pnetExists) {
    rc = devConnectInterruptVME(PNET_IRQ_VECTOR, pnetISR, (void *)pLocalBuf);
    if (rc != 0) {
      errlogPrintf("pnetInitialize: unable to connect intr vector to ISR. rc = %d\n",
                 rc);
      return -1;
    }
  }

#ifdef HAVE_VMTG
  {
  uint16_t omask;
  if ( vmtgInstallISR( vmtg_handler, 0 ) ) {
    errlogPrintf("pnetInitialize: unable to install VMTG ISR\n");
	return -1;
  }
  omask = vmtgIrqsDisable();
  if ( ! (omask & REG_IRQ_CTRL_LVL_MASK) ) {
	/* no level in use yet - share PNET level; it will
	 * be enabled at the board below. If the VMTG is
	 * already using a level then we'll use it and assume
	 * the 'other' user is enabling it at the board.
     */
	omask |= REG_IRQ_CTRL_LVL( VMTG_IRQ_LEVEL );
#if defined(VMTG_IRQ_LEVEL) && (VMTG_IRQ_LEVEL != PNET_IRQ_LEVEL)
	devEnableInterruptLevelVME( VMTG_IRQ_LEVEL );
#endif
  }
  omask |= REG_IRQ_CTRL_EI;
  vmtgIrqsEnable( omask );
  }
#endif
#endif  /* ifdef __rtems__ */

  /* enable the interrupt. Note: if this code is executed,
     the LED on the PNET board starts flashing */
  if (pnetExists && pnetEnableIntr()) return -1;

  return (0);
}
