./
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
15 / 183
8.2%
Branches:
6 / 74
8.1%
Functions:
5 / 37
13.5%

src/gpu/cuda.cpp
Line Branch Exec Source
1 // SPDX-License-Identifier: BSD-3-Clause
2
3 #include "gpu/cuda.h"
4
5 #include "terraingen/util/log.h"
6
7 #if defined(_WIN32)
8 #define NOMINMAX
9 #define WIN32_LEAN_AND_MEAN
10 #include <windows.h>
11 #else
12 #include <dlfcn.h>
13 #endif
14
15 #include <algorithm>
16 #include <cstring>
17 #include <map>
18 #include <mutex>
19 #include <stdexcept>
20 #include <utility>
21
22 namespace terraingen {
23
24 namespace {
25
26 /// The part of the CUDA driver API TerrainGen calls, declared from cuda.h so the build needs no
27 /// CUDA headers; the driver ABI is stable across versions.
28 namespace cu {
29
30 using Result = int;
31 using Device = int;
32 using Context = struct Context_st*;
33 using Module = struct Module_st*;
34 using Function = struct Function_st*;
35 using Stream = struct Stream_st*;
36 using DevicePtr = unsigned long long;
37
38 constexpr Result kSuccess = 0;
39 constexpr Result kErrorUnsupportedPtxVersion = 222;
40
41 } // namespace cu
42
43 #if defined(_WIN32)
44 constexpr const char* kCudaDriver = "nvcuda.dll";
45 void* OpenLibrary(const char* name) {
46 return reinterpret_cast<void*>(LoadLibraryA(name));
47 }
48 void* Symbol(void* library, const char* name) {
49 return reinterpret_cast<void*>(GetProcAddress(static_cast<HMODULE>(library), name));
50 }
51 #else
52 constexpr const char* kCudaDriver = "libcuda.so.1";
53 24 void* OpenLibrary(const char* name) {
54 24 return dlopen(name, RTLD_NOW | RTLD_LOCAL);
55 }
56 ✗ void* Symbol(void* library, const char* name) {
57 ✗ return dlsym(library, name);
58 }
59 #endif
60
61 /// The driver entry points, loaded from the driver library.
62 struct Driver {
63 cu::Result (*init)(unsigned int) = nullptr;
64 cu::Result (*deviceGetCount)(int*) = nullptr;
65 cu::Result (*deviceGet)(cu::Device*, int) = nullptr;
66 cu::Result (*deviceGetName)(char*, int, cu::Device) = nullptr;
67 cu::Result (*primaryCtxRetain)(cu::Context*, cu::Device) = nullptr;
68 cu::Result (*primaryCtxRelease)(cu::Device) = nullptr;
69 cu::Result (*ctxSetCurrent)(cu::Context) = nullptr;
70 cu::Result (*ctxSynchronize)() = nullptr;
71 cu::Result (*moduleLoadData)(cu::Module*, const void*) = nullptr;
72 cu::Result (*moduleUnload)(cu::Module) = nullptr;
73 cu::Result (*moduleGetFunction)(cu::Function*, cu::Module, const char*) = nullptr;
74 cu::Result (*moduleGetGlobal)(cu::DevicePtr*, std::size_t*, cu::Module, const char*) = nullptr;
75 cu::Result (*memAlloc)(cu::DevicePtr*, std::size_t) = nullptr;
76 cu::Result (*memFree)(cu::DevicePtr) = nullptr;
77 cu::Result (*memcpyHtoD)(cu::DevicePtr, const void*, std::size_t) = nullptr;
78 cu::Result (*memcpyDtoH)(void*, cu::DevicePtr, std::size_t) = nullptr;
79 cu::Result (*launchKernel)(cu::Function, unsigned int, unsigned int, unsigned int, unsigned int,
80 unsigned int, unsigned int, unsigned int, cu::Stream, void**,
81 void**) = nullptr;
82 cu::Result (*getErrorString)(cu::Result, const char**) = nullptr;
83 };
84
85 /// Sets `function` to the driver symbol `name`; false when the driver lacks it.
86 ✗ template <typename Function> bool Load(void* library, const char* name, Function& function) {
87 ✗ function = reinterpret_cast<Function>(Symbol(library, name));
88 ✗ return function != nullptr;
89 }
90
91 /// Loads every entry point of `driver` from `library`; the name of the first missing one, or null.
92 ✗ const char* LoadDriver(void* library, Driver& d) {
93 ✗ const std::pair<const char*, bool> loaded[] = {
94 ✗ {"cuInit", Load(library, "cuInit", d.init)},
95 ✗ {"cuDeviceGetCount", Load(library, "cuDeviceGetCount", d.deviceGetCount)},
96 ✗ {"cuDeviceGet", Load(library, "cuDeviceGet", d.deviceGet)},
97 ✗ {"cuDeviceGetName", Load(library, "cuDeviceGetName", d.deviceGetName)},
98 ✗ {"cuDevicePrimaryCtxRetain", Load(library, "cuDevicePrimaryCtxRetain", d.primaryCtxRetain)},
99 {"cuDevicePrimaryCtxRelease_v2",
100 ✗ Load(library, "cuDevicePrimaryCtxRelease_v2", d.primaryCtxRelease)},
101 ✗ {"cuCtxSetCurrent", Load(library, "cuCtxSetCurrent", d.ctxSetCurrent)},
102 ✗ {"cuCtxSynchronize", Load(library, "cuCtxSynchronize", d.ctxSynchronize)},
103 ✗ {"cuModuleLoadData", Load(library, "cuModuleLoadData", d.moduleLoadData)},
104 ✗ {"cuModuleUnload", Load(library, "cuModuleUnload", d.moduleUnload)},
105 ✗ {"cuModuleGetFunction", Load(library, "cuModuleGetFunction", d.moduleGetFunction)},
106 ✗ {"cuModuleGetGlobal_v2", Load(library, "cuModuleGetGlobal_v2", d.moduleGetGlobal)},
107 ✗ {"cuMemAlloc_v2", Load(library, "cuMemAlloc_v2", d.memAlloc)},
108 ✗ {"cuMemFree_v2", Load(library, "cuMemFree_v2", d.memFree)},
109 ✗ {"cuMemcpyHtoD_v2", Load(library, "cuMemcpyHtoD_v2", d.memcpyHtoD)},
110 ✗ {"cuMemcpyDtoH_v2", Load(library, "cuMemcpyDtoH_v2", d.memcpyDtoH)},
111 ✗ {"cuLaunchKernel", Load(library, "cuLaunchKernel", d.launchKernel)},
112 ✗ {"cuGetErrorString", Load(library, "cuGetErrorString", d.getErrorString)},
113 ✗ };
114
0/4
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ for (const auto& [name, ok] : loaded) {
115
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (!ok) {
116 ✗ return name;
117 }
118 }
119 return nullptr;
120 }
121
122 /// Device allocations of one `Run`, freed when it goes out of scope however the run ends.
123 struct RunAllocations {
124 const Driver& driver;
125 std::vector<cu::DevicePtr> pointers;
126
127 ✗ explicit RunAllocations(const Driver& d) : driver(d) {}
128 RunAllocations(const RunAllocations&) = delete;
129 RunAllocations& operator=(const RunAllocations&) = delete;
130 ✗ ~RunAllocations() {
131
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ for (const cu::DevicePtr pointer : pointers) {
132 ✗ driver.memFree(pointer);
133 }
134 }
135 };
136
137 /// A structured buffer as Slang passes it in `SLANG_globalParams`.
138 struct BufferParam {
139 cu::DevicePtr data;
140 std::uint64_t count;
141 };
142
143 /// The entry point of a loaded kernel and its global parameter block.
144 struct Entry {
145 cu::Function function = nullptr;
146 cu::DevicePtr globals = 0;
147 std::size_t globalsSize = 0;
148 };
149
150 } // namespace
151
152 /// The driver, device, primary context and loaded modules.
153 struct CudaCompute::State {
154 Driver driver;
155 cu::Device device = 0;
156 cu::Context context = nullptr;
157 std::string name;
158 std::mutex mutex;
159 /// Modules keyed by their PTX, which lives for the whole process.
160 std::map<const char*, cu::Module> modules;
161
162 24 State() = default;
163 State(const State&) = delete;
164 State& operator=(const State&) = delete;
165
166 24 ~State() {
167
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 24 times.
24 if (context != nullptr) {
168 ✗ driver.ctxSetCurrent(context);
169
0/2
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✗ for (const auto& [ptx, module] : modules) {
170 ✗ driver.moduleUnload(module);
171 }
172 ✗ driver.primaryCtxRelease(device);
173 }
174 24 }
175
176 /// Throws std::runtime_error naming `what` and the driver's message unless `result` succeeded.
177 ✗ void Check(cu::Result result, const char* what) const {
178
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (result == cu::kSuccess) {
179 ✗ return;
180 }
181 ✗ const char* message = nullptr;
182 ✗ driver.getErrorString(result, &message);
183
0/3
✗ Branch 1 not taken.
✗ Branch 4 not taken.
✗ Branch 7 not taken.
✗ throw std::runtime_error(std::string("CUDA ") + what + " failed (" +
184
0/4
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✗ Branch 4 not taken.
✗ Branch 8 not taken.
✗ (message != nullptr ? message : std::to_string(result)) + ")");
185 }
186
187 /// Opens the driver, the first device and its primary context.
188 24 void Open() {
189 24 void* library = OpenLibrary(kCudaDriver);
190
1/2
✓ Branch 0 taken 24 times.
✗ Branch 1 not taken.
24 if (library == nullptr) {
191
2/2
✓ Branch 1 taken 24 times.
✓ Branch 4 taken 24 times.
72 throw std::runtime_error(std::string("no NVIDIA driver found (") + kCudaDriver +
192
2/2
✓ Branch 2 taken 24 times.
✓ Branch 5 taken 24 times.
72 "); install the NVIDIA driver to use CUDA");
193 }
194
0/2
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✗ if (const char* missing = LoadDriver(library, driver)) {
195
0/2
✗ Branch 1 not taken.
✗ Branch 4 not taken.
✗ throw std::runtime_error(std::string("the NVIDIA driver lacks ") + missing +
196
0/2
✗ Branch 2 not taken.
✗ Branch 5 not taken.
✗ "; update the driver");
197 }
198 ✗ Check(driver.init(0), "initialization");
199 ✗ int count = 0;
200 ✗ Check(driver.deviceGetCount(&count), "device count");
201
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (count == 0) {
202
0/1
✗ Branch 2 not taken.
✗ throw std::runtime_error("no CUDA devices");
203 }
204 ✗ Check(driver.deviceGet(&device, 0), "device lookup");
205 ✗ char deviceName[256] = {};
206 ✗ Check(driver.deviceGetName(deviceName, static_cast<int>(sizeof(deviceName)), device),
207 "device name");
208 ✗ name = deviceName;
209 ✗ Check(driver.primaryCtxRetain(&context, device), "context creation");
210 }
211
212 /// The module of `ptx`, loaded on first use.
213 ✗ cu::Module CachedModule(Span<const char> ptx) {
214 ✗ const auto found = modules.find(ptx.data());
215
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (found != modules.end()) {
216 ✗ return found->second;
217 }
218 ✗ cu::Module module = nullptr;
219 ✗ const cu::Result loaded = driver.moduleLoadData(&module, ptx.data());
220
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (loaded == cu::kErrorUnsupportedPtxVersion) {
221 ✗ throw std::runtime_error("the NVIDIA driver is older than this build's CUDA kernels; "
222
0/1
✗ Branch 2 not taken.
✗ "update the driver");
223 }
224 ✗ Check(loaded, "module loading");
225 ✗ return modules.emplace(ptx.data(), module).first->second;
226 }
227
228 /// The entry point "main_0" of `ptx` and its global parameters, which must hold `buffers`
229 /// structured buffers and the push constants.
230 ✗ Entry FindEntry(Span<const char> ptx, std::size_t buffers) {
231 ✗ const cu::Module module = CachedModule(ptx);
232 ✗ Entry entry;
233 ✗ Check(driver.moduleGetFunction(&entry.function, module, "main_0"), "kernel lookup");
234 ✗ Check(driver.moduleGetGlobal(&entry.globals, &entry.globalsSize, module,
235 "SLANG_globalParams"),
236 "global parameter lookup");
237
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (entry.globalsSize != buffers * sizeof(BufferParam) + sizeof(cu::DevicePtr)) {
238
0/1
✗ Branch 1 not taken.
✗ throw std::runtime_error("The CUDA kernel's global parameters are not " +
239
0/2
✗ Branch 2 not taken.
✗ Branch 5 not taken.
✗ std::to_string(buffers) + " buffers and push constants");
240 }
241 ✗ return entry;
242 }
243
244 /// Allocates device memory for `bytes`, owned by `run`, and uploads them.
245 ✗ cu::DevicePtr Upload(Span<const std::byte> bytes, RunAllocations& run) const {
246 ✗ cu::DevicePtr pointer = 0;
247
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ Check(driver.memAlloc(&pointer, std::max<std::size_t>(bytes.size(), 4)),
248 "memory allocation");
249 ✗ run.pointers.push_back(pointer);
250 ✗ Check(driver.memcpyHtoD(pointer, bytes.data(), bytes.size()), "upload");
251 ✗ return pointer;
252 }
253
254 /// Uploads the buffers, then the push constants, and points the global parameters at them.
255 ✗ void UploadParams(const Entry& entry, Span<const DeviceBuffer> buffers,
256 Span<const std::byte> pushConstants, RunAllocations& run) const {
257 ✗ std::vector<std::byte> params(entry.globalsSize);
258
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ for (std::size_t i = 0; i < buffers.size(); ++i) {
259
0/1
✗ Branch 2 not taken.
✗ const BufferParam param{Upload(buffers[i].bytes, run), buffers[i].count};
260 ✗ std::memcpy(params.data() + i * sizeof(BufferParam), &param, sizeof(param));
261 }
262
0/1
✗ Branch 1 not taken.
✗ const cu::DevicePtr push = Upload(pushConstants, run);
263
0/1
✗ Branch 1 not taken.
✗ std::memcpy(params.data() + buffers.size() * sizeof(BufferParam), &push, sizeof(push));
264
0/2
✗ Branch 1 not taken.
✗ Branch 4 not taken.
✗ Check(driver.memcpyHtoD(entry.globals, params.data(), params.size()), "parameter upload");
265 }
266
267 /// Copies the output buffers back from their allocations, the first ones of `run`.
268 ✗ void DownloadOutputs(Span<const DeviceBuffer> buffers, const RunAllocations& run) const {
269
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ for (std::size_t i = 0; i < buffers.size(); ++i) {
270
0/2
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✗ if (buffers[i].output != nullptr) {
271 ✗ Check(
272 ✗ driver.memcpyDtoH(buffers[i].output, run.pointers[i], buffers[i].bytes.size()),
273 "download");
274 }
275 }
276 }
277 };
278
279 ✗ CudaCompute::CudaCompute(std::unique_ptr<State> state) : m_state(std::move(state)) {}
280
281 ✗ CudaCompute::~CudaCompute() = default;
282
283 24 std::unique_ptr<CudaCompute> CudaCompute::Open() {
284 24 auto state = std::make_unique<State>();
285
0/1
✗ Branch 1 not taken.
24 state->Open();
286
0/1
✗ Branch 1 not taken.
✗ return std::unique_ptr<CudaCompute>(new CudaCompute(std::move(state)));
287 24 }
288
289 ✗ const std::string& CudaCompute::DeviceName() const {
290 ✗ return m_state->name;
291 }
292
293 ✗ bool CudaCompute::CanRun(const KernelProgram& program) const {
294 ✗ return !program.ptx.empty();
295 }
296
297 ✗ void CudaCompute::Run(const KernelProgram& program, Span<const DeviceBuffer> buffers,
298 Span<const std::byte> pushConstants, const Dispatch& dispatch) {
299
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ if (!CanRun(program)) {
300
0/1
✗ Branch 2 not taken.
✗ throw std::runtime_error("The kernel has no PTX for CUDA");
301 }
302 ✗ State& s = *m_state;
303 ✗ const std::lock_guard lock(s.mutex);
304
0/2
✗ Branch 1 not taken.
✗ Branch 4 not taken.
✗ s.Check(s.driver.ctxSetCurrent(s.context), "context binding");
305
0/1
✗ Branch 1 not taken.
✗ const Entry entry = s.FindEntry(program.ptx, buffers.size());
306
0/1
✗ Branch 1 not taken.
✗ RunAllocations run(s.driver);
307
0/1
✗ Branch 1 not taken.
✗ s.UploadParams(entry, buffers, pushConstants, run);
308 ✗ const auto& [groups, size] = dispatch;
309
0/1
✗ Branch 1 not taken.
✗ s.Check(s.driver.launchKernel(entry.function, groups[0], groups[1], groups[2], size[0], size[1],
310
0/1
✗ Branch 1 not taken.
✗ size[2], 0, nullptr, nullptr, nullptr),
311 "kernel launch");
312
0/2
✗ Branch 1 not taken.
✗ Branch 4 not taken.
✗ s.Check(s.driver.ctxSynchronize(), "kernel");
313
0/1
✗ Branch 1 not taken.
✗ s.DownloadOutputs(buffers, run);
314 }
315
316 } // namespace terraingen
317