/*============================================================================= Name: mpsCommunication.c mpsCommunicationInit - Initialize MPS Communication mpsCommunicationReport - MPS Communication Report mpsCommunicationRcvd - Callback when message is received mpsCommunicationGet - Get MPS modifier mpsCommunicationPut - Put MPS modifier and state mpsCommunicationInitTS - Put First and Second Time Slot Numbers mpsCommunicationState - Get and Reset Diagnostic Counts Abs: Driver support for MPS UDP communication on 2nd ethernet port. Auth: 21-oct-2009, Stephen Norum (snorum): Rev: 29-oct-2009, S. Allison (saa) -----------------------------------------------------------------------------*/ #include "copyright_SLAC.h" /* SLAC copyright comments */ /*----------------------------------------------------------------------------- Mod: (newest to oldest) =============================================================================*/ #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef __rtems__ #include #include #include #include #include #include #if (__RTEMS_MAJOR__ > 4) || (__RTEMS_MAJOR__ == 4 && __RTEMS_MINOR__ >= 9) #define Timer_initialize benchmark_timer_initialize #define Read_timer benchmark_timer_read #endif void drvMveIpBasicPrintConfiguration(void); /* Divisor to go from ticks to microseconds */ #ifdef __PPC__ static double mpsTicksPerUsec = 1; #endif /* * From Till Straumann: * Macro for "Move From Time Base" to get current time in ticks. * The PowerPC Time Base is a 64-bit register incrementing usually * at 1/4 of the PPC bus frequency (which is CPU/Board dependent. * Even the 1/4 divisor is not fixed by the architecture). * * 'MFTB' just reads the lower 32-bit of the time base. */ #ifdef __PPC__ #define MFTB(var) asm volatile("mftb %0":"=r"(var)) #else #define MFTB(var) (var)=Read_timer() #endif #ifdef DEBUG_ACTIVITY #define MAX_ACTIVITY_CNT 24 static MPSLPMessagePermit activity_as[MAX_ACTIVITY_CNT]; static int activityCnt = 0; static int activityGo = 1; #endif #endif /* MPS state */ #define MPS_STATE_OK 0 #define MPS_STATE_TIMEOUT 1 #define MPS_STATE_PARSE_ERROR 2 /* Current MPS modifier and state and their mutex */ static epicsUInt32 mpsModifier = 0; static unsigned long mpsState = MPS_STATE_TIMEOUT; static epicsTimeStamp mpsTime_s = {0}; static epicsMutexId mpsMutex_ps = 0; static unsigned long firstTimeSlot = 1; static unsigned long secondTimeSlot = 4; static unsigned long mpsModifierSim = 0; /* Diagnostic counters */ #define MPS_MAX_INT (2147483647) #define MAX_DELTA_TIME 1000000 static unsigned long msgCount = 0; /* # messages processed since boot/reset */ static unsigned long msgRolloverCount = 0; /* # times msgCount reached MPS_MAX_INT */ static unsigned long invalidMsgCount = 0; /* # bad messages */ static unsigned long unknownMsgCount = 0; /* # unexpected messages */ static unsigned long parseErrCount = 0; /* # message parsing errors */ static unsigned long timeoutCount = 0; /* # timeouts */ static unsigned long invalidTimeCount = 0; /* # invalid timestamps */ static unsigned long offByOneCount = 0; /* # where timestamp is old by one pulse */ /* Diagnostic time intervals (in ticks) */ static unsigned long mpsMsgTimeDeltaMax = 0; static unsigned long mpsMsgTimeDeltaMin = MAX_DELTA_TIME; static unsigned long mpsFidTimeDeltaMax = 0; static unsigned long mpsFidTimeDeltaMin = MAX_DELTA_TIME; extern unsigned long evrFiducialTime; #ifdef __rtems__ /*============================================================================= Name: mpsCommunicationRcvd Abs: Get message from MPS link processor UDP broadcast, translate it to pattern modifier, and update static data. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- int status Read Message status MPSLPMessage * message_ps Read Message void * context_p Read Callback argument (not used) Rem: None Side: Updates static data. Ret: None ==============================================================================*/ static void mpsCommunicationRcvd(int status, MPSLPMessage *message_ps, void *context_p) { unsigned long mpsStateInp; unsigned long mpsMsgTimePrev; unsigned long deltaTime; unsigned long mask; int idx; static unsigned long mpsMsgTime; static unsigned long mpsModifierPermit = 0; epicsUInt32 mpsModifierInp = 0; epicsTimeStamp mpsTimeInp_s = {0}; MPSLPMessagePermit *permitMessage_ps = (MPSLPMessagePermit *)message_ps; /* Keep a count of messages and reset before overflow */ if (msgCount < MPS_MAX_INT) { msgCount++; } else { msgRolloverCount++; msgCount = 0; } /* Update counters for errors. */ if (status == MPSLPMsgRcvdCallbackStatusTimeout) { timeoutCount++; mpsStateInp = MPS_STATE_TIMEOUT; } else if (status != MPSLPMsgRcvdCallbackStatusValidMessage) { invalidMsgCount++; return; /* Ignore synch message and check for valid message type. */ } else if (message_ps->type == MPSLinkProcessorMessageTypeSynchronization) { return; } else if (message_ps->type != MPSLinkProcessorMessageTypePermit) { unknownMsgCount++; return; } else { /* Check if message can be parsed */ if (MPSLPParsePermitMessage(permitMessage_ps)) { parseErrCount++; mpsStateInp = MPS_STATE_PARSE_ERROR; } else { #ifdef DEBUG_ACTIVITY if (activityGo) { activity_as[activityCnt] = *permitMessage_ps; activityCnt++; if (activityCnt >= MAX_ACTIVITY_CNT) activityCnt = 0; } #endif mpsStateInp = MPS_STATE_OK; mpsModifierInp = MPS_VALID; mpsTimeInp_s = permitMessage_ps->timestamp; mask = 0; /* Set destination bits */ if (permitMessage_ps->destination != MPSDestinationInvalid) { for (idx=1; idxdestination <= idx) || (mask >= MPS_DEST_MASK)) break; } mpsModifierInp |= mask; } /* Set permit bits */ for (idx = 0; idx < MPSMitigationDeviceCount; idx++) { mask = 1 << (idx + 20); /* PockelsCell and Bykik permits valid only on off-timeslots */ if (((idx != MPSMitigationDevicePockelsCell) && (idx != MPSMitigationDeviceBykik)) || ((permitMessage_ps->timeslot != firstTimeSlot) && (permitMessage_ps->timeslot != secondTimeSlot))) { if (permitMessage_ps->beamPermitted[idx]) mpsModifierPermit |= mask; else mpsModifierPermit &= ~mask; } } /* Use simulator input if provided */ if (mpsModifierSim) mpsModifierInp |= mpsModifierSim; else mpsModifierInp |= mpsModifierPermit; } } mpsCommunicationPut(mpsModifierInp, mpsStateInp, &mpsTimeInp_s); /* Get time of message and check for min and max delta time from message to message and */ mpsMsgTimePrev = mpsMsgTime; MFTB(mpsMsgTime); deltaTime = mpsMsgTime - mpsMsgTimePrev; if (deltaTime < MAX_DELTA_TIME) { if (mpsMsgTimeDeltaMax < deltaTime) mpsMsgTimeDeltaMax = deltaTime; if (mpsMsgTimeDeltaMin > deltaTime) mpsMsgTimeDeltaMin = deltaTime; } deltaTime = mpsMsgTime - evrFiducialTime; if (deltaTime < MAX_DELTA_TIME) { if (mpsFidTimeDeltaMax < deltaTime) mpsFidTimeDeltaMax = deltaTime; if (mpsFidTimeDeltaMin > deltaTime) mpsFidTimeDeltaMin = deltaTime; } } #endif /*============================================================================= Name: mpsCommunicationInit Abs: Inititalize communication with MPS link processor. Args: None. Rem: None. Side: None. Ret: -1 = Failed, 0 = OK. ==============================================================================*/ static int mpsCommunicationInit() { /* Initialize only once */ if (!mpsMutex_ps) { mpsMutex_ps = epicsMutexCreate(); if (!mpsMutex_ps) { errlogPrintf("mpsCommunicationInit: unable to create mutex\n"); return -1; } #ifdef __rtems__ #ifdef DEBUG_ACTIVITY memset(activity_as, sizeof(activity_as), 0); #endif /* Find divisor to go from ticks to microseconds (coarse resolution good enough). */ #ifdef __PPC__ mpsTicksPerUsec = ((double)BSP_bus_frequency/ (double)BSP_time_base_divisor)/1000; #else Timer_initialize(); #endif if (MPSLPInitializeCommunication()) { errlogPrintf("mpsCommunicationInit: unable to initialize MPS communication\n"); errlogPrintf("MPS Last Error: %s\n", MPSGetLastErrorString()); return -1; } if (MPSLPSetMpsMsgRcvdCallback(mpsCommunicationRcvd, NULL)) { errlogPrintf("mpsCommunicationInit: unable to set MPS receiver callback\n"); errlogPrintf("MPS Last Error: %s\n", MPSGetLastErrorString()); return -1; } if (MPSLPSetReceiveTimeoutCallback(1)) { errlogPrintf("mpsCommunicationInit: unable to request callback on timeout\n"); errlogPrintf("MPS Last Error: %s\n", MPSGetLastErrorString()); return -1; } if (MPSLPStartReceiveThread(epicsThreadPriorityMax)) { errlogPrintf("mpsCommunicationInit: unable to start the MPS receive thread\n"); errlogPrintf("MPS Last Error: %s\n", MPSGetLastErrorString()); return -1; } #endif } return 0; } /*============================================================================= Name: mpsCommunicationReport Abs: Report on communication with MPS link processor. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- int interest Read Interest level Rem: None. Side: None. Ret: -1 = Failed, 0 = OK. ==============================================================================*/ static int mpsCommunicationReport(int interest) { if (interest <= 0) return 0; printf("Since last reset:\n"); printf(" Number of message received/rollover: %lu/%lu\n", msgCount, msgRolloverCount); printf(" Number of timeouts: %lu\n", timeoutCount); printf(" Number of invalid messages: %lu\n", invalidMsgCount); printf(" Number of unknown messages: %lu\n", unknownMsgCount); printf(" Number of permit message parse errors: %lu\n", parseErrCount); printf(" Number of invalid timestamp in mpsCommunicationGet: %lu\n", invalidTimeCount); printf(" Number of off-by-one timestamps in mpsCommunicationGet: %lu\n", offByOneCount); #ifdef __rtems__ #ifdef __PPC__ printf(" Max/Min time between messages (us) = %lf/%lf\n", (double)mpsMsgTimeDeltaMax/mpsTicksPerUsec, (double)mpsMsgTimeDeltaMin/mpsTicksPerUsec); printf(" Max/Min time from pattern (us) = %lf/%lf\n", (double)mpsFidTimeDeltaMax/mpsTicksPerUsec, (double)mpsFidTimeDeltaMin/mpsTicksPerUsec); #else printf(" Max/Min time between messages (us) = %lu/%lu\n", mpsMsgTimeDeltaMax, mpsMsgTimeDeltaMin); printf(" Max/Min time from pattern (us) = %lu/%lu\n", mpsFidTimeDeltaMax, mpsFidTimeDeltaMin); #endif printf("udpComm diagnostics:\n"); drvMveIpBasicPrintConfiguration(); #ifdef DEBUG_ACTIVITY if (interest > 1) { int activityOldIdx, activityIdx, devIdx; activityGo = 0; activityOldIdx = activityCnt; for (activityIdx = 0; activityIdx < MAX_ACTIVITY_CNT; activityIdx++) { printf("Idx = %d, secPastEpoch = %8.8x, nsec = %8.8x, timeslot = %u, destination = %u, beamrate = %u, outputCard = %u\n", activityOldIdx, activity_as[activityOldIdx].timestamp.secPastEpoch, activity_as[activityOldIdx].timestamp.nsec, activity_as[activityOldIdx].timeslot, activity_as[activityOldIdx].destination, activity_as[activityOldIdx].estimatedBeamRate, activity_as[activityOldIdx].outputCard); for (devIdx = 0; devIdx < MPSMitigationDeviceCount; devIdx++) { printf(" devIdx = %d, beamPermitted = %u, rateAfterDevice = %u\n", devIdx, activity_as[activityOldIdx].beamPermitted[devIdx], activity_as[activityOldIdx].rateAfterDevice[devIdx]); } activityOldIdx++; if (activityOldIdx >= MAX_ACTIVITY_CNT) activityOldIdx = 0; } activityGo = 1; } #endif #endif return 0; } /*============================================================================= Name: mpsCommunicationGet Abs: Gets a copy of the MPS modifier for pattern update. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- evrTimeId_te id Read Pipeline ID (see evrTime.h) epicsUInt32 * mpsModifier_p Write MPS modifier Rem: None. Side: Lock/unlock mutex, read static data. Ret: -1 = Failed, 0 = OK ==============================================================================*/ int mpsCommunicationGet(evrTimeId_te id, epicsUInt32 *mpsModifier_p) { epicsTimeStamp mpsTimeCopy_s; epicsTimeStamp evrTime_s; if (mpsMutex_ps && (!epicsMutexLock(mpsMutex_ps))) { *mpsModifier_p = mpsModifier; mpsTimeCopy_s = mpsTime_s; epicsMutexUnlock(mpsMutex_ps); /* If the MPS modifier is good, then check the timestamp */ if (*mpsModifier_p) { if (evrTimeGetFromPipeline(&evrTime_s,id,0,0,0,0,0)) { *mpsModifier_p = 0; invalidTimeCount++; /* If the time is not as expected, perhaps MPS is a little slow. If we haven't moved the pipeline yet, try the current time. Allow to be off by one pulse but keep a counter. */ } else if (epicsTimeDiffInSeconds(&mpsTimeCopy_s, &evrTime_s) != 0.0) { if (id == evrTimeNext1) { id = evrTimeCurrent; if (evrTimeGetFromPipeline(&evrTime_s,id,0,0,0,0,0)) { *mpsModifier_p = 0; invalidTimeCount++; } else if (epicsTimeDiffInSeconds(&mpsTimeCopy_s, &evrTime_s) != 0.0) { *mpsModifier_p = 0; invalidTimeCount++; } else { offByOneCount++; } } else { *mpsModifier_p = 0; invalidTimeCount++; } } } return 0; } *mpsModifier_p = 0; return -1; } /*============================================================================= Name: mpsCommunicationPut Abs: Update MPS modifier and state - can be used for testing which is why the function is not static. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- epicsUInt32 mpsModifierInp Read MPS modifier unsigned long mpsStateInp Read MPS state epicsTimeStamp mpsTimeInp_ps Read MPS timestamp Rem: None. Side: Lock/unlock mutex, write static data. Ret: -1 = Failed, 0 = OK ==============================================================================*/ int mpsCommunicationPut(epicsUInt32 mpsModifierInp, unsigned long mpsStateInp, epicsTimeStamp *mpsTimeInp_ps) { if (mpsMutex_ps && (!epicsMutexLock(mpsMutex_ps))) { mpsModifier = mpsModifierInp; mpsState = mpsStateInp; mpsTime_s = *mpsTimeInp_ps; epicsMutexUnlock(mpsMutex_ps); return 0; } return -1; } /*============================================================================= Name: mpsCommunicationInitTS Abs: Set first and second time slots. Also, set simulated MPS modifier. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- unsigned long firstTimeSlotInp Read First time slot (1, 2, or 3) unsigned long secondTimeSlotInp Read Second time slot (4, 5, or 6) unsigned long mpsSimulatorInp Read MPS simulator permit bits Rem: None. Side: Lock/unlock mutex, write static data. Ret: -1 = Failed, 0 = OK ==============================================================================*/ int mpsCommunicationInitTS(unsigned long firstTimeSlotInp, unsigned long secondTimeSlotInp, unsigned long mpsSimulatorInp) { mpsCommunicationInit(); if (mpsMutex_ps && (!epicsMutexLock(mpsMutex_ps))) { firstTimeSlot = firstTimeSlotInp; secondTimeSlot = secondTimeSlotInp; mpsModifierSim = mpsSimulatorInp << 20; epicsMutexUnlock(mpsMutex_ps); return 0; } return -1; } /*============================================================================= Name: mpsCommunicationState Abs: Get and reset diagnostic counters. This subroutine is for status only and updates at a slow rate. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- longSubRecord * psub read point to subroutine record Rem: Subroutine for IOC:LOCA:UNIT:MPSDIAG Inputs: A - Spare B - Counter Reset Flag Z - Flag to Send Test Message to Link Processor (0 = don't send, 1 = send) Outputs: C - Number of timeout errors D - Number of messages processed by mpsCommunicationRcvd E - Number of times D has rolled over F - Number of invalid messages G - Number of unknown messages H - Number of message parse errors I - Minimum time between messages (us) J - Maximum time between messages (us) K - Minimum time from pattern (us) L - Maximum time from pattern (us) M - Number of invalid timestamps N - Number of pulses with timestamps which are off by one pulse Z - Reset to 0 VAL = MPS State Side: File-scope counters may be reset. Ret: 0 = OK ==============================================================================*/ static long mpsCommunicationState(longSubRecord *psub) { psub->val = mpsState; psub->c = timeoutCount; psub->d = msgCount; psub->e = msgRolloverCount; psub->f = invalidMsgCount; psub->g = unknownMsgCount; psub->h = parseErrCount; psub->i = mpsMsgTimeDeltaMin; psub->j = mpsMsgTimeDeltaMax; psub->k = mpsFidTimeDeltaMin; psub->l = mpsFidTimeDeltaMax; psub->m = invalidTimeCount; psub->n = offByOneCount; #ifdef __PPC__ psub->i = (unsigned long)(((double)(psub->i)/mpsTicksPerUsec) + 0.5); psub->j = (unsigned long)(((double)(psub->j)/mpsTicksPerUsec) + 0.5); psub->k = (unsigned long)(((double)(psub->k)/mpsTicksPerUsec) + 0.5); psub->l = (unsigned long)(((double)(psub->l)/mpsTicksPerUsec) + 0.5); #endif if (psub->z) { psub->z = 0; #ifdef __rtems__ MPSMessageSendTestMessage(); #endif } if (psub->b > 0) { psub->b = 0; timeoutCount = 0; msgCount = 0; msgRolloverCount = 0; invalidMsgCount = 0; unknownMsgCount = 0; parseErrCount = 0; invalidTimeCount = 0; offByOneCount = 0; mpsMsgTimeDeltaMax = 0; mpsMsgTimeDeltaMin = MAX_DELTA_TIME; mpsFidTimeDeltaMax = 0; mpsFidTimeDeltaMin = MAX_DELTA_TIME; } return 0; } struct drvet mpsCommunication = { 2, (DRVSUPFUN) mpsCommunicationReport, (DRVSUPFUN) mpsCommunicationInit }; epicsExportAddress(drvet, mpsCommunication); epicsRegisterFunction(mpsCommunicationState);