/*============================================================================= Name: drvBunchLengthCF.c Abs: Driver support for LCLS Bunch Length Monitor 4 channel module (Arcturus Coldfire 5282 processor with LTC2208 ADC) Compiler Flags: DEBUGPRINT - SCAN_IO - should only be undefined if you use ASYN to scan I/O Intr via callbacks Auth: 16-nov-2005, Dayle Kotturi (dayle): Initial version for LLRF PAD -----------------------------------------------------------------------------*/ #include "copyright_SLAC.h" /* SLAC copyright comments */ /*----------------------------------------------------------------------------- Mod: (newest to oldest) 11-aug-2008, Dayle Kotturi: Adapt to use eth2 interface 23-jan-2007, Dayle Kotturi: Adapted for BunchLengthCFApp =============================================================================*/ #include /* for printf */ #include /* for malloc */ #include /* for memcpy */ #include /* for errno */ #include /* for sqrt */ #include /* for strerror */ #ifdef BASE_HAS_NO_NTP_PATCH #include #include #endif #include /* for IOSCANPVT */ #include /* for DRVSUPFN */ #include /* for dev*routines, atVMEA16 */ #include /* for epicsEvent* */ #include /* for epicsExportAddress */ #include /* for epicsMessageQueueCreate, ... */ #include /* for epicsTimeStamp and assoc fns */ #include /* for epicsTimerQueue for watchdog */ #include /* for epicsThreadPriorityMax and to get confdefs.h indirectly inc'd */ #include #include #include #include #include /* for DEBUGPRINT */ #include #include #include #ifdef DEBUG_PRINT #include /* for DEBUGPRINT */ #endif #include "drvBunchLengthCF.h" /* Which Arcturus 'IRQ' pins is used for triggering the FIFOs. This one is configured as an OUTPUT so that it can function as a s/w trigger */ #define TRIG_PIN 1 /* Which Arcturus 'IRQ' pins is used for interrupting the CPU. This one is configured as an INPUT (i.e. unchanged from default) so that it can function as the h/w trigger */ #define IRQ_PIN 2 /* Shall we interrupt on the falling (trigger detected) or * raising ('fifo full' [rather: N clocks expired]) edge? * The former is OK if the clock rate is faster than * we can read the fifo (~8MB/s -> clock > 1MHz). */ #define IRQ_EDGE EPORT_FALLING /* Which chip select we are using - this is setup by the BSP * but not published :-( */ #define CS1_BASE_ADDR 0x30000000 /* Just a name for sake of readability */ #define CS1 (1) #define DEBUG_TIMING (1<<1) typedef int16_t __attribute__ ((may_alias)) int16_t_a; typedef uint32_t __attribute__ ((may_alias)) uint32_t_a; typedef struct blmLan9118_s { epicsEventId data_ready; int irq_pin; int trig_pin; volatile int irq; CALLBACK cb_s; /* int orarm; not sure if needed */ unsigned long nusr; /* support user resizing of array */ void (*readFifos)(volatile void*, int, int); } blmLan9118_t; /* Interrupt/General-Purpose I/O Pin Descriptions All pins default to general-purpose input pins at reset. The pin value is synchronized to the rising edge of CLKOUT when read from the EPORT pin data register (EPPDR). The values used in the edge/level detect logic are also synchronized to the rising edge of CLKOUT. These pins use Schmitt triggered input buffers which have built in hysteresiss designed to decrease the probability of generating false edge-triggered interrrupts for slow rising and falling input signals. When a pin is configured as an output, it is driven to a state whose level is determined by the corresponding bit in the EPORT data register(EPDR). All bits in the EPDR are high at reset. */ #define IPSBAR (0x40000000) /* Default base address for the Edgeport and the Chip Select Module */ /* Adding the base address here, defies the purpose of having the change base address routine */ /* Interrupt controller module */ #define ICR02 (IPSBAR+0xC42) /* Address of interrupt control register #2. 1 byte */ #define IMRL (IPSBAR+0xC0C) /* Address of interrupt mask register low. 4 bytes */ #define EPPAR (IPSBAR+0x00130001) /* Two bytes. Big endian. 0=bits 15-8, 1=bits 7-0 */ #define EPDDR (IPSBAR+0x00130002) /* EPORT Data Direction Register */ #define EPIER (IPSBAR+0x00130003) /* EPORT Interrupt Enable Register */ #define EPDR (IPSBAR+0x00130004) /* EPORT Data Register */ #define EPPDR (IPSBAR+0x00130005) /* EPORT Pin Data Register */ #define EPFR (IPSBAR+0x00130006) /* EPORT Flag Register */ /* Note: 0x00130007 is reserved */ /* Note about access: EPPAR, EPDDR, and EPIER are Supervisor access EPDR, EPPDR and EPRF are Supervisor/User access Writing to reserved address has no effect, reading returns zeroes */ #define CSAR1 (IPSBAR+0x00008C) /* 2 bytes */ #define CSMR1 (IPSBAR+0x000090) /* 4 bytes */ #define CSCR1 (IPSBAR+0x000096) /* 2 bytes */ #define BLM_NUM_WAVEFORMS_KEPT (10) #define BLM_MAX_INT (2147483647) /* 4 byte int - 1 bit for sign */ #define BLM_IRQ_VECTOR (66) /* DECIMAL! */ #define BLM_MAX_FILENAME (100) typedef struct blm_channel_s { long long sum; /* 8/13/8: dayle. this may be able to safely be just "long". calculate max value */ /* long avg; not needed */ int ofst; int sz; int x; int nToRead; int nRead; int num; short* data; /* the raw sample of interest in the FIFO */ short* scalar; /* array of scalar corrections to multiply data by */ long* proc; /* resultant vector. proc = data * scalar */ } blm_channel_t; typedef struct iqcal_channel_s { int ofst; int sz; int nToRead; int nRead; short* data; /* the sample of interest in the FIFO */ } iqcal_channel_t; blm_channel_t blmCh0; blm_channel_t blmCh1; blm_channel_t blmCh2; blm_channel_t blmCh3; iqcal_channel_t blmCalCh0; iqcal_channel_t blmCalCh1; iqcal_channel_t blmCalCh2; iqcal_channel_t blmCalCh3; /* Use this array of pointers to group the 4 like channel structures together */ blm_channel_t* pChannels[4]={&blmCh0, &blmCh1, &blmCh2, &blmCh3}; iqcal_channel_t* pCalChannels[4]={&blmCalCh0, &blmCalCh1, &blmCalCh2, &blmCalCh3}; /* Forward Declarations */ static void blmISR(void *arg_p); /* 4/25/8 not needed. 5/12/8 put back */ static void blmUdpThread(void *arg); /* 5/12/8 make static */ int blmInitialise(); int blmReport(int interest); struct drvet drvBunchLengthCF = { 2, (DRVSUPFUN) blmReport, /* subroutine defined in this file */ (DRVSUPFUN) blmInitialise /* subroutine defined in this file */ }; epicsExportAddress(drvet, drvBunchLengthCF); epicsTimerQueueId blmWdTimerQ = 0; #ifdef DEBUG_PRINT /* ENUM with values: DP_FATAL, DP_ERROR, DP_WARN, DP_INFO, DP_DEBUG Anything less than or equal to drvPnetFlag gets printed out. Can be set to 0 here and altered via prompt or in st.cmd file */ int drvBlmLan9118Flag = 2; int drvBlmLan9118DacqFlag = 2; int drvBlmLan9118ArmFlag = 2; int drvBlmLan9118ISRFlag = 2; int drvBlmLan9118GetdataFlag = 2; int drvBlmLan9118ReadFifosFlag=2; int drvBlmCbFlag = 2; int drvBunchLengthCFCfgFlag = 2; int drvBunchLengthCFScalFlag = 2; int drvBunchLengthCFIntrFlag = 2; int drvBunchLengthCFSSFlag = 2; #endif /* Hardware registers for chip select and EPORT module */ LOCAL volatile unsigned char *epddr = (unsigned char *)EPDDR; LOCAL volatile unsigned char *epier = (unsigned char *)EPIER; LOCAL volatile unsigned char *epdr = (unsigned char *)EPDR; LOCAL volatile unsigned char *eppdr = (unsigned char *)EPPDR; LOCAL volatile short *csar1 = (short *)CSAR1; LOCAL volatile short *csar1_actual = (short *) 0x80000000; LOCAL volatile unsigned short *cscr1 = (unsigned short *)CSCR1; LOCAL volatile unsigned long *csmr1 = (unsigned long *)CSMR1; /* Driver globals */ LOCAL epicsTimeStamp timeAtBoot; int intrCount = 0; LOCAL int overflowCount = 0; LOCAL char filename[BLM_MAX_FILENAME]; LOCAL char filenameStem[BLM_MAX_FILENAME]; LOCAL int numIntrRollovers = 0; #ifdef SCAN_IO LOCAL int scanIoCount = 0; LOCAL IOSCANPVT blm_ioscanpvt; /* single interrupt source for all blm recs */ LOCAL int numScanIoRollovers = 0; #endif extern IpBscIf lanIpIf; epicsThreadId drvBlmStreamInit(); epicsThreadId drvBlmLan9118DacqThread = 0; blmLan9118_t blmLan9118; blmLan9118_t *pblmLan9118 = &blmLan9118; int drvBlmLan9118Irqs = 0; int drvBlmLan9118Acqs = 0; int drvBlmLan9118Debug = DEBUG_TIMING; int blm_card; /* called PADSLOT in startup, must match "card" on VME */ int updatingWfs = 0; /* This is the callback run at 1 Hz by the VME as part of the StartStrmRequest. */ int myArm() { /* to keep things simple, we disable interrupts here * so the ISR doesn't change EPORT bits under our feet. */ coldfEportIntDisable(pblmLan9118->irq_pin); /* clear old flag set by any pre-arm triggers */ coldfEportFlagClr(pblmLan9118->irq_pin); #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118ArmFlag, ("myArm: toggling interrupt\n")); #endif coldfEportIntEnable(pblmLan9118->irq_pin); return OK; } /* Since there is only one blmStreamInit on vme side, all blms must send the same number of shorts, which is 4 (1 sample) */ void myDrvBlmReadFifosRowMajor(volatile void *dst_pv, int n, int do_bswap) { volatile uint32_t_a *dst_p = dst_pv; /* Transfer long longs ... */ /* Transfer longs. Set drvPadUdpNsamples to 2, FTVL = LONG, struct to have longs (drvBlm.h) and read bptr in increments of 4 */ *dst_p = (long) blmCh0.sum; *dst_p = (long) blmCh1.sum; *dst_p = (long) blmCh2.sum; *dst_p = (long) blmCh3.sum; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118ReadFifosFlag, ("myDrvBlmReadFifosRowMajor: %lld %lld %lld %lld\n", blmCh0.sum, blmCh1.sum, blmCh2.sum, blmCh3.sum)); #endif /* Transfer longs. Set drvPadUdpNsamples to 2, FTVL = LONG, struct to have longs (drvBlm.h) and read bptr in increments of 4 *dst_p = blmCh0.avg; *dst_p = blmCh1.avg; *dst_p = blmCh2.avg; *dst_p = blmCh3.avg; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118ReadFifosFlag, ("myDrvBlmReadFifosRowMajor: %ld %ld %ld %ld\n", blmCh0.avg, blmCh1.avg, blmCh2.avg, blmCh3.avg)); #endif */ /* Transfer shorts. Set drvPadUdpNsamples to 1, FTVL = SHORT, struct to have shorts (drvBlm.h) and read bptr in increments of 2 and comment out the assert *dst_p = (((short) blmCh0.avg)<<16) | (((short) blmCh1.avg) & 0xffff); *dst_p = (((short) blmCh2.avg)<<16) | (((short) blmCh3.avg) & 0xffff); #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118ReadFifosFlag, ("myDrvBlmReadFifosRowMajor: %hd %hd %hd %hd\n", blmCh0.avg, blmCh1.avg, blmCh2.avg, blmCh3.avg)); #endif */ } /* nsamples is the number sent by the VME requesting streaming */ void * getdata(void *packBuffer, int idx, int nsamples, int endianLittle, int colMajor, void *uarg) { /*assert ( 0 == ( nsamples & 1 ) );*/ #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118GetdataFlag, ("getdata: reading %d*4 samples in row major order into 0x%0x\n", nsamples, (volatile unsigned int) LAN9118_FIFO_HACK)); #endif myDrvBlmReadFifosRowMajor( LAN9118_FIFO_HACK, nsamples * 4, endianLittle ); return NULL; } /*============================================================================= Name: blmDumpSignal(int channel) Abs: Print out latest raw data in channel "channel" =============================================================================*/ int blmDumpSignal(int channel) { int ii; blm_channel_t* pCh; iqcal_channel_t* pCCh; /* Channels 0-3 are samples used for calcs; channels 4-7 are full FIFOs of raw data */ switch (channel) { case 0: case 1: case 2: case 3: pCh = pChannels[channel]; printf("Channel %d's raw data:\n", channel); for (ii=0; iisz; ii++) { printf ("%8d ", *(pCh->data+ii)); } printf("\n"); for (ii=0; iisz; ii++) { printf ("0x%08x: ", (unsigned int)(pCh->data+ii)); } printf("\n"); break; case 4: case 5: case 6: case 7: pCCh = pCalChannels[channel-4]; printf("Calibration channel's raw data:\n"); for (ii=0; iisz; ii++) { printf ("0x%08x: %d, ", (unsigned int)(pCCh->data+ii), *(pCCh->data+ii)); } printf("\n"); break; default: printf("blmDumpSignal: invalid channel: %d\n", channel); return ERROR; } return OK; } /*============================================================================= Name: blmDumpProcessedSignal(int channel) Abs: Print out latest processed data for channel "channel" =============================================================================*/ int blmDumpProcessedSignal(int channel) { int ii; blm_channel_t* pCh; pCh = pChannels[channel]; printf("Channel %d's processed data:\n", channel); for (ii=0; iisz; ii++) { printf ("%8ld ", *(pCh->proc+ii)); } printf("\n"); for (ii=0; iisz; ii++) { printf ("0x%08x ", (unsigned int)(pCh->proc+ii)); } printf("\n"); return OK; } /*============================================================================= Name: blmDumpChannel Abs: Debug routine used to look at the contents of a channel's structure Ret: OK =============================================================================*/ int blmDumpChannel(int channel ) { int ii; blm_channel_t* pCh; iqcal_channel_t* pCCh; switch (channel) { case 0: case 1: case 2: case 3: printf("Contents of RF channel %d, (range is 0-3), sample 0\n", channel); pCh = pChannels[channel]; printf("sz: %d\n", pCh->sz); printf("ofst: %d\n", pCh->ofst); printf("\n"); printf("nToRead: %d\n", pCh->nToRead); printf("nRead: %d\n", pCh->nRead); printf("sum: %lld\n", pCh->sum); printf("num: %d\n", pCh->num); printf("First 10 values of scalar...\n"); for (ii=0; ii<10; ii++) { printf("addr:0x%08x val:%8hd\n", (unsigned int)(pCh->scalar+ii), *(pCh->scalar+ii)); } printf("\n"); blmDumpSignal(channel); blmDumpProcessedSignal(channel); return OK; break; case 4: case 5: case 6: case 7: pCCh = pCalChannels[channel-4]; printf("Contents of CAL channel (access is to 4-7, but physically, it's 0-3 in the array)\n"); printf("ofst: %d\n", pCCh->ofst); printf("sz: %d\n", pCCh->sz); printf("nToRead: %d\n", pCCh->nToRead); printf("nRead: %d\n", pCCh->nRead); blmDumpSignal(channel); break; default: printf("blmDumpChannel: unrecognized channel: %d\n", channel); return ERROR; } return OK; } /*============================================================================= Name: blmReport Ret: Driver support routine registered in DRVET structure =============================================================================*/ int blmReport( int interest ) { int rc; printf("IOC booted at %d seconds from EPOCH\n", timeAtBoot.secPastEpoch); printf("Current epics time: %d seconds from EPOCH\n", 0); printf("Num interrupts since boot: %d\n", intrCount); printf("Num overflow errors since boot: %d\n", overflowCount); #ifdef SCAN_IO printf("Num scan I/O requests since boot: %d\n", scanIoCount); #endif rc = blmDumpChannel(0); rc = blmDumpChannel(1); rc = blmDumpChannel(2); rc = blmDumpChannel(3); #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("PAD Stream Support for Communication with BPM Processor\n")); DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("over 2nd Ethernet Interface\n")); #endif if ( interest > 1 ) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("Dumping Interface Statistics\n"); #endif drvLan9118DumpStats(lanIpBscIfGetDrv(lanIpIf), 0)); } return interest; } static int start_stop_cb(int start, void *uarg) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmCbFlag, ("start_stop_cb:\n")); #endif myArm(); return OK; } epicsThreadId drvBlmStreamInit() { char *blmslot; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("drvBlmStreamInit: calling drvLan9118/padStreamInitialize...\n")); #endif if ( padStreamInitialize(lanIpIf, start_stop_cb, (void*)&(pblmLan9118->irq_pin)) ) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("drvBlmStreamInit: error calling padStreamInitialize\n")); #endif return 0; } #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("drvBlmStreamInit: blmStreamInitialize successful\n")); #endif if ( !(blmslot = getenv("PADSLOT")) ) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("drvBlmStreamInit: enviroment variable PADSLOT not set\n")); #endif return 0; } #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("drvBlmStreamInit: blmslot set to enviroment variable PADSLOT: %s\n",blmslot)); DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("drvBlmStreamInit: blmslot must match VME's $(blm) macro in _WF_CP INP field: %s\n",blmslot)); #endif blm_card = atoi(blmslot); #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("drvBlmStreamInit: Starting blmUdpListener thread to run blmUdpThread() for PAD channel %i\n", blm_card)); #endif return epicsThreadCreate( "blmUdpListener", epicsThreadPriorityScanHigh, epicsThreadGetStackSize(epicsThreadStackMedium), blmUdpThread, (void*)blm_card); } char ourBuffer[2000]; int setOurBuffer(char* stringToWrite) { strcpy(ourBuffer, stringToWrite); return OK; } void * getMyData(void *buf, int idx, int nsamples, int endianLittle, int colMajor, void *uarg) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("getMyData:\n")); #endif memcpy( buf, ourBuffer, nsamples * 2 ); return buf; } unsigned int padgMcastAddr; static void blmUdpThread(void *arg) { int err; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmUdpThread: starting padUdpHandler()\n")); #endif /* use default port and channel number passed as arg */ if ( (err = padUdpHandler(padgMcastAddr, 0, (int)arg, 0, 0, 0)) ) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("blmUdpThread: padUdpHandler() aborted: %s\n", strerror(-err))); #endif return; } #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmUdpThread: padUdpHandler started successfully for channel %d\n", (int)arg)); #endif } /* * /CS (chip-select) of the 4 fifos are driven by A2 / A3. * * This leads to the following memory layout starting at CS1_BASE_ADDR: * * 0..3 channel 0 * 4..7 channel 1 * 8..11 channel 2 * 12..15 channel 3 * 16..19 channel 0 * 20..23 channel 1 * 24..27 channel 2 * 28..31 channel 3 * ... and so on ... * * Seen as a struct of 16-bit values this looks like this * * struct { * signed short ch0; * signed short ch0; * signed short ch1; * signed short ch1; * signed short ch2; * signed short ch2; * signed short ch3; * signed short ch3; * } */ static inline uint32_t bswap(uint32_t x) { asm volatile("byterev %0; swap %0":"+d"(x)); return x; } /*============================================================================= Name: blmSetDataFileStem Abs: =============================================================================*/ /* Set the stem of the filename for the output data files */ int blmSetDataFileStem(char * stem){ strcpy(filenameStem, stem); printf("blmSetDataFileStem: setting filename to stem '%s'\n", filenameStem); return OK; } /*============================================================================= Name: blmGetDataFileStem Abs: =============================================================================*/ char * blmGetDataFileStem() { return filenameStem; } /*============================================================================= Name: blmInitialiseScalarFromFile Abs: RF is at 2856 MHz. There is no digitizer that runs this fast. So work at IF (intermediate frequency) of 25.5 MHz and (smartly) choose to "digitally downmix" (a fancy name for taking the sine and cosine of something) to the baseband frequency of DC (0 MHz). By choosing and ADC clock of 102 MHz, there are 4 points to each IF cycle. They are pi/2 apart, so taking the sine and cosine has the result that: 0 sin(0)=0; Q=0 cos(0)=1; I=I pi/2 sin(pi/2)=1; Q=Q cos(pi/2)=0; I=0 pi sin(pi)=0, Q=0 cos(pi)=-1; I=-I 3pi/2 sin(3pi/2)=-1; Q=-Q cos(3pi/2)=0; I=0 Since Q is non-zero only when I is zero, and vice versa, the two variables can be stored in a single array, in alternating positions What is stored in "scalar" looks like: [ 1, 1, -1, -1, ... ] and maps to the Qs and Is as: [ Q1, I2, Q3, I4, ... ] where I1, Q2, I3 and Q4 are all zero. But this is not all. There is also a weighting factor multiplied to each value in scalar to correct the I and Qs to be "what the beam sees". If the application is BLM_LSR ch0 or BLM_REF ch0-3, then scalar needs to be 64 Kwords long (BLM_FIFO_SIZE). Otherwise, it needs to be only BLM_SAMPLE_SIZE long. Note that for BLM_KLY and for BLM_L1X_KLY, no scalar correction is needed. Go get values for the scalar corrections from a value. One of three pointers in channel structure is filled in, depending on the value of sample. Ret: OK/ERROR =============================================================================*/ int blmInitialiseScalarFromFile(int channel, char* filename){ int ii; blm_channel_t* pCh; FILE *fin; /* Ensure nelm <= BLM_SAMPLE_SIZE? */ #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBunchLengthCFScalFlag, ("blmInitialiseScalarFromFile: inputs: channel: %d, filename = %s\n", channel, filename)); #endif printf("blmInitialiseScalarFromFile: inputs: channel: %d, filename = %s\n", channel, filename); /* Attempt to find/open the file */ fin = fopen(filename, "r"); if (fin==NULL) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBunchLengthCFScalFlag, ("blmInitialiseScalarFromFile: unable to open '%s' for read. Exiting.\n", filename)); #endif printf("blmInitialiseScalarFromFile: unable to open '%s' for read. Exiting.\n", filename); return ERROR; } /* Read the values into scalar */ pCh = pChannels[channel]; /* malloc space for and put file contents into channel struct's "scalar" */ printf("Filling scalar for ch %d\n", channel); pCh->scalar = (short*)malloc(sizeof(short)*BLM_SAMPLE_SIZE); for (ii=0; iiscalar+ii)); } /* Close the file */ fclose(fin); return OK; } /*============================================================================= Name: blmISR Abs: Executes every time the interrupt that indicates FIFO full arrives Rem: No function prototype. Passes typedef struct in. =============================================================================*/ void blmISR (void *arg_p) { blmLan9118_t* info_ps = (blmLan9118_t*)arg_p; coldfEportIntDisable(info_ps->irq_pin); if (intrCount < BLM_MAX_INT) { intrCount++; } else { intrCount = 0; numIntrRollovers++; } /* Wake up task which does the data acquisition */ /* FIX ME: debug, slow down the interrupt rate */ /*if((intrCount & 0x01) == 0)*/ epicsEventSignal(info_ps->data_ready); return; } /*============================================================================= Name: blmGetIntrCount Abs: Return the number of interrupts that have been processed since boot =============================================================================*/ int blmGetIntrCount() { return intrCount; } /*============================================================================= Name: blmGetOverflowCount Abs: Return the number of data overflows that have been processed since boot =============================================================================*/ int blmGetOverflowCount() { return overflowCount; } #ifdef SCAN_IO /*============================================================================= Name: blmGetScanIOCount Abs: =============================================================================*/ int blmGetScanIOCount() { return scanIoCount; } #endif /*============================================================================= Name: blmTurnOn/OffLED Abs: It should be obvious =============================================================================*/ int blmTurnOnLED() { volatile unsigned char *place; place = (unsigned char *) EPDR; *place = 0xF7; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmTurnOnLED: %d\n", (int) *place)); #endif return OK; } int blmTurnOffLED() { volatile unsigned char *place; place = (unsigned char *) EPDR; *place = 0xFF; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmTurnOffLED: %d\n", (int) *place)); #endif return OK; } /* It should take 2.5 millisec to write to the 256 Kword FIFO It should take 12.5 millisec to read from the 256 Kword FIFO NB: without the "while" stmt, you have to call this once to enable FIFO (which isn't yet full) and then call it again to see the full FIFO Args: Type Name Access Description --------------- ------------- ---------- ---------------------------- int startingPoint read-only first 40 nsec increment to read int num40SecIncs read-only number of (16 bit) shorts to read */ /*============================================================================= Name: blmGetSampleOffset Abs: =============================================================================*/ int blmGetSampleOffset(int channel) { int val = 0; iqcal_channel_t* pCCh; blm_channel_t* pCh; switch (channel) { case 0: case 1: case 2: case 3: pCh = pChannels[channel]; val = pCh->ofst; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetSampleOffset: ofst is %d\n", val)); #endif break; case 4: case 5: case 6: case 7: pCCh = pCalChannels[channel-4]; val = pCCh->ofst; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetSampleOffset: ofst is %d\n", val)); #endif break; default: #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("blmGetSampleOffset: unrecognized channel: %d\n", channel)); #endif } return val; } /*============================================================================= Name: blmSetSampleOffset Abs: Set offset to reflect desired value + 3 clock cycles that we must wait for =============================================================================*/ int blmSetSampleOffset(int channel, int ofst) { blm_channel_t* pCh; iqcal_channel_t* pCCh; /* Range checking limit depends on the mode of operation. When CALIBRATING, channels 4-7 are used. The sample offset is __________. When RUNNING, channels 0-3 are used. The sample offset is __________. */ switch (channel) { case 0: case 1: case 2: case 3: pCh = pChannels[channel]; pCh->ofst = ofst + 3; /* do 3 garbage reads while FIFO fills */ #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBunchLengthCFCfgFlag, ("blmSetSampleOffset: ofst = %d\n", pCh->ofst)); #endif break; case 4: case 5: case 6: case 7: pCCh = pCalChannels[channel-4]; pCCh->ofst = ofst + 3; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBunchLengthCFCfgFlag, ("blmSetSampleOffset: address to channel structure is 0x%08x\n", (unsigned int) pCCh)); DEBUGPRINT(DP_INFO, drvBunchLengthCFCfgFlag, ("blmSetSampleOffset: address to ofst] is 0x%08x\n", (unsigned int) &(pCCh->ofst))); DEBUGPRINT(DP_INFO, drvBunchLengthCFCfgFlag, ("blmSetSampleOffset: ofst = %d\n", pCCh->ofst)); #endif break; default: #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBunchLengthCFCfgFlag, ("blmSetSampleOffset: unrecognized channel: %d\n", channel)); #endif return ERROR; } return OK; } /*============================================================================= Name: blmGetSampleSize Abs: return sample size for any channel =============================================================================*/ int blmGetSampleSize(int channel) { int val; blm_channel_t* pCh; iqcal_channel_t* pCCh; switch (channel) { case 0: case 1: case 2: case 3: pCh = pChannels[channel]; val = pCh->sz; break; case 4: case 5: case 6: case 7: pCCh = pCalChannels[channel-4]; val = pCCh->sz; break; default: return ERROR; } #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetSampleSize: sz is %d\n", val)); #endif return val; } /*============================================================================= Name: blmSetSampleSize Abs: set sample size, free memory for the previous size and malloc the new =============================================================================*/ int blmSetSampleSize(int channel, int size) { blm_channel_t* pCh; iqcal_channel_t* pCCh; /* Range checking limit depends on the mode of operation. When CALIBRATING, channels 4-7 are used. The sample size is the BLM_FIFO_SIZE. When RUNNING, channels 0-3 are used. The sample size is BLM_SAMPLE_SIZE */ switch (channel) { case 0: case 1: case 2: case 3: if (size > BLM_SAMPLE_SIZE || size < 0) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBunchLengthCFCfgFlag, ("blmSetSampleSize: requested size, %d, out of range [0,%d]\n", size, BLM_SAMPLE_SIZE)); #endif return ERROR; } pCh = pChannels[channel]; /* Free old and allocate new size for this channel */ free(pCh->data); pCh->data = malloc(sizeof(short)*size); if (pCh->data == NULL) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_FATAL, drvBunchLengthCFCfgFlag, ("blmSetSampleSize: unable to malloc space for ch %d data\n", channel)); #endif return ERROR; } #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBunchLengthCFCfgFlag, ("blmSetSampleSize: malloced space for ch %d data: %d shorts at addr 0x%08x\n", channel, size, (unsigned int) (pCh->data))); #endif free(pCh->proc); pCh->proc = malloc(sizeof(long)*size); if (pCh->proc == NULL) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_FATAL, drvBunchLengthCFCfgFlag, ("blmSetSampleSize: unable to malloc space for ch %d proc\n", channel)); #endif return ERROR; } #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBunchLengthCFCfgFlag, ("blmSetSampleSize: malloced space for ch %d proc: %d longs at addr 0x%08x\n", channel, size, (unsigned int) (pCh->proc))); #endif pCh->sz = size; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBunchLengthCFCfgFlag, ("blmSetSampleSize: sz = %d\n", pCh->sz)); #endif break; case 4: case 5: case 6: case 7: if (size > BLM_FIFO_SIZE || size < 0) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBunchLengthCFCfgFlag, ("blmSetSampleSize: requested size, %d, out of range [0,%d]\n", size, BLM_FIFO_SIZE)); #endif return ERROR; } pCCh = pCalChannels[channel-4]; free(pCCh->data); pCCh->data = malloc(sizeof(short)*size); if (pCCh->data == NULL) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_FATAL, drvBunchLengthCFCfgFlag, ("blmSetSampleSize: unable to malloc space for ch %d calibration data 0\n", channel)); #endif return ERROR; } #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBunchLengthCFCfgFlag, ("blmSetSampleSize: malloced space for ch %d data: %d shorts at addr 0x%08x\n", channel, size, (unsigned int) (pCCh->data))); #endif pCCh->sz = size; break; default: #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBunchLengthCFCfgFlag, ("blmSetSampleSize: unrecognized channel: %d\n", channel)); #endif return ERROR; } return OK; } #ifdef OUT /*============================================================================= Name: blmGetOperationMode Abs: return mode of operation =============================================================================*/ int blmGetOperationMode() { #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetOperationMode: %d\n", blmOperationMode)); #endif return blmOperationMode; } /*============================================================================= Name: blmSetOperationMode Abs: set mode of operation =============================================================================*/ int blmSetOperationMode(int mode) { /* range check on mode */ if ((mode < 0) || (mode> BLM_NUM_OP_MODES)) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("blmSetOperationMode: mode %d is out of range [0,%d]\n", mode, BLM_NUM_OP_MODES)); #endif return ERROR; } blmOperationMode = mode; return OK; } /*============================================================================= Name: blmGetCalibrationControl Abs: return mode of operation =============================================================================*/ int blmGetCalibrationControl() { #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetCalibrationControl: %d\n", blmCalibrationControl)); #endif return blmCalibrationControl; } /*============================================================================= Name: blmSetCalibrationControl Abs: set calibration control =============================================================================*/ int blmSetCalibrationControl(int calibrationControl) { /* range check on calibrationControl */ if ((calibrationControl < 0) || (calibrationControl > BLM_NUM_CAL_MODES)) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("blmSetCalibrationControl: calibrationControl %d is out of range [0,%d]\n", calibrationControl, BLM_NUM_CAL_MODES)); #endif return ERROR; } blmCalibrationControl = calibrationControl; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmSetCalibrationControl: calibrationControl set to %d\n", calibrationControl)); #endif return OK; } #endif /*============================================================================= Name: blmReadSignal Desp: Data from all four channels are read and processed. Inp: none What else must be set up first: Abs: What is set up after: =============================================================================*/ blm_channel_t *pBlmCh[4] = { &blmCh0, &blmCh1, &blmCh2, &blmCh3 }; int fifoAddrOffset[4] = {0, 2, 4, 6}; int gNumChanToAcq=4; int blmReadSignal() { int ii; /* abs pos in the FIFO */ int mm; /* channel */ volatile short *pSrc = csar1_actual; /* MUST be volatile to avoid read-only *pSrc line below from being optimized away by the compiler AND for the blmChanneli[jj] = *pSrc from being optimized to be assigned */ blm_channel_t *chan; long sum; short *pChanData; short *pChanScalar; long *pChanProc; for (mm=0; mmnToRead = chan->ofst + chan->sz; /* skip the offset first */ for(ii=0; iiofst; ii++) *pSrc; sum = 0; pChanData = chan->data; pChanScalar = chan->scalar; pChanProc = chan->proc; #if 1 for(ii=0; iisz; ii++) { *pChanData = *pSrc; /* FIFO, address is fixed */ sum += (*pChanData++) * (*pChanScalar++); } #endif #if 0 for(ii=0; iisz; ii++) { *pChanData = *pSrc; /* FIFO, address is fixed */ *pChanProc = (*pChanData++) * (*pChanScalar++); sum += *pChanProc++; } #endif chan->sum = sum; chan->num = chan->sz; chan->nRead = chan->sz; } /* mm loop */ return OK; } /*============================================================================= Name: blmCalReadSignal Abs: What makes this read unique is that no processing is done; i.e., there is no correction factor multiplied in to the each data point What else must be set up first:... What is set up after: if in BLM_CALIBRATING operational mode:... NB: Since this calibration channel is ALWAYS in channel 0, there is no need for a srcOfst term to be added to pSrc here 9/29/2006 TO DO: Since every BLM now can do calibration in all of its channels, this routine no longer needs to pass any args in. Just make a loop through all 4 blmCalChannels where chan gets set to blmCalChannels[mm]; for (mm=0; mmnToRead = chan->ofst + chan->sz; #ifndef FAKE_DATA printf("blmCalReadSignal: initiating chip select read at 0x%08x for %d words\n", (unsigned int) csar1_actual, chan->nToRead); #else printf("blmCalReadSignal: faking channel %d data for %d words\n", mm, chan->sz); #endif /* Here are the guts of the read. This code was timed and found to take 250 ns to read one short */ printf("blmCalReadSignal: guts of read for channel %d\n",mm); jj = 0; for (ii=0; iinToRead; ii++) { /* Have we reached the starting point yet? Only copy data after that point*/ /* *pSrc will be refilled by hardware after read */ if (ii < chan->ofst) { /* We've not yet reached the starting point. Read pSrc, but only for purpose of getting to the next value */ #ifndef FAKE_DATA *(pSrc+srcOfst); #endif } else { #ifndef FAKE_DATA *(chan->data+jj) = *(pSrc+srcOfst); #else /* Make fake data */ *(chan->data+jj) = ii; printf("blmCalReadSignal: writing %d into addr 0x%08x (ch[%d]->data[%d])\n",ii,(unsigned int)chan->data+jj,mm,jj); #endif jj++; } } /* We've finished reading out the FIFO now */ /* Save the number of 16-bit words read */ chan->nRead = jj; printf("blmCalReadSignal: number of words read is: %d\n", chan->nRead); } /* mm loop */ return OK; } /*============================================================================= Name: blmGetSignal(int channel) Abs: Ret: The data read from the FIFO for a specified channel and sample for either type: raw (0) or processed (1) =============================================================================*/ short *blmGetSignal(int channel, int inputType) { #ifdef DEBUGPRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetSignal: returning signal for ch:%d, inputType:%d\n", channel, inputType)); #endif /* Determine if operational data or calibration data based on channel */ if (channel >= 0 && channel < BLM_NUM_CHANNELS_ON_BOARD) { /* Figure out what to do based on inputType */ switch (inputType) { case BLM_RAW: return pChannels[channel]->data; break; case BLM_SCALAR: return pChannels[channel]->scalar; break; case BLM_PROCESSED: return (short*)(pChannels[channel]->proc); break; default: #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetSignal: unrecognized input type: %d\n", inputType)); #endif } } else { /* Send back calibration data */ return pCalChannels[channel-4]->data; } return (short*) NULL; } /*============================================================================= Name: blmGetSum(int channel) Abs: =============================================================================*/ long long blmGetSum(int channel) { long long val; val = pChannels[channel]->sum; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetSum: sum is %lld\n", val)); #endif return val; } /*============================================================================= Abs: return a value for x to plot the average I and Q =============================================================================*/ short blmGetX(int channel) { int val1; int val2; int val3; val1 = pChannels[channel]->ofst; val2 = pChannels[channel]->sz; /* x is the offset + halfway point of the sample */ val3 = val1 + val2/2; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetX: ofst is %d\n", (int) val1)); DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetX: sz is %d\n", (int) val2)); DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("x=%d\n",val3)); #endif return (short) val3; } /*============================================================================= Name: blmGetNumShortsToRead(int channel) Abs: Debug routine to check number of words planned to read, given channel within the channel =============================================================================*/ int blmGetNumShortsToRead(int channel) { int val; val = pChannels[channel]->nToRead; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetNumShortsToRead: numToRead is %d\n", val)); #endif return val; } /*============================================================================= Name: blmGetNumShortsRead() Abs: Debug routine to check number of words actually read, given channel and within the channel =============================================================================*/ int blmGetNumShortsRead(int channel) { int val; val = pChannels[channel]->nRead; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmGetNumShortsRead: numRead is %d\n", val)); #endif return val; } /*============================================================================= Name: blmSetDataFileName Abs: =============================================================================*/ /* Create unique filename by appending first the "seconds past Epoch" and .dat" */ int blmSetDataFileName() { char timestampForFile[20]; epicsTimeStamp timeAtWrite; strcpy(filename, blmGetDataFileStem()); epicsTimeGetCurrent(&timeAtWrite); printf("sec=%d\n",timeAtWrite.secPastEpoch); /* seconds since 0000 Jan 1, 1990 */ printf("nsec=%d\n",timeAtWrite.nsec); /* nanoseconds */ sprintf(timestampForFile,"%lu", (unsigned long) timeAtWrite.secPastEpoch); printf("%s\n",timestampForFile); strcat(filename, timestampForFile); strcat(filename, ".dat"); printf("blmSetDataFileName: complete filename is now '%s'\n",filename); return OK; } /*============================================================================= Name: blmGetDataFileName Abs: =============================================================================*/ char * blmGetDataFileName() { return filename; } /*============================================================================= Name: blmDumpDataToFile Abs: data for all channel structures get written The second sample, sample '1', is only dumped for the BLM_BPH case =============================================================================*/ int blmDumpDataToFile() { int jj; int kk; int rc; FILE *fout; /* Create a new file for this acquisition */ rc = blmSetDataFileName(); fout = fopen(blmGetDataFileName(), "w"); if (fout == NULL) { fprintf(stderr, "blmDumpDataToFile: error opening file '%s': %s\n", filename, strerror(errno)); return ERROR; } else { printf("blmDumpDataToFile: writing to file '%s'\n", filename); } for (jj=0; jjsz, filename); fprintf(fout,"Channel %d Sample 0: ",jj); for (kk=0; kksz; kk++) { fprintf (fout,"%d ", (int) *(pChannels[jj]->data+kk)); } fprintf(fout,"\n"); #ifdef BLM_PROCESS_DURING_READ fprintf(fout, "sum %lld\n", pChannels[jj]->sum); fprintf(fout, "num %d\n", pChannels[jj]->num); #endif } fclose(fout); return OK; } /*============================================================================= Name: blmDumpCalDataToFile Abs: data for all calibration channel structures get written =============================================================================*/ int blmDumpCalDataToFile() { int jj; int kk; FILE *fout; char filename[40]; for (jj=0; jjsz, filename); } for (kk=0; kksz; kk++) { fprintf (fout,"%d\n", (int) *(pCalChannels[jj]->data+kk)); } fclose(fout); } return OK; } /*============================================================================= Name: blmDumpNonLinDataToFile Abs: Pass in num of channel 0 raw datasets you want written to server (one per file). No timestamping into filename is done because files are named so that they match names expected by blmHist executable. =============================================================================*/ int blmDumpNonLinDataToFile(int fileprefix) { int kk; FILE *fout0; FILE *fout1; FILE *fout2; FILE *fout3; char filename0[40]; char filename1[40]; char filename2[40]; char filename3[40]; /* Create 4 new files for this acquisition */ sprintf(filename0,"/data/zero/%d.dat",fileprefix); sprintf(filename1,"/data/one/%d.dat",fileprefix); sprintf(filename2,"/data/two/%d.dat",fileprefix); sprintf(filename3,"/data/three/%d.dat",fileprefix); /* Open the 4 new files */ fout0 = fopen(filename0, "w"); if (fout0 == NULL) { fprintf(stderr, "blmDumpNonLinDataToFile: error opening file '%s': %s\n", filename0, strerror(errno)); return ERROR; } else { printf("blmDumpNonLinDataToFile: writing to file '%s'\n", filename0); } fout1 = fopen(filename1, "w"); if (fout1 == NULL) { fprintf(stderr, "blmDumpNonLinDataToFile: error opening file '%s': %s\n", filename1, strerror(errno)); return ERROR; } else { printf("blmDumpNonLinDataToFile: writing to file '%s'\n", filename1); } fout2 = fopen(filename2, "w"); if (fout2 == NULL) { fprintf(stderr, "blmDumpNonLinDataToFile: error opening file '%s': %s\n", filename2, strerror(errno)); return ERROR; } else { printf("blmDumpNonLinDataToFile: writing to file '%s'\n", filename2); } fout3 = fopen(filename3, "w"); if (fout3 == NULL) { fprintf(stderr, "blmDumpNonLinDataToFile: error opening file '%s': %s\n", filename3, strerror(errno)); return ERROR; } else { printf("blmDumpNonLinDataToFile: writing to file '%s'\n", filename3); } /* Write the data to the files */ printf("blmDumpNonLinDataToFile: calibration channel 0: writing %d shorts to '%s'\n", pCalChannels[0]->sz, filename0); for (kk=0; kksz; kk++) { fprintf (fout0,"%d\n", (int) *(pCalChannels[0]->data+kk)); } printf("blmDumpNonLinDataToFile: calibration channel 1: writing %d shorts to '%s'\n", pCalChannels[1]->sz, filename1); for (kk=0; kksz; kk++) { fprintf (fout1,"%d\n", (int) *(pCalChannels[1]->data+kk)); } printf("blmDumpNonLinDataToFile: calibration channel 2: writing %d shorts to '%s'\n", pCalChannels[2]->sz, filename2); for (kk=0; kksz; kk++) { fprintf (fout2,"%d\n", (int) *(pCalChannels[2]->data+kk)); } printf("blmDumpNonLinDataToFile: calibration channel 3: writing %d shorts to '%s'\n", pCalChannels[3]->sz, filename3); for (kk=0; kksz; kk++) { fprintf (fout3,"%d\n", (int) *(pCalChannels[3]->data+kk)); } /* Close the files */ fclose(fout0); fclose(fout1); fclose(fout2); fclose(fout3); return OK; } /*============================================================================= Name: blmGetIoScanPvt Abs: Used by records that process on I/O Intr. Device support calls this in its get_ioint_info routines at init'n. =============================================================================*/ #ifdef SCAN_IO IOSCANPVT blmGetIoScanPvt() { return blm_ioscanpvt; } #endif #ifdef OUT /*============================================================================= Name: blmCalibration Abs: Does the calibration data acquisition upon receipt of calibration request. =============================================================================*/ int blmCalibration() { int rc; printf("blmCalibration: disabling hardware triggers for the calibration\n"); blmDisableIntr(); printf("blmCalibration: calling blmCalReadSignal\n"); blmCalReadSignal(&blmCalCh0,&blmCalCh1,&blmCalCh2,&blmCalCh3); /* For the BLM, calibration is a one-shot. Write the calibration data to files, one per channel and set the calibration done indicator */ printf("blmCalibration: calling blmDumpCalDataToFile\n"); rc = blmDumpCalDataToFile(); if (rc == ERROR) { printf ("blmCalibration: error writing calibration data to server\n"); return rc; } #ifdef SCAN_IO /* Process I/O Intr scan records registered to this callback COULD DO ANOTHER BLM_IOSCANPVT VARIABLE JUST TO PROCESS CAL WAVEFORM RECORDS scanIoRequest(blm_cal_ioscanpvt); if (scanIoCalCount < BLM_MAX_INT) { scanIoCalCount++; } else { scanIoCalCount = 0; numScanIoCalRollovers++; } */ #endif /* Since it's a one-shot, we want to automatically set calibration done here. I.e. don't wait for the button press */ printf("blmCalibration: setting calib done\n"); blmSetCalibrationControl(BLM_CAL_DONE); /* Check: this may be also being done by the state machine upon receipt of calib done */ printf("blmCalibration: enabling hardware triggers since calibration complete\n"); blmEnableIntr(); return OK; } #endif /*============================================================================= Name: blmDacqTask Abs: acquire and process the data upon receipt of event from ISR =============================================================================*/ struct timeval tpA; struct timeval tpB; int blmDacqExeTime[20]; int exeTimeIndex = 0; int blmDacqTask(void* arg) { int rc; int status; epicsEventWaitStatus waitStatus; blmLan9118_t *pblmLan9118 = arg; PadDataKind kind = PadDataBpm; /* PadDataKind is an enum defined in drvLan9118/ padStream.h distinguishing beam data from cal data */ while (TRUE) { /* wait for the ISR to indicate that there is data waiting to be read */ waitStatus = epicsEventWait(pblmLan9118->data_ready); if (waitStatus == epicsEventWaitOK) { gettimeofday(&tpA, NULL); drvBlmLan9118Acqs++; rc = blmReadSignal(); status = padStreamSend(getdata, kind, 0, 0); gettimeofday(&tpB, NULL); if(exeTimeIndex < 20) blmDacqExeTime[exeTimeIndex++] = tpB.tv_usec - tpA.tv_usec; /* If we can't send streaming data then * 'ordinary' record support is engaged. */ if ( status ) { pblmLan9118->irq = 1; /* signal IRQ */ updatingWfs++; /* stream not active; process record */ #ifdef SCAN_IO /* Process I/O Intr scan records registered to this callback */ scanIoRequest(blm_ioscanpvt); if (scanIoCount < BLM_MAX_INT) { scanIoCount++; } else { scanIoCount = 0; numScanIoRollovers++; } #endif } else { /* 6/26/8: option: take out this just this clause if too much */ #ifdef SCAN_IO /* Process I/O Intr scan records registered to this callback */ scanIoRequest(blm_ioscanpvt); if (scanIoCount < BLM_MAX_INT) { scanIoCount++; } else { scanIoCount = 0; numScanIoRollovers++; } #endif } /* Keep processing interrupts when streaming turned off by VME */ /* Clear interrupt here so we can detect a trigger overrun */ coldfEportFlagClr(pblmLan9118->irq_pin); coldfEportIntEnable(pblmLan9118->irq_pin); } else { /* event error processing */ if (waitStatus == epicsEventWaitTimeout) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118DacqFlag, ("blmDacqTask: timed out waiting for data to be available to read out of FIFO\n")); #endif return ERROR; } else { if (waitStatus == epicsEventWaitError) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118DacqFlag, ("blmDacqTask: error waiting for data to be available to read out of FIFO\n")); #endif return ERROR; } } } } return rc; } int blmDacqExeTimeShow() { int i; for(i=0; i<20; i++) printf("%d,", blmDacqExeTime[i]); exeTimeIndex=0; printf("\n"); } /*============================================================================= Name: blmInitialise Abs: Sets up interrupts and the chip select register: CSCR CSAR1 CSMR1. Sets up the event semaphore that ISR will post "data available" with. =============================================================================*/ int blmInitialise() { int rc; #ifdef DEBUG_PRINT drvBlmLan9118Flag=DP_INFO; DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: hardware initialisation in progress...\n")); #endif /* Fill a structure pointed to by pblmLan9118 with useful info */ pblmLan9118->irq_pin = IRQ_PIN; #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: Set irq_pin to %d\n", IRQ_PIN)); #endif /* Make an event that ISR will use to signal data acquisition task */ pblmLan9118->data_ready = epicsEventCreate(0); if ( ! pblmLan9118->data_ready ) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("blmInitialise: Unable to create EPICS event\n")); return ERROR; #endif } /* Initialize streaming mode */ #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("blmInitialise: calling drvBlmStreamInit()\n")); #endif if ( ! drvBlmStreamInit(blmLan9118)) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("blmInitialise: Warning - no streaming mode available\n")); #endif } else { #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: streaming mode initialized\n")); #endif } #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: ensure interrupts disabled\n")); #endif coldfEportIntDisable_inl(pblmLan9118->irq_pin); /* Setup trigger: configure eport as output, pull it low. Forever. This is not a BPM app. We don't want to block triggers by a s/w trigger */ #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: set up trigger\n")); #endif /* 7/2/8: coldfEport routines not working. See high impedance value (2V) for this pin on scope. Not sure why. #define EPORT_OUTPUT 1 coldfEportSetup(pblmLan9118->trig_pin, EPORT_OUTPUT); coldfEportEpdrSet(pblmLan9118->trig_pin, 0); */ *epddr |= 2; *epdr &= ~2; /* Setup Interrupt: configure EPORT for rising edge interrupt; clear any pending IRQs */ #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: set up interrupt\n")); #endif coldfEportFlagClr(pblmLan9118->irq_pin); coldfEportSetup(pblmLan9118->irq_pin, IRQ_EDGE); /* Connect the interrupt vector to the interrupt service routine */ #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: set up interrupt vector and ISR\n")); #endif rc = devConnectInterruptVME(64 + pblmLan9118->irq_pin, blmISR, pblmLan9118); if (rc != 0) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_FATAL, drvBlmLan9118Flag, ("blmInitialise: unable to connect to intr vector to blmISR. rc = %d\n", rc)); #endif return ERROR; } #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: intr vector, %x, connected to ISR\n", 64 + pblmLan9118->irq_pin)); #endif /* Set up the chip select register 1 */ *csar1 = 0x8000;/* bit 15: 1000 0000 0000 0000: bit 0 */ *cscr1 = 0x0580;/* bit 15: 0000 0101 1000 0000: bit 0 */ /* x one wait state */ /* x auto-acknowledge enable. Detemines the assertion of the internal transfer ack for accesses specified by the chip select address. */ /* x 16-bit port size. Valid data sampled and driven on D[31:16] */ /* NB: set csmr1 up LAST. It sets the chip select to valid. */ *csmr1 = 0x103; /* bit 31: 0000 0000 0000 0000 0000 0001 0000 0011: bit 0 */ #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: csar1 has addr 0x%08x and contents 0x%08x\n", (int) csar1, *csar1)); /* NB: Doing this next line actually triggers a READ of the chip select reg */ DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: csar1_actual has addr 0x%08x and contents 0x%08x\n", (int) csar1_actual, *csar1_actual)); DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: cscr1 has addr 0x%08x and contents 0x%08x\n", (int) cscr1, (short) *cscr1)); DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: csmr1 has addr 0x%08x and contents 0x%08x\n", (int) csmr1, (unsigned int) *csmr1)); #endif /* Initialize our watchdog timer queue */ blmWdTimerQ=epicsTimerQueueAllocate( 1, /* ok to share queue */ epicsThreadPriorityLow); if (blmWdTimerQ==0) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("blmInitialise: error initialising watchdog timer queue\n")); #endif return ERROR; } #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: watchdog timer queue initialised\n")); #endif /* Set this up if there are records scanned on "I/O Intr" in the db */ #ifdef SCAN_IO scanIoInit(&blm_ioscanpvt); #endif /* Ensure only one Dacq thread */ #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: start Dacq thread to run padDacqTask\n")); #endif if ( drvBlmLan9118DacqThread ) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: Dacq thread present, so skipping creation of another thread and using this one\n")); #endif } else { /* Create a thread to run at highest priority to do the data acquistion */ drvBlmLan9118DacqThread = epicsThreadCreate( "Dacq", epicsThreadPriorityMax, epicsThreadGetStackSize(epicsThreadStackMedium), (EPICSTHREADFUNC)blmDacqTask, pblmLan9118); #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: Dacq thread started. Id is %d \n", (int)drvBlmLan9118DacqThread)); #endif } /* To do: check val of drvBlmLan9118Thread and complain if error */ #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBlmLan9118Flag, ("blmInitialise: hardware initialisation complete, but interrupts not yet enabled.\n")); #endif /* Initialisation is done. Turn off DP_INFO messages */ #ifdef DEBUG_PRINT drvBlmLan9118Flag=DP_ERROR; #endif return OK; } int blmEnableIntr() { #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBunchLengthCFIntrFlag, ("blmEnableIntr: enabling interrupts.\n")); #endif /* Enable the interrupt. Don't do this UNTIL everything is set up */ *epier = 0x04; /* Enable IRQ2 */ return OK; } int blmDisableIntr() { #ifdef DEBUG_PRINT DEBUGPRINT(DP_INFO, drvBunchLengthCFIntrFlag, ("blmEnableIntr: disabling interrupts.\n")); #endif /* Disable the interrupt. Called when operational mode starts CALIBRATING */ *epier = 0x00; return OK; } /*============================================================================= Name: blmSoftTrigger Abs: toggles IRQ1 bit which causes an IRQ2 hardware trigger The rising edge of IRQ1 is what is tied to IRQ2 in the CPLD, so first lower it (to make sure it's low), then raise it, so the IRQ2 gets triggered. Then, leave IRQ1 low. =============================================================================*/ int blmSoftTrigger(){ *epdr &= ~2; *epdr |= 2; *epdr &= ~2; return OK; } /*============================================================================= Name: blmResetFifo Abs: manually resets FIFO =============================================================================*/ int blmResetFifo(){ *epdr &= ~8; /* 1111 0111 */ *epdr |= 8; /* 0000 1000 */ return OK; } /* DEBUG ROUTINES. NOT PART OF OPERATIONAL CODE */ /*============================================================================= Name: blmDumpEppdr Abs: Debug function =============================================================================*/ int blmDumpEppdr() { printf("eppdr contents: %d\n", *eppdr); return OK; } /*============================================================================= Name: blmToggleIRQ5 Abs: Debug function =============================================================================*/ int blmToggleIRQ5() { volatile char b; b = *eppdr ^ 32; *epdr = b; return (int) b; } /*============================================================================= Name: blmCauseChipSelect Abs: =============================================================================*/ int blmCauseChipSelect() { printf("csar1_actual has address 0x%08x and contents: %d\n", (unsigned int) csar1_actual, (short) *csar1_actual); return OK; } /*============================================================================= Name: blmClearChannel Abs: Sets entire contents of channel struct to zero. =============================================================================*/ int blmClearChannel(int channel) { if (channel >= BLM_NUM_CHANNELS_ON_BOARD ) { #ifdef DEBUG_PRINT DEBUGPRINT(DP_ERROR, drvBlmLan9118Flag, ("blmClearChannel: unrecognized channel %d\n", channel)); #endif return ERROR; } memset(pChannels[channel],0,sizeof(blm_channel_t)); return OK; }