]> git.uio.no Git - u/mrichter/AliRoot.git/blob - HLT/BASE/AliHLTDataBuffer.cxx
bugfix: adjust memory page size between 50 and 500 MByte, correcting warning
[u/mrichter/AliRoot.git] / HLT / BASE / AliHLTDataBuffer.cxx
1 // $Id$
2
3 //**************************************************************************
4 //* This file is property of and copyright by the ALICE HLT Project        * 
5 //* ALICE Experiment at CERN, All rights reserved.                         *
6 //*                                                                        *
7 //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
8 //*                  for The ALICE HLT Project.                            *
9 //*                                                                        *
10 //* Permission to use, copy, modify and distribute this software and its   *
11 //* documentation strictly for non-commercial purposes is hereby granted   *
12 //* without fee, provided that the above copyright notice appears in all   *
13 //* copies and that both the copyright notice and this permission notice   *
14 //* appear in the supporting documentation. The authors make no claims     *
15 //* about the suitability of this software for any purpose. It is          *
16 //* provided "as is" without express or implied warranty.                  *
17 //**************************************************************************
18
19 //  @file   AliHLTDataBuffer.cxx
20 //  @author Matthias Richter
21 //  @date   
22 //  @brief  Handling of Data Buffers for HLT components.
23 //  @note   Only used in the AliRoot framework
24
25 // see header file for class documentation
26 // or
27 // refer to README to build package
28 // or
29 // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
30
31 #if __GNUC__>= 3
32 using namespace std;
33 #endif
34
35 #include "AliHLTDataBuffer.h"
36 #include "AliHLTConsumerDescriptor.h"
37 #include "AliHLTComponent.h"
38 #include "AliHLTTask.h"
39 #include <cerrno>
40 #include <cassert>
41 //#include <string>
42 //#include "AliHLTSystem.h"
43
44 #define USE_ALIHLTRAWPAGE
45
46 typedef vector<AliHLTDataBuffer::AliHLTDataSegment> AliHLTDataSegmentList;
47
48 /** ROOT macro for the implementation of ROOT specific class methods */
49 ClassImp(AliHLTDataBuffer)
50
51 AliHLTDataBuffer::AliHLTDataBuffer()
52   :
53   fSegments(),
54   fConsumers(),
55   fActiveConsumers(),
56   fReleasedConsumers(),
57   fpBuffer(NULL),
58   fFlags(0),
59   fForwardedSegmentSources(),
60   fForwardedSegments()
61 {
62   // see header file for class documentation
63   // or
64   // refer to README to build package
65   // or
66   // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
67   fSegments.empty();
68   fConsumers.empty();
69   fActiveConsumers.empty();
70   fReleasedConsumers.empty();
71   fgNofInstances++;
72 }
73
74 int AliHLTDataBuffer::fgNofInstances=0;
75 AliHLTDataBuffer::AliHLTRawBufferPList AliHLTDataBuffer::fgFreeBuffers;
76 AliHLTDataBuffer::AliHLTRawBufferPList AliHLTDataBuffer::fgActiveBuffers;
77 AliHLTUInt32_t AliHLTDataBuffer::fgMargin=1024;
78 AliHLTLogging AliHLTDataBuffer::fgLogging;
79 const Int_t AliHLTDataBuffer::fgkSafetyPatternSize=16;
80 const char AliHLTDataBuffer::fgkSafetyPattern[]={0x28, 0x63, 0x29, 0x4d, 0x52, 0x49, 0x43, 0x48, 0x54, 0x45, 0x52, 0x20, 0x32, 0x30, 0x30, 0x37};
81 AliHLTUInt32_t AliHLTDataBuffer::fgEventCount=0;
82
83 AliHLTDataBuffer::~AliHLTDataBuffer()
84 {
85   // see header file for function documentation
86   CleanupConsumerList();
87
88   if (--fgNofInstances<=0) {
89     DeleteRawBuffers();
90   }
91 }
92
93 int AliHLTDataBuffer::SetConsumer(AliHLTComponent* pConsumer)
94 {
95   // see header file for function documentation
96   int iResult=0;
97   if (pConsumer) {
98     if (FindConsumer(pConsumer)) {
99       HLTWarning("consumer %s (%p) already set to data buffer %p", pConsumer->GetComponentID(), pConsumer, this);
100     }
101     AliHLTConsumerDescriptor* pDesc=new AliHLTConsumerDescriptor(pConsumer);
102     if (pDesc) {
103       fConsumers.push_back(pDesc);
104       HLTDebug("set consumer %s (%p) to data buffer %p", pConsumer->GetComponentID(), pConsumer, this);
105     } else {
106       HLTError("memory allocation failed");
107       iResult=-ENOMEM;
108     }
109   } else {
110     HLTError("invalid parameter: consumer component (nil)");
111     iResult=-EINVAL;
112   }
113   return iResult;
114 }
115
116 int AliHLTDataBuffer::FindMatchingDataBlocks(const AliHLTComponent* pConsumer, AliHLTComponentDataTypeList* tgtList)
117 {
118   // see header file for function documentation
119   int iResult=0;
120   if (pConsumer) {
121     AliHLTDataSegmentList segments;
122     if ((iResult=FindMatchingDataSegments(pConsumer, segments))>=0) {
123       if (tgtList) {
124         AliHLTDataSegmentList::iterator segment=segments.begin();
125         while (segment!=segments.end()) {
126           tgtList->push_back((*segment).fDataType);
127           segment++;
128         }
129       }
130       iResult=segments.size();
131     }
132   } else {
133     iResult=-EINVAL;
134   }
135   return iResult;
136 }
137
138 int AliHLTDataBuffer::FindMatchingDataSegments(const AliHLTComponent* pConsumer,
139                                                vector<AliHLTDataBuffer::AliHLTDataSegment>& tgtList)
140 {
141   // see header file for function documentation
142   int iResult=0;
143
144   // Matthias 26.09.2007 relax the restriction to matching data blocks
145   // all blocks are passed to the consumer, which is the policy also in
146   // PubSub
147   tgtList.assign(fSegments.begin(), fSegments.end());
148
149   // add all forwarded blocks
150   tgtList.insert(tgtList.begin(), fForwardedSegments.begin(), fForwardedSegments.end());
151   iResult=tgtList.size();
152   return iResult;
153   
154   if (pConsumer) {
155     AliHLTComponentDataTypeList dtlist;
156     ((AliHLTComponent*)pConsumer)->GetInputDataTypes(dtlist);
157     AliHLTDataSegmentList::iterator segment=fSegments.begin();
158     while (segment!=fSegments.end()) {
159       AliHLTComponentDataTypeList::iterator type=dtlist.begin();
160       while (type!=dtlist.end()) {
161         if ((*segment).fDataType==(*type)) {
162           tgtList.push_back(*segment);
163           iResult++;
164           break;
165         }
166         type++;
167       }
168       segment++;
169     }
170   } else {
171     iResult=-EINVAL;
172   }
173   return iResult;
174 }
175
176 int AliHLTDataBuffer::Subscribe(const AliHLTComponent* pConsumer, AliHLTComponentBlockDataList& blockDescList)
177 {
178   // see header file for function documentation
179   int iResult=0;
180   if (pConsumer) {
181     if (1/*fpBuffer*/) {
182       AliHLTConsumerDescriptor* pDesc=FindConsumer(pConsumer, fConsumers);
183       if (pDesc) {
184         AliHLTDataSegmentList tgtList;
185         // Matthias 26.07.2007 AliHLTSystem should behave the same way as PubSub
186         // so it does not matter if there are matching data types or not, unless
187         // we implement such a check in PubSub
188         if ((iResult=FindMatchingDataSegments(pConsumer, tgtList))>=0) {
189           AliHLTDataSegmentList::iterator segment=tgtList.begin();
190           while (segment!=tgtList.end()) {
191             // fill the block data descriptor
192             AliHLTComponentBlockData bd;
193             AliHLTComponent::FillBlockData(bd);
194             // This models the behavior of PubSub.
195             // For incoming data blocks, fOffset must be ignored by the
196             // processing component. It is set for bookkeeping in the framework.
197             // fPtr always points to the beginning of the data.
198             bd.fOffset=0;
199             AliHLTUInt8_t* pTgt=*segment;
200             bd.fPtr=reinterpret_cast<void*>(pTgt);
201             bd.fSize=(*segment).fSegmentSize;
202             bd.fDataType=(*segment).fDataType;
203             bd.fSpecification=(*segment).fSpecification;
204             blockDescList.push_back(bd);
205             pDesc->SetActiveDataSegment(*segment);
206             HLTDebug("component %p (%s) subscribed to segment offset %d size %d data type %s %#x", 
207                      pConsumer, ((AliHLTComponent*)pConsumer)->GetComponentID(), bd.fOffset,
208                      bd.fSize, (AliHLTComponent::DataType2Text(bd.fDataType)).c_str(), 
209                      bd.fSpecification);
210             segment++;
211           }
212           // move this consumer to the active list
213           if (tgtList.size()==0) {
214             ChangeConsumerState(pDesc, fConsumers, fReleasedConsumers);
215             HLTDebug("no input data for component %p (%s) available", pConsumer, ((AliHLTComponent*)pConsumer)->GetComponentID());
216           } else if (ChangeConsumerState(pDesc, fConsumers, fActiveConsumers)>=0) {
217             HLTDebug("component %p (%s) subscribed to data buffer %p", pConsumer, ((AliHLTComponent*)pConsumer)->GetComponentID(), this);
218           } else {
219             // TODO: cleanup the consumer descriptor correctly
220             segment=tgtList.begin();
221             while (segment!=tgtList.end()) {
222               blockDescList.pop_back();
223               segment++;
224             }
225             HLTError("can not activate consumer %p for data buffer %p", pConsumer, this);
226             iResult=-EACCES;
227           }
228         } else {
229           HLTError("unresolved data segment(s) for component %p (%s)", pConsumer, ((AliHLTComponent*)pConsumer)->GetComponentID());
230           iResult=-EBADF;
231         }
232       } else {
233         if (!FindConsumer(pConsumer)) {
234           HLTError("component %p is not a data consumer of data buffer %p", pConsumer, this);
235         } else {
236           HLTError("component %p is a valid data consumer of data buffer %p, but did not release it's buffer subscription", pConsumer, this);
237         }
238         iResult=-ENOENT;
239       }
240     } else {
241       // Matthias 26.07.2007 until now, data had to be present for successful subscription
242       // in order to be consistent with the PubSub framework, this restiction has been
243       // removed
244       //HLTError("data buffer %p is empty", this);
245       //iResult=-ENODATA;
246     }
247   } else {
248     HLTError("invalid parameter");
249     iResult=-EINVAL;
250   }
251   return iResult;
252 }
253
254 int AliHLTDataBuffer::Release(AliHLTComponentBlockData* pBlockDesc,
255                               const AliHLTComponent* pConsumer,
256                               const AliHLTTask* pOwnerTask)
257 {
258   // see header file for function documentation
259   int iResult=0;
260   if (pBlockDesc && pConsumer) {
261     AliHLTConsumerDescriptor* pDesc=FindConsumer(pConsumer, fActiveConsumers);
262     if (pDesc) {
263       if ((iResult=pDesc->CheckActiveDataSegment(AliHLTDataSegment(pBlockDesc->fPtr, pBlockDesc->fOffset, pBlockDesc->fSize)))!=1) {
264         HLTWarning("data segment mismatch, component %p has not subscribed to a segment with offset %#x and size %d", pConsumer, pBlockDesc->fOffset, pBlockDesc->fSize);
265         // TODO: appropriate error handling, but so far optional
266         iResult=0;
267       } else {
268         pDesc->ReleaseActiveDataSegment(AliHLTDataSegment(pBlockDesc->fPtr, pBlockDesc->fOffset, pBlockDesc->fSize));
269       }
270       if (GetNofPendingConsumers()==0 && fForwardedSegments.size()>0) {
271         // last consumer, release forwarded segments
272         ReleaseForwardedBlock(pBlockDesc, pOwnerTask);
273       }
274       pBlockDesc->fOffset=0;
275       pBlockDesc->fPtr=NULL;
276       pBlockDesc->fSize=0;
277       if (pDesc->GetNofActiveSegments()==0) {
278         if ((iResult=ChangeConsumerState(pDesc, fActiveConsumers, fReleasedConsumers))>=0) {
279           if (GetNofActiveConsumers()==0 && GetNofPendingConsumers()==0) {
280             // this is the last consumer, reset the consumer list and release the raw buffer
281             ResetDataBuffer();
282           }
283         } else {
284           HLTError("can not deactivate consumer %p for data buffer %p", pConsumer, this);
285           iResult=-EACCES;
286         }
287       }
288     } else {
289       HLTWarning("component %p has currently not subscribed to the data buffer %p", pConsumer, this);
290       iResult=-ENOENT;
291     }
292   } else {
293     HLTError("inavalid parameter: pBlockDesc=%p pConsumer=%p", pBlockDesc, pConsumer);
294     iResult=-EINVAL;
295   }
296   return iResult;
297 }
298
299 int AliHLTDataBuffer::ReleaseForwardedBlock(AliHLTComponentBlockData* pBlockDesc,
300                                             const AliHLTTask* pOwnerTask)
301 {
302   // see header file for function documentation
303   int iResult=0;
304   if (pBlockDesc && pOwnerTask) {
305         assert(fForwardedSegments.size()==fForwardedSegmentSources.size());
306         AliHLTDataSegmentList::iterator segment=fForwardedSegments.begin();
307         AliHLTTaskPList::iterator src=fForwardedSegmentSources.begin();
308         //HLTDebug("%p checking forwarded segments", this);
309         for (; segment!=fForwardedSegments.end(); segment++, src++) {
310           //HLTDebug("segment ptr=%p offset=%d size=%d\n"
311           //   "block ptr=%p offset=%d size=%d", (*segment).fPtr, (*segment).fSegmentOffset, (*segment).fSegmentSize, pBlockDesc->fPtr, pBlockDesc->fOffset, pBlockDesc->fSize);
312           if ((*segment)==AliHLTDataSegment(pBlockDesc->fPtr, pBlockDesc->fOffset, pBlockDesc->fSize)) {
313             //HLTDebug("release segment of task %p", *src);
314             assert((*src)!=NULL);
315             if ((*src)!=NULL) {
316               if ((*src)->Release(pBlockDesc, pOwnerTask)>=0) {
317                 HLTDebug("task %s (%p) released forwarded segment %p size %d of task %s (%p)",
318                          pOwnerTask->GetName(), pOwnerTask, (*segment).GetPtr(), (*segment).GetSize(),
319                          (*src)->GetName(), *src);
320               } else {
321                 HLTError("task %s (%p) failed releasing forwarded segment %p size %d of task %s (%p)",
322                          pOwnerTask->GetName(), pOwnerTask, (*segment).GetPtr(), (*segment).GetSize(),
323                          (*src)->GetName(), *src);
324               }
325             }
326             fForwardedSegments.erase(segment);
327             fForwardedSegmentSources.erase(src);
328             break;
329           }
330         }
331   } else {
332     HLTError("inavalid parameter: pBlockDesc=%p pOwnerTask=%p", pBlockDesc, pOwnerTask);
333     iResult=-EINVAL;
334   }
335   return iResult;
336 }
337
338 int AliHLTDataBuffer::Forward(AliHLTTask* pSrcTask, AliHLTComponentBlockData* pBlockDesc)
339 {
340   // see header file for function documentation
341   if (pSrcTask==NULL || pBlockDesc==NULL) return -EINVAL;
342   assert(fForwardedSegments.size()==fForwardedSegmentSources.size());
343   if (fForwardedSegments.size()!=fForwardedSegmentSources.size()) return -EFAULT;
344   fForwardedSegmentSources.push_back(pSrcTask);
345   fForwardedSegments.push_back(AliHLTDataSegment(pBlockDesc->fPtr, pBlockDesc->fOffset, pBlockDesc->fSize, pBlockDesc->fDataType, pBlockDesc->fSpecification));
346   return 0;
347 }
348
349 AliHLTUInt8_t* AliHLTDataBuffer::GetTargetBuffer(int iMinSize)
350 {
351   // see header file for function documentation
352   AliHLTUInt8_t* pTargetBuffer=NULL;
353   if (fpBuffer!=NULL) {
354     HLTWarning("data buffer not properly reset, possible memory leak\n");
355   }
356   fpBuffer=CreateRawBuffer(iMinSize);
357   if (fpBuffer) {
358     pTargetBuffer=*fpBuffer;
359   } else {
360     HLTError("can not create raw buffer");
361   }
362   return pTargetBuffer;
363 }
364
365 int AliHLTDataBuffer::SetSegments(AliHLTUInt8_t* pTgt, AliHLTComponentBlockData* arrayBlockData, int iSize)
366 {
367   // see header file for function documentation
368   int iResult=0;
369   if (pTgt && arrayBlockData && iSize>=0) {
370     if (fpBuffer) {
371       if (*fpBuffer==pTgt) {
372         AliHLTDataBuffer::AliHLTDataSegment segment;
373         AliHLTUInt32_t maxSize=0;
374         for (int i=0; i<iSize; i++) {
375           // This function has to model the behavior of PubSub
376           // For output blocks only the fOffset value is used, this must be the offset
377           // relative to the output pointer. fPtr must be either NULL or the output
378           // pointer. In either case it is 'ignored' and set to the beginning of the
379           // data buffer
380           if (arrayBlockData[i].fPtr==NULL ||
381               arrayBlockData[i].fPtr==*fpBuffer) {
382             arrayBlockData[i].fPtr=*fpBuffer;
383             if ((arrayBlockData[i].fOffset+arrayBlockData[i].fSize<=fpBuffer->GetUsedSize()) ||
384                 ((arrayBlockData[i].fOffset==~(AliHLTUInt32_t)0) && arrayBlockData[i].fSize==0)) {
385               segment.fSegmentOffset=arrayBlockData[i].fOffset;
386               segment.fPtr=(AliHLTUInt8_t*)arrayBlockData[i].fPtr;
387               segment.fSegmentSize=arrayBlockData[i].fSize;
388               segment.fDataType=arrayBlockData[i].fDataType;
389               segment.fSpecification=arrayBlockData[i].fSpecification;
390               fSegments.push_back(segment);
391               HLTDebug("set segment %s with size %d at offset %d", AliHLTComponent::DataType2Text(segment.fDataType).data(), segment.fSegmentSize, segment.fSegmentOffset);
392
393               // find the actual size of the data
394               if ((arrayBlockData[i].fOffset!=~(AliHLTUInt32_t)0) &&
395                   arrayBlockData[i].fOffset+arrayBlockData[i].fSize>maxSize) {
396                 maxSize=arrayBlockData[i].fOffset+arrayBlockData[i].fSize;
397               }
398             } else {
399               HLTError("block data specification %#d (%s) exceeds size of data buffer", i, AliHLTComponent::DataType2Text(arrayBlockData[i].fDataType).data());
400               HLTError("block offset=%d, block size=%d, buffer size=%d", arrayBlockData[i].fOffset, arrayBlockData[i].fSize, fpBuffer->GetUsedSize());
401               iResult=-E2BIG;
402             }
403           } else {
404             HLTError("invalid pointer (%p) in block data specification (buffer %p size %d)."
405                      "please note: for output blocks only the fOffset value is valid and must "
406                      "be relative to the output buffer", arrayBlockData[i].fPtr, fpBuffer->GetPointer(), fpBuffer->GetUsedSize());
407             iResult=-ERANGE;
408           }
409         }
410         // to be enabled if unit test is ready
411 #ifdef USE_ALIHLTRAWPAGE
412         iResult=SetRawBufferDataSize(fpBuffer, maxSize);        
413 #endif //USE_ALIHLTRAWPAGE
414       } else {
415         HLTError("this data buffer (%p) does not match the internal data buffer %p of raw buffer %p", pTgt, fpBuffer->GetPointer(), fpBuffer);
416         iResult=-EINVAL;
417       }
418     } else {
419       HLTFatal("internal data structur mismatch");
420       iResult=-EFAULT;
421     }
422   } else {
423     HLTError("invalid parameter: pTgtBuffer=%p arrayBlockData=%p", pTgt, arrayBlockData);
424     iResult=-EINVAL;
425   }
426   return iResult;
427 }
428
429 int AliHLTDataBuffer::IsEmpty()
430 {
431   // see header file for function documentation
432   int iResult=(fpBuffer==NULL && fForwardedSegments.size()==0) || GetNofSegments()==0;
433   return iResult;
434 }
435
436 int AliHLTDataBuffer::GetNofSegments()
437 {
438   // see header file for function documentation
439   int iResult=fSegments.size() + fForwardedSegments.size();
440   return iResult;
441 }
442
443 int AliHLTDataBuffer::GetNofConsumers()
444 {
445   // see header file for function documentation
446   int iResult=fConsumers.size() + GetNofActiveConsumers() + fReleasedConsumers.size();
447   return iResult;
448 }
449
450 int AliHLTDataBuffer::GetNofPendingConsumers()
451 {
452   // see header file for function documentation
453   int iResult=fConsumers.size();
454   return iResult;
455 }
456
457 int AliHLTDataBuffer::GetNofActiveConsumers()
458 {
459   // see header file for function documentation
460   int iResult=fActiveConsumers.size();
461   return iResult;
462 }
463
464 AliHLTDataBuffer::AliHLTRawBuffer* AliHLTDataBuffer::CreateRawBuffer(AliHLTUInt32_t size)
465 {
466   // see header file for function documentation
467   AliHLTRawBuffer* pRawBuffer=NULL;
468   unsigned int reqSize=size+fgkSafetyPatternSize;
469 #ifndef USE_ALIHLTRAWPAGE
470   AliHLTRawBufferPList::iterator buffer=fgFreeBuffers.begin();
471   while (buffer!=fgFreeBuffers.end() && pRawBuffer==NULL) {
472     if ((*buffer)->CheckSize(reqSize)) {
473       // assign this element
474       pRawBuffer=*buffer;
475       pRawBuffer->UseBuffer(size);
476       fgFreeBuffers.erase(buffer);
477       fgLogging.Logging(kHLTLogDebug, "AliHLTDataBuffer::CreateRawBuffer", "data buffer handling", "raw buffer container %p provided for request of %d bytes (total %d available in buffer %p)", pRawBuffer, size, pRawBuffer->GetTotalSize(), pRawBuffer->GetPointer());
478       fgActiveBuffers.push_back(pRawBuffer);
479       break;
480     }
481     buffer++;
482   }
483   if (pRawBuffer==NULL) {
484     // no buffer found, create a new one
485     pRawBuffer=new AliHLTRawBuffer(reqSize);
486     if (pRawBuffer) {
487       if (pRawBuffer->GetPointer()) {
488         pRawBuffer->UseBuffer(size);
489         fgActiveBuffers.push_back(pRawBuffer);
490         fgLogging.Logging(kHLTLogDebug, "AliHLTDataBuffer::CreateRawBuffer", "data buffer handling", "new raw buffer %p of size %d created (container %p)", pRawBuffer->GetPointer(), pRawBuffer->GetTotalSize(), pRawBuffer);
491       } else {
492         delete pRawBuffer;
493         pRawBuffer=NULL;
494         fgLogging.Logging(kHLTLogError, "AliHLTDataBuffer::CreateRawBuffer", "data buffer handling", "memory allocation failed");
495       } 
496     } else {
497       fgLogging.Logging(kHLTLogError, "AliHLTDataBuffer::CreateRawBuffer", "data buffer handling", "memory allocation failed");
498     }
499   }
500 #else
501   pRawBuffer=AliHLTDataBuffer::AliHLTRawPage::GlobalAlloc(reqSize);
502   if (pRawBuffer) {
503     pRawBuffer->UseBuffer(size);
504   }
505 #endif
506   if (pRawBuffer!=NULL && fgkSafetyPatternSize>0) {
507     //fgLogging.Logging(kHLTLogDebug, "AliHLTDataBuffer::CreateRawBuffer", "data buffer handling", "writing safety pattern to %p offset %d", (*buffer)->GetPointer(), (*buffer)->GetUsedSize());
508     pRawBuffer->WritePattern(fgkSafetyPattern, fgkSafetyPatternSize);
509   }
510   return pRawBuffer;
511 }
512
513 int AliHLTDataBuffer::SetRawBufferDataSize(AliHLTRawBuffer* pBuffer, AliHLTUInt32_t size) const
514 {
515   // see header file for function documentation
516   int iResult=0;
517   if (!pBuffer) return -EINVAL;
518   if (size>pBuffer->GetUsedSize()) {
519     HLTError("indicated data size %d exceeds data buffer %p (%d)", size, pBuffer->GetPointer(), pBuffer->GetUsedSize());
520     return -ENOSPC;
521   }
522   if (fgkSafetyPatternSize>0) {
523     if (pBuffer->CheckPattern(fgkSafetyPattern, fgkSafetyPatternSize)) {
524       HLTError("potential memory corruption: component has written beyond end of data buffer %p size %d", pBuffer->GetPointer(), pBuffer->GetUsedSize());
525     }
526   }
527   // shrink the buffer and write new pattern at the end
528 #ifdef USE_ALIHLTRAWPAGE
529   AliHLTDataBuffer::AliHLTRawPage* rawpage=AliHLTDataBuffer::AliHLTRawPage::FindPage(pBuffer);
530   if (rawpage) {
531     pBuffer->UseBuffer(size);
532     if (rawpage->SetSize(pBuffer, size+fgkSafetyPatternSize)==0) {
533       // nothing to do
534     } else {
535       fgLogging.Logging(kHLTLogError, "AliHLTDataBuffer::SetRawBufferDataSize", "data buffer handling", "failed to set size for raw buffer %p", pBuffer);
536       iResult=-EFAULT;
537     }
538   } else {
539     fgLogging.Logging(kHLTLogError, "AliHLTDataBuffer::SetRawBufferDataSize", "data buffer handling", "can not find raw page for buffer %p", pBuffer);
540     iResult=-ENOENT;
541   }
542 #else //!USE_ALIHLTRAWPAGE
543   pBuffer->UseBuffer(size);
544 #endif //USE_ALIHLTRAWPAGE
545   if (fgkSafetyPatternSize>0) {
546     pBuffer->WritePattern(fgkSafetyPattern, fgkSafetyPatternSize);
547   }
548   return iResult;
549 }
550
551 int AliHLTDataBuffer::ReleaseRawBuffer(AliHLTRawBuffer* pBuffer)
552 {
553   // see header file for function documentation
554   int iResult=0;
555   if (pBuffer) {
556 #ifdef USE_ALIHLTRAWPAGE
557     AliHLTDataBuffer::AliHLTRawPage* rawpage=AliHLTDataBuffer::AliHLTRawPage::FindPage(pBuffer);
558     if (rawpage)
559 #else //!USE_ALIHLTRAWPAGE
560     AliHLTRawBufferPList::iterator buffer=fgActiveBuffers.begin();
561     while (buffer!=fgActiveBuffers.end() && (*buffer)!=pBuffer) {
562       buffer++;
563     }
564     if (buffer!=fgActiveBuffers.end())
565 #endif //USE_ALIHLTRAWPAGE
566     {
567       if (fgkSafetyPatternSize>0) {
568         //fgLogging.Logging(kHLTLogDebug, "AliHLTDataBuffer::ReleaseRawBuffer", "data buffer handling", "comparing safety pattern at %p offset %d", pBuffer->GetPointer(), reinterpret_cast<AliHLTUInt32_t>(pBuffer));
569         if ((pBuffer)->CheckPattern(fgkSafetyPattern, fgkSafetyPatternSize)) {
570           fgLogging.Logging(kHLTLogFatal, "AliHLTDataBuffer::ReleaseRawBuffer", "data buffer handling", "component has written beyond end of data buffer %p size %d", pBuffer->GetPointer(), pBuffer->GetUsedSize());
571         }
572       }
573       pBuffer->Reset();
574 #ifdef USE_ALIHLTRAWPAGE
575       if (rawpage->Free(pBuffer)==0) {
576       } else {
577         fgLogging.Logging(kHLTLogError, "AliHLTDataBuffer::ReleaseRawBuffer", "data buffer handling", "failed to release raw buffer %p", pBuffer);
578       }
579 #else //!USE_ALIHLTRAWPAGE
580       fgFreeBuffers.push_back(pBuffer);
581       fgActiveBuffers.erase(buffer);
582 #endif //USE_ALIHLTRAWPAGE
583     } else {
584 #ifdef USE_ALIHLTRAWPAGE
585       fgLogging.Logging(kHLTLogError, "AliHLTDataBuffer::ReleaseRawBuffer", "data buffer handling", "can not find raw page for buffer %p", pBuffer);
586 #else //!USE_ALIHLTRAWPAGE
587       fgLogging.Logging(kHLTLogWarning, "AliHLTDataBuffer::ReleaseRawBuffer", "data buffer handling", "can not find raw buffer container %p in the list of active containers", pBuffer);
588 #endif //USE_ALIHLTRAWPAGE
589       iResult=-ENOENT;
590     }
591   } else {
592     fgLogging.Logging(kHLTLogError, "AliHLTDataBuffer::ReleaseRawBuffer", "data buffer handling", "invalid parameter");
593     iResult=-EINVAL;
594   }
595   return iResult;
596 }
597
598
599 int AliHLTDataBuffer::DeleteRawBuffers() 
600 {
601   // see header file for function documentation
602   int iResult=0;
603 #ifdef ALIHLTSYSTEM_PROFILING
604   int iTotalSize=0;
605   int iCount=fgFreeBuffers.size()+fgActiveBuffers.size();
606 #endif //ALIHLTSYSTEM_PROFILING
607   AliHLTRawBufferPList::iterator buffer;;
608   while ((buffer=fgFreeBuffers.begin())!=fgFreeBuffers.end()) {
609 #ifdef ALIHLTSYSTEM_PROFILING
610     iTotalSize+=(*buffer)->GetTotalSize();
611 #endif //ALIHLTSYSTEM_PROFILING
612     delete *buffer;
613     fgFreeBuffers.erase(buffer);
614   }
615   while ((buffer=fgActiveBuffers.begin())!=fgActiveBuffers.end()) {
616 #ifdef ALIHLTSYSTEM_PROFILING
617     iTotalSize+=(*buffer)->GetTotalSize();
618 #endif //ALIHLTSYSTEM_PROFILING
619     fgLogging.Logging(kHLTLogWarning, "AliHLTDataBuffer::DeleteRawBuffer", "data buffer handling", "request to delete active raw buffer container (raw buffer %p, size %d)", (*buffer)->GetPointer(), (*buffer)->GetTotalSize());
620     delete *buffer;
621     fgActiveBuffers.erase(buffer);
622   }
623 #ifdef ALIHLTSYSTEM_PROFILING
624   fgLogging.Logging(kHLTLogImportant, "AliHLTDataBuffer::DeleteRawBuffer", "data buffer handling", "Total memory allocation: %d byte in %d buffers", iTotalSize, iCount);
625 #endif //ALIHLTSYSTEM_PROFILING
626   return iResult;
627 }
628
629 int AliHLTDataBuffer::PrintStatistics() 
630 {
631   // see header file for function documentation
632   int iResult=0;
633 #ifdef USE_ALIHLTRAWPAGE
634   int nofPages=0;
635   AliHLTUInt32_t totalSize=0;
636   for (AliHLTDataBuffer::AliHLTRawPage* rawpage=AliHLTDataBuffer::AliHLTRawPage::NextPage(NULL);
637        rawpage!=NULL; 
638        rawpage=AliHLTDataBuffer::AliHLTRawPage::NextPage(rawpage)) {
639     nofPages++;
640     totalSize+=rawpage->Size();
641   }
642   //if (rawpage) rawpage->Print("global");
643   fgLogging.Logging(kHLTLogInfo, "AliHLTDataBuffer::PrintStatistics", "data buffer handling", "total number of memory pages: %d   total size %d", nofPages, totalSize);
644
645 #else //! USE_ALIHLTRAWPAGE
646   int iFree=0;
647   int iActive=0;
648   AliHLTRawBufferPList::iterator buffer;;
649   for (buffer=fgFreeBuffers.begin(); buffer!=fgFreeBuffers.end(); buffer++) {
650     iFree+=(*buffer)->GetTotalSize();
651   }
652   for (buffer=fgActiveBuffers.begin(); buffer!=fgActiveBuffers.end(); buffer++) {
653     iActive+=(*buffer)->GetTotalSize();
654   }
655   fgLogging.Logging(kHLTLogInfo, "AliHLTDataBuffer::PrintStatistics", "data buffer handling", "Total memory allocation: %d byte; %d free buffers (%d byte) - %d active buffers (%d byte) ", iFree+iActive, fgFreeBuffers.size(), iFree, fgActiveBuffers.size(), iActive);
656 #endif // USE_ALIHLTRAWPAGE
657   return iResult;
658 }
659
660 AliHLTConsumerDescriptor* AliHLTDataBuffer::FindConsumer(const AliHLTComponent* pConsumer, AliHLTConsumerDescriptorPList &list) const
661 {
662   // see header file for function documentation
663   AliHLTConsumerDescriptor* pDesc=NULL;
664   AliHLTConsumerDescriptorPList::iterator desc=list.begin();
665   while (desc!=list.end() && pDesc==NULL) {
666     if ((pConsumer==NULL || (*desc)->GetComponent()==pConsumer)) {
667       pDesc=*desc;
668     }
669     desc++;
670   }
671   return pDesc;
672 }
673
674 int AliHLTDataBuffer::ResetDataBuffer() 
675 {
676   // see header file for function documentation
677   int iResult=0;
678   AliHLTRawBuffer* pBuffer=fpBuffer;
679   fpBuffer=NULL;
680
681   // cleanup forwarded segment lists
682   assert(fForwardedSegments.size()==0);
683   fForwardedSegments.clear();
684   fForwardedSegmentSources.clear();
685
686   // cleanup consumer states
687   AliHLTConsumerDescriptorPList::iterator desc;
688 //   if (GetNofPendingConsumers()>0) {
689 //     desc=fConsumers.begin();
690 //     while (desc!=fConsumers.end()) {
691 //       AliHLTComponent* pComp=(*desc)->GetComponent();
692 //       HLTError("internal error: consumer %p (%s %p) did not get data from data buffer %p", *desc, pComp?pComp->GetComponentID():"", pComp, this);
693 //       desc++;
694 //     }
695 //   }
696   desc=fReleasedConsumers.begin();
697   while (desc!=fReleasedConsumers.end()) {
698     AliHLTConsumerDescriptor* pDesc=*desc;
699     fReleasedConsumers.erase(desc);
700     desc=fReleasedConsumers.begin();
701     fConsumers.push_back(pDesc);
702   }
703   desc=fActiveConsumers.begin();
704   while (desc!=fActiveConsumers.end()) {
705     AliHLTConsumerDescriptor* pDesc=*desc;
706     HLTWarning("consumer %p (%s) was not released", pDesc, pDesc->GetComponent()?pDesc->GetComponent()->GetComponentID():"### invalid component ###");
707     fActiveConsumers.erase(desc);
708     desc=fActiveConsumers.begin();
709     fConsumers.push_back(pDesc);
710   }
711
712   // cleanup segments
713   AliHLTDataSegmentList::iterator segment=fSegments.begin();
714   while (segment!=fSegments.end()) {
715     fSegments.erase(segment);
716     segment=fSegments.begin();
717   }
718
719   // cleanup raw buffer
720   if (pBuffer) {
721     ReleaseRawBuffer(pBuffer);
722   }
723   return iResult;
724 }
725
726 int AliHLTDataBuffer::Reset()
727 {
728   // see header file for function documentation
729   return ResetDataBuffer();
730 }
731
732 // this is the version which works on lists of components instead of consumer descriptors
733 // int AliHLTDataBuffer::ChangeConsumerState(AliHLTComponent* pConsumer, AliHLTComponentPList &srcList, AliHLTComponentPList &tgtList)
734 // {
735 //   int iResult=0;
736 //   if (pDesc) {
737 //     AliHLTComponentPList::iterator desc=srcList.begin();
738 //     while (desc!=srcList.end()) {
739 //       if ((*desc)==pConsumer) {
740 //      srcList.erase(desc);
741 //      tgtList.push_back(pConsumer);
742 //      break;
743 //       }
744 //      desc++;
745 //     }
746 //     if (desc==srcList.end()) {
747 //       HLTError("can not find consumer component %p in list", pConsumer);
748 //       iResult=-ENOENT;
749 //     }
750 //   } else {
751 //     HLTError("invalid parameter");
752 //     iResult=-EINVAL;
753 //   }
754 //   return iResult;
755 // }
756
757 int AliHLTDataBuffer::ChangeConsumerState(AliHLTConsumerDescriptor* pDesc, AliHLTConsumerDescriptorPList &srcList, AliHLTConsumerDescriptorPList &tgtList)
758 {
759   // see header file for function documentation
760   int iResult=-ENOENT;
761   if (pDesc) {
762     AliHLTConsumerDescriptorPList::iterator desc=srcList.begin();
763     while (desc!=srcList.end()) {
764       if ((*desc)==pDesc) {
765         srcList.erase(desc);
766         tgtList.push_back(pDesc);
767         iResult=0;
768         break;
769       }
770       desc++;
771     }
772     if (iResult<0) {
773       HLTError("can not find consumer descriptor %p in list", pDesc);
774     }
775   } else {
776     HLTError("invalid parameter");
777     iResult=-EINVAL;
778   }
779   return iResult;
780 }
781
782 int AliHLTDataBuffer::CleanupConsumerList() 
783 {
784   // see header file for function documentation
785   int iResult=0;
786   ResetDataBuffer();
787   AliHLTConsumerDescriptorPList::iterator desc=fConsumers.begin();
788   while (desc!=fConsumers.end()) {
789     delete *desc;
790     fConsumers.erase(desc);
791     desc=fConsumers.begin();
792   }
793   return iResult;
794 }
795
796 int AliHLTDataBuffer::FindConsumer(const AliHLTComponent* pConsumer, int bAllLists)
797 {
798   // see header file for function documentation
799   AliHLTConsumerDescriptorPList::iterator desc=fConsumers.begin();
800   while (desc!=fConsumers.end()) {
801     if ((*desc)->GetComponent()==pConsumer)
802       return 1;
803     desc++;
804   }
805   if (bAllLists==0) return 0;
806
807   desc=fActiveConsumers.begin();
808   while (desc!=fActiveConsumers.end()) {
809     if ((*desc)->GetComponent()==pConsumer)
810       return 1;
811     desc++;
812   }
813   desc=fReleasedConsumers.begin();
814   while (desc!=fReleasedConsumers.end()) {
815     if ((*desc)->GetComponent()==pConsumer)
816       return 1;
817     desc++;
818   }
819   return 0;
820 }
821
822 AliHLTDataBuffer::AliHLTRawBuffer::AliHLTRawBuffer(AliHLTUInt32_t size)
823   : fSize(0)
824   , fTotalSize(size)
825   , fExternalPtr(NULL)
826   , fPtr(static_cast<AliHLTUInt8_t*>(malloc(size)))
827   , fLastEventCount(0)
828 {
829   // see header file for class documentation
830   // or
831   // refer to README to build package
832   // or
833   // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
834   if (fPtr==NULL) {
835     fSize=0;
836     fTotalSize=0;
837   }
838 }
839
840 AliHLTDataBuffer::AliHLTRawBuffer::AliHLTRawBuffer(AliHLTUInt32_t size, AliHLTUInt8_t* buffer)
841   : fSize(0)
842   , fTotalSize(size)
843   , fExternalPtr(buffer)
844   , fPtr(fExternalPtr)
845   , fLastEventCount(0)
846 {
847   // see header file for class documentation
848 }
849
850 AliHLTDataBuffer::AliHLTRawBuffer::~AliHLTRawBuffer()
851 {
852   // see header file for class documentation
853   if (fExternalPtr==NULL && fPtr) {
854     free(fPtr);
855   }
856   fPtr=NULL;
857   fSize=0;
858   fTotalSize=0;
859 }
860
861 int AliHLTDataBuffer::AliHLTRawBuffer::operator==(void* ptr) const
862 {
863   // see header file for function documentation
864   return fPtr == static_cast<AliHLTUInt8_t*>(ptr);
865 }
866
867 int AliHLTDataBuffer::AliHLTRawBuffer::operator<(void* ptr) const
868 {
869   // see header file for function documentation
870   int iResult=fPtr < static_cast<AliHLTUInt8_t*>(ptr);
871   //printf("%p: %p <= %p (%d)\n", this, fPtr, ptr, iResult);
872   return iResult;
873 }
874
875 int AliHLTDataBuffer::AliHLTRawBuffer::operator<=(void* ptr) const
876 {
877   // see header file for function documentation
878   int iResult=fPtr <= static_cast<AliHLTUInt8_t*>(ptr);
879   //printf("%p: %p <= %p (%d)\n", this, fPtr, ptr, iResult);
880   return iResult;
881 }
882
883 int AliHLTDataBuffer::AliHLTRawBuffer::operator>(void* ptr) const
884 {
885   // see header file for function documentation
886   int iResult=fPtr+fSize > static_cast<AliHLTUInt8_t*>(ptr);
887   //printf("%p: %p + %d > %p (%d)\n", this, fPtr, fSize, ptr, iResult);
888   return iResult;
889 }
890
891 int AliHLTDataBuffer::AliHLTRawBuffer::operator-(void* ptr) const
892 {
893   // see header file for function documentation
894   return static_cast<int>(static_cast<AliHLTUInt8_t*>(ptr)-fPtr);
895 }
896
897 int AliHLTDataBuffer::AliHLTRawBuffer::operator<(const AliHLTRawBuffer& op) const
898 {
899   // see header file for function documentation
900   return (fPtr+fSize < op.fPtr);
901 }
902
903 int AliHLTDataBuffer::AliHLTRawBuffer::operator<=(const AliHLTRawBuffer& op) const
904 {
905   // see header file for function documentation
906   return (fPtr+fSize <= op.fPtr);
907 }
908
909 int AliHLTDataBuffer::AliHLTRawBuffer::operator>(const AliHLTRawBuffer& op) const
910 {
911   // see header file for function documentation
912   return (fPtr >= op.fPtr+op.fSize);
913 }
914
915 AliHLTUInt8_t* AliHLTDataBuffer::AliHLTRawBuffer::UseBuffer(AliHLTUInt32_t size)
916 {
917   // mark a portion of the buffer as used
918   if (size>0 && fTotalSize>=size) {
919     fSize=size;
920     fLastEventCount=AliHLTDataBuffer::fgEventCount;
921     return fPtr;
922   }
923   return NULL;
924 }
925
926 AliHLTDataBuffer::AliHLTRawBuffer* AliHLTDataBuffer::AliHLTRawBuffer::Split(AliHLTUInt32_t size)
927 {
928   // split a buffer at specified size
929   // only possible for buffers with external memory
930   if (fTotalSize>size && 
931       (fSize==0 || fSize<=size) &&
932       fExternalPtr!=NULL) {
933     AliHLTRawBuffer* part2=new AliHLTRawBuffer(fTotalSize-size, fPtr+size);
934     if (part2) {
935       fTotalSize=size;
936     }
937     return part2;
938   } else {
939     //cout << "can not split fTotalSize=" << fTotalSize << "  fSize=" << fSize << "  at size=" << size << endl; 
940   }
941   return NULL;
942 }
943
944 int AliHLTDataBuffer::AliHLTRawBuffer::CheckSize(AliHLTUInt32_t size) const
945 {
946   // see header file for function documentation
947   if (fTotalSize<size) return 0;
948   unsigned adjust=0;
949   if (fLastEventCount+1<AliHLTDataBuffer::fgEventCount) {
950     adjust=AliHLTDataBuffer::fgEventCount-fLastEventCount;
951   }
952   return (adjust>2) || ((fTotalSize-size)<(fgMargin<<adjust));
953 }
954
955 int AliHLTDataBuffer::AliHLTRawBuffer::Reset()
956 {
957   // see header file for function documentation
958   fSize=0;
959   return 0;
960 }
961
962 int AliHLTDataBuffer::AliHLTRawBuffer::WritePattern(const char* pattern, int size)
963 {
964   // see header file for function documentation
965   int iResult=0;
966   if (pattern!=NULL && size>0) {
967     if (fSize+size<=fTotalSize) {
968       memcpy(((char*)fPtr)+fSize, pattern, size);
969       iResult=size;
970     } else {
971       iResult=-ENOSPC;
972     }
973   }
974   return iResult;
975 }
976
977 int AliHLTDataBuffer::AliHLTRawBuffer::CheckPattern(const char* pattern, int size) const
978 {
979   // see header file for function documentation
980   int iResult=0;
981   if (pattern!=NULL && size>0) {
982     if (fSize+size<=fTotalSize) {
983       iResult=memcmp(((char*)fPtr)+fSize, pattern, size)!=0;
984     } else {
985       iResult=-ENOSPC;
986     }
987   }
988   return iResult;
989 }
990
991 int AliHLTDataBuffer::AliHLTRawBuffer::Merge(const AliHLTDataBuffer::AliHLTRawBuffer& neighbor)
992 {
993   // Merge buffer with neighboring buffer.
994   // Only possible if the buffers are consecutive with out any gap.
995
996   if (!fExternalPtr || !neighbor.fExternalPtr) return -EPERM;
997
998   if (neighbor.fTotalSize==0 &&
999       fPtr < neighbor.fPtr &&
1000       fPtr+fTotalSize > neighbor.fPtr) {
1001     // special case for a buffer of zero size embedded into this buffer
1002     // nothing to do
1003     return 0;
1004   }
1005   if (fTotalSize==0 &&
1006       neighbor.fPtr < fPtr &&
1007       neighbor.fPtr+neighbor.fTotalSize > fPtr) {
1008     // special case for this buffer of size zero embedded into another buffer
1009     fPtr=neighbor.fPtr;
1010     fExternalPtr=fPtr;
1011     fTotalSize+=neighbor.fTotalSize;
1012     fSize=0;
1013     return 0;
1014   }
1015   if (fPtr+fTotalSize == neighbor.fPtr) {
1016     fTotalSize+=neighbor.fTotalSize;
1017     fSize=0;
1018     return 0;
1019   }
1020   if (fPtr == neighbor.fPtr+neighbor.fTotalSize) {
1021     fPtr=neighbor.fPtr;
1022     fExternalPtr=fPtr;
1023     fTotalSize+=neighbor.fTotalSize;
1024     fSize=0;
1025     return 0;
1026   }
1027   return -EINVAL;
1028 }
1029
1030 void AliHLTDataBuffer::AliHLTRawBuffer::Print(const char* option)
1031 {
1032   /// print buffer information
1033   if (strcmp(option, "min")!=0) {
1034     cout << "************* AliHLTRawBuffer status ***********" << endl;
1035   }
1036   printf("  %p: buffer %p%s size %d used %d\n", this, fPtr, fExternalPtr?" (external)":"", fTotalSize, fSize); fflush(stdout);
1037 }
1038
1039 AliHLTDataBuffer::AliHLTRawPage::AliHLTRawPage(AliHLTUInt32_t pagesize)
1040   : fSize(pagesize)
1041   , fPtr(static_cast<AliHLTUInt8_t*>(malloc(pagesize)))
1042   , fFreeBuffers()
1043   , fUsedBuffers()
1044 {
1045   // constructor
1046   if (fPtr) {
1047     fFreeBuffers.push_back(new AliHLTRawBuffer(fSize, fPtr));
1048   } else {
1049     fSize=0;
1050   }
1051 }
1052
1053 AliHLTDataBuffer::AliHLTRawPage::~AliHLTRawPage()
1054 {
1055   // destructor
1056   if (IsUsed()) {
1057     // do not free if the resources have not been completely freed
1058     HLTError("memory mismatch: not all allocated intances have been released");
1059   } else {
1060     if (IsFragmented()) {
1061       HLTWarning("page still fragmented");
1062     }
1063     AliHLTRawBufferPList::iterator element=fFreeBuffers.begin();
1064     while (element!=fFreeBuffers.end()) {
1065       if (*element) delete *element;
1066       element=fFreeBuffers.erase(element);
1067     }
1068     if (fPtr) {
1069       free(fPtr);
1070     }
1071     fPtr=NULL;
1072     fSize=0;
1073   }
1074 }
1075
1076 AliHLTDataBuffer::AliHLTRawBuffer* AliHLTDataBuffer::AliHLTRawPage::Alloc(AliHLTUInt32_t size)
1077 {
1078   /// alloc a buffer of specified size
1079   if (fFreeBuffers.size()==0) return NULL;
1080   
1081   for (AliHLTRawBufferPList::iterator iter=fFreeBuffers.begin();
1082        iter!=fFreeBuffers.end();
1083        iter++) {
1084     if ((*iter)->GetTotalSize()==size) {
1085       AliHLTRawBuffer* thisbuffer=*iter;
1086       fFreeBuffers.erase(iter);
1087       fUsedBuffers.push_back(thisbuffer);
1088       return thisbuffer;
1089     } else if ((*iter)->GetTotalSize()>size) {
1090       AliHLTRawBuffer* thisbuffer=*iter;
1091       AliHLTRawBuffer* newbuffer=thisbuffer->Split(size);
1092       if (newbuffer) {
1093         *iter=newbuffer;
1094         fUsedBuffers.push_back(thisbuffer);
1095         return thisbuffer;
1096       } else {
1097         HLTWarning("failed to alloc raw buffer: cannot split raw buffer %p of size %d (used %d) at size %d", *iter, (*iter)->GetTotalSize(), (*iter)->GetUsedSize(), size);
1098       }
1099     }
1100   }
1101   return NULL;
1102 }
1103
1104 int AliHLTDataBuffer::AliHLTRawPage::Free(AliHLTRawBuffer* pBuffer)
1105 {
1106   /// free a buffer and merge consecutive free buffers
1107   int iResult=0;
1108   for (AliHLTRawBufferPList::iterator iter=fUsedBuffers.begin();
1109        iter!=fUsedBuffers.end() && iResult>=0;
1110        iter++) {
1111     if ((*iter)==pBuffer) {
1112       fUsedBuffers.erase(iter);
1113       AliHLTRawBufferPList::iterator prev=fFreeBuffers.begin();
1114       for (; prev!=fFreeBuffers.end() && iResult>=0; prev++) {
1115         if ((*pBuffer)<(*(*prev)) ||
1116             ((*prev)->GetTotalSize()==0 && pBuffer->GetPointer()<=(*prev)->GetPointer() && (*prev)->GetPointer()<=pBuffer->GetPointer()+pBuffer->GetTotalSize())) {
1117           // check consecutive buffers
1118           if ((*(*prev)) == (pBuffer->GetPointer()+pBuffer->GetTotalSize()) ||
1119               ((*prev)->GetTotalSize()==0 && pBuffer->GetPointer()<=(*prev)->GetPointer() && (*prev)->GetPointer()<=pBuffer->GetPointer()+pBuffer->GetTotalSize())) {
1120             // the buffer to be released has a consecutive free buffer -> merge them
1121             if ((iResult=pBuffer->Merge(*(*prev)))>=0) {
1122               delete *prev;
1123               *prev=pBuffer;
1124             } else {
1125               HLTError("failed to merge consecutive/overlapping buffers %p and %p", pBuffer, (*prev));
1126               pBuffer->Print("");
1127               (*prev)->Print("");
1128             }
1129             break;
1130           }
1131           fFreeBuffers.insert(prev, pBuffer);
1132           break;
1133         }
1134         if ((*pBuffer)>(*(*prev)) ||
1135             (pBuffer->GetTotalSize()==0 && (*prev)->GetPointer()<=pBuffer->GetPointer() && pBuffer->GetPointer()<=(*prev)->GetPointer()+(*prev)->GetTotalSize())) {
1136           // check consecutive buffers
1137           if ((*pBuffer) == ((*prev)->GetPointer()+(*prev)->GetTotalSize())||
1138               (pBuffer->GetTotalSize()==0 && (*prev)->GetPointer()<=pBuffer->GetPointer() && pBuffer->GetPointer()<=(*prev)->GetPointer()+(*prev)->GetTotalSize())) {
1139             // the buffer to be released is consecutive to a free buffer -> merge them
1140             if ((iResult=pBuffer->Merge(*(*prev)))>=0) {
1141               AliHLTRawBufferPList::iterator succ=prev+1;
1142               delete *prev;
1143               *prev=pBuffer;
1144               // check if the buffer and the following one are consecutive
1145               if (succ!=fFreeBuffers.end() &&
1146                   (*(*succ)) == (pBuffer->GetPointer()+pBuffer->GetTotalSize())) {
1147                 if ((iResult=pBuffer->Merge(*(*succ)))>=0) {
1148                   delete *succ;
1149                   fFreeBuffers.erase(succ);
1150                 }
1151               }
1152             }
1153             break;
1154           }
1155         }
1156       }
1157       if (prev==fFreeBuffers.end()) {
1158         fFreeBuffers.push_back(pBuffer);
1159       }
1160
1161       // merge consecutive free buffers
1162       prev=fFreeBuffers.begin();
1163       for (AliHLTRawBufferPList::iterator current=prev+1; current!=fFreeBuffers.end() && iResult>=0; ) {
1164         // check if the buffer is embedded into the previous one
1165         if ((*current)->GetTotalSize()==0 && (*prev)->GetPointer()<=(*current)->GetPointer() && (*current)->GetPointer()<(*prev)->GetPointer()+(*prev)->GetTotalSize())  {
1166           if ((iResult=(*prev)->Merge(*(*current)))>=0) {
1167             current=fFreeBuffers.erase(current);
1168             continue;
1169           } else {
1170             HLTError("failed to merge embedded zero length buffer into preceeding buffer");
1171             Print("");
1172           }
1173         }
1174         // check if the buffer is consecutive to the previous one
1175         if ((*(*current)) == ((*prev)->GetPointer()+(*prev)->GetTotalSize())) {
1176           if ((iResult=(*prev)->Merge(*(*current)))>=0) {
1177             current=fFreeBuffers.erase(current);
1178             continue;
1179           } else {
1180             HLTError("failed to merge consecutive free buffers");
1181             Print("");
1182           }
1183         }
1184         prev=current++;
1185       }
1186
1187       // buffer was part of this page
1188       return 0;
1189     }
1190   }
1191   // buffer not found in this page
1192   return 1;
1193 }
1194
1195 int AliHLTDataBuffer::AliHLTRawPage::SetSize(const AliHLTDataBuffer::AliHLTRawBuffer* pBuffer, AliHLTUInt32_t size)
1196 {
1197   /// set the size of a raw buffer and release the remaining part
1198   int iResult=0;
1199   for (AliHLTRawBufferPList::iterator iter=fUsedBuffers.begin();
1200        iter!=fUsedBuffers.end() && iResult>=0;
1201        iter++) {
1202     if ((*iter)==pBuffer) {      // buffer was part of this page
1203       if ((*iter)->GetTotalSize()==size) return 0;
1204       if ((*iter)->GetTotalSize()<size) {
1205         HLTError("%d exceeds total size of buffer %p (%d used %d)\n", size, *iter, (*iter)->GetTotalSize(), (*iter)->GetUsedSize());
1206         return -ENOSPC;
1207       }
1208       AliHLTDataBuffer::AliHLTRawBuffer* freespace=(*iter)->Split(size);
1209       if (freespace) {
1210         fUsedBuffers.push_back(freespace);
1211         Free(freespace);
1212       } else {
1213         HLTWarning("failed to relase unused memory: cannot split raw buffer %p of size %d (used %d) at size %d", *iter, (*iter)->GetTotalSize(), (*iter)->GetUsedSize(), size);
1214       }
1215       return 0;
1216     }
1217   }
1218   // buffer not found in this page
1219   return 1;
1220 }
1221
1222 bool AliHLTDataBuffer::AliHLTRawPage::HasBuffer(const AliHLTDataBuffer::AliHLTRawBuffer* pBuffer)
1223 {
1224   /// check if the buffer is in this page
1225   for (AliHLTRawBufferPList::iterator iter=fUsedBuffers.begin();
1226        iter!=fUsedBuffers.end();
1227        iter++) {
1228     if ((*iter)==pBuffer) {      // buffer was part of this page
1229       return true;
1230     }
1231   }
1232   // buffer not found in this page
1233   return false;
1234 }
1235
1236 AliHLTUInt32_t AliHLTDataBuffer::AliHLTRawPage::Capacity() const 
1237 {
1238   /// get max available contiguous buffer
1239   AliHLTUInt32_t capacity=0;
1240   for (unsigned i=0; i<fFreeBuffers.size(); i++) {
1241     if (fFreeBuffers[i]->GetTotalSize()>capacity) 
1242       capacity=fFreeBuffers[i]->GetTotalSize();
1243   }
1244   return capacity;
1245 }
1246
1247 void AliHLTDataBuffer::AliHLTRawPage::Print(const char* option)
1248 {
1249   /// print page information
1250   if (strcmp(option, "global")==0) {
1251     cout << "number of global pages: " << fgGlobalPages.size() << endl;
1252     for (AliHLTRawPage* rawpage=NextPage(NULL);
1253          rawpage!=NULL; 
1254          rawpage=NextPage(rawpage)) {
1255       rawpage->Print("");
1256     }
1257     return;
1258   }
1259   cout << "************* AliHLTRawPage status ***********" << endl;
1260   cout << "  instance " << this << endl;
1261   printf("  buffer %p  size %d", fPtr, fSize);
1262   cout << "  used buffers: " << fUsedBuffers.size() << endl;
1263   AliHLTRawBufferPList::iterator iter=fUsedBuffers.begin();
1264   for (; iter!=fUsedBuffers.end(); iter++) {
1265     cout << "  "; (*iter)->Print("min");
1266   }
1267   cout << "  free buffers: " << fFreeBuffers.size() << endl;
1268   iter=fFreeBuffers.begin();
1269   for (; iter!=fFreeBuffers.end(); iter++) {
1270     cout << "  "; (*iter)->Print("min");
1271   }
1272 }
1273
1274
1275 vector<AliHLTDataBuffer::AliHLTRawPage*> AliHLTDataBuffer::AliHLTRawPage::fgGlobalPages;
1276
1277 AliHLTUInt32_t AliHLTDataBuffer::AliHLTRawPage::fgGlobalPageSize=50*1024*1024;
1278
1279 AliHLTDataBuffer::AliHLTRawBuffer* AliHLTDataBuffer::AliHLTRawPage::GlobalAlloc(AliHLTUInt32_t size, int verbosity)
1280 {
1281   // alloc a buffer of specified size from the global pages
1282   AliHLTDataBuffer::AliHLTRawBuffer* rawbuffer=NULL;
1283   vector<AliHLTDataBuffer::AliHLTRawPage*>::iterator page=fgGlobalPages.begin();
1284   AliHLTLogging log;
1285   for (page=fgGlobalPages.begin();page!=fgGlobalPages.end(); page++) {
1286     if ((rawbuffer=(*page)->Alloc(size))!=NULL) {
1287       if (verbosity>1) {
1288         log.Logging(kHLTLogInfo, "AliHLTDataBuffer::AliHLTRawPage::GlobalAlloc", "data buffer handling", "allocated raw buffer %p from page %p\n", rawbuffer, *page);
1289         rawbuffer->Print("min");
1290       }
1291       break;
1292     }
1293   }
1294   if (!rawbuffer) {
1295     AliHLTUInt32_t rawPageSize=fgGlobalPageSize;
1296     if (rawPageSize<size) {
1297       if (rawPageSize*10<size) {
1298         log.Logging(kHLTLogError, "AliHLTDataBuffer::AliHLTRawPage::GlobalAlloc", "data buffer handling", "refusing to allocate buffer of size %d", size);
1299         return NULL;
1300       }
1301       rawPageSize=size;
1302     }
1303     AliHLTDataBuffer::AliHLTRawPage* rawpage=new AliHLTDataBuffer::AliHLTRawPage(rawPageSize);
1304     if (!rawpage) {
1305       log.Logging(kHLTLogError, "AliHLTDataBuffer::AliHLTRawPage::GlobalAlloc", "data buffer handling", "can not create raw page");
1306       return NULL;
1307     }
1308     fgGlobalPages.push_back(rawpage);
1309     if ((rawbuffer=rawpage->Alloc(size))!=NULL) {
1310       if (verbosity>1) {
1311         log.Logging(kHLTLogInfo, "AliHLTDataBuffer::AliHLTRawPage::GlobalAlloc", "data buffer handling", "allocated raw buffer %p from page %p\n", rawbuffer, rawpage);
1312         rawbuffer->Print("min");
1313       }
1314     }
1315   }
1316
1317   return rawbuffer;
1318 }
1319
1320 AliHLTDataBuffer::AliHLTRawPage* AliHLTDataBuffer::AliHLTRawPage::FindPage(AliHLTDataBuffer::AliHLTRawBuffer* buffer)
1321 {
1322   // find buffer in the global pages
1323   vector<AliHLTDataBuffer::AliHLTRawPage*>::iterator page=fgGlobalPages.begin();
1324   for (; page!=fgGlobalPages.end(); page++) {
1325     if ((*page)->HasBuffer(buffer)) {
1326       return *page;
1327     }
1328   }
1329
1330   return NULL;
1331 }
1332
1333 int AliHLTDataBuffer::AliHLTRawPage::GlobalClean()
1334 {
1335   // cleanup the global pages */
1336   vector<AliHLTDataBuffer::AliHLTRawPage*>::iterator page=fgGlobalPages.begin();
1337   while (page!=fgGlobalPages.end()) {
1338     if (!(*page)->IsUsed()) {
1339       delete *page;
1340       page=fgGlobalPages.erase(page);
1341       continue;
1342     }
1343     AliHLTLogging log;
1344     log.Logging(kHLTLogError, "AliHLTDataBuffer::AliHLTRawPage::GlobalClean", "data buffer handling", "HLT memory page still in use, skipping cleanup, potential memory leak");
1345     
1346     page++;
1347   }
1348   
1349   return 0;
1350 }
1351
1352 AliHLTDataBuffer::AliHLTRawPage* AliHLTDataBuffer::AliHLTRawPage::NextPage(const AliHLTDataBuffer::AliHLTRawPage* prev)
1353 {
1354   // get next global page
1355   vector<AliHLTDataBuffer::AliHLTRawPage*>::iterator page=fgGlobalPages.begin();
1356   for (; page!=fgGlobalPages.end(); page++) {
1357     if (prev==NULL) return *page;
1358     if (*page!=prev) continue;
1359     if (++page!=fgGlobalPages.end()) return *page;
1360     break;
1361   }
1362   return NULL;
1363 }