/* * MachineStateBuffer.c * MPS Link Processor * * Created by Stephen Norum. * Copyright 2007 Stanford Linear Accelerator Center. All rights reserved. * * Interface and storage of autorecover, device state, bypass value, and bypass activity for each MPS fault input. */ /* Includes */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "MachineStateBuffer.h" #include "HistoryCommunication.h" #include "LinkNodeCommunication.h" #include "Timing.h" #include "MPSConfiguration.h" /* Structs and Typedefs */ struct bypassActiveTimerDataElement { ELLNODE listNode; unsigned long faultNumber; epicsUInt32 secPastEpoch; }; typedef struct bypassActiveTimerDataElement bypassActiveTimerData; /* * Local Variables */ /* Data structure to hold Link Node, Card, and Channel information */ static mpsLinkNode linkNode[MPSLinkNodeMaxCount]; /* Queue and handle for bypass active timer */ static epicsTimerQueueId bypassActiveTimerQueue; static epicsTimerId bypassActiveTimerID; /* One list to hold which inputs are actively bypassed. */ /* A second list to hold free nodes for use in the first list. */ static ELLLIST bypassActiveTimerList; static ELLLIST freeBypassActiveTimerList; static epicsUInt8 bypassTimesPvShouldUpdateEventId = 0; /* An array of booleans storing which inputs are autorecoverable. One byte per input. */ static char autorecover[FAULT_ARRAY_SIZE]; /* An array of booleans storing whether or not a fault is unlatchable. */ static char isUnlatchableBuffer[FAULT_ARRAY_SIZE]; /* An array of epicsUInt8 storing truth table states */ static char truthTableBuffer[MPSMaxTruthTableCount]; /* The path to Bypass Recover file */ static char bypassRecoverDefaultFilePath[1024] = ""; /* * Global Variables */ /* deviceStateBuffer * Description: An array of booleans showing current device states. One byte * per state. * Values: 0 represents a faulted or inactive state * 1 represents a non-faulted, OK, or active state * * * latchedDeviceStateBuffer * Description: An array of booleans showing latched device states. * Auto-recover devices are always equal to their corresponding * deviceStateBuffer. One byte per state. * Values: 0 represents a faulted or inactive state * 1 represents a non-faulted, OK, or active state * * * chatterBuffer * Description: An array of booleans that overides deviceStateBuffer. One byte * per state. * Values: See deviceStateBuffer * * * bypassValueBuffer * Description: An array of booleans storing the value that will be used by the * machine protection algorithm when a device state is bypassed. * One byte per value. * Values: See deviceStateBuffer * * * bypassActiveBuffer * Description: An array of booleans storing whether or not a device state is * actively (currently) bypassed. One byte per state. * Values: 0 represents the device state not being bypassed * 1 repreesnts the device state being bypassed * * * machineStateBufferMutex * Description: A mutex for the global variables */ char deviceStateBuffer[FAULT_ARRAY_SIZE]; char latchedDeviceStateBuffer[FAULT_ARRAY_SIZE]; char chatterBuffer[FAULT_ARRAY_SIZE]; char bypassValueBuffer[FAULT_ARRAY_SIZE]; char bypassActiveBuffer[FAULT_ARRAY_SIZE]; static epicsMutexId machineStateBufferMutex; #if 0 #pragma mark - #pragma mark Mutexes #endif /**************************************************************************************** * Mutexes ***************************************************************************************/ void mpsMutexLockMachineStateBuffer() { epicsMutexLock(machineStateBufferMutex); } void mpsMutexUnlockMachineStateBuffer() { epicsMutexUnlock(machineStateBufferMutex); } #if 0 #pragma mark - #pragma mark Autorecover Buffer #endif /**************************************************************************************** * Autorecover Buffer ***************************************************************************************/ int setInputAutorecover(unsigned int faultNumber, char automatic) { if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } autorecover[faultNumber] = automatic ? epicsTrue : epicsFalse; return MPS_SUCCESS; } int inputIsAutorecoverable(unsigned int faultNumber) { if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return autorecover[faultNumber]; } #if 0 #pragma mark - #pragma mark Device State Buffer #endif /**************************************************************************************** * Device State Buffer ***************************************************************************************/ int getDeviceState(unsigned int faultNumber) { if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return deviceStateBuffer[faultNumber]; } int getLatchedDeviceState(unsigned int faultNumber) { if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return latchedDeviceStateBuffer[faultNumber]; } int getLinkNodeFaultState(unsigned int baseFaultNumber, unsigned int linkNodeId) { unsigned int faultNumber; faultNumber = baseFaultNumber + linkNode[linkNodeId].number; return getDeviceState(faultNumber); } int getLatchedLinkNodeFaultState(unsigned int baseFaultNumber, unsigned int linkNodeId) { unsigned int faultNumber; faultNumber = baseFaultNumber + linkNode[linkNodeId].number; return getLatchedDeviceState(faultNumber); } int deviceStateSetState(unsigned int faultNumber, epicsTimeStamp timestamp, char timeslot, char state) { char oldLatchedState; char newLatchedState; char newState; MPSHistoryMessage message; if (faultNumber >= FAULT_ARRAY_SIZE) { errlogPrintf("epicsFaultStateMakeOk: Argument out of range (%u)", faultNumber); return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } if (state != 0) { newState = chatterBuffer[faultNumber]; } else { newState = FAULTED; } epicsMutexLock(machineStateBufferMutex); oldLatchedState = latchedDeviceStateBuffer[faultNumber]; deviceStateBuffer[faultNumber] = newState; /* Only set latched state if it is autorecoverable... */ if (autorecover[faultNumber]) { latchedDeviceStateBuffer[faultNumber] = newState; } /* ... but always allow latch faulted states */ if (newState == FAULTED) { latchedDeviceStateBuffer[faultNumber] = FAULTED; } newLatchedState = latchedDeviceStateBuffer[faultNumber]; epicsMutexUnlock(machineStateBufferMutex); if (oldLatchedState != newLatchedState) { message.type = MPSHistoryMessageTypeFaultState; message.timestampWithPulseId = timestamp; message.timeslot = timeslot; message.oldValue = oldLatchedState; message.newValue = newLatchedState; message.id = faultNumber; mpsHistoryAddMessageToQueue(&message, sizeof(message)); } return oldLatchedState; } int deviceStateMakeOk(unsigned int faultNumber, epicsTimeStamp timestamp, char timeslot) { return deviceStateSetState(faultNumber, timestamp, timeslot, OK); } int deviceStateMakeFaulted(unsigned int faultNumber, epicsTimeStamp timestamp, char timeslot) { return deviceStateSetState(faultNumber, timestamp, timeslot, FAULTED); } int linkNodeFaultStateMakeOk(unsigned int baseFaultNumber, unsigned int linkNodeId, epicsTimeStamp timestamp, char timeslot) { unsigned int faultNumber; faultNumber = baseFaultNumber + linkNode[linkNodeId].number; return deviceStateMakeOk(faultNumber, timestamp, timeslot); } int linkNodeFaultStateMakeFaulted(unsigned int baseFaultNumber, unsigned int linkNodeId, epicsTimeStamp timestamp, char timeslot) { unsigned int faultNumber; faultNumber = baseFaultNumber + linkNode[linkNodeId].number; return deviceStateMakeFaulted(faultNumber, timestamp, timeslot); } int epicsFaultStateMakeOk(unsigned int faultNumber) { int err; MPSTimingData timingData; if ((faultNumber < EPICS_FAULT_NUMBER_BASE ) || (faultNumber > EPICS_FAULT_NUMBER_BASE + EPICS_FAULT_COUNT - 1)) { errlogPrintf("epicsFaultStateMakeOk: Argument out of range (%u)", faultNumber); return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } lockTimingMutexAndGetCurrentTimingData(&timingData); err = deviceStateMakeOk(faultNumber, timingData.timestamp, timingData.timeslot); return err; } int epicsFaultStateMakeFaulted(unsigned int faultNumber) { int err; MPSTimingData timingData; if ((faultNumber < EPICS_FAULT_NUMBER_BASE ) || (faultNumber > EPICS_FAULT_NUMBER_BASE + EPICS_FAULT_COUNT - 1)) { errlogPrintf("epicsFaultStateMakeOk: Argument out of range (%u)", faultNumber); return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } lockTimingMutexAndGetCurrentTimingData(&timingData); err = deviceStateMakeFaulted(faultNumber, timingData.timestamp, timingData.timeslot); return err; } int faultAllEpicsFaults() { unsigned int i; for (i = EPICS_FAULT_NUMBER_BASE; i < EPICS_FAULT_NUMBER_BASE + EPICS_FAULT_COUNT; i++) { epicsFaultStateMakeFaulted(i); } return MPS_SUCCESS; } int faultAllInputsForLinkNode(unsigned char linkNodeId, epicsTimeStamp timestamp, char timeslot) { unsigned int firstFaultNumber; unsigned int faultNumberCount; /* MPSHistoryMessage message; */ if ((linkNodeId < MPSLinkNodeIdMin) || (linkNodeId > MPSLinkNodeIdMax)) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } firstFaultNumber = linkNode[linkNodeId].faultNumberFirst; faultNumberCount = linkNode[linkNodeId].faultNumberCount; /* Fault all inputs for this Link Node */ memset((deviceStateBuffer + firstFaultNumber), FAULTED, faultNumberCount); memset((latchedDeviceStateBuffer + firstFaultNumber), FAULTED, faultNumberCount); /* message.type = MPSHistoryMessageTypeAllLinkNodeChannels; message.timestampWithPulseId = timestamp; message.timeslot = timeslot; message.id = linkNodeId; message.newValue = FAULTED; message.oldValue = FAULTED; mpsHistoryAddMessageToQueue(&message, sizeof(message)); */ return MPS_SUCCESS; } int explodeDeviceStatesWithAutorecover( unsigned int linkNodeId, unsigned int numberOfCards, unsigned int channelsPerCard, const unsigned char *newStates, epicsTimeStamp timestampWithPulseId, char timeslot ) { static MPSHistoryMessage message; unsigned int cardIndex, channelIndex, byte, bit; unsigned int faultNumber; char oldLatchedState; char newState; mpsLinkNodeCard *card; if ((linkNodeId < MPSLinkNodeIdMin) || (linkNodeId > MPSLinkNodeIdMax)) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } message.type = MPSHistoryMessageTypeFaultState; message.timestampWithPulseId = timestampWithPulseId; message.timeslot = timeslot; bit = 0; byte = 0; /* Set all device states respecting the autorecover mask */ /* Lock Mutex */ epicsMutexLock(machineStateBufferMutex); for (cardIndex = 0; cardIndex < numberOfCards; cardIndex++) { card = &(linkNode[linkNodeId].card[cardIndex]); bit = 0; for(channelIndex = 0; channelIndex < channelsPerCard; channelIndex++) { faultNumber = card->channel[channelIndex].faultNumber; if (faultNumber != 0) { oldLatchedState = latchedDeviceStateBuffer[faultNumber]; if ((newStates[byte] & (0x01 << bit)) != 0) { newState = chatterBuffer[faultNumber]; } else { newState = FAULTED; } deviceStateBuffer[faultNumber] = newState; /* Only set latched state if it is autorecoverable... */ if (autorecover[faultNumber]) { latchedDeviceStateBuffer[faultNumber] = newState; } /* ... but always allow latch faulted states */ if (newState == FAULTED) { latchedDeviceStateBuffer[faultNumber] = FAULTED; } if (oldLatchedState != latchedDeviceStateBuffer[faultNumber]) { message.id = faultNumber; message.oldValue = oldLatchedState; message.newValue = latchedDeviceStateBuffer[faultNumber]; mpsHistoryAddMessageToQueue(&message, sizeof(message)); } } bit = (bit + 1) % 8; /* Increment bit, rollover at 8 */ byte += (bit == 0) ? 1 : 0; /* If bit has rolled over, increment byte */ } } /* Unlock Mutex */ epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } #if 0 #pragma mark - #pragma mark Bypass Value Buffer #endif /**************************************************************************************** * Bypass Value Buffer ***************************************************************************************/ int getBypassValue(unsigned int faultNumber) { if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return bypassValueBuffer[faultNumber]; } int setBypassValue(unsigned int faultNumber, unsigned int state) { MPSTimingData timingData; MPSHistoryMessage message; int oldState, newState; if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } newState = state ? OK : FAULTED; /* Set the new value and send history message */ epicsMutexLock(machineStateBufferMutex); oldState = bypassValueBuffer[faultNumber]; bypassValueBuffer[faultNumber] = newState; epicsMutexUnlock(machineStateBufferMutex); if (oldState == newState) { return MPS_SUCCESS; } lockTimingMutexAndGetCurrentTimingData(&timingData); message.type = MPSHistoryMessageTypeBypassValue; message.timestampWithPulseId = timingData.timestamp; message.timeslot = timingData.timeslot; message.id = faultNumber; message.oldValue = oldState; message.newValue = newState; mpsHistoryAddMessageToQueue(&message, sizeof(message)); mpsUpdateBypassRecoverFile(); return MPS_SUCCESS; } #if 0 #pragma mark - #pragma mark Unlatch Buffer #endif /**************************************************************************************** * Unlatch Buffer ***************************************************************************************/ int unlatchAllFaults() { if (sizeof(latchedDeviceStateBuffer) != sizeof(deviceStateBuffer)) { return MPS_ERROR; } epicsMutexLock(machineStateBufferMutex); memcpy(latchedDeviceStateBuffer, deviceStateBuffer, sizeof(latchedDeviceStateBuffer)); epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } int unlatchFault(unsigned int faultNumber) { if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } epicsMutexLock(machineStateBufferMutex); latchedDeviceStateBuffer[faultNumber] = deviceStateBuffer[faultNumber]; epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } #if 0 #pragma mark - #pragma mark Bypass Active Buffer #endif /**************************************************************************************** * Bypass Active Buffer ***************************************************************************************/ int inputIsByassed(unsigned int faultNumber) { if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return bypassActiveBuffer[faultNumber]; } /* Lock machineStateBufferMutex before calling */ static bypassActiveTimerData* findInputInBypassActiveList(unsigned int faultNumber) { bypassActiveTimerData *batd; batd = (bypassActiveTimerData *) ellFirst(&bypassActiveTimerList); while (batd != NULL) { if (batd->faultNumber == faultNumber) { return batd; } batd = (bypassActiveTimerData *) ellNext((ELLNODE *) batd); } return NULL; } static int cancelBypassActive(unsigned int faultNumber) { bypassActiveTimerData *batd; MPSHistoryMessage message; MPSTimingData timingData; if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } epicsMutexLock(machineStateBufferMutex); /* Find the node */ batd = findInputInBypassActiveList(faultNumber); if (batd != NULL) { /* Deactivate bypass */ bypassActiveBuffer[batd->faultNumber] = epicsFalse; /* Return the node to the free list */ ellDelete(&bypassActiveTimerList, (ELLNODE *) batd); ellAdd (&freeBypassActiveTimerList, (ELLNODE *) batd); } epicsMutexUnlock(machineStateBufferMutex); if (batd == NULL) { return MPS_SUCCESS; } lockTimingMutexAndGetCurrentTimingData(&timingData); message.type = MPSHistoryMessageTypeBypassTime; message.timestampWithPulseId = timingData.timestamp; message.timeslot = timingData.timeslot; message.id = faultNumber; message.oldValue = 0; message.newValue = 0; mpsHistoryAddMessageToQueue(&message, sizeof(message)); if (bypassTimesPvShouldUpdateEventId != 0) { post_event(bypassTimesPvShouldUpdateEventId); } mpsUpdateBypassRecoverFile(); return MPS_SUCCESS; } int setBypassActiveUntilExpirationTimestamp(unsigned int faultNumber, epicsUInt32 bypassExpirationTimestamp) { static MPSHistoryMessage message; bypassActiveTimerData *newNode; bypassActiveTimerData *activeNode; MPSTimingData timingData; epicsTimeStamp currentTime; epicsTimeGetCurrent(¤tTime); if (bypassExpirationTimestamp <= currentTime.secPastEpoch) { return cancelBypassActive(faultNumber); } if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } /* Lock the free and active bypass active timer lists */ epicsMutexLock(machineStateBufferMutex); /* * Check to see if a node with this fault number is already in active list. * Use this node if found, otherwise get a node from the free list. */ newNode = findInputInBypassActiveList(faultNumber); if (newNode != NULL) { /* * Treat newNode like it came from the free list. * Remove newNode from active list. */ ellDelete(&bypassActiveTimerList, (ELLNODE *) newNode); } else { /* * Node isn't already in the active list. Get a node from the free list. * Note that ellGet gets and removes the first node of a list. */ newNode = (bypassActiveTimerData *) ellGet(&freeBypassActiveTimerList); } if (newNode == NULL) { /* * No free nodes are available. * Unlock the free and used bypass active timer lists and * return an error. */ epicsMutexUnlock(machineStateBufferMutex); errlogPrintf("setBypassActiveForDurationInSeconds no free nodes in " "freeBypassActiveTimerList. Signal not bypassed."); return MPS_ERROR_EMPTY_LIST; } /* * Find correct location to insert the node */ activeNode = (bypassActiveTimerData *) ellFirst(&bypassActiveTimerList); while (activeNode != NULL) { if (bypassExpirationTimestamp < activeNode->secPastEpoch) { break; } activeNode = (bypassActiveTimerData *) ellNext((ELLNODE *) activeNode); } /* * Insert the new node into the active list */ if (activeNode == NULL) { /* Either bypassActiveTimerList is empty or node should be added to the end of the list */ ellAdd(&bypassActiveTimerList, (ELLNODE *) newNode); } else { /* Insert the node in the middle or beginning of the list */ ellInsert(&bypassActiveTimerList, ellPrevious((ELLNODE *) activeNode), (ELLNODE *) newNode); } /* * Configure the node and make the bypass active */ newNode->faultNumber = faultNumber; newNode->secPastEpoch = bypassExpirationTimestamp; bypassActiveBuffer[newNode->faultNumber] = epicsTrue; /* Unlock the free and used bypass active timer lists */ epicsMutexUnlock(machineStateBufferMutex); lockTimingMutexAndGetCurrentTimingData(&timingData); message.type = MPSHistoryMessageTypeBypassTime; message.timestampWithPulseId = timingData.timestamp; message.timeslot = timingData.timeslot; message.id = faultNumber; message.oldValue = 0; message.newValue = bypassExpirationTimestamp; mpsHistoryAddMessageToQueue(&message, sizeof(message)); if (bypassTimesPvShouldUpdateEventId != 0) { post_event(bypassTimesPvShouldUpdateEventId); } mpsUpdateBypassRecoverFile(); return MPS_SUCCESS; } int setBypassActiveForDurationInSeconds(unsigned int faultNumber, epicsUInt32 timeInSeconds) { int status; epicsUInt32 bypassExpirationTimestamp; epicsTimeStamp currentTime; epicsTimeGetCurrent(¤tTime); bypassExpirationTimestamp = currentTime.secPastEpoch + timeInSeconds; if (bypassExpirationTimestamp < currentTime.secPastEpoch) { return MPS_ERROR; } status = setBypassActiveUntilExpirationTimestamp(faultNumber, bypassExpirationTimestamp); return status; } int getRemainingBypassActiveDurationForInput(unsigned int faultNumber, unsigned int *timeRemainingInSeconds) { int err; bypassActiveTimerData *batd; epicsTimeStamp currentTime; if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } if (timeRemainingInSeconds == NULL) { return MPS_ERROR_INVALID_ARGUMENT; } /* Initialize */ *timeRemainingInSeconds = ~(0); err = MPS_ERROR_ELEMENT_NOT_FOUND_IN_LIST; epicsTimeGetCurrent(¤tTime); /* Lock the bypass active mutex */ epicsMutexLock(machineStateBufferMutex); /* Find the requested input and compute its time remaining */ batd = (bypassActiveTimerData *) ellFirst(&bypassActiveTimerList); while (batd != NULL) { if (batd->faultNumber == faultNumber) { if (batd->secPastEpoch < currentTime.secPastEpoch) { err = MPS_ERROR; } else { *timeRemainingInSeconds = batd->secPastEpoch - currentTime.secPastEpoch; err = MPS_SUCCESS; } break; } batd = (bypassActiveTimerData *) ellNext((ELLNODE *) batd); } /* Unlock the bypass active mutex */ epicsMutexUnlock(machineStateBufferMutex); return err; } static void updateBypassActiveTimes(void *arg) { static unsigned int pvUpdateTime = 0; static MPSHistoryMessage message; static MPSTimingData timingData; int shouldUpdateBypassRecoverFile; bypassActiveTimerData *batd; /* Restart the timer */ epicsTimerStartDelay(bypassActiveTimerID, MPSBypassTimerResolutionSeconds); /* Initialize message */ lockTimingMutexAndGetCurrentTimingData(&timingData); message.type = MPSHistoryMessageTypeBypassTime; message.timestampWithPulseId = timingData.timestamp; message.timeslot = timingData.timeslot; message.oldValue = 0; message.newValue = 0; /* Check for expired bypasses */ shouldUpdateBypassRecoverFile = epicsFalse; epicsMutexLock(machineStateBufferMutex); batd = (bypassActiveTimerData *) ellFirst(&bypassActiveTimerList); while (batd != NULL) { if (batd->secPastEpoch > timingData.timestamp.secPastEpoch) { /* No more bypasses have expired */ break; } else { /* This bypass has expired */ /* Clear the bypass active for the current input */ bypassActiveBuffer[batd->faultNumber] = epicsFalse; /* Send a message logging that this fault's bypass has expired */ message.id = batd->faultNumber; mpsHistoryAddMessageToQueue(&message, sizeof(message)); /* Return the node to the free list */ ellDelete(&bypassActiveTimerList, (ELLNODE *) batd); ellAdd(&freeBypassActiveTimerList, (ELLNODE *) batd); shouldUpdateBypassRecoverFile = epicsTrue; } /* Check the next upcoming node (the node now at the head of the list) */ batd = (bypassActiveTimerData *) ellFirst(&bypassActiveTimerList); } epicsMutexUnlock(machineStateBufferMutex); /* Update bypass time PVs */ pvUpdateTime = (pvUpdateTime + MPSBypassTimerResolutionSeconds) % MPSBypassUpdateBypassTimesPvPeriod; if ((pvUpdateTime == 0) && (bypassTimesPvShouldUpdateEventId != 0)) { post_event(bypassTimesPvShouldUpdateEventId); } if (shouldUpdateBypassRecoverFile) { mpsUpdateBypassRecoverFile(); } return; } void printBypassTimes() { epicsTimeStamp currentTime; bypassActiveTimerData *batd; epicsTimeGetCurrent(¤tTime); epicsMutexLock(machineStateBufferMutex); batd = (bypassActiveTimerData *) ellFirst(&bypassActiveTimerList); while (batd != NULL) { printf("\n%lu: %u (%u)", batd->faultNumber, batd->secPastEpoch, batd->secPastEpoch - currentTime.secPastEpoch); batd = (bypassActiveTimerData *) ellNext((ELLNODE *) batd); } printf("\n"); epicsMutexUnlock(machineStateBufferMutex); } int setBypassTimesPvShouldUpdateEventId(unsigned char eventId) { if (eventId == 0) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } bypassTimesPvShouldUpdateEventId = eventId; return MPS_SUCCESS; } unsigned int mpsBypassListToArrays(unsigned long *faultIdArray, unsigned long *bypassExpireTimestampArray, unsigned int numberOfElements) { bypassActiveTimerData *batd = NULL; unsigned int bypassedInputsCount = 0; if (numberOfElements < MPSBypassMaxNumberOfBypasses) { return 0; } epicsMutexLock(machineStateBufferMutex); batd = (bypassActiveTimerData *) ellFirst(&bypassActiveTimerList); while (batd != NULL) { *(faultIdArray++) = batd->faultNumber; *(bypassExpireTimestampArray++) = batd->secPastEpoch; bypassedInputsCount++; batd = (bypassActiveTimerData *) ellNext((ELLNODE *) batd); } epicsMutexUnlock(machineStateBufferMutex); return bypassedInputsCount; } unsigned int mpsBypassListToArraysWithValues(unsigned long *faultIdArray, unsigned long *bypassExpireTimestampArray, unsigned int *valueArray, unsigned int numberOfElements) { bypassActiveTimerData *batd = NULL; unsigned int bypassedInputsCount = 0; if (numberOfElements < MPSBypassMaxNumberOfBypasses) { return 0; } epicsMutexLock(machineStateBufferMutex); batd = (bypassActiveTimerData *) ellFirst(&bypassActiveTimerList); while (batd != NULL) { *(faultIdArray++) = batd->faultNumber; *(bypassExpireTimestampArray++) = batd->secPastEpoch; *(valueArray++) = bypassValueBuffer[batd->faultNumber]; bypassedInputsCount++; batd = (bypassActiveTimerData *) ellNext((ELLNODE *) batd); } epicsMutexUnlock(machineStateBufferMutex); return bypassedInputsCount; } int mpsBypassArraysToList(unsigned long *faultIdArray, unsigned long *bypassExpireTimestampArray, unsigned int *valueArray, unsigned int numberOfElements) { unsigned int i; for (i = 0; i < numberOfElements; i++) { setBypassValue(faultIdArray[i], valueArray[i]); setBypassActiveUntilExpirationTimestamp(faultIdArray[i], bypassExpireTimestampArray[i]); } return MPS_SUCCESS; } /* Bypass Recover File Format (JSON) * See http://www.json.org/ for JSON information * --------------------------------------------- * { * "format version": , * "epics timestamp": [, ], * "config db version": , * "bypass list": [[, , ], * [, , ], * ... * [, , ]] * } * --------------------------------------------- */ int mpsBypassListToFile(const char *path) { static unsigned int uniqueNumber = 0; static char tempPath[MPSMaxPathLength]; static unsigned long faultIdArray[MPSBypassMaxNumberOfBypasses]; static unsigned long bypassExpireTimestampArray[MPSBypassMaxNumberOfBypasses]; static unsigned int valueArray[MPSBypassMaxNumberOfBypasses]; unsigned int i, err; unsigned int numberOfElements = 0; epicsTimeStamp currentTime; char *listsep = ""; FILE *outfile; /* Get the current time */ epicsTimeGetCurrent(¤tTime); /* Get the data */ numberOfElements = mpsBypassListToArraysWithValues( faultIdArray, bypassExpireTimestampArray, valueArray, MPSBypassMaxNumberOfBypasses ); /* Open the output file * If no output path is specified, the file will be written to * bypassRecoverDefaultFilePath. */ if (path == NULL) { path = bypassRecoverDefaultFilePath; } /* Create a name for the temp file */ epicsSnprintf(tempPath, sizeof(tempPath), "%s.temp.%u", path, uniqueNumber); uniqueNumber++; outfile = fopen(tempPath, "w"); if (outfile == NULL) { errlogPrintf("mpsBypassListToFile: could not open \"%s\" for writing\n", tempPath); perror("mpsBypassListToFile"); return MPS_ERROR; } fprintf(outfile, "{\n"); fprintf(outfile, "\"format version\": %u,\n", MPSBypassFileFormatVersionCurrent); fprintf(outfile, "\"epics timestamp\": [%u, %u],\n", currentTime.secPastEpoch, currentTime.nsec); fprintf(outfile, "\"config db version\": \"%s\",\n", getenv(MPS_ENV_CONFIG_DATABASE_VERSION)); fprintf(outfile, "\"bypass list\": ["); listsep = ""; for (i = 0; i < numberOfElements; i++) { fprintf( outfile, "%s[%lu, %lu, %u]", listsep, faultIdArray[i], bypassExpireTimestampArray[i], valueArray[i] ); listsep = ",\n"; } fprintf(outfile, "]\n"); fprintf(outfile, "}\n"); err = fclose(outfile); if (err != 0) { perror("mpsBypassListToFile"); return MPS_ERROR; } /* Rename the temp file to the requested path */ #warning snorum: unlink should not be needed. However a "File exists" error occurs if the file at rename's newpath exists. unlink(path); /*Required due to NFS? Or maybe sticky bits set on the directory? */ err = rename(tempPath, path); if (err != 0) { errlogPrintf("mpsBypassListToFile: could not rename \"%s\" to \"%s\"\n", tempPath, path); perror("mpsBypassListToFile"); return MPS_ERROR; } return MPS_SUCCESS; } int mpsUpdateBypassRecoverFile() { return mpsBypassListToFile(NULL); } #if 0 #pragma mark - #pragma mark Link Node Accessors #endif int setLinkNodeActive(unsigned int linkNodeId, char isActive) { if ((linkNodeId < MPSLinkNodeIdMin) || (linkNodeId > MPSLinkNodeIdMax)) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } epicsMutexLock(machineStateBufferMutex); linkNode[linkNodeId].isActive = isActive ? epicsTrue : epicsFalse; epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } int linkNodeIsActive(unsigned int linkNodeId) { if ((linkNodeId < MPSLinkNodeIdMin) || (linkNodeId > MPSLinkNodeIdMax)) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return linkNode[linkNodeId].isActive; } int setLinkNodeType(unsigned int linkNodeId, char type) { if ((linkNodeId < MPSLinkNodeIdMin) || (linkNodeId > MPSLinkNodeIdMax)) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } if ((type < MPSLinkNodeTypeMitigationControl) || (type > MPSLinkNodeTypePic ) ) { return MPS_ERROR_INVALID_ARGUMENT; } epicsMutexLock(machineStateBufferMutex); linkNode[linkNodeId].type = type; epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } unsigned char linkNodeType(unsigned int linkNodeId) { if ((linkNodeId < MPSLinkNodeIdMin) || (linkNodeId > MPSLinkNodeIdMax)) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return linkNode[linkNodeId].type; } int setFaultNumberForLinkNodeCardAndChannel(unsigned int faultNumber, unsigned int linkNodeId, unsigned int card, unsigned int channel) { epicsMutexLock(machineStateBufferMutex); linkNode[linkNodeId].card[card - 1].channel[channel -1].faultNumber = faultNumber; if (linkNode[linkNodeId].faultNumberFirst == 0) { linkNode[linkNodeId].faultNumberFirst = faultNumber; } if (linkNode[linkNodeId].faultNumberFirst > faultNumber) { linkNode[linkNodeId].faultNumberFirst = faultNumber; } if (linkNode[linkNodeId].faultNumberLast < faultNumber) { linkNode[linkNodeId].faultNumberLast = faultNumber; } linkNode[linkNodeId].faultNumberCount = linkNode[linkNodeId].faultNumberLast - linkNode[linkNodeId].faultNumberFirst + 1; epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } unsigned int getFaultNumberForLinkNodeCardAndChannel(unsigned int linkNodeId, unsigned int card, unsigned int channel) { return linkNode[linkNodeId].card[card - 1].channel[channel - 1].faultNumber; } int setLinkNodeNumber(unsigned int linkNodeId, unsigned int number) { if ((linkNodeId < MPSLinkNodeIdMin) || (linkNodeId > MPSLinkNodeIdMax)) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } epicsMutexLock(machineStateBufferMutex); linkNode[linkNodeId].number = number; epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } void setLinkNodeNumbers() { unsigned int i; unsigned int number; number = 0; epicsMutexLock(machineStateBufferMutex); for (i = 0; i < sizeof(linkNode)/sizeof(linkNode[0]); i++) { if (linkNode[i].isActive) { linkNode[i].number = number; number++; } else { linkNode[i].number = 0; } } epicsMutexUnlock(machineStateBufferMutex); } unsigned int linkNodeNumber(unsigned int linkNodeId) { if ((linkNodeId < MPSLinkNodeIdMin) || (linkNodeId > MPSLinkNodeIdMax)) { return 0; } return linkNode[linkNodeId].number; } #if 0 #pragma mark - #pragma mark Mitigation Device Can Allow Beam Accessors #endif /**************************************************************************************** * Mitigation Device Can Allow Beam Accessors ***************************************************************************************/ int setCanAllowBeamAfterMitigationDevice(MPSMitigationDevice device, char canAllow) { MPSTimingData timingData; lockTimingMutexAndGetCurrentTimingData(&timingData); switch(device) { case MPSMitigationDeviceAll: deviceStateSetState(LP_BYPASS_RECOVER__INDEX, timingData.timestamp, timingData.timeslot, canAllow); break; case MPSMitigationDevicePockelsCell: deviceStateSetState(LP_ALLOWS_BEAM_POCKELS_CELL__INDEX, timingData.timestamp, timingData.timeslot, canAllow); break; case MPSMitigationDeviceMechanicalShutter: deviceStateSetState(LP_ALLOWS_BEAM_MECH_SHUT__INDEX, timingData.timestamp, timingData.timeslot, canAllow); break; case MPSMitigationDeviceBykik: deviceStateSetState(LP_ALLOWS_BEAM_BYKIK__INDEX, timingData.timestamp, timingData.timeslot, canAllow); break; case MPSMitigationDeviceFuture: deviceStateSetState(LP_ALLOWS_BEAM_LH_SHUT__INDEX, timingData.timestamp, timingData.timeslot, canAllow); break; default: return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return MPS_SUCCESS; } int canAllowBeamAfterMitigationDevice(MPSMitigationDevice device) { switch(device) { case MPSMitigationDeviceAll: return getLatchedDeviceState(LP_BYPASS_RECOVER__INDEX); case MPSMitigationDevicePockelsCell: return getLatchedDeviceState(LP_ALLOWS_BEAM_POCKELS_CELL__INDEX); case MPSMitigationDeviceMechanicalShutter: return getLatchedDeviceState(LP_ALLOWS_BEAM_MECH_SHUT__INDEX); case MPSMitigationDeviceBykik: return getLatchedDeviceState(LP_ALLOWS_BEAM_BYKIK__INDEX); case MPSMitigationDeviceFuture: return getLatchedDeviceState(LP_ALLOWS_BEAM_LH_SHUT__INDEX); default: return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return MPS_ERROR; } #if 0 #pragma mark - #pragma mark Chatter #endif /**************************************************************************************** * Chatter ***************************************************************************************/ int getChatter(unsigned int faultNumber) { if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return chatterBuffer[faultNumber]; } int setChatter(unsigned int faultNumber, unsigned int state) { int oldState, newState; if (faultNumber >= FAULT_ARRAY_SIZE) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } newState = state ? epicsTrue : epicsFalse; epicsMutexLock(machineStateBufferMutex); oldState = chatterBuffer[faultNumber]; chatterBuffer[faultNumber] = newState; epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } #if 0 #pragma mark - #pragma mark Truth Table States #endif /**************************************************************************************** * Truth Table ***************************************************************************************/ unsigned char truthTableState(unsigned int truthTableNumber) { if (truthTableNumber >= MPSMaxTruthTableCount) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } return truthTableBuffer[truthTableNumber]; } int setTruthTableState(unsigned int truthTableNumber, unsigned char state) { if (truthTableNumber >= MPSMaxTruthTableCount) { return MPS_ERROR_ARGUMENT_OUT_OF_RANGE; } /* Set the new value and send history message */ epicsMutexLock(machineStateBufferMutex); truthTableBuffer[truthTableNumber] = state; epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } int mpsCopyTruthTableStatusArray(unsigned char *dst, unsigned int maxElements) { if (maxElements < sizeof(truthTableBuffer) / sizeof(truthTableBuffer[0])) { return MPS_ERROR; } epicsMutexLock(machineStateBufferMutex); memcpy((void *) dst, (const void *) truthTableBuffer, sizeof(truthTableBuffer) / sizeof(truthTableBuffer[0])); epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } /* Must lock machineStateBuffer before calling */ int setAllTruthTableStatesToInvalid() { /* Set all truth table states to invalid */ memset(truthTableBuffer, MPSTruthTableStateInvalid, sizeof(truthTableBuffer)); return MPS_SUCCESS; } #if 0 #pragma mark - #pragma mark Other Accessors #endif /**************************************************************************************** * Other Accessors ***************************************************************************************/ int getMachineStateBuffers(MPSMachineStateBuffers *msb) { if (msb != NULL) { /* Buffer locations */ msb->deviceState = deviceStateBuffer; msb->latchedDeviceState = latchedDeviceStateBuffer; msb->bypassValue = bypassValueBuffer; msb->bypassActive = bypassActiveBuffer; msb->truthTableState = truthTableBuffer; /* Buffer sizes */ msb->deviceStateSize = sizeof(deviceStateBuffer); msb->latchedDeviceStateSize = sizeof(latchedDeviceStateBuffer); msb->bypassValueSize = sizeof(bypassValueBuffer); msb->bypassActiveSize = sizeof(bypassActiveBuffer); msb->truthTableStateSize = sizeof(truthTableBuffer); return MPS_SUCCESS; } return MPS_ERROR; } void printLinkNodeInfo(unsigned int linkNodeId) { if (!(linkNodeIsActive(linkNodeId))) { printf("Link Node %u is not active\n", linkNodeId); return; } printf("Fault Number First: %u\n", linkNode[linkNodeId].faultNumberFirst); printf(" Fault Number Last: %u\n", linkNode[linkNodeId].faultNumberLast); printf("Fault Number Count: %u\n", linkNode[linkNodeId].faultNumberCount); } #if 0 #pragma mark - #pragma mark Rate Requests #endif /**************************************************************************************** * Rate Requests ***************************************************************************************/ int mpsGetRateRequest(MPSMitigationDevice device, MPSBeamRate rate, epicsUInt32 *status) { unsigned int index = 0; int err = MPS_ERROR_INVALID_ARGUMENT; if(device == MPSMitigationDeviceAll) { switch (rate) { case MPSRateSingleShot: index = LP_MAX_RATE_SINGLE_SHOT__INDEX; break; case MPSRateBurstMode: index = LP_MAX_RATE_BURST__INDEX; break; default: err = MPS_ERROR_ARGUMENT_OUT_OF_RANGE; break; } } if (device == MPSMitigationDevicePockelsCell) { switch (rate) { case MPSRate60Hz: index = LP_MAX_RATE_PC_60_HZ__INDEX; break; case MPSRate30Hz: index = LP_MAX_RATE_PC_30_HZ__INDEX; break; case MPSRate10Hz: index = LP_MAX_RATE_PC_10_HZ__INDEX; break; case MPSRate1Hz: index = LP_MAX_RATE_PC_1_HZ__INDEX; break; case MPSRateSingleShot: index = LP_MAX_RATE_PC_SINGLE_SHOT__INDEX; break; case MPSRateBurstMode: index = LP_MAX_RATE_PC_BURST__INDEX; break; default: err = MPS_ERROR_ARGUMENT_OUT_OF_RANGE; break; } } if (device == MPSMitigationDeviceBykik) { switch (rate) { case MPSRate60Hz: index = LP_MAX_RATE_BYKIK_60_HZ__INDEX; break; case MPSRate30Hz: index = LP_MAX_RATE_BYKIK_30_HZ__INDEX; break; case MPSRate10Hz: index = LP_MAX_RATE_BYKIK_10_HZ__INDEX; break; case MPSRate1Hz: index = LP_MAX_RATE_BYKIK_1_HZ__INDEX; break; case MPSRateSingleShot: index = LP_MAX_RATE_BYKIK_SINGLE_SHOT__INDEX; break; case MPSRateBurstMode: index = LP_MAX_RATE_BYKIK_BURST__INDEX; break; default: err = MPS_ERROR_ARGUMENT_OUT_OF_RANGE; break; } } if (index == 0) { return err; } *status = getLatchedDeviceState(index); return MPS_SUCCESS; } int mpsSetRateRequest(MPSMitigationDevice device, MPSBeamRate rate, epicsUInt32 state) { MPSTimingData timingData; unsigned int index = 0; int err = MPS_ERROR_INVALID_ARGUMENT; if(device == MPSMitigationDeviceAll) { switch (rate) { case MPSRateSingleShot: index = LP_MAX_RATE_SINGLE_SHOT__INDEX; break; case MPSRateBurstMode: index = LP_MAX_RATE_BURST__INDEX; break; default: err = MPS_ERROR_ARGUMENT_OUT_OF_RANGE; break; } } if (device == MPSMitigationDevicePockelsCell) { switch (rate) { case MPSRate60Hz: index = LP_MAX_RATE_PC_60_HZ__INDEX; break; case MPSRate30Hz: index = LP_MAX_RATE_PC_30_HZ__INDEX; break; case MPSRate10Hz: index = LP_MAX_RATE_PC_10_HZ__INDEX; break; case MPSRate1Hz: index = LP_MAX_RATE_PC_1_HZ__INDEX; break; case MPSRateSingleShot: index = LP_MAX_RATE_PC_SINGLE_SHOT__INDEX; break; case MPSRateBurstMode: index = LP_MAX_RATE_PC_BURST__INDEX; break; default: err = MPS_ERROR_ARGUMENT_OUT_OF_RANGE; break; } } if (device == MPSMitigationDeviceBykik) { switch (rate) { case MPSRate60Hz: index = LP_MAX_RATE_BYKIK_60_HZ__INDEX; break; case MPSRate30Hz: index = LP_MAX_RATE_BYKIK_30_HZ__INDEX; break; case MPSRate10Hz: index = LP_MAX_RATE_BYKIK_10_HZ__INDEX; break; case MPSRate1Hz: index = LP_MAX_RATE_BYKIK_1_HZ__INDEX; break; case MPSRateSingleShot: index = LP_MAX_RATE_BYKIK_SINGLE_SHOT__INDEX; break; case MPSRateBurstMode: index = LP_MAX_RATE_BYKIK_BURST__INDEX; break; default: err = MPS_ERROR_ARGUMENT_OUT_OF_RANGE; break; } } if (index == 0) { return err; } state = state ? OK : FAULTED; lockTimingMutexAndGetCurrentTimingData(&timingData); epicsMutexLock(machineStateBufferMutex); deviceStateSetState(index, timingData.timestamp, timingData.timeslot, state); epicsMutexUnlock(machineStateBufferMutex); return MPS_SUCCESS; } #if 0 #pragma mark - #pragma mark Initialization #endif /**************************************************************************************** * Initialization ***************************************************************************************/ int initializeMachineStateBuffers() { int i; int okToShareTimer; bypassActiveTimerData *batd; char *bypassRecoverDir = NULL; epicsTimeStamp currentTime; /* Initialize mutex */ machineStateBufferMutex = epicsMutexMustCreate(); /* * Create a bypass active node for each input */ /* Get memory */ batd = (bypassActiveTimerData *) callocMustSucceed(MPSBypassMaxNumberOfBypasses, sizeof(bypassActiveTimerData), "initializeMachineStateBuffers"); epicsMutexLock(machineStateBufferMutex); /* Initialize bypass lists */ ellInit(&bypassActiveTimerList); ellInit(&freeBypassActiveTimerList); /* Add the nodes to the free list */ for (i = 0; i < MPSBypassMaxNumberOfBypasses; i++) { /* Add the node to the free list */ ellAdd(&freeBypassActiveTimerList, (ELLNODE *) batd); batd++; } epicsMutexUnlock(machineStateBufferMutex); /* Fault and clear all arrays */ memset(linkNode, 0x00, sizeof(linkNode)); memset(deviceStateBuffer, 0x00, sizeof(deviceStateBuffer)); memset(latchedDeviceStateBuffer, 0x00, sizeof(latchedDeviceStateBuffer)); memset(bypassValueBuffer, 0x00, sizeof(bypassValueBuffer)); memset(bypassActiveBuffer, 0x00, sizeof(bypassActiveBuffer)); memset(isUnlatchableBuffer, 0x00, sizeof(isUnlatchableBuffer)); memset(chatterBuffer, OK, sizeof(chatterBuffer)); memset(truthTableBuffer, MPSTruthTableStateInvalid, sizeof(truthTableBuffer)); /* Configure default bypass recover path */ bypassRecoverDir = getenv(MPS_ENV_BYPASS_RECOVER_DIR); epicsTimeGetCurrent(¤tTime); if (bypassRecoverDir == NULL) { bypassRecoverDir = ""; } epicsSnprintf(bypassRecoverDefaultFilePath, sizeof(bypassRecoverDefaultFilePath), "%s/bypass_recover-%u.json", bypassRecoverDir, currentTime.secPastEpoch); /* Initialize and start the bypass active timer queue */ okToShareTimer = 1; bypassActiveTimerQueue = epicsTimerQueueAllocate(okToShareTimer, epicsThreadPriorityScanLow); bypassActiveTimerID = epicsTimerQueueCreateTimer(bypassActiveTimerQueue, updateBypassActiveTimes, NULL); epicsTimerStartDelay(bypassActiveTimerID, MPSBypassTimerResolutionSeconds); return MPS_SUCCESS; }