File: command_stream_receiver.h

package info (click to toggle)
intel-compute-runtime 25.44.36015.8-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 79,632 kB
  • sloc: cpp: 931,547; lisp: 2,074; sh: 719; makefile: 162; python: 21
file content (741 lines) | stat: -rw-r--r-- 30,672 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
/*
 * Copyright (C) 2018-2025 Intel Corporation
 *
 * SPDX-License-Identifier: MIT
 *
 */

#pragma once
#include "shared/source/command_stream/host_function.h"
#include "shared/source/command_stream/linear_stream.h"
#include "shared/source/command_stream/memory_compression_state.h"
#include "shared/source/command_stream/preemption_mode.h"
#include "shared/source/command_stream/stream_properties.h"
#include "shared/source/helpers/blit_properties_container.h"
#include "shared/source/helpers/cache_policy.h"
#include "shared/source/helpers/common_types.h"
#include "shared/source/helpers/completion_stamp.h"
#include "shared/source/helpers/device_bitfield.h"
#include "shared/source/helpers/kmd_notify_properties.h"
#include "shared/source/helpers/non_copyable_or_moveable.h"
#include "shared/source/helpers/options.h"
#include "shared/source/kernel/kernel_execution_type.h"
#include "shared/source/utilities/spinlock.h"

#include <atomic>
#include <chrono>
#include <cstdint>
#include <functional>

namespace aub_stream {
struct AllocationParams;
} // namespace aub_stream

namespace NEO {
enum class AllocationType;
enum class DebugPauseState : uint32_t;
struct BatchBuffer;
struct DispatchBcsFlags;
struct DispatchFlags;
struct HardwareInfo;
struct ImmediateDispatchFlags;
struct WaitParams;
class SubmissionAggregator;
class FlushStampTracker;
class Thread;
class FlatBatchBufferHelper;
class AllocationsList;
class Device;
class ExecutionEnvironment;
class GmmPageTableMngr;
class GraphicsAllocation;
class HostPtrSurface;
class IndirectHeap;
class InternalAllocationStorage;
class LinearStream;
class MemoryManager;
class MultiGraphicsAllocation;
class OsContext;
class OSInterface;
class ScratchSpaceController;
class HwPerfCounter;
class HwTimeStamps;
class GmmHelper;
class TagAllocatorBase;
class TimestampPacketContainer;
class KmdNotifyHelper;
class GfxCoreHelper;
class ProductHelper;
class ReleaseHelper;
enum class WaitStatus;
struct AubSubCaptureStatus;
class SharedPoolAllocation;

template <typename TSize, uint32_t packetCount>
class TimestampPackets;

template <typename T1>
class TagAllocator;
class TagNodeBase;

enum class DispatchMode {
    deviceDefault = 0, // default for given device
    immediateDispatch, // everything is submitted to the HW immediately
    batchedDispatch    // dispatching is batched, explicit clFlush is required
};

class CommandStreamReceiver : NEO::NonCopyableAndNonMovableClass {
  public:
    static constexpr size_t startingResidencyContainerSize = 128;

    enum class SamplerCacheFlushState {
        samplerCacheFlushNotRequired,
        samplerCacheFlushBefore, // add sampler cache flush before Walker with redescribed image
        samplerCacheFlushAfter   // add sampler cache flush after Walker with redescribed image
    };

    using MutexType = std::recursive_mutex;
    using TimeType = std::chrono::high_resolution_clock::time_point;

    CommandStreamReceiver() = delete;

    CommandStreamReceiver(ExecutionEnvironment &executionEnvironment,
                          uint32_t rootDeviceIndex,
                          const DeviceBitfield deviceBitfield);

    virtual ~CommandStreamReceiver();

    virtual SubmissionStatus flush(BatchBuffer &batchBuffer, ResidencyContainer &allocationsForResidency) = 0;

    virtual CompletionStamp flushTask(LinearStream &commandStreamTask, size_t commandStreamTaskStart,
                                      const IndirectHeap *dsh, const IndirectHeap *ioh, const IndirectHeap *ssh,
                                      TaskCountType taskLevel, DispatchFlags &dispatchFlags, Device &device) = 0;

    virtual CompletionStamp flushBcsTask(LinearStream &commandStream, size_t commandStreamStart, const DispatchBcsFlags &dispatchBcsFlags, const HardwareInfo &hwInfo) = 0;
    virtual CompletionStamp flushImmediateTask(LinearStream &immediateCommandStream, size_t immediateCommandStreamStart,
                                               ImmediateDispatchFlags &dispatchFlags, Device &device) = 0;

    virtual CompletionStamp flushImmediateTaskStateless(LinearStream &immediateCommandStream, size_t immediateCommandStreamStart,
                                                        ImmediateDispatchFlags &dispatchFlags, Device &device) = 0;
    virtual SubmissionStatus sendRenderStateCacheFlush() = 0;

    virtual bool flushBatchedSubmissions() = 0;
    MOCKABLE_VIRTUAL SubmissionStatus submitBatchBuffer(BatchBuffer &batchBuffer, ResidencyContainer &allocationsForResidency);
    void pollForCompletion() { pollForCompletion(false); }
    virtual void pollForAubCompletion(){};
    virtual void pollForCompletion(bool skipTaskCountCheck) {}
    virtual void programHardwareContext(LinearStream &cmdStream) = 0;
    virtual size_t getCmdsSizeForHardwareContext() const = 0;

    void makeResident(MultiGraphicsAllocation &gfxAllocation);
    MOCKABLE_VIRTUAL void makeResident(GraphicsAllocation &gfxAllocation);
    virtual void makeNonResident(GraphicsAllocation &gfxAllocation);
    MOCKABLE_VIRTUAL void makeSurfacePackNonResident(ResidencyContainer &allocationsForResidency, bool clearAllocations);
    virtual SubmissionStatus processResidency(ResidencyContainer &allocationsForResidency, uint32_t handleId);
    virtual void processEviction();
    void makeResidentHostPtrAllocation(GraphicsAllocation *gfxAllocation);

    MOCKABLE_VIRTUAL void ensureCommandBufferAllocation(LinearStream &commandStream, size_t minimumRequiredSize, size_t additionalAllocationSize);

    MemoryManager *getMemoryManager() const;

    ResidencyContainer &getResidencyAllocations();
    PrivateAllocsToReuseContainer &getOwnedPrivateAllocations();

    virtual GmmPageTableMngr *createPageTableManager() { return nullptr; }
    bool needsPageTableManager() const;

    MOCKABLE_VIRTUAL WaitStatus waitForTaskCount(TaskCountType requiredTaskCount);
    WaitStatus waitForTaskCountAndCleanAllocationList(TaskCountType requiredTaskCount, uint32_t allocationUsage);
    MOCKABLE_VIRTUAL WaitStatus waitForTaskCountAndCleanTemporaryAllocationList(TaskCountType requiredTaskCount);

    LinearStream &getCS(size_t minRequiredSize = 1024u);
    OSInterface *getOSInterface() const;
    ExecutionEnvironment &peekExecutionEnvironment() const { return executionEnvironment; }
    GmmHelper *peekGmmHelper() const;
    DeviceBitfield peekDeviceBitfield() const { return deviceBitfield; }

    MOCKABLE_VIRTUAL void setTagAllocation(GraphicsAllocation *allocation);
    GraphicsAllocation *getTagAllocation() const {
        return tagAllocation;
    }
    MultiGraphicsAllocation *getTagsMultiAllocation() const {
        return tagsMultiAllocation;
    }
    MultiGraphicsAllocation &createMultiAllocationInSystemMemoryPool(AllocationType allocationType);
    void makeResidentHostFunctionAllocation();
    TaskCountType getNextBarrierCount() { return this->barrierCount.fetch_add(1u); }
    TaskCountType peekBarrierCount() const { return this->barrierCount.load(); }
    volatile TagAddressType *getTagAddress() const { return tagAddress; }
    volatile TagAddressType *getUcTagAddress() const { return ucTagAddress; }
    volatile TagAddressType *getBarrierCountTagAddress() const { return this->barrierCountTagAddress; }
    uint64_t getBarrierCountGpuAddress() const;
    uint64_t getDebugPauseStateGPUAddress() const;
    uint64_t getUcTagGPUAddress() const;

    virtual bool waitForFlushStamp(FlushStamp &flushStampToWait) { return true; }

    TaskCountType peekTaskCount() const { return taskCount; }

    TaskCountType peekTaskLevel() const { return taskLevel; }
    FlushStamp obtainCurrentFlushStamp() const;

    TaskCountType peekLatestSentTaskCount() const { return latestSentTaskCount; }

    TaskCountType peekLatestFlushedTaskCount() const { return latestFlushedTaskCount; }

    void enableNTo1SubmissionModel() { this->nTo1SubmissionModelEnabled = true; }
    bool isNTo1SubmissionModelEnabled() const { return this->nTo1SubmissionModelEnabled; }
    void overrideDispatchPolicy(DispatchMode overrideValue) { this->dispatchMode = overrideValue; }

    void setMediaVFEStateDirty(bool dirty) { mediaVfeStateDirty = dirty; }
    bool getMediaVFEStateDirty() const { return mediaVfeStateDirty; }

    void setGSBAStateDirty(bool dirty) { gsbaStateDirty = dirty; }
    bool getGSBAStateDirty() const { return gsbaStateDirty; }

    void setStateComputeModeDirty(bool dirty) { stateComputeModeDirty = dirty; }
    bool getStateComputeModeDirty() const { return stateComputeModeDirty; }

    void setBtdCommandDirty(bool dirty) { btdCommandDirty = dirty; }
    bool getBtdCommandDirty() const { return btdCommandDirty; }
    bool isRayTracingStateProgramingNeeded(Device &device) const;

    void setRequiredScratchSizes(uint32_t newRequiredScratchSlot0Size, uint32_t newRequiredPrivateScratchSlot1Size);
    GraphicsAllocation *getScratchAllocation();
    GraphicsAllocation *getDebugSurfaceAllocation() const {
        if (primaryCsr) {
            return primaryCsr->getDebugSurfaceAllocation();
        }
        return debugSurface;
    }
    GraphicsAllocation *allocateDebugSurface(size_t size);
    GraphicsAllocation *getPreemptionAllocation() const {
        if (primaryCsr) {
            return primaryCsr->getPreemptionAllocation();
        }
        return preemptionAllocation;
    }
    GraphicsAllocation *getGlobalFenceAllocation() const {
        if (primaryCsr) {
            return primaryCsr->getGlobalFenceAllocation();
        }

        return globalFenceAllocation;
    }
    GraphicsAllocation *getWorkPartitionAllocation() const {
        if (primaryCsr) {
            return primaryCsr->getWorkPartitionAllocation();
        }
        return workPartitionAllocation;
    }

    GraphicsAllocation *getGlobalStatelessHeapAllocation() const {
        if (primaryCsr) {
            return primaryCsr->getGlobalStatelessHeapAllocation();
        }

        return globalStatelessHeapAllocation;
    }

    virtual WaitStatus waitForTaskCountWithKmdNotifyFallback(TaskCountType taskCountToWait, FlushStamp flushStampToWait, bool useQuickKmdSleep, QueueThrottle throttle) = 0;
    virtual WaitStatus waitForCompletionWithTimeout(const WaitParams &params, TaskCountType taskCountToWait);
    WaitStatus baseWaitFunction(volatile TagAddressType *pollAddress, const WaitParams &params, TaskCountType taskCountToWait);
    MOCKABLE_VIRTUAL bool testTaskCountReady(volatile TagAddressType *pollAddress, TaskCountType taskCountToWait);
    void downloadAllocations(bool blockingWait) { downloadAllocations(blockingWait, this->latestFlushedTaskCount); };
    virtual void downloadAllocations(bool blockingWait, TaskCountType taskCount){};
    virtual void removeDownloadAllocation(GraphicsAllocation *alloc){};

    void setSamplerCacheFlushRequired(SamplerCacheFlushState value) { this->samplerCacheFlushRequired = value; }

    FlatBatchBufferHelper &getFlatBatchBufferHelper() const { return *flatBatchBufferHelper; }
    void overwriteFlatBatchBufferHelper(FlatBatchBufferHelper *newHelper);

    MOCKABLE_VIRTUAL void initProgrammingFlags();
    virtual AubSubCaptureStatus checkAndActivateAubSubCapture(const std::string &kernelName);
    void programForAubSubCapture(bool wasActiveInPreviousEnqueue, bool isActive);
    virtual void addAubComment(const char *comment);

    IndirectHeap &getIndirectHeap(IndirectHeapType heapType, size_t minRequiredSize);
    void allocateHeapMemory(IndirectHeapType heapType, size_t minRequiredSize, IndirectHeap *&indirectHeap);
    void releaseIndirectHeap(IndirectHeapType heapType);
    void *getIndirectHeapCurrentPtr(IndirectHeapType heapType) const;

    virtual enum CommandStreamReceiverType getType() const = 0;

    bool initializeTagAllocation();
    MOCKABLE_VIRTUAL bool createWorkPartitionAllocation(const Device &device);
    MOCKABLE_VIRTUAL bool createGlobalFenceAllocation();
    MOCKABLE_VIRTUAL bool createPreemptionAllocation();
    MOCKABLE_VIRTUAL bool createPerDssBackedBuffer(Device &device);
    [[nodiscard]] MOCKABLE_VIRTUAL std::unique_lock<MutexType> obtainUniqueOwnership();
    [[nodiscard]] MOCKABLE_VIRTUAL std::unique_lock<MutexType> tryObtainUniqueOwnership();

    bool peekTimestampPacketWriteEnabled() const { return timestampPacketWriteEnabled; }

    bool isLatestTaskCountFlushed() {
        return this->peekLatestFlushedTaskCount() == this->peekTaskCount();
    }

    size_t defaultSshSize = 0u;

    AllocationsList &getTemporaryAllocations();
    AllocationsList &getAllocationsForReuse();
    AllocationsList &getDeferredAllocations();
    InternalAllocationStorage *getInternalAllocationStorage() const { return internalAllocationStorage.get(); }
    MOCKABLE_VIRTUAL bool createAllocationForHostSurface(HostPtrSurface &surface, bool requiresL3Flush);
    virtual size_t getPreferredTagPoolSize() const;
    virtual void fillReusableAllocationsList();
    virtual void setupContext(OsContext &osContext) { this->osContext = &osContext; }
    OsContext &getOsContext() const { return *osContext; }
    uint8_t getUmdPowerHintValue() const;
    bool initializeResources(bool allocateInterrupt, const PreemptionMode preemptionMode);
    TagAllocatorBase *getEventTsAllocator();
    TagAllocatorBase *getEventPerfCountAllocator(const uint32_t tagSize);
    virtual TagAllocatorBase *getTimestampPacketAllocator() = 0;
    virtual std::unique_ptr<TagAllocatorBase> createMultiRootDeviceTimestampPacketAllocator(const RootDeviceIndicesContainer &rootDeviceIndices) = 0;

    virtual bool expectMemory(const void *gfxAddress, const void *srcAddress, size_t length, uint32_t compareOperation);
    MOCKABLE_VIRTUAL bool writeMemory(GraphicsAllocation &gfxAllocation) { return writeMemory(gfxAllocation, false, 0, 0); }
    virtual bool writeMemory(GraphicsAllocation &gfxAllocation, bool isChunkCopy, uint64_t gpuVaChunkOffset, size_t chunkSize) { return false; }
    virtual void writeMemoryAub(aub_stream::AllocationParams &allocationParams){};
    virtual void writePooledMemory(SharedPoolAllocation &sharedPoolAllocation, bool initFullPageTables){};
    virtual void initializeEngine(){};

    virtual bool isMultiOsContextCapable() const = 0;

    virtual MemoryCompressionState getMemoryCompressionState(bool auxTranslationRequired) const = 0;

    void setLatestSentTaskCount(TaskCountType latestSentTaskCount) {
        this->latestSentTaskCount = latestSentTaskCount;
    }
    void setLatestFlushedTaskCount(TaskCountType latestFlushedTaskCount) {
        this->latestFlushedTaskCount = latestFlushedTaskCount;
    }

    virtual TaskCountType flushBcsTask(const BlitPropertiesContainer &blitPropertiesContainer, bool blocking, Device &device) = 0;

    virtual SubmissionStatus flushTagUpdate() = 0;
    virtual void updateTagFromWait() = 0;
    virtual bool isUpdateTagFromWaitEnabled() = 0;
    virtual void flushMonitorFence(bool notifyKmd){};
    virtual bool isTlbFlushRequiredForStateCacheFlush();

    ScratchSpaceController *getScratchSpaceController() const {
        return scratchSpaceController.get();
    }

    ScratchSpaceController *getPrimaryScratchSpaceController() const {
        if (primaryCsr) {
            return primaryCsr->getScratchSpaceController();
        }
        return getScratchSpaceController();
    }

    void downloadAllocation(GraphicsAllocation &gfxAllocation);

    bool isInstructionCacheFlushRequired() const {
        return requiresInstructionCacheFlush;
    }

    void setInstructionCacheFlushed() {
        requiresInstructionCacheFlush = false;
    }

    void registerInstructionCacheFlush() {
        auto mutex = obtainUniqueOwnership();
        requiresInstructionCacheFlush = true;
    }

    bool isLocalMemoryEnabled() const { return localMemoryEnabled; }

    uint32_t getRootDeviceIndex() const { return rootDeviceIndex; }

    MOCKABLE_VIRTUAL void startControllingDirectSubmissions();

    MOCKABLE_VIRTUAL bool isAnyDirectSubmissionEnabled() const {
        return this->isDirectSubmissionEnabled() || isBlitterDirectSubmissionEnabled();
    }

    virtual bool initDirectSubmission() {
        return true;
    }

    virtual bool isDirectSubmissionEnabled() const {
        return false;
    }

    virtual bool isBlitterDirectSubmissionEnabled() const {
        return false;
    }

    virtual bool directSubmissionRelaxedOrderingEnabled() const {
        return false;
    }

    virtual uint32_t getDirectSubmissionRelaxedOrderingQueueDepth() const { return 0; }

    virtual bool isKmdWaitOnTaskCountAllowed() const {
        return false;
    }

    virtual void stopDirectSubmission(bool blocking, bool needsLock) {}

    virtual QueueThrottle getLastDirectSubmissionThrottle() = 0;

    bool isStaticWorkPartitioningEnabled() const {
        return staticWorkPartitioningEnabled;
    }

    uint64_t getWorkPartitionAllocationGpuAddress() const;

    MOCKABLE_VIRTUAL bool isRcs() const;

    virtual GraphicsAllocation *getClearColorAllocation() = 0;

    virtual void postInitFlagsSetup() = 0;

    bool isUsedNotifyEnableForPostSync() const {
        return useNotifyEnableForPostSync;
    }

    NEO::StreamProperties &getStreamProperties() {
        return this->streamProperties;
    }

    inline void setActivePartitions(uint32_t newPartitionCount) {
        activePartitions = newPartitionCount;
    }

    inline uint32_t getActivePartitions() const {
        return activePartitions;
    }

    bool skipResourceCleanup() const;

    inline bool isProgramActivePartitionConfigRequired() const {
        return this->isDirectSubmissionEnabled() ? false : this->activePartitionsConfig != this->activePartitions;
    }

    std::unique_ptr<GmmPageTableMngr> pageTableManager;

    inline uint32_t getImmWritePostSyncWriteOffset() const {
        return immWritePostSyncWriteOffset;
    }

    inline uint32_t getTimeStampPostSyncWriteOffset() const {
        return timeStampPostSyncWriteOffset;
    }

    inline bool isMultiTileOperationEnabled() const {
        return (activePartitions > 1) && staticWorkPartitioningEnabled;
    }

    virtual void programComputeBarrierCommand(LinearStream &cmdStream) = 0;
    virtual size_t getCmdsSizeForComputeBarrierCommand() const = 0;

    virtual void programStallingCommandsForBarrier(LinearStream &cmdStream, TimestampPacketContainer *barrierTimestampPacketNodes, const bool isDcFlushRequired) = 0;

    const HardwareInfo &peekHwInfo() const;
    const RootDeviceEnvironment &peekRootDeviceEnvironment() const;

    const GfxCoreHelper &getGfxCoreHelper() const;
    const ProductHelper &getProductHelper() const;
    const ReleaseHelper *getReleaseHelper() const;

    MOCKABLE_VIRTUAL bool isGpuHangDetected() const;
    MOCKABLE_VIRTUAL bool checkGpuHangDetected(TimeType currentTime, TimeType &lastHangCheckTime) const;

    uint64_t getCompletionAddress() const;

    TaskCountType getCompletionValue(const GraphicsAllocation &gfxAllocation);
    DispatchMode getDispatchMode() const {
        return this->dispatchMode;
    }

    bool getPreambleSetFlag() const {
        return isPreambleSent;
    }

    void setPreambleSetFlag(bool value) {
        isPreambleSent = value;
    }

    bool getSipSentFlag() const {
        return isStateSipSent;
    }

    void setSipSentFlag(bool value) {
        isStateSipSent = value;
    }

    PreemptionMode getPreemptionMode() const {
        return lastPreemptionMode;
    }

    void setPreemptionMode(PreemptionMode value) {
        lastPreemptionMode = value;
    }
    bool csrSurfaceProgrammed() const {
        return csrSurfaceProgrammingDone;
    }
    void setCsrSurfaceProgrammed(bool value) {
        csrSurfaceProgrammingDone = value;
    }

    virtual SubmissionStatus initializeDeviceWithFirstSubmission(Device &device) = 0;

    uint32_t getNumClients() const {
        return this->numClients.load();
    }
    void registerClient(void *client);
    void unregisterClient(void *client);

    bool getDcFlushSupport() const {
        return dcFlushSupport;
    }

    bool getDcFlushRequired(bool externalCondition) const {
        return externalCondition ? dcFlushSupport : false;
    }

    bool getHeaplessStateInitEnabled() const {
        return heaplessStateInitEnabled;
    }

    bool isTbxMode() const;
    bool isAubMode() const;
    bool isHardwareMode() const;
    bool ensureTagAllocationForRootDeviceIndex(uint32_t rootDeviceIndex);

    L1CachePolicy *getStoredL1CachePolicy() {
        return &l1CachePolicyData;
    }
    void createGlobalStatelessHeap();
    IndirectHeap *getGlobalStatelessHeap() {
        if (primaryCsr) {
            return primaryCsr->getGlobalStatelessHeap();
        }
        return globalStatelessHeap.get();
    }

    bool isRecyclingTagForHeapStorageRequired() const { return heapStorageRequiresRecyclingTag; }

    virtual bool waitUserFenceSupported() { return false; }
    virtual bool waitUserFence(TaskCountType waitValue, uint64_t hostAddress, int64_t timeout, bool userInterrupt, uint32_t externalInterruptId, GraphicsAllocation *allocForInterruptWait) { return false; }
    void setPrimaryCsr(CommandStreamReceiver *primaryCsr) {
        this->primaryCsr = primaryCsr;
    }
    CommandStreamReceiver *getPrimaryCsr() const { return primaryCsr; }

    void requestPreallocation();
    void releasePreallocationRequest();
    void preallocateAllocation(AllocationType type, size_t size);
    void preallocateCommandBuffer();
    void preallocateInternalHeap();

    bool isInitialized() const {
        return this->resourcesInitialized;
    }

    MOCKABLE_VIRTUAL bool getAcLineConnected(bool updateStatus) const {
        if (updateStatus) {
            this->kmdNotifyHelper->updateAcLineStatus();
        }
        return this->kmdNotifyHelper->getAcLineConnected();
    }

    uint32_t getRequiredScratchSlot0Size() { return requiredScratchSlot0Size; }
    uint32_t getRequiredScratchSlot1Size() { return requiredScratchSlot1Size; }
    virtual bool submitDependencyUpdate(TagNodeBase *tag) = 0;

    MOCKABLE_VIRTUAL bool isBusy() {
        return !testTaskCountReady(getTagAddress(), this->taskCount);
    }

    MOCKABLE_VIRTUAL bool isBusyWithoutHang(TimeType &lastHangCheckTime) {
        return isBusy() && !this->checkGpuHangDetected(std::chrono::high_resolution_clock::now(), lastHangCheckTime);
    }

    bool canUse4GbHeaps() const {
        return this->use4GbHeaps;
    }

    void ensurePrimaryCsrInitialized(Device &device);

    bool enqueueWaitForPagingFence(uint64_t pagingFenceValue);
    virtual void unblockPagingFenceSemaphore(uint64_t pagingFenceValue) {}
    MOCKABLE_VIRTUAL void drainPagingFenceQueue();
    bool isLatestFlushIsTaskCountUpdateOnly() const { return latestFlushIsTaskCountUpdateOnly; }

    MOCKABLE_VIRTUAL uint32_t getContextGroupId() const;

    void ensureHostFunctionDataInitialization();
    HostFunctionData &getHostFunctionData();
    GraphicsAllocation *getHostFunctionDataAllocation();

  protected:
    MOCKABLE_VIRTUAL void initializeHostFunctionData();

    virtual CompletionStamp flushTaskHeapless(LinearStream &commandStreamTask, size_t commandStreamTaskStart,
                                              const IndirectHeap *dsh, const IndirectHeap *ioh, const IndirectHeap *ssh,
                                              TaskCountType taskLevel, DispatchFlags &dispatchFlags, Device &device) = 0;

    virtual CompletionStamp flushTaskHeapful(LinearStream &commandStreamTask, size_t commandStreamTaskStart,
                                             const IndirectHeap *dsh, const IndirectHeap *ioh, const IndirectHeap *ssh,
                                             TaskCountType taskLevel, DispatchFlags &dispatchFlags, Device &device) = 0;

    void cleanupResources();
    void printDeviceIndex();
    void checkForNewResources(TaskCountType submittedTaskCount, TaskCountType allocationTaskCount, GraphicsAllocation &gfxAllocation);
    bool checkImplicitFlushForGpuIdle();
    MOCKABLE_VIRTUAL bool getAndClearIsWalkerWithProfilingEnqueued();
    void downloadTagAllocation(TaskCountType taskCountToWait);
    void printTagAddressContent(TaskCountType taskCountToWait, int64_t waitTimeout, bool start);
    virtual void addToEvictionContainer(GraphicsAllocation &gfxAllocation);

    [[nodiscard]] MOCKABLE_VIRTUAL std::unique_lock<MutexType> obtainHostPtrSurfaceCreationLock();

    std::vector<void *> registeredClients;

    std::unique_ptr<FlushStampTracker> flushStamp;
    std::unique_ptr<SubmissionAggregator> submissionAggregator;
    std::unique_ptr<FlatBatchBufferHelper> flatBatchBufferHelper;
    std::unique_ptr<InternalAllocationStorage> internalAllocationStorage;
    std::atomic<uint32_t> preallocatedAmount{0};
    std::atomic<uint32_t> requestedPreallocationsAmount{0};

    std::unique_ptr<KmdNotifyHelper> kmdNotifyHelper;
    std::unique_ptr<ScratchSpaceController> scratchSpaceController;
    std::unique_ptr<TagAllocatorBase> profilingTimeStampAllocator;
    std::unique_ptr<TagAllocatorBase> perfCounterAllocator;
    std::unique_ptr<TagAllocatorBase> timestampPacketAllocator;
    std::unique_ptr<Thread> userPauseConfirmation;
    std::unique_ptr<IndirectHeap> globalStatelessHeap;

    ResidencyContainer residencyAllocations;
    PrivateAllocsToReuseContainer ownedPrivateAllocations;

    MutexType ownershipMutex;
    MutexType hostPtrSurfaceCreationMutex;
    MutexType registeredClientsMutex;
    ExecutionEnvironment &executionEnvironment;

    LinearStream commandStream;
    StreamProperties streamProperties{};
    FrontEndPropertiesSupport feSupportFlags{};
    PipelineSelectPropertiesSupport pipelineSupportFlags{};
    StateBaseAddressPropertiesSupport sbaSupportFlags{};
    L1CachePolicy l1CachePolicyData{};

    uint64_t totalMemoryUsed = 0u;

    volatile TagAddressType *tagAddress = nullptr;
    volatile TagAddressType *ucTagAddress = nullptr;
    volatile TagAddressType *barrierCountTagAddress = nullptr;
    volatile DebugPauseState *debugPauseStateAddress = nullptr;
    SpinLock debugPauseStateLock;
    static void *asyncDebugBreakConfirmation(void *arg);
    static std::function<void()> debugConfirmationFunction;
    std::function<void(GraphicsAllocation &)> downloadAllocationImpl;

    GraphicsAllocation *tagAllocation = nullptr;
    GraphicsAllocation *globalFenceAllocation = nullptr;
    GraphicsAllocation *preemptionAllocation = nullptr;
    GraphicsAllocation *debugSurface = nullptr;
    GraphicsAllocation *perDssBackedBuffer = nullptr;
    GraphicsAllocation *clearColorAllocation = nullptr;
    GraphicsAllocation *workPartitionAllocation = nullptr;
    GraphicsAllocation *globalStatelessHeapAllocation = nullptr;

    MultiGraphicsAllocation *tagsMultiAllocation = nullptr;
    MultiGraphicsAllocation *hostFunctionDataMultiAllocation = nullptr;
    GraphicsAllocation *hostFunctionDataAllocation = nullptr;
    IndirectHeap *indirectHeap[IndirectHeapType::numTypes];
    OsContext *osContext = nullptr;
    CommandStreamReceiver *primaryCsr = nullptr;
    TaskCountType *completionFenceValuePointer = nullptr;
    HostFunctionData hostFunctionData;

    std::atomic<TaskCountType> barrierCount{0};
    // current taskLevel.  Used for determining if a PIPE_CONTROL is needed.
    std::atomic<TaskCountType> taskLevel{0};
    std::atomic<TaskCountType> latestSentTaskCount{0};
    std::atomic<TaskCountType> latestFlushedTaskCount{0};
    // taskCount - # of tasks submitted
    std::atomic<TaskCountType> taskCount{0};

    std::atomic<uint32_t> numClients = 0u;

    DispatchMode dispatchMode = DispatchMode::immediateDispatch;
    SamplerCacheFlushState samplerCacheFlushRequired = SamplerCacheFlushState::samplerCacheFlushNotRequired;
    PreemptionMode lastPreemptionMode = PreemptionMode::Initial;

    std::chrono::microseconds gpuHangCheckPeriod{CommonConstants::gpuHangCheckTimeInUS};
    uint32_t lastSentL3Config = 0;
    uint32_t latestSentStatelessMocsConfig;
    uint64_t lastSentSliceCount;

    uint32_t requiredScratchSlot0Size = 0;
    uint32_t requiredScratchSlot1Size = 0;
    uint32_t lastAdditionalKernelExecInfo;
    KernelExecutionType lastKernelExecutionType = KernelExecutionType::defaultType;
    MemoryCompressionState lastMemoryCompressionState = MemoryCompressionState::notApplicable;
    uint32_t activePartitions = 1;
    uint32_t activePartitionsConfig = 1;
    uint32_t immWritePostSyncWriteOffset = 0;
    uint32_t timeStampPostSyncWriteOffset = 0;
    TaskCountType completionFenceValue = 0;
    const uint32_t rootDeviceIndex;
    const DeviceBitfield deviceBitfield;
    std::atomic<bool> hostFunctionInitialized = false;
    bool isPreambleSent = false;
    bool isStateSipSent = false;
    bool isEnginePrologueSent = false;
    bool areExceptionsSent = false;
    bool isPerDssBackedBufferSent = false;
    bool isWalkerWithProfilingEnqueued = false;
    bool gsbaFor32BitProgrammed = false;
    bool gsbaStateDirty = true;
    bool bindingTableBaseAddressRequired = false;
    bool heapStorageRequiresRecyclingTag = false;
    bool ucResourceRequiresTagUpdate = false;
    bool mediaVfeStateDirty = true;
    bool stateComputeModeDirty = true;
    bool btdCommandDirty = true;
    bool lastVmeSubslicesConfig = false;
    bool timestampPacketWriteEnabled = false;
    bool staticWorkPartitioningEnabled = false;
    bool nTo1SubmissionModelEnabled = false;
    bool lastSystolicPipelineSelectMode = false;
    bool requiresInstructionCacheFlush = false;
    bool requiresDcFlush = false;
    bool pushAllocationsForMakeResident = true;

    bool localMemoryEnabled = false;
    bool pageTableManagerInitialized = false;

    bool useNewResourceImplicitFlush = false;
    bool newResources = false;
    bool useGpuIdleImplicitFlush = false;
    bool useNotifyEnableForPostSync = false;
    bool dcFlushSupport = false;
    bool forceSkipResourceCleanupRequired = false;
    bool resourcesInitialized = false;
    bool heaplessStateInitialized = false;
    bool heaplessStateInitEnabled = false;
    bool doubleSbaWa = false;
    bool dshSupported = false;
    bool heaplessModeEnabled = false;
    bool use4GbHeaps = true;
    bool csrSurfaceProgrammingDone = false;
    bool latestFlushIsTaskCountUpdateOnly = false;
};

static_assert(NEO::NonCopyableAndNonMovable<CommandStreamReceiver>);

typedef CommandStreamReceiver *(*CommandStreamReceiverCreateFunc)(bool withAubDump,
                                                                  ExecutionEnvironment &executionEnvironment,
                                                                  uint32_t rootDeviceIndex,
                                                                  const DeviceBitfield deviceBitfield);
} // namespace NEO