Files
nvdriver/tools/ioctl_capture/cuda_basic.py

65 lines
2.4 KiB
Python

#!/usr/bin/env python3
"""Minimal CUDA driver-API workload: init, context, alloc, H2D, D2H, free, destroy.
Run under tools/ioctl_capture/capture_stock.sh so the ioctl sequence is recorded.
"""
import ctypes
import sys
def _bind_cuda(cuda):
signatures = {
"cuInit": ([ctypes.c_uint], ctypes.c_int),
"cuDeviceGet": ([ctypes.POINTER(ctypes.c_int), ctypes.c_int], ctypes.c_int),
"cuCtxCreate_v2": ([ctypes.POINTER(ctypes.c_void_p), ctypes.c_uint, ctypes.c_int], ctypes.c_int),
"cuMemAlloc_v2": ([ctypes.POINTER(ctypes.c_uint64), ctypes.c_size_t], ctypes.c_int),
"cuMemcpyHtoD_v2": ([ctypes.c_uint64, ctypes.c_void_p, ctypes.c_size_t], ctypes.c_int),
"cuMemcpyDtoH_v2": ([ctypes.c_void_p, ctypes.c_uint64, ctypes.c_size_t], ctypes.c_int),
"cuCtxSynchronize": ([], ctypes.c_int),
"cuMemFree_v2": ([ctypes.c_uint64], ctypes.c_int),
"cuCtxDestroy_v2": ([ctypes.c_void_p], ctypes.c_int),
}
for name, (argtypes, restype) in signatures.items():
fn = getattr(cuda, name)
fn.argtypes = argtypes
fn.restype = restype
return cuda
def ok(name, rc):
print(f"{name}: {rc}", flush=True)
if rc != 0 and name != "cuCtxDestroy_v2":
sys.exit(f"{name} failed with {rc}")
def main():
cuda = _bind_cuda(ctypes.CDLL("libcuda.so.1"))
ok("cuInit", cuda.cuInit(0))
dev = ctypes.c_int()
ok("cuDeviceGet", cuda.cuDeviceGet(ctypes.byref(dev), 0))
ctx = ctypes.c_void_p()
ok("cuCtxCreate_v2", cuda.cuCtxCreate_v2(ctypes.byref(ctx), 0, dev.value))
ptr = ctypes.c_uint64()
try:
try:
ok("cuMemAlloc_v2", cuda.cuMemAlloc_v2(ctypes.byref(ptr), 1 << 20))
src = (ctypes.c_ubyte * 4096)(*[i & 0xFF for i in range(4096)])
dst = (ctypes.c_ubyte * 4096)()
ok("cuMemcpyHtoD_v2", cuda.cuMemcpyHtoD_v2(ptr.value, src, 4096))
ok("cuMemcpyDtoH_v2", cuda.cuMemcpyDtoH_v2(dst, ptr.value, 4096))
ok("cuCtxSynchronize", cuda.cuCtxSynchronize())
matched = bytes(src) == bytes(dst)
print("roundtrip_match", matched, flush=True)
if not matched:
sys.exit("roundtrip mismatch between H2D and D2H buffers")
finally:
if ptr.value:
ok("cuMemFree_v2", cuda.cuMemFree_v2(ptr.value))
finally:
if ctx.value:
ok("cuCtxDestroy_v2", cuda.cuCtxDestroy_v2(ctx))
if __name__ == "__main__":
main()