/* Front-end for SLAC Common Platform ADCs */ #include #include #include #include #include #include #include #include #include #ifndef TEST_ONLY #include #include #else #define MOD5_IDX 4 #define MOD5_BEAMFULL_MASK 0x10000000 #endif #include #include #include // NON-STD // Ugly global wart static Path theRoot; #define SIM_SAMPLES 256 #define NUM_DACS 2 #define NUM_ADCS 4 #define TS_DEPTH_LD 5 extern "C" { volatile uint32_t commonPFMaxPer = 0; volatile uint32_t commonPFMinPer = -1; volatile uint32_t commonPFMod5OnCount = 0; volatile uint32_t commonPFMod5OffCount = 0; volatile uint32_t tsBuf[4][1<= 0 && tsPos[ch] ) { tsBuf[ch][tsPtr[ch]] = ts; tsPtr[ch] = (tsPtr[ch]+1) & ((1< 0 ) { (tsPos[ch])--; int f = 1; for ( unsigned j = 0; j<4; j++ ) { if ( 0 != tsPos[j] ) f = 0; } if ( f ) tsState = -1; } } } void tsFreeze() { if ( tsState ) return; tsState = 1; for ( unsigned j=0; j<4; j++ ) { tsPos[j] = (1<tail()->isHub() ) found_ = here->findByName( needl_ ); return false; } catch ( NotFoundError &e ) { } return true; } virtual void visitPost(ConstPath here) { } Path find(const char *fmt, ...) { va_list ap; va_start(ap, fmt); ::vsnprintf(needl_, sizeof(needl_), fmt, ap); va_end(ap); found_.reset(); try { found_ = root_->findByName( needl_ ); } catch ( NotFoundError &e ) { root_->explore( this ); } if ( ! found_ ) throw NotFoundError( needl_ ); Path rval; found_.swap( rval ); return rval;; } }; struct EmuVal { ScalVal sv_; double scale_; EmuVal(ScalVal sv, int scale = 1) : sv_(sv), scale_(scale) { } }; class CPDigiFE { private: ScalVal triggerHwArm_; ScalVal triggerHwAutoRearm_; ScalVal daqBufferSize_; ScalVal bsaBufferStart_; ScalVal bsaBufferEnd_; ScalVal calMode_; ScalVal calSoftTrig_; ScalVal initFlag_; std::vector simDacs_; std::vector adcStreams_; typedef std::map QspiRegMap; typedef std::pair QspiPair; QspiRegMap qspiEmulMap_; double simTbl[SIM_SAMPLES]; unsigned bsaBytes_; unsigned syncLostCount_; PadDataKind curKind_; GenDigiChannelSel sel_; int qspiState_; bool bsaHack_; bool haveStriplAfe_; unsigned bay_; private: ScalVal mkSV(Path pre, const char *name) { return IScalVal::create( pre->findByName( name ) ); } public: CPDigiFE(Path root, unsigned bay) : bsaBytes_(0), syncLostCount_(0), curKind_( PadDataBpm ), sel_(0), qspiState_( -1 ), bsaHack_( false ), haveStriplAfe_( false ), bay_(bay) { PathFinder finder(root); Path bsaWavf = finder.find( "BsaWaveformEngine[%d]/WaveformEngineBuffers", bay_ ); bsaBufferStart_ = mkSV( bsaWavf, "StartAddr"); bsaBufferEnd_ = mkSV( bsaWavf, "EndAddr" ); Path daqMux2 = finder.find( "DaqMuxV2[%d]", bay_ ); printf("DAQMUX: %s\n", daqMux2 ? daqMux2->toString().c_str() : "NULL"); triggerHwArm_ = mkSV( daqMux2, "TriggerHwArm"); triggerHwAutoRearm_ = mkSV( daqMux2, "TriggerHwAutoRearm"); daqBufferSize_ = mkSV( daqMux2, "DataBufferSize"); /* are we on real HW or on the simulator ? */ try { daqMux2->findByName("TriggerSwStatus"); // only real FW has this bsaHack_ = true; // FW currently needs 4k min buffer } catch ( NotFoundError &e ) { } // enable timing header mkSV( daqMux2, "PacketHeaderEn" )->setVal( "Enabled" ); for ( unsigned i=0; isetVal( mode ); if ( PadDataBpm != kind ) { // issue soft-trigger right now calSoftTrig_->setVal( 1 ); curKind_ = kind; return 0; } } else { if ( PadDataBpm != kind ) return -1; } #ifdef CPDEBUG printf("CDARM\n"); #endif curKind_ = kind; // FIXME -- hack; sometimes trigger seems to get lost... triggerHwAutoRearm_->setVal( "Enabled" ); // // must clear bit; FW reacts to 0->1 transition triggerHwArm_->setVal( (uint64_t)0 ); triggerHwArm_->setVal( 1 ); return 0; } int disarm() { #ifdef CPDEBUG printf("CDDISARM\n"); #endif triggerHwAutoRearm_->setVal( "Disabled" ); triggerHwArm_->setVal( (uint64_t) 0 ); return 0; } int writeReg( unsigned reg, uint32_t val ) { // will be used for stripline AFE return -1; } int readReg( unsigned reg, uint32_t *val_p ) { // will be used for stripline AFE return -1; } int validSel(GenDigiChannelSel sel) { unsigned ch; unsigned msk; unsigned nch; unsigned nbits; GenDigiChannelSel origSel = sel; for (nch=0, msk=0; nch<4; nch++) { if ( (ch = (sel & 0xf)) > 4 ) { fprintf(stderr,"commonPlatformDigiFE::setCount -- invalid selector; channel %d out of valid range\n", ch); return -1; } if ( 0 == ch ) break; msk |= (1<<(ch-1)); // channel may only be present once sel >>= 4; } nbits = 0; for ( unsigned m = msk; m; m>>=1 ) nbits++; if ( nbits != nch ) { fprintf(stderr,"commonPlatformDigiFE::setCount -- invalid selector; any channel may only be present ONCE\n"); return -1; } // release (close!) unused streams for ( unsigned m = 0; m < 4; m++ ) { if ( ! (msk & (1<setVal( nWords ); // buffer for readback value of BSA start addresses unsigned nelms = bsaBufferEnd_->getNelms(); uint64_t endAddr[ nelms ]; // retrieve start addr bsaBufferStart_->getVal( endAddr, nelms ); bsaBytes_ = sizeof(uint32_t)*nWords; // add number of DAQMUX buffer in bytes for ( unsigned i = 0; isetVal( endAddr, nelms ); return 0; } int qspiReadEmul(int data_out, uint16_t *data_in) { unsigned reg = (data_out >> 8) & 0x3f; unsigned dat; uint32_t initFlag; QspiRegMap::iterator it = qspiEmulMap_.find( reg ); if ( it == qspiEmulMap_.end() ) { // special handling switch ( reg ) { case AFE_REG_VER: dat = 8; goto leave; case AFE_REG_CSR: initFlag_->getVal( &initFlag, 1 ); /* traditional AFE has initFlag==1 on reboot */ dat = initFlag ? 0 : AFE_REG_CSR_CNFG; dat |= AFE_REG_CSR_ONLN; goto leave; case AFE_REG_SOFTTRG: dat = 0; goto leave; default: fprintf(stderr,"QSPI REG %d not implemented\n", reg); abort(); return -1; } } { int nelms = it->second.sv_->getNelms(); uint32_t val[ nelms ]; it->second.sv_->getVal(val, nelms); // only ATT registers are arrays and we // set them identically... dat = ((unsigned)(((double)val[0])/it->second.scale_)) & 0xff; } leave: *data_in = (data_out & 0xff00) | dat; #ifdef QSPIDEBUG printf("QSPI READ (reg %d, val %d) 0x%04x\n", reg, dat, *data_in); #endif return 0; } int qspiWriteEmul(int data_out) { if ( (data_out & 0x4000) ) { // read-only bit #ifdef QSPIDEBUG printf("QSPI NO_WRITE %x\n", data_out); #endif return 0; } unsigned reg = (data_out >> 8) & 0x3f; unsigned dat = data_out & 0xff; #ifdef QSPIDEBUG printf("QSPI WRITE (reg %d, val %d)\n", reg, dat); #endif QspiRegMap::iterator it = qspiEmulMap_.find( reg ); if ( it == qspiEmulMap_.end() ) { switch ( reg ) { case AFE_REG_VER: // ignore return 0; case AFE_REG_CSR: // traditional AFE has CNFG set on reboot if ( (data_out & AFE_REG_CSR_CNFG) ) initFlag_->setVal( 1 ); return 0; case AFE_REG_SOFTTRG: calSoftTrig_->setVal( 1 ); return 0; default: fprintf(stderr,"QSPI REG %d not implemented\n", reg); abort(); return -1; } } uint32_t val = (uint32_t)( dat * it->second.scale_ ); it->second.sv_->setVal( val ); return 0; } int qspiWriteRead(int data_out, uint16_t *data_in) { int rval; if ( ! haveStriplAfe_ ) return -1; if ( AFE_DEV_SUP_IO_RDONLY == data_out ) { data_out = qspiState_; qspiState_ = -1; if ( data_out < 0 ) return -1; } else { bool wrOnly = ( AFE_DEV_SUP_IO_WRONLY == data_in ); if ( wrOnly ) { qspiState_ = data_out; } if ( (rval = qspiWriteEmul( data_out )) || wrOnly ) { return rval; } } return qspiReadEmul( data_out, data_in ); } void setSim(int32_t a, int32_t b, int32_t c, int32_t d, int quiet) { int16_t buf[SIM_SAMPLES]; int32_t AA[4], aa[4]; unsigned nch, idx; // scale by two to produce readings simimlar to other digitizer (??) aa[0] = a / 10; aa[1] = b / 10; aa[2] = c / 10; aa[3] = d / 10; // remap throught he selector mapping (assumes ADC0 wired to DAC0 etc.) nch = 0; for ( GenDigiChannelSel selPos = sel_; (idx = (selPos & 0xf)); selPos >>= 4, nch++ ) { AA[nch] = aa[idx-1]; } IndexRange range(0, SIM_SAMPLES-1); #ifdef CPDEBUG printf("Setting SIM (sel): 0x%lx %d %d %d %d =>", sel_, a,b,c,d); #endif for ( unsigned k = 0; k simDacs_.size() ) nch = simDacs_.size(); for (unsigned i = 0; isetVal( reinterpret_cast(buf), SIM_SAMPLES, &range ); } catch (InvalidArgError &e) { printf("%s\n", simDacs_[i]->getPath()->toString().c_str()); } } printf("Leaving\n"); } int drainStreams() { int idx, drained = 0; for ( GenDigiChannelSel selPos = sel_; (idx = (selPos & 0xf)); selPos >>= 4 ) { idx--; // indices in selectors are 1-based uint8_t dummyBuf[TIMING_LOW_OFFST + 4]; // must read at least one char -- otherwise the stream believes // we are just polling and keeps the data in its internal buffer. while ( adcStreams_[idx]->read( dummyBuf, sizeof(dummyBuf), TIMEOUT_NONE ) > 0 ) { uint32_t tsLo; memcpy( &tsLo, dummyBuf + TIMING_LOW_OFFST, 4); tsPut(idx, tsLo); } drained++; } return drained; } // BIG FAT WARNING ==== this assumes Little-Endian host byte order ! #ifndef __BYTE_ORDER #error "Undefined __BYTE_ORDER" #else #if __BYTE_ORDER != __LITTLE_ENDIAN #error "read() doesn't implement byte-swap" #endif #endif int read( uint8_t **buf_p, size_t bufsz, size_t nBytes, FrontEndTimestamp *ts_p ) { uint8_t *bufStart = *buf_p; int headroom = TIMING_HDR_WORDS*sizeof(uint32_t); uint8_t *payStart = bufStart + headroom; /* let them know that the useful data start at 'payload_start' */ *buf_p = payStart; #ifdef CPDEBUG printf("CD read enter\n"); #endif struct timespec now_ts; clock_gettime( CLOCK_REALTIME, &now_ts ); uint64_t now = now_ts.tv_sec*1000000 + now_ts.tv_nsec/1000; if ( lastTime ) { uint64_t diff = now - lastTime; if ( diff > commonPFMaxPer ) commonPFMaxPer = diff; if ( diff < commonPFMinPer ) commonPFMinPer = diff; } lastTime = now; int nBytesPerStream = nBytes / PADRPLY_STRM_NCHANNELS; if ( nBytes + headroom > bufsz ) { return -1; } uint32_t commonTimingHi = 0; uint32_t commonTimingLo = 0; bool syncLost, haveTiming, haveBeam; unsigned gotStreams; do { haveTiming = false; haveBeam = true; // Eventually we want to have: // | header0, stream0, stream1, stream2, stream3 // // Thus, the third stream (which we store first) must // (including its header) be stored at // // headroom + 3*nBytesPerStream - headroom; uint64_t off = 3*nBytesPerStream; syncLost = false; gotStreams = 0; for ( int selPos = 12; selPos >= 0; selPos -= 4, /* overwrite header of the previously stored stream */ off -= nBytesPerStream ) { unsigned idx = (sel_ >> selPos) & 0xf; if ( ! idx ) // unused channel continue; idx--; /* indices in selectors are 1-based */ #ifdef CPDEBUG printf("CD read (off %ld, head %d, nBperStream %d)\n", off, headroom, nBytesPerStream); #endif /* skip the header if we already have it */ int64_t got = adcStreams_[ idx ]->read( bufStart + off, nBytesPerStream + headroom ); if ( got < headroom ) return -1; uint32_t timingHi, timingLo, mod5; memcpy(&timingHi, bufStart + off + TIMING_HIW_OFFST, sizeof(timingHi)); memcpy(&timingLo, bufStart + off + TIMING_LOW_OFFST, sizeof(timingLo)); memcpy(&mod5 , bufStart + off + TIMING_MD5_OFFST, sizeof(mod5 )); tsPut(idx, timingLo); if ( ! haveTiming ) { commonTimingHi = timingHi; commonTimingLo = timingLo; haveTiming = true; haveBeam = !!(mod5 & MOD5_BEAMFULL_MASK); if ( haveBeam ) { commonPFMod5OnCount++; } else { commonPFMod5OffCount++; } } else { if ( (commonTimingHi != timingHi) || (commonTimingLo != timingLo) ) { tsFreeze(); /* timestamp mismatch; drain streams and start over */ int drained = drainStreams(); syncLost = true; syncLostCount_++; if ( 0 == (syncLostCount_ & 0xf) ) { errlogPrintf("commonPlatformDigiFE: lost timing sync 16 times since last message\n"); errlogPrintf("gotStreams: %d; drained %d; expected: hi %d lo %d, got: hi %d, lo %d\n", gotStreams, drained, commonTimingHi, commonTimingLo, timingHi, timingLo); } // rearm arm( curKind_ ); break; // for loop } } gotStreams++; } } while ( syncLost ); #ifdef CPDEBUG printf("CD read leave "); #endif if ( haveTiming ) { #ifdef CPDEBUG printf("Hi %ld, lo %ld\n", commonTimingHi, commonTimingLo); #endif ts_p->timestampHi = htobe32(commonTimingHi); ts_p->timestampLo = htobe32(commonTimingLo); } #ifdef CPDEBUG else printf("No timing\n"); for ( int i = 0; i<10; i++ ) printf("0x%02x ", payStart[i]); printf("\n"); { double a1 = 0.; double a2 = 0.; double v; int16_t *pp = (int16_t*)payStart; for ( int i = 0; i<100; i++ ) { v = (double)pp[i]; a1 += v; a2 += v*v; } a2/=100.; a1/=100.; printf("MS: %g\n", a2 - a1*a1); } #endif return nBytes; } }; static int cpDigiFEArm(void *frontEndPvt, PadDataKind kind) { CPDigiFE *fe = static_cast( frontEndPvt ); return fe->arm( kind ); } static int cpDigiFEDisarm(void *frontEndPvt) { CPDigiFE *fe = static_cast( frontEndPvt ); return fe->disarm(); } static int cpDigiFEWriteReg(void *frontEndPvt, unsigned reg, uint32_t val) { CPDigiFE *fe = static_cast( frontEndPvt ); return fe->writeReg( reg, val ); } static int cpDigiFEReadReg(void *frontEndPvt, unsigned reg, uint32_t *val_p) { CPDigiFE *fe = static_cast( frontEndPvt ); return fe->readReg( reg, val_p ); } static int cpDigiFESetCount(void *frontEndPvt, GenDigiChannelSel sel, unsigned nSamples) { CPDigiFE *fe = static_cast( frontEndPvt ); printf("Setting count %lx %d\n", sel, nSamples); return fe->setCount( sel, nSamples ); } static int cpDigiFEQspiWriteRead(void *frontEndPvt, int data_out, uint16_t *data_in) { CPDigiFE *fe = static_cast( frontEndPvt ); return fe->qspiWriteRead( data_out, data_in ); } static int cpDigiFEValidateSel(void *frontEndPvt, GenDigiChannelSel sel) { CPDigiFE *fe = static_cast( frontEndPvt ); return fe->validSel( sel ); } int cpDigiFEClose(void *frontEndPvt) { CPDigiFE *fe = static_cast( frontEndPvt ); delete fe; return 0; } void cpDigiFESetSim(void *frontEndPvt, int32_t a, int32_t b, int32_t c, int32_t d, int quiet) { CPDigiFE *fe = static_cast( frontEndPvt ); fe->setSim( a, b, c, d, quiet ); } int cpDigiFEOpen(const char *name, unsigned long param, void **frontEndPvt_p) { if ( ! theRoot ) { fprintf(stderr,"No YAML file loaded! -- use cpswLoadYamlFile()\n"); return -1; } if ( param > 1 ) { fprintf(stderr,"Bay must be 0 or 1\n"); return -1; } *frontEndPvt_p = new CPDigiFE( theRoot, param ); return 0; } static int cpDigiFERead(void *frontEndPvt, uint8_t **buf_p, size_t bufsz, size_t nBytes, FrontEndTimestamp *ts_p) { CPDigiFE *fe = static_cast( frontEndPvt ); return fe->read( buf_p, bufsz, nBytes, ts_p ); } static GenDigiFrontEndRec commonPlatformFrontEnd = { arm : cpDigiFEArm, disarm : cpDigiFEDisarm, writeReg : cpDigiFEWriteReg, readReg : cpDigiFEReadReg, setCount : cpDigiFESetCount, afeWriteRead : cpDigiFEQspiWriteRead, setSim : cpDigiFESetSim, open : cpDigiFEOpen, close : cpDigiFEClose, validSel : cpDigiFEValidateSel, read : cpDigiFERead }; // helper for cexp extern "C" { int commonPlatformDigiCommConfig(unsigned udpCommChnl, const char *devnam, unsigned bay, unsigned sel_in, int nPkts, AfeAttachFunc afe_attach) { return genDigiCommConfig(udpCommChnl, devnam, sel_in, bay, nPkts, afe_attach, &commonPlatformFrontEnd); } static const struct iocshArg cpDigiCommConfigArgs[] = { { "udpComm channel", iocshArgInt }, { "commonPlatform device file", iocshArgString }, { "bay", iocshArgInt }, { "digitizer channel selector", iocshArgInt }, { "number of packet buffers (per channel; optional)", iocshArgInt }, { "name of AFE attach function", iocshArgString } }; static const struct iocshArg *cpDigiCommConfigArgp[sizeof(cpDigiCommConfigArgs)/sizeof(cpDigiCommConfigArgs[0])]; static const struct iocshFuncDef commonPlatformDigiCommConfigDesc = { "commonPlatformDigiCommConfig", sizeof(cpDigiCommConfigArgs)/sizeof(cpDigiCommConfigArgs[0]), cpDigiCommConfigArgp }; static void commonPlatformDigiCommConfigFunc(const iocshArgBuf *args) { AfeAttachFunc f = 0; int i; if ( !args[1].sval ) { epicsPrintf("commonPlatformDigiCommConfig -- need non-NULL device file name arg\n"); return; } if ( args[5].sval && args[5].sval[0] ) { if ( strcmp(args[5].sval,"NULL") && ( 1 != sscanf(args[5].sval,"%i",&i) || 0 != i) ) { if ( ! (f = afeAttachFind( args[5].sval )) ) { errlogPrintf("commonPlatformDigiCommConfig: AFE attach function '%s' not found!\n", args[5].sval); return; } } } if ( genDigiCommConfig(args[0].ival, args[1].sval, (unsigned)args[3].ival, (unsigned)args[2].ival, args[4].ival, f, &commonPlatformFrontEnd) ) { epicsPrintf("commonPlatformDigiCommConfig() FAILED for channel %i\n", args[0].ival); } } int cpswLoadYamlFile(const char *yaml_file, const char *root, const char *yaml_dir) { if ( ! yaml_file ) { fprintf(stderr,"Missing YAML hierarchy file name argument\n"); return -1; } try { theRoot = IPath::loadYamlFile( yaml_file, root, yaml_dir ); } catch ( CPSWError &e ) { fprintf(stderr,"Unable to load YAML file: %s\n", e.getInfo().c_str()); return -1; } return 0; } int cpswLoadConfigFile(const char *yaml_file, const char *prefix, const char *yaml_dir) { Path pre; if ( ! theRoot ) { fprintf(stderr,"No hierarchy found; use 'cpswLoadYamlFile (with HIERARCHY yaml, not config yaml)\n"); return -1; } if ( ! yaml_file ) { fprintf(stderr,"Missing YAML config file name argument\n"); return -1; } try { pre = prefix ? theRoot->findByName( prefix ) : theRoot; } catch ( CPSWError &e ) { fprintf(stderr,"Unable to load CONFIG file: %s\n", e.getInfo().c_str()); return -1; } if ( ! pre ) { throw InternalError("cpswLoadConfigFile: Should have a Path object here!"); } return pre->loadConfigFromYamlFile( yaml_file, yaml_dir ); } }; static const struct iocshArg loadYamlArgs[] = { { "YAML hierarchy description file", iocshArgString }, { "Root Device Name (optional; default = 'root' -- but must match what is in the description)", iocshArgString }, { "directory where YAML includes can be found (optional; uses dir of main yaml by default)", iocshArgString } }; static const struct iocshArg loadConfigArgs[] = { { "CONFIG YAML file (NOT hierarchy YAML!)", iocshArgString }, { "Path prefix (if config YAML is not based off the root device; optional", iocshArgString }, { "directory where YAML includes can be found (optional; uses dir of main yaml by default)", iocshArgString } }; static const struct iocshArg *loadYamlArgp[sizeof(loadYamlArgs)/sizeof(loadYamlArgs[0])]; static const struct iocshArg *loadConfigArgp[sizeof(loadConfigArgs)/sizeof(loadConfigArgs[0])]; static const struct iocshFuncDef loadYamlDesc = { "cpswLoadYamlFile", sizeof(loadYamlArgs)/sizeof(loadYamlArgs[0]), loadYamlArgp }; static const struct iocshFuncDef loadConfigDesc = { "cpswLoadConfigFile", sizeof(loadConfigArgs)/sizeof(loadConfigArgs[0]), loadConfigArgp }; static void loadYamlFunc(const iocshArgBuf *args) { if ( ! args[0].sval ) { epicsPrintf("cpswLoadYamlFile: need a YAML HIERARCHY definition file argument\n"); return; } cpswLoadYamlFile( args[0].sval, args[1].sval, args[2].sval ); } static void loadConfigFunc(const iocshArgBuf *args) { if ( ! args[0].sval ) { epicsPrintf("cpswLoadConfigFile: need a YAML CONFIG definition file argument\n"); return; } cpswLoadConfigFile( args[0].sval, args[1].sval, args[2].sval ); } static void commonPlatformDigiFERegistrar(void) { unsigned i; for ( i=0; i