2 //****************************************************************************
3 //* This file is property of and copyright by the ALICE HLT Project *
4 //* ALICE Experiment at CERN, All rights reserved. *
6 //* Primary Authors: Sergey Gorbunov, Torsten Alt *
7 //* Developers: Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de> *
8 //* Torsten Alt <talt@cern.ch> *
9 //* for The ALICE HLT Project. *
11 //* Permission to use, copy, modify and distribute this software and its *
12 //* documentation strictly for non-commercial purposes is hereby granted *
13 //* without fee, provided that the above copyright notice appears in all *
14 //* copies and that both the copyright notice and this permission notice *
15 //* appear in the supporting documentation. The authors make no claims *
16 //* about the suitability of this software for any purpose. It is *
17 //* provided "as is" without express or implied warranty. *
18 //****************************************************************************
20 // @file AliHLTTPCHWCFSupport.cxx
21 // @author Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de>
22 // @author Torsten Alt <talt@cern.ch>
23 // @brief Input interfaces for FPGA ClusterFinder Emulator for TPC
24 // @brief ( see AliHLTTPCHWCFEmulator class )
28 #include "AliHLTTPCHWCFSupport.h"
29 #include "AliHLTDataTypes.h"
30 #include "AliHLTTPCMapping.h"
31 #include "AliHLTTPCDigitReaderUnpacked.h"
32 #include "AliHLTTPCTransform.h"
33 #include "AliHLTTPCDefinitions.h"
34 #include "AliRawDataHeader.h"
35 #include "AliHLTTPCHWCFEmulator.h"
36 #include "AliTPCcalibDB.h"
37 #include "AliTPCCalPad.h"
38 #include "AliTPCCalROC.h"
51 AliHLTTPCHWCFSupport::AliHLTTPCHWCFSupport()
57 // see header file for class documentation
58 for( int i=0; i<fgkNSlices; i++ )
59 for( int j=0; j<fgkNPatches; j++ ) fMapping[i][j] = 0;
63 AliHLTTPCHWCFSupport::~AliHLTTPCHWCFSupport()
65 // see header file for class documentation
66 for( int i=0; i<fgkNSlices; i++ )
67 for( int j=0; j<fgkNPatches; j++ ) delete[] fMapping[i][j];
68 delete[] fEventMemory;
69 delete[] fEventMCMemory;
72 AliHLTTPCHWCFSupport::AliHLTTPCHWCFSupport(const AliHLTTPCHWCFSupport&)
81 AliHLTTPCHWCFSupport& AliHLTTPCHWCFSupport::operator=(const AliHLTTPCHWCFSupport&){
87 const AliHLTUInt32_t *AliHLTTPCHWCFSupport::GetMapping( int slice, int patch )
89 // see header file for class documentation
90 if( slice<0 || slice>=fgkNSlices ){
91 HLTFatal("Wrong slice number %d, no mapping is provided.", slice);
94 if( patch<0 || patch>= fgkNPatches ){
95 HLTFatal("Wrong patch number %d, no mapping is provided.", patch);
98 if( !fMapping[slice][patch] ) fMapping[slice][patch] = ReadMapping(slice,patch);
99 return fMapping[slice][patch];
103 AliHLTUInt32_t *AliHLTTPCHWCFSupport::ReadMapping( int slice, int patch, const char *mappingFileName ) const
105 // Create mapping array for one patch
106 // If no mapping file provided, reads from default file
107 // Output: mapping [] array of type AliHLTUInt32_t, where :
109 // mapping[0] == N hardware adresses in the array (mapping size is maping[0] + 1 )
110 // mapping[hwAddress] == configWord
112 // configWord consist of:
114 // bits 0-7: pad number
115 // bits 8-13: row number
116 // bit 14 : flag for border pad
117 // bit 15 : is the pad active
118 // bits 16->28 : gain calibration as 13 bit fixed point,
119 // with 1 bit position before decimal point
121 const AliHLTUInt32_t kBorderFlag = (1 << 14);
122 const AliHLTUInt32_t kActiveFlag = (1 << 15);
124 if( slice<0 || slice>=fgkNSlices ){
125 HLTFatal("Wrong slice number %d, no mapping is provided.", slice);
129 if( patch<0 || patch>5 ){
130 HLTFatal("Wrong patch number %d, no mapping is provided.", patch);
134 // AliHLTTPCTransform::GetFirstRow returns first row in scheme A.
135 // We have to transform to scheme B by AliHLTTPCTransform::Slice2Sector.
137 UInt_t offsetSchemeB=0;
141 AliHLTTPCTransform::Slice2Sector(slice, AliHLTTPCTransform::GetFirstRow(patch),
143 offsetSchemeB = (UInt_t) tmp;
147 AliTPCcalibDB *calib = AliTPCcalibDB::Instance();
148 AliTPCCalPad * gainTPC = 0;
149 AliTPCCalROC * gainROC = 0;
150 if( calib ) gainTPC = calib->GetPadGainFactor();
151 if( gainTPC ) gainROC = gainTPC->GetCalROC(sector); // pad gains per given sector
153 HLTWarning("No TPC gain calibration found");
158 if( mappingFileName ){
159 filename = mappingFileName;
161 const char* basePath=getenv("ALICE_ROOT");
162 if (basePath) filename.Form("%s/TPC/mapping/Patch%d.data", basePath,patch);
166 inFile.open(filename.Data());
168 HLTFatal("Unable to open mapping file: %s This means no mapping is provided.", filename.Data());
173 AliHLTUInt32_t *mapping = 0;
174 AliHLTUInt32_t *rowBranchPadHw = 0;
181 if( !(inFile >> nHWAdd ) || !(inFile >> maxHWAdd) ){
182 HLTError("Mapping file for patch %d corrupted &s", patch,filename.Data());
186 if( maxHWAdd > 0xFFF ){
187 HLTError("Max hardware address exceeded for patch %d, max number is %d, number from mapping file is %d.",patch, 0xFFF, maxHWAdd+1);
191 if(nHWAdd > maxHWAdd ){
192 HLTError("Too large number of hardware addresses for patch %d: max number is %d, number from mapping file is %d.",patch, maxHWAdd, nHWAdd );
196 mapping = new AliHLTUInt32_t[maxHWAdd+2];
197 rowBranchPadHw = new AliHLTUInt32_t[nHWAdd];
198 if( !mapping || !rowBranchPadHw ){
199 HLTError("Can not allocate &d bytes of memory", (maxHWAdd+1+nHWAdd)*sizeof(AliHLTUInt32_t));
203 for( unsigned int i=0; i<maxHWAdd+2; i++ ) mapping[i] = 0;
204 for( unsigned int i=0; i<nHWAdd; i++ ) rowBranchPadHw[i] = 0;
205 mapping[0] = maxHWAdd+1;
212 if( !(inFile>>hwAdd) || !(inFile>>row) || !(inFile>>pad) ) break;
216 if ( nRead >= nHWAdd ){
217 HLTError("Too many hardware addresses: %d, expected %d, mapping file %s corrupted?", nRead+1, nHWAdd, filename.Data());
220 if (hwAdd>maxHWAdd) {
221 HLTError("hardware address exceeds max hwAddress %d, mapping file %s corrupted?", maxHWAdd, filename.Data());
225 if( row < offsetSchemeB ){
226 HLTError("row number %d below minimum %d for patch %d, mapping file %s corrupted?", row, offsetSchemeB, patch, filename.Data());
230 row -= offsetSchemeB;
233 HLTError("row number %d withing patch exceed the maximum %d for patch %d, mapping file %s corrupted?", row, 0x3F, patch, filename.Data());
238 HLTError("pad number %d exceed the maximum %d for patch %d, mapping file %s corrupted?", pad, 0xFF, patch, filename.Data());
242 bool active = true; // Currently all channels are always active
245 AliHLTFloat64_t gain = 1.;
247 gain = gainROC->GetValue(offsetSchemeB+row,pad);
248 if( gain>1.e-4 ) gain = 1./gain;
252 AliHLTUInt32_t gainCalib = TMath::Nint(gain);
253 if( gainCalib > 0x1FFF ) gainCalib = 0x1FFF;
255 AliHLTUInt32_t configWord = ( (row & 0x3F) << 8 ) | (pad & 0xFF);
256 if ( active ) configWord |= kActiveFlag;
257 configWord |= (gainCalib & 0x1FFF) << 16;
259 mapping[1+hwAdd] = configWord;
261 AliHLTUInt32_t branch = (hwAdd >> 11) & 0x1;
262 rowBranchPadHw[nRead] = (row<<25) | (branch<<24) | (pad<<16) | hwAdd;
270 if ( nRead!= nHWAdd ){
271 HLTError("Too less hardware addresses: %d, expected %d, mapping file %s corrupted?", nRead, nHWAdd, filename.Data());
276 // mark pads at borders of A/B branches
278 std::sort(rowBranchPadHw, rowBranchPadHw + nHWAdd);
279 int rowBranchLast = -1;
280 for( unsigned int i=0; i<nHWAdd; i++ ){
281 int rowBranch = rowBranchPadHw[i]>>24;
282 if( rowBranch != rowBranchLast ){
283 mapping[1+(rowBranchPadHw[i] & 0xFFF)] |= kBorderFlag;
284 rowBranchLast = rowBranch;
285 if( i>0 ) mapping[1+(rowBranchPadHw[i-1] & 0xFFF)] |= kBorderFlag;
288 mapping[1+(rowBranchPadHw[nRead-1] & 0xFFF)] |= kBorderFlag;
294 delete[] rowBranchPadHw;
304 int AliHLTTPCHWCFSupport::CreateRawEvent
305 ( const AliHLTComponentBlockData* block,
306 const AliHLTUInt32_t *&rawEvent, AliHLTUInt32_t &rawEventSize32,
307 const AliHLTTPCClusterMCLabel *&mcLabels, AliHLTUInt32_t &nMCLabels
310 // the method creates TPC raw data out of the input block
311 // MC labels are provided if possible
314 delete[] fEventMemory;
315 delete[] fEventMCMemory;
322 if( block->fPtr==NULL ){
323 HLTWarning("NULL pointer to the data block");
327 Int_t slice = AliHLTTPCDefinitions::GetMinSliceNr( *block );
328 Int_t patch = AliHLTTPCDefinitions::GetMinPatchNr( *block );
329 AliHLTTPCMapping mapping(patch);
331 const char *str=Form("slice %d patch %d:", slice, patch);
333 if ( block->fDataType == (kAliHLTDataTypeDDLRaw | kAliHLTDataOriginTPC) )
335 // already raw format -> only set the pointers and estimate the size
337 // read CDH header, estimate size of the data
339 AliHLTUInt64_t headerSize = sizeof(AliRawDataHeader);
341 AliRawDataHeader *cdhHeader = reinterpret_cast<AliRawDataHeader*>(block->fPtr);
343 AliHLTUInt64_t blockSize = block->fSize; // size of the raw data in bytes
345 if( cdhHeader->fSize!=0xFFFFFFFF ){ // use size information from the header
346 blockSize = cdhHeader->fSize;
347 if( blockSize > block->fSize ){
348 HLTWarning("%s Could not find a valid DDL header!",str);
353 if( blockSize < headerSize ){
354 HLTWarning("%s Buffer size is smaller than CDH header size", str);
358 rawEvent = reinterpret_cast<AliHLTUInt32_t*> (reinterpret_cast<UChar_t*>(block->fPtr)+headerSize);
359 rawEventSize32 = ( blockSize - headerSize )/sizeof(AliHLTUInt32_t);
362 else if ( block->fDataType == AliHLTTPCDefinitions::fgkUnpackedRawDataType )
365 AliHLTTPCDigitReaderUnpacked digitReader;
366 digitReader.SetUnsorted(kTRUE);
368 if( digitReader.InitBlock(block->fPtr,block->fSize,patch,slice)<0 ) {
369 HLTWarning("failed setting up digit reader (InitBlock)");
373 int nDigitsTotal = 0;
374 int nBunchesTotal = 0;
376 while( digitReader.NextChannel() ){
377 while(digitReader.NextBunch()){
379 nDigitsTotal+=digitReader.GetBunchSize();
385 if( digitReader.InitBlock(block->fPtr,block->fSize,patch,slice)<0) {
386 HLTWarning("failed setting up digit reader (InitBlock)");
390 Int_t nPadsTotal = 0;
391 Int_t firstRow = AliHLTTPCTransform::GetFirstRow(patch);
392 Int_t nRows = AliHLTTPCTransform::GetNRows(patch);
394 for( int i=0; i<nRows; i++ ){
395 nPadsTotal += AliHLTTPCTransform::GetNPads(firstRow+i);
398 AliHLTUInt32_t totalSize32 = (nDigitsTotal + nBunchesTotal*2)/3+2*nPadsTotal + 10;
399 AliHLTUInt32_t totalNMC = nDigitsTotal + 10;
401 fEventMemory = new AliHLTUInt32_t[totalSize32];
403 HLTWarning("Not enougth memory: can not allocate %d bytes",totalSize32*8);
407 fEventMCMemory = new AliHLTTPCClusterMCLabel[totalNMC];
408 if( !fEventMCMemory ){
409 HLTWarning("Not enougth memory: can not allocate %d bytes",totalNMC*sizeof(AliHLTTPCClusterMCLabel));
410 delete[] fEventMemory;
414 AliHLTUInt32_t nWords32 = 0;
415 AliHLTUInt32_t mcIndex = 0;
418 AliHLTTPCDigitData tmpDigit;
419 tmpDigit.fTrackID[0] = -1;
420 tmpDigit.fTrackID[1] = -1;
421 tmpDigit.fTrackID[2] = -1;
423 while( !err && digitReader.NextChannel() ){
425 Int_t row=digitReader.GetRow();
426 Int_t pad=digitReader.GetPad();
428 AliHLTUInt32_t hwAddr = mapping.GetHwAddress(row, pad);
432 if( nWords32 >= totalSize32){ err = 1; break; }
434 AliHLTUInt32_t *header = fEventMemory + nWords32;
438 int prevTime = 10000000;
440 while(digitReader.NextBunch()){
442 if( hwAddr > 0xFFF ) continue;
444 Int_t nSignals = digitReader.GetBunchSize();
446 HLTWarning("Empty bunch received");
450 Int_t time = digitReader.GetTime() + nSignals-1;
452 if( time-nSignals+1<0 || time>=AliHLTTPCTransform::GetNTimeBins() ){
453 HLTWarning("Wrong time bins received: %d-%d for row %d pad %d", time-nSignals+1, time, row, pad);
457 if( time >= prevTime ){
458 HLTWarning("Unexpected order of TPC bunches in row %d, pad %d", row, pad);
462 prevTime = time-nSignals+1;
464 if( nWords32+( 2+nSignals)/3+1 >= totalSize32 ){ err = 1; break; }
465 if( mcIndex + nSignals >= totalNMC ){ err = 1; break; }
467 if( nWords10 + 2 + nSignals > 0x3FF ){
468 HLTWarning("Too much data in row %d, pad %d", row, pad);
472 nWords10 += 2 + nSignals;
474 Add10Word( nWords32, seek10, nSignals + 2 );
475 Add10Word( nWords32, seek10, time );
477 const UInt_t *bunchData = digitReader.GetSignals();
478 const AliHLTTPCDigitData *mcDigits = digitReader.GetBunchDigits();
480 HLTWarning("No MC labels found for a bunch of digits");
483 for(Int_t is=nSignals-1; is>=0; is--){
484 Add10Word( nWords32, seek10, bunchData[is] );
485 const AliHLTTPCDigitData &digit = mcDigits ?mcDigits[is] :tmpDigit;
487 for( int i=0; i<3; i++ ) if( digit.fTrackID[i] >=0 ) nmc++;
488 for( int i=0; i<3; i++ ){
489 fEventMCMemory[mcIndex].fClusterID[i].fMCID = digit.fTrackID[i];
490 fEventMCMemory[mcIndex].fClusterID[i].fWeight = 0;
491 if( digit.fTrackID[i] >=0 ){
492 fEventMCMemory[mcIndex].fClusterID[i].fWeight = ((float)bunchData[is])/nmc;
500 *header = (1<<30) | ((nWords10&0x3FF)<<16) | (hwAddr & 0xFFF);
505 HLTError("Internal error: too less memory allocated");
507 for( AliHLTUInt32_t i=0; i<nWords32; i++ ) fEventMemory[i] = AliHLTTPCHWCFEmulator::WriteBigEndian(fEventMemory[i]);
508 rawEvent = fEventMemory;
509 rawEventSize32 = nWords32;
510 mcLabels = fEventMCMemory;
514 } // unpacked data type
520 void AliHLTTPCHWCFSupport::Add10Word( AliHLTUInt32_t &nWords32, int &seek10, UInt_t data )
522 // add 10-bit data to the 32-bit word
523 // fEventMemory [nWords32] --- current 32-bit word
524 // *seek10 --- 10-bit position withing the word
525 // pointers are increased, a new word is first initialised to 0
527 data = data & 0x3FF; // truncate to 10 bits
531 fEventMemory[nWords32-1] = data<<20;
533 } else if( seek10 == 1 ){
534 fEventMemory[nWords32-1] &= 0xFFF003FF;
535 fEventMemory[nWords32-1] |= (data<<10);
537 } else if( seek10 == 0 ){
538 fEventMemory[nWords32-1] &= 0xFFFFFC00;
539 fEventMemory[nWords32-1] |= data;
546 int AliHLTTPCHWCFSupport::CheckRawData( const AliHLTUInt32_t *buffer,
547 unsigned long bufferSize32, int patch, int slice )
550 // The procedure checks consistency of the data
553 const unsigned int headerSize32 = 8;
555 if (!buffer) return 0;
557 const char *str=Form("slice %d patch %d:", slice, patch);
559 if( bufferSize32 < headerSize32 ){
560 HLTWarning("%s Buffer size is smaller than CDH header size", str);
566 AliHLTUInt32_t blockSize32 = bufferSize32; // size of the raw data in words
568 if( buffer[0]!=0xFFFFFFFF ) blockSize32 = buffer[0]/4; // use size information from the header
569 if( blockSize32 > bufferSize32 ){
570 HLTWarning(Form("%s Could not find a valid DDL header!",str));
574 UChar_t rcuVer = (UChar_t)( (buffer[1] >> 24) & 0xFF );
577 HLTWarning("%s Old data format, RCU version %d", str,rcuVer);
581 // is the block valid
582 //AliHLTUInt32_t blockAttributes = buffer[3]; // block attributes (bits 24-31) and participating sub detectors
583 //cout<<blockAttributes<<" "<<(blockAttributes >> 24)<<endl;
584 //if ( !( (blockAttributes >> 24) & 1) ) return 0;
587 const AliHLTUInt32_t* fData = buffer + headerSize32;
588 unsigned long dataSize32 = blockSize32 - headerSize32;
590 // Read the RCU trailer according to the RCU formware version specified in CDH
591 // Cross-check with version found in the trailer
592 // The two major bit should be 11 (identifies the end of the trailer)
594 AliHLTUInt32_t word = fData[dataSize32 - 1];
596 if ((word >> 30) != 3) {
597 HLTWarning("%s Last RCU trailer word not found!", str);
601 UChar_t ver = (word >> 16) & 0xFF;
602 //AliHLTUInt32_t rcuId = (Int_t)((word >> 7) & 0x1FF);
603 AliHLTUInt32_t rcuTrailerSize32 = (word & 0x7F); // size of RCU trailer data in words
606 HLTWarning("%s Wrong RCU firmware version detected: %d != %d",
611 if (rcuTrailerSize32 < 2) {
612 HLTWarning(Form("Invalid trailer size found (%d bytes) !",
613 rcuTrailerSize32*4));
617 if( rcuTrailerSize32 > dataSize32 ){
618 HLTWarning(Form("%s Invalid trailer size found (%d bytes) ! The size is bigger than the raw data size (%ld bytes)!",
619 str, rcuTrailerSize32*4,dataSize32*4));
625 Int_t trailerIndex = dataSize32 - rcuTrailerSize32;
627 for( unsigned int i=trailerIndex; i<dataSize32-1; i++){
628 if ((fData[i] >> 30) != 2) {
629 HLTWarning("%s Missing RCU trailer identifier pattern!",str);
634 // Read the payload size
636 Int_t rcuPayloadSize32 = fData[trailerIndex] & 0x3FFFFFF;
638 if ( rcuPayloadSize32 + rcuTrailerSize32 != dataSize32) {
639 HLTWarning(Form("%s Inconsistent raw data size ! Raw data size - %ld bytes (from CDH), RCU trailer - %d bytes, raw data size (from RCU trailer) - %d bytes !",
641 (rcuTrailerSize32)*4,
642 rcuPayloadSize32*4));
647 //AliHLTTPCMapping *mapping = new AliHLTTPCMapping(patch);
648 const int kMaxNTimeBins = 2000;
650 UShort_t *channelData10 = new UShort_t[kMaxNTimeBins]; // cache for the decoded altro payload
652 Int_t position = 0; // current position (32-bit words) in fData
656 // Search for the next Altro channel
659 while( position < rcuPayloadSize32 ){
660 word = fData[position++];
661 if( (word >> 30) == 1) break;
663 if (position >= rcuPayloadSize32 ) break; // no next channel found
665 // extract channel payload and hw address
667 Int_t channelPayloadSize10 = (word >> 16) & 0x3FF; // payload size in 10-bit words
668 Int_t channelPayloadSize32 = (channelPayloadSize10+2)/3;
669 Bool_t channelIOErrors = (word >> 29) & 0x1; // check for readout errors
670 Short_t channelHWAddress = word & 0xFFF;
672 if( position + channelPayloadSize32-1> rcuPayloadSize32 ){
673 HLTWarning(Form("%s Inconsistent channel payload data size: expected <= %d bytes from RCU trailer, found %d bytes in the channel header!",
674 str,(rcuPayloadSize32 - position)*4, channelPayloadSize32*4 ));
678 //bool channelBranchAB = ((channelHWAddress >> 11) & 0x1);
679 // int channelFEC = ((channelHWAddress >> 7) & 0xF); // front-end card index
680 //int channelAltro = ((channelHWAddress >> 4) & 0x7); // altro chip index
681 //int channelIndex = (channelHWAddress & 0xF); // channel index
682 //int channelRow = mapping->GetRow(channelHWAddress);
683 //int channelPad = mapping->GetPad(channelHWAddress);
685 // Now unpack the Altro data: 10-bit words to 16 bit-words
687 Int_t channelData10Index = 0;// current position in the payload
689 for (Int_t iword = 0; iword < channelPayloadSize32; iword++) {
690 word = fData[position++];
691 if ((word >> 30) != 0) {
692 HLTWarning(Form("%s Unexpected end of payload in altro channel payload! Address=0x%x, word=0x%x",
693 str, channelHWAddress,word));
698 channelData10[channelData10Index++] = (word >> 20) & 0x3FF;
699 channelData10[channelData10Index++] = (word >> 10) & 0x3FF;
700 channelData10[channelData10Index++] = word & 0x3FF;
703 if ( channelIOErrors ) continue;
707 Int_t prevTimeBin = 1024;
708 channelData10Index = 0;
712 // Read next Altro bunch
714 if ((channelData10Index+1 >= channelPayloadSize10) ) break;
716 Int_t bunchLength = channelData10[channelData10Index++];
717 Int_t bunchStartTimeBin = channelData10[channelData10Index++];
719 if (bunchLength <= 2) {
720 // Invalid bunch size
721 HLTWarning(Form("%s Too short bunch length (%d) in Address=0x%x!",
722 str, bunchLength,channelHWAddress));
725 if( channelData10Index + bunchLength - 2 > channelPayloadSize10 ){
726 // Too long bunch detected
727 HLTWarning(Form("%s Too long bunch detected in Address=0x%x! Expected <= %d 10-bit words, found %d !",
728 str,channelHWAddress,channelPayloadSize10-channelData10Index,bunchLength));
732 if( bunchStartTimeBin-bunchLength+1 < 0) {
733 HLTWarning(Form("%s Invalid start time-bin in Address=0x%x ! (%d-%d+1) < 0",
734 str,channelHWAddress,bunchStartTimeBin,bunchLength));
737 if (bunchStartTimeBin >= prevTimeBin) {
738 HLTWarning(Form("%s Invalid start time-bin in Address=0x%x! (%d>=%d)",
739 str,channelHWAddress,bunchStartTimeBin,prevTimeBin));
743 prevTimeBin = bunchStartTimeBin-bunchLength+1;
747 //UShort_t* bunchData = &channelData10[channelData10Index]; // pointer to the current bunch samples
748 channelData10Index += bunchLength;
752 delete[] channelData10;