/* $Id: devWfPadBpm.c,v 1.26 2012/11/12 22:04:41 strauman Exp $ */ /*============================================================================= Name: devWfPadBpm.c Abs: Device support for pumping data of a 4-channel PAD into a single waveform. Auth: 10-oct-2006, Till Straumann (TSS) Rev: -----------------------------------------------------------------------------*/ #if 0 #include "copyright_SLAC.h" /* SLAC copyright comments */ #endif /*----------------------------------------------------------------------------- Mod: (see CVS log) =============================================================================*/ #include #include #include #include #include #ifdef BASE_HAS_NO_NTP_PATCH #include #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* RTEMS priorities of the most important threads */ /* IIRC the highest priority task we start are the watchdog (19) * and the lanIpBasic callout task which is at 25. * * Hence we use numbers below that. */ /* The padThread is the worker who copies data from * the ADC FIFOs to the 9118 Lan chip. * It has the highest priority. */ #define PAD_THREAD_PRI 10 /* The udp listener is the task that handles padRequests * etc. It is responsible for setting the stream timestamp * and therefore has the second-highest priority */ #define UDP_LISTEN_PRI 12 /* If neither of the above have any work to do then * the next important thing is handling lanIpBasic * networking. */ #define LAN_IPBASIC_PRI 14 /* #include */ #include #include #include #include #include /* Re-define symbols for rtems 4.9.1 */ #if !defined(__RTEMS_MAJOR__) #error "missing header" #elif (__RTEMS_MAJOR__ > 4) || (__RTEMS_MAJOR__ == 4 && __RTEMS_MINOR__ >= 9) #include #define Timer_initialize() benchmark_timer_initialize() #define Read_timer() benchmark_timer_read() #endif #include #include #include #define DEVSUPNAM "devWfPadBpm" /* Align up to next multiple of 8. * We strictly only need multiples of 4 (4 channels) * but making sure we always have an even number of * samples makes storing the row-major format easier */ #define CHANNEL_NO_ALIGN(x) (((x)+7) & ~7) /* Which chip select we are using - this is setup by the BSP * but not published :-( */ #define CS1_BASE_ADDR 0x30000000 /* Direct access to the LAN9118 FIFO -- an ugly hack * but it's much faster... */ #define LAN9118_FIFO_HACK ((volatile void*)0x31000800) /* Just a name for sake of readability */ #define CS1 1 /* 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 #define STATIC #define DEBUG_PROC (1<<0) #define DEBUG_TIMING (1<<1) #define DEBUG_IRQ (1<<3) typedef struct { int channel; uint32_t mcaddr; } *PadUdpThreadArg; int drvPadTrigPin = TRIG_PIN_DFLT; int drvPadIrqPin = IRQ_PIN_DFLT; volatile int devWfPadDebug = 0; volatile int devWfPadIrqs = 0; volatile uint32_t drvPadIrqTime = 0; volatile uint32_t drvPadIsrEndTime = 0; volatile uint32_t drvPadMaxProcessingTime = 0; volatile uint32_t drvPadMaxStreamSendTime = 0; volatile uint32_t drvPadMaxIsrTime = 0; volatile uint32_t drvPadMaxGetCaltTime = 0; volatile uint32_t drvPadMaxDispatchTime = 0; typedef int16_t __attribute__ ((may_alias)) int16_t_a; typedef uint32_t __attribute__ ((may_alias)) uint32_t_a; epicsThreadId devWfPadThread = 0; static DBADDR dbAddrRarm = {0}; static int gotCalt; typedef struct DevWfPadDpvt_ts_ { waveformRecord *rec_p; CALLBACK cb_s; int irq_pin; int trig_pin; volatile int irq; int orarm; epicsEventId sync; unsigned long nusr; /* support user resizing of array */ void (*readFifos)(volatile void*, int, int, int, int); } DevWfPadDpvt_ts, *DevWfPadDpvt_tps; /* Forward Declarations */ static int start_stop_cb(PadRequest req, PadStrmCommand start, void *uarg); static void isr(void *arg_p); static void padThread(void *arg); /* Little Helpers */ static void trigRaise(int trig_pin) { coldfEportEpdrSet(trig_pin, 1); } static void disarm(DevWfPadDpvt_tps dpvt_ps) { /* if the device is currently armed we can't * really disarm it, i.e., we can't prevent * the next trigger from happening. */ coldfEportIntDisable(dpvt_ps->irq_pin); /* If a hw trigger happens after the board * is disarmed the following can happen * on the next 'arm' operation: * a) FIFO full -> everything OK * b) FIFO still filling -> OK, next trigger will be caught * c) FIFO still filling, SW trigger -> BAD will effectively * disarm board. * ==> SW trigger should verify that fifo is not * currently filling. If it is then * just run the ISR so the current data * is sucked. */ } /* * Read RARM field directly from the record * (we assume reading an 'int' is atomical). */ int devPadWfGetRarm(int *p_val) { if ( ! dbAddrRarm.precord ) { epicsPrintf("devPadWfGetRarm: dbAddr not initialized\n"); return -1; } *p_val = (int)((waveformRecord*)dbAddrRarm.precord)->rarm; return 0; } /* Write RARM field through database */ int devPadWfSetRarm(int val) { long x = val; if ( ! dbAddrRarm.precord ) { epicsPrintf("devPadWfSetRarm: dbAddr not initialized\n"); return -1; } return dbPutField(&dbAddrRarm, DBR_LONG, &x, 1); } static void arm(DevWfPadDpvt_tps dpvt_ps, int doSwTrig) { int intEnable = 1; /* to keep things simple, we disable interrupts here * so the ISR doesn't change EPORT bits under our feet. */ coldfEportIntDisable(dpvt_ps->irq_pin); /* clear old flag set by any pre-arm triggers */ coldfEportFlagClr(dpvt_ps->irq_pin); /* clear old CAL flag */ drvPadAfeGotCalt(1); /* release trigger pin */ coldfEportEpdrSet(dpvt_ps->trig_pin, 0); if ( doSwTrig ) { intEnable = ( 0 == drvPadAdcTrigger(dpvt_ps->trig_pin, dpvt_ps->irq_pin) ); if ( !intEnable ) { /* no; it appears above we cleared the interrupt * that caused this acquisition. * just fake an IRQ here. */ dpvt_ps->irq = 1; /* signal IRQ */ callbackRequestProcessCallback(&dpvt_ps->cb_s, priorityHigh, dpvt_ps->rec_p); /* If we just signalled an IRQ manually then we must not * enable interrupts (arm()) */ } } if ( intEnable ) coldfEportIntEnable(dpvt_ps->irq_pin); } static long report(int interest) { epicsPrintf(DEVSUPNAM": PAD raw data into a single waveform\n"); return 0; } static long init(int after) { extern void Timer_initialize(); if ( !after ) Timer_initialize(); return 0; } static void isr(void *arg_p) { uint32_t diff; DevWfPadDpvt_tps info_ps = arg_p; drvPadIrqTime = Read_timer(); coldfEportIntDisable(info_ps->irq_pin); /* Clear interrupt here so we can detect a trigger overrun */ coldfEportFlagClr(info_ps->irq_pin); /* Check and clear CAL trigger flag */ diff = Read_timer(); gotCalt = drvPadAfeGotCalt(1); diff = Read_timer() - diff; if ( diff > drvPadMaxGetCaltTime ) drvPadMaxGetCaltTime = diff; if ( -1 == gotCalt ) { static int simt=0; /* If no AFE is present we are in lab/simulation mode * and fake the cal triggers... */ if ( 3 == ++simt ) simt = 0; gotCalt = (simt != 0); } /* disarm by raising SW trigger * * NOTE: THIS REQUIRES THE TRIGGER INPUT BEING 'active high' * w/o this arrangement there is no way to disarm * the PAD and preserve its FIFO. * We use this triggering scheme as a workaround: * * Trigger: ---------------- ------------------ * | 10ns | | overrun * |______| |___ * * IRQ: ------------- * fifo | * full | * ______________________________| * * SW-TRIG: -------- * | * 'armed' ISR |disarmed * _____________________________________| */ trigRaise(info_ps->trig_pin); if ( (devWfPadDebug & DEBUG_IRQ) > 0 ) { epicsInterruptContextMessage(DEVSUPNAM": Interrupt\n"); } devWfPadIrqs++; drvPadIsrEndTime = Read_timer(); epicsEventSignal(info_ps->sync); if ( (diff = (drvPadIsrEndTime - drvPadIrqTime)) > drvPadMaxIsrTime ) drvPadMaxIsrTime = diff; } static void set_pri(const char *nm, rtems_id tid, rtems_task_priority p) { rtems_status_code sc; rtems_task_priority old; sc = rtems_task_set_priority(tid, p, &old); if ( RTEMS_SUCCESSFUL != sc ) { rtems_error(sc,"WARNING: Unable to adjust task priority for '%s' -- may affect RT performance!\n", nm); } } static long init_record(void *record_p) { waveformRecord *waveform_ps = record_p; DevWfPadDpvt_tps dpvt_ps; char rarm_name[100]; int edge = IRQ_EDGE; rtems_id tid; rtems_status_code sc; /* Check DB configuration */ if ( waveform_ps->nelm & 3 ) { epicsPrintf(DEVSUPNAM": Warning -- NELM should be a multiple of four, truncating\n"); waveform_ps->nelm &= ~3; if ( ! waveform_ps->nelm ) { epicsPrintf(DEVSUPNAM": Error -- NELM zero\n"); goto egress; } } if ( waveform_ps->ftvl != menuFtypeSHORT ) { epicsPrintf(DEVSUPNAM": Error -- FTVL should be SHORT (is %i)\n", waveform_ps->ftvl); goto egress; } if ( VME_IO != waveform_ps->inp.type ) { epicsPrintf(DEVSUPNAM": Error -- INP is not VME_IO (but type %i)\n", waveform_ps->inp.type); goto egress; } if ( !(dpvt_ps = waveform_ps->dpvt = malloc(sizeof(*dpvt_ps))) ) { epicsPrintf(DEVSUPNAM": No memory to allocate DPVT\n"); waveform_ps->pact = 1; return -1; } dpvt_ps->rec_p = waveform_ps; dpvt_ps->irq_pin = drvPadIrqPin; dpvt_ps->trig_pin = drvPadTrigPin; dpvt_ps->irq = 0; dpvt_ps->orarm = waveform_ps->rarm; dpvt_ps->nusr = waveform_ps->nelm; if ( ! (dpvt_ps->sync = epicsEventCreate(0)) ) { epicsPrintf(DEVSUPNAM": Unable to create EPICS event\n"); waveform_ps->pact = 1; return -1; } if ( devWfPadThread ) { epicsPrintf(DEVSUPNAM": Only ONE raw waveform record can be present\n"); waveform_ps->pact = 1; return -1; } /* Start task that does the interrupt work */ devWfPadThread = epicsThreadCreate( "padT", epicsThreadPriorityMax, epicsThreadGetStackSize(epicsThreadStackMedium), padThread, waveform_ps); if ( 0 == (tid = (rtems_id)drvPadAdcStreamInit( start_stop_cb )) ) { epicsPrintf(DEVSUPNAM": Warning - no streaming mode available\n"); } /* RTEMS priorities are not a accessible to epics OSI :-( */ set_pri("padThread", (rtems_id)devWfPadThread, PAD_THREAD_PRI); set_pri("padUdpListener", tid, UDP_LISTEN_PRI); /* Ugly hack to change driver task priority; we should fix that * in lanIpBasic itself but I don't want to have to do a new * release :-( */ sc = rtems_task_ident( rtems_build_name('9','1','1','8'), RTEMS_SEARCH_ALL_NODES, &tid ); if ( sc ) { rtems_error(sc,"WARNING: Unable to determine ID of lanIpBasic driver task -- cannot readjust priority\n This may affect RT behavior!\n"); } else { set_pri("lanIpBasic", tid, LAN_IPBASIC_PRI); } strcpy(rarm_name, waveform_ps->name); strcat(rarm_name, ".RARM"); if ( dbNameToAddr(rarm_name, &dbAddrRarm) ) { epicsPrintf(DEVSUPNAM": Unable to resolve dbAddr of RARM field\n"); waveform_ps->pact = 1; return -1; } { const char *x = waveform_ps->inp.value.vmeio.parm; if ( x && strstr(x, "RowMajor") ) dpvt_ps->readFifos = drvPadReadFifosRowMajor; else dpvt_ps->readFifos = drvPadReadFifosColMajor; } /* Setup Chip Select */ coldfCsSetup(CS1, CSELECT_FLAG_AA | CSELECT_FLAG_WS(1)); coldfEportIntDisable_inl(dpvt_ps->irq_pin); /* Setup trigger */ /* Configure eport as output, hold trigger high */ trigRaise(dpvt_ps->trig_pin); coldfEportSetup(dpvt_ps->trig_pin, EPORT_OUTPUT); /* Setup Interrupt */ /* Configure EPORT for edge interrupt; clear any pending IRQS */ coldfEportFlagClr(dpvt_ps->irq_pin); /* Special HACK -- we have a stripped-down prototype board * without any digitizer/FIFO hardware. * We can still make simulation mode work if we use a single * pin for triggering and IRQ (the trigger immediately causes * an interrupt as if there was a FIFO). * However, we must make sure we use EPORT_RAISING in this * case. */ if ( dpvt_ps->trig_pin == dpvt_ps->irq_pin ) edge = EPORT_RAISING; coldfEportSetup(dpvt_ps->irq_pin, edge); /* Special HACK -- we have a stripped-down prototype board * without any digitizer/FIFO hardware. * We can still make simulation mode work if we use a single * pin for triggering and IRQ (the trigger immediately causes * an interrupt as if there was a FIFO). * However, in that case we must make the trigger pin an output * again, AFTER setting the IRQ edge mode. */ if ( dpvt_ps->trig_pin == dpvt_ps->irq_pin ) coldfEportSetup(dpvt_ps->trig_pin, EPORT_OUTPUT); devConnectInterruptVME(64 + dpvt_ps->irq_pin, isr, dpvt_ps); if ( dpvt_ps->orarm ) { arm(dpvt_ps, dpvt_ps->orarm < 0); } return 0; egress: waveform_ps->pact = 1; return -1; } #if 0 static long get_ioint_info(int cmd, struct dbCommon *record_ps, IOSCANPVT *pvt_ps) { DevWfPadDpvt_tps dpvt_ps = record_ps->dpvt; *pvt_ps = *dpvt_ps->scan_p; return 0; } #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; } static long read_waveform(void *record_p) { waveformRecord *waveform_ps = record_p; DevWfPadDpvt_tps dpvt_ps = waveform_ps->dpvt; long rval = 0; int post = 0; uint32_t then,now; int needsArm = 0; if ( devWfPadDebug & DEBUG_PROC ) epicsPrintf("Entering READ\n"); /* Record can be processed due to a PUTF or an interrupt (or both) */ if ( waveform_ps->nord && waveform_ps->nord != dpvt_ps->nusr ) { unsigned long a; /* user may have resized the array (by writing an array of the * desired size to 'VAL'. * Omit setting 'nusr' if 'nord' is zero - we could have written * zero as a result of a data acq. failure. */ dpvt_ps->nusr = waveform_ps->nord; /* must always be a multiple of eight; bump up */ a = CHANNEL_NO_ALIGN(dpvt_ps->nusr); if ( a > waveform_ps->nelm ) { a = waveform_ps->nelm; } if ( a != dpvt_ps->nusr ) { waveform_ps->nord = a; /* clear excess elements */ while ( --a >= dpvt_ps->nusr ) { ((int16_t*)waveform_ps->bptr)[a] = 0; } dpvt_ps->nusr = waveform_ps->nord; } /* It seems the waveform record doesn't post monitors if users change the size * of the array. Therefore we post here anyways (whether we aligned or not). */ post |= 1; } if ( dpvt_ps->irq ) { extern uint32_t Read_timer(); dpvt_ps->irq = 0; then = Read_timer(); dpvt_ps->readFifos( waveform_ps->bptr, 0, PADCMD_STRM_CHANNELS_ALL, dpvt_ps->nusr/PADRPLY_STRM_NCHANNELS, 0 ); now = Read_timer(); if ( devWfPadDebug & DEBUG_TIMING ) epicsPrintf("Reading FIFOs took %luus\n",now-then); if ( coldfEportFlagClr(dpvt_ps->irq_pin) ) { epicsPrintf(DEVSUPNAM": triggering too fast\n"); recGblSetSevr(waveform_ps, SCAN_ALARM, MAJOR_ALARM); waveform_ps->nord = 0; post |= 1; rval = -1; } else { /* SUCCESS */ if ( waveform_ps->nord != dpvt_ps->nusr ) post |= 1; waveform_ps->nord = dpvt_ps->nusr; } if ( waveform_ps->rarm > 1 ) { /* auto-rearm */ needsArm = 1; } else if ( waveform_ps->rarm == -10 ) { /* special, soft-triggered simulation mode; */ needsArm = 1; waveform_ps->rarm = 10; post |= 2; } else { /* disarm (leave IRQ disabled) */ waveform_ps->rarm = dpvt_ps->orarm = 0; post |= 2; } } /* handle rearm and soft trigger */ if ( dpvt_ps->orarm != waveform_ps->rarm ) { if ( devWfPadDebug & DEBUG_PROC ) epicsPrintf("RARM changed (from %i to %i)\n",dpvt_ps->orarm, waveform_ps->rarm); if ( 0 > waveform_ps->rarm ) { /* Soft Trigger */ needsArm = 2; } else { if ( waveform_ps->rarm ) { needsArm = 1; } else { disarm(dpvt_ps); } } dpvt_ps->orarm = waveform_ps->rarm; } if ( needsArm ) { arm(dpvt_ps, needsArm > 1); } if ( post & 1 ) db_post_events(waveform_ps, &waveform_ps->nord, (DBE_VALUE|DBE_LOG)); if ( post & 2 ) db_post_events(waveform_ps, &waveform_ps->rarm, (DBE_VALUE|DBE_LOG)); if ( devWfPadDebug & DEBUG_PROC ) epicsPrintf("Leaving READ\n"); return rval; } struct { long number; DEVSUPFUN report; DEVSUPFUN init; DEVSUPFUN init_record; DEVSUPFUN get_ioint_info; DEVSUPFUN read; } devWfPad = { 5, report, init, init_record, 0 /* get_ioint_info */, read_waveform }; epicsExportAddress(dset, devWfPad); /* Stuff below should eventually move to a separate module */ /* Check for a overrun condition (IRQ happens while trigger * is still high) */ int drvPadCheckOverrun(int irq_pin) { if ( coldfEportEppdrGet(irq_pin) ) { /* no acquisition in progress, either a HW trigger * happening right now or this SW trigger will be * caught. */ } else { /* Ops. IRQ line was already low. In this case, * we have to check if this is a new interrupt * that just happened or if it was lost. */ if ( coldfEportFlagGet(irq_pin) ) { /* still pending just let them detect this interrupt */ } else { return -1; } } return 0; } /* Issue a software ADC trigger * RETURNS: 0 on success, nonzero if no trigger raised * (but a ongoing acq. is used with no IRQ pending). * */ int drvPadAdcTrigger(int trig_pin, int irq_pin) { int old_mask; int rval; old_mask = coldfEportIntDisable_inl(irq_pin); trigRaise(trig_pin); /* If we need a soft trigger then things are more complicated: * We need to probe the status of the IRQ line because if we * raise the trigger while a acquisition is in progress * then we could lock out a trigger instead of generating one... */ rval = drvPadCheckOverrun(irq_pin); if ( old_mask ) coldfEportIntEnable(irq_pin); return rval; } #include #include #include #include #undef DEBUG static int start_stop_cb(PadRequest req, PadStrmCommand start, void *uarg) { int old_rarm, rval; int cmd = start ? PADCMD_GET(start->type) : PADCMD_STOP; rval = drvPadAdcStream_start_stop_cb( req, start, uarg ); /* this also handles the PADCMD_SQRY case since the query * should never return 0 */ if ( rval || PADCMD_SQRY == cmd ) return rval; if ( PADCMD_STRM != cmd ) { if ( PADCMD_STOP != cmd ) return -EINVAL; else start = 0; } if ( 0 == devPadWfGetRarm(&old_rarm) ) { /* * Skip all unnecessary cases * (start && already started or !start && already stopped) * * If we're in simulator mode RARM is 10 or -10 if a SW trigger * is just being processed. The 'abs' takes care of this last * special case. * */ if ( (start && abs(old_rarm) > 1) || (!start && old_rarm == 0) ) { /* nothing to do */ return 0; } } return devPadWfSetRarm(start ? 2 : 0); } static void padThread(void *arg) { waveformRecord *waveform_ps = arg; DevWfPadDpvt_tps dpvt_ps = waveform_ps->dpvt; PadDataKind kind; uint32_t t1,t2,diff; int isCal, status; PadStripSimValRec calsimv[2] = { { {80000, 80000, 80000, 80000 } }, { {160000,160000,160000,160000 } }, }; while (1) { epicsEventWait( dpvt_ps->sync ); t1 = Read_timer(); if ( ( diff = (t1 - drvPadIsrEndTime)) > drvPadMaxDispatchTime ) drvPadMaxDispatchTime = diff; kind = PadDataBpm; /* A CAL event ? */ if ( (isCal = gotCalt) ) { switch ( drvPadAfeGetCalm() ) { case AFE_REG_CSR_CALM_RED: kind = PadDataCalRed; break; case AFE_REG_CSR_CALM_GRN: kind = PadDataCalGrn; break; case AFE_REG_CSR_CALM_BOTH: /* TODO -- handle this case */ break; case AFE_REG_CSR_CALM_NONE: default: break; } } t1 = Read_timer(); if ( abs(waveform_ps->rarm) == 10 ) { if ( PadDataBpm == kind ) status = padStreamSim(0, 0); else { /* TODO: implement special mode where we send real * calib. data */ status = padStreamSend(padStreamSim_getdata, kind, &calsimv[kind-1]); } /* Never scan waveform in simulation mode */ status = 0; } else { status = padStreamSend(drvPadAdcStream_getdata, kind, 0); } t2 = Read_timer(); diff = t1 - drvPadIrqTime; if ( diff > drvPadMaxStreamSendTime ) drvPadMaxStreamSendTime = diff; diff = t2 - drvPadIrqTime; if ( diff > drvPadMaxProcessingTime ) drvPadMaxProcessingTime = diff; /* Toggle CAL mode; if we're not in 'soft toggle' mode * then nothing happens. */ if ( isCal ) drvPadAfeCalToggle(); /* If we can't send streaming data then * 'ordinary' record support is engaged. */ if ( status ) { dpvt_ps->irq = 1; /* signal IRQ */ if ( epicsTimeEventDeviceTime == waveform_ps->tse ) { #ifdef BASE_HAS_NO_NTP_PATCH struct ntptimeval ntv; if ( 0 == ntp_gettime(&ntv) ) { #ifdef NTP_NANO epicsTimeFromTimespec(&waveform_ps->time, &ntv.time); #else epicsTimeFromTimeval(&waveform_ps->time, &ntv.time); #endif } else #endif epicsTimeGetEvent(&waveform_ps->time, epicsTimeEventCurrentTime); } /* stream not active; process record */ callbackRequestProcessCallback(&dpvt_ps->cb_s, priorityHigh, dpvt_ps->rec_p); } else { /* Clear interrupt here so we can detect a trigger overrun */ coldfEportFlagClr(dpvt_ps->irq_pin); /* release trigger pin */ coldfEportEpdrSet(dpvt_ps->trig_pin, 0); coldfEportIntEnable(dpvt_ps->irq_pin); } } }