summaryrefslogtreecommitdiffstats
path: root/tools/gfx/cuda/cuda-command-queue.cpp
blob: 60e81246d67696e12ddd5db0ce37c346e8c5de8a (plain)
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
// cuda-command-queue.cpp
#include "cuda-command-queue.h"

#include "cuda-buffer.h"
#include "cuda-command-buffer.h"
#include "cuda-query.h"
#include "cuda-shader-object-layout.h"

namespace gfx
{
#ifdef GFX_ENABLE_CUDA
using namespace Slang;

namespace cuda
{

ICommandQueue* CommandQueueImpl::getInterface(const Guid& guid)
{
    if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_ICommandQueue)
        return static_cast<ICommandQueue*>(this);
    return nullptr;
}

void CommandQueueImpl::init(DeviceImpl* inRenderer)
{
    renderer = inRenderer;
    m_desc.type = ICommandQueue::QueueType::Graphics;
    cuStreamCreate(&stream, 0);
}
CommandQueueImpl::~CommandQueueImpl()
{
    cuStreamSynchronize(stream);
    cuStreamDestroy(stream);
    currentPipeline = nullptr;
    currentRootObject = nullptr;
}

SLANG_NO_THROW void SLANG_MCALL CommandQueueImpl::executeCommandBuffers(
    GfxCount count, ICommandBuffer* const* commandBuffers, IFence* fence, uint64_t valueToSignal)
{
    SLANG_UNUSED(valueToSignal);
    // TODO: implement fence.
    assert(fence == nullptr);
    for (GfxIndex i = 0; i < count; i++)
    {
        execute(static_cast<CommandBufferImpl*>(commandBuffers[i]));
    }
}

SLANG_NO_THROW void SLANG_MCALL CommandQueueImpl::waitOnHost()
{
    auto resultCode = cuStreamSynchronize(stream);
    if (resultCode != cudaSuccess)
        SLANG_CUDA_HANDLE_ERROR(resultCode);
}

SLANG_NO_THROW Result SLANG_MCALL CommandQueueImpl::waitForFenceValuesOnDevice(
    GfxCount fenceCount, IFence** fences, uint64_t* waitValues)
{
    return SLANG_FAIL;
}

SLANG_NO_THROW Result SLANG_MCALL CommandQueueImpl::getNativeHandle(InteropHandle* outHandle)
{
    return SLANG_FAIL;
}

void CommandQueueImpl::setPipelineState(IPipelineState* state)
{
    currentPipeline = dynamic_cast<ComputePipelineStateImpl*>(state);
}

Result CommandQueueImpl::bindRootShaderObject(IShaderObject* object)
{
    currentRootObject = dynamic_cast<RootShaderObjectImpl*>(object);
    if (currentRootObject)
        return SLANG_OK;
    return SLANG_E_INVALID_ARG;
}

void CommandQueueImpl::dispatchCompute(int x, int y, int z)
{
    // Specialize the compute kernel based on the shader object bindings.
    RefPtr<PipelineStateBase> newPipeline;
    renderer->maybeSpecializePipeline(currentPipeline, currentRootObject, newPipeline);
    currentPipeline = static_cast<ComputePipelineStateImpl*>(newPipeline.Ptr());

    // Find out thread group size from program reflection.
    auto& kernelName = currentPipeline->shaderProgram->kernelName;
    auto programLayout = static_cast<RootShaderObjectLayoutImpl*>(currentRootObject->getLayout());
    int kernelId = programLayout->getKernelIndex(kernelName.getUnownedSlice());
    SLANG_ASSERT(kernelId != -1);
    UInt threadGroupSize[3];
    programLayout->getKernelThreadGroupSize(kernelId, threadGroupSize);

    int sharedSizeInBytes;
    cuFuncGetAttribute(
        &sharedSizeInBytes,
        CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES,
        currentPipeline->shaderProgram->cudaKernel);

    // Copy global parameter data to the `SLANG_globalParams` symbol.
    {
        CUdeviceptr globalParamsSymbol = 0;
        size_t globalParamsSymbolSize = 0;
        cuModuleGetGlobal(
            &globalParamsSymbol,
            &globalParamsSymbolSize,
            currentPipeline->shaderProgram->cudaModule,
            "SLANG_globalParams");

        CUdeviceptr globalParamsCUDAData = (CUdeviceptr)currentRootObject->getBuffer();
        cudaMemcpyAsync(
            (void*)globalParamsSymbol,
            (void*)globalParamsCUDAData,
            globalParamsSymbolSize,
            cudaMemcpyDefault,
            0);
    }
    //
    // The argument data for the entry-point parameters are already
    // stored in host memory in a CUDAEntryPointShaderObject, as expected by cuLaunchKernel.
    //
    auto entryPointBuffer = currentRootObject->entryPointObjects[kernelId]->getBuffer();
    auto entryPointDataSize =
        currentRootObject->entryPointObjects[kernelId]->getBufferSize();

    void* extraOptions[] = {
        CU_LAUNCH_PARAM_BUFFER_POINTER,
        entryPointBuffer,
        CU_LAUNCH_PARAM_BUFFER_SIZE,
        &entryPointDataSize,
        CU_LAUNCH_PARAM_END,
    };

    // Once we have all the necessary data extracted and/or
    // set up, we can launch the kernel and see what happens.
    //
    auto cudaLaunchResult = cuLaunchKernel(
        currentPipeline->shaderProgram->cudaKernel,
        x,
        y,
        z,
        int(threadGroupSize[0]),
        int(threadGroupSize[1]),
        int(threadGroupSize[2]),
        sharedSizeInBytes,
        stream,
        nullptr,
        extraOptions);

    SLANG_ASSERT(cudaLaunchResult == CUDA_SUCCESS);
}

void CommandQueueImpl::copyBuffer(
    IBufferResource* dst,
    size_t dstOffset,
    IBufferResource* src,
    size_t srcOffset,
    size_t size)
{
    auto dstImpl = static_cast<BufferResourceImpl*>(dst);
    auto srcImpl = static_cast<BufferResourceImpl*>(src);
    cudaMemcpy(
        (uint8_t*)dstImpl->m_cudaMemory + dstOffset,
        (uint8_t*)srcImpl->m_cudaMemory + srcOffset,
        size,
        cudaMemcpyDefault);
}

void CommandQueueImpl::uploadBufferData(IBufferResource* dst, size_t offset, size_t size, void* data)
{
    auto dstImpl = static_cast<BufferResourceImpl*>(dst);
    cudaMemcpy((uint8_t*)dstImpl->m_cudaMemory + offset, data, size, cudaMemcpyDefault);
}

void CommandQueueImpl::writeTimestamp(IQueryPool* pool, SlangInt index)
{
    auto poolImpl = static_cast<QueryPoolImpl*>(pool);
    cuEventRecord(poolImpl->m_events[index], stream);
}

void CommandQueueImpl::execute(CommandBufferImpl* commandBuffer)
{
    for (auto& cmd : commandBuffer->m_commands)
    {
        switch (cmd.name)
        {
        case CommandName::SetPipelineState:
            setPipelineState(commandBuffer->getObject<PipelineStateBase>(cmd.operands[0]));
            break;
        case CommandName::BindRootShaderObject:
            bindRootShaderObject(
                commandBuffer->getObject<ShaderObjectBase>(cmd.operands[0]));
            break;
        case CommandName::DispatchCompute:
            dispatchCompute(
                int(cmd.operands[0]), int(cmd.operands[1]), int(cmd.operands[2]));
            break;
        case CommandName::CopyBuffer:
            copyBuffer(
                commandBuffer->getObject<BufferResource>(cmd.operands[0]),
                cmd.operands[1],
                commandBuffer->getObject<BufferResource>(cmd.operands[2]),
                cmd.operands[3],
                cmd.operands[4]);
            break;
        case CommandName::UploadBufferData:
            uploadBufferData(
                commandBuffer->getObject<BufferResource>(cmd.operands[0]),
                cmd.operands[1],
                cmd.operands[2],
                commandBuffer->getData<uint8_t>(cmd.operands[3]));
            break;
        case CommandName::WriteTimestamp:
            writeTimestamp(
                commandBuffer->getObject<QueryPoolBase>(cmd.operands[0]),
                (SlangInt)cmd.operands[1]);
        }
    }
}

} // namespace cuda
#endif
} // namespace gfx