#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #undef __STRICT_ANSI__ #include #include #define MY_PI 3.14159265358979323846 /* align to 16-bytes (altivec) */ #define UPALIGN(x) (((x) + 15) & ~ 15) /* size of FFT (slightly larger than NSAMPLES/2; see fftw documentation) */ #define BPM_CAV_FDOM_SIZE UPALIGN((BPM_CAV_NSAMPLES/2 + 1)*sizeof(BpmFilterNumber)) #define NO_FC(fc) (0. == (fc)) #define NO_BW(bw) (0. == (bw)) #if 0 #if 0 #define NO_TD(td) (BPM_CAV_NSAMPLES*2 < (td)) #else /* They can pre-set it to .00001 if they mean to initialize it to 'zero' */ #define NO_TD(td) (0. == (td)) #endif #else /* Always use user-supplied td */ #define NO_TD(td) (0) #endif #define JOB_FLT 0 #define JOB_ENV 1 typedef struct FilterJobRec_ { unsigned type; union { struct { FilterParmsRec parms[NUM_BPM_CAVS]; int channel; } flt; struct { WavBuf wb; dbCommon *prec; void **pres; int chnl; } env; } args; } FilterJobRec, *FilterJob; typedef void *BpmCavFFTPlan; epicsMutexId bpmCavFilterMutex; static epicsMessageQueueId bpmCavFilterQ; BpmCavFilterRec bpmCavFilterBank[MAX_CAV_BPM][NUM_BPM_CAVS] = {{{{0}}}}; static BpmFilterNumber *coeffFreeList = 0; static int wbFreeFFTW(WavBuf wb); static BpmFilterNumber * coeffAlloc() { int key; BpmFilterNumber *rval; key = epicsInterruptLock(); if ( (rval = coeffFreeList) ) { /* copy 'next' pointer in alias-safe (hopefully) way */ memcpy(&coeffFreeList, coeffFreeList, sizeof(coeffFreeList)); } epicsInterruptUnlock(key); return rval; } void bpmCavCoeffsFree(BpmFilterNumber *v) { int key; if ( v ) { key = epicsInterruptLock(); memcpy(v, &coeffFreeList, sizeof(coeffFreeList)); coeffFreeList = v; epicsInterruptUnlock(key); } } int bpmCavCoeffsAlloc(FilterCoeffs c) { c->nsamples = BPM_CAV_NSAMPLES; if ( ( c->Hre = coeffAlloc() ) ) { if ( !(c->Him = coeffAlloc()) ) { bpmCavCoeffsFree(c->Hre); c->Hre = 0; } else { return 0; } } else { c->Him = 0; } c->nsamples = 0; epicsPrintf("bpmCavCoeffsAlloc: not enough buffers!\n"); return -1; } static int coeffsInit(int n) { BpmFilterNumber *v; while ( n-- > 0 ) { if ( ! (v = fftwf_malloc(BPM_CAV_FDOM_SIZE)) ) { epicsPrintf("No memory for filter buffers\n"); return -1; } bpmCavCoeffsFree(v); } return 0; } static int checkRange(unsigned chnl, unsigned idx) { return chnl >= MAX_CAV_BPM || idx >= NUM_BPM_CAVS; } static int bpmCavFilterInstall(int chnl, int idx, BpmCavFilter f) { BpmFilterNumber *Hre, *Him; BpmCavFilter dst; if ( checkRange(chnl,idx) ) return -1; dst = &bpmCavFilterBank[chnl][idx]; bpmCavFilterBankLock(); { Hre = dst->coeffs.Hre; Him = dst->coeffs.Him; /* replace */ *dst = *f; } bpmCavFilterBankUnlock(); bpmCavCoeffsFree(Hre); bpmCavCoeffsFree(Him); return 0; } static int filterJobPost(FilterJob j) { return epicsMessageQueueSend(bpmCavFilterQ, j, sizeof(*j)); } static WavBuf respBufFreeList = 0; static WavBuf bpmCavRespAlloc(unsigned refcnt) { int key; WavBuf rval; if ( !refcnt ) return 0; key = epicsInterruptLock(); if ( (rval = respBufFreeList) ) { respBufFreeList = rval->usrData; } epicsInterruptUnlock(key); if ( rval ) rval->usrData = (void*)(uintptr_t)refcnt; return rval; } static int respFree(WavBuf wb) { int key; key = epicsInterruptLock(); /* decrement refcnt */ wb->usrData = (void*)((uintptr_t)wb->usrData - 1); if ( 0 == wb->usrData ) { wb->usrData = respBufFreeList; respBufFreeList = wb; } epicsInterruptUnlock(key); /* DONT return the header to the general-purpose * free-list; we maintain our own one and * leave buffer space attached! */ return -1; } static int respInit(int n) { WavBuf wb; int stride; int type = WavBufCplx; stride = BPM_CAV_FDOM_SIZE/sizeof(BpmFilterNumber); wavBufInit(); while ( n-- ) { if ( !(wb=wavBufAlloc()) ) { epicsPrintf("respInit(): not enough wavBuf headers!\n"); return -1; } wb->segs.nsegs = 2; if ( ! (wb->d_re = fftwf_malloc(NUM_BPM_CAVS*BPM_CAV_FDOM_SIZE)) || ! (wb->d_im = fftwf_malloc(NUM_BPM_CAVS*BPM_CAV_FDOM_SIZE)) ) { wbFreeFFTW( wb ); wavBufFreeHdr( wb ); epicsPrintf("respInit(): not enough memory\n"); return -1; } wb->type = type; wb->flags = 0; /* row-major */ wb->stride = stride; wb->m = wb->segs.m = NUM_BPM_CAVS; wb->n = wb->segs.n = BPM_CAV_NSAMPLES/2; wb->free = respFree; /* initial refcnt == 1 so that respFree releases this wb to the free-list */ wb->usrData = (void*)(uintptr_t)1; /* put on free list */ respFree(wb); } return 0; } static __inline__ size_t ibufSzCalc(fftwf_iodim *dim, fftwf_iodim *howm) { size_t m; /* exact space requirements */ m = ( dim->n - 1 ) * dim->is + 1; m += ( howm->n - 1 ) * howm->is; m *= sizeof(float); /* align up for vector access */ return UPALIGN(m); } static __inline__ size_t obufSzCalc(fftwf_iodim *dim, fftwf_iodim *howm) { size_t m; /* exact space requirements */ m = ( dim->n - 1 ) * dim->os + 1; m += ( howm->n - 1 ) * howm->os; m *= sizeof(float); /* align up for vector access */ return UPALIGN(m); } static int wbFreeFFTW(WavBuf wb) { int i; for ( i=0; isegs.nsegs; i++ ) { if ( wb->segs.data[i] ) fftwf_free(wb->segs.data[i]); } return 0; } static WavBuf tdRespAlloc(fftwf_iodim *dims, fftwf_iodim *howm, int cplx) { WavBuf tdResp; if ( (tdResp = wavBufAlloc()) ) { tdResp->type = cplx ? WavBufCplx : WavBufFloat; tdResp->m = tdResp->segs.m = howm->n; tdResp->n = tdResp->segs.n = dims->n; tdResp->d_re = fftwf_malloc(obufSzCalc(dims,howm)); tdResp->segs.nsegs = 1; if ( cplx ) { tdResp->d_im = fftwf_malloc(obufSzCalc(dims,howm)); tdResp->segs.nsegs++; } tdResp->free = wbFreeFFTW; if ( !tdResp->d_re || (cplx && !tdResp->d_im) ) { wavBufFree(tdResp); tdResp = 0; } } return tdResp; } static fftwf_iodim r2hc_dims = {0}; static fftwf_iodim r2hc_howm = {0}; BpmCavFFTBuf bpmCavFFTBufAlloc() { if ( 0 == r2hc_dims.n ) { /* not initialized yet */ return 0; } return fftwf_malloc(ibufSzCalc(&r2hc_dims, &r2hc_howm)); } void bpmCavFFTBufFree(BpmCavFFTBuf buf) { fftwf_free(buf); } /* According to docs a plan is thread-safe if executed by * multiple threads in parallel calling fftw_execute_split_dft_r2c() */ static BpmCavFFTPlan plan_r2hc = 0; static BpmCavFFTPlan bpmCavFFTPlan() { WavBuf wb; BpmCavFFTBuf rb = 0; if ( plan_r2hc ) return plan_r2hc; if ( ! (wb = bpmCavRespAlloc(1)) ) { epicsPrintf("bpmCavFFTPlan(): unable to allocate response\n"); return 0; } /* initialize dimensions/howmanys before allocating * work-buffer; allocator needs to know the dimensions... */ r2hc_dims.n = 2*wb->n; r2hc_dims.is = NUM_DIGI_CHNLS; r2hc_dims.os = 1; r2hc_howm.n = wb->m; r2hc_howm.is = 1; r2hc_howm.os = wb->stride; if ( ! (rb = bpmCavFFTBufAlloc()) ) { epicsPrintf("bpmCavFFTPlan(): unable to allocate workspace\n"); } else { plan_r2hc = fftwf_plan_guru_split_dft_r2c( 1, &r2hc_dims, 1, &r2hc_howm, rb, wb->d_re, wb->d_im, FFTW_MEASURE | FFTW_PRESERVE_INPUT); if ( !plan_r2hc ) { errlogPrintf("bpmCavFFTPlan(): Creation of FFTW plan r2hc failed -- FATAL ERROR\n"); errlogFlush(); abort(); } } bpmCavFFTBufFree(rb); wavBufFree(wb); return plan_r2hc; } WavBuf bpmCavFFT(BpmCavFFTBuf tdSignal, unsigned refcnt) { WavBuf rval = bpmCavRespAlloc(refcnt); if ( rval ) { fftwf_execute_split_dft_r2c(plan_r2hc, tdSignal, rval->d_re, rval->d_im); } return rval; } static fftwf_plan generatePlan(fftwf_iodim *dim, fftwf_iodim *howm) { fftwf_plan p = 0; WavBuf wb = bpmCavRespAlloc(1); float *rb = 0; dim->n = 2*wb->n; dim->is = 1; dim->os = 1; howm->n = wb->m; howm->is = wb->stride; howm->os = dim->n; if ( !(rb = fftwf_malloc(obufSzCalc(dim,howm))) ) { epicsPrintf("generatePlan: unable to allocate workspace\n"); abort(); } p = fftwf_plan_guru_split_dft_c2r( 1, dim, 1, howm, wb->d_re, wb->d_im, rb, FFTW_MEASURE | FFTW_PRESERVE_INPUT); if ( !p ) { epicsPrintf("Creation of FFTW plan hc2r failed -- FATAL ERROR\n"); abort(); } fftwf_free(rb); wavBufFree(wb); return p; } #define TRIGSTEP(c,s,a,b,t) \ do { \ t = a*c+b*s; \ s-= a*s-b*c; \ c-= t; \ } while (0) void bpmCavGenerateFilter(BpmCavFilter f) { int i,l,u; double phi2,a,b,c,s,t; phi2 = MY_PI/(double)f->coeffs.nsamples*f->parms.td; b = sin(phi2*2.0); a = sin(phi2); a *= 2.0*a; u = (int)rintf( (f->parms.fc + f->parms.bw/2.0) * f->coeffs.nsamples ); l = (int)rintf( (f->parms.fc - f->parms.bw/2.0) * f->coeffs.nsamples ); if ( u >= f->coeffs.nsamples/2 ) u = f->coeffs.nsamples/2 - 1; if ( l < 0 ) l = 0; /* ideal band-pass filter */ i = 0; for ( ; icoeffs.Hre[i] = 0.; f->coeffs.Him[i] = 0.; } c = cos(i*2.0*phi2); s = sin(i*2.0*phi2); for ( ; icoeffs.Hre[i] = c; f->coeffs.Him[i] = -s; TRIGSTEP(c,s,a,b,t); } f->coeffs.Hre[i] = c; f->coeffs.Him[i] = -s; i++; for (; icoeffs.nsamples/2; i++ ) { f->coeffs.Hre[i] = 0.; f->coeffs.Him[i] = 0.; } /* Clear extra element */ f->coeffs.Hre[i] = 0.; f->coeffs.Him[i] = 0.; } /* clear element at fc/2 (weird fftw storage layout) */ static __inline__ void clearFc2Elements(WavBuf b) { int i,idx; BpmFilterNumber zero=0.; for ( i=0, idx=b->n; im; i++, idx+=b->stride ) { memcpy( ((BpmFilterNumber*)b->d_re)+idx, &zero, sizeof(zero) ); } } static void filterTask(void *arg) { FilterJobRec job; BpmCavFilterRec flt; int i,j,idx; fftwf_plan plan_hc2r; WavBuf resp; WavBuf tdResp; fftwf_iodim dims, howm; #ifdef __PPC__ vec_task_enable(); altivec_nonC9xmode(); #endif plan_hc2r = generatePlan(&dims, &howm); while ( 1 ) { epicsMessageQueueReceive(bpmCavFilterQ, &job, sizeof(job)); switch ( job.type ) { default: epicsPrintf("cavFilterTask: invalid job %u; discarding\n", job.type); continue; case JOB_FLT: /* Compute new filters in freq. domain given the * parameters fc, bw, td. */ { int chnl = job.args.flt.channel; FilterParms parms = job.args.flt.parms; if ( checkRange(chnl, 0) ) { epicsPrintf("filterTask: received request for illegal channel %i -- dropped.\n", chnl); continue; } if ( !(resp=bpmCavRespAlloc(1)) ) continue; for ( i=idx=0; istride ) { flt.parms = parms[i]; flt.coeffs.nsamples = 0; if ( NO_FC( parms[i].fc ) || NO_BW( parms[i].bw ) || NO_TD( parms[i].td ) || bpmCavCoeffsAlloc(&flt.coeffs) ) { /* zero out */ flt.coeffs.Hre = 0; flt.coeffs.Him = 0; memset( &((BpmFilterNumber*)resp->d_re)[idx], 0, resp->n*sizeof(BpmFilterNumber)); memset( &((BpmFilterNumber*)resp->d_im)[idx], 0, resp->n*sizeof(BpmFilterNumber)); } else { bpmCavGenerateFilter(&flt); memcpy( &((BpmFilterNumber*)resp->d_re)[idx], flt.coeffs.Hre, resp->n*sizeof(float)); memcpy( &((BpmFilterNumber*)resp->d_im)[idx], flt.coeffs.Him, resp->n*sizeof(float)); } bpmCavFilterInstall(chnl, i, &flt); } tdResp = tdRespAlloc(&dims, &howm, 0); if ( tdResp ) { /* clear element at fc/2 (weird fftw storage layout) */ clearFc2Elements(resp); fftwf_execute_split_dft_c2r(plan_hc2r, resp->d_re, resp->d_im, tdResp->d_re); wavBufPost(chnl, WB_KIND_h, tdResp); } wavBufPost(chnl, WB_KIND_H, resp); } break; /* Compute complex envelope of filtered signals; this * is not necessarily the most efficient algorithm but * we use existing fft plans and buffer sizes etc. * Also, the peak detector was already run by the * low-level (fast) data-acq. task but we have no * easy way to communicate the result from there to * here so we just do it again... */ case JOB_ENV: { double dP, dT, rms, pr, pi; int nFvecs; float *pHre, *pHim, *pHdr, *pHdi; WavBuf oresp; BpmCavFilter filt; int haveAllFilters; oresp = job.args.env.wb; resp = 0; tdResp = 0; nFvecs = oresp->n / (VECTSZ/sizeof(float)); filt = bpmCavFilterBank[job.args.env.chnl]; /* IMPORTANT NOTE: we don't lock the filter coefficients * while working with them because we don't * want the low-level, high-priority task * to wait for the lock! * * We assume that his task context is the * only one to install new coefficients * so while we're executing they can't * change. * * The only other task who is allowed * to install coefficients is the * high-pri task which may install * coefficients if they are NULL. * * Clearing the coefficients is only * done from this task context (JOB_FLT * when the user sets a fc/bw parameter * to zero). Hence it is OK to lock, * check if we have all coefficients * and unlock. * -> If any coefficients are missing * we don't do anything. * -> If we have coefficients then they * can't 'go away' while we are using * them (because only THIS task could * remove them). */ bpmCavFilterBankLock(); haveAllFilters = filt[CAV_REF].coeffs.nsamples && filt[CAV_U ].coeffs.nsamples && filt[CAV_V ].coeffs.nsamples; bpmCavFilterBankUnlock(); if ( haveAllFilters ) { pHre = oresp->d_re; pHim = oresp->d_im; vec_tadj(&dP, &dT, &rms, (vFloat*)filt[CAV_REF].coeffs.Hre, (vFloat*)filt[CAV_REF].coeffs.Him, (vFloat*)(pHre+CAV_REF*oresp->stride), (vFloat*)(pHim+CAV_REF*oresp->stride), nFvecs); /* Allocate a new 'work' response buffer for computation... */ if ( (resp = bpmCavRespAlloc(1)) ) { pHdr = resp->d_re; pHdi = resp->d_im; /* Scale by the number of samples; FFTW does not normalize, * so FFTINV(FFT) gains by NSAMPLES. Do that here * to avoid an extra multiplication step. */ pr = cos(dP)/(float)dims.n; pi = sin(dP)/(float)dims.n; /* * Compute filtered, time+phase-shifted signal in freq-domain */ for ( i=0; im; i++) { vec_filtv( (vFloat*)&pHdr[i*resp->stride], (vFloat*)&pHdi[i*resp->stride], pr, pi, dT, (vFloat*)filt[i].coeffs.Hre, (vFloat*)filt[i].coeffs.Him, (vFloat*)(pHre+i*oresp->stride), (vFloat*)(pHim+i*oresp->stride), nFvecs); } /* clear element at fc/2 (weird fftw storage layout) */ clearFc2Elements(resp); tdResp = tdRespAlloc(&dims, &howm, 1); if ( tdResp ) { int stride = resp->stride ? resp->stride : resp->n; fftwf_execute_split_dft_c2r(plan_hc2r, resp->d_re, resp->d_im, tdResp->d_re); for ( i = 0; i < resp->m*stride; i+=stride ) { for ( j = 0; j < resp->n; j++ ) ((float*)resp->d_re)[i+j] = -((float*)resp->d_re)[i+j]; } fftwf_execute_split_dft_c2r(plan_hc2r, resp->d_im, resp->d_re, tdResp->d_im); } } } /* free temp buffer */ wavBufFree(resp); /* release original buffer */ wavBufFree(oresp); /* post new buffer */ *job.args.env.pres = tdResp; /* schedule record processing */ if ( job.args.env.prec ) { dbScanLock(job.args.env.prec); ((struct rset *)job.args.env.prec->rset)->process(job.args.env.prec); dbScanUnlock(job.args.env.prec); } } break; } } } static WavBuf envAsyncProcCb(dbCommon *prec, void **ppvt, unsigned slot, unsigned kind, WavBuf wb) { if ( wb) { /* Phase 1 */ FilterJobRec job; job.type = JOB_ENV; job.args.env.wb = wb; job.args.env.prec = prec; job.args.env.pres = ppvt; job.args.env.chnl = slot; filterJobPost(&job); wb = 0; } else { /* Phase 2 */ /* relay result */ wb = *ppvt; *ppvt = 0; } return wb; } void bpmCavFilterInit() { bpmCavFilterQ = epicsMessageQueueCreate(MAX_CAV_BPM*2, sizeof(FilterJobRec)); bpmCavFilterMutex = epicsMutexCreate(); respInit( MAX_CAV_BPM*2*2*2 ); coeffsInit( (MAX_CAV_BPM*NUM_BPM_CAVS+4)*2 ); wavBufAsyncCbRegister(WB_KIND_E, envAsyncProcCb); bpmCavFFTPlan(); epicsThreadCreate( "bpmCavFilterTask", epicsThreadPriorityMedium, 4*epicsThreadGetStackSize(epicsThreadStackBig), filterTask, 0); } #define CHN(psub) ((psub)->a) #define FC0(psub) ((psub)->b) #define BW0(psub) ((psub)->c) #define TD0(psub) ((psub)->d) #define LFC0(psub) ((psub)->lb) #define LBW0(psub) ((psub)->lc) #define LTD0(psub) ((psub)->ld) #define FC1(psub) ((psub)->e) #define BW1(psub) ((psub)->f) #define TD1(psub) ((psub)->g) #define LFC1(psub) ((psub)->le) #define LBW1(psub) ((psub)->lf) #define LTD1(psub) ((psub)->lg) #define FC2(psub) ((psub)->h) #define BW2(psub) ((psub)->i) #define TD2(psub) ((psub)->j) #define LFC2(psub) ((psub)->lh) #define LBW2(psub) ((psub)->li) #define LTD2(psub) ((psub)->lj) #define FRQ(psub) ((psub)->k) #define FRQ_DEFLT (120E6) #define UPDATE_SUB(psub, chnl, idx, f) \ do { \ if ( NO_FC( FC##idx(psub) ) && NO_FC( LFC##idx(psub) ) ) { \ FC##idx(psub) = bpmCavFilterBank[chnl][idx].parms.fc*(f); \ db_post_events(psub, &FC##idx(psub), (DBE_VALUE|DBE_LOG));\ } \ if ( NO_BW( BW##idx(psub) ) && NO_BW( LBW##idx(psub) ) ) { \ BW##idx(psub) = bpmCavFilterBank[chnl][idx].parms.bw*(f); \ db_post_events(psub, &BW##idx(psub), (DBE_VALUE|DBE_LOG));\ } \ if ( NO_TD( TD##idx(psub)*f ) && NO_TD( LTD##idx(psub)*f ) ) {\ TD##idx(psub) = bpmCavFilterBank[chnl][idx].parms.td/(f); \ db_post_events(psub, &TD##idx(psub), (DBE_VALUE|DBE_LOG));\ } \ } while (0) #define UPDATE_JOB(psub, job, idx, f) \ do { \ (job).args.flt.parms[idx].fc = FC##idx(psub)/(f); \ (job).args.flt.parms[idx].bw = BW##idx(psub)/(f); \ (job).args.flt.parms[idx].td = TD##idx(psub)*(f); \ } while (0) static subRecord *subRecs[MAX_CAV_BPM] = {0}; void bpmCavLLFilterPostJob(int chnl) { if ( checkRange(chnl,0) || !subRecs[chnl] ) return; scanOnce((dbCommon*)subRecs[chnl]); } static long bpmCavFilterSubInit(subRecord *psub) { int chnl = psub->a; if ( checkRange(chnl,0) ) { epicsPrintf("filterSubr(%s) -- channel # (field A) out of range %i\n", psub->name, chnl); return -1; } if ( 0. == FRQ(psub) ) { epicsPrintf("filterSubr(%s) -- sampling freq. not initialized! (using %gHz)\n", psub->name, FRQ_DEFLT); } subRecs[chnl] = psub; return 0; } epicsRegisterFunction(bpmCavFilterSubInit); static long bpmCavFilterSubProc(subRecord *psub) { int chnl = CHN(psub); double f = FRQ(psub); FilterJobRec job; job.type = JOB_FLT; if ( checkRange(chnl,0) ) { epicsPrintf("filterSubr(%s) -- channel # (field A) out of range %i\n", psub->name, chnl); return -1; } UPDATE_SUB(psub,chnl,0,f); UPDATE_SUB(psub,chnl,1,f); UPDATE_SUB(psub,chnl,2,f); UPDATE_JOB(psub,job, 0,f); UPDATE_JOB(psub,job, 1,f); UPDATE_JOB(psub,job, 2,f); job.args.flt.channel = chnl; filterJobPost(&job); return 0; } epicsRegisterFunction(bpmCavFilterSubProc);