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"
48 AliHLTTPCHWCFSupport::AliHLTTPCHWCFSupport()
54 // see header file for class documentation
55 for( int i=0; i<fgkNSlices; i++ )
56 for( int j=0; j<fgkNPatches; j++ ) fMapping[i][j] = 0;
60 AliHLTTPCHWCFSupport::~AliHLTTPCHWCFSupport()
62 // see header file for class documentation
63 for( int i=0; i<fgkNSlices; i++ )
64 for( int j=0; j<fgkNPatches; j++ ) delete[] fMapping[i][j];
68 AliHLTTPCHWCFSupport::AliHLTTPCHWCFSupport(const AliHLTTPCHWCFSupport&)
77 AliHLTTPCHWCFSupport& AliHLTTPCHWCFSupport::operator=(const AliHLTTPCHWCFSupport&){
83 void AliHLTTPCHWCFSupport::ReleaseEventMemory()
86 if( fEventMemory ) delete[] fEventMemory;
87 if( fEventMCMemory )delete[] fEventMCMemory;
93 const AliHLTUInt32_t *AliHLTTPCHWCFSupport::GetMapping( int slice, int patch )
95 // see header file for class documentation
96 if( slice<0 || slice>=fgkNSlices ){
97 HLTFatal("Wrong slice number %d, no mapping is provided.", slice);
100 if( patch<0 || patch>= fgkNPatches ){
101 HLTFatal("Wrong patch number %d, no mapping is provided.", patch);
104 if( !fMapping[slice][patch] ) fMapping[slice][patch] = ReadMapping(slice,patch);
105 return fMapping[slice][patch];
109 AliHLTUInt32_t *AliHLTTPCHWCFSupport::ReadMapping( int slice, int patch, const char *mappingFileName ) const
111 // Create mapping array for one patch
112 // If no mapping file provided, reads from default file
113 // Output: mapping [] array of type AliHLTUInt32_t, where :
115 // mapping[0] == N hardware adresses in the array (mapping size is maping[0] + 1 )
116 // mapping[hwAddress] == configWord
118 // configWord consist of:
120 // bits 0-7: pad number
121 // bits 8-13: row number
122 // bit 14 : flag for border pad
123 // bit 15 : is the pad active
124 // bits 16->28 : gain calibration as 13 bit fixed point,
125 // with 1 bit position before decimal point
127 const AliHLTUInt32_t kBorderFlag = (1 << 14);
128 const AliHLTUInt32_t kActiveFlag = (1 << 15);
130 if( slice<0 || slice>=fgkNSlices ){
131 HLTFatal("Wrong slice number %d, no mapping is provided.", slice);
135 if( patch<0 || patch>5 ){
136 HLTFatal("Wrong patch number %d, no mapping is provided.", patch);
140 // AliHLTTPCTransform::GetFirstRow returns first row in scheme A.
141 // We have to transform to scheme B by AliHLTTPCTransform::Slice2Sector.
143 UInt_t offsetSchemeB=0;
147 AliHLTTPCTransform::Slice2Sector(slice, AliHLTTPCTransform::GetFirstRow(patch),
149 offsetSchemeB = (UInt_t) tmp;
153 AliTPCcalibDB *calib = AliTPCcalibDB::Instance();
154 AliTPCCalPad * gainTPC = 0;
155 AliTPCCalROC * gainROC = 0;
156 if( calib ) gainTPC = calib->GetPadGainFactor();
157 if( gainTPC ) gainROC = gainTPC->GetCalROC(sector); // pad gains per given sector
159 HLTWarning("No TPC gain calibration found");
164 if( mappingFileName ){
165 filename = mappingFileName;
167 const char* basePath=getenv("ALICE_ROOT");
168 if (basePath) filename.Form("%s/TPC/mapping/Patch%d.data", basePath,patch);
172 inFile.open(filename.Data());
174 HLTFatal("Unable to open mapping file: %s This means no mapping is provided.", filename.Data());
179 AliHLTUInt32_t *mapping = 0;
180 AliHLTUInt32_t *rowBranchPadHw = 0;
187 if( !(inFile >> nHWAdd ) || !(inFile >> maxHWAdd) ){
188 HLTError("Mapping file for patch %d corrupted &s", patch,filename.Data());
192 if( maxHWAdd > 0xFFF ){
193 HLTError("Max hardware address exceeded for patch %d, max number is %d, number from mapping file is %d.",patch, 0xFFF, maxHWAdd+1);
197 if(nHWAdd > maxHWAdd ){
198 HLTError("Too large number of hardware addresses for patch %d: max number is %d, number from mapping file is %d.",patch, maxHWAdd, nHWAdd );
202 mapping = new AliHLTUInt32_t[maxHWAdd+2];
203 rowBranchPadHw = new AliHLTUInt32_t[nHWAdd];
204 if( !mapping || !rowBranchPadHw ){
205 HLTError("Can not allocate &d bytes of memory", (maxHWAdd+1+nHWAdd)*sizeof(AliHLTUInt32_t));
209 for( unsigned int i=0; i<maxHWAdd+2; i++ ) mapping[i] = 0;
210 for( unsigned int i=0; i<nHWAdd; i++ ) rowBranchPadHw[i] = 0;
211 mapping[0] = maxHWAdd+1;
218 if( !(inFile>>hwAdd) || !(inFile>>row) || !(inFile>>pad) ) break;
222 if ( nRead >= nHWAdd ){
223 HLTError("Too many hardware addresses: %d, expected %d, mapping file %s corrupted?", nRead+1, nHWAdd, filename.Data());
226 if (hwAdd>maxHWAdd) {
227 HLTError("hardware address exceeds max hwAddress %d, mapping file %s corrupted?", maxHWAdd, filename.Data());
231 if( row < offsetSchemeB ){
232 HLTError("row number %d below minimum %d for patch %d, mapping file %s corrupted?", row, offsetSchemeB, patch, filename.Data());
236 row -= offsetSchemeB;
239 HLTError("row number %d withing patch exceed the maximum %d for patch %d, mapping file %s corrupted?", row, 0x3F, patch, filename.Data());
244 HLTError("pad number %d exceed the maximum %d for patch %d, mapping file %s corrupted?", pad, 0xFF, patch, filename.Data());
248 bool active = true; // Currently all channels are always active
251 AliHLTFloat64_t gain = 1.;
253 gain = gainROC->GetValue(offsetSchemeB+row,pad);
254 if( gain>1.e-4 ) gain = 1./gain;
258 AliHLTUInt32_t gainCalib = TMath::Nint(gain);
259 if( gainCalib > 0x1FFF ) gainCalib = 0x1FFF;
261 AliHLTUInt32_t configWord = ( (row & 0x3F) << 8 ) | (pad & 0xFF);
262 if ( active ) configWord |= kActiveFlag;
263 configWord |= (gainCalib & 0x1FFF) << 16;
265 mapping[1+hwAdd] = configWord;
267 AliHLTUInt32_t branch = (hwAdd >> 11) & 0x1;
268 rowBranchPadHw[nRead] = (row<<25) | (branch<<24) | (pad<<16) | hwAdd;
276 if ( nRead!= nHWAdd ){
277 HLTError("Too less hardware addresses: %d, expected %d, mapping file %s corrupted?", nRead, nHWAdd, filename.Data());
282 // mark pads at borders of A/B branches
284 std::sort(rowBranchPadHw, rowBranchPadHw + nHWAdd);
285 int rowBranchLast = -1;
286 for( unsigned int i=0; i<nHWAdd; i++ ){
287 int rowBranch = rowBranchPadHw[i]>>24;
288 if( rowBranch != rowBranchLast ){
289 mapping[1+(rowBranchPadHw[i] & 0xFFF)] |= kBorderFlag;
290 rowBranchLast = rowBranch;
291 if( i>0 ) mapping[1+(rowBranchPadHw[i-1] & 0xFFF)] |= kBorderFlag;
294 mapping[1+(rowBranchPadHw[nRead-1] & 0xFFF)] |= kBorderFlag;
300 delete[] rowBranchPadHw;
310 int AliHLTTPCHWCFSupport::CreateRawEvent
311 ( const AliHLTComponentBlockData* block,
312 const AliHLTUInt32_t *&rawEvent, AliHLTUInt32_t &rawEventSize32,
313 const AliHLTTPCClusterMCLabel *&mcLabels, AliHLTUInt32_t &nMCLabels
316 // the method creates TPC raw data out of the input block
317 // MC labels are provided if possible
320 ReleaseEventMemory();
327 if( block->fPtr==NULL ){
328 HLTWarning("NULL pointer to the data block");
332 Int_t slice = AliHLTTPCDefinitions::GetMinSliceNr( *block );
333 Int_t patch = AliHLTTPCDefinitions::GetMinPatchNr( *block );
334 AliHLTTPCMapping mapping(patch);
336 const char *str=Form("slice %d patch %d:", slice, patch);
338 if ( block->fDataType == (kAliHLTDataTypeDDLRaw | kAliHLTDataOriginTPC) )
340 // already raw format -> only set the pointers and estimate the size
342 // read CDH header, estimate size of the data
344 AliHLTUInt64_t headerSize = sizeof(AliRawDataHeader);
346 AliRawDataHeader *cdhHeader = reinterpret_cast<AliRawDataHeader*>(block->fPtr);
348 AliHLTUInt64_t blockSize = block->fSize; // size of the raw data in bytes
350 if( cdhHeader->fSize!=0xFFFFFFFF ){ // use size information from the header
351 blockSize = cdhHeader->fSize;
352 if( blockSize > block->fSize ){
353 HLTWarning("%s Could not find a valid DDL header!",str);
358 if( blockSize < headerSize ){
359 HLTWarning("%s Buffer size is smaller than CDH header size", str);
363 rawEvent = reinterpret_cast<AliHLTUInt32_t*> (reinterpret_cast<UChar_t*>(block->fPtr)+headerSize);
364 rawEventSize32 = ( blockSize - headerSize )/sizeof(AliHLTUInt32_t);
367 else if ( block->fDataType == AliHLTTPCDefinitions::fgkUnpackedRawDataType )
370 AliHLTTPCDigitReaderUnpacked digitReader;
371 digitReader.SetUnsorted(kTRUE);
373 if( digitReader.InitBlock(block->fPtr,block->fSize,patch,slice)<0 ) {
374 HLTWarning("failed setting up digit reader (InitBlock)");
378 int nDigitsTotal = 0;
379 int nBunchesTotal = 0;
381 while( digitReader.NextChannel() ){
382 while(digitReader.NextBunch()){
384 nDigitsTotal+=digitReader.GetBunchSize();
390 if( digitReader.InitBlock(block->fPtr,block->fSize,patch,slice)<0) {
391 HLTWarning("failed setting up digit reader (InitBlock)");
395 Int_t nPadsTotal = 0;
396 Int_t firstRow = AliHLTTPCTransform::GetFirstRow(patch);
397 Int_t nRows = AliHLTTPCTransform::GetNRows(patch);
399 for( int i=0; i<nRows; i++ ){
400 nPadsTotal += AliHLTTPCTransform::GetNPads(firstRow+i);
403 AliHLTUInt32_t totalSize32 = (nDigitsTotal + nBunchesTotal*2)/3+2*nPadsTotal + 10;
404 AliHLTUInt32_t totalNMC = nDigitsTotal + 10;
406 fEventMemory = new AliHLTUInt32_t[totalSize32];
408 HLTWarning("Not enougth memory: can not allocate %d bytes",totalSize32*8);
412 fEventMCMemory = new AliHLTTPCClusterMCLabel[totalNMC];
413 if( !fEventMCMemory ){
414 HLTWarning("Not enougth memory: can not allocate %d bytes",totalNMC*sizeof(AliHLTTPCClusterMCLabel));
415 delete[] fEventMemory;
420 AliHLTUInt32_t nWords32 = 0;
421 AliHLTUInt32_t mcIndex = 0;
424 AliHLTTPCDigitData tmpDigit;
425 tmpDigit.fTrackID[0] = -1;
426 tmpDigit.fTrackID[1] = -1;
427 tmpDigit.fTrackID[2] = -1;
429 while( !err && digitReader.NextChannel() ){
431 Int_t row=digitReader.GetRow();
432 Int_t pad=digitReader.GetPad();
434 AliHLTUInt32_t hwAddr = mapping.GetHwAddress(row, pad);
438 if( nWords32 >= totalSize32){ err = 1; break; }
440 AliHLTUInt32_t *header = fEventMemory + nWords32;
444 int prevTime = 10000000;
446 while(digitReader.NextBunch()){
448 if( hwAddr > 0xFFF ) continue;
450 Int_t nSignals = digitReader.GetBunchSize();
452 HLTWarning("Empty bunch received");
456 Int_t time = digitReader.GetTime() + nSignals-1;
458 if( time-nSignals+1<0 || time>=AliHLTTPCTransform::GetNTimeBins() ){
459 HLTWarning("Wrong time bins received: %d-%d for row %d pad %d", time-nSignals+1, time, row, pad);
463 if( time >= prevTime ){
464 HLTWarning("Unexpected order of TPC bunches in row %d, pad %d", row, pad);
468 prevTime = time-nSignals+1;
470 if( nWords32+( 2+nSignals)/3+1 >= totalSize32 ){ err = 1; break; }
471 if( mcIndex + nSignals >= totalNMC ){ err = 1; break; }
473 if( nWords10 + 2 + nSignals > 0x3FF ){
474 HLTWarning("Too much data in row %d, pad %d", row, pad);
478 nWords10 += 2 + nSignals;
480 Add10Word( nWords32, seek10, nSignals + 2 );
481 Add10Word( nWords32, seek10, time );
483 const UInt_t *bunchData = digitReader.GetSignals();
484 const AliHLTTPCDigitData *mcDigits = digitReader.GetBunchDigits();
486 HLTWarning("No MC labels found for a bunch of digits");
489 for(Int_t is=nSignals-1; is>=0; is--){
490 Add10Word( nWords32, seek10, bunchData[is] );
491 const AliHLTTPCDigitData &digit = mcDigits ?mcDigits[is] :tmpDigit;
493 for( int i=0; i<3; i++ ) if( digit.fTrackID[i] >=0 ) nmc++;
494 for( int i=0; i<3; i++ ){
495 fEventMCMemory[mcIndex].fClusterID[i].fMCID = digit.fTrackID[i];
496 fEventMCMemory[mcIndex].fClusterID[i].fWeight = 0;
497 if( digit.fTrackID[i] >=0 ){
498 fEventMCMemory[mcIndex].fClusterID[i].fWeight = ((float)bunchData[is])/nmc;
506 *header = (1<<30) | ((nWords10&0x3FF)<<16) | (hwAddr & 0xFFF);
511 HLTError("Internal error: too less memory allocated");
513 for( AliHLTUInt32_t i=0; i<nWords32; i++ ) fEventMemory[i] = AliHLTTPCHWCFEmulator::WriteBigEndian(fEventMemory[i]);
514 rawEvent = fEventMemory;
515 rawEventSize32 = nWords32;
516 mcLabels = fEventMCMemory;
520 } // unpacked data type
526 void AliHLTTPCHWCFSupport::Add10Word( AliHLTUInt32_t &nWords32, int &seek10, UInt_t data )
528 // add 10-bit data to the 32-bit word
529 // fEventMemory [nWords32] --- current 32-bit word
530 // *seek10 --- 10-bit position withing the word
531 // pointers are increased, a new word is first initialised to 0
533 data = data & 0x3FF; // truncate to 10 bits
537 fEventMemory[nWords32-1] = data<<20;
539 } else if( seek10 == 1 ){
540 fEventMemory[nWords32-1] &= 0xFFF003FF;
541 fEventMemory[nWords32-1] |= (data<<10);
543 } else if( seek10 == 0 ){
544 fEventMemory[nWords32-1] &= 0xFFFFFC00;
545 fEventMemory[nWords32-1] |= data;
552 int AliHLTTPCHWCFSupport::CheckRawData( const AliHLTUInt32_t *buffer,
553 unsigned long bufferSize32, int patch, int slice )
556 // The procedure checks consistency of the data
559 const unsigned int headerSize32 = 8;
561 if (!buffer) return 0;
563 const char *str=Form("slice %d patch %d:", slice, patch);
565 if( bufferSize32 < headerSize32 ){
566 HLTWarning("%s Buffer size is smaller than CDH header size", str);
572 AliHLTUInt32_t blockSize32 = bufferSize32; // size of the raw data in words
574 if( buffer[0]!=0xFFFFFFFF ) blockSize32 = buffer[0]/4; // use size information from the header
575 if( blockSize32 > bufferSize32 ){
576 HLTWarning(Form("%s Could not find a valid DDL header!",str));
580 UChar_t rcuVer = (UChar_t)( (buffer[1] >> 24) & 0xFF );
583 HLTWarning("%s Old data format, RCU version %d", str,rcuVer);
587 // is the block valid
588 //AliHLTUInt32_t blockAttributes = buffer[3]; // block attributes (bits 24-31) and participating sub detectors
589 //cout<<blockAttributes<<" "<<(blockAttributes >> 24)<<endl;
590 //if ( !( (blockAttributes >> 24) & 1) ) return 0;
593 const AliHLTUInt32_t* fData = buffer + headerSize32;
594 unsigned long dataSize32 = blockSize32 - headerSize32;
596 // Read the RCU trailer according to the RCU formware version specified in CDH
597 // Cross-check with version found in the trailer
598 // The two major bit should be 11 (identifies the end of the trailer)
600 AliHLTUInt32_t word = fData[dataSize32 - 1];
602 if ((word >> 30) != 3) {
603 HLTWarning("%s Last RCU trailer word not found!", str);
607 UChar_t ver = (word >> 16) & 0xFF;
608 //AliHLTUInt32_t rcuId = (Int_t)((word >> 7) & 0x1FF);
609 AliHLTUInt32_t rcuTrailerSize32 = (word & 0x7F); // size of RCU trailer data in words
612 HLTWarning("%s Wrong RCU firmware version detected: %d != %d",
617 if (rcuTrailerSize32 < 2) {
618 HLTWarning(Form("Invalid trailer size found (%d bytes) !",
619 rcuTrailerSize32*4));
623 if( rcuTrailerSize32 > dataSize32 ){
624 HLTWarning(Form("%s Invalid trailer size found (%d bytes) ! The size is bigger than the raw data size (%ld bytes)!",
625 str, rcuTrailerSize32*4,dataSize32*4));
631 Int_t trailerIndex = dataSize32 - rcuTrailerSize32;
633 for( unsigned int i=trailerIndex; i<dataSize32-1; i++){
634 if ((fData[i] >> 30) != 2) {
635 HLTWarning("%s Missing RCU trailer identifier pattern!",str);
640 // Read the payload size
642 Int_t rcuPayloadSize32 = fData[trailerIndex] & 0x3FFFFFF;
644 if ( rcuPayloadSize32 + rcuTrailerSize32 != dataSize32) {
645 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 !",
647 (rcuTrailerSize32)*4,
648 rcuPayloadSize32*4));
653 //AliHLTTPCMapping *mapping = new AliHLTTPCMapping(patch);
654 const int kMaxNTimeBins = 2000;
656 UShort_t *channelData10 = new UShort_t[kMaxNTimeBins]; // cache for the decoded altro payload
658 Int_t position = 0; // current position (32-bit words) in fData
662 // Search for the next Altro channel
665 while( position < rcuPayloadSize32 ){
666 word = fData[position++];
667 if( (word >> 30) == 1) break;
669 if (position >= rcuPayloadSize32 ) break; // no next channel found
671 // extract channel payload and hw address
673 Int_t channelPayloadSize10 = (word >> 16) & 0x3FF; // payload size in 10-bit words
674 Int_t channelPayloadSize32 = (channelPayloadSize10+2)/3;
675 Bool_t channelIOErrors = (word >> 29) & 0x1; // check for readout errors
676 Short_t channelHWAddress = word & 0xFFF;
678 if( position + channelPayloadSize32-1> rcuPayloadSize32 ){
679 HLTWarning(Form("%s Inconsistent channel payload data size: expected <= %d bytes from RCU trailer, found %d bytes in the channel header!",
680 str,(rcuPayloadSize32 - position)*4, channelPayloadSize32*4 ));
684 //bool channelBranchAB = ((channelHWAddress >> 11) & 0x1);
685 // int channelFEC = ((channelHWAddress >> 7) & 0xF); // front-end card index
686 //int channelAltro = ((channelHWAddress >> 4) & 0x7); // altro chip index
687 //int channelIndex = (channelHWAddress & 0xF); // channel index
688 //int channelRow = mapping->GetRow(channelHWAddress);
689 //int channelPad = mapping->GetPad(channelHWAddress);
691 // Now unpack the Altro data: 10-bit words to 16 bit-words
693 Int_t channelData10Index = 0;// current position in the payload
695 for (Int_t iword = 0; iword < channelPayloadSize32; iword++) {
696 word = fData[position++];
697 if ((word >> 30) != 0) {
698 HLTWarning(Form("%s Unexpected end of payload in altro channel payload! Address=0x%x, word=0x%x",
699 str, channelHWAddress,word));
704 channelData10[channelData10Index++] = (word >> 20) & 0x3FF;
705 channelData10[channelData10Index++] = (word >> 10) & 0x3FF;
706 channelData10[channelData10Index++] = word & 0x3FF;
709 if ( channelIOErrors ) continue;
713 Int_t prevTimeBin = 1024;
714 channelData10Index = 0;
718 // Read next Altro bunch
720 if ((channelData10Index+1 >= channelPayloadSize10) ) break;
722 Int_t bunchLength = channelData10[channelData10Index++];
723 Int_t bunchStartTimeBin = channelData10[channelData10Index++];
725 if (bunchLength <= 2) {
726 // Invalid bunch size
727 HLTWarning(Form("%s Too short bunch length (%d) in Address=0x%x!",
728 str, bunchLength,channelHWAddress));
731 if( channelData10Index + bunchLength - 2 > channelPayloadSize10 ){
732 // Too long bunch detected
733 HLTWarning(Form("%s Too long bunch detected in Address=0x%x! Expected <= %d 10-bit words, found %d !",
734 str,channelHWAddress,channelPayloadSize10-channelData10Index,bunchLength));
738 if( bunchStartTimeBin-bunchLength+1 < 0) {
739 HLTWarning(Form("%s Invalid start time-bin in Address=0x%x ! (%d-%d+1) < 0",
740 str,channelHWAddress,bunchStartTimeBin,bunchLength));
743 if (bunchStartTimeBin >= prevTimeBin) {
744 HLTWarning(Form("%s Invalid start time-bin in Address=0x%x! (%d>=%d)",
745 str,channelHWAddress,bunchStartTimeBin,prevTimeBin));
749 prevTimeBin = bunchStartTimeBin-bunchLength+1;
753 //UShort_t* bunchData = &channelData10[channelData10Index]; // pointer to the current bunch samples
754 channelData10Index += bunchLength;
758 delete[] channelData10;