okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-151-amd (d9070189c) into f-split-int258f81f20e

main
10.8 KiB317 linesraw
1#include "strata/core/vmm.hpp"
2
3#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL)
4#include <cuda.h>
5#include <cuda_runtime.h>
6
7#include <mutex>
8
9namespace strata::core {
10namespace {
11
12struct Api {
13    bool ok = false;
14    uint64_t gran = 0;
15    int dev = -1;
16    decltype(&cuMemAddressReserve) reserve = nullptr;
17    decltype(&cuMemAddressFree) free_va = nullptr;
18    decltype(&cuMemCreate) create = nullptr;
19    decltype(&cuMemRelease) release = nullptr;
20    decltype(&cuMemMap) map = nullptr;
21    decltype(&cuMemUnmap) unmap = nullptr;
22    decltype(&cuMemSetAccess) access = nullptr;
23};
24
25template <class F> bool resolve(const char* name, F& f) {
26    cudaDriverEntryPointQueryResult q{};
27    void* p = nullptr;
28#if CUDART_VERSION >= 12050
29    const cudaError_t e = cudaGetDriverEntryPointByVersion(name, &p, 12000, cudaEnableDefault, &q);
30#else   // the versioned query arrived in CUDA 12.5
31    const cudaError_t e = cudaGetDriverEntryPoint(name, &p, cudaEnableDefault, &q);
32#endif
33    if (e != cudaSuccess || q != cudaDriverEntryPointSuccess || p == nullptr) {
34        (void) cudaGetLastError();
35        return false;
36    }
37    f = (F) p;
38    return true;
39}
40
41// never destroyed: the K/V pools and the cache release their chunks from static destructors at exit
42const Api& api() {
43    static Api& a = *new Api;
44    static std::once_flag once;
45    std::call_once(once, [] {
46        decltype(&cuDeviceGetAttribute) attr = nullptr;
47        decltype(&cuMemGetAllocationGranularity) granularity = nullptr;
48        if (cudaGetDevice(&a.dev) != cudaSuccess) return;
49        if (!resolve("cuDeviceGetAttribute", attr) || !resolve("cuMemGetAllocationGranularity", granularity) ||
50            !resolve("cuMemAddressReserve", a.reserve) || !resolve("cuMemAddressFree", a.free_va) ||
51            !resolve("cuMemCreate", a.create) || !resolve("cuMemRelease", a.release) || !resolve("cuMemMap", a.map) ||
52            !resolve("cuMemUnmap", a.unmap) || !resolve("cuMemSetAccess", a.access))
53            return;
54        int vmm = 0;
55        if (attr(&vmm, CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED, (CUdevice) a.dev) != CUDA_SUCCESS || !vmm)
56            return;
57        CUmemAllocationProp prop{};
58        prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
59        prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
60        prop.location.id = a.dev;
61        size_t g = 0;
62        if (granularity(&g, &prop, CU_MEM_ALLOC_GRANULARITY_MINIMUM) != CUDA_SUCCESS || g == 0) return;
63        a.gran = g;
64        a.ok = true;
65    });
66    return a;
67}
68
69}  // namespace
70
71bool vmm_available() { return api().ok; }
72uint64_t vmm_granularity() { return api().ok ? api().gran : 0; }
73
74VmmChunk vmm_chunk_new() {
75    const Api& a = api();
76    if (!a.ok) return 0;
77    CUmemAllocationProp prop{};
78    prop.type = CU_MEM_ALLOCATION_TYPE_PINNED;
79    prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
80    prop.location.id = a.dev;
81    CUmemGenericAllocationHandle h = 0;
82    if (a.create(&h, (size_t) a.gran, &prop, 0) != CUDA_SUCCESS) return 0;
83    return (VmmChunk) h;
84}
85
86void vmm_chunk_free(VmmChunk h) {
87    if (h != 0 && api().ok) api().release((CUmemGenericAllocationHandle) h);
88}
89
90bool VmmRange::reserve(uint64_t bytes) {
91    release();
92    const Api& a = api();
93    if (!a.ok || bytes == 0) return false;
94    const uint64_t n = (bytes + a.gran - 1) / a.gran;
95    CUdeviceptr p = 0;
96    if (a.reserve(&p, (size_t) (n * a.gran), 0, 0, 0) != CUDA_SUCCESS) return false;
97    base_ = (unsigned long long) p;
98    h_.assign((size_t) n, 0);
99    return true;
100}
101
102void VmmRange::release() {
103    if (base_ == 0) return;
104    const Api& a = api();
105    for (int64_t i = 0; i < chunks(); ++i) vmm_chunk_free(unmap(i));
106    a.free_va((CUdeviceptr) base_, (size_t) ((uint64_t) h_.size() * a.gran));
107    base_ = 0;
108    h_.clear();
109}
110
111int64_t VmmRange::mapped_count() const {
112    int64_t n = 0;
113    for (const VmmChunk h : h_) n += h != 0;
114    return n;
115}
116
117bool VmmRange::map_one(int64_t i, VmmChunk h) {
118    const Api& a = api();
119    if (a.map((CUdeviceptr) (base_ + (uint64_t) i * a.gran), (size_t) a.gran, 0, (CUmemGenericAllocationHandle) h, 0) !=
120        CUDA_SUCCESS)
121        return false;
122    h_[(size_t) i] = h;
123    return true;
124}
125
126bool VmmRange::set_access(int64_t lo, int64_t hi) {
127    if (hi <= lo) return true;
128    const Api& a = api();
129    CUmemAccessDesc d{};
130    d.location.type = CU_MEM_LOCATION_TYPE_DEVICE;
131    d.location.id = a.dev;
132    d.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE;
133    return a.access((CUdeviceptr) (base_ + (uint64_t) lo * a.gran), (size_t) ((uint64_t) (hi - lo) * a.gran), &d, 1) ==
134           CUDA_SUCCESS;
135}
136
137bool VmmRange::commit_run(int64_t lo, int64_t hi) {
138    if (set_access(lo, hi)) return true;
139    for (int64_t c = lo; c < hi; ++c) vmm_chunk_free(unmap(c));
140    return false;
141}
142
143VmmChunk VmmRange::unmap(int64_t i) {
144    if (!mapped(i)) return 0;
145    const Api& a = api();
146    const VmmChunk h = h_[(size_t) i];
147    if (a.unmap((CUdeviceptr) (base_ + (uint64_t) i * a.gran), (size_t) a.gran) != CUDA_SUCCESS) return 0;
148    h_[(size_t) i] = 0;
149    return h;
150}
151
152}  // namespace strata::core
153
154#else  // not CUDA
155// HIP (ROCm 6+): the same elastic range through hipMemAddressReserve / hipMemCreate / hipMemMap / hipMemSetAccess.  Available
156// only where the device reports virtual memory management support (STRATA_HIP_VMM=0 turns it off): --kv-grow stays off
157// otherwise, as before.  Everything else (Metal, gfx906, ROCm older than 6): no virtual memory, the elastic K/V stays off.
158#if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
159#include <hip/hip_runtime.h>
160#include <hip/hip_version.h>
161
162#include <cstdio>
163#include <cstdlib>
164#include <mutex>
165#endif
166
167#if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && defined(HIP_VERSION_MAJOR) && HIP_VERSION_MAJOR >= 6
168namespace strata::core {
169namespace {
170struct Api {
171    bool ok = false;
172    uint64_t gran = 0;
173    int dev = -1;
174};
175void fail(const char* what, hipError_t e) {
176    static int n = 0;
177    if (n++ < 8) std::fprintf(stderr, "strata: HIP virtual memory: %s failed: %s\n", what, hipGetErrorString(e));
178    (void) hipGetLastError();
179}
180hipMemAllocationProp alloc_prop(int dev) {
181    hipMemAllocationProp p{};
182    p.type = hipMemAllocationTypePinned;
183    p.requestedHandleType = hipMemHandleTypeNone;
184    p.location.type = hipMemLocationTypeDevice;
185    p.location.id = dev;
186    return p;
187}
188const Api& api() {
189    static Api& a = *new Api;   // never destroyed: the K/V pools and the cache release their chunks from static destructors
190    static std::once_flag once;
191    std::call_once(once, [] {
192        const char* off = std::getenv("STRATA_HIP_VMM");
193        if (off != nullptr && off[0] == '0') return;
194        if (hipGetDevice(&a.dev) != hipSuccess) { (void) hipGetLastError(); return; }
195        int vmm = 0;
196        if (hipDeviceGetAttribute(&vmm, hipDeviceAttributeVirtualMemoryManagementSupported, a.dev) != hipSuccess || !vmm) {
197            (void) hipGetLastError();
198            return;
199        }
200        const hipMemAllocationProp prop = alloc_prop(a.dev);
201        size_t g = 0;
202        if (hipMemGetAllocationGranularity(&g, &prop, hipMemAllocationGranularityMinimum) != hipSuccess || g == 0) {
203            (void) hipGetLastError();
204            return;
205        }
206        // gfx1201 reports a 4 KiB minimum granularity; the elastic range works in 2 MiB chunks like CUDA's (any multiple of the minimum)
207        const uint64_t want = 2ull << 20;
208        a.gran = g >= want ? g : (want + g - 1) / g * g;
209        a.ok = true;
210    });
211    return a;
212}
213}  // namespace
214
215bool vmm_available() { return api().ok; }
216uint64_t vmm_granularity() { return api().ok ? api().gran : 0; }
217
218VmmChunk vmm_chunk_new() {
219    const Api& a = api();
220    if (!a.ok) return 0;
221    const hipMemAllocationProp prop = alloc_prop(a.dev);
222    hipMemGenericAllocationHandle_t h = nullptr;
223    if (const hipError_t e = hipMemCreate(&h, (size_t) a.gran, &prop, 0); e != hipSuccess) { fail("hipMemCreate", e); return 0; }
224    return (VmmChunk) (uintptr_t) h;
225}
226
227void vmm_chunk_free(VmmChunk h) {
228    if (h != 0 && api().ok) (void) hipMemRelease((hipMemGenericAllocationHandle_t) (uintptr_t) h);
229}
230
231bool VmmRange::reserve(uint64_t bytes) {
232    release();
233    const Api& a = api();
234    if (!a.ok || bytes == 0) return false;
235    const uint64_t n = (bytes + a.gran - 1) / a.gran;
236    void* p = nullptr;
237    if (const hipError_t e = hipMemAddressReserve(&p, (size_t) (n * a.gran), 0, nullptr, 0); e != hipSuccess) { fail("hipMemAddressReserve", e); return false; }
238    base_ = (unsigned long long) (uintptr_t) p;
239    h_.assign((size_t) n, 0);
240    return true;
241}
242
243void VmmRange::release() {
244    if (base_ == 0) return;
245    const Api& a = api();
246    for (int64_t i = 0; i < chunks(); ++i) vmm_chunk_free(unmap(i));
247    (void) hipMemAddressFree((void*) (uintptr_t) base_, (size_t) ((uint64_t) h_.size() * a.gran));
248    base_ = 0;
249    h_.clear();
250}
251
252int64_t VmmRange::mapped_count() const {
253    int64_t n = 0;
254    for (const VmmChunk h : h_) n += h != 0;
255    return n;
256}
257
258bool VmmRange::map_one(int64_t i, VmmChunk h) {
259    const Api& a = api();
260    if (const hipError_t e = hipMemMap((void*) (uintptr_t) (base_ + (uint64_t) i * a.gran), (size_t) a.gran, 0,
261                                      (hipMemGenericAllocationHandle_t) (uintptr_t) h, 0);
262        e != hipSuccess) {
263        fail("hipMemMap", e);
264        return false;
265    }
266    h_[(size_t) i] = h;
267    return true;
268}
269
270bool VmmRange::set_access(int64_t lo, int64_t hi) {
271    if (hi <= lo) return true;
272    const Api& a = api();
273    hipMemAccessDesc d{};
274    d.location.type = hipMemLocationTypeDevice;
275    d.location.id = a.dev;
276    d.flags = hipMemAccessFlagsProtReadWrite;
277    const hipError_t e = hipMemSetAccess((void*) (uintptr_t) (base_ + (uint64_t) lo * a.gran), (size_t) ((uint64_t) (hi - lo) * a.gran),
278                                         &d, 1);
279    const bool ok = e == hipSuccess;
280    if (!ok) fail("hipMemSetAccess", e);
281    return ok;
282}
283
284bool VmmRange::commit_run(int64_t lo, int64_t hi) {
285    if (set_access(lo, hi)) return true;
286    for (int64_t c = lo; c < hi; ++c) vmm_chunk_free(unmap(c));
287    return false;
288}
289
290VmmChunk VmmRange::unmap(int64_t i) {
291    if (!mapped(i)) return 0;
292    const Api& a = api();
293    const VmmChunk h = h_[(size_t) i];
294    if (hipMemUnmap((void*) (uintptr_t) (base_ + (uint64_t) i * a.gran), (size_t) a.gran) != hipSuccess) { (void) hipGetLastError(); return 0; }
295    h_[(size_t) i] = 0;
296    return h;
297}
298}  // namespace strata::core
299#else
300
301
302namespace strata::core {
303bool vmm_available() { return false; }
304uint64_t vmm_granularity() { return 0; }
305VmmChunk vmm_chunk_new() { return 0; }
306void vmm_chunk_free(VmmChunk) {}
307bool VmmRange::reserve(uint64_t) { return false; }
308void VmmRange::release() {}
309int64_t VmmRange::mapped_count() const { return 0; }
310bool VmmRange::map_one(int64_t, VmmChunk) { return false; }
311bool VmmRange::set_access(int64_t, int64_t) { return false; }
312bool VmmRange::commit_run(int64_t, int64_t) { return false; }
313VmmChunk VmmRange::unmap(int64_t) { return 0; }
314}  // namespace strata::core
315
316#endif
317#endif