/* * AlgorithmWrapper.c * mpsLinkProcessor * * Created by Stephen Norum. * Copyright 2007 Stanford Linear Accelerator Center. All rights reserved. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "AlgorithmWrapper.h" #include "MachineStateBuffer.h" #include "MachineRatesBuffer.h" #include "MPSConfiguration.h" /* Global variable: algorithm list */ ELLLIST algorithmList; /* Local variables */ static epicsMutexId algorithmFunctionMutex; static int (*algorithm)(void *arg); static algorithmData *runningAlgorithmData; static unsigned int loadableObjectVersions[2] = {2, 0}; static unsigned int algorithmCount; static char algorithmDataUpdatedEvent; static epicsMutexId algorithmListMutex; #if 0 #pragma mark - #pragma mark Accessors #endif /* Must lock algorithmListMutex before calling this function */ static algorithmData* getAlgorithmByInfo(unsigned int year, unsigned int month, unsigned int day, const char *revision) { algorithmData *ad; ad = (algorithmData *) ellFirst(&algorithmList); while (ad != NULL) { if ((ad->year == year) && (ad->month == month) && (ad->day == day) && (strncmp(ad->revision, revision, MPSAlgorithmRevisionStringMaxLength) == 0)) { /* Supplied data matches node */ break; } ad = (algorithmData *) ellNext((ELLNODE *) ad); } /* ad points to the found algorithm data or NULL if matching algorithm data is not found. */ return ad; } /* Must lock algorithmListMutex before calling this function */ /* A pointer to the running algorithm is returned for negative indexes. */ static algorithmData* getAlgorithmByIndex(int index) { int i = 0; algorithmData *ad; if (index < 0) { return runningAlgorithmData; } i = 0; ad = (algorithmData *) ellFirst(&algorithmList); while ((ad != NULL) && (i != index)) { i++; ad = (algorithmData *) ellNext((ELLNODE *) ad); } if (index != i) { ad = NULL; } /* ad points to the found algorithm data or NULL if matching algorithm data is not found. */ return ad; } int getAlgorithmName(int index, char *buffer, unsigned int bufferSize) { algorithmData *ad; int length; if ((buffer == NULL) || (bufferSize < 2)) { return 0; } buffer[0] = '-'; buffer[1] = '\0'; epicsMutexLock(algorithmListMutex); ad = getAlgorithmByIndex(index); if (ad != NULL) { epicsSnprintf(buffer, bufferSize, "%4u-%02u-%02u-%s", ad->year, ad->month, ad->day, ad->revision); } epicsMutexUnlock(algorithmListMutex); length = strlen(buffer) + 1; return length; } int getAlgorithmMpsDatabaseVersion(int index, char *buffer, unsigned int bufferSize) { algorithmData *ad; int length; if ((buffer == NULL) || (bufferSize < 2)) { return 0; } buffer[0] = '-'; buffer[1] = '\0'; epicsMutexLock(algorithmListMutex); ad = getAlgorithmByIndex(index); if (ad != NULL) { strncpy(buffer, ad->mpsDatabaseVersion, bufferSize); } epicsMutexUnlock(algorithmListMutex); length = strlen(buffer) + 1; return length; } int getAlgorithmCompileDate(int index, char *buffer, unsigned int bufferSize) { algorithmData *ad; int length; if ((buffer == NULL) || (bufferSize < 2)) { return 0; } buffer[0] = '-'; buffer[1] = '\0'; epicsMutexLock(algorithmListMutex); ad = getAlgorithmByIndex(index); if (ad != NULL) { strncpy(buffer, ad->compileDate, bufferSize); } epicsMutexUnlock(algorithmListMutex); length = strlen(buffer) + 1; return length; } int getAlgorithmCompileTime(int index, char *buffer, unsigned int bufferSize) { algorithmData *ad; int length; if ((buffer == NULL) || (bufferSize < 2)) { return 0; } buffer[0] = '\0'; epicsMutexLock(algorithmListMutex); ad = getAlgorithmByIndex(index); if (ad != NULL) { strncpy(buffer, ad->compileTime, bufferSize); } epicsMutexUnlock(algorithmListMutex); length = strlen(buffer) + 1; return length; } int getAlgorithmIsRunning (int index) { int status; algorithmData *ad; status = 0; epicsMutexLock(algorithmListMutex); ad = getAlgorithmByIndex(index); if (ad == runningAlgorithmData) { status = 1; } epicsMutexUnlock(algorithmListMutex); if ((ad != NULL) && (status != 1)) { /* Algorithm is loaded, but not running */ status = 0; } if (ad == NULL) { /* Algorithm is not loaded */ status = 2; } return status; } CexpModule getAlgorithmModuleHandle (unsigned int year, unsigned int month, unsigned int day, const char *revision) { algorithmData *ad; CexpModule handle; handle = NULL; epicsMutexLock(algorithmListMutex); ad = getAlgorithmByInfo(year, month, day, revision); if (ad != NULL) { handle = ad->moduleHandle; } epicsMutexUnlock(algorithmListMutex); return handle; } int setAlgorithmModuleHandle (unsigned int year, unsigned int month, unsigned int day, const char *revision, CexpModule handle) { algorithmData *ad; epicsMutexLock(algorithmListMutex); ad = getAlgorithmByInfo(year, month, day, revision); epicsMutexUnlock(algorithmListMutex); if (ad == NULL) { return MPS_ERROR; } ad->moduleHandle = handle; return MPS_SUCCESS; } int setAlgorithmListUpdatedEventId(char eventId) { algorithmDataUpdatedEvent = eventId; return MPS_SUCCESS; } void mpsAlgorithmListLockMutex() { epicsMutexLock(algorithmListMutex); } void mpsAlgorithmListUnlockMutex() { epicsMutexUnlock(algorithmListMutex); } int getAlgorithmList(ELLLIST *list) { if (list == NULL) { return MPS_ERROR; } *list = algorithmList; return MPS_SUCCESS; } #if 0 #pragma mark - #pragma mark Diagnostics #endif void mpsAlgorithmInfo() { algorithmData *ad; epicsMutexLock(algorithmListMutex); ad = (algorithmData *) ellFirst(&algorithmList); printf("Number of algorithms loaded: %d\n\n", ellCount(&algorithmList)); while(ad != NULL) { printf(" Name: %04d-%02d-%02d revision %s\n", ad->year, ad->month, ad->day, ad->revision); printf(" Handle: %p\n", ad->moduleHandle); printf("Function: %s (%p)\n", ad->functionName, ad->function); printf("Compiled: %s %s\n", ad->compileDate, ad->compileTime); printf(" MPS DB: %s\n", ad->mpsDatabaseVersion); printf(" Running: %s\n\n", ((ad == runningAlgorithmData) ? "Yes" : "No")); ad = (algorithmData *) ellNext((ELLNODE *) ad); } epicsMutexUnlock(algorithmListMutex); } void mpsRunningAlgorithmInfo() { /* Lock the algorithm list */ epicsMutexLock(algorithmListMutex); if (runningAlgorithmData == NULL) { printf("No algorithm running.\n"); } else { printf(" Version: %04d-%02d-%02d revision %s\n", runningAlgorithmData->year, runningAlgorithmData->month, runningAlgorithmData->day, runningAlgorithmData->revision); printf(" Handle: %p\n", runningAlgorithmData->moduleHandle); printf("Function: %s (%p)\n", runningAlgorithmData->functionName, runningAlgorithmData->function); printf("Compiled: %s %s\n", runningAlgorithmData->compileDate, runningAlgorithmData->compileTime); printf(" MPS DB: %s\n", runningAlgorithmData->mpsDatabaseVersion); } /* Unlock the algorithm list */ epicsMutexUnlock(algorithmListMutex); } #if 0 #pragma mark - #pragma mark Algorithm List #endif int mpsLoadAlgorithmRestoreFile(const char *path) { int err; const char *restoreFilePath; static char restoreFileTempPath[MPSMaxPathLength]; FILE *restoreFileTemp; static char buffer[MPSMaxPathLength]; static char command[MPSMaxPathLength]; static char argument[MPSMaxPathLength]; char *loadPv; char *runPv; restoreFilePath = path; if (restoreFilePath == NULL) { /* Get the path to the restore file */ restoreFilePath = getenv(MPS_ENV_ALGORITHM_SETUP_PATH); } if (restoreFilePath == NULL) { return MPS_ERROR; } /* Get the load and run PVs */ loadPv = getenv(MPS_ENV_ALGORITHM_LOAD_PV); runPv = getenv(MPS_ENV_ALGORITHM_RUN_PV); if ((loadPv == NULL) || (runPv == NULL)){ return MPS_ERROR_ENVIRONMENT_VARIABLE_NOT_SET; } /* Create a name for a temp file */ epicsSnprintf(restoreFileTempPath, sizeof(restoreFileTempPath), "%s.loading", restoreFilePath); /* Rename the restore file to the temp file name */ err = rename(restoreFilePath, restoreFileTempPath); if (err != 0) { errlogPrintf("mpsLoadAlgorithmRestoreFile: could not rename \"%s\" to \"%s\"\n", restoreFilePath, restoreFileTempPath); perror("mpsLoadAlgorithmRestoreFile"); return MPS_ERROR; } /* Open the temp file for reading */ restoreFileTemp = fopen(restoreFileTempPath, "r"); if (restoreFileTemp == NULL) { errlogPrintf("mpsLoadAlgorithmRestoreFile: could not open \"%s\" for reading\n", restoreFileTempPath); perror("mpsLoadAlgorithmRestoreFile"); return MPS_ERROR; } while(fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), restoreFileTemp) != NULL) { err = sscanf(buffer, "%s %s", command, argument); if (err == 2) { printf("Command: %s Argument: %s\n", command, argument); switch (command[0]) { case 'l': case 'L': dbpf(loadPv, argument); break; case 'r': case 'R': dbpf(runPv, argument); break; default: break; } } } fclose(restoreFileTemp); unlink(restoreFileTempPath); return MPS_SUCCESS; } static int updateAlgorithmRestoreFile() { int err; algorithmData *ad; const char *restoreFilePath; static char restoreFileTempPath[MPSMaxPathLength]; FILE *restoreFileTemp; static unsigned int uniqueNumber = 0; /* Get the path to the restore file */ restoreFilePath = getenv(MPS_ENV_ALGORITHM_SETUP_PATH); if (restoreFilePath == NULL) { return MPS_ERROR; } /* Create a name for a temp file */ epicsSnprintf(restoreFileTempPath, sizeof(restoreFileTempPath), "%s.temp.%u", restoreFilePath, uniqueNumber); uniqueNumber++; /* Open the temp file */ restoreFileTemp = fopen(restoreFileTempPath, "w+"); if (restoreFileTemp == NULL) { errlogPrintf("updateAlgorithmRestoreFile: could not open \"%s\" for writing\n", restoreFileTempPath); perror("updateAlgorithmRestoreFile"); return MPS_ERROR; } /* Write out dbpf's able to rebuild the algorithm list to the temp file*/ epicsMutexLock(algorithmListMutex); ad = (algorithmData *) ellFirst(&algorithmList); while(ad != NULL) { fprintf(restoreFileTemp, "Load %04d-%02d-%02d-%s\n", ad->year, ad->month, ad->day, ad->revision); if (ad == runningAlgorithmData) { fprintf(restoreFileTemp, "Run %04d-%02d-%02d-%s\n", ad->year, ad->month, ad->day, ad->revision); } ad = (algorithmData *) ellNext((ELLNODE *) ad); } epicsMutexUnlock(algorithmListMutex); /* Close the temp file */ err = fclose(restoreFileTemp); if (err != 0) { errlogPrintf("updateAlgorithmRestoreFile: could not close \"%s\"\n", restoreFileTempPath); perror("updateAlgorithmRestoreFile"); return MPS_ERROR; } /* Rename the temp file to the restore file */ #warning snorum: unlink should not be needed. However a "File exists" error occurs if the file at renames newpath exists. unlink(restoreFilePath); /* Required due to NFS? Or maybe sticky bits set on the directory? */ err = rename(restoreFileTempPath, restoreFilePath); if (err != 0) { errlogPrintf("updateAlgorithmRestoreFile: could not rename \"%s\" to \"%s\"\n", restoreFileTempPath, restoreFilePath); perror("updateAlgorithmRestoreFile"); return MPS_ERROR; } return MPS_SUCCESS; } int addAlgorithmToList(algorithmData *newAd) { int i; int err; algorithmData *ad; char *mpsDatabaseVersion; if (algorithmCount == MPSAlgorithmMaxLoadedAlgorithmCount) { errlogPrintf("addAlgorithmToList: Max number of algorithms (%d) already loaded.\n", MPSAlgorithmMaxLoadedAlgorithmCount); return MPS_ERROR; } if (newAd == NULL) { return MPS_ERROR_INVALID_ARGUMENT; } /* See if algorithm object is a loadable version */ err = MPS_ERROR; for (i = 0; loadableObjectVersions[i] != 0; i++) { if (newAd->objectVersion == loadableObjectVersions[i]) { break; } } if (loadableObjectVersions[i] == 0) { /* newAd is not a loadable version */ errlogPrintf("addAlgorithmToList: cannot load this algorithm object version (%d).\n", newAd->objectVersion); return MPS_ERROR; } /* See if algorithm is using the same MPS database version as the Link Processor */ mpsDatabaseVersion = getenv(MPS_ENV_CONFIG_DATABASE_VERSION); if (strcmp(mpsDatabaseVersion, newAd->mpsDatabaseVersion) != 0) { /* newAd's MPS database version does not match the Link Processor's */ errlogPrintf("addAlgorithmToList: Algorithm's MPS Database version (%s) does not match Link Processor's (%s).\n", newAd->mpsDatabaseVersion, mpsDatabaseVersion); return MPS_ERROR; } /* See if the algorithm is already loaded */ epicsMutexLock(algorithmListMutex); ad = getAlgorithmByInfo(newAd->year, newAd->month, newAd->day, newAd->revision); if (ad == NULL) { /* Add the object to the list and make sure the object doesn't get unloaded. */ ellAdd(&algorithmList, (ELLNODE *) newAd); algorithmCount++; newAd->canUnload = epicsFalse; err = MPS_SUCCESS; if (algorithmDataUpdatedEvent != 0) { post_event(algorithmDataUpdatedEvent); } } else { /* Already in list */ errlogPrintf("addAlgorithmToList: cannot reload existing algorithm.\n"); err = MPS_ERROR; } epicsMutexUnlock(algorithmListMutex); updateAlgorithmRestoreFile(); return err; } /* Must lock algorithmListMutex before calling this function */ int removeAlgorithmFromList (algorithmData *ad) { int err; if (ad == NULL) { return MPS_ERROR_INVALID_ARGUMENT; } /* If the ad is the running algorithm, clear it */ epicsMutexLock(algorithmFunctionMutex); if (ad == runningAlgorithmData) { algorithm = NULL; runningAlgorithmData = NULL; } epicsMutexUnlock(algorithmFunctionMutex); /* Remove the algorithm from the list */ ellDelete(&algorithmList, (ELLNODE *) ad); algorithmCount--; ad->canUnload = epicsTrue; if (algorithmDataUpdatedEvent != 0) { post_event(algorithmDataUpdatedEvent); } err = updateAlgorithmRestoreFile(); return err; } void mpsClearRunningAlgorithm() { int err; epicsMutexLock(algorithmListMutex); epicsMutexLock(algorithmFunctionMutex); algorithm = NULL; runningAlgorithmData = NULL; epicsMutexUnlock(algorithmFunctionMutex); epicsMutexUnlock(algorithmListMutex); if (algorithmDataUpdatedEvent != 0) { post_event(algorithmDataUpdatedEvent); } err = updateAlgorithmRestoreFile(); } int mpsSetAlgorithmToRun (unsigned int year, unsigned int month, unsigned int day, const char *revision) { int err; algorithmData *ad; epicsMutexLock(algorithmListMutex); ad = getAlgorithmByInfo(year, month, day, revision); if (ad == NULL) { err = MPS_ERROR; } else { /* Set the running function data and function pointers */ epicsMutexLock(algorithmFunctionMutex); algorithm = ad->function; runningAlgorithmData = ad; epicsMutexUnlock(algorithmFunctionMutex); err = MPS_SUCCESS; if (algorithmDataUpdatedEvent != 0) { post_event(algorithmDataUpdatedEvent); } } epicsMutexUnlock(algorithmListMutex); if (err != MPS_SUCCESS) { mpsClearRunningAlgorithm(); } err = updateAlgorithmRestoreFile(); return err; } #if 0 #pragma mark - #pragma mark Running #endif int algorithmRun(const MPSTimingData *currentTimingData) { MPSMachineStateBuffers buffers; MPSMitigationDevice aDevice; epicsMutexLock(algorithmFunctionMutex); if (algorithm != NULL) { /* Function pointer to the algorithm is set */ deviceStateMakeOk(LP_MPS_ALGORITHM_COUNT__INDEX, currentTimingData->timestamp, currentTimingData->timeslot); /* Get the buffer locations */ getMachineStateBuffers(&buffers); /* Process the states using the supplied algorithm */ mpsMutexLockMachineRatesBuffer(); mpsMutexLockMachineStateBuffer(); /* If beam is allowed after mitigation device, set rate to 120 Hz, otherwise set rate to 0 Hz */ for (aDevice = 0; aDevice < MPSMitigationDeviceCount; aDevice++) { if (canAllowBeamAfterMitigationDevice(aDevice)) { setRateAfterDevice_warning_allows_any_rate(MPSRate120Hz, aDevice); } else { setRateAfterDevice_warning_allows_any_rate(MPSRate0Hz, aDevice); } } /* Clear burst modes */ clearAllBurstModes(); /* Run the algorithm */ algorithm(&buffers); mpsMutexUnlockMachineStateBuffer(); mpsMutexUnlockMachineRatesBuffer(); } else { /* Function pointer to the algorithm is not set */ deviceStateMakeFaulted(LP_MPS_ALGORITHM_COUNT__INDEX, currentTimingData->timestamp, currentTimingData->timeslot); mpsMutexLockMachineRatesBuffer(); /* Set all rates to most restrictive and clear burst modes */ setAllRatesToMostRestrictiveAndClearBurstModes(); mpsMutexUnlockMachineRatesBuffer(); } epicsMutexUnlock(algorithmFunctionMutex); return MPS_SUCCESS; } #if 0 #pragma mark - #pragma mark Load and Unload Algorithms #endif int mpsLoadAlgorithm(const char *fullVersionName) { static char buffer[MPSMaxPathLength + 1]; char *mpsConfigPath; CexpModule moduleHandle = 0; unsigned int year, month, day; printf("Link Processor Loading Algorithm: %s \n", fullVersionName); mpsConfigPath = getenv("MPS_CONFIG_PATH"); if (mpsConfigPath == NULL) { printf("Link Processor Failed Algorithm Load no config path: %s \n", fullVersionName); return MPS_ERROR_ENVIRONMENT_VARIABLE_NOT_SET; } epicsSnprintf(buffer, MPSMaxPathLength, "%s/algorithm/%s/bin/RTEMS-beatnik/algorithm-%s.o", mpsConfigPath, fullVersionName, fullVersionName); buffer[MPSMaxPathLength] = '\0'; moduleHandle = cexpModuleLoad(buffer, NULL); if (moduleHandle == 0) { printf("Link Processor Failed Algorithm Load no buffer: %s \n", fullVersionName); return MPS_ERROR; } sscanf(fullVersionName, "%u-%u-%u-%s", &year, &month, &day, buffer); setAlgorithmModuleHandle(year, month, day, buffer, moduleHandle); printf("Link Processor Loaded Algorithm successfully: %s \n", fullVersionName); return MPS_SUCCESS; } int mpsUnloadAlgorithm(const char *fullVersionName) { static char revision[MPSAlgorithmRevisionStringMaxLength]; unsigned int year, month, day; CexpModule moduleHandle = 0; sscanf(fullVersionName, "%u-%u-%u-%s", &year, &month, &day, revision); moduleHandle = getAlgorithmModuleHandle(year, month, day, revision); if (moduleHandle == NULL) { return MPS_ERROR; } cexpModuleUnload(moduleHandle); return MPS_SUCCESS; } #if 0 #pragma mark - #pragma mark Initialization #endif int initializeAlgorithm() { /* Initialize algorithm mutex and list */ algorithmListMutex = epicsMutexMustCreate(); algorithmFunctionMutex = epicsMutexMustCreate(); epicsMutexLock(algorithmListMutex); epicsMutexLock(algorithmFunctionMutex); ellInit(&algorithmList); algorithmCount = 0; algorithm = NULL; runningAlgorithmData = NULL; algorithmDataUpdatedEvent = 0; setAlgorithmListUpdatedEventId(102); /* See devMpsAlgorithmTemplate.template for now... */ epicsMutexUnlock(algorithmFunctionMutex); epicsMutexUnlock(algorithmListMutex); return MPS_SUCCESS; }