Project
Loading...
Searching...
No Matches
GPUReconstruction.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
14
15#include <cstring>
16#include <cstdio>
17#include <iostream>
18#include <mutex>
19#include <string>
20#include <map>
21#include <queue>
22#include <mutex>
23#include <condition_variable>
24#include <array>
25
26#include "GPUReconstruction.h"
29#include "GPUReconstructionIO.h"
30#include "GPUROOTDumpCore.h"
31#include "GPUConfigDump.h"
32#include "GPUChainTracking.h"
33#include "GPUConstantMem.h"
34#include "GPUCommonHelpers.h"
35#include "GPUSettings.h"
36
37#include "GPUMemoryResource.h"
38#include "GPUChain.h"
40
41#include "GPULogging.h"
42#include "utils/strtag.h"
43#include "utils/stdspinlock.h"
44
45#ifdef GPUCA_O2_LIB
47#endif
48
50
51namespace o2::gpu
52{
53namespace // anonymous
54{
55struct GPUReconstructionPipelineQueue {
56 uint32_t op = 0; // For now, 0 = process, 1 = terminate
57 GPUChain* chain = nullptr;
58 std::mutex m;
59 std::condition_variable c;
60 bool done = false;
61 int32_t retVal = 0;
62};
63} // namespace
64
66 std::queue<GPUReconstructionPipelineQueue*> queue;
67 std::mutex mutex;
68 std::condition_variable cond;
69 bool terminate = false;
70};
71} // namespace o2::gpu
72
73using namespace o2::gpu;
74
75constexpr const char* const GPUReconstruction::GEOMETRY_TYPE_NAMES[];
76constexpr const char* const GPUReconstruction::IOTYPENAMES[];
78
79static ptrdiff_t ptrDiff(void* a, void* b) { return (char*)a - (char*)b; }
80
81GPUReconstruction::GPUReconstruction(const GPUSettingsDeviceBackend& cfg) : mHostConstantMem(new GPUConstantMem), mGRPSettings(new GPUSettingsGRP), mDeviceBackendSettings(new GPUSettingsDeviceBackend(cfg)), mProcessingSettings(new GPUSettingsProcessing)
82{
83 if (cfg.master) {
85 throw std::invalid_argument("device type of master and slave GPUReconstruction does not match");
86 }
87 if (cfg.master->mMaster) {
88 throw std::invalid_argument("Cannot be slave to a slave");
89 }
90 mMaster = cfg.master;
91 mSlaveId = cfg.master->mSlaves.size();
92 cfg.master->mSlaves.emplace_back(this);
93 }
96 for (uint32_t i = 0; i < NSECTORS; i++) {
97 processors()->tpcTrackers[i].SetSector(i); // TODO: Move to a better place
99#ifdef GPUCA_HAS_ONNX
100 processors()->tpcNNClusterer[i].mISector = i;
101#endif
102 }
103#ifndef GPUCA_NO_ROOT
104 mROOTDump = GPUROOTDumpCore::getAndCreate();
105#endif
106}
107
109{
110 if (mInitialized) {
111 GPUError("GPU Reconstruction not properly deinitialized!");
112 }
113}
114
115void GPUReconstruction::GetITSTraits(std::unique_ptr<o2::its::TrackerTraits<7>>* trackerTraits, std::unique_ptr<o2::its::VertexerTraits<7>>* vertexerTraits, std::unique_ptr<o2::its::TimeFrame<7>>* timeFrame)
116{
117 if (trackerTraits) {
118 trackerTraits->reset(new o2::its::TrackerTraits<7>);
119 }
120 if (vertexerTraits) {
121 vertexerTraits->reset(new o2::its::VertexerTraits<7>);
122 }
123 if (timeFrame) {
124 timeFrame->reset(new o2::its::TimeFrame<7>);
125 }
126}
127
129{
130 return std::max<int32_t>(0, tbb::this_task_arena::current_thread_index());
131}
132
134{
135 if (mMaster) {
136 throw std::runtime_error("Must not call init on slave!");
137 }
138 int32_t retVal = InitPhaseBeforeDevice();
139 if (retVal) {
140 return retVal;
141 }
142 for (uint32_t i = 0; i < mSlaves.size(); i++) {
143 retVal = mSlaves[i]->InitPhaseBeforeDevice();
144 if (retVal) {
145 GPUError("Error initialization slave (before deviceinit)");
146 return retVal;
147 }
148 mNStreams = std::max(mNStreams, mSlaves[i]->mNStreams);
151 }
152 if (InitDevice()) {
153 return 1;
154 }
155 if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_GLOBAL) {
158 } else {
160 }
162 return 1;
163 }
164 for (uint32_t i = 0; i < mSlaves.size(); i++) {
165 mSlaves[i]->mDeviceMemoryBase = mDeviceMemoryPermanent;
166 mSlaves[i]->mHostMemoryBase = mHostMemoryPermanent;
167 mSlaves[i]->mDeviceMemorySize = mDeviceMemorySize - ptrDiff(mSlaves[i]->mDeviceMemoryBase, mDeviceMemoryBase);
168 mSlaves[i]->mHostMemorySize = mHostMemorySize - ptrDiff(mSlaves[i]->mHostMemoryBase, mHostMemoryBase);
169 mSlaves[i]->mHostMemoryPoolEnd = mHostMemoryPoolEnd;
170 mSlaves[i]->mDeviceMemoryPoolEnd = mDeviceMemoryPoolEnd;
171 if (mSlaves[i]->InitDevice()) {
172 GPUError("Error initialization slave (deviceinit)");
173 return 1;
174 }
176 GPUError("Error initialization slave (permanent memory)");
177 return 1;
178 }
179 mDeviceMemoryPermanent = mSlaves[i]->mDeviceMemoryPermanent;
180 mHostMemoryPermanent = mSlaves[i]->mHostMemoryPermanent;
181 }
183 if (retVal) {
184 return retVal;
185 }
187 for (uint32_t i = 0; i < mSlaves.size(); i++) {
188 mSlaves[i]->mDeviceMemoryPermanent = mDeviceMemoryPermanent;
189 mSlaves[i]->mHostMemoryPermanent = mHostMemoryPermanent;
190 retVal = mSlaves[i]->InitPhaseAfterDevice();
191 if (retVal) {
192 GPUError("Error initialization slave (after device init)");
193 return retVal;
194 }
195 mSlaves[i]->ClearAllocatedMemory();
196 }
197 debugInit();
198 return 0;
199}
200
201namespace o2::gpu::internal
202{
203static uint32_t getDefaultNThreads()
204{
205 const char* tbbEnv = getenv("TBB_NUM_THREADS");
206 uint32_t tbbNum = tbbEnv ? atoi(tbbEnv) : 0;
207 if (tbbNum) {
208 return tbbNum;
209 }
210 const char* ompEnv = getenv("OMP_NUM_THREADS");
211 uint32_t ompNum = ompEnv ? atoi(ompEnv) : 0;
212 if (ompNum) {
213 return ompNum;
214 }
215 return tbb::info::default_concurrency();
216}
217} // namespace o2::gpu::internal
218
220{
221 if (GetProcessingSettings().printSettings) {
222 if (mSlaves.size() || mMaster) {
223 printf("\nConfig Dump %s\n", mMaster ? "Slave" : "Master");
224 }
225 const GPUChainTracking* chTrk;
226 for (uint32_t i = 0; i < mChains.size(); i++) {
227 if ((chTrk = dynamic_cast<GPUChainTracking*>(mChains[i].get()))) {
228 break;
229 }
230 }
231 GPUConfigDump::dumpConfig(&param().rec, mProcessingSettings.get(), chTrk ? chTrk->GetQAConfig() : nullptr, chTrk ? chTrk->GetEventDisplayConfig() : nullptr, mDeviceBackendSettings.get(), &mRecoSteps);
232 }
235 if (!IsGPU()) {
236 mRecoSteps.stepsGPUMask.set((uint8_t)0);
237 }
238
239 if (GetProcessingSettings().forceMemoryPoolSize >= 1024 || GetProcessingSettings().forceHostMemoryPoolSize >= 1024) {
241 }
242 if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_AUTO) {
244 }
245 if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_INDIVIDUAL) {
246 mProcessingSettings->forceMemoryPoolSize = mProcessingSettings->forceHostMemoryPoolSize = 0;
247 }
248 if (GetProcessingSettings().debugLevel >= 4) {
249 mProcessingSettings->keepAllMemory = true;
250 }
251 if (GetProcessingSettings().debugLevel >= 5 && GetProcessingSettings().allocDebugLevel < 2) {
252 mProcessingSettings->allocDebugLevel = 2;
253 }
255 mProcessingSettings->keepDisplayMemory = true;
256 }
257 if (GetProcessingSettings().debugLevel < 6) {
258 mProcessingSettings->debugMask = 0;
259 }
260 if (GetProcessingSettings().debugLevel < 1) {
261 mProcessingSettings->deviceTimers = false;
262 }
263 if (GetProcessingSettings().debugLevel > 0) {
264 mProcessingSettings->recoTaskTiming = true;
265 }
266 if (GetProcessingSettings().deterministicGPUReconstruction == -1) {
267 mProcessingSettings->deterministicGPUReconstruction = GetProcessingSettings().debugLevel >= 6;
268 }
269 if (GetProcessingSettings().deterministicGPUReconstruction) {
270#ifndef GPUCA_DETERMINISTIC_MODE
271 GPUError("WARNING, deterministicGPUReconstruction needs GPUCA_DETERMINISTIC_MODE for being fully deterministic, without only most indeterminism by concurrency is removed, but floating point effects remain!");
272#endif
273 if (mProcessingSettings->debugLevel >= 6 && ((mProcessingSettings->debugMask + 1) & mProcessingSettings->debugMask)) {
274 GPUError("WARNING: debugMask %d - debug output might not be deterministic with intermediate steps missing", mProcessingSettings->debugMask);
275 }
276 mProcessingSettings->overrideClusterizerFragmentLen = TPC_MAX_FRAGMENT_LEN_GPU;
277 if (GetProcessingSettings().createO2Output > 1) {
278 mProcessingSettings->createO2Output = 1;
279 }
280 mProcessingSettings->rtc.deterministic = 1;
281 } else {
282#ifdef GPUCA_DETERMINISTIC_MODE
283 GPUError("WARNING, compiled with GPUCA_DETERMINISTIC_MODE but deterministicGPUReconstruction not set, only compile-time determinism and deterministic math enforced, not fully deterministic!");
284#endif
285 }
286 if (GetProcessingSettings().deterministicGPUReconstruction && GetProcessingSettings().debugLevel >= 6) {
287 mProcessingSettings->nTPCClustererLanes = 1;
288 }
289 if (GetProcessingSettings().createO2Output > 1 && GetProcessingSettings().runQA && GetProcessingSettings().qcRunFraction == 100.f) {
290 mProcessingSettings->createO2Output = 1;
291 }
292 if (!GetProcessingSettings().createO2Output || !IsGPU()) {
293 mProcessingSettings->clearO2OutputFromGPU = false;
294 }
296 mProcessingSettings->mergerSortTracks = false;
297 }
298 if (GetProcessingSettings().debugLevel > 3 || !IsGPU() || GetProcessingSettings().deterministicGPUReconstruction) {
299 mProcessingSettings->delayedOutput = false;
300 }
301 if (!GetProcessingSettings().rtc.enable) {
302 mProcessingSettings->rtc.optConstexpr = false;
303 }
304 if (GetProcessingSettings().allSanityChecks) {
305 mProcessingSettings->clusterizerZSSanityCheck = mProcessingSettings->mergerSanityCheck = mProcessingSettings->outputSanityCheck = true;
306 }
307
308 mMemoryScalers->scalingFactor = GetProcessingSettings().memoryScalingFactor;
309 mMemoryScalers->conservative = GetProcessingSettings().conservativeMemoryEstimate;
310 mMemoryScalers->returnMaxVal = GetProcessingSettings().forceMaxMemScalers != 0;
311 if (GetProcessingSettings().forceMaxMemScalers > 1) {
312 mMemoryScalers->rescaleMaxMem(GetProcessingSettings().forceMaxMemScalers);
313 }
314
315 if (GetProcessingSettings().nHostThreads != -1 && GetProcessingSettings().ompThreads != -1) {
316 GPUFatal("Must not use both nHostThreads and ompThreads at the same time!");
317 } else if (GetProcessingSettings().ompThreads != -1) {
318 mProcessingSettings->nHostThreads = GetProcessingSettings().ompThreads;
319 GPUWarning("You are using the deprecated ompThreads option, please switch to nHostThreads!");
320 }
321
322 if (GetProcessingSettings().nHostThreads <= 0) {
323 mProcessingSettings->nHostThreads = internal::getDefaultNThreads();
324 } else {
325 mProcessingSettings->autoAdjustHostThreads = false;
326 }
327 mMaxHostThreads = GetProcessingSettings().nHostThreads;
328 if (mMaster == nullptr) {
329 mThreading = std::make_shared<GPUReconstructionThreading>();
330 mThreading->control = std::make_unique<tbb::global_control>(tbb::global_control::max_allowed_parallelism, mMaxHostThreads);
331 mThreading->allThreads = std::make_unique<tbb::task_arena>(mMaxHostThreads);
332 mThreading->activeThreads = std::make_unique<tbb::task_arena>(mMaxHostThreads);
333 } else {
335 }
337 if (IsGPU()) {
338 mNStreams = std::max<int32_t>(GetProcessingSettings().nStreams, 3);
339 }
340
341 if (GetProcessingSettings().nTPCClustererLanes == -1) {
342 mProcessingSettings->nTPCClustererLanes = (GetRecoStepsGPU() & RecoStep::TPCClusterFinding) ? 3 : std::max<int32_t>(1, std::min<int32_t>(GPUCA_NSECTORS, GetProcessingSettings().inKernelParallel ? (mMaxHostThreads >= 4 ? std::min<int32_t>(mMaxHostThreads / 2, mMaxHostThreads >= 32 ? GPUCA_NSECTORS : 4) : 1) : mMaxHostThreads));
343 }
344 if (GetProcessingSettings().overrideClusterizerFragmentLen == -1) {
345 mProcessingSettings->overrideClusterizerFragmentLen = ((GetRecoStepsGPU() & RecoStep::TPCClusterFinding) || (mMaxHostThreads / GetProcessingSettings().nTPCClustererLanes >= 3)) ? TPC_MAX_FRAGMENT_LEN_GPU : TPC_MAX_FRAGMENT_LEN_HOST;
346 }
347 if (GetProcessingSettings().nTPCClustererLanes > GPUCA_NSECTORS) {
348 GPUError("Invalid value for nTPCClustererLanes: %d", GetProcessingSettings().nTPCClustererLanes);
349 mProcessingSettings->nTPCClustererLanes = GPUCA_NSECTORS;
350 }
351
352 if (GetProcessingSettings().doublePipeline) {
353 mProcessingSettings->rtctech.allowOptimizedSlaveReconstruction = true;
354 }
355 if (GetProcessingSettings().doublePipeline && (mChains.size() != 1 || mChains[0]->SupportsDoublePipeline() == false || !IsGPU() || GetProcessingSettings().memoryAllocationStrategy != GPUMemoryResource::ALLOCATION_GLOBAL)) {
356 GPUError("Must use double pipeline mode only with exactly one chain that must support it");
357 return 1;
358 }
359 if (mMaster == nullptr && GetProcessingSettings().doublePipeline) {
361 }
362
363 if (mMaster && GetProcessingSettings().rtc.enable && (GetProcessingSettings().rtc.optConstexpr || GetProcessingSettings().rtc.optSpecialCode) && !GetProcessingSettings().rtctech.allowOptimizedSlaveReconstruction) {
364 GPUError("Not allowed to create optimized RTC code with more than one GPUReconstruction instances");
365 return 1;
366 }
367
369 for (uint32_t i = 0; i < mChains.size(); i++) {
370 if (mChains[i]->EarlyConfigure()) {
371 return 1;
372 }
373 mChains[i]->RegisterPermanentMemoryAndProcessors();
374 size_t memPrimary, memPageLocked;
375 mChains[i]->MemorySize(memPrimary, memPageLocked);
376 if (!IsGPU() || mOutputControl.useInternal()) {
377 memPageLocked = memPrimary;
378 }
379 mDeviceMemorySize += memPrimary;
380 mHostMemorySize += memPageLocked;
381 }
382 if (GetProcessingSettings().forceMemoryPoolSize && GetProcessingSettings().forceMemoryPoolSize <= 2 && CanQueryMaxMemory()) {
383 mDeviceMemorySize = GetProcessingSettings().forceMemoryPoolSize;
384 } else if (GetProcessingSettings().forceMemoryPoolSize > 2) {
385 mDeviceMemorySize = GetProcessingSettings().forceMemoryPoolSize;
386 if (!IsGPU() || mOutputControl.useInternal()) {
388 }
389 }
390 if (GetProcessingSettings().forceHostMemoryPoolSize) {
391 mHostMemorySize = GetProcessingSettings().forceHostMemoryPoolSize;
392 }
393
394 for (uint32_t i = 0; i < mProcessors.size(); i++) {
395 (mProcessors[i].proc->*(mProcessors[i].RegisterMemoryAllocation))();
396 }
397
398 return 0;
399}
400
402{
403 if (IsGPU()) {
404 for (uint32_t i = 0; i < mChains.size(); i++) {
405 mChains[i]->RegisterGPUProcessors();
406 }
407 }
409 return 0;
410}
411
413{
414 if (GetProcessingSettings().forceMaxMemScalers <= 1 && GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_GLOBAL) {
416 }
417 for (uint32_t i = 0; i < mChains.size(); i++) {
418 if (mChains[i]->Init()) {
419 return 1;
420 }
421 }
422 for (uint32_t i = 0; i < mProcessors.size(); i++) {
423 (mProcessors[i].proc->*(mProcessors[i].InitializeProcessor))();
424 }
425
426 WriteConstantParams(); // Initialize with initial values, can optionally be updated later
427
428 mInitialized = true;
429 return 0;
430}
431
433{
434 if (IsGPU()) {
435 const auto threadContext = GetThreadContext();
436 WriteToConstantMemory(ptrDiff(&processors()->param, processors()), &param(), sizeof(param()), -1);
437 }
438}
439
441{
442 for (uint32_t i = 0; i < mChains.size(); i++) {
443 mChains[i]->Finalize();
444 }
445 return 0;
446}
447
449{
450 if (!mInitialized) {
451 return 1;
452 }
453 for (uint32_t i = 0; i < mSlaves.size(); i++) {
454 if (mSlaves[i]->Exit()) {
455 GPUError("Error exiting slave");
456 }
457 }
458
459 mChains.clear(); // Make sure we destroy a possible ITS GPU tracker before we call the destructors
460 mHostConstantMem.reset(); // Reset these explicitly before the destruction of other members unloads the library
461 if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_INDIVIDUAL) {
462 for (uint32_t i = 0; i < mMemoryResources.size(); i++) {
463 if (mMemoryResources[i].mReuse >= 0) {
464 continue;
465 }
466 operator delete(mMemoryResources[i].mPtrDevice, std::align_val_t(GPUCA_BUFFER_ALIGNMENT));
467 mMemoryResources[i].mPtr = mMemoryResources[i].mPtrDevice = nullptr;
468 }
469 }
470 mMemoryResources.clear();
471 if (mInitialized) {
472 ExitDevice();
473 }
474 debugExit();
475 mInitialized = false;
476 return 0;
477}
478
481
483{
484 for (auto it = mMemoryReuse1to1.begin(); it != mMemoryReuse1to1.end(); it++) {
485 auto& re = it->second;
486 if (proc == nullptr || re.proc == proc) {
487 GPUMemoryResource& resMain = mMemoryResources[re.res[0]];
488 resMain.mOverrideSize = 0;
489 for (uint32_t i = 0; i < re.res.size(); i++) {
491 resMain.mOverrideSize = std::max<size_t>(resMain.mOverrideSize, ptrDiff(res.SetPointers((void*)1), (char*)1));
492 }
493 }
494 }
495}
496
498{
500 if ((type & GPUMemoryResource::MEMORY_SCRATCH) && !GetProcessingSettings().keepDisplayMemory) { // keepAllMemory --> keepDisplayMemory
502 } else {
504 }
505 }
507 type &= ~GPUMemoryResource::MEMORY_GPU;
508 }
509 mMemoryResources.emplace_back(proc, setPtr, (GPUMemoryResource::MemoryType)type, name);
510 if (mMemoryResources.size() >= 32768) {
511 throw std::bad_alloc();
512 }
513 uint16_t retVal = mMemoryResources.size() - 1;
514 if (re.type != GPUMemoryReuse::NONE && !GetProcessingSettings().disableMemoryReuse) {
515 const auto& it = mMemoryReuse1to1.find(re.id);
516 if (it == mMemoryReuse1to1.end()) {
517 mMemoryReuse1to1[re.id] = {proc, retVal};
518 } else {
519 mMemoryResources[retVal].mReuse = it->second.res[0];
520 it->second.res.emplace_back(retVal);
521 }
522 }
523 return retVal;
524}
525
527{
528 if (GetProcessingSettings().debugLevel >= 5) {
529 GPUInfo("Allocating memory %p", (void*)proc);
530 }
531 size_t total = 0;
532 for (uint32_t i = 0; i < mMemoryResources.size(); i++) {
533 if (proc == nullptr ? !mMemoryResources[i].mProcessor->mAllocateAndInitializeLate : mMemoryResources[i].mProcessor == proc) {
535 total += AllocateRegisteredMemory(i);
536 } else if (resetCustom && (mMemoryResources[i].mPtr || mMemoryResources[i].mPtrDevice)) {
538 }
539 }
540 }
541 if (GetProcessingSettings().debugLevel >= 5) {
542 GPUInfo("Allocating memory done");
543 }
544 return total;
545}
546
548{
549 if (GetProcessingSettings().debugLevel >= 5) {
550 GPUInfo("Allocating Permanent Memory");
551 }
553 GPUError("Must not allocate permanent memory while volatile chunks are allocated");
554 throw std::bad_alloc();
555 }
556 int32_t total = 0;
557 for (uint32_t i = 0; i < mMemoryResources.size(); i++) {
558 if ((mMemoryResources[i].mType & GPUMemoryResource::MEMORY_PERMANENT) && mMemoryResources[i].mPtr == nullptr) {
559 total += AllocateRegisteredMemory(i);
560 }
561 }
564 if (GetProcessingSettings().debugLevel >= 5) {
565 GPUInfo("Permanent Memory Done");
566 }
567 return total;
568}
569
570size_t GPUReconstruction::AllocateRegisteredMemoryHelper(GPUMemoryResource* res, void*& ptr, void*& memorypool, void* memorybase, size_t memorysize, void* (GPUMemoryResource::*setPtr)(void*), void*& memorypoolend, const char* device)
571{
572 if (res->mReuse >= 0) {
573 ptr = (&ptr == &res->mPtrDevice) ? mMemoryResources[res->mReuse].mPtrDevice : mMemoryResources[res->mReuse].mPtr;
574 if (ptr == nullptr) {
575 GPUError("Invalid reuse ptr (%s)", res->mName);
576 throw std::bad_alloc();
577 }
578 size_t retVal = ptrDiff((res->*setPtr)(ptr), ptr);
579 if (retVal > mMemoryResources[res->mReuse].mSize) {
580 GPUError("Insufficient reuse memory %lu < %lu (%s) (%s)", mMemoryResources[res->mReuse].mSize, retVal, res->mName, device);
581 throw std::bad_alloc();
582 }
583 if (GetProcessingSettings().allocDebugLevel >= 2) {
584 std::cout << "Reused (" << device << ") " << res->mName << ": " << retVal << "\n";
585 }
586 return retVal;
587 }
588 if (memorypool == nullptr) {
589 GPUError("Cannot allocate memory from uninitialized pool");
590 throw std::bad_alloc();
591 }
592 size_t retVal;
593 stdspinlock spinlock(mMemoryMutex);
594 if ((res->mType & GPUMemoryResource::MEMORY_STACK) && memorypoolend) {
595 retVal = ptrDiff((res->*setPtr)((char*)1), (char*)(1));
596 memorypoolend = (void*)((char*)memorypoolend - GPUProcessor::getAlignmentMod<GPUCA_MEMALIGN>(memorypoolend));
597 if (retVal < res->mOverrideSize) {
598 retVal = res->mOverrideSize;
599 }
600 retVal += GPUProcessor::getAlignment<GPUCA_MEMALIGN>(retVal);
601 memorypoolend = (char*)memorypoolend - retVal;
602 ptr = memorypoolend;
603 retVal = std::max<size_t>(ptrDiff((res->*setPtr)(ptr), ptr), res->mOverrideSize);
604 } else {
605 ptr = memorypool;
606 memorypool = (char*)((res->*setPtr)(ptr));
607 retVal = ptrDiff(memorypool, ptr);
608 if (retVal < res->mOverrideSize) {
609 retVal = res->mOverrideSize;
610 memorypool = (char*)ptr + res->mOverrideSize;
611 }
612 memorypool = (void*)((char*)memorypool + GPUProcessor::getAlignment<GPUCA_MEMALIGN>(memorypool));
613 }
614 if (memorypoolend ? (memorypool > memorypoolend) : ((size_t)ptrDiff(memorypool, memorybase) > memorysize)) {
615 std::cerr << "Memory pool size exceeded (" << device << ") (" << res->mName << ": " << (memorypoolend ? (memorysize + ptrDiff(memorypool, memorypoolend)) : ptrDiff(memorypool, memorybase)) << " > " << memorysize << "\n";
616 throw std::bad_alloc();
617 }
618 if (GetProcessingSettings().allocDebugLevel >= 2) {
619 std::cout << "Allocated (" << device << ") " << res->mName << ": " << retVal << " - available: " << (memorypoolend ? ptrDiff(memorypoolend, memorypool) : (memorysize - ptrDiff(memorypool, memorybase))) << "\n";
620 }
621 return retVal;
622}
623
625{
626 if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_INDIVIDUAL && (control == nullptr || control->useInternal())) {
627 if (!(res->mType & GPUMemoryResource::MEMORY_EXTERNAL)) {
628 if (res->mPtrDevice && res->mReuse < 0) {
629 operator delete(res->mPtrDevice, std::align_val_t(GPUCA_BUFFER_ALIGNMENT));
630 }
631 res->mSize = std::max((size_t)res->SetPointers((void*)1) - 1, res->mOverrideSize);
632 if (res->mReuse >= 0) {
633 if (res->mSize > mMemoryResources[res->mReuse].mSize) {
634 GPUError("Invalid reuse, insufficient size: %ld < %ld", (int64_t)mMemoryResources[res->mReuse].mSize, (int64_t)res->mSize);
635 throw std::bad_alloc();
636 }
637 res->mPtrDevice = mMemoryResources[res->mReuse].mPtrDevice;
638 } else {
639 res->mPtrDevice = operator new(res->mSize + GPUCA_BUFFER_ALIGNMENT, std::align_val_t(GPUCA_BUFFER_ALIGNMENT));
640 }
641 res->mPtr = GPUProcessor::alignPointer<GPUCA_BUFFER_ALIGNMENT>(res->mPtrDevice);
642 res->SetPointers(res->mPtr);
643 if (GetProcessingSettings().allocDebugLevel >= 2) {
644 std::cout << (res->mReuse >= 0 ? "Reused " : "Allocated ") << res->mName << ": " << res->mSize << " (individual" << ((res->mType & GPUMemoryResource::MEMORY_STACK) ? " stack" : "") << ")\n";
645 }
647 stdspinlock spinlock(mMemoryMutex);
649 }
650 if ((size_t)res->mPtr % GPUCA_BUFFER_ALIGNMENT) {
651 GPUError("Got buffer with insufficient alignment");
652 throw std::bad_alloc();
653 }
654 }
655 } else {
656 if (res->mPtr != nullptr) {
657 GPUError("Double allocation! (%s)", res->mName);
658 throw std::bad_alloc();
659 }
660 if (IsGPU() && res->mOverrideSize < GPUCA_BUFFER_ALIGNMENT) {
661 res->mOverrideSize = GPUCA_BUFFER_ALIGNMENT;
662 }
663 if ((!IsGPU() || (res->mType & GPUMemoryResource::MEMORY_HOST) || GetProcessingSettings().keepDisplayMemory) && !(res->mType & GPUMemoryResource::MEMORY_EXTERNAL)) { // keepAllMemory --> keepDisplayMemory
664 if (control && control->useExternal()) {
665 if (control->allocator) {
666 res->mSize = std::max((size_t)res->SetPointers((void*)1) - 1, res->mOverrideSize);
667 res->mPtr = control->allocator(CAMath::nextMultipleOf<GPUCA_BUFFER_ALIGNMENT>(res->mSize));
668 res->mSize = std::max<size_t>(ptrDiff(res->SetPointers(res->mPtr), res->mPtr), res->mOverrideSize);
669 if (GetProcessingSettings().allocDebugLevel >= 2) {
670 std::cout << "Allocated (from callback) " << res->mName << ": " << res->mSize << "\n";
671 }
672 } else {
673 void* dummy = nullptr;
674 res->mSize = AllocateRegisteredMemoryHelper(res, res->mPtr, control->ptrCurrent, control->ptrBase, control->size, &GPUMemoryResource::SetPointers, dummy, "host");
675 }
676 } else {
678 }
679 if ((size_t)res->mPtr % GPUCA_BUFFER_ALIGNMENT) {
680 GPUError("Got buffer with insufficient alignment");
681 throw std::bad_alloc();
682 }
683 }
684 if (IsGPU() && (res->mType & GPUMemoryResource::MEMORY_GPU)) {
685 if (res->mProcessor->mLinkedProcessor == nullptr) {
686 GPUError("Device Processor not set (%s)", res->mName);
687 throw std::bad_alloc();
688 }
690 GPUError("Must not allocate non-stacked device memory while volatile chunks are allocated");
691 throw std::bad_alloc();
692 }
694
696 res->mSize = size;
697 } else if (size != res->mSize) {
698 GPUError("Inconsistent device memory allocation (%s: device %lu vs %lu)", res->mName, size, res->mSize);
699 throw std::bad_alloc();
700 }
701 if ((size_t)res->mPtrDevice % GPUCA_BUFFER_ALIGNMENT) {
702 GPUError("Got buffer with insufficient alignment");
703 throw std::bad_alloc();
704 }
705 }
707 }
708}
709
714
716{
718 if ((res->mType & GPUMemoryResource::MEMORY_PERMANENT) && res->mPtr != nullptr) {
720 } else {
722 }
723 return res->mReuse >= 0 ? 0 : res->mSize;
724}
725
727{
728 stdspinlock spinlock(mMemoryMutex);
729 if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_INDIVIDUAL) {
730 char* retVal = new (std::align_val_t(GPUCA_BUFFER_ALIGNMENT)) char[size];
733 } else {
735 }
736 return retVal;
737 }
738
740 throw std::runtime_error("Requested invalid memory typo for direct allocation");
741 }
743 GPUError("Must not allocate direct memory while volatile chunks are allocated");
744 throw std::bad_alloc();
745 }
746
749 char* retVal;
751 poolend = (char*)poolend - size;
752 poolend = (char*)poolend - GPUProcessor::getAlignmentMod<GPUCA_MEMALIGN>(poolend);
753 retVal = (char*)poolend;
754 } else {
756 }
757 if (pool > poolend) {
758 GPUError("Insufficient unmanaged memory: missing %ld bytes", ptrDiff(pool, poolend));
759 throw std::bad_alloc();
760 }
762 if (GetProcessingSettings().allocDebugLevel >= 2) {
763 std::cout << "Allocated (unmanaged " << (type == GPUMemoryResource::MEMORY_GPU ? "gpu" : "host") << "): " << size << " - available: " << ptrDiff(poolend, pool) << "\n";
764 }
765 return retVal;
766}
767
769{
770 stdspinlock spinlock(mMemoryMutex);
771 if (mVolatileMemoryStart == nullptr) {
773 }
774 if (size == 0) {
775 return nullptr; // Future GPU memory allocation is volatile
776 }
777 char* retVal;
780 GPUError("Insufficient volatile device memory: missing %ld", ptrDiff(mDeviceMemoryPool, mDeviceMemoryPoolEnd));
781 throw std::bad_alloc();
782 }
784 if (GetProcessingSettings().allocDebugLevel >= 2) {
785 std::cout << "Allocated (volatile GPU): " << size << " - available: " << ptrDiff(mDeviceMemoryPoolEnd, mDeviceMemoryPool) << "\n";
786 }
787 return retVal;
788}
789
791{
792 if (device) {
794 }
795 char* retVal = new (std::align_val_t(GPUCA_BUFFER_ALIGNMENT)) char[size];
796 stdspinlock spinlock(mMemoryMutex);
797 mVolatileChunks.emplace_back(retVal, alignedDeleter());
798 return retVal;
799}
800
806
808{
812 mVolatileMemoryStart = nullptr;
813 }
814 if (GetProcessingSettings().allocDebugLevel >= 2) {
815 std::cout << "Freed (volatile GPU) - available: " << ptrDiff(mDeviceMemoryPoolEnd, mDeviceMemoryPool) << "\n";
816 }
817}
818
824
826{
827 for (uint32_t i = 0; i < mMemoryResources.size(); i++) {
828 if (proc == nullptr || mMemoryResources[i].mProcessor == proc) {
830 }
831 }
832}
833
835{
838 void* basePtr = res->mReuse >= 0 ? mMemoryResources[res->mReuse].mPtr : res->mPtr;
839 size_t size = ptrDiff(res->SetPointers(basePtr), basePtr);
840 if (basePtr && size > std::max(res->mSize, res->mOverrideSize)) {
841 std::cerr << "Updated pointers exceed available memory size: " << size << " > " << std::max(res->mSize, res->mOverrideSize) << " - host - " << res->mName << "\n";
842 throw std::bad_alloc();
843 }
844 }
845 if (IsGPU() && (res->mType & GPUMemoryResource::MEMORY_GPU)) {
846 void* basePtr = res->mReuse >= 0 ? mMemoryResources[res->mReuse].mPtrDevice : res->mPtrDevice;
847 size_t size = ptrDiff(res->SetDevicePointers(basePtr), basePtr);
848 if (basePtr && size > std::max(res->mSize, res->mOverrideSize)) {
849 std::cerr << "Updated pointers exceed available memory size: " << size << " > " << std::max(res->mSize, res->mOverrideSize) << " - GPU - " << res->mName << "\n";
850 throw std::bad_alloc();
851 }
852 }
853}
854
855void GPUReconstruction::FreeRegisteredMemory(GPUProcessor* proc, bool freeCustom, bool freePermanent)
856{
857 for (uint32_t i = 0; i < mMemoryResources.size(); i++) {
858 if ((proc == nullptr || mMemoryResources[i].mProcessor == proc) && (freeCustom || !(mMemoryResources[i].mType & GPUMemoryResource::MEMORY_CUSTOM)) && (freePermanent || !(mMemoryResources[i].mType & GPUMemoryResource::MEMORY_PERMANENT))) {
860 }
861 }
862}
863
868
870{
871 if (GetProcessingSettings().allocDebugLevel >= 2 && (res->mPtr || res->mPtrDevice)) {
872 std::cout << "Freeing " << res->mName << ": size " << res->mSize << " (reused " << res->mReuse << ")\n";
873 }
874 if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_INDIVIDUAL && res->mReuse < 0) {
875 operator delete(res->mPtrDevice, std::align_val_t(GPUCA_BUFFER_ALIGNMENT));
876 }
877 res->mPtr = nullptr;
878 res->mPtrDevice = nullptr;
879}
880
885
887{
888 if (proc && GetProcessingSettings().memoryAllocationStrategy != GPUMemoryResource::ALLOCATION_INDIVIDUAL) {
889 GPUFatal("Processor-depending memory-free works only with allocation strategy ALLOCATION_INDIVIDUAL");
890 }
891 if (GetProcessingSettings().keepDisplayMemory || GetProcessingSettings().disableMemoryReuse) {
892 return;
893 }
894 if (mNonPersistentMemoryStack.size() == 0) {
895 GPUFatal("Trying to pop memory state from empty stack");
896 }
897 if (tag != 0 && std::get<4>(mNonPersistentMemoryStack.back()) != tag) {
898 GPUFatal("Tag mismatch when popping non persistent memory from stack : pop %s vs on stack %s", qTag2Str(tag).c_str(), qTag2Str(std::get<4>(mNonPersistentMemoryStack.back())).c_str());
899 }
900 if (!proc && (GetProcessingSettings().debugLevel >= 3 || GetProcessingSettings().allocDebugLevel) && (IsGPU() || GetProcessingSettings().forceHostMemoryPoolSize)) {
901 printf("Allocated memory after %30s (%8s) (Stack %zu): ", GPUDataTypes::RECO_STEP_NAMES[getRecoStepNum(step, true)], qTag2Str(std::get<4>(mNonPersistentMemoryStack.back())).c_str(), mNonPersistentMemoryStack.size());
903 printf("%76s", "");
905 }
906 for (uint32_t i = std::get<2>(mNonPersistentMemoryStack.back()); i < mNonPersistentIndividualAllocations.size(); i++) {
908 if (proc && res->mProcessor != proc) {
909 continue;
910 }
911 if (GetProcessingSettings().allocDebugLevel >= 2 && (res->mPtr || res->mPtrDevice)) {
912 std::cout << "Freeing NonPersistent " << res->mName << ": size " << res->mSize << " (reused " << res->mReuse << ")\n";
913 }
914 if (res->mReuse < 0) {
915 operator delete(res->mPtrDevice, std::align_val_t(GPUCA_BUFFER_ALIGNMENT));
916 }
917 res->mPtr = nullptr;
918 res->mPtrDevice = nullptr;
919 }
920 if (!proc) {
921 stdspinlock spinlock(mMemoryMutex);
922 mHostMemoryPoolEnd = std::get<0>(mNonPersistentMemoryStack.back());
926 mNonPersistentMemoryStack.pop_back();
927 }
928}
929
931{
933 throw std::runtime_error("temporary memory stack already blocked");
934 }
937}
938
940{
941 if (mNonPersistentMemoryStack.size()) {
942 throw std::runtime_error("cannot unblock while there is stacked memory");
943 }
946 mHostMemoryPoolBlocked = nullptr;
947 mDeviceMemoryPoolBlocked = nullptr;
948}
949
951{
952 mMemoryResources[res].mPtr = ptr;
953}
954
956{
957 for (uint32_t i = 0; i < mMemoryResources.size(); i++) {
960 }
961 }
964 mDirectMemoryChunks.clear();
966 mVolatileChunks.clear();
967 mVolatileMemoryStart = nullptr;
968 if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_GLOBAL) {
969 mHostMemoryPool = GPUProcessor::alignPointer<GPUCA_MEMALIGN>(mHostMemoryPermanent);
970 mDeviceMemoryPool = GPUProcessor::alignPointer<GPUCA_MEMALIGN>(mDeviceMemoryPermanent);
973 } else {
975 }
976}
977
983
985{
986 printf("Maximum Memory Allocation: Host %'zu / Device %'zu\n", mHostMemoryUsedMax, mDeviceMemoryUsedMax);
987}
988
990{
991 if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_GLOBAL) {
992 printf("Memory Allocation: Host %'13zd / %'13zu (Permanent %'13zd, Data %'13zd, Scratch %'13zd), Device %'13zd / %'13zu, (Permanent %'13zd, Data %'13zd, Scratch %'13zd) %zu chunks\n",
995 mMemoryResources.size());
996 }
997}
998
1000{
1001 std::map<std::string, std::array<size_t, 3>> sizes;
1002 for (uint32_t i = 0; i < mMemoryResources.size(); i++) {
1003 auto& res = mMemoryResources[i];
1004 if (res.mReuse >= 0) {
1005 continue;
1006 }
1007 auto& x = sizes[res.mName];
1008 if (res.mPtr) {
1009 x[0] += res.mSize;
1010 }
1011 if (res.mPtrDevice) {
1012 x[1] += res.mSize;
1013 }
1015 x[2] = 1;
1016 }
1017 }
1018 printf("%59s CPU / %9s GPU\n", "", "");
1019 for (auto it = sizes.begin(); it != sizes.end(); it++) {
1020 printf("Allocation %50s %s: Size %'14zu / %'14zu\n", it->first.c_str(), it->second[2] ? "P" : " ", it->second[0], it->second[1]);
1021 }
1023 for (uint32_t i = 0; i < mChains.size(); i++) {
1024 mChains[i]->PrintMemoryStatistics();
1025 }
1026}
1027
1029{
1030 if (GetProcessingSettings().noGPUMemoryRegistration) {
1031 return 0;
1032 }
1034 if (retVal == 0) {
1035 mRegisteredMemoryPtrs.emplace(ptr);
1036 }
1037 return retVal;
1038}
1039
1041{
1042 if (GetProcessingSettings().noGPUMemoryRegistration) {
1043 return 0;
1044 }
1045 const auto& pos = mRegisteredMemoryPtrs.find(ptr);
1046 if (pos != mRegisteredMemoryPtrs.end()) {
1049 }
1050 return 1;
1051}
1052
1053namespace o2::gpu::internal
1054{
1055namespace // anonymous
1056{
1057template <class T>
1058constexpr static inline int32_t getStepNum(T step, bool validCheck, int32_t N, const char* err = "Invalid step num")
1059{
1060 static_assert(sizeof(step) == sizeof(uint32_t), "Invalid step enum size");
1061 int32_t retVal = 8 * sizeof(uint32_t) - 1 - CAMath::Clz((uint32_t)step);
1062 if ((uint32_t)step == 0 || retVal >= N) {
1063 if (!validCheck) {
1064 return -1;
1065 }
1066 throw std::runtime_error("Invalid General Step");
1067 }
1068 return retVal;
1069}
1070} // anonymous namespace
1071} // namespace o2::gpu::internal
1072
1073int32_t GPUReconstruction::getRecoStepNum(RecoStep step, bool validCheck) { return internal::getStepNum(step, validCheck, GPUDataTypes::N_RECO_STEPS, "Invalid Reco Step"); }
1074int32_t GPUReconstruction::getGeneralStepNum(GeneralStep step, bool validCheck) { return internal::getStepNum(step, validCheck, GPUDataTypes::N_GENERAL_STEPS, "Invalid General Step"); }
1075
1077{
1078 if (!mInitialized || !GetProcessingSettings().doublePipeline || mMaster != nullptr || !mSlaves.size()) {
1079 throw std::invalid_argument("Cannot start double pipeline mode");
1080 }
1081 if (GetProcessingSettings().debugLevel >= 3) {
1082 GPUInfo("Pipeline worker started");
1083 }
1084 bool terminate = false;
1085 while (!terminate) {
1086 {
1087 std::unique_lock<std::mutex> lk(mPipelineContext->mutex);
1088 mPipelineContext->cond.wait(lk, [this] { return this->mPipelineContext->queue.size() > 0; });
1089 }
1090 GPUReconstructionPipelineQueue* q;
1091 {
1092 std::lock_guard<std::mutex> lk(mPipelineContext->mutex);
1093 q = mPipelineContext->queue.front();
1094 mPipelineContext->queue.pop();
1095 }
1096 if (q->op == 1) {
1097 terminate = 1;
1098 } else {
1099 q->retVal = q->chain->RunChain();
1100 }
1101 {
1102 std::lock_guard<std::mutex> lk(q->m);
1103 q->done = true;
1104 }
1105 q->c.notify_one();
1106 }
1107 if (GetProcessingSettings().debugLevel >= 3) {
1108 GPUInfo("Pipeline worker ended");
1109 }
1110}
1111
1116
1118{
1121 std::unique_ptr<GPUReconstructionPipelineQueue> qu(new GPUReconstructionPipelineQueue);
1122 GPUReconstructionPipelineQueue* q = qu.get();
1123 q->chain = terminate ? nullptr : mChains[0].get();
1124 q->op = terminate ? 1 : 0;
1125 std::unique_lock<std::mutex> lkdone(q->m);
1126 {
1127 std::lock_guard<std::mutex> lkpipe(rec->mPipelineContext->mutex);
1128 if (rec->mPipelineContext->terminate) {
1129 throw std::runtime_error("Must not enqueue work after termination request");
1130 }
1131 rec->mPipelineContext->queue.push(q);
1132 rec->mPipelineContext->terminate = terminate;
1133 rec->mPipelineContext->cond.notify_one();
1134 }
1135 q->c.wait(lkdone, [&q]() { return q->done; });
1136 if (q->retVal) {
1137 return q->retVal;
1138 }
1139 if (terminate) {
1140 return 0;
1141 } else {
1142 return mChains[0]->FinalizePipelinedProcessing();
1143 }
1144}
1145
1147{
1149 std::lock_guard<std::mutex> lk(rec->mPipelineContext->mutex);
1150 return rec->mPipelineContext->queue.size() && rec->mPipelineContext->queue.front()->op == 0 ? rec->mPipelineContext->queue.front()->chain : nullptr;
1151}
1152
1153void GPUReconstruction::PrepareEvent() // TODO: Clean this up, this should not be called from chainTracking but before
1154{
1156 for (uint32_t i = 0; i < mChains.size(); i++) {
1157 mChains[i]->PrepareEvent();
1158 }
1159 for (uint32_t i = 0; i < mProcessors.size(); i++) {
1160 if (mProcessors[i].proc->mAllocateAndInitializeLate) {
1161 continue;
1162 }
1163 (mProcessors[i].proc->*(mProcessors[i].SetMaxData))(mHostConstantMem->ioPtrs);
1164 if (mProcessors[i].proc->mGPUProcessorType != GPUProcessor::PROCESSOR_TYPE_DEVICE && mProcessors[i].proc->mLinkedProcessor) {
1165 (mProcessors[i].proc->mLinkedProcessor->*(mProcessors[i].SetMaxData))(mHostConstantMem->ioPtrs);
1166 }
1167 }
1168 ComputeReuseMax(nullptr);
1169 AllocateRegisteredMemory(nullptr);
1170}
1171
1172int32_t GPUReconstruction::CheckErrorCodes(bool cpuOnly, bool forceShowErrors, std::vector<std::array<uint32_t, 4>>* fillErrors)
1173{
1174 int32_t retVal = 0;
1175 for (uint32_t i = 0; i < mChains.size(); i++) {
1176 if (mChains[i]->CheckErrorCodes(cpuOnly, forceShowErrors, fillErrors)) {
1177 retVal++;
1178 }
1179 }
1180 return retVal;
1181}
1182
1183int32_t GPUReconstruction::GPUChkErrA(const int64_t error, const char* file, int32_t line, bool failOnError)
1184{
1185 if (error == 0 || !GPUChkErrInternal(error, file, line)) {
1186 return 0;
1187 }
1188 if (failOnError) {
1189 if (mInitialized && mInErrorHandling == false) {
1190 mInErrorHandling = true;
1191 CheckErrorCodes(false, true);
1192 }
1193 throw std::runtime_error("GPU Backend Failure");
1194 }
1195 return 1;
1196}
1197
1199{
1200 std::string f;
1201 f = dir;
1202 f += "settings.dump";
1203 DumpStructToFile(mGRPSettings.get(), f.c_str());
1204 for (uint32_t i = 0; i < mChains.size(); i++) {
1205 mChains[i]->DumpSettings(dir);
1206 }
1207}
1208
1209void GPUReconstruction::UpdateDynamicSettings(const GPUSettingsRecDynamic* d)
1210{
1211 UpdateSettings(nullptr, nullptr, d);
1212}
1213
1214void GPUReconstruction::UpdateSettings(const GPUSettingsGRP* g, const GPUSettingsProcessing* p, const GPUSettingsRecDynamic* d)
1215{
1216 if (g) {
1217 *mGRPSettings = *g;
1218 }
1219 if (p) {
1220 mProcessingSettings->debugLevel = p->debugLevel;
1221 mProcessingSettings->resetTimers = p->resetTimers;
1222 }
1223 GPURecoStepConfiguration* w = nullptr;
1225 w = &mRecoSteps;
1226 }
1227 param().UpdateSettings(g, p, w, d);
1228 if (mInitialized) {
1230 }
1231}
1232
1233int32_t GPUReconstruction::ReadSettings(const char* dir)
1234{
1235 std::string f;
1236 f = dir;
1237 f += "settings.dump";
1238 new (mGRPSettings.get()) GPUSettingsGRP;
1239 if (ReadStructFromFile(f.c_str(), mGRPSettings.get())) {
1240 return 1;
1241 }
1243 for (uint32_t i = 0; i < mChains.size(); i++) {
1244 mChains[i]->ReadSettings(dir);
1245 }
1246 return 0;
1247}
1248
1249void GPUReconstruction::SetSettings(float solenoidBzNominalGPU, const GPURecoStepConfiguration* workflow)
1250{
1251#ifdef GPUCA_O2_LIB
1253 config.ReadConfigurableParam(config);
1254 config.configGRP.solenoidBzNominalGPU = solenoidBzNominalGPU;
1255 SetSettings(&config.configGRP, &config.configReconstruction, &config.configProcessing, workflow);
1256#else
1257 GPUSettingsGRP grp;
1258 grp.solenoidBzNominalGPU = solenoidBzNominalGPU;
1259 SetSettings(&grp, nullptr, nullptr, workflow);
1260#endif
1261}
1262
1263void GPUReconstruction::SetSettings(const GPUSettingsGRP* grp, const GPUSettingsRec* rec, const GPUSettingsProcessing* proc, const GPURecoStepConfiguration* workflow)
1264{
1265 if (mInitialized) {
1266 GPUError("Cannot update settings while initialized");
1267 throw std::runtime_error("Settings updated while initialized");
1268 }
1269 *mGRPSettings = *grp;
1270 if (proc) {
1271 *mProcessingSettings = *proc;
1272 }
1273 if (workflow) {
1274 mRecoSteps.steps = workflow->steps;
1276 mRecoSteps.inputs = workflow->inputs;
1277 mRecoSteps.outputs = workflow->outputs;
1278 }
1279 param().SetDefaults(mGRPSettings.get(), rec, proc, workflow);
1280}
1281
1283{
1284 GPUOutputControl outputControl;
1285 outputControl.set(ptr, size);
1286 SetOutputControl(outputControl);
1287}
1288
1292void GPUReconstruction::SetResetTimers(bool reset) { mProcessingSettings->resetTimers = reset; }
1297
1298ThrustVolatileAllocator::ThrustVolatileAllocator(GPUReconstruction* r)
1299{
1300 mAlloc = [&r](size_t n) { return (char*)r->AllocateVolatileDeviceMemory(n); };
1301}
int32_t i
#define GPUCA_BUFFER_ALIGNMENT
uint32_t op
bool done
int32_t retVal
GPUChain * chain
#define GPUCA_NSECTORS
uint16_t pos
Definition RawData.h:3
uint32_t res
Definition RawData.h:0
TBranch * ptr
void set(S v)
Definition bitfield.h:55
bool isSet(const bitfield &v) const
Definition bitfield.h:66
const GPUSettingsDisplay * GetEventDisplayConfig() const
const GPUSettingsQA * GetQAConfig() const
static void dumpConfig(const GPUSettingsRec *rec, const GPUSettingsProcessing *proc, const GPUSettingsQA *qa, const GPUSettingsDisplay *display, const GPUSettingsDeviceBackend *device, const GPURecoStepConfiguration *workflow)
static constexpr const char *const RECO_STEP_NAMES[]
static constexpr int32_t N_RECO_STEPS
static constexpr int32_t N_GENERAL_STEPS
void * SetDevicePointers(void *ptr)
static void computePointerWithAlignment(T *&basePtr, S *&objPtr, size_t nEntries=1)
void InitGPUProcessor(GPUReconstruction *rec, ProcessorType type=PROCESSOR_TYPE_CPU, GPUProcessor *slaveProcessor=nullptr)
ProcessorType mGPUProcessorType
GPURecoStepConfiguration mRecoSteps
std::unordered_set< const void * > mRegisteredMemoryPtrs
int16_t RegisterMemoryAllocationHelper(GPUProcessor *proc, void *(GPUProcessor::*setPtr)(void *), int32_t type, const char *name, const GPUMemoryReuse &re)
std::vector< std::unique_ptr< GPUChain > > mChains
void * AllocateVolatileMemory(size_t size, bool device)
ThrustVolatileAllocator getThrustVolatileDeviceAllocator()
std::unique_ptr< GPUMemorySizeScalers > mMemoryScalers
void AllocateRegisteredForeignMemory(int16_t res, GPUReconstruction *rec, GPUOutputControl *control=nullptr)
void SetInputControl(void *ptr, size_t size)
GPUConstantMem * mDeviceConstantMem
void ConstructGPUProcessor(GPUProcessor *proc)
std::shared_ptr< GPUROOTDumpCore > mROOTDump
size_t AllocateRegisteredMemoryHelper(GPUMemoryResource *res, void *&ptr, void *&memorypool, void *memorybase, size_t memorysize, void *(GPUMemoryResource::*SetPointers)(void *), void *&memorypoolend, const char *device)
const GPUSettingsDeviceBackend & GetDeviceBackendSettings() const
void ComputeReuseMax(GPUProcessor *proc)
void SetMemoryExternalInput(int16_t res, void *ptr)
int32_t getGeneralStepNum(GeneralStep step, bool validCheck=true)
static constexpr uint32_t NSECTORS
RecoStepField GetRecoStepsGPU() const
void RegisterGPUDeviceProcessor(GPUProcessor *proc, GPUProcessor *slaveProcessor)
std::vector< GPUReconstruction * > mSlaves
std::vector< std::tuple< void *, void *, size_t, size_t, uint64_t > > mNonPersistentMemoryStack
std::unique_ptr< T > ReadStructFromFile(const char *file)
void UpdateDynamicSettings(const GPUSettingsRecDynamic *d)
std::unique_ptr< GPUSettingsDeviceBackend > mDeviceBackendSettings
std::vector< GPUMemoryResource > mMemoryResources
std::unique_ptr< GPUReconstructionPipelineContext > mPipelineContext
std::unique_ptr< GPUConstantMem > mHostConstantMem
void ResetRegisteredMemoryPointers(GPUProcessor *proc)
void DumpStructToFile(const T *obj, const char *file)
void AllocateRegisteredMemoryInternal(GPUMemoryResource *res, GPUOutputControl *control, GPUReconstruction *recPool)
virtual int32_t registerMemoryForGPU_internal(const void *ptr, size_t size)=0
virtual size_t WriteToConstantMemory(size_t offset, const void *src, size_t size, int32_t stream=-1, gpu_reconstruction_kernels::deviceEvent *ev=nullptr)=0
std::unordered_map< GPUMemoryReuse::ID, MemoryReuseMeta > mMemoryReuse1to1
std::vector< ProcessorData > mProcessors
void * AllocateVolatileDeviceMemory(size_t size)
virtual int32_t InitDevice()=0
void SetSettings(float solenoidBzNominalGPU, const GPURecoStepConfiguration *workflow=nullptr)
const GPUCalibObjectsConst & GetCalib() const
const GPUTrackingInOutPointers GetIOPtrs() const
virtual std::unique_ptr< gpu_reconstruction_kernels::threadContext > GetThreadContext()=0
GPUReconstruction(const GPUReconstruction &)=delete
static constexpr GeometryType geometryType
std::vector< std::unique_ptr< char[], alignedDeleter > > mNonPersistentIndividualDirectAllocations
void FreeRegisteredMemory(GPUProcessor *proc, bool freeCustom=false, bool freePermanent=false)
std::vector< std::unique_ptr< char[], alignedDeleter > > mVolatileChunks
virtual RecoStepField AvailableGPURecoSteps()
static constexpr const char *const IOTYPENAMES[]
void PopNonPersistentMemory(RecoStep step, uint64_t tag, const GPUProcessor *proc=nullptr)
std::vector< std::unique_ptr< char[], alignedDeleter > > mDirectMemoryChunks
void UpdateSettings(const GPUSettingsGRP *g, const GPUSettingsProcessing *p=nullptr, const GPUSettingsRecDynamic *d=nullptr)
int32_t CheckErrorCodes(bool cpuOnly=false, bool forceShowErrors=false, std::vector< std::array< uint32_t, 4 > > *fillErrors=nullptr)
const GPUParam & GetParam() const
void ClearAllocatedMemory(bool clearOutputs=true)
static constexpr const char *const GEOMETRY_TYPE_NAMES[]
virtual int32_t ExitDevice()=0
std::unique_ptr< GPUSettingsGRP > mGRPSettings
std::unique_ptr< GPUSettingsProcessing > mProcessingSettings
void PushNonPersistentMemory(uint64_t tag)
int32_t getRecoStepNum(RecoStep step, bool validCheck=true)
virtual int32_t unregisterMemoryForGPU_internal(const void *ptr)=0
void BlockStackedMemory(GPUReconstruction *rec)
const GPUSettingsProcessing & GetProcessingSettings() const
void DumpSettings(const char *dir="")
void * AllocateDirectMemory(size_t size, int32_t type)
virtual void GetITSTraits(std::unique_ptr< o2::its::TrackerTraits< 7 > > *trackerTraits, std::unique_ptr< o2::its::VertexerTraits< 7 > > *vertexerTraits, std::unique_ptr< o2::its::TimeFrame< 7 > > *timeFrame)
int32_t unregisterMemoryForGPU(const void *ptr)
int32_t registerMemoryForGPU(const void *ptr, size_t size)
void SetDebugLevelTmp(int32_t level)
int32_t EnqueuePipeline(bool terminate=false)
std::shared_ptr< GPUReconstructionThreading > mThreading
std::vector< GPUMemoryResource * > mNonPersistentIndividualAllocations
virtual int32_t GPUChkErrInternal(const int64_t error, const char *file, int32_t line) const
int32_t GPUChkErrA(const int64_t error, const char *file, int32_t line, bool failOnError)
size_t AllocateRegisteredMemory(GPUProcessor *proc, bool resetCustom=false)
int32_t ReadSettings(const char *dir="")
void SetOutputControl(const GPUOutputControl &v)
void SetSector(int32_t iSector)
#define TPC_MAX_FRAGMENT_LEN_GPU
#define TPC_MAX_FRAGMENT_LEN_HOST
GLdouble n
Definition glcorearb.h:1982
GLint GLenum GLint x
Definition glcorearb.h:403
const GLfloat * m
Definition glcorearb.h:4066
GLsizeiptr size
Definition glcorearb.h:659
GLuint GLsizei const GLuint const GLintptr const GLsizeiptr * sizes
Definition glcorearb.h:2595
GLuint const GLchar * name
Definition glcorearb.h:781
GLdouble f
Definition glcorearb.h:310
GLboolean GLboolean GLboolean b
Definition glcorearb.h:1233
GLint GLint GLsizei GLint GLenum GLenum type
Definition glcorearb.h:275
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLboolean GLboolean g
Definition glcorearb.h:1233
GLint level
Definition glcorearb.h:275
GLboolean r
Definition glcorearb.h:1233
GLenum GLfloat param
Definition glcorearb.h:271
GLboolean GLboolean GLboolean GLboolean a
Definition glcorearb.h:1233
GLubyte GLubyte GLubyte GLubyte w
Definition glcorearb.h:852
std::unique_ptr< GPUDisplayFrontendInterface > eventDisplay
GPUReconstruction * rec
std::string qTag2Str(const T tag)
Definition strtag.h:35
GPUTPCTracker tpcTrackers[GPUCA_NSECTORS]
GPUTPCClusterFinder tpcClusterer[GPUCA_NSECTORS]
GPUCalibObjectsConst calibObjects
void set(void *p, size_t s)
std::function< void *(size_t)> allocator
void UpdateSettings(const GPUSettingsGRP *g, const GPUSettingsProcessing *p=nullptr, const GPURecoStepConfiguration *w=nullptr, const GPUSettingsRecDynamic *d=nullptr)
Definition GPUParam.cxx:116
void SetDefaults(float solenoidBz, bool assumeConstantBz)
Definition GPUParam.cxx:33
GPUDataTypes::RecoStepField stepsGPUMask
GPUDataTypes::InOutTypeField outputs
GPUDataTypes::RecoStepField steps
GPUDataTypes::InOutTypeField inputs
std::queue< GPUReconstructionPipelineQueue * > queue