Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/engine/message-queue.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const edsm = @import("edsm.zig"); const ecap = @import("event-capture.zig"); const esrc = @import("event-sources.zig"); pub const MessageDispatcher = struct { const Self = @This(); mq: *MessageQueue, eq: ecap.EventQueue, /// Ring buffer (non-growable) that holds messages pub const MessageQueue = struct { const MQ = @This(); cap: u32, storage: []Message, index_mask: u32, r_index: u32, w_index: u32, n_items: u32, pub const Error = error { IsFull, }; /// This structure decribes a message being sent to stage machines pub const Message = struct { /// internal messages pub const M0: u4 = 0; pub const M1: u4 = 1; pub const M2: u4 = 2; pub const M3: u4 = 3; pub const M4: u4 = 4; pub const M5: u4 = 5; pub const M6: u4 = 6; pub const M7: u4 = 7; /// read()/accept() will not block (POLLIN) pub const D0: u4 = 0; /// write() will not block/connection established (POLLOUT) pub const D1: u4 = 1; /// error happened (POLLERR, POLLHUP, POLLRDHUP) pub const D2: u4 = 2; /// timers pub const T0: u4 = 0; pub const T1: u4 = 1; pub const T2: u4 = 2; /// signals pub const S0: u4 = 0; pub const S1: u4 = 1; pub const S2: u4 = 2; /// file system events (TODO) pub const F0: u4 = 0; pub const F1: u4 = 1; pub const F2: u4 = 2; /// message sender (null for messages from OS) src: ?*edsm.StageMachine, /// message recipient (null will stop event loop) dst: ?*edsm.StageMachine, /// row number for stage reflex matrix esk: esrc.EventSource.Kind, /// column number for stage reflex matrix sqn: u4, /// *EventSource for messages from OS (Tx, Sx, Dx, Fx), /// otherwise (Mx) pointer to some arbitrary data if needed ptr: ?*anyopaque, }; pub fn onHeap(a: Allocator, order: u5) !*MessageQueue { var mq = try a.create(MessageQueue); mq.cap = @as(u32, 1) << order; mq.storage = try a.alloc(Message, mq.cap); mq.index_mask = mq.cap - 1; mq.r_index = 0; mq.w_index = mq.cap - 1; mq.n_items = 0; return mq; } pub fn onStack(a: Allocator, order: u5) !MessageQueue { const cap = @as(u32, 1) << order; const buf = try a.alloc(Message, cap); return MessageQueue { .cap = cap, .storage = buf, .index_mask = cap - 1, .r_index = 0, .w_index = cap - 1, .n_items = 0, }; } pub fn put(self: *MQ, item: Message) !void { if (self.n_items == self.cap) return error.IsFull; self.w_index += 1; self.w_index &= self.index_mask; self.storage[self.w_index] = item; self.n_items += 1; } pub fn get(self: *MQ) ?Message { if (0 == self.n_items) return null; const item = self.storage[self.r_index]; self.n_items -= 1; self.r_index += 1; self.r_index &= self.index_mask; return item; } }; pub fn onStack(a: Allocator, mq_cap_order: u5) !MessageDispatcher { const mq = try MessageQueue.onHeap(a, mq_cap_order); const eq = try ecap.EventQueue.onStack(mq); return MessageDispatcher { .mq = mq, .eq = eq, }; } /// message processing loop pub fn loop(self: *Self) !void { outer: while (true) { while (true) { const msg = self.mq.get() orelse break; if (msg.dst) |sm| { sm.reactTo(msg); } else { if (msg.src) |sm| { if (sm.current_stage.leave) |bye| { bye(sm); } } break :outer; } } try self.eq.wait(); } } };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/engine/edsm.zig
const std = @import("std"); const print = std.debug.print; const Allocator = std.mem.Allocator; const mq = @import("message-queue.zig"); const MessageDispatcher = mq.MessageDispatcher; const MessageQueue = MessageDispatcher.MessageQueue; const Message = MessageQueue.Message; const esrc = @import("event-sources.zig"); const EventSource = esrc.EventSource; const AboutSignal= EventSource.AboutSignal; const AboutIo = EventSource.AboutIo; const AboutTimer= EventSource.AboutTimer; pub const StageMachine = struct { const Self = @This(); name: []const u8 = undefined, namebuf: [32]u8 = undefined, is_running: bool = false, stages: StageList, current_stage: *Stage = undefined, md: *MessageDispatcher, allocator: Allocator, data: ?*anyopaque = null, const StageMachineError = error { IsAlreadyRunning, HasNoStates, }; const StageList = std.ArrayList(StageMachine.Stage); pub const Stage = struct { const reactFnPtr = *const fn(me: *StageMachine, src: ?*StageMachine, data: ?*anyopaque) void; const enterFnPtr = *const fn(me: *StageMachine) void; const leaveFnPtr = enterFnPtr; const ReflexKind = enum { action, transition }; pub const Reflex = union(ReflexKind) { action: reactFnPtr, transition: *Stage, }; /// number of rows in reflex matrix const nrows = @typeInfo(EventSource.Kind).Enum.fields.len; const esk_tags = "MDSTF"; /// number of columns in reflex matrix const ncols = 16; /// name of a stage name: []const u8, /// called when machine enters a stage enter: ?enterFnPtr = null, /// called when machine leaves a stage leave: ?leaveFnPtr = null, /// reflex matrix /// row 0: M0 M1 M2 ... M15 : internal messages /// row 1: D0 D1 D2 : i/o (POLLIN, POLLOUT, POLLERR) /// row 2: S0 S1 S2 ... S15 : signals /// row 3: T0 T1 T2 ... T15 : timers /// row 4: F0.............. : file system events reflexes: [nrows][ncols]?Reflex = [nrows][ncols]?Reflex { [_]?Reflex{null} ** ncols, [_]?Reflex{null} ** ncols, [_]?Reflex{null} ** ncols, [_]?Reflex{null} ** ncols, [_]?Reflex{null} ** ncols, }, sm: *StageMachine = undefined, pub fn setReflex(self: *Stage, esk: EventSource.Kind, seqn: u4, refl: Reflex) void { const row: u8 = @intFromEnum(esk); const col: u8 = seqn; if (self.reflexes[row][col]) |_| { print("{s}/{s} already has relfex for '{c}{}'\n", .{self.sm.name, self.name, esk_tags[row], seqn}); unreachable; } self.reflexes[row][col] = refl; } }; pub fn init(a: Allocator, md: *MessageDispatcher) StageMachine { return StageMachine { .md = md, .stages = StageList.init(a), .allocator = a, }; } pub fn onHeap(a: Allocator, md: *MessageDispatcher, name: []const u8, numb: u16) !*StageMachine { var sm = try a.create(StageMachine); sm.* = init(a, md); sm.name = try std.fmt.bufPrint(&sm.namebuf, "{s}-{}", .{name, numb}); return sm; } pub fn addStage(self: *Self, st: Stage) !void { const ptr = try self.stages.addOne(); ptr.* = st; ptr.*.sm = self; } pub fn initTimer(self: *Self, tm: *EventSource, seqn: u4) !void { tm.* = EventSource.init(self, .tm, .none, seqn); try tm.getId(.{}); } pub fn initSignal(self: *Self, sg: *EventSource, signo: u6, seqn: u4) !void { sg.* = EventSource.init(self, .sg, .none, seqn); try sg.getId(.{signo}); } pub fn initListener(self: *Self, io: *EventSource, port: u16) !void { io.* = EventSource.init(self, .io, .ssock, Message.D0); try io.getId(.{port}); } pub fn initIo(self: *Self, io: *EventSource) void { io.id = -1; io.kind = .io; io.info = EventSource.Info{.io = AboutIo{}}; io.owner = self; io.seqn = 0; // undefined; } /// state machine engine pub fn reactTo(self: *Self, msg: Message) void { const row: u8 = @intFromEnum(msg.esk); const col = msg.sqn; const current_stage = self.current_stage; var sender = if (msg.src) |s| s.name else "OS"; if (msg.src == self) sender = "SELF"; print( "{s} @ {s} got '{c}{}' from {s}\n", .{self.name, current_stage.name, Stage.esk_tags[row], col, sender} ); if (current_stage.reflexes[row][col]) |refl| { switch (refl) { .action => |func| func(self, msg.src, msg.ptr), .transition => |next_stage| { if (current_stage.leave) |func| { func(self); // func(self, next_stage)?.. might be useful } self.current_stage = next_stage; if (next_stage.enter) |func| { func(self); } }, } } else { print( "\n{s} @ {s} : no reflex for '{c}{}'\n", .{self.name, current_stage.name, Stage.esk_tags[row], col} ); unreachable; } } pub fn msgTo(self: *Self, dst: ?*Self, sqn: u4, data: ?*anyopaque) void { const msg = Message { .src = self, .dst = dst, .esk = .sm, .sqn = sqn, .ptr = data, }; // message buffer is not growable so this will panic // when there is no more space left in the buffer self.md.mq.put(msg) catch unreachable; } pub fn run(self: *Self) !void { if (0 == self.stages.items.len) return error.HasNoStates; if (self.is_running) return error.IsAlreadyRunning; self.current_stage = &self.stages.items[0]; if (self.current_stage.enter) |hello| { hello(self); } self.is_running = true; } };
0
repos/edsm-in-zig-demo-2/src
repos/edsm-in-zig-demo-2/src/engine/event-sources.zig
const std = @import("std"); const os = std.os; const mem = std.mem; const net = std.net; const timerFd = std.posix.timerfd_create; const timerFdSetTime = std.posix.timerfd_settime; const TimeSpec = os.linux.timespec; const ITimerSpec = os.linux.itimerspec; const signalFd = std.posix.signalfd; const sigProcMask = std.posix.sigprocmask; const SigSet = std.posix.sigset_t; const SIG = std.posix.SIG; const SigInfo = os.linux.signalfd_siginfo; const edsm = @import("edsm.zig"); const StageMachine = edsm.StageMachine; const ecap = @import("event-capture.zig"); //pub const ClientSocket = struct { // fd: i32, // addr: net.Address, //}; pub const EventSource = struct { const Self = @This(); kind: Kind, subkind: SubKind, id: i32 = -1, // fd in most cases, but not always owner: *StageMachine, seqn: u4 = 0, info: Info, pub const Kind = enum { sm, // state machine io, // socket, serial etc. sg, // signal tm, // timer fs, // file system }; /// this is for i/o kind, for other kind must be set to 'none' pub const SubKind = enum { none, ssock, // listening TCP socket csock, // client TCP socket serdev, // '/dev/ttyS0' and alike }; pub const AboutIo = struct { bytes_avail: u32 = 0, }; pub const AboutTimer = struct { nexp: u64 = 0, }; pub const AboutSignal = struct { sig_info: SigInfo = undefined, }; pub const Info = union(Kind) { sm: void, io: AboutIo, sg: AboutSignal, tm: AboutTimer, fs: void, }; pub fn init( owner: *StageMachine, esk: EventSource.Kind, essk: EventSource.SubKind, seqn: u4 ) EventSource { if ((esk != .io) and (essk != .none)) unreachable; return EventSource { .kind = esk, .subkind = essk, .owner = owner, .seqn = seqn, .info = switch (esk) { .io => Info{.io = AboutIo{}}, .sg => Info{.sg = AboutSignal{}}, .tm => Info{.tm = AboutTimer{}}, else => unreachable, } }; } fn getServerSocketFd(port: u16) !i32 { const fd = try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.STREAM, std.posix.IPPROTO.TCP); errdefer std.posix.close(fd); const yes = mem.toBytes(@as(c_int, 1)); try std.posix.setsockopt(fd, std.posix.SOL.SOCKET, std.posix.SO.REUSEADDR, &yes); const addr = net.Address.initIp4(.{0,0,0,0}, port); const socklen = addr.getOsSockLen(); try std.posix.bind(fd, &addr.any, socklen); try std.posix.listen(fd, 128); return fd; } pub fn acceptClient(self: *Self) !i32 { if (self.kind != .io) unreachable; if (self.subkind != .ssock) unreachable; var addr: net.Address = undefined; var alen: std.posix.socklen_t = @sizeOf(net.Address); return try std.posix.accept(self.id, &addr.any, &alen, 0); } fn getClientSocketFd() !i32 { return try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.STREAM, std.posix.IPPROTO.TCP); } pub fn startConnect(self: *Self, addr: *net.Address) !void { const InProgress = std.posix.ConnectError.WouldBlock; if (self.kind != .io) unreachable; if (self.subkind != .csock) unreachable; var flags = std.posix.fcntl(self.id, std.posix.F.GETFL, 0) catch unreachable; flags |= std.posix.SOCK.NONBLOCK; _ = std.posix.fcntl(self.id, std.posix.F.SETFL, flags) catch unreachable; std.posix.connect(self.id, &addr.any, addr.getOsSockLen()) catch |err| { switch (err) { InProgress => return, else => return err, } }; } fn getIoId(subkind: EventSource.SubKind, args: anytype) !i32 { return switch (subkind) { .ssock => if (1 == args.len) try getServerSocketFd(args[0]) else unreachable, .csock => if (0 == args.len) try getClientSocketFd() else unreachable, else => unreachable, }; } fn getSignalId(signo: u6) !i32 { var sset: SigSet = std.posix.empty_sigset; // block the signal std.os.linux.sigaddset(&sset, signo); sigProcMask(SIG.BLOCK, &sset, null); return signalFd(-1, &sset, 0); } fn getTimerId() !i32 { return try timerFd(std.posix.CLOCK.REALTIME, .{}); } /// obtain fd from OS pub fn getId(self: *Self, args: anytype) !void { self.id = switch (self.kind) { .io => try getIoId(self.subkind, args), .sg => blk: { if (1 != args.len) unreachable; const signo: u6 = @intCast(args[0]); break :blk try getSignalId(signo); }, .tm => if (0 == args.len) try getTimerId() else unreachable, else => unreachable, }; } fn setTimer(id: i32, msec: u32) !void { const its = ITimerSpec { .it_interval = TimeSpec { .sec = 0, .nsec = 0, }, .it_value = TimeSpec { .sec = msec / 1000, .nsec = (msec % 1000) * 1000 * 1000, }, }; try timerFdSetTime(id, .{}, &its, null); } pub fn enable(self: *Self, eq: *ecap.EventQueue, args: anytype) !void { try eq.enableCanRead(self); if (self.kind == .tm) { if (1 == args.len) try setTimer(self.id, args[0]) else unreachable; } } pub fn enableOut(self: *Self, eq: *ecap.EventQueue) !void { if (self.kind != .io) unreachable; try eq.enableCanWrite(self); } pub fn disable(self: *Self, eq: *ecap.EventQueue) !void { if (self.kind == .tm) try setTimer(self.id, 0); try eq.disableEventSource(self); } fn readTimerInfo(self: *Self) !void { const p1 = switch (self.kind) { .tm => &self.info.tm.nexp, else => unreachable, }; var p2: [*]u8 = @ptrCast(@alignCast(p1)); var buf = p2[0..@sizeOf(AboutTimer)]; _ = try std.posix.read(self.id, buf[0..]); } fn readSignalInfo(self: *Self) !void { const p1 = switch (self.kind) { .sg => &self.info.sg.sig_info, else => unreachable, }; var p2: [*]u8 = @ptrCast(@alignCast(p1)); var buf = p2[0..@sizeOf(SigInfo)]; _ = try std.posix.read(self.id, buf[0..]); } pub fn readInfo(self: *Self) !void { switch (self.kind) { .sg => try readSignalInfo(self), .tm => try readTimerInfo(self), else => return, } } };
0
repos
repos/cudaz/Readme.md
# Cudaz ## Overview The main motivation for this project was to complete the assignment of [Intro to Parallel Programming](https://classroom.udacity.com/courses/cs344) using as little C++ as possible. The class is meant to use Cuda. Cuda is a superset of C++ with custom annotation to distinguish between device (GPU) functions and host (CPU) functions. They also have special variables for GPU thread IDs and special syntax to schedule a GPU function. You're supposed to compile this Cuda code using `nvcc` NVidia proprietary compiler. But Cuda also has a C api that you can call easily in Zig. And you can also load device code using a the PTX "assembly" format. This assembly can be produced by `nvptx` itself, allowing you to write only the GPU code in C, compile it with `nvcc` and load it from your Zig code. Since Zig can parse the C code for GPU, it knows the signature of your device code and can properly call them. The second, more experimental, way is to generate the PTX using LLVM through Zig stage 2. That way you can write both host and device code in Zig. ## Project structure This repo is divided in several parts: * `cudaz` folder contains the "library" code * `CS344` contains code for all the lesson and homework. Typically code is divided in two files. Host code: `hw1.zig` Device code: `hw1.cu` or `hw1_kernel.zig` * [lodepng](https://github.com/lvandeve/lodepng) is a dependency to read/write images. * Run `git submodule init; git submodule update` to fetch it. ## Using Zig to drive the GPU A lot of the magic happens in `build.zig` and notably in `addCudaz` function. Generally we assume one executable will only have one .ptx. This is actually important because we need to `cImport` at the same time `cuda.h` and your device code. I don't think it's a huge constraint since you can include several files in your main device code file. The main gotchas is that the .cu code must be `C` not `C++`. To help with this you can include [cuda_helpers.h](./cudaz/cuda_helpers.h) that defines a few helpers like min/max. You also need to disable name mangling by wrapping your full device code with: ```C #ifdef __cplusplus extern "C" { #endif ... #ifdef __cplusplus } #endif ``` The `#ifdef __cplusplus` is unfortunately needed because the `extern "C"` will trip up the Zig C-parser. I recommend looking at the examples to learn more about how the API work. And also taking the full class :-) To use block-shared memory (`__shared` keyword in Cuda) you'll need to use the `SHARED` macro defined in [cuda_helpers.h](./cudaz/cuda_helpers.h). The main issue with the Cuda API, is that most operation will use the default context and default GPU. This make it a bit awkward if you need to write code to drive two GPUs, because you'll need to call `cuContextPush`/`cuContextPop` every time you want to talk to the other GPU. I haven't tried to fix this in the Zig wrapper which is just a wrapper with some utility function (also my laptop has only one GPU). ## Using Zig to write device code For this I'm using stage2 compiler. Zig stage1 can theoretically target the PTX platform too but it's seems to be broken in 0.9 dev versions. (nvptx-cuda platform is Tier4 of support which means "unsupported by Zig but LLVM has the flag, so maybe it will work") I was able to use a [light fork](https://github.com/gwenzek/zig/pull/1) of Zig stage2 to generate a `.ptx` though without having to do any crazy stuff. More details and pointers can be found on this ["documentation issue"](https://github.com/ziglang/zig/issues/10064)
0
repos/cudaz
repos/cudaz/CS344/build.zig
const std = @import("std"); const cuda_sdk = @import("cudaz/sdk.zig"); const CUDA_PATH = "/usr/local/cuda"; const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; const RunStep = std.build.RunStep; var target: std.zig.CrossTarget = undefined; var mode: std.builtin.Mode = undefined; pub fn build(b: *Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. mode = b.standardReleaseOptions(); var tests = b.step("test", "Tests"); const test_png = b.addTest("src/png.zig"); addLodePng(test_png); tests.dependOn(&test_png.step); // CS344 lessons and home works const hw1 = addHomework(b, tests, "hw1"); addLesson(b, "lesson2"); const hw2 = addHomework(b, tests, "hw2"); addLesson(b, "lesson3"); const hw3 = addHomework(b, tests, "hw3"); const hw4 = addHomework(b, tests, "hw4"); // addZigLesson(b, "lesson5"); const run_step = b.step("run", "Run the example"); const run_hw1 = hw1.run(); run_hw1.step.dependOn(b.getInstallStep()); run_step.dependOn(&run_hw1.step); const run_hw2 = hw2.run(); run_hw2.step.dependOn(b.getInstallStep()); run_step.dependOn(&run_hw2.step); const run_hw3 = hw3.run(); run_hw3.step.dependOn(b.getInstallStep()); run_step.dependOn(&run_hw3.step); const run_hw4 = hw4.run(); run_hw4.step.dependOn(b.getInstallStep()); run_step.dependOn(&run_hw4.step); // Pure const run_pure_step = b.step("run_pure", "Run the example"); const hw1_pure = addZigHomework(b, tests, "hw1_pure"); run_pure_step.dependOn(&hw1_pure.step); const hw2_pure = addZigHomework(b, tests, "hw2_pure"); run_pure_step.dependOn(&hw2_pure.step); const hw5 = addZigHomework(b, tests, "hw5"); run_pure_step.dependOn(&hw5.step); } fn addLodePng(exe: *LibExeObjStep) void { // TODO remove libc dependency exe.linkLibC(); const lodepng_flags = [_][]const u8{ "-DLODEPNG_COMPILE_ERROR_TEXT", }; exe.addIncludeDir("lodepng/"); exe.addCSourceFile("lodepng/lodepng.c", &lodepng_flags); } fn addHomework(b: *Builder, tests: *std.build.Step, comptime name: []const u8) *LibExeObjStep { const hw = b.addExecutable(name, "src/" ++ name ++ ".zig"); hw.setTarget(target); hw.setBuildMode(mode); cuda_sdk.addCudazWithNvcc(b, hw, CUDA_PATH, "src/" ++ name ++ ".cu"); addLodePng(hw); hw.install(); const test_hw = b.addTest("src/" ++ name ++ ".zig"); cuda_sdk.addCudazWithNvcc(b, test_hw, CUDA_PATH, "src/" ++ name ++ ".cu"); tests.dependOn(&test_hw.step); return hw; } fn addZigHomework(b: *Builder, tests: *std.build.Step, comptime name: []const u8) *RunStep { const hw = b.addExecutable(name, "src/" ++ name ++ ".zig"); hw.setTarget(target); hw.setBuildMode(mode); cuda_sdk.addCudazWithZigKernel(b, hw, CUDA_PATH, "src/" ++ name ++ "_kernel.zig"); addLodePng(hw); hw.install(); const hw_run = hw.run(); hw_run.step.dependOn(b.getInstallStep()); const test_hw = b.addTest("src/" ++ name ++ ".zig"); cuda_sdk.addCudazWithZigKernel(b, test_hw, CUDA_PATH, "src/" ++ name ++ "_kernel.zig"); tests.dependOn(&test_hw.step); return hw_run; } fn addLesson(b: *Builder, comptime name: []const u8) void { const lesson = b.addExecutable(name, "src/" ++ name ++ ".zig"); cuda_sdk.addCudazWithNvcc(b, lesson, CUDA_PATH, "src/" ++ name ++ ".cu"); lesson.setTarget(target); lesson.setBuildMode(mode); lesson.install(); const run_lesson_step = b.step(name, "Run " ++ name); const run_lesson = lesson.run(); run_lesson.step.dependOn(b.getInstallStep()); run_lesson_step.dependOn(&run_lesson.step); } fn addZigLesson(b: *Builder, comptime name: []const u8) void { const lesson = b.addExecutable(name, "src/" ++ name ++ ".zig"); cuda_sdk.addCudazWithZigKernel(b, lesson, CUDA_PATH, "src/" ++ name ++ "_kernel.zig"); lesson.setTarget(target); lesson.setBuildMode(mode); lesson.install(); const run_lesson_step = b.step(name, "Run " ++ name); const run_lesson = lesson.run(); run_lesson.step.dependOn(b.getInstallStep()); run_lesson_step.dependOn(&run_lesson.step); }
0
repos/cudaz/CS344/resources
repos/cudaz/CS344/resources/hw5/ncu_report.txt
==PROF== Connected to process 118431 (/home/guw/github/cudaz/CS344/zig-out/bin/hw5) ==PROF== Profiling "atomicHistogram" - 1: 0%....50%....100% - 8 passes ==PROF== Profiling "bychunkHistogram" - 2: 0%....50%....100% - 8 passes ==PROF== Disconnected from process 118431 [118431] [email protected] atomicHistogram, 2021-Dec-13 10:49:41, Context 1, Stream 14 Section: GPU Speed Of Light Throughput ---------------------------------------------------------------------- --------------- ------------------------------ DRAM Frequency cycle/nsecond 5,50 SM Frequency cycle/usecond 931,21 Elapsed Cycles cycle 4 688 436 Memory [%] % 8,21 DRAM Throughput % 2,31 Duration msecond 5,03 L1/TEX Cache Throughput % 12,66 L2 Cache Throughput % 8,21 SM Active Cycles cycle 4 627 894,17 Compute (SM) [%] % 1,02 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel exhibits low compute throughput and memory bandwidth utilization relative to the peak performance of this device. Achieved compute throughput and/or memory bandwidth below 60.0% of peak typically indicate latency issues. Look at Scheduler Statistics and Warp State Statistics for potential reasons. Section: Launch Statistics ---------------------------------------------------------------------- --------------- ------------------------------ Block Size 1 024 Function Cache Configuration cudaFuncCachePreferNone Grid Size 10 000 Registers Per Thread register/thread 16 Shared Memory Configuration Size Kbyte 32,77 Driver Shared Memory Per Block byte/block 0 Dynamic Shared Memory Per Block Kbyte/block 4,10 Static Shared Memory Per Block byte/block 0 Threads thread 10 240 000 Waves Per SM 250 ---------------------------------------------------------------------- --------------- ------------------------------ Section: Occupancy ---------------------------------------------------------------------- --------------- ------------------------------ Block Limit SM block 16 Block Limit Registers block 4 Block Limit Shared Mem block 16 Block Limit Warps block 1 Theoretical Active Warps per SM warp 32 Theoretical Occupancy % 100 Achieved Occupancy % 54,93 Achieved Active Warps Per SM warp 17,58 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel's theoretical occupancy is not impacted by any block limit. The difference between calculated theoretical (100.0%) and measured achieved occupancy (54.9%) can be the result of warp scheduling overheads or workload imbalances during the kernel execution. Load imbalances can occur between warps within a block as well as across blocks of the same kernel. See the CUDA Best Practices Guide (https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#occupancy) for more details on optimizing occupancy. bychunkHistogram, 2021-Dec-13 10:49:41, Context 1, Stream 15 Section: GPU Speed Of Light Throughput ---------------------------------------------------------------------- --------------- ------------------------------ DRAM Frequency cycle/nsecond 5,51 SM Frequency cycle/usecond 932,85 Elapsed Cycles cycle 178 011 Memory [%] % 63,66 DRAM Throughput % 63,66 Duration usecond 190,82 L1/TEX Cache Throughput % 54,20 L2 Cache Throughput % 24,43 SM Active Cycles cycle 165 075,15 Compute (SM) [%] % 19,10 ---------------------------------------------------------------------- --------------- ------------------------------ WRN Memory is more heavily utilized than Compute: Look at the Memory Workload Analysis report section to see where the memory system bottleneck is. Check memory replay (coalescing) metrics to make sure you're efficiently utilizing the bytes transferred. Also consider whether it is possible to do more work per memory access (kernel fusion) or whether there are values you can (re)compute. Section: Launch Statistics ---------------------------------------------------------------------- --------------- ------------------------------ Block Size 1 024 Function Cache Configuration cudaFuncCachePreferNone Grid Size 313 Registers Per Thread register/thread 30 Shared Memory Configuration Size Kbyte 32,77 Driver Shared Memory Per Block byte/block 0 Dynamic Shared Memory Per Block Kbyte/block 4,10 Static Shared Memory Per Block byte/block 0 Threads thread 320 512 Waves Per SM 7,83 ---------------------------------------------------------------------- --------------- ------------------------------ Section: Occupancy ---------------------------------------------------------------------- --------------- ------------------------------ Block Limit SM block 16 Block Limit Registers block 2 Block Limit Shared Mem block 16 Block Limit Warps block 1 Theoretical Active Warps per SM warp 32 Theoretical Occupancy % 100 Achieved Occupancy % 99,63 Achieved Active Warps Per SM warp 31,88 ---------------------------------------------------------------------- --------------- ------------------------------ INF This kernel's theoretical occupancy is not impacted by any block limit.
0
repos/cudaz/CS344/resources
repos/cudaz/CS344/resources/lesson5/ncu_report.txt
==PROF== Connected to process 635218 (/home/guw/github/cudaz/CS344/zig-out/bin/lesson5) ==PROF== Profiling "transposeCpu" - 1: 0%....50%....100% - 8 passes ==PROF== Profiling "transposePerRow" - 2: 0%....50%....100% - 8 passes ==PROF== Profiling "transposePerCell" - 3: 0%....50%....100% - 8 passes ==PROF== Profiling "transposePerBlock" - 4: 0%....50%....100% - 8 passes ==PROF== Profiling "transposePerBlockInlined" - 5: 0%....50%....100% - 8 passes ==PROF== Disconnected from process 635218 [635218] [email protected] transposeCpu, 2021-Nov-26 16:34:08, Context 1, Stream 13 Section: GPU Speed Of Light Throughput ---------------------------------------------------------------------- --------------- ------------------------------ DRAM Frequency cycle/usecond 404,05 SM Frequency cycle/usecond 150,47 Elapsed Cycles cycle 719 098 237 Memory [%] % 3,90 DRAM Throughput % 3,90 Duration second 4,75 L1/TEX Cache Throughput % 2,36 L2 Cache Throughput % 0,17 SM Active Cycles cycle 17 805 789,30 Compute (SM) [%] % 0,06 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel grid is too small to fill the available resources on this device, resulting in only 0.0 full waves across all SMs. Look at Launch Statistics for more details. Section: Launch Statistics ---------------------------------------------------------------------- --------------- ------------------------------ Block Size 1 Function Cache Configuration cudaFuncCachePreferNone Grid Size 1 Registers Per Thread register/thread 30 Shared Memory Configuration Size Kbyte 32,77 Driver Shared Memory Per Block byte/block 0 Dynamic Shared Memory Per Block byte/block 0 Static Shared Memory Per Block byte/block 0 Threads thread 1 Waves Per SM 0,00 ---------------------------------------------------------------------- --------------- ------------------------------ WRN Threads are executed in groups of 32 threads called warps. This kernel launch is configured to execute 1 threads per block. Consequently, some threads in a warp are masked off and those hardware resources are unused. Try changing the number of threads per block to be a multiple of 32 threads. Between 128 and 256 threads per block is a good initial range for experimentation. Use smaller thread blocks rather than one large thread block per multiprocessor if latency affects performance. This is particularly beneficial to kernels that frequently call __syncthreads(). See the Hardware Model (https://docs.nvidia.com/nsight-compute/ProfilingGuide/index.html#metrics-hw-model) description for more details on launch configurations. ----- -------------------------------------------------------------------------------------------------------------- WRN The grid for this launch is configured to execute only 1 blocks, which is less than the GPU's 40 multiprocessors. This can underutilize some multiprocessors. If you do not intend to execute this kernel concurrently with other workloads, consider reducing the block size to have at least one block per multiprocessor or increase the size of the grid to fully utilize the available hardware resources. See the Hardware Model (https://docs.nvidia.com/nsight-compute/ProfilingGuide/index.html#metrics-hw-model) description for more details on launch configurations. Section: Occupancy ---------------------------------------------------------------------- --------------- ------------------------------ Block Limit SM block 16 Block Limit Registers block 64 Block Limit Shared Mem block 16 Block Limit Warps block 32 Theoretical Active Warps per SM warp 16 Theoretical Occupancy % 50 Achieved Occupancy % 3,12 Achieved Active Warps Per SM warp 1 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel's theoretical occupancy (50.0%) is limited by the required amount of shared memory This kernel's theoretical occupancy (50.0%) is limited by the number of blocks that can fit on the SM The difference between calculated theoretical (50.0%) and measured achieved occupancy (3.1%) can be the result of warp scheduling overheads or workload imbalances during the kernel execution. Load imbalances can occur between warps within a block as well as across blocks of the same kernel. See the CUDA Best Practices Guide (https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#occupancy) for more details on optimizing occupancy. transposePerRow, 2021-Nov-26 16:34:08, Context 1, Stream 13 Section: GPU Speed Of Light Throughput ---------------------------------------------------------------------- --------------- ------------------------------ DRAM Frequency cycle/usecond 394,69 SM Frequency cycle/usecond 146,96 Elapsed Cycles cycle 1 000 183 Memory [%] % 22,99 DRAM Throughput % 22,99 Duration msecond 6,77 L1/TEX Cache Throughput % 42,84 L2 Cache Throughput % 6,80 SM Active Cycles cycle 967 911,25 Compute (SM) [%] % 2,64 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel grid is too small to fill the available resources on this device, resulting in only 0.1 full waves across all SMs. Look at Launch Statistics for more details. Section: Launch Statistics ---------------------------------------------------------------------- --------------- ------------------------------ Block Size 32 Function Cache Configuration cudaFuncCachePreferNone Grid Size 64 Registers Per Thread register/thread 24 Shared Memory Configuration Size Kbyte 32,77 Driver Shared Memory Per Block byte/block 0 Dynamic Shared Memory Per Block byte/block 0 Static Shared Memory Per Block byte/block 0 Threads thread 2 048 Waves Per SM 0,10 ---------------------------------------------------------------------- --------------- ------------------------------ WRN If you execute __syncthreads() to synchronize the threads of a block, it is recommended to have more than the achieved 1 blocks per multiprocessor. This way, blocks that aren't waiting for __syncthreads() can keep the hardware busy. Section: Occupancy ---------------------------------------------------------------------- --------------- ------------------------------ Block Limit SM block 16 Block Limit Registers block 84 Block Limit Shared Mem block 16 Block Limit Warps block 32 Theoretical Active Warps per SM warp 16 Theoretical Occupancy % 50 Achieved Occupancy % 5,00 Achieved Active Warps Per SM warp 1,60 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel's theoretical occupancy (50.0%) is limited by the required amount of shared memory This kernel's theoretical occupancy (50.0%) is limited by the number of blocks that can fit on the SM The difference between calculated theoretical (50.0%) and measured achieved occupancy (5.0%) can be the result of warp scheduling overheads or workload imbalances during the kernel execution. Load imbalances can occur between warps within a block as well as across blocks of the same kernel. See the CUDA Best Practices Guide (https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#occupancy) for more details on optimizing occupancy. transposePerCell, 2021-Nov-26 16:34:09, Context 1, Stream 13 Section: GPU Speed Of Light Throughput ---------------------------------------------------------------------- --------------- ------------------------------ DRAM Frequency cycle/usecond 415,83 SM Frequency cycle/usecond 154,84 Elapsed Cycles cycle 449 053 Memory [%] % 47,71 DRAM Throughput % 46,00 Duration msecond 2,88 L1/TEX Cache Throughput % 95,41 L2 Cache Throughput % 14,95 SM Active Cycles cycle 430 471,58 Compute (SM) [%] % 5,88 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel exhibits low compute throughput and memory bandwidth utilization relative to the peak performance of this device. Achieved compute throughput and/or memory bandwidth below 60.0% of peak typically indicate latency issues. Look at Scheduler Statistics and Warp State Statistics for potential reasons. Section: Launch Statistics ---------------------------------------------------------------------- --------------- ------------------------------ Block Size 1 024 Function Cache Configuration cudaFuncCachePreferNone Grid Size 4 096 Registers Per Thread register/thread 16 Shared Memory Configuration Size Kbyte 32,77 Driver Shared Memory Per Block byte/block 0 Dynamic Shared Memory Per Block byte/block 0 Static Shared Memory Per Block byte/block 0 Threads thread 4 194 304 Waves Per SM 102,40 ---------------------------------------------------------------------- --------------- ------------------------------ Section: Occupancy ---------------------------------------------------------------------- --------------- ------------------------------ Block Limit SM block 16 Block Limit Registers block 4 Block Limit Shared Mem block 16 Block Limit Warps block 1 Theoretical Active Warps per SM warp 32 Theoretical Occupancy % 100 Achieved Occupancy % 60,56 Achieved Active Warps Per SM warp 19,38 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel's theoretical occupancy is not impacted by any block limit. The difference between calculated theoretical (100.0%) and measured achieved occupancy (60.6%) can be the result of warp scheduling overheads or workload imbalances during the kernel execution. Load imbalances can occur between warps within a block as well as across blocks of the same kernel. See the CUDA Best Practices Guide (https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#occupancy) for more details on optimizing occupancy. transposePerBlock, 2021-Nov-26 16:34:10, Context 1, Stream 13 Section: GPU Speed Of Light Throughput ---------------------------------------------------------------------- --------------- ------------------------------ DRAM Frequency cycle/usecond 404,06 SM Frequency cycle/usecond 150,47 Elapsed Cycles cycle 223 696 Memory [%] % 48,93 DRAM Throughput % 48,93 Duration msecond 1,48 L1/TEX Cache Throughput % 62,84 L2 Cache Throughput % 3,89 SM Active Cycles cycle 217 340,30 Compute (SM) [%] % 17,68 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel exhibits low compute throughput and memory bandwidth utilization relative to the peak performance of this device. Achieved compute throughput and/or memory bandwidth below 60.0% of peak typically indicate latency issues. Look at Scheduler Statistics and Warp State Statistics for potential reasons. Section: Launch Statistics ---------------------------------------------------------------------- --------------- ------------------------------ Block Size 512 Function Cache Configuration cudaFuncCachePreferNone Grid Size 8 192 Registers Per Thread register/thread 18 Shared Memory Configuration Size Kbyte 32,77 Driver Shared Memory Per Block byte/block 0 Dynamic Shared Memory Per Block Kbyte/block 1,02 Static Shared Memory Per Block Kbyte/block 1,02 Threads thread 4 194 304 Waves Per SM 102,40 ---------------------------------------------------------------------- --------------- ------------------------------ Section: Occupancy ---------------------------------------------------------------------- --------------- ------------------------------ Block Limit SM block 16 Block Limit Registers block 5 Block Limit Shared Mem block 32 Block Limit Warps block 2 Theoretical Active Warps per SM warp 32 Theoretical Occupancy % 100 Achieved Occupancy % 91,55 Achieved Active Warps Per SM warp 29,29 ---------------------------------------------------------------------- --------------- ------------------------------ INF This kernel's theoretical occupancy is not impacted by any block limit. transposePerBlockInlined, 2021-Nov-26 16:34:10, Context 1, Stream 13 Section: GPU Speed Of Light Throughput ---------------------------------------------------------------------- --------------- ------------------------------ DRAM Frequency cycle/usecond 401,90 SM Frequency cycle/usecond 149,62 Elapsed Cycles cycle 642 827 Memory [%] % 43,21 DRAM Throughput % 33,82 Duration msecond 4,27 L1/TEX Cache Throughput % 86,42 L2 Cache Throughput % 11,48 SM Active Cycles cycle 615 088,18 Compute (SM) [%] % 7,92 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel exhibits low compute throughput and memory bandwidth utilization relative to the peak performance of this device. Achieved compute throughput and/or memory bandwidth below 60.0% of peak typically indicate latency issues. Look at Scheduler Statistics and Warp State Statistics for potential reasons. Section: Launch Statistics ---------------------------------------------------------------------- --------------- ------------------------------ Block Size 256 Function Cache Configuration cudaFuncCachePreferNone Grid Size 16 384 Registers Per Thread register/thread 24 Shared Memory Configuration Size Kbyte 65,54 Driver Shared Memory Per Block byte/block 0 Dynamic Shared Memory Per Block Kbyte/block 16,38 Static Shared Memory Per Block Kbyte/block 16,38 Threads thread 4 194 304 Waves Per SM 204,80 ---------------------------------------------------------------------- --------------- ------------------------------ Section: Occupancy ---------------------------------------------------------------------- --------------- ------------------------------ Block Limit SM block 16 Block Limit Registers block 10 Block Limit Shared Mem block 2 Block Limit Warps block 4 Theoretical Active Warps per SM warp 16 Theoretical Occupancy % 50 Achieved Occupancy % 47,25 Achieved Active Warps Per SM warp 15,12 ---------------------------------------------------------------------- --------------- ------------------------------ WRN This kernel's theoretical occupancy (50.0%) is limited by the required amount of shared memory See the CUDA Best Practices Guide (https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#occupancy) for more details on optimizing occupancy.
0
repos/cudaz/CS344
repos/cudaz/CS344/src/lesson2.zig
const std = @import("std"); const log = std.log; const cuda = @import("cudaz"); const cu = cuda.cu; const ARRAY_SIZE = 100; pub fn main() anyerror!void { var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = general_purpose_allocator.allocator(); const args = try std.process.argsAlloc(alloc); defer std.process.argsFree(alloc, args); var stream = try cuda.Stream.init(0); defer stream.deinit(); // Instructions: This program is needed for the next quiz // uncomment increment_naive to measure speed and accuracy // of non-atomic increments or uncomment increment_atomic to // measure speed and accuracy of atomic icrements time_kernel(alloc, &stream, "increment_naive", 1e6, 1000, 1e6); time_kernel(alloc, &stream, "increment_atomic", 1e6, 1000, 1e6); time_kernel(alloc, &stream, "increment_naive", 1e6, 1000, 100); time_kernel(alloc, &stream, "increment_atomic", 1e6, 1000, 100); time_kernel(alloc, &stream, "increment_atomic", 1e7, 1000, 100); } fn time_kernel( alloc: std.mem.Allocator, stream: *cuda.Stream, comptime kernel_name: [:0]const u8, num_threads: u32, block_width: u32, comptime array_size: u32, ) void { _time_kernel(alloc, stream, kernel_name, num_threads, block_width, array_size) catch |err| { log.err("Failed to run kernel {s}: {}", .{ kernel_name, err }); }; } fn _time_kernel( alloc: std.mem.Allocator, stream: *cuda.Stream, comptime kernel_name: [:0]const u8, num_threads: u32, block_width: u32, comptime array_size: u32, ) !void { const kernel = try cuda.CudaKernel(kernel_name).init(); // declare and allocate memory const h_array = try alloc.alloc(i32, array_size); defer alloc.free(h_array); var d_array = try cuda.alloc(i32, array_size); defer cuda.free(d_array); try cuda.memset(i32, d_array, 0); log.info("*** Will benchmark kernel {s} ***", .{kernel_name}); log.info("{} total threads in {} blocks writing into {} array elements", .{ num_threads, num_threads / block_width, array_size }); var timer = cuda.GpuTimer.start(stream); try kernel.launch( stream, cuda.Grid.init1D(num_threads, block_width), .{ d_array.ptr, array_size }, ); timer.stop(); // copy back the array of sums from GPU and print try cuda.memcpyDtoH(i32, h_array, d_array); log.info("array: {any}", .{h_array[0..std.math.min(h_array.len, 100)]}); log.info("time elapsed: {d:.4} ms", .{timer.elapsed()}); }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/utils.zig
const std = @import("std"); const assert = std.debug.assert; const log = std.log; const cuda = @import("cudaz"); const cu = cuda.cu; const png = @import("png.zig"); const Image = png.Image; const builtin = @import("builtin"); const CallingConvention = @import("std").builtin.CallingConvention; pub const is_nvptx = builtin.cpu.arch == .nvptx64; pub const kernel: CallingConvention = if (is_nvptx) .PtxKernel else .Unspecified; pub fn validate_output(alloc: std.mem.Allocator, comptime dir: []const u8, threshold: f32) !void { const output = try Image.fromFilePath(alloc, dir ++ "output.png"); const reference = try Image.fromFilePath(alloc, dir ++ "reference.png"); log.info("Loaded output image and reference image for comparison", .{}); assert(output.width == reference.width); assert(output.height == reference.height); // assert(output.image_format == reference.image_format); assert(output.raw().len == reference.raw().len); const avg_diff = try eq_and_show_diff(alloc, dir, output, reference); if (avg_diff < threshold) { log.info("*** The image matches, Congrats ! ***", .{}); } } pub fn eq_and_show_diff(alloc: std.mem.Allocator, comptime dir: []const u8, output: Image, reference: Image) !f32 { var diff = try png.Image.init(alloc, reference.width, reference.height, .gray8); var out_pxls = output.iterator(); var ref_pxls = reference.iterator(); const num_pixels = reference.width * reference.height; var i: usize = 0; var min_val: f32 = 255; var max_val: f32 = -255; var total: f32 = 0; while (true) { var ref_pxl = ref_pxls.next(); if (ref_pxl == null) break; var out_pxl = out_pxls.next(); var d = ref_pxl.?.r - out_pxl.?.r; d = std.math.fabs(d); min_val = std.math.min(min_val, d); max_val = std.math.max(max_val, d); i += 1; total += d; } var avg_diff = 255.0 * total / @intToFloat(f32, num_pixels); i = 0; var diff_pxls = diff.px.gray8; while (true) { var ref_pxl = ref_pxls.next(); if (ref_pxl == null) break; var out_pxl = out_pxls.next(); var d = ref_pxl.?.r - out_pxl.?.r; d = std.math.fabs(d); const centered_d = 255.0 * (d - min_val) / (max_val - min_val); diff_pxls[i] = @floatToInt(u8, centered_d); i += 1; } try diff.writeToFilePath(dir ++ "output_diff.png"); if (min_val != 0 or max_val != 0) { std.log.err("Found diffs between two images, avg: {d:.3}, ranging from {d:.1} to {d:.1} pixel value.", .{ avg_diff, 255 * min_val, 255 * max_val }); } return avg_diff; } pub fn asUchar3(img: Image) []cu.uchar3 { var ptr: [*]cu.uchar3 = @ptrCast([*]cu.uchar3, img.px.rgb24); const num_pixels = img.width * img.height; return ptr[0..num_pixels]; } pub fn expectEqualDeviceSlices( comptime DType: type, h_expected: []const DType, d_values: []const DType, ) !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); const h_values = try cuda.allocAndCopyResult(DType, allocator, d_values); defer allocator.free(h_values); std.testing.expectEqualSlices(DType, h_expected, h_values) catch |err| { if (h_expected.len < 80) { log.err("Expected: {any}, got: {any}", .{ h_expected, h_values }); } return err; }; }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/kernel_utils.zig
// TODO: should be moved to Cudaz const std = @import("std"); const builtin = @import("builtin"); const TypeInfo = std.builtin.TypeInfo; const CallingConvention = @import("std").builtin.CallingConvention; pub const is_nvptx = builtin.cpu.arch == .nvptx64; pub const Kernel = if (is_nvptx) CallingConvention.PtxKernel else CallingConvention.Unspecified; // Size for storing a thread id pub const utid = u32; pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn { _ = error_return_trace; _ = msg; asm volatile ("trap;"); unreachable; } pub fn threadIdX() utid { if (!is_nvptx) return 0; var tid = asm volatile ("mov.u32 \t%[r], %tid.x;" : [r] "=r" (-> utid), ); return tid; } pub fn blockDimX() utid { if (!is_nvptx) return 0; var ntid = asm volatile ("mov.u32 \t%[r], %ntid.x;" : [r] "=r" (-> utid), ); return ntid; } pub fn blockIdX() utid { if (!is_nvptx) return 0; var ctaid = asm volatile ("mov.u32 \t%[r], %ctaid.x;" : [r] "=r" (-> utid), ); return ctaid; } pub fn gridDimX() utid { if (!is_nvptx) return 0; var nctaid = asm volatile ("mov.u32 \t%[r], %nctaid.x;" : [r] "=r" (-> utid), ); return nctaid; } pub fn getIdX() utid { return threadIdX() + blockDimX() * blockIdX(); } pub fn threadIdY() utid { if (!is_nvptx) return 0; var tid = asm volatile ("mov.u32 \t%[r], %tid.y;" : [r] "=r" (-> utid), ); return tid; } pub fn blockDimY() utid { if (!is_nvptx) return 0; var ntid = asm volatile ("mov.u32 \t%[r], %ntid.y;" : [r] "=r" (-> utid), ); return ntid; } pub fn blockIdY() utid { if (!is_nvptx) return 0; var ctaid = asm volatile ("mov.u32 \t%[r], %ctaid.y;" : [r] "=r" (-> utid), ); return ctaid; } pub fn threadIdZ() utid { if (!is_nvptx) return 0; var tid = asm volatile ("mov.u32 \t%[r], %tid.z;" : [r] "=r" (-> utid), ); return tid; } pub fn blockDimZ() utid { if (!is_nvptx) return 0; var ntid = asm volatile ("mov.u32 \t%[r], %ntid.z;" : [r] "=r" (-> utid), ); return ntid; } pub fn blockIdZ() utid { if (!is_nvptx) return 0; var ctaid = asm volatile ("mov.u32 \t%[r], %ctaid.z;" : [r] "=r" (-> utid), ); return ctaid; } pub fn syncThreads() void { if (!is_nvptx) return; asm volatile ("bar.sync \t0;"); } pub fn atomicAdd(x: *u32, a: u32) void { _ = @atomicRmw(u32, x, .Add, a, .SeqCst); } pub fn lastTid(n: usize) utid { var block_dim = blockDimX(); if (blockIdX() == gridDimX() - 1) { return @intCast(utid, (n - 1) % block_dim); } else { return block_dim - 1; } } const Dim2 = struct { x: usize, y: usize }; pub fn getId_2D() Dim2 { return Dim2{ .x = threadIdX() + blockDimX() * blockIdX(), .y = threadIdY() + blockDimY() * blockIdY(), }; } const Dim3 = struct { x: u32, y: u32, z: u32 }; pub fn getId_3D() Dim3 { return Dim3{ .x = threadIdX() + blockDimX() * blockIdX(), .y = threadIdY() + blockDimY() * blockIdY(), .z = threadIdZ() + blockDimZ() * blockIdZ(), }; } // pub fn exportModule(comptime Module: anytype, comptime Exports: anytype) void { // if (!is_nvptx) return; // // TODO assert call conv // const fields: []const TypeInfo.StructField = std.meta.fields(Exports); // // var args_ptrs: [fields.len:0]usize = undefined; // // https://github.com/ziglang/zig/issues/12532 // inline for (fields) |field, i| { // @export(@field(Module, field.name), .{ .name = field.name, .linkage = .Strong }); // } // } pub const Operator = enum { add, mul, min, max }; /// Exclusive scan using Blelloch algorithm /// Returns the total value which won't be part of the array // TODO: use generics once it works in Stage2 pub fn exclusiveScan( comptime op: Operator, data: anytype, tid: usize, last_tid: usize, ) u32 { var step: u32 = 1; while (step <= last_tid) : (step *= 2) { if (tid >= step and (last_tid - tid) % (step * 2) == 0) { var right = data[tid]; var left = data[tid - step]; data[tid] = switch (op) { .add => right + left, .mul => right * left, .min => if (left < right) left else right, .max => if (left > right) left else right, }; } syncThreads(); } var total: u32 = 0; if (tid == last_tid) { total = data[tid]; data[tid] = 0; } syncThreads(); step /= 2; while (step > 0) : (step /= 2) { if (tid >= step and (last_tid - tid) % (step * 2) == 0) { var right = data[tid]; var left = data[tid - step]; data[tid] = switch (op) { .add => right + left, .mul => right * left, .min => if (left < right) left else right, .max => if (left > right) left else right, }; data[tid - step] = right; } syncThreads(); } return total; }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/lesson6.zig
// TODO: implement algorithms mentioned in the class // 1. N-body simulation // 2. Sparse Matrix Vector multiply // a. per-element // b. per-row // c. mixed approach // 3. Breadth First Search in Graph // a. naive implementation: N^2 work / N steps algorithm // b. more complex implementation with "frontier" // 4. Find linked-list end // 5. Linked-list ranking // 6. Cuckoo hashing
0
repos/cudaz/CS344
repos/cudaz/CS344/src/hw1_pure.zig
const std = @import("std"); const log = std.log; const assert = std.debug.assert; const cudaz = @import("cudaz"); const cu = cudaz.cu; const png = @import("png.zig"); const utils = @import("utils.zig"); const hw1_kernel = @import("hw1_pure_kernel.zig"); const resources_dir = "resources/hw1_resources/"; pub fn main() anyerror!void { log.info("***** HW1 ******", .{}); var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = general_purpose_allocator.allocator(); const args = try std.process.argsAlloc(alloc); defer std.process.argsFree(alloc, args); var stream = try cudaz.Stream.init(0); defer stream.deinit(); const img = try png.Image.fromFilePath(alloc, resources_dir ++ "cinque_terre_small.png"); defer img.deinit(); var max_show: usize = 12; log.info("Loaded img {}x{}: ({any}...)", .{ img.width, img.height, std.mem.sliceAsBytes(img.px.rgb24[200 .. 200 + max_show]) }); const Rgb24 = png.Rgb24; var d_img = try cudaz.allocAndCopy(Rgb24, img.px.rgb24); defer cudaz.free(d_img); const Gray8 = png.Gray8; var gray = try png.grayscale(alloc, img.width, img.height); defer gray.deinit(); var d_gray = try cudaz.alloc(Gray8, img.width * img.height); defer cudaz.free(d_gray); try cudaz.memset(Gray8, d_gray, 0); const kernel = try cudaz.ZigKernel(hw1_kernel, "rgba_to_greyscale").init(); var timer = cudaz.GpuTimer.start(&stream); try kernel.launch( &stream, cudaz.Grid.init1D(img.height * img.width, 64), .{ std.mem.sliceAsBytes(d_img), std.mem.sliceAsBytes(d_gray) }, ); timer.stop(); try cudaz.memcpyDtoH(Gray8, gray.px.gray8, d_gray); log.info("Got grayscale img {}x{}: ({any}...)", .{ img.width, img.height, std.mem.sliceAsBytes(gray.px.gray8[200 .. 200 + @divExact(max_show, 3)]) }); try gray.writeToFilePath(resources_dir ++ "output.png"); try utils.validate_output(alloc, resources_dir, 1.0); }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/lesson7_kernel.zig
const ku = @import("kernel_utils.zig"); const cu = @import("cudaz").cu; const Kernel = ku.Kernel; pub export fn quicksort(d_out: []f32) callconv(.Kernel) void { // TODO: this should be a "no-divergence point", mark it as such if (d_out.len == 1) return; const tid = ku.getIdX(); // TODO actual run partitionning const pivot_id = d_out.len / 2; const sub_stream: cu.CUstream = undefined; if (tid == 0 and pivot_id > 0) { // Left stream cu.cudaStreamCreateWithFlags(&sub_stream, CU_STREAM_NON_BLOCKING); // quicksort<<<(n + 1023) / 1024, 1024, 0, sub_stream>>>(&d_out[pivot_id], n - pivot_id); } // TODO: right stream // Even better we can start the two streams at once. }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/hw2.zig
const std = @import("std"); const log = std.log; const math = std.math; const assert = std.debug.assert; const cuda = @import("cudaz"); const cu = cuda.cu; const png = @import("png.zig"); const utils = @import("utils.zig"); const resources_dir = "resources/hw2_resources/"; const Rgb24 = png.Rgb24; const Gray8 = png.Gray8; pub fn main() anyerror!void { log.info("***** HW2 ******", .{}); var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = general_purpose_allocator.allocator(); try all_tests(alloc); const args = try std.process.argsAlloc(alloc); defer std.process.argsFree(alloc, args); var stream = try cuda.Stream.init(0); defer stream.deinit(); const img = try png.Image.fromFilePath(alloc, resources_dir ++ "cinque_terre_small.png"); defer img.deinit(); assert(img.px == .rgb24); var max_show: usize = 10; log.info("Loaded img {}x{}: ({any}...)", .{ img.width, img.height, std.mem.sliceAsBytes(img.px.rgb24[200 .. 200 + max_show]) }); var d_img = try cuda.allocAndCopy(Rgb24, img.px.rgb24); defer cuda.free(d_img); var d_red = try cuda.alloc(Gray8, img.width * img.height); defer cuda.free(d_red); var d_green = try cuda.alloc(Gray8, img.width * img.height); defer cuda.free(d_green); var d_blue = try cuda.alloc(Gray8, img.width * img.height); defer cuda.free(d_blue); var d_red_blured = try cuda.alloc(Gray8, img.width * img.height); defer cuda.free(d_red_blured); var d_green_blured = try cuda.alloc(Gray8, img.width * img.height); defer cuda.free(d_green_blured); var d_blue_blured = try cuda.alloc(Gray8, img.width * img.height); defer cuda.free(d_blue_blured); const d_buffers = [_][2]@TypeOf(d_red){ .{ d_red, d_red_blured }, .{ d_green, d_green_blured }, .{ d_blue, d_blue_blured }, }; var d_out = try cuda.alloc(Rgb24, img.width * img.height); defer cuda.free(d_out); const separateChannels = try cuda.CudaKernel("separateChannels").init(); const gaussianBlur = try cuda.CudaKernel("gaussian_blur").init(); const recombineChannels = try cuda.CudaKernel("recombineChannels").init(); var d_filter = try cuda.allocAndCopy(f32, &blurFilter()); defer cuda.free(d_filter); var grid2D = cuda.Grid.init2D(img.height, img.width, 32, 32); try separateChannels.launch( &stream, grid2D, .{ @ptrCast([*c]const cu.uchar3, d_img.ptr), @intCast(c_int, img.height), @intCast(c_int, img.width), @ptrCast([*c]u8, d_red.ptr), @ptrCast([*c]u8, d_green.ptr), @ptrCast([*c]u8, d_blue.ptr), }, ); var timer = cuda.GpuTimer.start(&stream); for (d_buffers) |d_src_tgt| { try gaussianBlur.launch( &stream, grid2D, .{ @ptrCast([*c]const u8, d_src_tgt[0].ptr), @ptrCast([*c]u8, d_src_tgt[1].ptr), @intCast(c_uint, img.height), @intCast(c_uint, img.width), @ptrCast([*c]const f32, d_filter), @intCast(c_int, blurKernelWidth), }, ); } timer.stop(); var h_red = try png.grayscale(alloc, img.width, img.height); try cuda.memcpyDtoH(Gray8, h_red.px.gray8, d_red_blured); try h_red.writeToFilePath(resources_dir ++ "output_red.png"); try recombineChannels.launch( &stream, grid2D, .{ @ptrCast([*c]const u8, d_red_blured.ptr), @ptrCast([*c]const u8, d_green_blured.ptr), @ptrCast([*c]const u8, d_blue_blured.ptr), @ptrCast([*c]cu.uchar3, d_out.ptr), @intCast(c_int, img.height), @intCast(c_int, img.width), }, ); try cuda.memcpyDtoH(Rgb24, img.px.rgb24, d_out); try img.writeToFilePath(resources_dir ++ "output.png"); try utils.validate_output(alloc, resources_dir, 2.0); } const blurKernelWidth = 9; fn blurFilter() [blurKernelWidth * blurKernelWidth]f32 { const blurKernelSigma = 2.0; // create and fill the filter we will convolve with var filter: [blurKernelWidth * blurKernelWidth]f32 = undefined; var filterSum: f32 = 0.0; // for normalization const halfWidth: i8 = @divTrunc(blurKernelWidth, 2); var r: i8 = -halfWidth; while (r <= halfWidth) : (r += 1) { var c: i8 = -halfWidth; while (c <= halfWidth) : (c += 1) { const filterValue: f32 = math.exp(-@intToFloat(f32, c * c + r * r) / (2.0 * blurKernelSigma * blurKernelSigma)); filter[@intCast(usize, (r + halfWidth) * blurKernelWidth + c + halfWidth)] = filterValue; filterSum += filterValue; } } const normalizationFactor = 1.0 / filterSum; var result: f32 = 0.0; for (filter) |*v| { v.* *= normalizationFactor; result += v.*; } return filter; } fn all_tests(alloc: std.mem.Allocator) !void { var arena_alloc = std.heap.ArenaAllocator.init(alloc); defer arena_alloc.deinit(); try test_gaussianBlur(arena_alloc.allocator()); } fn test_gaussianBlur(alloc: std.mem.Allocator) !void { // const blur_kernel_size = blurKernelWidth * blurKernelWidth; var cols: c_uint = 50; var rows: c_uint = 100; var img: []u8 = try alloc.alloc(u8, @intCast(usize, rows * cols)); std.mem.set(u8, img, 100); var out: []u8 = try alloc.alloc(u8, @intCast(usize, rows * cols)); std.mem.set(u8, out, 0); cu.blockDim = cu.dim3{ .x = cols, .y = rows, .z = 1 }; cu.blockIdx = cu.dim3{ .x = 0, .y = 0, .z = 0 }; cu.threadIdx = cu.dim3{ .x = 10, .y = 10, .z = 0 }; cu.gaussian_blur(img.ptr, out.ptr, rows, cols, &blurFilter(), blurKernelWidth); try std.testing.expectEqual(out[cols * 10 + 10], 100); cu.threadIdx = cu.dim3{ .x = cols - 1, .y = 10, .z = 0 }; cu.gaussian_blur(img.ptr, out.ptr, rows, cols, &blurFilter(), blurKernelWidth); try std.testing.expectEqual(out[cols * 11 - 1], 100); try std.testing.expectEqual(out[cols * 11 - 1], 100); } fn recombine( img: png.Image, red: []const Gray8, green: []const Gray8, blue: []const Gray8, ) !void { for (img.px) |_, i| { img.px.rgb24[i] = Rgb24(red[i], green[i], blue[i]); } }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/lesson5.zig
//! Compare implementations of different transpose algorithms //! Compile with Zig, then run: sudo /usr/local/cuda/bin/ncu ./CS344/zig-out/bin/lesson5 > ./CS344/resources/lesson5/ncu_report.txt //! This will generate a performance report const std = @import("std"); const Allocator = std.mem.Allocator; const Random = std.rand.DefaultPrng; const base_log = std.log.scoped(.lesson5); const cuda = @import("cudaz"); const cu = cuda.cu; const RawKernels = @import("lesson5_kernel.zig"); pub fn main() !void { try nosuspend amain(); } const CudaEventLoop = struct { running_streams: std.ArrayList(*cuda.Stream), suspended_frames: std.ArrayList(anyframe), pub fn initCapacity(allocator: Allocator, num: usize) !CudaEventLoop { return CudaEventLoop{ .running_streams = try std.ArrayList(*cuda.Stream).initCapacity(allocator, num), .suspended_frames = try std.ArrayList(anyframe).initCapacity(allocator, num), }; } pub fn deinit(self: *CudaEventLoop) void { self.running_streams.deinit(); self.suspended_frames.deinit(); } pub fn registerStream(self: *CudaEventLoop, stream: *cuda.Stream, frame: anyframe) void { self.running_streams.appendAssumeCapacity(stream); self.suspended_frames.appendAssumeCapacity(frame); } pub fn joinStreamsAndResume(self: *CudaEventLoop) void { var n_streams = self.running_streams.items.len; std.debug.assert(self.suspended_frames.items.len == n_streams); while (self.running_streams.items.len > 0) { for (self.running_streams.items) |stream, i| { if (stream.done()) { _ = self.running_streams.swapRemove(i); resume self.suspended_frames.swapRemove(i); break; } } else { // only sleep if no frame was resumed. std.time.sleep(100 * std.time.ns_per_us); } } self.deinit(); } }; pub fn amain() !void { var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = general_purpose_allocator.allocator(); var random = Random.init(10298374); const num_cols: usize = 2048; var data = try allocator.alloc(u32, num_cols * num_cols); defer allocator.free(data); random.fill(std.mem.sliceAsBytes(data)); var trans_cpu = try allocator.alloc(u32, num_cols * num_cols); defer allocator.free(trans_cpu); var timer = std.time.Timer.start() catch unreachable; RawKernels.transposeCpu(data, trans_cpu, num_cols); const elapsed_cpu = @intToFloat(f32, timer.lap()) / std.time.ns_per_us; base_log.info("CPU transpose of {}x{} matrix took {:.3}ms", .{ num_cols, num_cols, elapsed_cpu }); try initModule(0); gpuInfo(0); // var elapsed = try transposeSerial(&stream, d_data, d_trans, num_cols); // log.info("GPU serial transpose of {}x{} matrix took {:.3}ms", .{ num_cols, num_cols, elapsed }); // log.info("GPU serial transpose bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6}); // This is not the best way of doing profiling cause we are // scheduling all kernels at the same time on the GPU // and they will interfere with each others. // But it shows how multi streams work. var ex = try CudaEventLoop.initCapacity(allocator, 4); var per_row = async transposePerRow(&ex, allocator, data, num_cols); var per_cell = async transposePerCell(&ex, allocator, data, num_cols); var per_block = async transposePerBlock(&ex, allocator, data, num_cols); var per_block_inline = async transposePerBlockInlined(&ex, allocator, data, num_cols); ex.joinStreamsAndResume(); // nosuspend ensure that joinStreams has correctly resumed the frames already. try nosuspend await per_row; try nosuspend await per_cell; try nosuspend await per_block; try nosuspend await per_block_inline; } fn transposeSerial(stream: *cuda.Stream, d_data: []const u32, d_out: []u32, num_cols: usize) !f64 { var timer = cuda.GpuTimer.start(stream); try k.transposeCpu.launch( stream, cuda.Grid.init1D(1, 1), .{ d_data, d_out, num_cols }, ); timer.stop(); try expectTransposed(d_data, d_out, num_cols); return timer.elapsed(); } fn transposePerRow(ex: *CudaEventLoop, allocator: Allocator, data: []const u32, num_cols: usize) !void { var stream = cuda.Stream.init(0) catch unreachable; defer stream.deinit(); const d_data = try stream.alloc(u32, data.len); stream.memcpyHtoD(u32, d_data, data); var out = try allocator.alloc(u32, data.len); defer allocator.free(out); const d_out = try stream.alloc(u32, data.len); defer cuda.free(d_out); const log = std.log.scoped(.transposePerRow); log.info("Scheduling GPU", .{}); var timer = cuda.GpuTimer.start(&stream); k.transposePerRow.launch( &stream, cuda.Grid.init1D(num_cols, 32), .{ d_data, d_out, num_cols }, ) catch unreachable; timer.stop(); stream.memcpyDtoH(u32, out, d_out); // Yield control to main loop suspend { ex.registerStream(&stream, @frame()); } stream.synchronize(); const elapsed = timer.elapsed(); log.info("{}x{} matrix took {:.3}ms", .{ num_cols, num_cols, elapsed }); log.info("bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6}); expectTransposed(data, out, num_cols) catch { log.err("didn't properly transpose !", .{}); }; } fn transposePerCell(ex: *CudaEventLoop, allocator: Allocator, data: []const u32, num_cols: usize) !void { var stream = cuda.Stream.init(0) catch unreachable; defer stream.deinit(); const d_data = try stream.alloc(u32, data.len); stream.memcpyHtoD(u32, d_data, data); var out = try allocator.alloc(u32, data.len); defer allocator.free(out); const d_out = try stream.alloc(u32, data.len); defer cuda.free(d_out); const log = std.log.scoped(.transposePerCell); log.info("Scheduling GPU", .{}); var timer = cuda.GpuTimer.start(&stream); k.transposePerCell.launch( &stream, cuda.Grid.init2D(num_cols, num_cols, 32, 32), .{ d_data, d_out, num_cols }, ) catch unreachable; timer.stop(); stream.memcpyDtoH(u32, out, d_out); // Yield control to main loop suspend { ex.registerStream(&stream, @frame()); } stream.synchronize(); const elapsed = timer.elapsed(); log.info("{}x{} matrix took {:.3}ms", .{ num_cols, num_cols, elapsed }); log.info("bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6}); expectTransposed(data, out, num_cols) catch { log.err("didn't properly transpose !", .{}); }; } fn transposePerBlock(ex: *CudaEventLoop, allocator: Allocator, data: []const u32, num_cols: usize) !void { var out = try allocator.alloc(u32, data.len); defer allocator.free(out); var stream = cuda.Stream.init(0) catch unreachable; defer stream.deinit(); const d_data = try stream.alloc(u32, data.len); stream.memcpyHtoD(u32, d_data, data); const d_out = try stream.alloc(u32, data.len); defer cuda.free(d_out); const log = std.log.scoped(.transposePerBlock); log.info("Scheduling GPU", .{}); var timer = cuda.GpuTimer.start(&stream); const block_size = RawKernels.block_size; const grid = cuda.Grid.init2D(num_cols, num_cols, 32, block_size); try k.transposePerBlock.launchWithSharedMem( &stream, grid, @sizeOf(u32) * 16 * 16 * 16, .{ d_data, d_out, num_cols }, ); timer.stop(); stream.memcpyDtoH(u32, out, d_out); // Yield control to main loop suspend { ex.registerStream(&stream, @frame()); } stream.synchronize(); const elapsed = timer.elapsed(); log.info("{}x{} matrix took {:.3}ms", .{ num_cols, num_cols, elapsed }); log.info("bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6}); expectTransposed(data, out, num_cols) catch { log.err("didn't properly transpose !", .{}); }; } fn transposePerBlockInlined(ex: *CudaEventLoop, allocator: Allocator, data: []const u32, num_cols: usize) !void { var out = try allocator.alloc(u32, data.len); defer allocator.free(out); var stream = cuda.Stream.init(0) catch unreachable; defer stream.deinit(); const d_data = try stream.alloc(u32, data.len); stream.memcpyHtoD(u32, d_data, data); const d_out = try stream.alloc(u32, data.len); defer cuda.free(d_out); const log = std.log.scoped(.transposePerBlockInlined); log.info("Scheduling GPU", .{}); var timer = cuda.GpuTimer.start(&stream); const block_size = RawKernels.block_size_inline; const grid = cuda.Grid.init2D(num_cols, num_cols, 256 / block_size, block_size); try k.transposePerBlockInlined.launch( &stream, grid, .{ d_data, d_out, num_cols }, ); timer.stop(); stream.memcpyDtoH(u32, out, d_out); // Yield control to main loop suspend { ex.registerStream(&stream, @frame()); } stream.synchronize(); const elapsed = timer.elapsed(); log.info("{}x{} matrix took {:.3}ms", .{ num_cols, num_cols, elapsed }); log.info("bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6}); expectTransposed(data, out, num_cols) catch { log.err("didn't properly transpose !", .{}); }; } const Kernels = struct { transposeCpu: cuda.FnStruct("transposeCpu", RawKernels.transposeCpu), transposePerRow: cuda.FnStruct("transposePerRow", RawKernels.transposePerRow), transposePerCell: cuda.FnStruct("transposePerCell", RawKernels.transposePerCell), transposePerBlock: cuda.FnStruct("transposePerBlock", RawKernels.transposePerBlock), transposePerBlockInlined: cuda.FnStruct("transposePerBlockInlined", RawKernels.transposePerBlockInlined), }; var k: Kernels = undefined; fn initModule(device: u3) !void { _ = try cuda.Stream.init(device); _ = cuda.initDevice(device) catch @panic("No GPU"); // Panic if we can't load the module. k = Kernels{ .transposeCpu = @TypeOf(k.transposeCpu).init() catch unreachable, .transposePerRow = @TypeOf(k.transposePerRow).init() catch unreachable, .transposePerCell = @TypeOf(k.transposePerCell).init() catch unreachable, .transposePerBlock = @TypeOf(k.transposePerBlock).init() catch unreachable, .transposePerBlockInlined = @TypeOf(k.transposePerBlockInlined).init() catch unreachable, }; } fn gpuInfo(device: u8) void { var mem_clock_rate_khz: i32 = cuda.getAttr(device, cuda.Attribute.MemoryClockRate); var mem_bus_width_bits: i32 = cuda.getAttr(device, cuda.Attribute.GlobalMemoryBusWidth); const mem_bus_width_bytes = @intToFloat(f64, @divExact(mem_bus_width_bits, 8)); const peek_bandwith = @intToFloat(f64, mem_clock_rate_khz) * 1e3 * mem_bus_width_bytes; base_log.info("GPU peek bandwith: {:.3}MB/s", .{peek_bandwith * 1e-6}); var l1_cache: i32 = cuda.getAttr(device, cuda.Attribute.GlobalL1CacheSupported); var l2_cache: i32 = cuda.getAttr(device, cuda.Attribute.L2CacheSize); base_log.info("GPU L1 cache {}, L2 cache {}", .{ l1_cache, l2_cache }); } fn computeBandwith(elapsed_ms: f64, data: []const u32) f64 { const n = @intToFloat(f64, data.len); const bytes = @intToFloat(f64, @sizeOf(u32)); return n * bytes / elapsed_ms * 1000; } fn expectTransposed(data: []const u32, trans: []u32, num_cols: usize) !void { var i: usize = 0; while (i < num_cols) : (i += 1) { var j: usize = 0; while (j < num_cols) : (j += 1) { std.testing.expectEqual(data[num_cols * j + i], trans[num_cols * i + j]) catch |err| { if (data.len < 100) { base_log.err("original: {any}", .{data}); base_log.err("transposed: {any}", .{trans}); } base_log.err("failed expectTransposed !", .{}); return err; }; } } }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/lesson3.zig
const std = @import("std"); const log = std.log; const cuda = @import("cudaz"); const cu = cuda.cu; const ShmemReduce = cuda.CudaKernel("shmem_reduce_kernel"); const GlobalReduce = cuda.CudaKernel("global_reduce_kernel"); pub fn main() !void { log.info("***** Lesson 3 ******", .{}); var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = general_purpose_allocator.allocator(); var stream = try cuda.Stream.init(0); try main_reduce(&stream, gpa); try main_histo(&stream, gpa); } fn main_reduce(stream: *const cuda.Stream, gpa: std.mem.Allocator) !void { const array_size: i32 = 1 << 20; // generate the input array on the host var h_in = try gpa.alloc(f32, array_size); defer gpa.free(h_in); log.debug("h_in = {*}", .{h_in.ptr}); var prng = std.rand.DefaultPrng.init(0); const random = prng.random(); var sum: f32 = 0.0; for (h_in) |*value| { // generate random float in [-1.0f, 1.0f] var v = -1.0 + random.float(f32) * 2.0; value.* = v; sum += v; } log.info("original sum = {}", .{sum}); // allocate GPU memory var d_in = try cuda.allocAndCopy(f32, h_in); defer cuda.free(d_in); var d_intermediate = try cuda.alloc(f32, array_size); // overallocated defer cuda.free(d_intermediate); var d_out = try cuda.alloc(f32, 1); defer cuda.free(d_out); // launch the kernel // Run shared_reduced first because it doesn't modify d_in _ = try benchmark_reduce(stream, 100, d_out, d_intermediate, d_in, true); _ = try benchmark_reduce(stream, 100, d_out, d_intermediate, d_in, false); } fn benchmark_reduce( stream: *const cuda.Stream, iter: u32, d_out: []f32, d_intermediate: []f32, d_in: []f32, uses_shared_memory: bool, ) !f32 { if (uses_shared_memory) { log.info("Running shared memory reduce {} times.", .{iter}); } else { log.info("Running global reduce {} times.", .{iter}); } log.info("using cuda: {}", .{cuda}); var reduce_kernel: GlobalReduce = undefined; if (uses_shared_memory) { reduce_kernel = GlobalReduce{ .f = (try ShmemReduce.init()).f }; } else { reduce_kernel = try GlobalReduce.init(); } // Set the buffers to 0 to have correct computation on the first try try cuda.memset(f32, d_intermediate, 0.0); try cuda.memset(f32, d_out, 0.0); var timer = cuda.GpuTimer.start(stream); errdefer timer.deinit(); var result: f32 = undefined; var i: usize = 0; while (i < iter) : (i += 1) { var r_i = try reduce( stream, reduce_kernel, d_out, d_intermediate, d_in, uses_shared_memory, ); if (i == 0) { result = r_i; } } timer.stop(); var avg_time = timer.elapsed() / @intToFloat(f32, iter) * 1000.0; log.info("average time elapsed: {d:.1}ms", .{avg_time}); log.info("found sum = {}", .{result}); return result; } fn reduce(stream: *const cuda.Stream, reduce_kernel: GlobalReduce, d_out: []f32, d_intermediate: []f32, d_in: []f32, uses_shared_memory: bool) !f32 { // assumes that size is not greater than blockSize^2 // and that size is a multiple of blockSize const blockSize: usize = 1024; var size = d_in.len; if (size % blockSize != 0 or size > blockSize * blockSize) { log.err("Can't run reduce operator on an array of size {} with blockSize={} ({})", .{ size, blockSize, blockSize * blockSize }); @panic("Invalid reduce on too big array"); } const full_grid = cuda.Grid.init1D(size, blockSize); var shared_mem = if (uses_shared_memory) blockSize * @sizeOf(f32) else 0; try reduce_kernel.launchWithSharedMem( stream, full_grid, shared_mem, .{ d_intermediate.ptr, d_in.ptr }, ); // try cuda.synchronize(); // now we're down to one block left, so reduce it const one_block = cuda.Grid.init1D(blockSize, 0); try reduce_kernel.launchWithSharedMem( stream, one_block, shared_mem, .{ d_out.ptr, d_intermediate.ptr }, ); // try cuda.synchronize(); var result: [1]f32 = undefined; try cuda.memcpyDtoH(f32, &result, d_out); return result[0]; } fn main_histo(stream: *const cuda.Stream, gpa: std.mem.Allocator) !void { const array_size = 65536; const bin_count = 16; // generate the input array on the host var cpu_bins = [_]i32{0} ** bin_count; var h_in = try gpa.alloc(i32, array_size); for (h_in) |*value, i| { var item = bit_reverse(@intCast(i32, i), log2(array_size)); value.* = item; cpu_bins[@intCast(usize, @mod(item, bin_count))] += 1; } log.info("Cpu bins: {any}", .{cpu_bins}); var naive_bins = [_]i32{0} ** bin_count; var simple_bins = [_]i32{0} ** bin_count; // allocate GPU memory var d_in = try cuda.allocAndCopy(i32, h_in); var d_bins = try cuda.allocAndCopy(i32, &naive_bins); log.info("Running naive histo", .{}); const grid = cuda.Grid{ .blocks = .{ .x = @divExact(array_size, 64) }, .threads = .{ .x = 64 } }; const naive_histo = try cuda.CudaKernel("naive_histo").init(); try naive_histo.launch(stream, grid, .{ d_bins.ptr, d_in.ptr, bin_count }); try cuda.memcpyDtoH(i32, &naive_bins, d_bins); log.info("naive bins: {any}", .{naive_bins}); log.info("Running simple histo", .{}); try cuda.memcpyHtoD(i32, d_bins, &simple_bins); const simple_histo = try cuda.CudaKernel("simple_histo").init(); try simple_histo.launch(stream, grid, .{ d_bins.ptr, d_in.ptr, bin_count }); try cuda.memcpyDtoH(i32, &simple_bins, d_bins); log.info("simple bins: {any}", .{simple_bins}); } fn log2(i: i32) u5 { var r: u5 = 0; var j = i; while (j > 0) : (j >>= 1) { r += 1; } return r; } fn bit_reverse(w: i32, bits: u5) i32 { var r: i32 = 0; var i: u5 = 0; while (i < bits) : (i += 1) { const bit = (w & (@intCast(i32, 1) << i)) >> i; r |= bit << (bits - i - 1); } return r; }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/hw3.zig
const std = @import("std"); const log = std.log; const math = std.math; const testing = std.testing; const assert = std.debug.assert; const cuda = @import("cudaz"); const cu = cuda.cu; const png = @import("png.zig"); const utils = @import("utils.zig"); const resources_dir = "resources/hw3_resources/"; pub fn main() !void { var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = general_purpose_allocator.allocator(); var stream = try cuda.Stream.init(0); defer stream.deinit(); log.info("***** HW3 ******", .{}); const img = try png.Image.fromFilePath(allocator, resources_dir ++ "/memorial_exr.png"); const numRows = img.height; const numCols = img.width; const rgb = try asFloat32(allocator, img); img.deinit(); // load the image and convert it to xyY format const d_rgb = try cuda.allocAndCopy(cu.float3, rgb); const d_xyY = try cuda.alloc(cu.float3, numCols * numRows); const threads = cuda.Dim3.init(32, 16, 1); const blocks = cuda.Dim3.init((numCols + threads.x - 1) / threads.x, (numRows + threads.y - 1) / threads.y, 1); const grid = cuda.Grid{ .blocks = blocks, .threads = threads }; const rgb_to_xyY = try cuda.CudaKernel("rgb_to_xyY").init(); try rgb_to_xyY.launch(&stream, grid, .{ d_rgb.ptr, d_xyY.ptr, 0.0001, @intCast(c_int, numRows), @intCast(c_int, numCols), }); const h_xyY = try allocator.alloc(cu.float3, numCols * numRows); try cuda.memcpyDtoH(cu.float3, h_xyY, d_xyY); // allocate memory for the cdf of the histogram const numBins: usize = 1024; var d_cdf = try cuda.alloc(f32, numBins); defer cuda.free(d_cdf); var timer = cuda.GpuTimer.start(&stream); errdefer timer.deinit(); const min_max_lum = try histogram_and_prefixsum(&stream, d_xyY, d_cdf, numRows, numCols, numBins); var lum_min = min_max_lum.x; var lum_range = min_max_lum.y - min_max_lum.x; timer.stop(); stream.synchronize(); std.log.info("Your code ran in: {d:.1} msecs.", .{timer.elapsed() * 1000}); std.log.info("Found a lum range of: ({d:.5}, {d:.5})", min_max_lum); var h_cdf = try cuda.allocAndCopyResult(f32, allocator, d_cdf); std.log.info("Lum cdf: {d:.3}", .{h_cdf}); const tone_map = try cuda.CudaKernel("tone_map").init(); try tone_map.launch( &stream, grid, .{ d_xyY.ptr, d_cdf.ptr, d_rgb.ptr, lum_min, lum_range, numBins, @intCast(c_int, numRows), @intCast(c_int, numCols), }, ); try cuda.memcpyDtoH(cu.float3, rgb, d_rgb); var out_img = try fromFloat32(allocator, rgb, numCols, numRows); defer out_img.deinit(); try out_img.writeToFilePath(resources_dir ++ "output.png"); try utils.validate_output(allocator, resources_dir, 2.0); try std.testing.expect(lum_range > 0); } fn asFloat32(allocator: std.mem.Allocator, img: png.Image) ![]cu.float3 { var rgb = try allocator.alloc(cu.float3, img.width * img.height); var pixels = img.iterator(); var i: usize = 0; while (pixels.next()) |color| : (i += 1) { rgb[i] = .{ .x = color.r, .y = color.g, .z = color.b, }; } return rgb; } pub inline fn toColorIntClamp(comptime T: type, value: f32) T { if (math.isNan(value)) return 0; var val = value; var max_val = @intToFloat(f32, math.maxInt(T)); var min_val = @intToFloat(f32, math.minInt(T)); val = math.max(min_val, math.min(max_val, val * max_val)); return @floatToInt(T, math.round(val)); } fn fromFloat32(allocator: std.mem.Allocator, rgb: []cu.float3, width: usize, height: usize) !png.Image { var pixels = try allocator.alloc(png.Rgb24, width * height); for (rgb) |value, i| { pixels[i] = png.Rgb24{ .r = toColorIntClamp(u8, value.x), .g = toColorIntClamp(u8, value.y), .b = toColorIntClamp(u8, value.z), }; // if (i % 100 == 0) { // log.debug("{} -> {}", .{ value, pixels[i] }); // } } return png.Image{ .allocator = allocator, .width = @intCast(u32, width), .height = @intCast(u32, height), .px = .{ .rgb24 = pixels }, }; } fn histogram_and_prefixsum( stream: *cuda.Stream, d_xyY: []const cu.float3, d_cdf: []f32, numRows: usize, numCols: usize, numBins: usize, ) !cu.float2 { // Here are the steps you need to implement // 1) find the minimum and maximum value in the input logLuminance channel // store in min_logLum and max_logLum // 2) subtract them to find the range // 3) generate a histogram of all the values in the logLuminance channel using // the formula: bin = (lum[i] - lumMin) / lumRange * numBins // 4) Perform an exclusive scan (prefix sum) on the histogram to get // the cumulative distribution of luminance values (this should go in the // incoming d_cdf pointer which already has been allocated for you) var num_pixels = numRows * numCols; var min_max_lum = try reduceMinMaxLum(stream, d_xyY); const lumHisto = try cuda.CudaKernel("lum_histo").init(); var d_histo = try cuda.alloc(c_uint, numBins); try cuda.memset(c_uint, d_histo, 0); try lumHisto.launch( stream, cuda.Grid.init1D(num_pixels, 1024), .{ d_histo.ptr, d_xyY.ptr, min_max_lum.x, min_max_lum.y - min_max_lum.x, @intCast(c_int, numBins), @intCast(c_int, num_pixels), }, ); const computeCdf = try cuda.CudaKernel("blellochCdf").init(); try computeCdf.launch( stream, cuda.Grid.init1D(numBins, numBins), .{ d_cdf.ptr, d_histo.ptr, @intCast(c_int, numBins) }, ); stream.synchronize(); return min_max_lum; } fn reduceMinMaxLum( stream: *cuda.Stream, d_xyY: []const cu.float3, ) !cu.float2 { // TODO: the results seems to change between runs const num_pixels = d_xyY.len; const reduce_minmax_lum = try cuda.CudaKernel("reduce_minmax_lum").init(); const grid = cuda.Grid.init1D(num_pixels, 1024); var d_buff = try cuda.alloc(cu.float2, grid.blocks.x); defer cuda.free(d_buff); var d_min_max_lum = try cuda.alloc(cu.float2, 1); try cuda.memsetD8(cu.float2, d_min_max_lum, 0xaa); defer cuda.free(d_min_max_lum); try reduce_minmax_lum.launchWithSharedMem( stream, grid, grid.threads.x * @sizeOf(cu.float2), .{ d_xyY.ptr, d_buff.ptr, @intCast(c_int, num_pixels) }, ); const one_block = cuda.Grid.init1D(d_buff.len, 0); const reduce_minmax = try cuda.CudaKernel("reduce_minmax").init(); try reduce_minmax.launchWithSharedMem( stream, one_block, one_block.threads.x * @sizeOf(cu.float2), .{ d_buff.ptr, d_min_max_lum.ptr, @intCast(c_int, num_pixels) }, ); var min_max_lum = try cuda.readResult(cu.float2, &d_min_max_lum[0]); try std.testing.expect(min_max_lum.x < min_max_lum.y); return min_max_lum; } fn z(_z: f32) cu.float3 { return cu.float3{ .x = 0.0, .y = 0.0, .z = _z }; } test "histogram" { var stream = try cuda.Stream.init(0); var img = [_]cu.float3{ z(0.0), z(0.0), z(1.0), z(2.0), z(3.0), z(4.0), z(6.0), z(7.0), z(8.0), z(9.0), z(3.0), z(3.0), z(3.0), z(9.0), z(10.0), }; const lumHisto = try cuda.CudaKernel("lum_histo").init(); var bins = [_]c_uint{0} ** 10; var d_img = try cuda.allocAndCopy(cu.float3, &img); var d_bins = try cuda.allocAndCopy(c_uint, &bins); try lumHisto.launch( &stream, cuda.Grid.init1D(img.len, 3), .{ d_bins.ptr, d_img.ptr, 0, 9, @intCast(c_int, bins.len), @intCast(c_int, img.len), }, ); try cuda.memcpyDtoH(c_uint, &bins, d_bins); std.log.warn("bins: {any}", .{bins}); try std.testing.expectEqual( [10]c_uint{ 2, 1, 1, 4, 1, 0, 1, 1, 1, 3 }, bins, ); } const ReduceMinmaxLum = cuda.CudaKernel("reduce_minmax_lum"); fn test_min_max_lum(stream: *cuda.Stream, f: ReduceMinmaxLum, d_img: []cu.float3, expected: []const cu.float2) !void { var num_blocks = expected.len; var d_minmax = try cuda.alloc(cu.float2, num_blocks); defer cuda.free(d_minmax); var grid1D = cuda.Grid{ .blocks = .{ .x = @intCast(c_uint, num_blocks) }, .threads = .{ .x = @intCast(c_uint, std.math.divCeil(usize, d_img.len, num_blocks) catch unreachable) }, }; try f.launchWithSharedMem( stream, grid1D, @sizeOf(cu.float2) * grid1D.threads.x, .{ d_img.ptr, d_minmax.ptr, @intCast(c_int, d_img.len), }, ); var minmax = try cuda.allocAndCopyResult(cu.float2, testing.allocator, d_minmax); defer testing.allocator.free(minmax); std.log.warn("minmax ({}x{}): {any}", .{ grid1D.blocks.x, grid1D.threads.x, minmax }); for (expected) |exp, index| { std.testing.expectEqual(exp, minmax[index]) catch |err| { switch (err) { error.TestExpectedEqual => log.err("At index {} expected {d:.0} got {d:.0}", .{ index, exp, minmax[index] }), else => {}, } return err; }; } } test "min_max_lum" { var stream = try cuda.Stream.init(0); var img = [_]cu.float3{ z(0), z(3), z(0), z(1), z(2), z(4), z(6), z(7), z(8), z(9), z(10), z(3), z(3), z(3), z(9), z(3), }; const f = try ReduceMinmaxLum.init(); var d_img = try cuda.allocAndCopy(cu.float3, &img); try test_min_max_lum(&stream, f, d_img, &[_]cu.float2{ .{ .x = 0, .y = 7 }, .{ .x = 3, .y = 10 }, }); try test_min_max_lum(&stream, f, d_img, &[_]cu.float2{ .{ .x = 0, .y = 3 }, .{ .x = 2, .y = 7 }, .{ .x = 3, .y = 10 }, .{ .x = 3, .y = 9 }, }); } test "cdf" { var stream = try cuda.Stream.init(0); inline for ([_][:0]const u8{ "computeCdf", "blellochCdf" }) |variant| { log.warn("Testing Cdf implementation: {s}", .{variant}); var bins = [_]c_uint{ 2, 1, 1, 4, 1, 0, 1, 1, 1, 3 }; const computeCdf = try cuda.CudaKernel(variant).init(); var cdf = [_]f32{0.0} ** 10; var d_bins = try cuda.allocAndCopy(c_uint, &bins); var d_cdf = try cuda.allocAndCopy(f32, &cdf); try computeCdf.launch( &stream, cuda.Grid.init1D(bins.len, 0), .{ d_cdf.ptr, d_bins.ptr, @intCast(c_int, bins.len), }, ); try cuda.memcpyDtoH(f32, &cdf, d_cdf); try cuda.memcpyDtoH(c_uint, &bins, d_bins); var t: f32 = 15.0; const tgt_cdf = [10]f32{ 0, 2 / t, 3 / t, 4 / t, 8 / t, 9 / t, 9 / t, 10 / t, 11 / t, 12 / t }; log.warn("bins: {d}", .{bins}); log.warn("tgt_cdf: {d:.3}", .{tgt_cdf}); log.warn("cdf: {d:.3}", .{cdf}); var i: u8 = 0; while (i < cdf.len) : (i += 1) { try std.testing.expectApproxEqRel(tgt_cdf[i], cdf[i], 0.0001); } } }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/hw2_pure.zig
const std = @import("std"); const log = std.log; const math = std.math; const assert = std.debug.assert; const cuda = @import("cudaz"); const cu = cuda.cu; const png = @import("png.zig"); const utils = @import("utils.zig"); const kernels = @import("hw2_pure_kernel.zig"); const Mat3 = kernels.Mat3; const Mat2Float = kernels.Mat2Float; const resources_dir = "resources/hw2_resources/"; const Rgb24 = png.Rgb24; const Gray8 = png.Grayscale8; pub fn main() anyerror!void { log.info("***** HW2 ******", .{}); var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = general_purpose_allocator.allocator(); const args = try std.process.argsAlloc(alloc); defer std.process.argsFree(alloc, args); var stream = try cuda.Stream.init(0); defer stream.deinit(); const img = try png.Image.fromFilePath(alloc, resources_dir ++ "cinque_terre_small.png"); defer img.deinit(); log.info("Loaded {}", .{img}); var d_img = try cuda.allocAndCopy(Rgb24, img.px.rgb24); defer cuda.free(d_img); var d_out = try cuda.alloc(Rgb24, img.width * img.height); defer cuda.free(d_out); // const gaussianBlur = try cuda.FnStruct("gaussianBlur", kernels.gaussianBlur).init(); const d_filter = Mat2Float{ .data = (try cuda.allocAndCopy(f32, &blurFilter())).ptr, .shape = [_]i32{ blur_kernel_width, blur_kernel_width }, }; defer cuda.free(d_filter.data[0..@intCast(usize, d_filter.shape[0])]); var img_mat = Mat3{ .data = std.mem.sliceAsBytes(d_img).ptr, .shape = [3]u32{ @intCast(u32, img.height), @intCast(u32, img.width), 3 }, }; var grid3D = cuda.Grid.init3D(img.height, img.width, 3, 32, 32, 1); var timer = cuda.GpuTimer.start(&stream); const gaussianBlurVerbose = try cuda.FnStruct("gaussianBlurVerbose", kernels.gaussianBlurVerbose).init(); try gaussianBlurVerbose.launch( &stream, grid3D, .{ img_mat.data, img_mat.shape[0], img_mat.shape[1], d_filter.data[0 .. blur_kernel_width * blur_kernel_width], @intCast(i32, blur_kernel_width), std.mem.sliceAsBytes(d_out).ptr, }, ); const blur_args = kernels.GaussianBlurArgs{ .img = img_mat, .filter = d_filter.data[0 .. blur_kernel_width * blur_kernel_width], .filter_width = @intCast(i32, blur_kernel_width), .output = std.mem.sliceAsBytes(d_out).ptr, }; log.info("arg.img.data={*}", .{blur_args.img.data}); log.info("arg.img.shape={any}", .{blur_args.img.shape}); log.info("arg.filter={*}", .{blur_args.filter}); log.info("arg.filter_width={}", .{blur_args.filter_width}); log.info("arg.output={*}", .{blur_args.output}); const gaussianBlurStruct = try cuda.FnStruct("gaussianBlurStruct", kernels.gaussianBlurStruct).init(); try gaussianBlurStruct.launch( &stream, grid3D, .{blur_args}, ); stream.synchronize(); const gaussianBlur = try cuda.FnStruct("gaussianBlur", kernels.gaussianBlur).init(); try gaussianBlur.launch( &stream, grid3D, .{ img_mat, d_filter, std.mem.sliceAsBytes(d_out), }, ); timer.stop(); try cuda.memcpyDtoH(Rgb24, img.px.rgb24, d_out); try img.writeToFilePath(resources_dir ++ "output.png"); try utils.validate_output(alloc, resources_dir, 2.0); } const blur_kernel_width: i32 = 9; fn blurFilter() [blur_kernel_width * blur_kernel_width]f32 { const blurKernelSigma = 2.0; // create and fill the filter we will convolve with var filter: [blur_kernel_width * blur_kernel_width]f32 = undefined; var filterSum: f32 = 0.0; // for normalization const halfWidth: i8 = @divTrunc(blur_kernel_width, 2); var r: i8 = -halfWidth; while (r <= halfWidth) : (r += 1) { var c: i8 = -halfWidth; while (c <= halfWidth) : (c += 1) { const filterValue: f32 = math.exp(-@intToFloat(f32, c * c + r * r) / (2.0 * blurKernelSigma * blurKernelSigma)); filter[@intCast(usize, (r + halfWidth) * blur_kernel_width + c + halfWidth)] = filterValue; filterSum += filterValue; } } const normalizationFactor = 1.0 / filterSum; var result: f32 = 0.0; for (filter) |*v| { v.* *= normalizationFactor; result += v.*; } return filter; }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/hw1_pure_kernel.zig
const ptx = @import("kernel_utils.zig"); pub const panic = ptx.panic; pub fn rgba_to_greyscale(rgbaImage: []u8, greyImage: []u8) callconv(ptx.Kernel) void { const i = ptx.getIdX(); if (i >= greyImage.len) return; const px = rgbaImage[i * 3 .. i * 3 + 3]; const R = @intCast(u32, px[0]); const G = @intCast(u32, px[1]); const B = @intCast(u32, px[2]); var grey = @divFloor(299 * R + 587 * G + 114 * B, 1000); greyImage[i] = @intCast(u8, grey); } comptime { if (ptx.is_nvptx) { @export(rgba_to_greyscale, .{ .name = "rgba_to_greyscale" }); } }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/hw4.zig
//! Red Eye Removal //! =============== //! //! For this assignment we are implementing red eye removal. This i //! accomplished by first creating a score for every pixel that tells us how //! likely it is to be a red eye pixel. We have already done this for you - you //! are receiving the scores and need to sort them in ascending order so that we //! know which pixels to alter to remove the red eye. //! //! Note: ascending order == smallest to largest //! //! Each score is associated with a position, when you sort the scores, you must //! also move the positions accordingly. //! //! Implementing Parallel Radix Sort with CUDA //! ========================================== //! //! The basic idea is to construct a histogram on each pass of how many of each //! "digit" there are. Then we scan this histogram so that we know where to put //! the output of each digit. For example, the first 1 must come after all the //! 0s so we have to know how many 0s there are to be able to start moving 1s //! into the correct position. //! //! 1) Histogram of the number of occurrences of each digit //! 2) Exclusive Prefix Sum of Histogram //! 3) Determine relative offset of each digit //! For example [0 0 1 1 0 0 1] //! -> [0 1 0 1 2 3 2] //! 4) Combine the results of steps 2 & 3 to determine the final //! output location for each element and move it there //! //! LSB Radix sort is an out-of-place sort and you will need to ping-pong values //! between the input and output buffers we have provided. Make sure the final //! sorted results end up in the output buffer! Hint: You may need to do a copy //! at the end. const std = @import("std"); const math = std.math; const testing = std.testing; const assert = std.debug.assert; const cuda = @import("cudaz"); const cu = cuda.cu; const png = @import("png.zig"); const utils = @import("utils.zig"); const resources_dir = "resources/hw4/"; const log = std.log.scoped(.HW4); const log_level = std.log.Level.warn; pub fn main() !void { try hw4(); } pub fn hw4() !void { var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = general_purpose_allocator.allocator(); log.info("***** HW4 ******", .{}); const img = try png.Image.fromFilePath(allocator, resources_dir ++ "/red_eye_effect.png"); const num_rows = img.height; const num_cols = img.width; const template = try png.Image.fromFilePath(allocator, resources_dir ++ "/red_eye_effect_template.png"); const num_rows_template = template.height; const num_cols_template = template.width; defer img.deinit(); var stream = initStreamWithModule(0); defer stream.deinit(); const d_img = try cuda.allocAndCopy(cu.uchar3, utils.asUchar3(img)); const d_template = try cuda.allocAndCopy(cu.uchar3, utils.asUchar3(template)); log.info("Loaded image: {}x{}", .{ num_rows, num_cols }); log.info("Loaded template: {}x{}", .{ num_rows_template, num_cols_template }); const d_scores = try cuda.alloc(f32, num_rows * num_cols); try test_naive_normalized_cross_correlation(&stream, d_template, num_rows_template, num_cols_template); // Create a 2D grid for the image and use the last dimension for the channel (R, G, B) const gridWithChannel = cuda.Grid.init3D(num_cols, num_rows, 3, 32, 1, 3); log.info("crossCorrelation({}, {},)", .{ gridWithChannel, gridWithChannel.sharedMem(f32, 1) }); try k.crossCorrelation.launchWithSharedMem( &stream, gridWithChannel, gridWithChannel.sharedMem(f32, 1), .{ d_scores.ptr, d_img.ptr, d_template.ptr, @intCast(c_int, num_rows), @intCast(c_int, num_cols), @intCast(c_int, num_rows_template), @intCast(c_int, @divFloor(num_rows_template, 2)), @intCast(c_int, num_cols_template), @intCast(c_int, @divFloor(num_cols_template, 2)), @intCast(c_int, num_rows_template * num_cols_template), }, ); const min_corr = try reduceMin(&stream, d_scores); try k.addConstant.launch( &stream, cuda.Grid.init1D(d_scores.len, 32), .{ d_scores.ptr, -min_corr, @intCast(c_uint, d_scores.len) }, ); log.info("min_corr = {}", .{min_corr}); debugDevice(allocator, "crossCorrelation", d_scores[0..100]); var timer = cuda.GpuTimer.start(&stream); var d_permutation = try radixSortAlloc(&stream, bitCastU32(d_scores)); defer cuda.free(d_permutation); timer.stop(); const d_perm_min = try reduce(&stream, k.minU32, d_permutation); const d_perm_max = try reduce(&stream, k.maxU32, d_permutation); log.info("Permutation ranges from {} to {} (expected 0 to {})", .{ d_perm_min, d_perm_max, d_permutation.len - 1 }); stream.synchronize(); std.log.info("Your code ran in: {d:.1} msecs.", .{timer.elapsed() * 1000}); var d_out = try cuda.alloc(cu.uchar3, d_img.len); debugDevice(allocator, "d_perm", d_permutation[20000..21000]); try k.removeRedness.launch(&stream, cuda.Grid.init1D(d_img.len, 64), .{ d_permutation.ptr, d_img.ptr, d_out.ptr, 30, @intCast(c_int, num_rows), @intCast(c_int, num_cols), 9, // We use something smaller than the full template 9, // to only edit the pupil and not the rest of the eye }); try cuda.memcpyDtoH(cu.uchar3, utils.asUchar3(img), d_out); try img.writeToFilePath(resources_dir ++ "output.png"); try utils.validate_output(allocator, resources_dir, 0.1); } pub fn range(stream: *const cuda.Stream, len: usize) ![]u32 { var coords = try cuda.alloc(c_uint, len); try k.rangeFn.launch(stream, cuda.Grid.init1D(len, 64), .{ coords.ptr, @intCast(c_uint, len) }); return coords; } test "range" { var stream = initStreamWithModule(0); defer stream.deinit(); var numbers = try range(&stream, 5); try expectEqualDeviceSlices(u32, &[_]u32{ 0, 1, 2, 3, 4 }, numbers); } pub fn reduceMin(stream: *const cuda.Stream, d_data: []const f32) !f32 { return reduce(stream, k.min, d_data); } /// Finds the minimum value of the given input slice. /// Do several passes until the minimum is found. /// Each block computes the minimum over 1024 elements. /// Each pass divides the size of the input array per 1024. pub fn reduce(stream: *const cuda.Stream, operator: anytype, d_data: anytype) !std.meta.Elem(@TypeOf(d_data)) { const n_threads = 1024; const n1 = math.divCeil(usize, d_data.len, n_threads) catch unreachable; var n2 = math.divCeil(usize, n1, n_threads) catch unreachable; const DType = std.meta.Elem(@TypeOf(d_data)); const buffer = try cuda.alloc(DType, n1 + n2); defer cuda.free(buffer); var d_in = d_data; var d_out = buffer[0..n1]; var d_next = buffer[n1 .. n1 + n2]; while (d_in.len > 1) { try operator.launchWithSharedMem( stream, cuda.Grid.init1D(d_in.len, n_threads), n_threads * @sizeOf(DType), .{ d_in.ptr, d_out.ptr, @intCast(c_int, d_in.len) }, ); d_in = d_out; d_out = d_next; n2 = math.divCeil(usize, d_next.len, n_threads) catch unreachable; d_next = d_out[0..n2]; } return try cuda.readResult(DType, &d_in[0]); } test "reduce min" { var stream = initStreamWithModule(0); defer stream.deinit(); const h_x = try testing.allocator.alloc(f32, 2100); defer testing.allocator.free(h_x); std.mem.set(f32, h_x, 0.0); h_x[987] = -5.0; h_x[1024] = -6.0; h_x[1479] = -7.0; const d_x = try cuda.allocAndCopy(f32, h_x); try testing.expectEqual(try reduceMin(&stream, d_x), -7.0); } test "reduce sum" { var stream = initStreamWithModule(0); defer stream.deinit(); const d1 = try cuda.allocAndCopy(u32, &[_]u32{ 1, 4, 8, 0, 1 }); try testing.expectEqual(@intCast(u32, 14), try reduce(&stream, k.sumU32, d1)); const h_x = try testing.allocator.alloc(u32, 2100); defer testing.allocator.free(h_x); std.mem.set(u32, h_x, 0.0); h_x[987] = 5; h_x[1024] = 6; h_x[1479] = 7; h_x[14] = 42; const d_x = try cuda.allocAndCopy(u32, h_x); try testing.expectEqual(@intCast(u32, 60), try reduce(&stream, k.sumU32, d_x)); } pub fn sortNetwork(stream: *const cuda.Stream, d_data: []f32, n_threads: usize) !void { const grid = cuda.Grid.init1D(d_data.len, n_threads); try k.sortNet.launchWithSharedMem( stream, grid, grid.threads.x * @sizeOf(f32), .{ d_data.ptr, @intCast(c_uint, d_data.len) }, ); } test "sorting network" { var stream = initStreamWithModule(0); defer stream.deinit(); const h_x = [_]f32{ 2, 3, 1, 0, 7, 9, 6, 5 }; var h_out = [_]f32{0} ** h_x.len; const d_x = try cuda.alloc(f32, h_x.len); defer cuda.free(d_x); try cuda.memcpyHtoD(f32, d_x, &h_x); try sortNetwork(&stream, d_x, 2); try cuda.memcpyDtoH(f32, &h_out, d_x); try testing.expectEqual([_]f32{ 2, 3, 0, 1, 7, 9, 5, 6 }, h_out); try cuda.memcpyHtoD(f32, d_x, &h_x); try sortNetwork(&stream, d_x, 4); try cuda.memcpyDtoH(f32, &h_out, d_x); try testing.expectEqual([_]f32{ 0, 1, 2, 3, 5, 6, 7, 9 }, h_out); try cuda.memcpyHtoD(f32, d_x, &h_x); try sortNetwork(&stream, d_x, 8); try cuda.memcpyDtoH(f32, &h_out, d_x); try testing.expectEqual([_]f32{ 0, 1, 2, 3, 5, 6, 7, 9 }, h_out); try cuda.memcpyHtoD(f32, d_x, &h_x); try sortNetwork(&stream, d_x, 16); try cuda.memcpyDtoH(f32, &h_out, d_x); try testing.expectEqual([_]f32{ 0, 1, 2, 3, 5, 6, 7, 9 }, h_out); } pub fn inPlaceCdf(stream: *const cuda.Stream, d_values: []u32, n_threads: u32) cuda.Error!void { const n = d_values.len; const grid_N = cuda.Grid.init1D(n, n_threads); const n_blocks = grid_N.blocks.x; var d_grid_bins = try cuda.alloc(u32, n_blocks); defer cuda.free(d_grid_bins); log.debug("cdf(n={}, n_threads={}, n_blocks={})", .{ n, n_threads, n_blocks }); var n_threads_pow_2 = n_threads; while (n_threads_pow_2 > 1) { std.debug.assert(n_threads_pow_2 % 2 == 0); n_threads_pow_2 /= 2; } try k.cdfIncremental.launchWithSharedMem( stream, grid_N, n_threads * @sizeOf(u32), .{ d_values.ptr, d_grid_bins.ptr, @intCast(c_int, n) }, ); var d_cdf_min = try reduce(stream, k.minU32, d_values); var d_cdf_max = try reduce(stream, k.maxU32, d_values); log.info("Cdf ranges from {} to {}", .{ d_cdf_min, d_cdf_max }); if (n_blocks == 1) return; // log.debug("cdf_shift({}, {})", .{ n, N }); try inPlaceCdf(stream, d_grid_bins, n_threads); try k.cdfShift.launch( stream, grid_N, .{ d_values.ptr, d_grid_bins.ptr, @intCast(c_int, n) }, ); d_cdf_min = try reduce(stream, k.minU32, d_values); d_cdf_max = try reduce(stream, k.maxU32, d_values); log.info("After shift cdf ranges from {} to {}", .{ d_cdf_min, d_cdf_max }); } test "inPlaceCdf" { var stream = initStreamWithModule(0); defer stream.deinit(); const h_x = [_]u32{ 0, 2, 1, 1, 0, 1, 3, 0, 2 }; var h_out = [_]u32{0} ** h_x.len; const h_cdf = [_]u32{ 0, 0, 2, 3, 4, 4, 5, 8, 8 }; const d_x = try cuda.alloc(u32, h_x.len); defer cuda.free(d_x); try cuda.memcpyHtoD(u32, d_x, &h_x); try inPlaceCdf(&stream, d_x, 16); try cuda.memcpyDtoH(u32, &h_out, d_x); try testing.expectEqual(h_cdf, h_out); try cuda.memcpyHtoD(u32, d_x, &h_x); try inPlaceCdf(&stream, d_x, 8); try cuda.memcpyDtoH(u32, &h_out, d_x); try testing.expectEqual(h_cdf, h_out); // Try with smaller batch sizes, forcing several passes try cuda.memcpyHtoD(u32, d_x, &h_x); try inPlaceCdf(&stream, d_x, 4); try cuda.memcpyDtoH(u32, &h_out, d_x); try testing.expectEqual(h_cdf, h_out); try cuda.memcpyHtoD(u32, d_x, &h_x); try inPlaceCdf(&stream, d_x, 2); try expectEqualDeviceSlices(u32, &h_cdf, d_x); } pub fn radixSortAlloc(stream: *const cuda.Stream, d_values: []const u32) ![]u32 { const n = d_values.len; const mask: u8 = 0b1111; const mask_bits: u8 = 8 - @clz(mask); const d_radix = try cuda.alloc(u32, n * (mask + 1)); defer cuda.free(d_radix); var d_perm0 = try range(stream, n); errdefer cuda.free(d_perm0); var d_perm1 = try cuda.alloc(u32, n); errdefer cuda.free(d_perm1); // Unroll the loop at compile time. comptime var shift: u8 = 0; inline while (shift < 32) { try _radixSort(stream, d_values, d_perm0, d_perm1, d_radix, shift, mask); shift += mask_bits; if (shift >= 32) { cuda.free(d_perm0); return d_perm1; } try _radixSort(stream, d_values, d_perm1, d_perm0, d_radix, shift, mask); shift += mask_bits; } cuda.free(d_perm1); return d_perm0; } fn _radixSort( stream: *const cuda.Stream, d_values: []const u32, d_perm0: []const u32, d_perm1: []u32, d_radix: []u32, shift: u8, mask: u8, ) !void { const n = d_values.len; try cuda.memset(u32, d_radix, 0); // debugDevice(allocator, "d_values", d_values); // debugDevice(allocator, "d_perm0", d_perm0); log.debug("radixSort(n={}, shift={}, mask={})", .{ n, shift, mask }); try k.findRadixSplitted.launch( stream, cuda.Grid.init1D(n, 1024), .{ d_radix.ptr, d_values.ptr, d_perm0.ptr, shift, mask, @intCast(c_int, n) }, ); const radix_sum = try reduce(stream, k.sumU32, d_radix); log.debug("Radix sums to {}, expected {}", .{ radix_sum, d_values.len }); std.debug.assert(radix_sum == d_values.len); try inPlaceCdf(stream, d_radix, 1024); // debugDevice(allocator, "d_radix + cdf", d_radix); try k.updatePermutation.launch( stream, cuda.Grid.init1D(n, 1024), .{ d_perm1.ptr, d_radix.ptr, d_values.ptr, d_perm0.ptr, shift, mask, @intCast(c_int, n) }, ); // debugDevice(allocator, "d_perm1", d_perm1); } test "findRadixSplitted" { var stream = initStreamWithModule(0); defer stream.deinit(); const h_x0 = [_]u32{ 0b10, 0b01, 0b00 }; const n = h_x0.len; const d_values = try cuda.allocAndCopy(u32, &h_x0); defer cuda.free(d_values); const d_radix = try cuda.alloc(u32, 2 * n); defer cuda.free(d_radix); try cuda.memset(u32, d_radix, 0); const d_perm0 = try range(&stream, n); defer cuda.free(d_perm0); try k.findRadixSplitted.launch( &stream, cuda.Grid.init1D(n, 1024), .{ d_radix.ptr, d_values.ptr, d_perm0.ptr, 0, @intCast(c_uint, 0b1), @intCast(c_int, n) }, ); try expectEqualDeviceSlices(u32, &[_]u32{ 1, 0, 1, 0, 1, 0 }, d_radix); try cuda.memset(u32, d_radix, 0); try k.findRadixSplitted.launch( &stream, cuda.Grid.init1D(n, 1024), .{ d_radix.ptr, d_values.ptr, d_perm0.ptr, 1, @intCast(c_uint, 0b1), @intCast(c_int, n) }, ); try expectEqualDeviceSlices(u32, &[_]u32{ 0, 1, 1, 1, 0, 0 }, d_radix); try cuda.memcpyHtoD(u32, d_perm0, &[_]u32{ 0, 2, 1 }); // values: { 0b10, 0b01, 0b00 }; perm: {0, 2, 1} try cuda.memset(u32, d_radix, 0); try k.findRadixSplitted.launch( &stream, cuda.Grid.init1D(n, 1024), .{ d_radix.ptr, d_values.ptr, d_perm0.ptr, 0, @intCast(c_uint, 0b1), @intCast(c_int, n) }, ); try expectEqualDeviceSlices(u32, &[_]u32{ 1, 1, 0, 0, 0, 1 }, d_radix); try cuda.memset(u32, d_radix, 0); try k.findRadixSplitted.launch( &stream, cuda.Grid.init1D(n, 1024), .{ d_radix.ptr, d_values.ptr, d_perm0.ptr, 1, @intCast(c_uint, 0b1), @intCast(c_int, n) }, ); try expectEqualDeviceSlices(u32, &[_]u32{ 0, 1, 1, 1, 0, 0 }, d_radix); } test "_radixSort" { var stream = initStreamWithModule(0); defer stream.deinit(); testing.log_level = std.log.Level.debug; defer testing.log_level = std.log.Level.warn; const h_x0 = [_]u32{ 0b10, 0b01, 0b00 }; const n = h_x0.len; const d_values = try cuda.allocAndCopy(u32, &h_x0); defer cuda.free(d_values); const d_radix = try cuda.alloc(u32, 2 * n); defer cuda.free(d_radix); const d_perm0 = try range(&stream, n); defer cuda.free(d_perm0); const d_perm1 = try range(&stream, n); defer cuda.free(d_perm1); try _radixSort(&stream, d_values, d_perm0, d_perm1, d_radix, 0, 0b1); // d_radix before cdf = { 1, 0, 1, 0, 1, 0 } try expectEqualDeviceSlices(u32, &[_]u32{ 0, 1, 1, 2, 2, 3 }, d_radix); try expectEqualDeviceSlices(u32, &[_]u32{ 0, 2, 1 }, d_perm1); try _radixSort(&stream, d_values, d_perm0, d_perm1, d_radix, 1, 0b1); // d_radix before cdf = { 0, 1, 1, 1, 0, 0 } try expectEqualDeviceSlices(u32, &[_]u32{ 0, 0, 1, 2, 3, 3 }, d_radix); try expectEqualDeviceSlices(u32, &[_]u32{ 2, 0, 1 }, d_perm1); try cuda.memcpyHtoD(u32, d_perm0, &[_]u32{ 0, 2, 1 }); try _radixSort(&stream, d_values, d_perm0, d_perm1, d_radix, 0, 0b1); // d_radix before cdf = { 1, 1, 0, 0, 0, 1 } try expectEqualDeviceSlices(u32, &[_]u32{ 0, 1, 2, 2, 2, 2 }, d_radix); try expectEqualDeviceSlices(u32, &[_]u32{ 0, 2, 1 }, d_perm1); try _radixSort(&stream, d_values, d_perm0, d_perm1, d_radix, 1, 0b1); // d_radix before cdf = { 0, 1, 1, 1, 0, 0 } try expectEqualDeviceSlices(u32, &[6]u32{ 0, 0, 1, 2, 3, 3 }, d_radix); try expectEqualDeviceSlices(u32, &[_]u32{ 2, 1, 0 }, d_perm1); } test "updatePermutation" { var stream = initStreamWithModule(0); defer stream.deinit(); const h_x0 = [_]u32{ 0b1000, 0b0001 }; const n = h_x0.len; const d_values = try cuda.allocAndCopy(u32, &h_x0); defer cuda.free(d_values); var d_radix = try cuda.allocAndCopy(u32, &[_]u32{ 0, 1, 1, 1, 2, 2, 2, 2 }); defer cuda.free(d_radix); var d_perm0 = try range(&stream, n); defer cuda.free(d_perm0); const d_perm1 = try range(&stream, n); defer cuda.free(d_perm1); try k.updatePermutation.launch( &stream, cuda.Grid.init1D(n, 1024), .{ d_perm1.ptr, d_radix.ptr, d_values.ptr, d_perm0.ptr, 0, @intCast(c_uint, 0b11), @intCast(c_int, n), }, ); } test "radixSort" { var stream = initStreamWithModule(0); defer stream.deinit(); const h_x0 = [_]u32{ 2, 3, 1, 0, 6, 7, 5, 4 }; // h_x should be it's own permutation, since there is only consecutive integers const expected = [_]u32{ 2, 3, 1, 0, 6, 7, 5, 4 }; const d_x = try cuda.allocAndCopy(u32, &h_x0); defer cuda.free(d_x); var d_perm0 = try radixSortAlloc(&stream, d_x); defer cuda.free(d_perm0); try expectEqualDeviceSlices(u32, &expected, d_perm0); const h_x1 = [_]u32{ 1073741824, 1077936128, 1065353216, 0, 1088421888, 1091567616, 1086324736, 1084227584 }; try cuda.memcpyHtoD(u32, d_x, &h_x1); var d_perm1 = try radixSortAlloc(&stream, d_x); try expectEqualDeviceSlices(u32, &expected, d_perm1); // With floats ! const h_x2 = [_]f32{ 2.0, 3.0, 1.0, 0.0, 6.0, 7.0, 5.0, 4.0 }; try cuda.memcpyHtoD(u32, d_x, bitCastU32(&h_x2)); var d_perm2 = try radixSortAlloc(&stream, d_x); try expectEqualDeviceSlices(u32, &expected, d_perm2); } fn test_naive_normalized_cross_correlation( stream: *const cuda.Stream, d_template: []const cu.uchar3, num_rows: usize, num_cols: usize, ) !void { try testing.expectEqual(num_rows, num_cols); const half_height = @divFloor(num_rows, 2); log.info("Loaded template: {}x{}", .{ num_rows, num_rows }); const d_scores = try cuda.alloc(f32, num_rows * num_rows); defer cuda.free(d_scores); const gridWithChannel = cuda.Grid.init3D(num_rows, num_rows, 3, 32, 1, 3); // Auto cross-correlation log.info("crossCorrelation({}, {},)", .{ gridWithChannel, gridWithChannel.sharedMem(f32, 1) }); try k.crossCorrelation.launchWithSharedMem( stream, gridWithChannel, gridWithChannel.sharedMem(f32, 1), .{ d_scores.ptr, d_template.ptr, d_template.ptr, @intCast(c_int, num_rows), @intCast(c_int, num_rows), @intCast(c_int, num_rows), @intCast(c_int, half_height), @intCast(c_int, num_rows), @intCast(c_int, half_height), @intCast(c_int, num_rows * num_rows), }, ); // debugDevice(allocator, "auto_corr", d_scores); // Should be maximal at the center const center_corr = try cuda.readResult(f32, &d_scores[num_rows * half_height + half_height]); const max_corr = try reduce(stream, k.max, d_scores); try testing.expectEqual(max_corr, center_corr); } fn bitCastU32(data: anytype) []const u32 { return @ptrCast([*]const u32, data)[0..data.len]; } fn expectEqualDeviceSlices( comptime DType: type, h_expected: []const DType, d_values: []const DType, ) !void { const allocator = std.testing.allocator; const h_values = try cuda.allocAndCopyResult(DType, allocator, d_values); defer allocator.free(h_values); testing.expectEqualSlices(DType, h_expected, h_values) catch |err| { log.err("Expected: {any}, got: {any}", .{ h_expected, h_values }); return err; }; } fn debugDevice( allocator: std.mem.Allocator, name: []const u8, d_values: anytype, ) void { const DType = std.meta.Elem(@TypeOf(d_values)); var h = cuda.allocAndCopyResult(DType, allocator, d_values) catch unreachable; defer allocator.free(h); log.debug("{s} -> {any}", .{ name, h }); } // TODO: generate this when the kernel is written in Zig. const Kernels = struct { addConstant: cuda.CudaKernel("add_constant"), cdfIncremental: cuda.CudaKernel("cdf_incremental"), cdfShift: cuda.CudaKernel("cdf_incremental_shift"), crossCorrelation: cuda.CudaKernel("naive_normalized_cross_correlation"), findRadixSplitted: cuda.CudaKernel("find_radix_splitted"), rangeFn: cuda.CudaKernel("range"), min: cuda.CudaKernel("reduce_min"), max: cuda.CudaKernel("reduce_max"), minU32: cuda.CudaKernel("reduce_min_u32"), maxU32: cuda.CudaKernel("reduce_max_u32"), removeRedness: cuda.CudaKernel("remove_redness"), sortNet: cuda.CudaKernel("sort_network"), sumU32: cuda.CudaKernel("reduce_sum_u32"), updatePermutation: cuda.CudaKernel("update_permutation"), }; var k: Kernels = undefined; fn initStreamWithModule(device: u3) cuda.Stream { const stream = cuda.Stream.init(device) catch unreachable; // Panic if we can't load the module. k = Kernels{ .addConstant = @TypeOf(k.addConstant).init() catch unreachable, .cdfIncremental = @TypeOf(k.cdfIncremental).init() catch unreachable, .cdfShift = @TypeOf(k.cdfShift).init() catch unreachable, .crossCorrelation = @TypeOf(k.crossCorrelation).init() catch unreachable, .findRadixSplitted = @TypeOf(k.findRadixSplitted).init() catch unreachable, .rangeFn = @TypeOf(k.rangeFn).init() catch unreachable, .min = @TypeOf(k.min).init() catch unreachable, .max = @TypeOf(k.max).init() catch unreachable, .minU32 = @TypeOf(k.minU32).init() catch unreachable, .maxU32 = @TypeOf(k.maxU32).init() catch unreachable, .removeRedness = @TypeOf(k.removeRedness).init() catch unreachable, .sortNet = @TypeOf(k.sortNet).init() catch unreachable, .sumU32 = @TypeOf(k.sumU32).init() catch unreachable, .updatePermutation = @TypeOf(k.updatePermutation).init() catch unreachable, }; return stream; }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/hw5.zig
const std = @import("std"); const log = std.log.scoped(.hw5); const math = std.math; const testing = std.testing; const Allocator = std.mem.Allocator; const Random = std.rand.Random; const cuda = @import("cudaz"); const cu = cuda.cu; const utils = @import("utils.zig"); const RawKernels = @import("hw5_kernel.zig"); pub fn main() !void { var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &general_purpose_allocator.allocator(); try initModule(0); log.info("***** HW5 ******", .{}); const num_bins: usize = 1024; const num_elems: usize = 10_000 * num_bins; var data = try allocator.alloc(u32, num_elems); defer allocator.free(data); var prng = std.rand.DefaultPrng.init(387418298); const random = prng.random(); // make the mean unpredictable, but close enough to the middle // so that timings are unaffected const mean = random.intRangeLessThan(u32, num_bins / 2 - num_bins / 8, num_bins / 2 + num_bins / 8); const std_dev: f32 = 100; // TODO: generate this on the GPU for (data) |*x| { var r = @floatToInt(i32, random.floatNorm(f32) * std_dev) + @intCast(i32, mean); x.* = math.min(math.absCast(r), @intCast(u32, num_bins - 1)); } var ref_histo = try allocator.alloc(u32, num_bins); defer allocator.free(ref_histo); cpu_histogram(data, ref_histo); var atomic_histo = try allocator.alloc(u32, num_bins); defer allocator.free(atomic_histo); var elapsed = try histogram(k.atomicHistogram.f, data, atomic_histo, ref_histo, cuda.Grid.init1D(data.len, 1024)); log.info("atomicHistogram of {} array took {:.3}ms", .{ num_elems, elapsed }); log.info("atomicHistogram bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6}); elapsed = try histogram(k.bychunkHistogram.f, data, atomic_histo, ref_histo, cuda.Grid.init1D(data.len / 32, 1024)); log.info("bychunkHistogram of {} array took {:.3}ms", .{ num_elems, elapsed }); log.info("bychunkHistogram bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6}); elapsed = try fastHistogram(data, atomic_histo, ref_histo); log.info("fastHistogram of {} array took {:.3}ms", .{ num_elems, elapsed }); log.info("fastHistogram bandwith: {:.3}MB/s", .{computeBandwith(elapsed, data) * 1e-6}); } pub fn cpu_histogram(data: []const u32, histo: []u32) void { std.mem.set(u32, histo, 0); for (data) |x| { histo[x] += 1; } } pub fn histogram(kernel: cu.CUfunction, data: []const u32, histo: []u32, ref_histo: []const u32, grid: cuda.Grid) !f64 { var stream = try cuda.Stream.init(0); var d_data = try stream.allocAndCopy(u32, data); var d_histo = try stream.alloc(u32, histo.len); stream.memset(u32, d_histo, 0); var timer = cuda.GpuTimer.start(&stream); try stream.launchWithSharedMem( kernel, grid, d_histo.len * @sizeOf(u32), .{ d_data, d_histo }, ); timer.stop(); stream.memcpyDtoH(u32, histo, d_histo); stream.synchronize(); var elapsed = timer.elapsed(); std.testing.expectEqualSlices(u32, ref_histo, histo) catch { if (ref_histo.len < 100) { log.err("Histogram mismatch. Expected: {d}, got {d}", .{ ref_histo, histo }); } // return err; }; return elapsed; } const Kernels = struct { atomicHistogram: cuda.FnStruct("atomicHistogram", RawKernels.atomicHistogram), bychunkHistogram: cuda.FnStruct("bychunkHistogram", RawKernels.bychunkHistogram), coarseBins: cuda.FnStruct("coarseBins", RawKernels.coarseBins), shuffleCoarseBins: cuda.FnStruct("shuffleCoarseBins32", RawKernels.shuffleCoarseBins32), cdfIncremental: cuda.FnStruct("cdfIncremental", RawKernels.cdfIncremental), cdfIncrementalShift: cuda.FnStruct("cdfIncrementalShift", RawKernels.cdfIncrementalShift), }; var k: Kernels = undefined; fn initModule(device: u3) !void { _ = try cuda.Stream.init(device); // Panic if we can't load the module. k = Kernels{ .atomicHistogram = try @TypeOf(k.atomicHistogram).init(), .bychunkHistogram = try @TypeOf(k.bychunkHistogram).init(), .coarseBins = try @TypeOf(k.coarseBins).init(), .shuffleCoarseBins = try @TypeOf(k.shuffleCoarseBins).init(), .cdfIncremental = try @TypeOf(k.cdfIncremental).init(), .cdfIncrementalShift = try @TypeOf(k.cdfIncrementalShift).init(), }; } fn computeBandwith(elapsed_ms: f64, data: []const u32) f64 { const n = @intToFloat(f64, data.len); const bytes = @intToFloat(f64, @sizeOf(u32)); return n * bytes / elapsed_ms * 1000; } fn fastHistogram(data: []const u32, histo: []u32, ref_histo: []const u32) !f32 { var stream = &(try cuda.Stream.init(0)); _ = try stream.allocAndCopy(u32, data); var d_histo = try stream.alloc(u32, histo.len); stream.memset(u32, d_histo, 0); var d_radix = try stream.alloc(u32, data.len * 32); stream.memset(u32, d_radix, 0); try cuda.memset(u32, d_radix, 0); _ = ref_histo; return 0.0; } fn fastHistogramBroken(data: []const u32, histo: []u32, ref_histo: []const u32) !f32 { var stream = &(try cuda.Stream.init(0)); var d_values = try stream.allocAndCopy(u32, data); var d_histo = try stream.alloc(u32, histo.len); stream.memset(u32, d_histo, 0); var d_radix = try stream.alloc(u32, data.len * 32); stream.memset(u32, d_radix, 0); var timer = cuda.GpuTimer.start(stream); const n = d_values.len; try cuda.memset(u32, d_radix, 0); // We split the bins into 32 coarse bins. const d_histo_boundaries = try stream.alloc(u32, 32); try k.coarseBins.launch( stream, cuda.Grid.init1D(n, 1024), .{ d_values, d_radix }, ); // const radix_sum = try cuda.algorithms.reduce(&stream, k.sumU32, d_radix); // log.debug("Radix sums to {}, expected {}", .{ radix_sum, d_values.len }); // std.debug.assert(radix_sum == d_values.len); try inPlaceCdf(stream, d_radix, 1024); // debugDevice("d_radix + cdf", d_radix); try k.shuffleCoarseBins.launch( stream, cuda.Grid.init1D(n, 1024), .{ d_histo, d_histo_boundaries, d_radix, d_values }, ); var histo_boundaries: [33]u32 = undefined; stream.memcpyDtoH(u32, &histo_boundaries, d_histo_boundaries); timer.stop(); stream.synchronize(); // Now we can partition d_values into coarse bins. var bin: u32 = 0; while (bin < 32) : (bin += 1) { var bin_start = histo_boundaries[bin]; var bin_end = histo_boundaries[bin + 1]; var d_bin_values = d_histo[bin_start .. bin_end + 1]; // TODO histogram(d_bin_values) _ = d_bin_values; } var elapsed = timer.elapsed(); std.testing.expectEqualSlices(u32, ref_histo, histo) catch { if (ref_histo.len < 100) { log.err("Histogram mismatch. Expected: {d}, got {d}", .{ ref_histo, histo }); } // return err; }; return elapsed; } // TODO: the cdf kernels should be part of cudaz pub fn inPlaceCdf(stream: *const cuda.Stream, d_values: []u32, n_threads: u32) cuda.Error!void { const n = d_values.len; const grid_N = cuda.Grid.init1D(n, n_threads); const n_blocks = grid_N.blocks.x; var d_grid_bins = try cuda.alloc(u32, n_blocks); defer cuda.free(d_grid_bins); var n_threads_pow_2 = n_threads; while (n_threads_pow_2 > 1) { std.debug.assert(n_threads_pow_2 % 2 == 0); n_threads_pow_2 /= 2; } log.warn("cdf(n={}, n_threads={}, n_blocks={})", .{ n, n_threads, n_blocks }); try k.cdfIncremental.launchWithSharedMem( stream, grid_N, n_threads * @sizeOf(u32), .{ d_values, d_grid_bins }, ); if (n_blocks == 1) return; try inPlaceCdf(stream, d_grid_bins, n_threads); try k.cdfIncrementalShift.launch( stream, grid_N, .{ d_values, d_grid_bins }, ); } test "inPlaceCdf" { try initModule(0); var stream = try cuda.Stream.init(0); defer stream.deinit(); const h_x = [_]u32{ 0, 2, 1, 1, 0, 1, 3, 0, 2 }; var h_out = [_]u32{0} ** h_x.len; const h_cdf = [_]u32{ 0, 0, 2, 3, 4, 4, 5, 8, 8 }; const d_x = try cuda.alloc(u32, h_x.len); defer cuda.free(d_x); try cuda.memcpyHtoD(u32, d_x, &h_x); try inPlaceCdf(&stream, d_x, 16); try utils.expectEqualDeviceSlices(u32, &h_cdf, d_x); try cuda.memcpyHtoD(u32, d_x, &h_x); try inPlaceCdf(&stream, d_x, 8); try cuda.memcpyDtoH(u32, &h_out, d_x); try testing.expectEqual(h_cdf, h_out); // Try with smaller batch sizes, forcing several passes try cuda.memcpyHtoD(u32, d_x, &h_x); try inPlaceCdf(&stream, d_x, 4); try cuda.memcpyDtoH(u32, &h_out, d_x); try testing.expectEqual(h_cdf, h_out); try cuda.memcpyHtoD(u32, d_x, &h_x); try inPlaceCdf(&stream, d_x, 2); try utils.expectEqualDeviceSlices(u32, &h_cdf, d_x); }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/png.zig
const std = @import("std"); const Allocator = std.mem.Allocator; pub const png = @cImport({ @cDefine("LODEPNG_NO_COMPILE_CPP", "1"); @cDefine("LODEPNG_COMPILE_ERROR_TEXT", "1"); // TODO remove libc dependency // @cDefine("LODEPNG_NO_COMPILE_DISK", "1"); // @cDefine("LODEPNG_NO_COMPILE_ALLOCATORS", "1"); @cInclude("lodepng.h"); }); const testing = std.testing; const log = std.log.scoped(.png); /// Control how many pixels are printed when formatting an image. pub const PRINT_PIXELS = 30; pub const Rgb24 = extern struct { r: u8, g: u8, b: u8 }; pub const Gray8 = u8; pub const Rgb_f32 = struct { r: f32, g: f32, b: f32, alpha: f32 = 1.0 }; // TODO enable all types pub const ColorType = enum(c_uint) { rgb24 = png.LCT_RGB, gray8 = png.LCT_GREY, }; pub fn PixelType(t: ColorType) type { return switch (t) { .rgb24 => Rgb24, .gray8 => Gray8, }; } pub fn grayscale(allocator: std.mem.Allocator, width: u32, height: u32) !Image { return Image.init(allocator, width, height, .gray8); } pub const Image = struct { width: u32, height: u32, px: union(ColorType) { rgb24: []Rgb24, gray8: []u8 }, allocator: Allocator, pub fn init(allocator: Allocator, width: u32, height: u32, color_type: ColorType) !Image { const n = @as(usize, width * height); return Image{ .width = width, .height = height, .allocator = allocator, .px = switch (color_type) { .rgb24 => .{ .rgb24 = try allocator.alloc(Rgb24, n) }, .gray8 => .{ .gray8 = try allocator.alloc(Gray8, n) }, }, }; } pub fn deinit(self: Image) void { self.allocator.free(self.raw()); } pub fn raw(self: Image) []u8 { return switch (self.px) { .rgb24 => |px| std.mem.sliceAsBytes(px), .gray8 => |px| std.mem.sliceAsBytes(px), }; } pub fn len(self: Image) usize { return self.width * self.height; } pub fn fromFilePath(allocator: Allocator, file_path: []const u8) !Image { var img: Image = undefined; // TODO: use lodepng_inspect to get the image size and handle allocations ourselves img.allocator = std.heap.c_allocator; var buffer: [*c]u8 = undefined; var resolved_path = try std.fs.path.resolve(allocator, &[_][]const u8{file_path}); defer allocator.free(resolved_path); var resolved_pathZ: []u8 = try allocator.dupeZ(u8, resolved_path); defer allocator.free(resolved_pathZ); // TODO: handle different color encoding try check(png.lodepng_decode24_file( &buffer, &img.width, &img.height, @ptrCast([*c]const u8, resolved_pathZ), )); std.debug.assert(buffer != null); img.px = .{ .rgb24 = @ptrCast([*]Rgb24, buffer.?)[0..img.len()] }; return img; } fn lodeBitDepth(self: Image) c_uint { _ = self; return 8; } pub fn writeToFilePath(self: Image, file_path: []const u8) !void { var resolved_path = try std.fs.path.resolve(self.allocator, &[_][]const u8{file_path}); defer self.allocator.free(resolved_path); var resolved_pathZ: []u8 = try self.allocator.dupeZ(u8, resolved_path); defer self.allocator.free(resolved_pathZ); // Write image data try check(png.lodepng_encode_file( @ptrCast([*c]const u8, resolved_pathZ), self.raw().ptr, @intCast(c_uint, self.width), @intCast(c_uint, self.height), @enumToInt(self.px), self.lodeBitDepth(), )); log.info("Wrote full image {s}", .{resolved_pathZ}); return; } // TODO: does it make sense to use f32 here ? shouldn't we stick with pub const Iterator = struct { image: Image, i: usize, fn u8_to_f32(value: u8) f32 { return @intToFloat(f32, value) / 255.0; } pub fn next(self: *Iterator) ?Rgb_f32 { if (self.i >= self.image.width * self.image.height) return null; const px_f32 = switch (self.image.px) { .rgb24 => |pixels| blk: { const px = pixels[self.i]; break :blk Rgb_f32{ .r = u8_to_f32(px.r), .g = u8_to_f32(px.g), .b = u8_to_f32(px.b) }; }, .gray8 => |pixels| blk: { const gray = u8_to_f32(pixels[self.i]); break :blk Rgb_f32{ .r = gray, .g = gray, .b = gray }; }, }; self.i += 1; return px_f32; } }; pub fn iterator(self: Image) Iterator { return .{ .image = self, .i = 0 }; } pub fn format( self: *const Image, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = fmt; _ = options; try std.fmt.format(writer, "Image ({s}){}x{}: (...{any}...)", .{ @tagName(self.px), self.width, self.height, self.raw()[200 .. 200 + PRINT_PIXELS] }); } }; pub fn check(err: c_uint) !void { if (err != 0) { log.err("Error {s}({})", .{ png.lodepng_error_text(err), err }); return error.PngError; } } pub fn img_eq(output: Image, reference: Image) bool { const same_dim = (output.width == reference.width) and (output.height == reference.height); if (!same_dim) return false; const same_len = output.raw().len == reference.raw().len; if (!same_len) return false; var i: usize = 0; while (i < output.raw().len) : (i += 1) { if (output.raw()[i] != reference.raw()[i]) return false; } return true; } test "read/write/read" { var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var base = try Image.fromFilePath(testing.allocator, "resources/hw1_resources/cinque_terre_small.png"); defer base.deinit(); try tmp.dir.writeFile("out.png", "hello"); var tmp_img = try tmp.dir.realpathAlloc(testing.allocator, "out.png"); log.warn("will write image ({}x{}) to {s}", .{ base.width, base.height, tmp_img }); defer testing.allocator.free(tmp_img); try base.writeToFilePath(tmp_img); var loaded = try Image.fromFilePath(testing.allocator, tmp_img); defer loaded.deinit(); try testing.expectEqualSlices(u8, base.raw(), loaded.raw()); try testing.expect(img_eq(base, loaded)); }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/lesson7.zig
// TODO: implement a dynamic parallel quicksort // Need to compile "Cudaz" for the GPU ? // 1. write a sample dynamic parallel quicksort in C // 2. look at the .ptx generated by nvcc // 3. update Cudaz so that it's easy to use on the GPU too // stream launched from the device need to have the CU_STREAM_NON_BLOCKING flag // we don't need to run device initialization on the device. const cudaz = @import("cudaz"); const std = @import("std"); const log = std.log; pub fn main() anyerror!void { log.info("***** HW1 ******", .{}); var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; var alloc = general_purpose_allocator.allocator(); const args = try std.process.argsAlloc(alloc); defer std.process.argsFree(alloc, args); var stream = try cudaz.Stream.init(0); defer stream.deinit(); }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/hw2_pure_kernel.zig
const builtin = @import("builtin"); const std = @import("std"); const math = std.math; const ptx = @import("kernel_utils.zig"); fn clamp(x: i32, min: i32, max: i32) i32 { if (x < min) return min; if (x >= max) return max - 1; return x; } pub const Mat3 = struct { data: [*]const u8, shape: [3]u32, pub fn getClamped(self: Mat3, x: i32, y: i32, z: i32) u8 { return self.data[self.idxClamped(x, y, z)]; } pub fn idx(self: Mat3, x: usize, y: usize, z: usize) usize { const i = (x * self.shape[1] + y) * self.shape[2] + z; return @intCast(usize, i); } pub fn idxClamped(self: Mat3, x: i32, y: i32, z: i32) usize { return self.idx( clamp(x, 0, self.shape[0]), clamp(y, 0, self.shape[1]), clamp(z, 0, self.shape[2]), ); } }; pub const Mat2Float = struct { data: [*]f32, shape: [2]i32, pub fn getClamped(self: Mat2Float, x: i32, y: i32) f32 { return self.data[self.idxClamped(x, y)]; } pub fn idx(self: Mat2Float, x: i32, y: i32) usize { const i = x * self.shape[1] + y; return @intCast(usize, i); } pub fn idxClamped(self: Mat2Float, x: i32, y: i32) usize { return self.idx( clamp(x, 0, self.shape[0]), clamp(y, 0, self.shape[1]), ); } }; inline fn clampedOffset(x: u32, step: i32, n: u32) u32 { var x_step = x; if (step < 0) { const abs_step = math.absCast(step); if (abs_step > x) return 0; x_step -= abs_step; } if (x_step >= n) return n - 1; return x_step; } pub const GaussianBlurArgs = struct { img: Mat3, filter: []const f32, filter_width: u32, output: [*]u8, }; pub fn gaussianBlurStruct(args: GaussianBlurArgs) callconv(ptx.Kernel) void { return gaussianBlurVerbose( args.img.data, args.img.shape[0], args.img.shape[1], args.filter.ptr, args.filter_width, args.output, ); } pub fn gaussianBlurVerbose( raw_input: [*]const u8, num_cols: u32, num_rows: u32, filter: [*]const f32, filter_width: u32, output: [*]u8, ) callconv(ptx.Kernel) void { const id = ptx.getId_3D(); const input = Mat3{ .data = raw_input, .shape = [_]u32{ num_cols, num_rows, 3 } }; if (id.x >= num_cols or id.y >= num_rows) return; const channel_id = @intCast(usize, input.idx(id.x, id.y, id.z)); var pixel: f32 = 0.0; const half_width: i32 = @intCast(i32, filter_width >> 1); var r = -half_width; while (r <= half_width) : (r += 1) { var c = -half_width; while (c <= half_width) : (c += 1) { const weight = filter[@intCast(usize, (r + half_width) * @intCast(i32, filter_width) + c + half_width)]; pixel += weight * @intToFloat(f32, input.idx( clampedOffset(id.x, c, input.shape[0]), clampedOffset(id.y, r, input.shape[1]), @as(usize, id.z), )); } } output[channel_id] = @floatToInt(u8, pixel); } pub fn gaussianBlur( input: Mat3, filter: Mat2Float, output: []u8, ) callconv(ptx.Kernel) void { const id = ptx.getId_3D(); if (id.x >= input.shape[0] or id.y >= input.shape[1]) return; const channel_id = @intCast(usize, input.idx(id.x, id.y, id.z)); const half_width: i32 = filter.shape[0] >> 1; var pixel: f32 = 0.0; var r = -half_width; while (r <= half_width) : (r += 1) { var c = -half_width; while (c <= half_width) : (c += 1) { const weight = filter.getClamped(r + half_width, c + half_width); pixel += weight * @intToFloat(f32, input.idx( clampedOffset(id.x, c, input.shape[0]), clampedOffset(id.y, r, input.shape[1]), @as(usize, id.z), )); } } output[channel_id] = @floatToInt(u8, pixel); } comptime { if (ptx.is_nvptx) { @export(gaussianBlur, .{ .name = "gaussianBlur" }); @export(gaussianBlurStruct, .{ .name = "gaussianBlurStruct" }); @export(gaussianBlurVerbose, .{ .name = "gaussianBlurVerbose" }); } }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/hw1.zig
const std = @import("std"); const log = std.log; const assert = std.debug.assert; const cudaz = @import("cudaz"); const cu = cudaz.cu; const png = @import("png.zig"); const utils = @import("utils.zig"); // const hw1_kernel = @import("hw1_kernel.zig"); const resources_dir = "resources/hw1_resources/"; pub fn main() anyerror!void { log.info("***** HW1 ******", .{}); var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; var alloc = general_purpose_allocator.allocator(); const args = try std.process.argsAlloc(alloc); defer std.process.argsFree(alloc, args); var stream = try cudaz.Stream.init(0); defer stream.deinit(); const img = try png.Image.fromFilePath(alloc, resources_dir ++ "cinque_terre_small.png"); defer img.deinit(); log.info("Loaded {}", .{img}); var d_img = try cudaz.allocAndCopy(png.Rgb24, img.px.rgb24); defer cudaz.free(d_img); var gray = try png.grayscale(alloc, img.width, img.height); defer gray.deinit(); var d_gray = try cudaz.alloc(png.Gray8, img.width * img.height); defer cudaz.free(d_gray); try cudaz.memset(png.Gray8, d_gray, 0); const kernel = try cudaz.CudaKernel("rgba_to_greyscale").init(); // const kernel = try cudaz.ZigStruct(hw1_kernel, "rgba_to_greyscale").init(); var timer = cudaz.GpuTimer.start(&stream); try kernel.launch( &stream, cudaz.Grid.init1D(img.height * img.width, 64), .{ @ptrCast([*c]const cu.uchar3, d_img.ptr), @ptrCast([*c]u8, d_gray.ptr), @intCast(c_int, img.height), @intCast(c_int, img.width), // std.mem.sliceAsBytes(d_img), // std.mem.sliceAsBytes(d_gray), }, ); timer.stop(); stream.synchronize(); try cudaz.memcpyDtoH(png.Gray8, gray.px.gray8, d_gray); log.info("Got grayscale {}", .{img}); try gray.writeToFilePath(resources_dir ++ "output.png"); try utils.validate_output(alloc, resources_dir, 1.0); }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/hw5_kernel.zig
const std = @import("std"); const builtin = @import("builtin"); const ptx = @import("kernel_utils.zig"); pub fn atomicHistogram(d_data: []u32, d_bins: []u32) callconv(ptx.Kernel) void { const gid = ptx.getIdX(); if (gid >= d_data.len) return; const bin = d_data[gid]; ptx.atomicAdd(&d_bins[bin], 1); } // const step: u32 = 32; const SharedMem = opaque {}; // extern var bychunkHistogram_shared: SharedMem align(8) addrspace(.shared); // stage2 var bychunkHistogram_shared: [1024]u32 = undefined; // stage1 const bychunkHistogram_step: u32 = 32; /// Fist accumulate into a shared histogram /// then accumulate to the global histogram. /// Should decreases contention when doing atomic adds. pub fn bychunkHistogram(d_data: []u32, d_bins: []u32) callconv(ptx.Kernel) void { const n = d_data.len; const num_bins = d_bins.len; const step = bychunkHistogram_step; // var s_bins = @ptrCast([*]addrspace(.shared) u32, &bychunkHistogram_shared); // stage2 var s_bins = @ptrCast([*]u32, &bychunkHistogram_shared); // stage1 const tid = ptx.threadIdX(); if (tid < num_bins) s_bins[ptx.threadIdX()] = 0; ptx.syncThreads(); var i: u32 = 0; while (i < step) : (i += 1) { const offset = ptx.blockIdX() * ptx.blockDimX() * step + i * ptx.blockDimX() + tid; if (offset < n) { // Passing a .shared pointer to atomicAdd crashes stage2 here // atomicAdd(&s_bins[d_data[offset]], 1); _ = @atomicRmw(u32, &s_bins[d_data[offset]], .Add, 1, .SeqCst); } } ptx.syncThreads(); if (tid < num_bins) { ptx.atomicAdd(&d_bins[tid], s_bins[tid]); } } pub fn coarseBins(d_data: []u32, d_coarse_bins: []u32) callconv(ptx.Kernel) void { const n = d_data.len; const id = ptx.getIdX(); if (id < n) { const rad = d_data[id] / 32; d_coarse_bins[rad * n + id] = 1; } } pub fn shuffleCoarseBins32( d_coarse_bins: []u32, d_coarse_bins_boundaries: []u32, d_cdf: []const u32, d_in: []const u32, ) callconv(ptx.Kernel) void { const n = d_in.len; const id = ptx.getIdX(); if (id >= n) return; const x = d_in[id]; const rad = x >> 5 & 0b11111; const new_id = d_cdf[rad * n + id]; d_coarse_bins[new_id] = x; if (id < 32) { d_coarse_bins_boundaries[id] = d_cdf[id * n]; } if (id == 32) { d_coarse_bins_boundaries[id] = d_cdf[id * n - 1]; } } // extern var cdfIncremental_shared: SharedMem align(8) addrspace(.shared); // stage2 var cdfIncremental_shared: [1024]u32 = undefined; // stage1 pub fn cdfIncremental(d_glob_bins: []u32, d_block_bins: []u32) callconv(ptx.Kernel) void { const n = d_glob_bins.len; const global_id = ptx.getIdX(); if (global_id >= n) return; const tid = ptx.threadIdX(); // var d_bins = @ptrCast([*]addrspace(.shared) u32, &cdfIncremental_shared); // stage2 var d_bins = @ptrCast([*]u32, &cdfIncremental_shared); // stage1 ptx.syncThreads(); const last_tid = ptx.lastTid(@intCast(u32, n)); const total = ptx.exclusiveScan(.add, d_bins, tid, last_tid); if (tid == last_tid) { d_block_bins[ptx.blockIdX()] = total; } d_glob_bins[global_id] = d_bins[tid]; } pub fn cdfIncrementalShift(d_glob_bins: []u32, d_block_bins: []const u32) callconv(ptx.Kernel) void { const block_shift = d_block_bins[ptx.blockIdX()]; d_glob_bins[ptx.getIdX()] += block_shift; } comptime { if (ptx.is_nvptx) { @export(atomicHistogram, .{ .name = "atomicHistogram" }); @export(bychunkHistogram, .{ .name = "bychunkHistogram" }); @export(coarseBins, .{ .name = "coarseBins" }); @export(shuffleCoarseBins32, .{ .name = "shuffleCoarseBins32" }); @export(cdfIncremental, .{ .name = "cdfIncremental" }); @export(cdfIncrementalShift, .{ .name = "cdfIncrementalShift" }); } }
0
repos/cudaz/CS344
repos/cudaz/CS344/src/lesson5_kernel.zig
const std = @import("std"); const builtin = @import("builtin"); const CallingConvention = @import("std").builtin.CallingConvention; const is_nvptx = builtin.cpu.arch == .nvptx64; const PtxKernel = if (is_nvptx) CallingConvention.PtxKernel else CallingConvention.Unspecified; pub export fn transposeCpu(data: []const u32, trans: []u32, num_cols: usize) callconv(PtxKernel) void { var i: usize = 0; while (i < num_cols) : (i += 1) { var j: usize = 0; while (j < num_cols) : (j += 1) { trans[num_cols * i + j] = data[num_cols * j + i]; } } } pub export fn transposePerRow(data: []const u32, trans: []u32, num_cols: usize) callconv(PtxKernel) void { const i = getIdX(); var j: usize = 0; while (j < num_cols) : (j += 1) { trans[num_cols * i + j] = data[num_cols * j + i]; } } pub export fn transposePerCell(data: []const u32, trans: []u32, num_cols: usize) callconv(PtxKernel) void { const i = getIdX(); const j = getIdY(); if (i >= num_cols or j >= num_cols) return; trans[num_cols * i + j] = data[num_cols * j + i]; } pub const block_size = 16; // Stage1 can't parse addrspace, so we use pre-processing tricks to only // set the addrspace in Stage2. // In Cuda, the kernel will have access to shared memory. This memory // can have a compile-known size or a dynamic size. // In the case of dynamic size the corresponding Cuda code is: // extern __shared__ int buffer[]; // In Zig, the only type with unknown size is "opaque". // Also note that the extern keyword is technically not correct, because the variable // isn't defined in another compilation unit. // This seems to only work for Ptx target, not sure why. // The generated .ll code will be: // `@transpose_per_block_buffer = external dso_local addrspace(3) global %lesson5_kernel.SharedMem, align 8` // Corresponding .ptx: // `.extern .shared .align 8 .b8 transpose_per_block_buffer[]` const SharedMem = opaque {}; // extern var transpose_per_block_buffer: SharedMem align(8) addrspace(.shared); // stage2 var transpose_per_block_buffer: [block_size][block_size]u32 = undefined; // stage1 /// Each threads copy one element to the shared buffer and then back to the output /// The speed up comes from the fact that all threads in the block will read contiguous /// data and then write contiguous data. pub export fn transposePerBlock(data: []const u32, trans: []u32, num_cols: usize) callconv(PtxKernel) void { if (!is_nvptx) return; // var buffer = @ptrCast([*]addrspace(.shared) [block_size]u32, &transpose_per_block_buffer); // stage2 var buffer = @ptrCast([*][block_size]u32, &transpose_per_block_buffer); // stage1 const block_i = gridIdX() * block_size; const block_j = gridIdY() * block_size; const block_out_i = block_j; const block_out_j = block_i; const i = threadIdX(); const j = threadIdY(); // coalesced read if (i + block_i < num_cols and j + block_j < num_cols) { buffer[j][i] = data[num_cols * (block_j + j) + (block_i + i)]; } syncThreads(); // coalesced write if (i + block_out_i < num_cols and j + block_out_j < num_cols) { trans[num_cols * (block_out_j + j) + (block_out_i + i)] = buffer[i][j]; } } pub const block_size_inline = block_size; // pub var transpose_per_block_inlined_buffer: [16][block_size][block_size]u32 addrspace(.shared) = undefined; // stage2 pub var transpose_per_block_inlined_buffer: [16][block_size][block_size]u32 = undefined; // stage1 /// Each threads copy a `block_size` contiguous elements to the shared buffer /// and copy non-contiguous element from the buffer to a contiguous slice of the output pub export fn transposePerBlockInlined(data: []const u32, trans: []u32, num_cols: usize) callconv(PtxKernel) void { var buffer = &transpose_per_block_inlined_buffer[threadIdX()]; const block_i = getIdX() * block_size; const block_j = gridIdY() * block_size; const block_out_i = block_j; const block_out_j = block_i; const i = threadIdY(); if (i + block_i >= num_cols) return; var j: usize = 0; // coalesced read while (j < block_size and j + block_j < num_cols) : (j += 1) { buffer[j][i] = data[num_cols * (block_j + j) + (block_i + i)]; } syncThreads(); if (block_out_i + i >= num_cols) return; // coalesced write j = 0; while (j < block_size and block_out_j + j < num_cols) : (j += 1) { trans[num_cols * (block_out_j + j) + (block_out_i + i)] = buffer[i][j]; } } pub inline fn threadIdX() usize { if (!is_nvptx) return 0; var tid = asm volatile ("mov.u32 \t$0, %tid.x;" : [ret] "=r" (-> u32), ); return @intCast(usize, tid); } pub inline fn threadDimX() usize { if (!is_nvptx) return 0; var ntid = asm volatile ("mov.u32 \t$0, %ntid.x;" : [ret] "=r" (-> u32), ); return @intCast(usize, ntid); } pub inline fn gridIdX() usize { if (!is_nvptx) return 0; var ctaid = asm volatile ("mov.u32 \t$0, %ctaid.x;" : [ret] "=r" (-> u32), ); return @intCast(usize, ctaid); } pub inline fn threadIdY() usize { if (!is_nvptx) return 0; var tid = asm volatile ("mov.u32 \t$0, %tid.y;" : [ret] "=r" (-> u32), ); return @intCast(usize, tid); } pub inline fn threadDimY() usize { if (!is_nvptx) return 0; var ntid = asm volatile ("mov.u32 \t$0, %ntid.y;" : [ret] "=r" (-> u32), ); return @intCast(usize, ntid); } pub inline fn gridIdY() usize { if (!is_nvptx) return 0; var ctaid = asm volatile ("mov.u32 \t$0, %ctaid.y;" : [ret] "=r" (-> u32), ); return @intCast(usize, ctaid); } pub inline fn getIdX() usize { return threadIdX() + threadDimX() * gridIdX(); } pub inline fn getIdY() usize { return threadIdY() + threadDimY() * gridIdY(); } pub inline fn syncThreads() void { // @"llvm.nvvm.barrier0"(); if (!is_nvptx) return; asm volatile ("bar.sync \t0;"); }
0
repos/cudaz
repos/cudaz/cudaz/sdk.zig
const std = @import("std"); const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; /// Can be one of "ptx" or "fatbin". "cubin" don't work, because it implies a main. /// Fatbin contains device specialized assembly for all GPU arch supported /// by this compiler. This provides faster startup time. /// Ptx is a high-level text assembly that can converted to GPU specialized /// instruction on loading. /// We default to .ptx because it's more easy to distribute. // TODO: make this a build option const NVCC_OUTPUT_FORMAT = "ptx"; const ZIG_STAGE2 = "/home/guw/github/zig/build/stage3/bin/zig"; const SDK_ROOT = sdk_root() ++ "/"; /// For a given object: /// 1. Compile the given .cu file to a .ptx with `nvcc` /// 2. Add lib C /// 3. Add cuda headers, and cuda lib path /// 4. Add Cudaz package with the given .cu file that will get imported as C code. /// /// The .ptx file will have the same base name than the executable /// and will appear in zig-out/bin folder next to the executable. /// In release mode the .ptx will be embedded inside the executable /// so you can distribute it. pub fn addCudazWithNvcc( b: *Builder, exe: *LibExeObjStep, comptime cuda_dir: []const u8, comptime kernel_path: [:0]const u8, ) void { const outfile = std.mem.join( b.allocator, ".", &[_][]const u8{ exe.name, NVCC_OUTPUT_FORMAT }, ) catch unreachable; const kernel_ptx_path = std.fs.path.joinZ( b.allocator, &[_][]const u8{ b.exe_dir, outfile }, ) catch unreachable; std.fs.cwd().makePath(b.exe_dir) catch @panic("Couldn't create zig-out output dir"); // Use nvcc to compile the .cu file const nvcc = b.addSystemCommand(&[_][]const u8{ cuda_dir ++ "/bin/nvcc", // In Zig spirit, promote warnings to errors. "--Werror=all-warnings", "--display-error-number", // Don't require exactly gcc-11 "-allow-unsupported-compiler", // TODO: try to use zig c++ here. For me it failed with: // zig: error: CUDA version is newer than the latest supported version 11.5 [-Werror,-Wunknown-cuda-version] // zig: error: cannot specify -o when generating multiple output files "-ccbin", "/usr/bin/gcc", "--" ++ NVCC_OUTPUT_FORMAT, "-I", SDK_ROOT ++ "src", kernel_path, "-o", kernel_ptx_path, }); exe.step.dependOn(&nvcc.step); addCudazDeps(b, exe, cuda_dir, kernel_path, kernel_ptx_path); } /// Leverages stage2 to generate the .ptx from a .zig file. /// This restricts the kernel to use the subset of Zig supported by stage2. pub fn addCudazWithZigKernel( b: *Builder, exe: *LibExeObjStep, comptime cuda_dir: []const u8, comptime kernel_path: [:0]const u8, ) void { const name = std.fs.path.basename(kernel_path); const zig_kernel = b.addObject(name, kernel_path); // This yield an <error: unknown CPU: ''> // const sm32ptx75 = std.Target.Cpu.Model{ // .name = "sm_32", // .llvm_name = "sm_32", // .features = std.Target.nvptx.featureSet(&[_]std.Target.nvptx.Feature{ // .ptx75, // .sm_32, // }), // }; zig_kernel.setTarget(.{ .cpu_arch = .nvptx64, .os_tag = .cuda, // .cpu_model = .{ .explicit = &sm32ptx75 }, .cpu_model = .{ .explicit = &std.Target.nvptx.cpu.sm_32 }, // .cpu_features_add = std.Target.nvptx.featureSet(&[_]std.Target.nvptx.Feature{ // .ptx75, // }), }); // ReleaseFast because the panic handler leads to a // external dso_local constant with a name to complex for PTX // TODO: try to sanitize name in the NvPtx Zig backend. zig_kernel.setBuildMode(.ReleaseFast); // Adding the nvptx.zig package doesn't seem to work const ptx_pkg = std.build.Pkg{ .name = "ptx", .source = .{ .path = SDK_ROOT ++ "src/nvptx.zig" }, }; if (!std.mem.eql(u8, name, "nvptx.zig")) { // Don't include nvptx.zig in itself // TODO: find a more robust test zig_kernel.addPackage(ptx_pkg); } // Copy the .ptx next to the binary for easy review. zig_kernel.setOutputDir(b.exe_dir); const kernel_ptx_path = std.mem.joinZ( b.allocator, "", &[_][]const u8{ b.exe_dir, "/", zig_kernel.out_filename, ".ptx" }, ) catch unreachable; // TODO: we should make this optional to allow compiling without a CUDA toolchain const validate_ptx = b.addSystemCommand( &[_][]const u8{ cuda_dir ++ "/bin/ptxas", kernel_ptx_path }, ); validate_ptx.step.dependOn(&zig_kernel.step); exe.step.dependOn(&validate_ptx.step); addCudazDeps(b, exe, cuda_dir, kernel_path, kernel_ptx_path); } pub fn addCudazDeps( b: *Builder, exe: *LibExeObjStep, comptime cuda_dir: []const u8, comptime kernel_path: [:0]const u8, kernel_ptx_path: [:0]const u8, ) void { const kernel_dir = std.fs.path.dirname(kernel_path).?; // Add libc and cuda headers / lib, and our own .cu files exe.linkLibC(); exe.addLibPath(cuda_dir ++ "/lib64"); exe.linkSystemLibraryNeeded("cuda"); // If nvidia-ptxjitcompiler is not found on your system, // check that there is a libnvidia-ptxjitcompiler.so, or create a symlink // to the right version. // We don't need to link ptxjit compiler, since it's loaded at runtime, // but this should warn the user that something is wrong. exe.linkSystemLibraryNeeded("nvidia-ptxjitcompiler"); exe.addIncludeDir(SDK_ROOT ++ "src"); exe.addIncludeDir(cuda_dir ++ "/include"); exe.addIncludeDir(kernel_dir); // Add cudaz package with the kernel paths. const cudaz_options = b.addOptions(); cudaz_options.addOption([:0]const u8, "kernel_path", kernel_path); cudaz_options.addOption([]const u8, "kernel_name", std.fs.path.basename(kernel_path)); cudaz_options.addOption([:0]const u8, "kernel_ptx_path", kernel_ptx_path); cudaz_options.addOption([]const u8, "kernel_dir", kernel_dir); cudaz_options.addOption(bool, "cuda_kernel", std.mem.endsWith(u8, kernel_path, ".cu")); // Portable mode will embed the cuda modules inside the binary. // In debug mode we skip this step to have faster compilation. // But this makes the debug executable dependent on a hard-coded path. cudaz_options.addOption(bool, "portable", exe.build_mode != .Debug); const cudaz_pkg = std.build.Pkg{ .name = "cudaz", .source = .{ .path = SDK_ROOT ++ "src/cuda.zig" }, .dependencies = &[_]std.build.Pkg{ .{ .name = "cudaz_options", .source = cudaz_options.getSource() }, }, }; const root_src = exe.root_src.?; if (std.mem.eql(u8, root_src.path, "src/cuda.zig")) { // Don't include the package in itself exe.addOptions("cudaz_options", cudaz_options); } else { exe.addPackage(cudaz_pkg); } } fn sdk_root() []const u8 { return std.fs.path.dirname(@src().file).?; } fn needRebuild(kernel_path: [:0]const u8, kernel_ptx_path: [:0]const u8) bool { var ptx_file = std.fs.openFileAbsoluteZ(kernel_ptx_path, .{}) catch return true; var ptx_stat = ptx_file.stat() catch return true; // detect empty .ptx files if (ptx_stat.size < 128) return true; var zig_file = (std.fs.cwd().openFileZ(kernel_path, .{}) catch return true); var zig_time = (zig_file.stat() catch return true).mtime; return zig_time >= ptx_stat.mtime + std.time.ns_per_s * 10; }
0
repos/cudaz
repos/cudaz/cudaz/build.zig
const std = @import("std"); const sdk = @import("sdk.zig"); const CUDA_PATH = "/usr/local/cuda"; const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; pub fn build(b: *Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. // const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. // const mode = b.standardReleaseOptions(); // This isn't very useful, because we still have to declare `extern` symbols // const kernel = b.addObject("kernel", "src/kernel.o"); // kernel.linkLibC(); // kernel.addLibPath("/usr/local/cuda/lib64"); // kernel.linkSystemLibraryName("cudart"); var tests_nvcc = b.step("test_nvcc", "Tests"); const test_cuda = b.addTest("src/cuda.zig"); sdk.addCudazWithNvcc(b, test_cuda, CUDA_PATH, "src/test.cu"); tests_nvcc.dependOn(&test_cuda.step); var tests = b.step("test", "Tests"); const test_nvptx = b.addTest("src/test_nvptx.zig"); sdk.addCudazWithZigKernel(b, test_nvptx, CUDA_PATH, "src/nvptx.zig"); tests.dependOn(&test_nvptx.step); }
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/cuda_errors.zig
const std = @import("std"); const log = std.log.scoped(.Cuda); pub const cu = @import("cuda_cimports.zig").cu; pub const Error = error{ OutOfMemory, LaunchOutOfResources, UnexpectedByCudaz, NotSupported, NotReady, // TODO: add more generic errors to allow forward compatibilities with more // Cuda versions / Cudaz development. }; /// Converts the Cuda result code into a simplified Zig error. /// The goal is to only surface errors that are recoverable and aren't due to a /// bug in caller code, library code or kernel code. /// Cuda can yield a lot of different errors, but there are different categories. /// Note that in any case we will log the detailed error and its message. /// * Resource errors: typically out of memory. /// -> original error (OutOfMemory, ...) /// * Device capability errors: the current device doesn't support this function. /// -> NotSupported /// * API usage errors: errors that will deterministically be returned /// when the API is misused. Cudaz is allowed to panic here. /// Cudaz aims at preventing this kind of error by providing an API harder to misuses. /// Typically calling Cuda methods before calling cuInit(). /// This can also be due to passing host pointer to functions expecting device pointer. /// -> @panic /// * Message passing: not actual error, but things that should be retried. /// eg: CUDA_ERROR_NOT_READY /// -> NotReady /// * Bug in Cudaz: Cudaz is creating a default context and loading the compiled /// Cuda code for you. Those operation shouldn't fail unless bug in Cudaz. /// -> @panic /// * Kernel execution error: /// There was a bug during kernel execution (stackoverflow, segfault, ...) /// Typically those leave the driver in unusable state, the process must be restarted. /// Cudaz will panic here. /// This will typically not trigger at the expected place because they will /// happen asynchronously to the host code execution. /// -> @panic /// * Unhandled errors: /// Cudaz doesn't support the full Cuda API (yet ?). Trying to use Cudaz /// check on errors returned by unsupported part of the API will trigger a @panic /// (this will only happen if you directly call cuda). Feel free to open PR /// to support more parts of Cuda /// -> @panic pub fn check(result: cu.CUresult) Error!void { if (result == cu.CUDA_SUCCESS) return; log_err_message(result); return silent_check(result); } pub fn silent_check(result: cu.CUresult) Error!void { var err: Error = switch (result) { cu.CUDA_SUCCESS => return, // Resource errors: cu.CUDA_ERROR_OUT_OF_MEMORY => error.OutOfMemory, // Device capability error: cu.CUDA_ERROR_STUB_LIBRARY, cu.CUDA_ERROR_NO_DEVICE, cu.CUDA_ERROR_INVALID_DEVICE, cu.CUDA_ERROR_DEVICE_NOT_LICENSED, cu.CUDA_ERROR_NOT_PERMITTED, // TODO: make a distinctions for permission ? cu.CUDA_ERROR_NOT_SUPPORTED, cu.CUDA_ERROR_SYSTEM_NOT_READY, cu.CUDA_ERROR_SYSTEM_DRIVER_MISMATCH, cu.CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE, cu.CUDA_ERROR_JIT_COMPILER_NOT_FOUND, => error.NotSupported, // LAUNCH_OUT_OF_RESOURCES can indicate either that the too many threads // where requested wrt to the maximum supported by the GPU. // It can also be triggered by passing too many args to a kernel, // but this should be caught at compile time by Cudaz, so we will ignore this. cu.CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES => error.NotSupported, // API usage errors: cu.CUDA_ERROR_INVALID_VALUE => @panic("Received invalid parameters (typically device/host pointer mismatch"), cu.CUDA_ERROR_NOT_INITIALIZED, cu.CUDA_ERROR_DEINITIALIZED, cu.CUDA_ERROR_PROFILER_NOT_INITIALIZED, cu.CUDA_ERROR_PROFILER_ALREADY_STARTED, cu.CUDA_ERROR_PROFILER_ALREADY_STOPPED, cu.CUDA_ERROR_PROFILER_DISABLED, cu.CUDA_ERROR_CONTEXT_ALREADY_CURRENT, cu.CUDA_ERROR_CONTEXT_ALREADY_IN_USE, cu.CUDA_ERROR_INVALID_HANDLE, => @panic("Invalid API usage"), // Bug in Cudaz: cu.CUDA_ERROR_INVALID_IMAGE, cu.CUDA_ERROR_INVALID_CONTEXT, cu.CUDA_ERROR_NO_BINARY_FOR_GPU, cu.CUDA_ERROR_INVALID_PTX, cu.CUDA_ERROR_INVALID_GRAPHICS_CONTEXT, cu.CUDA_ERROR_UNSUPPORTED_PTX_VERSION, cu.CUDA_ERROR_INVALID_SOURCE, cu.CUDA_ERROR_FILE_NOT_FOUND, cu.CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, cu.CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, cu.CUDA_ERROR_NOT_FOUND, => @panic("Something looks wrong with compiled device code"), // Kernel execution error: cu.CUDA_ERROR_ECC_UNCORRECTABLE, cu.CUDA_ERROR_HARDWARE_STACK_ERROR, cu.CUDA_ERROR_ILLEGAL_INSTRUCTION, cu.CUDA_ERROR_MISALIGNED_ADDRESS, cu.CUDA_ERROR_ILLEGAL_ADDRESS, cu.CUDA_ERROR_INVALID_ADDRESS_SPACE, cu.CUDA_ERROR_INVALID_PC, cu.CUDA_ERROR_LAUNCH_FAILED, cu.CUDA_ERROR_EXTERNAL_DEVICE, => @panic("Unrecoverable error while running device code"), // Unhandled errors: // Map, Stream, Graph else => @panic("Part of the API not handled by Cudaz"), }; return err; } pub fn error_name(result: cu.CUresult) []const u8 { return switch (result) { cu.CUDA_SUCCESS => "CUDA_SUCCESS", cu.CUDA_ERROR_INVALID_VALUE => "CUDA_ERROR_INVALID_VALUE", cu.CUDA_ERROR_OUT_OF_MEMORY => "CUDA_ERROR_OUT_OF_MEMORY", cu.CUDA_ERROR_NOT_INITIALIZED => "CUDA_ERROR_NOT_INITIALIZED", cu.CUDA_ERROR_DEINITIALIZED => "CUDA_ERROR_DEINITIALIZED", cu.CUDA_ERROR_PROFILER_DISABLED => "CUDA_ERROR_PROFILER_DISABLED", cu.CUDA_ERROR_PROFILER_NOT_INITIALIZED => "CUDA_ERROR_PROFILER_NOT_INITIALIZED", cu.CUDA_ERROR_PROFILER_ALREADY_STARTED => "CUDA_ERROR_PROFILER_ALREADY_STARTED", cu.CUDA_ERROR_PROFILER_ALREADY_STOPPED => "CUDA_ERROR_PROFILER_ALREADY_STOPPED", cu.CUDA_ERROR_STUB_LIBRARY => "CUDA_ERROR_STUB_LIBRARY", cu.CUDA_ERROR_NO_DEVICE => "CUDA_ERROR_NO_DEVICE", cu.CUDA_ERROR_INVALID_DEVICE => "CUDA_ERROR_INVALID_DEVICE", cu.CUDA_ERROR_DEVICE_NOT_LICENSED => "CUDA_ERROR_DEVICE_NOT_LICENSED", cu.CUDA_ERROR_INVALID_IMAGE => "CUDA_ERROR_INVALID_IMAGE", cu.CUDA_ERROR_INVALID_CONTEXT => "CUDA_ERROR_INVALID_CONTEXT", cu.CUDA_ERROR_CONTEXT_ALREADY_CURRENT => "CUDA_ERROR_CONTEXT_ALREADY_CURRENT", cu.CUDA_ERROR_MAP_FAILED => "CUDA_ERROR_MAP_FAILED", cu.CUDA_ERROR_UNMAP_FAILED => "CUDA_ERROR_UNMAP_FAILED", cu.CUDA_ERROR_ARRAY_IS_MAPPED => "CUDA_ERROR_ARRAY_IS_MAPPED", cu.CUDA_ERROR_ALREADY_MAPPED => "CUDA_ERROR_ALREADY_MAPPED", cu.CUDA_ERROR_NO_BINARY_FOR_GPU => "CUDA_ERROR_NO_BINARY_FOR_GPU", cu.CUDA_ERROR_ALREADY_ACQUIRED => "CUDA_ERROR_ALREADY_ACQUIRED", cu.CUDA_ERROR_NOT_MAPPED => "CUDA_ERROR_NOT_MAPPED", cu.CUDA_ERROR_NOT_MAPPED_AS_ARRAY => "CUDA_ERROR_NOT_MAPPED_AS_ARRAY", cu.CUDA_ERROR_NOT_MAPPED_AS_POINTER => "CUDA_ERROR_NOT_MAPPED_AS_POINTER", cu.CUDA_ERROR_ECC_UNCORRECTABLE => "CUDA_ERROR_ECC_UNCORRECTABLE", cu.CUDA_ERROR_UNSUPPORTED_LIMIT => "CUDA_ERROR_UNSUPPORTED_LIMIT", cu.CUDA_ERROR_CONTEXT_ALREADY_IN_USE => "CUDA_ERROR_CONTEXT_ALREADY_IN_USE", cu.CUDA_ERROR_PEER_ACCESS_UNSUPPORTED => "CUDA_ERROR_PEER_ACCESS_UNSUPPORTED", cu.CUDA_ERROR_INVALID_PTX => "CUDA_ERROR_INVALID_PTX", cu.CUDA_ERROR_INVALID_GRAPHICS_CONTEXT => "CUDA_ERROR_INVALID_GRAPHICS_CONTEXT", cu.CUDA_ERROR_NVLINK_UNCORRECTABLE => "CUDA_ERROR_NVLINK_UNCORRECTABLE", cu.CUDA_ERROR_JIT_COMPILER_NOT_FOUND => "CUDA_ERROR_JIT_COMPILER_NOT_FOUND", cu.CUDA_ERROR_UNSUPPORTED_PTX_VERSION => "CUDA_ERROR_UNSUPPORTED_PTX_VERSION", cu.CUDA_ERROR_JIT_COMPILATION_DISABLED => "CUDA_ERROR_JIT_COMPILATION_DISABLED", cu.CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY => "CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY", cu.CUDA_ERROR_INVALID_SOURCE => "CUDA_ERROR_INVALID_SOURCE", cu.CUDA_ERROR_FILE_NOT_FOUND => "CUDA_ERROR_FILE_NOT_FOUND", cu.CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND => "CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND", cu.CUDA_ERROR_SHARED_OBJECT_INIT_FAILED => "CUDA_ERROR_SHARED_OBJECT_INIT_FAILED", cu.CUDA_ERROR_OPERATING_SYSTEM => "CUDA_ERROR_OPERATING_SYSTEM", cu.CUDA_ERROR_INVALID_HANDLE => "CUDA_ERROR_INVALID_HANDLE", cu.CUDA_ERROR_ILLEGAL_STATE => "CUDA_ERROR_ILLEGAL_STATE", cu.CUDA_ERROR_NOT_FOUND => "CUDA_ERROR_NOT_FOUND", cu.CUDA_ERROR_NOT_READY => "CUDA_ERROR_NOT_READY", cu.CUDA_ERROR_ILLEGAL_ADDRESS => "CUDA_ERROR_ILLEGAL_ADDRESS", cu.CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES => "CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES", cu.CUDA_ERROR_LAUNCH_TIMEOUT => "CUDA_ERROR_LAUNCH_TIMEOUT", cu.CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING => "CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING", cu.CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED => "CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED", cu.CUDA_ERROR_PEER_ACCESS_NOT_ENABLED => "CUDA_ERROR_PEER_ACCESS_NOT_ENABLED", cu.CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE => "CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE", cu.CUDA_ERROR_CONTEXT_IS_DESTROYED => "CUDA_ERROR_CONTEXT_IS_DESTROYED", cu.CUDA_ERROR_ASSERT => "CUDA_ERROR_ASSERT", cu.CUDA_ERROR_TOO_MANY_PEERS => "CUDA_ERROR_TOO_MANY_PEERS", cu.CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED => "CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED", cu.CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED => "CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED", cu.CUDA_ERROR_HARDWARE_STACK_ERROR => "CUDA_ERROR_HARDWARE_STACK_ERROR", cu.CUDA_ERROR_ILLEGAL_INSTRUCTION => "CUDA_ERROR_ILLEGAL_INSTRUCTION", cu.CUDA_ERROR_MISALIGNED_ADDRESS => "CUDA_ERROR_MISALIGNED_ADDRESS", cu.CUDA_ERROR_INVALID_ADDRESS_SPACE => "CUDA_ERROR_INVALID_ADDRESS_SPACE", cu.CUDA_ERROR_INVALID_PC => "CUDA_ERROR_INVALID_PC", cu.CUDA_ERROR_LAUNCH_FAILED => "CUDA_ERROR_LAUNCH_FAILED", cu.CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE => "CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE", cu.CUDA_ERROR_NOT_PERMITTED => "CUDA_ERROR_NOT_PERMITTED", cu.CUDA_ERROR_NOT_SUPPORTED => "CUDA_ERROR_NOT_SUPPORTED", cu.CUDA_ERROR_SYSTEM_NOT_READY => "CUDA_ERROR_SYSTEM_NOT_READY", cu.CUDA_ERROR_SYSTEM_DRIVER_MISMATCH => "CUDA_ERROR_SYSTEM_DRIVER_MISMATCH", cu.CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE => "CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE", cu.CUDA_ERROR_MPS_CONNECTION_FAILED => "CUDA_ERROR_MPS_CONNECTION_FAILED", cu.CUDA_ERROR_MPS_RPC_FAILURE => "CUDA_ERROR_MPS_RPC_FAILURE", cu.CUDA_ERROR_MPS_SERVER_NOT_READY => "CUDA_ERROR_MPS_SERVER_NOT_READY", cu.CUDA_ERROR_MPS_MAX_CLIENTS_REACHED => "CUDA_ERROR_MPS_MAX_CLIENTS_REACHED", cu.CUDA_ERROR_MPS_MAX_CONNECTIONS_REACHED => "CUDA_ERROR_MPS_MAX_CONNECTIONS_REACHED", cu.CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED => "CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED", cu.CUDA_ERROR_STREAM_CAPTURE_INVALIDATED => "CUDA_ERROR_STREAM_CAPTURE_INVALIDATED", cu.CUDA_ERROR_STREAM_CAPTURE_MERGE => "CUDA_ERROR_STREAM_CAPTURE_MERGE", cu.CUDA_ERROR_STREAM_CAPTURE_UNMATCHED => "CUDA_ERROR_STREAM_CAPTURE_UNMATCHED", cu.CUDA_ERROR_STREAM_CAPTURE_UNJOINED => "CUDA_ERROR_STREAM_CAPTURE_UNJOINED", cu.CUDA_ERROR_STREAM_CAPTURE_ISOLATION => "CUDA_ERROR_STREAM_CAPTURE_ISOLATION", cu.CUDA_ERROR_STREAM_CAPTURE_IMPLICIT => "CUDA_ERROR_STREAM_CAPTURE_IMPLICIT", cu.CUDA_ERROR_CAPTURED_EVENT => "CUDA_ERROR_CAPTURED_EVENT", cu.CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD => "CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD", cu.CUDA_ERROR_TIMEOUT => "CUDA_ERROR_TIMEOUT", cu.CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE => "CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE", cu.CUDA_ERROR_EXTERNAL_DEVICE => "CUDA_ERROR_EXTERNAL_DEVICE", cu.CUDA_ERROR_UNKNOWN => "CUDA_ERROR_UNKNOWN", else => "<Unexpected cuda error please open a bug to Cudaz>", }; } pub fn log_err_message(result: cu.CUresult) void { const err_name = error_name(result); var err_message: [*c]const u8 = undefined; const error_string_res = cu.cuGetErrorString(result, &err_message); if (error_string_res != cu.CUDA_SUCCESS) { err_message = "(no error message)"; } log.err("{s}({d}): {s}", .{ err_name, result, err_message }); }
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/attributes.zig
const std = @import("std"); const cu = @import("cuda_cimports.zig").cu; pub const Attribute = enum(c_uint) { /// Maximum number of threads per block MaxThreadsPerBlock = 1, /// Maximum block dimension X MaxBlockDimX = 2, /// Maximum block dimension Y MaxBlockDimY = 3, /// Maximum block dimension Z MaxBlockDimZ = 4, /// Maximum grid dimension X MaxGridDimX = 5, /// Maximum grid dimension Y MaxGridDimY = 6, /// Maximum grid dimension Z MaxGridDimZ = 7, /// Maximum shared memory available per block in bytes MaxSharedMemoryPerBlock = 8, /// Memory available on device for __constant__ variables in a CUDA C kernel in bytes TotalConstantMemory = 9, /// Warp size in threads WarpSize = 10, /// Maximum pitch in bytes allowed by memory copies MaxPitch = 11, /// Maximum number of 32-bit registers available per block MaxRegistersPerBlock = 12, /// Typical clock frequency in kilohertz ClockRate = 13, /// Alignment requirement for textures TextureAlignment = 14, /// Device can possibly copy memory and execute a kernel concurrently. Deprecated. Use instead AsyncEngineCount. GpuOverlap = 15, /// Number of multiprocessors on device MultiprocessorCount = 16, /// Specifies whether there is a run time limit on kernels KernelExecTimeout = 17, /// Device is integrated with host memory Integrated = 18, /// Device can map host memory into CUDA address space CanMapHostMemory = 19, /// Compute mode (See ::CUcomputemode for details) ComputeMode = 20, /// Maximum 1D texture width MaximumTexture1dWidth = 21, /// Maximum 2D texture width MaximumTexture2dWidth = 22, /// Maximum 2D texture height MaximumTexture2dHeight = 23, /// Maximum 3D texture width MaximumTexture3dWidth = 24, /// Maximum 3D texture height MaximumTexture3dHeight = 25, /// Maximum 3D texture depth MaximumTexture3dDepth = 26, /// Maximum 2D layered texture width MaximumTexture2dLayeredWidth = 27, /// Maximum 2D layered texture height MaximumTexture2dLayeredHeight = 28, /// Maximum layers in a 2D layered texture MaximumTexture2dLayeredLayers = 29, /// Alignment requirement for surfaces SurfaceAlignment = 30, /// Device can possibly execute multiple kernels concurrently ConcurrentKernels = 31, /// Device has ECC support enabled EccEnabled = 32, /// PCI bus ID of the device PciBusID = 33, /// PCI device ID of the device PciDeviceID = 34, /// Device is using TCC driver model TccDriver = 35, /// Peak memory clock frequency in kilohertz MemoryClockRate = 36, /// Global memory bus width in bits GlobalMemoryBusWidth = 37, /// Size of L2 cache in bytes L2CacheSize = 38, /// Maximum resident threads per multiprocessor MaxThreadsPerMultiprocessor = 39, /// Number of asynchronous engines AsyncEngineCount = 40, /// Device shares a unified address space with the host UnifiedAddressing = 41, /// Maximum 1D layered texture width MaximumTexture1dLayeredWidth = 42, /// Maximum layers in a 1D layered texture MaximumTexture1dLayeredLayers = 43, /// Deprecated, do not use. CanTex2dGather = 44, /// Maximum 2D texture width if CUDA_ARRAY3D_TEXTURE_GATHER is set MaximumTexture2dGatherWidth = 45, /// Maximum 2D texture height if CUDA_ARRAY3D_TEXTURE_GATHER is set MaximumTexture2dGatherHeight = 46, /// Alternate maximum 3D texture width MaximumTexture3dWidthAlternate = 47, /// Alternate maximum 3D texture height MaximumTexture3dHeightAlternate = 48, /// Alternate maximum 3D texture depth MaximumTexture3dDepthAlternate = 49, /// PCI domain ID of the device PciDomainID = 50, /// Pitch alignment requirement for textures TexturePitchAlignment = 51, /// Maximum cubemap texture width/height MaximumTexturecubemapWidth = 52, /// Maximum cubemap layered texture width/height MaximumTexturecubemapLayeredWidth = 53, /// Maximum layers in a cubemap layered texture MaximumTexturecubemapLayeredLayers = 54, /// Maximum 1D surface width MaximumSurface1dWidth = 55, /// Maximum 2D surface width MaximumSurface2dWidth = 56, /// Maximum 2D surface height MaximumSurface2dHeight = 57, /// Maximum 3D surface width MaximumSurface3dWidth = 58, /// Maximum 3D surface height MaximumSurface3dHeight = 59, /// Maximum 3D surface depth MaximumSurface3dDepth = 60, /// Maximum 1D layered surface width MaximumSurface1dLayeredWidth = 61, /// Maximum layers in a 1D layered surface MaximumSurface1dLayeredLayers = 62, /// Maximum 2D layered surface width MaximumSurface2dLayeredWidth = 63, /// Maximum 2D layered surface height MaximumSurface2dLayeredHeight = 64, /// Maximum layers in a 2D layered surface MaximumSurface2dLayeredLayers = 65, /// Maximum cubemap surface width MaximumSurfacecubemapWidth = 66, /// Maximum cubemap layered surface width MaximumSurfacecubemapLayeredWidth = 67, /// Maximum layers in a cubemap layered surface MaximumSurfacecubemapLayeredLayers = 68, /// Deprecated, do not use. Use cudaDeviceGetTexture1DLinearMaxWidth() or cuDeviceGetTexture1DLinearMaxWidth() instead. MaximumTexture1dLinearWidth = 69, /// Maximum 2D linear texture width MaximumTexture2dLinearWidth = 70, /// Maximum 2D linear texture height MaximumTexture2dLinearHeight = 71, /// Maximum 2D linear texture pitch in bytes MaximumTexture2dLinearPitch = 72, /// Maximum mipmapped 2D texture width MaximumTexture2dMipmappedWidth = 73, /// Maximum mipmapped 2D texture height MaximumTexture2dMipmappedHeight = 74, /// Major compute capability version number ComputeCapabilityMajor = 75, /// Minor compute capability version number ComputeCapabilityMinor = 76, /// Maximum mipmapped 1D texture width MaximumTexture1dMipmappedWidth = 77, /// Device supports stream priorities StreamPrioritiesSupported = 78, /// Device supports caching globals in L1 GlobalL1CacheSupported = 79, /// Device supports caching locals in L1 LocalL1CacheSupported = 80, /// Maximum shared memory available per multiprocessor in bytes MaxSharedMemoryPerMultiprocessor = 81, /// Maximum number of 32-bit registers available per multiprocessor MaxRegistersPerMultiprocessor = 82, /// Device can allocate managed memory on this system ManagedMemory = 83, /// Device is on a multi-GPU board MultiGpuBoard = 84, /// Unique id for a group of devices on the same multi-GPU board MultiGpuBoardGroupID = 85, /// Link between the device and the host supports native atomic operations (this is a placeholder attribute, and is not supported on any current hardware HostNativeAtomicSupported = 86, /// Ratio of single precision performance (in floating-point operations per second) to double precision performance SingleToDoublePrecisionPerfRatio = 87, /// Device supports coherently accessing pageable memory without calling cudaHostRegister on it PageableMemoryAccess = 88, /// Device can coherently access managed memory concurrently with the CPU ConcurrentManagedAccess = 89, /// Device supports compute preemption. ComputePreemptionSupported = 90, /// Device can access host registered memory at the same virtual address as the CPU CanUseHostPointerForRegisteredMem = 91, /// ::cuStreamBatchMemOp and related APIs are supported. CanUseStreamMemOps = 92, /// 64-bit operations are supported in ::cuStreamBatchMemOp and related APIs. CanUse64BitStreamMemOps = 93, /// ::CU_STREAM_WAIT_VALUE_NOR is supported. CanUseStreamWaitValueNor = 94, /// Device supports launching cooperative kernels via ::cuLaunchCooperativeKernel CooperativeLaunch = 95, /// Deprecated, ::cuLaunchCooperativeKernelMultiDevice is deprecated. CooperativeMultiDeviceLaunch = 96, /// Maximum optin shared memory per block MaxSharedMemoryPerBlockOptin = 97, /// The ::CU_STREAM_WAIT_VALUE_FLUSH flag and the ::CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES MemOp are supported on the device. See \ref CUDA_MEMOP for additional details. CanFlushRemoteWrites = 98, /// Device supports host memory registration via ::cudaHostRegister. HostRegisterSupported = 99, /// Device accesses pageable memory via the host's page tables. PageableMemoryAccessUsesHostPageTables = 100, /// The host can directly access managed memory on the device without migration. DirectManagedMemAccessFromHost = 101, /// Device supports virtual memory management APIs like ::cuMemAddressReserve, ::cuMemCreate, ::cuMemMap and related APIs VirtualMemoryManagementSupported = 102, /// Device supports exporting memory to a posix file descriptor with ::cuMemExportToShareableHandle, if requested via ::cuMemCreate HandleTypePosixFileDescriptorSupported = 103, /// Device supports exporting memory to a Win32 NT handle with ::cuMemExportToShareableHandle, if requested via ::cuMemCreate HandleTypeWin32HandleSupported = 104, /// Device supports exporting memory to a Win32 KMT handle with ::cuMemExportToShareableHandle, if requested ::cuMemCreate HandleTypeWin32KmtHandleSupported = 105, /// Maximum number of blocks per multiprocessor MaxBlocksPerMultiprocessor = 106, /// Device supports compression of memory GenericCompressionSupported = 107, /// Maximum L2 persisting lines capacity setting in bytes. MaxPersistingL2CacheSize = 108, /// Maximum value of CUaccessPolicyWindow::num_bytes. MaxAccessPolicyWindowSize = 109, /// Device supports specifying the GPUDirect RDMA flag with ::cuMemCreate GpuDirectRdmaWithCudaVmmSupported = 110, /// Shared memory reserved by CUDA driver per block in bytes ReservedSharedMemoryPerBlock = 111, /// Device supports sparse CUDA arrays and sparse CUDA mipmapped arrays SparseCudaArraySupported = 112, /// Device supports using the ::cuMemHostRegister flag CU_MEMHOSTERGISTER_READ_ONLY to register memory that must be mapped as read-only to the GPU ReadOnlyHostRegisterSupported = 113, /// External timeline semaphore interop is supported on the device TimelineSemaphoreInteropSupported = 114, /// Device supports using the ::cuMemAllocAsync and ::cuMemPool family of APIs MemoryPoolsSupported = 115, /// Device supports GPUDirect RDMA APIs, like nvidia_p2p_get_pages (see https://docs.nvidia.com/cuda/gpudirect-rdma for more information) GpuDirectRdmaSupported = 116, /// The returned attribute shall be interpreted as a bitmask, where the individual bits are described by the ::CUflushGPUDirectRDMAWritesOptions enum GpuDirectRdmaFlushWritesOptions = 117, /// GPUDirect RDMA writes to the device do not need to be flushed for consumers within the scope indicated by the returned attribute. See ::CUGPUDirectRDMAWritesOrdering for the numerical values returned here. GpuDirectRdmaWritesOrdering = 118, /// Handle types supported with mempool based IPC MempoolSupportedHandleTypes = 119, }; // TODO: take a CUdevice here, and expose device in the Stream object pub fn getAttr(device: u8, attr: Attribute) i32 { var d: cu.CUdevice = undefined; _ = cu.cuDeviceGet(&d, device); var value: i32 = std.math.minInt(i32); _ = cu.cuDeviceGetAttribute(&value, @enumToInt(attr), d); return value; }
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/cuda.zig
const std = @import("std"); const builtin = @import("builtin"); const meta = std.meta; const testing = std.testing; const TypeInfo = std.builtin.TypeInfo; const cudaz_options = @import("cudaz_options"); pub const cu = @import("cuda_cimports.zig").cu; pub const cuda_errors = @import("cuda_errors.zig"); pub const check = cuda_errors.check; pub const Error = cuda_errors.Error; const attributes = @import("attributes.zig"); pub const Attribute = attributes.Attribute; pub const getAttr = attributes.getAttr; pub const algorithms = @import("algorithms.zig"); const log = std.log.scoped(.Cuda); pub const Dim3 = struct { x: c_uint = 1, y: c_uint = 1, z: c_uint = 1, pub fn init(x: usize, y: usize, z: usize) Dim3 { return .{ .x = @intCast(c_uint, x), .y = @intCast(c_uint, y), .z = @intCast(c_uint, z), }; } pub fn dim3(self: *const Dim3) cu.dim3 { return cu.dim3{ .x = self.x, .y = self.y, .z = self.z }; } }; /// Represents how kernel are execut pub const Grid = struct { blocks: Dim3 = .{}, threads: Dim3 = .{}, pub fn init1D(len: usize, threads: usize) Grid { return init3D(len, 1, 1, threads, 1, 1); } pub fn init2D(cols: usize, rows: usize, threads_x: usize, threads_y: usize) Grid { return init3D(cols, rows, 1, threads_x, threads_y, 1); } pub fn init3D( cols: usize, rows: usize, depth: usize, threads_x: usize, threads_y: usize, threads_z: usize, ) Grid { var t_x = if (threads_x == 0) cols else threads_x; var t_y = if (threads_y == 0) rows else threads_y; var t_z = if (threads_z == 0) depth else threads_z; return Grid{ .blocks = Dim3.init( std.math.divCeil(usize, cols, t_x) catch unreachable, std.math.divCeil(usize, rows, t_y) catch unreachable, std.math.divCeil(usize, depth, t_z) catch unreachable, ), .threads = Dim3.init(t_x, t_y, t_z), }; } pub fn threadsPerBlock(self: *const Grid) usize { return self.threads.x * self.threads.y * self.threads.z; } pub fn sharedMem(self: *const Grid, comptime ty: type, per_thread: usize) usize { return self.threadsPerBlock() * @sizeOf(ty) * per_thread; } }; pub const Stream = struct { device: cu.CUdevice, _stream: *cu.CUstream_st, pub fn init(device: u3) !Stream { const cu_dev = try initDevice(device); _ = try getCtx(device, cu_dev); var stream: cu.CUstream = undefined; check(cu.cuStreamCreate(&stream, cu.CU_STREAM_DEFAULT)) catch |err| switch (err) { error.NotSupported => return error.NotSupported, else => unreachable, }; return Stream{ .device = cu_dev, ._stream = stream.? }; } pub fn deinit(self: *Stream) void { // Don't handle CUDA errors here _ = self.synchronize(); _ = cu.cuStreamDestroy(self._stream); self._stream = undefined; } // TODO: can this OOM ? Or will the error be raised later ? pub fn alloc(self: *const Stream, comptime DestType: type, size: usize) ![]DestType { var int_ptr: cu.CUdeviceptr = undefined; const byte_size = size * @sizeOf(DestType); check(cu.cuMemAllocAsync(&int_ptr, byte_size, self._stream)) catch |err| { switch (err) { error.OutOfMemory => { var free_mem: usize = undefined; var total_mem: usize = undefined; const mb = 1024 * 1024; check(cu.cuMemGetInfo(&free_mem, &total_mem)) catch return err; log.err( "Cuda OutOfMemory: tried to allocate {d:.1}Mb, free {d:.1}Mb, total {d:.1}Mb", .{ byte_size / mb, free_mem / mb, total_mem / mb }, ); return err; }, else => unreachable, } }; var ptr = @intToPtr([*]DestType, int_ptr); return ptr[0..size]; } pub fn free(self: *const Stream, device_ptr: anytype) void { var raw_ptr: *anyopaque = if (meta.trait.isSlice(@TypeOf(device_ptr))) @ptrCast(*anyopaque, device_ptr.ptr) else @ptrCast(*anyopaque, device_ptr); _ = cu.cuMemFreeAsync(@ptrToInt(raw_ptr), self._stream); } pub fn memcpyHtoD(self: *const Stream, comptime DestType: type, d_target: []DestType, h_source: []const DestType) void { std.debug.assert(h_source.len == d_target.len); check(cu.cuMemcpyHtoDAsync( @ptrToInt(d_target.ptr), @ptrCast(*const anyopaque, h_source.ptr), h_source.len * @sizeOf(DestType), self._stream, )) catch unreachable; } pub fn memcpyDtoH(self: *const Stream, comptime DestType: type, h_target: []DestType, d_source: []const DestType) void { std.debug.assert(d_source.len == h_target.len); check(cu.cuMemcpyDtoHAsync( @ptrCast(*anyopaque, h_target.ptr), @ptrToInt(d_source.ptr), d_source.len * @sizeOf(DestType), self._stream, )) catch unreachable; // The only cause of failures here are segfaults or hardware issues, // can't recover. } pub fn allocAndCopy(self: *const Stream, comptime DestType: type, h_source: []const DestType) ![]DestType { var ptr = try self.alloc(DestType, h_source.len); self.memcpyHtoD(DestType, ptr, h_source); return ptr; } pub fn allocAndCopyResult( self: *const Stream, comptime DestType: type, host_allocator: std.mem.Allocator, d_source: []const DestType, ) ![]DestType { var h_tgt = try host_allocator.alloc(DestType, d_source.len); self.memcpyDtoH(DestType, h_tgt, d_source); return h_tgt; } pub fn memset(self: *const Stream, comptime DestType: type, slice: []DestType, value: DestType) void { var d_ptr = @ptrToInt(slice.ptr); var n = slice.len; var memset_res = switch (@sizeOf(DestType)) { 1 => cu.cuMemsetD8Async(d_ptr, @bitCast(u8, value), n, self._stream), 2 => cu.cuMemsetD16Async(d_ptr, @bitCast(u16, value), n, self._stream), 4 => cu.cuMemsetD32Async(d_ptr, @bitCast(u32, value), n, self._stream), else => @compileError("memset doesn't support type: " ++ @typeName(DestType)), }; check(memset_res) catch unreachable; } pub inline fn launch(self: *const Stream, f: cu.CUfunction, grid: Grid, args: anytype) !void { try self.launchWithSharedMem(f, grid, 0, args); } pub fn launchWithSharedMem(self: *const Stream, f: cu.CUfunction, grid: Grid, shared_mem: usize, args: anytype) !void { // Create an array of pointers pointing to the given args. const fields: []const TypeInfo.StructField = meta.fields(@TypeOf(args)); var args_ptrs: [fields.len:0]usize = undefined; inline for (fields) |field, i| { args_ptrs[i] = @ptrToInt(&@field(args, field.name)); } const res = cu.cuLaunchKernel( f, grid.blocks.x, grid.blocks.y, grid.blocks.z, grid.threads.x, grid.threads.y, grid.threads.z, @intCast(c_uint, shared_mem), self._stream, @ptrCast([*c]?*anyopaque, &args_ptrs), null, ); try check(res); // TODO use callback API to keep the asynchronous scheduling } pub fn synchronize(self: *const Stream) void { check(cu.cuStreamSynchronize(self._stream)) catch unreachable; } pub fn format( self: *const Stream, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = fmt; _ = options; try std.fmt.format(writer, "CuStream(device={}, stream={*})", .{ self.device, self._stream }); } // TODO: I'd like to have an async method that suspends until the stream is over. // Currently the best way too achieve something like this is to `suspend {} stream.synchronize();` // once the stream is scheduled, and then `resume` once you are ready to wait // for the blocking `synchronize` call. // Ideally we would have an event loop that poll streams to check // if they are over. pub fn done(self: *Stream) bool { const res = cu.cuStreamQuery(self._stream); return res != cu.CUDA_ERROR_NOT_READY; } }; // TODO: return a device pointer pub fn alloc(comptime DestType: type, size: usize) ![]DestType { var int_ptr: cu.CUdeviceptr = undefined; const byte_size = size * @sizeOf(DestType); check(cu.cuMemAlloc(&int_ptr, byte_size)) catch |err| { switch (err) { error.OutOfMemory => { var free_mem: usize = undefined; var total_mem: usize = undefined; const mb = 1024 * 1024; check(cu.cuMemGetInfo(&free_mem, &total_mem)) catch return err; log.err( "Cuda OutOfMemory: tried to allocate {d:.1}Mb, free {d:.1}Mb, total {d:.1}Mb", .{ byte_size / mb, free_mem / mb, total_mem / mb }, ); return err; }, else => unreachable, } }; var ptr = @intToPtr([*]DestType, int_ptr); return ptr[0..size]; } // TODO: move all this to stream using async variants pub fn free(device_ptr: anytype) void { var raw_ptr: *anyopaque = if (meta.trait.isSlice(@TypeOf(device_ptr))) @ptrCast(*anyopaque, device_ptr.ptr) else @ptrCast(*anyopaque, device_ptr); _ = cu.cuMemFree(@ptrToInt(raw_ptr)); } pub fn memset(comptime DestType: type, slice: []DestType, value: DestType) !void { var d_ptr = @ptrToInt(slice.ptr); var n = slice.len; var memset_res = switch (@sizeOf(DestType)) { 1 => cu.cuMemsetD8(d_ptr, @bitCast(u8, value), n), 2 => cu.cuMemsetD16(d_ptr, @bitCast(u16, value), n), 4 => cu.cuMemsetD32(d_ptr, @bitCast(u32, value), n), else => @compileError("memset doesn't support type: " ++ @typeName(DestType)), }; try check(memset_res); } pub fn memsetD8(comptime DestType: type, slice: []DestType, value: u8) !void { var d_ptr = @ptrToInt(slice.ptr); var n = slice.len * @sizeOf(DestType); try check(cu.cuMemsetD8(d_ptr, value, n)); } pub fn allocAndCopy(comptime DestType: type, h_source: []const DestType) ![]DestType { var ptr = try alloc(DestType, h_source.len); try memcpyHtoD(DestType, ptr, h_source); return ptr; } pub fn allocAndCopyResult( comptime DestType: type, host_allocator: std.mem.Allocator, d_source: []const DestType, ) ![]DestType { var h_tgt = try host_allocator.alloc(DestType, d_source.len); try memcpyDtoH(DestType, h_tgt, d_source); return h_tgt; } pub fn readResult(comptime DestType: type, d_source: *const DestType) !DestType { var h_res: [1]DestType = undefined; try check(cu.cuMemcpyDtoH( @ptrCast(*anyopaque, &h_res), @ptrToInt(d_source), @sizeOf(DestType), )); return h_res[0]; } pub fn memcpyHtoD(comptime DestType: type, d_target: []DestType, h_source: []const DestType) !void { std.debug.assert(h_source.len == d_target.len); try check(cu.cuMemcpyHtoD( @ptrToInt(d_target.ptr), @ptrCast(*const anyopaque, h_source.ptr), h_source.len * @sizeOf(DestType), )); } pub fn memcpyDtoH(comptime DestType: type, h_target: []DestType, d_source: []const DestType) !void { std.debug.assert(d_source.len == h_target.len); try check(cu.cuMemcpyDtoH( @ptrCast(*anyopaque, h_target.ptr), @ptrToInt(d_source.ptr), d_source.len * @sizeOf(DestType), )); } pub fn push(value: anytype) !*@TypeOf(value) { const DestType = @TypeOf(value); var d_ptr = try alloc(DestType, 1); try check(cu.cuMemcpyHtoD( @ptrToInt(d_ptr.ptr), @ptrCast(*const anyopaque, &value), @sizeOf(DestType), )); return @ptrCast(*DestType, d_ptr.ptr); } /// Time gpu event. /// `deinit` is called when `elapsed` is called. /// Note: we don't check errors, you'll receive Nan if any error happens. /// start and stop are asynchronous, only elapsed is blocking and will wait /// for the underlying operations to be over. pub const GpuTimer = struct { _start: cu.CUevent, _stop: cu.CUevent, // Here we take a pointer to the Zig struct. // This way we can detect if we try to use a timer on a deleted stream stream: *const Stream, _elapsed: f32 = std.math.nan_f32, pub fn start(stream: *const Stream) GpuTimer { // The cuEvent are implicitly reffering to the current context. // We don't know if the current context is the same than the stream context. // Typically I'm not sure what happens with 2 streams on 2 gpus. // We might need to restore the stream context before creating the events. var timer = GpuTimer{ ._start = undefined, ._stop = undefined, .stream = stream }; _ = cu.cuEventCreate(&timer._start, 0); _ = cu.cuEventCreate(&timer._stop, 0); _ = cu.cuEventRecord(timer._start, stream._stream); return timer; } pub fn deinit(self: *GpuTimer) void { // Double deinit is allowed if (self._stop == null) return; _ = cu.cuEventDestroy(self._start); self._start = null; _ = cu.cuEventDestroy(self._stop); self._stop = null; } pub fn stop(self: *GpuTimer) void { _ = cu.cuEventRecord(self._stop, self.stream._stream); } /// Return the elapsed time in milliseconds. /// Resolution is around 0.5 microseconds. pub fn elapsed(self: *GpuTimer) f32 { if (!std.math.isNan(self._elapsed)) return self._elapsed; var _elapsed = std.math.nan_f32; // _ = cu.cuEventSynchronize(self._stop); _ = cu.cuEventElapsedTime(&_elapsed, self._start, self._stop); self.deinit(); self._elapsed = _elapsed; if (_elapsed < 1e-3) log.warn("Cuda events only have 0.5 microseconds of resolution, so this might not be precise", .{}); return _elapsed; } }; pub fn main() anyerror!void { var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = &general_purpose_allocator.allocator; const args = try std.process.argsAlloc(gpa); defer std.process.argsFree(gpa, args); log.info("All your codebase are belong to us.", .{}); log.info("cuda: {}", .{cu.cuInit}); log.info("cuInit: {}", .{cu.cuInit(0)}); } test "cuda version" { log.warn("Cuda version: {d}", .{cu.CUDA_VERSION}); try testing.expect(cu.CUDA_VERSION > 11000); try testing.expectEqual(cu.cuInit(0), cu.CUDA_SUCCESS); } var _device = [_]cu.CUdevice{-1} ** 8; pub fn initDevice(device: u3) !cu.CUdevice { var cu_dev = &_device[device]; if (cu_dev.* == -1) { try check(cu.cuInit(0)); try check(cu.cuDeviceGet(cu_dev, device)); } return cu_dev.*; } /// Returns the ctx for the given device /// Given that we already assume one program == one module, /// we can also assume one program == one context per GPU. /// From Nvidia doc: /// A host thread may have only one device context current at a time. // TODO: who is responsible for destroying the context ? // we should use cuCtxAttach and cuCtxDetach in stream init/deinit var _ctx = [1]cu.CUcontext{null} ** 8; fn getCtx(device: u3, cu_dev: cu.CUdevice) !cu.CUcontext { var cu_ctx = &_ctx[device]; if (cu_ctx.* == null) { try check(cu.cuCtxCreate(cu_ctx, 0, cu_dev)); } return cu_ctx.*; } var _default_module: cu.CUmodule = null; pub const kernel_ptx_content = if (cudaz_options.portable) @embedFile(cudaz_options.kernel_ptx_path) else [0:0]u8{}; fn defaultModule() cu.CUmodule { if (_default_module != null) return _default_module; const file = cudaz_options.kernel_ptx_path; if (kernel_ptx_content.len == 0) { log.warn("Loading Cuda module from local file {s}", .{file}); // Note: I tried to make this a path relative to the executable but failed because // the main executable and the test executable are in different folder // but refer to the same .ptx file. check(cu.cuModuleLoad(&_default_module, @ptrCast([*c]const u8, file))) catch |err| { std.debug.panic("Couldn't load cuda module: {s}: {}", .{ file, err }); }; } else { log.info("Loading Cuda module from embedded file.", .{}); // TODO see if we can use nvPTXCompiler to explicitly compile it ourselve check(cu.cuModuleLoadData(&_default_module, kernel_ptx_content)) catch |err| { std.debug.panic("Couldn't load embedded cuda module. Originally file was at {s}: {}", .{ file, err }); }; } if (_default_module == null) { std.debug.panic("Couldn't find module.", .{}); } return _default_module; } /// Create a function with the correct signature for a cuda Kernel. /// The kernel must come from the default .cu file pub inline fn CudaKernel(comptime name: [:0]const u8) type { return FnStruct(name, @field(cu, name)); } pub inline fn ZigKernel(comptime Module: anytype, comptime name: [:0]const u8) type { return FnStruct(name, @field(Module, name)); } pub fn FnStruct(comptime name: []const u8, comptime func: anytype) type { return struct { const Self = @This(); const CpuFn = *const @TypeOf(func); pub const Args = meta.ArgsTuple(meta.Child(Self.CpuFn)); f: cu.CUfunction, pub fn init() !Self { var f: cu.CUfunction = undefined; var code = cu.cuModuleGetFunction(&f, defaultModule(), @ptrCast([*c]const u8, name)); if (code != cu.CUDA_SUCCESS) log.err("Couldn't load function {s}", .{name}); try check(code); var res = Self{ .f = f }; return res; } // TODO: deinit -> CUDestroy // Note: I'm not fond of having the primary launch be on the Function object, // but it works best with Zig type inference pub inline fn launch(self: *const Self, stream: *const Stream, grid: Grid, args: Args) !void { if (args.len != @typeInfo(Args).Struct.fields.len) { @compileError("Expected more arguments"); } try self.launchWithSharedMem(stream, grid, 0, args); } pub fn launchWithSharedMem(self: *const Self, stream: *const Stream, grid: Grid, shared_mem: usize, args: Args) !void { // TODO: this seems error prone, could we make the type of the shared buffer // part of the function signature ? try stream.launchWithSharedMem(self.f, grid, shared_mem, args); } // pub fn debugCpuCall(grid: Grid, point: Grid, args: Args) void { // cu.threadIdx = point.threads.dim3(); // cu.blockDim = grid.threads.dim3(); // cu.blockIdx = point.blocks.dim3(); // cu.gridDim = grid.blocks.dim3(); // _ = @call(.{}, CpuFn, args); // } pub fn format( self: *const Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = self; _ = fmt; _ = options; try std.fmt.format(writer, "{s}(", .{name}); inline for (@typeInfo(Args).Struct.fields) |arg| { const ArgT = arg.field_type; try std.fmt.format(writer, "{}, ", .{ArgT}); } try std.fmt.format(writer, ")", .{}); } }; } test "can read function signature from .cu files" { log.warn("My kernel: {s}", .{@TypeOf(cu.rgba_to_greyscale)}); } test "we use only one context per GPU" { var default_ctx: cu.CUcontext = undefined; try check(cu.cuCtxGetCurrent(&default_ctx)); std.log.warn("default_ctx: {any}", .{std.mem.asBytes(&default_ctx).*}); var stream = try Stream.init(0); var stream_ctx: cu.CUcontext = undefined; try check(cu.cuStreamGetCtx(stream._stream, &stream_ctx)); std.log.warn("stream_ctx: {any}", .{std.mem.asBytes(&stream_ctx).*}); // try testing.expectEqual(default_ctx, stream_ctx); // Create a new stream var stream2 = try Stream.init(0); var stream2_ctx: cu.CUcontext = undefined; try check(cu.cuStreamGetCtx(stream2._stream, &stream2_ctx)); std.log.warn("stream2_ctx: {any}", .{std.mem.asBytes(&stream2_ctx).*}); try testing.expectEqual(stream_ctx, stream2_ctx); } test "rgba_to_greyscale" { var stream = try Stream.init(0); defer stream.deinit(); log.warn("cuda: {}", .{stream}); const rgba_to_greyscale = try CudaKernel("rgba_to_greyscale").init(); const numRows: u32 = 10; const numCols: u32 = 20; const d_rgbaImage = try alloc([4]u8, numRows * numCols); // try memset([4]u8, d_rgbaImage, [4]u8{ 0xaa, 0, 0, 255 }); const d_greyImage = try alloc(u8, numRows * numCols); try memset(u8, d_greyImage, 0); try stream.launch( rgba_to_greyscale.f, .{ .blocks = Dim3.init(numRows, numCols, 1) }, .{ d_rgbaImage, d_greyImage, numRows, numCols }, ); stream.synchronize(); } test "safe kernel" { const rgba_to_greyscale = try CudaKernel("rgba_to_greyscale").init(); var stream = try Stream.init(0); defer stream.deinit(); const numRows: u32 = 10; const numCols: u32 = 20; var d_rgbaImage = try alloc(cu.uchar3, numRows * numCols); // memset(cu.uchar3, d_rgbaImage, 0xaa); const d_greyImage = try alloc(u8, numRows * numCols); try memset(u8, d_greyImage, 0); stream.synchronize(); log.warn("stream: {}, fn: {}", .{ stream, rgba_to_greyscale.f }); try rgba_to_greyscale.launch( &stream, .{ .blocks = Dim3.init(numCols, numRows, 1) }, // TODO: we should accept slices .{ d_rgbaImage.ptr, d_greyImage.ptr, numRows, numCols }, ); } test "cuda alloc" { var stream = try Stream.init(0); defer stream.deinit(); const d_greyImage = try alloc(u8, 128); try memset(u8, d_greyImage, 0); defer free(d_greyImage); } test "run the kernel on CPU" { // This isn't very ergonomic, but it's possible ! // Also ironically it can't run in parallel because of the usage of the // globals blockIdx and threadIdx. // I think it could be useful to detect out of bound errors that Cuda // tend to ignore. const rgba_to_greyscale = CudaKernel("rgba_to_greyscale"); const rgbImage = [_]cu.uchar3{ .{ .x = 0x2D, .y = 0x24, .z = 0x1F }, .{ .x = 0xEB, .y = 0x82, .z = 0x48 }, }; var gray = [_]u8{ 0, 0 }; rgba_to_greyscale.debugCpuCall( Grid.init1D(2, 1), .{ .blocks = Dim3.init(0, 0, 0), .threads = Dim3.init(0, 0, 0) }, .{ &rgbImage, &gray, 1, 2 }, ); rgba_to_greyscale.debugCpuCall( Grid.init1D(2, 1), .{ .blocks = Dim3.init(0, 0, 0), .threads = Dim3.init(1, 0, 0) }, .{ &rgbImage, &gray, 1, 2 }, ); try testing.expectEqual([_]u8{ 38, 154 }, gray); } test "GpuTimer" { const rgba_to_greyscale = try CudaKernel("rgba_to_greyscale").init(); var stream = try Stream.init(0); defer stream.deinit(); const numRows: u32 = 10; const numCols: u32 = 20; var d_rgbaImage = try alloc(cu.uchar3, numRows * numCols); // memset(cu.uchar3, d_rgbaImage, 0xaa); const d_greyImage = try alloc(u8, numRows * numCols); try memset(u8, d_greyImage, 0); log.warn("stream: {}, fn: {}", .{ stream, rgba_to_greyscale.f }); var timer = GpuTimer.start(&stream); try rgba_to_greyscale.launch( &stream, .{ .blocks = Dim3.init(numCols, numRows, 1) }, .{ d_rgbaImage.ptr, d_greyImage.ptr, numRows, numCols }, ); timer.stop(); stream.synchronize(); log.warn("rgba_to_greyscale took: {}", .{timer.elapsed()}); try testing.expect(timer.elapsed() > 0); } pub fn Kernels(comptime module: type) type { // @compileLog(@typeName(module)); const decls = @typeInfo(module).Struct.decls; var kernels: [decls.len]TypeInfo.StructField = undefined; comptime var kernels_count = 0; inline for (decls) |decl| { if (decl.data != .Fn or !decl.data.Fn.is_export) continue; kernels[kernels_count] = .{ .name = decl.name, .field_type = FnStruct(decl.name, decl.data.Fn.fn_type), .default_value = null, .is_comptime = false, .alignment = @alignOf(cu.CUfunction), }; kernels_count += 1; } // @compileLog(kernels_count); return @Type(TypeInfo{ .Struct = TypeInfo.Struct{ .is_tuple = false, .layout = .Auto, .decls = &[_]TypeInfo.Declaration{}, .fields = kernels[0..kernels_count], }, }); } pub fn loadKernels(comptime module: type) Kernels(module) { const KernelType = Kernels(module); var kernels: KernelType = undefined; inline for (std.meta.fields(KernelType)) |field| { @field(kernels, field.name) = field.field_type.init() catch unreachable; } return kernels; }
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/cuda_globals.h
// When compiling .cu files `nvcc` will automatically add some builtin types // and thread variables. // This headers aims to allow zig to also be able to compile .cu files. // The goal isn't to call the zig compiled cuda, but to have proper type // checking on the kernel function call. #include "builtin_types.h" #define __global__ // In cuda shared memory buffers are declared as extern array // But this confuses Zig, because it can't find the extern definition. // Declare them as pointers so that Zig doesn't try to find the size. #define SHARED(NAME, TYPE) extern TYPE *NAME; #define extern dim3 gridDim; dim3 blockIdx; dim3 blockDim; dim3 threadIdx; int atomicAdd(int* a, int b) {a += b;} int atomicMin(int* a, int b) { if (b < *a) *a = b; } int atomicMax(int* a, int b) { if (b > *a) *a = b; } void __syncthreads() {}
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/cuda_cimports.zig
const cudaz_options = @import("cudaz_options"); pub const cu = @cImport({ @cInclude("cuda.h"); @cInclude("cuda_globals.h"); if (cudaz_options.cuda_kernel) { @cInclude(cudaz_options.kernel_name); } }); // pub const kernels = if (cudaz_options.cuda_cimports) struct {} else @import(cudaz_options.kernel_name);
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/nvptx.zig
const std = @import("std"); const builtin = @import("builtin"); const CallingConvention = @import("std").builtin.CallingConvention; pub const is_nvptx = builtin.cpu.arch == .nvptx64; pub const Kernel = if (is_nvptx) CallingConvention.PtxKernel else CallingConvention.Win64; // Equivalent of Cuda's __syncthreads() /// Wait to all the threads in this block to reach this barrier /// before going on. pub inline fn syncThreads() void { // @"llvm.nvvm.barrier0"(); if (!is_nvptx) return; asm volatile ("bar.sync \t0;"); } // extern fn @"llvm.nvvm.barrier0"() void; // This doesn't seem to work. LLVM (called from Zig) crashes with a "Cannot select error" // pub inline fn threadDimX() usize { // return @intCast(usize, @"llvm.nvvm.read.ptx.sreg.ntid.x"()); // } // extern fn @"llvm.nvvm.read.ptx.sreg.ntid.x"() i32; pub fn threadIdX() usize { if (!is_nvptx) return 0; var tid = asm volatile ("mov.u32 \t%[r], %tid.x;" : [r] "=r" (-> u32), ); return @as(usize, tid); } pub fn blockDimX() usize { if (!is_nvptx) return 0; var ntid = asm volatile ("mov.u32 \t%[r], %ntid.x;" : [r] "=r" (-> u32), ); return @as(usize, ntid); } pub fn blockIdX() usize { if (!is_nvptx) return 0; var ctaid = asm volatile ("mov.u32 \t%[r], %ctaid.x;" : [r] "=r" (-> u32), ); return @as(usize, ctaid); } pub fn gridDimX() usize { if (!is_nvptx) return 0; var nctaid = asm volatile ("mov.u32 \t%[r], %nctaid.x;" : [r] "=r" (-> u32), ); return @as(usize, nctaid); } pub fn getIdX() usize { return threadIdX() + blockDimX() * blockIdX(); } /// threadId.y pub inline fn threadIdY() usize { var tid = asm volatile ("mov.u32 \t%[r], %tid.y;" : [r] "=r" (-> u32), ); return @intCast(usize, tid); } /// threadId.z pub inline fn threadIdZ() usize { var tid = asm volatile ("mov.u32 \t%[r], %tid.z;" : [r] "=r" (-> u32), ); return @intCast(usize, tid); } /// threadDim.y pub inline fn threadDimY() usize { var ntid = asm volatile ("mov.u32 \t%[r], %ntid.y;" : [r] "=r" (-> u32), ); return @intCast(usize, ntid); } /// threadDim.z pub inline fn threadDimZ() usize { var ntid = asm volatile ("mov.u32 \t%[r], %ntid.z;" : [r] "=r" (-> u32), ); return @intCast(usize, ntid); } /// gridId.y pub inline fn gridIdY() usize { var ctaid = asm volatile ("mov.u32 \t%[r], %ctaid.y;" : [r] "=r" (-> u32), ); return @intCast(usize, ctaid); } /// gridId.z pub inline fn gridIdZ() usize { var ctaid = asm volatile ("mov.u32 \t%[r], %ctaid.z;" : [r] "=r" (-> u32), ); return @intCast(usize, ctaid); } /// gridDim.y pub inline fn gridDimY() usize { var nctaid = asm volatile ("mov.u32 \t%[r], %nctaid.y;" : [r] "=r" (-> u32), ); return @intCast(usize, nctaid); } /// gridDim.z pub inline fn gridDimZ() usize { var nctaid = asm volatile ("mov.u32 \t%[r], %nctaid.z;" : [r] "=r" (-> u32), ); return @intCast(usize, nctaid); } const Dim2 = struct { x: usize, y: usize }; pub fn getId_2D() Dim2 { return Dim2{ .x = threadIdX() + blockDimX() * blockIdX(), .y = threadIdY() + threadDimY() * gridIdY(), }; } const Dim3 = struct { x: usize, y: usize, z: usize }; pub fn getId_3D() Dim3 { return Dim3{ .x = threadIdX() + blockDimX() * blockIdX(), .y = threadIdY() + threadDimY() * gridIdY(), .z = threadIdZ() + threadDimZ() * gridIdZ(), }; } // var panic_message_buffer: ?[]u8 = null; // pub export fn init_panic_message_buffer(buffer: []u8) callconv(Kernel) void { // panic_message_buffer = buffer; // } // if (!is_nvptx) @compileError("This panic handler is made for GPU"); pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn { _ = error_return_trace; _ = msg; asm volatile ("trap;"); // `unreachable` implictly calls panic recursively and confuses ptxas. unreachable; // `noreturn` crashes LLVM because "Basic Block in function 'nvptx.panic' does not have terminator!" // This seems to be a bad .ll generation // return asm volatile ("trap;" // : [r] "=r" (-> noreturn), // ); // while(true) fails to compile because of "LLVM ERROR: Symbol name with unsupported characters" // while(true){} } // if (panic_message_buffer) |*buffer| { // const len = std.math.min(msg.len, buffer.len); // std.mem.copy(u8, buffer.*.ptr[0..len], msg[0..len]); // TODO: this assumes nobody will try to write afterward, which I'm not sure // TODO: prevent all threads wirting in the same place // buffer.*.len = len; // } const message = "Hello World !\x00"; pub export fn _test_hello_world(out: []u8) callconv(Kernel) void { const i = getIdX(); if (i > message.len or i > out.len) return; syncThreads(); out[i] = message[i]; }
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/algorithms.zig
const std = @import("std"); const math = std.math; const cuda = @import("cuda.zig"); /// Wrapper algorithm for a reduce kernel like min, max, sum, ... /// Those kernels compute the reduce operator only for a block of data. /// We need several passes for the global minimun/maximum/sum. /// The block size is hardcoded to 1024 which is the max number of threads per block /// on modern NVidia GPUs. // TODO: copy tests from HW4 pub fn reduce( stream: *const cuda.Stream, operator: anytype, d_data: anytype, ) !std.meta.Elem(@TypeOf(d_data)) { const n_threads = 1024; const n1 = math.divCeil(usize, d_data.len, n_threads) catch unreachable; var n2 = math.divCeil(usize, n1, n_threads) catch unreachable; const DType = std.meta.Elem(@TypeOf(d_data)); const buffer = try stream.alloc(DType, n1 + n2); defer stream.free(buffer); var d_in = d_data; var d_out = buffer[0..n1]; var d_next = buffer[n1 .. n1 + n2]; while (d_in.len > 1) { try operator.launchWithSharedMem( stream, cuda.Grid.init1D(d_in.len, n_threads), n_threads * @sizeOf(DType), .{ d_in.ptr, d_out.ptr, @intCast(c_int, d_in.len) }, ); d_in = d_out; d_out = d_next; n2 = math.divCeil(usize, d_next.len, n_threads) catch unreachable; d_next = d_out[0..n2]; } return try cuda.readResult(DType, &d_in[0]); }
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/test_nvptx.zig
const std = @import("std"); const testing = std.testing; const cuda = @import("cudaz"); const nvptx = @import("nvptx.zig"); test "hello_world" { var stream = try cuda.Stream.init(0); defer stream.deinit(); var d_buffer = try cuda.alloc(u8, 20); defer cuda.free(d_buffer); const gpu_hello_world = try cuda.FnStruct("_test_hello_world", nvptx._test_hello_world).init(); try gpu_hello_world.launch(&stream, cuda.Grid.init1D(d_buffer.len, 0), .{d_buffer}); var h_buffer = try stream.allocAndCopyResult(u8, testing.allocator, d_buffer); defer testing.allocator.free(h_buffer); var expected = "Hello World !"; std.log.warn("{s}", .{h_buffer}); try testing.expectEqualSlices(u8, expected, h_buffer[0..expected.len]); }
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/allocator.zig
const std = @import("std"); const cuda = @import("cuda.zig"); const assert = std.debug.assert; const mem = std.mem; const Allocator = std.mem.Allocator; const log = std.log.scoped(.Cuda); /// This allocator takes the cuda allocator, wraps it, and provides an interface /// where you can allocate without freeing, and then free it all together. /// It also need a host allocator to store the node metadata. /// It is an adapation from std lib arena allocator, where create_node uses the host allocator /// Technically it works, but don't have all the convenient methods /// from the std.mem.Allocator API. See below for more explanation pub const ArenaAllocator = struct { nodes: std.ArrayList([]u8), end_index: usize = 0, const Node = []u8; pub fn init(host_allocator: Allocator) ArenaAllocator { return .{ .nodes = std.ArrayList([]u8).init(host_allocator) }; } pub fn deinit(self: *ArenaAllocator) void { for (self.nodes.items) |node| { // this has to occur before the free because the free frees node cuda.free(node); } self.nodes.deinit(); } fn createNode(self: *ArenaAllocator, prev_len: usize, minimum_size: usize) Allocator.Error!*Node { const big_enough_len = prev_len + minimum_size; const len = big_enough_len + big_enough_len / 2; const buf = cuda.alloc(u8, len) catch |err| switch (err) { error.OutOfMemory => cuda.alloc(u8, minimum_size) catch return error.OutOfMemory, else => unreachable, }; const buf_node = try self.nodes.addOne(); buf_node.* = buf; self.end_index = 0; return buf_node; } pub fn alloc(self: *ArenaAllocator, comptime T: type, n_items: usize) Allocator.Error![]T { const n = @sizeOf(T) * n_items; var num_nodes = self.nodes.items.len; var cur_node = if (num_nodes > 0) &self.nodes.items[num_nodes - 1] else try self.createNode(0, n); // this while loop should only execute twice var counter: u8 = 0; while (true) { const cur_buf = cur_node.*; const new_end_index = self.end_index + n; if (new_end_index <= cur_buf.len) { const result = cur_buf[self.end_index..new_end_index]; self.end_index = new_end_index; return result; } // Allocate more memory cur_node = try self.createNode(cur_buf.len, n); counter += 1; std.debug.assert(counter < 2); } } pub fn resizeFn(allocator: Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) Allocator.Error!usize { _ = buf_align; _ = len_align; _ = ret_addr; const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator); var num_nodes = self.nodes.items.len; var cur_node = if (num_nodes > 0) &self.nodes.items[num_nodes - 1] else return error.OutOfMemory; const cur_buf = cur_node.*[@sizeOf(Node)..]; if (@ptrToInt(cur_buf.ptr) + self.end_index != @ptrToInt(buf.ptr) + buf.len) { if (new_len > buf.len) return error.OutOfMemory; return new_len; } if (buf.len >= new_len) { self.end_index -= buf.len - new_len; return new_len; } else if (cur_buf.len - self.end_index >= new_len - buf.len) { self.end_index += new_len - buf.len; return new_len; } else { return error.OutOfMemory; } } }; // *** Tentative to create a standard allocator API using cuAlloc *** // This doesn't work because Allocator.zig from std will call @memset(undefined) // on the returned pointer which will segfault, because we're returning a device pointer. // https://github.com/ziglang/zig/issues/4298 want to make the @memset optional // But does it make sense to have an allocator that return GPU memory ? // Most function that want an allocator want to read/write the returned data. // I think we should only have this in GPU code. // TODO: we could create an allocator that map the memory to the host // this will likely make read/write much slower though // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA // fn cudaAllocMappedFn(allocator: Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) Allocator.Error![]u8 { // } // pub const cuda_allocator = &cuda_allocator_state; var cuda_allocator_state = Allocator{ .allocFn = cudaAllocFn, .resizeFn = cudaResizeFn, }; fn cudaAllocFn(allocator: Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) Allocator.Error![]u8 { _ = allocator; _ = ra; _ = ptr_align; _ = len_align; const x = cuda.alloc(u8, n) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { log.err("Cuda error while allocating memory: {}", .{err}); return error.OutOfMemory; }, }; @memset(x.ptr, undefined, x.len); log.warn("allocated {}b at {*}", .{ x.len, x.ptr }); return x; } fn cudaResizeFn(allocator: Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ra: usize) Allocator.Error!usize { _ = allocator; _ = ra; _ = buf_align; if (new_len == 0) { cuda.free(buf); return new_len; } if (new_len <= buf.len) { return std.mem.alignAllocLen(buf.len, new_len, len_align); } return error.OutOfMemory; } test "cuda_allocator" { _ = try cuda.Stream.init(0); const x = cuda.alloc(u8, 800) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { log.err("Cuda error while allocating memory: {}", .{err}); return error.OutOfMemory; }, }; log.warn("allocated {} bytes at {*}", .{ x.len, x.ptr }); @memset(x.ptr, undefined, x.len); // try std.heap.testAllocator(cuda_allocator); } test "nice error when OOM" { var stream = try cuda.Stream.init(0); defer stream.deinit(); var arena = ArenaAllocator.init(std.testing.allocator); var last_err: anyerror = blk: { while (true) { _ = arena.alloc(u8, 1024 * 1024) catch |err| break :blk err; } }; try std.testing.expectEqual(last_err, error.OutOfMemory); log.warn("Cleaning up cuda memory and reallocating", .{}); arena.deinit(); var buff = try cuda.alloc(u8, 1024 * 1024); defer cuda.free(buff); }
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/kernel.zig
// const ptx = @import("nvptx.zig"); const message = []u8{ 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33, 13, 10 }; export fn hello(out: []u8) void { const i = getId_1D(); if (i > message.len or i > out.len) return; // ptx.syncThreads(); out[i] = message[i]; } pub inline fn threadIdX() usize { var tid = asm volatile ("mov.u32 \t$0, %tid.x;" : [ret] "=r" (-> u32), ); return @intCast(usize, tid); } pub inline fn threadDimX() usize { var ntid = asm volatile ("mov.u32 \t$0, %ntid.x;" : [ret] "=r" (-> u32), ); return @intCast(usize, ntid); } pub inline fn gridIdX() usize { var ctaid = asm volatile ("mov.u32 \t$0, %ctaid.x;" : [ret] "=r" (-> u32), ); return @intCast(usize, ctaid); } pub inline fn getId_1D() usize { return threadIdX() + threadDimX() * gridIdX(); }
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/cuda_helpers.h
#include <stdbool.h> #define uchar unsigned char #define FLAT_ID_2D(threadIdx, blockIdx, blockDim) threadIdx + blockDim * blockIdx; #define ID_X threadIdx.x + blockDim.x * blockIdx.x #define ID_Y threadIdx.y + blockDim.y * blockIdx.y #define ID_Z threadIdx.z + blockDim.z * blockIdx.z #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y)) #define MAX(X, Y) (((X) > (Y)) ? (X) : (Y)) #define CLAMP(x, n) MIN(n - 1, MAX(0, x)) // Get the last valid thread id in this block // The last block often contains thread id that goes above the input size #define LAST_TID(n) (blockIdx.x == gridDim.x - 1) ? (n-1) % blockDim.x : blockDim.x - 1; #ifdef __cplusplus // This is only seen by nvcc, not by Zig // You must use this macro to declare shared buffers #define SHARED(NAME, TYPE) extern __shared__ TYPE NAME[]; #endif
0
repos/cudaz/cudaz
repos/cudaz/cudaz/src/cuda.h
/* * Copyright 1993-2018 NVIDIA Corporation. All rights reserved. * * NOTICE TO LICENSEE: * * This source code and/or documentation ("Licensed Deliverables") are * subject to NVIDIA intellectual property rights under U.S. and * international Copyright laws. * * These Licensed Deliverables contained herein is PROPRIETARY and * CONFIDENTIAL to NVIDIA and is being provided under the terms and * conditions of a form of NVIDIA software license agreement by and * between NVIDIA and Licensee ("License Agreement") or electronically * accepted by Licensee. Notwithstanding any terms or conditions to * the contrary in the License Agreement, reproduction or disclosure * of the Licensed Deliverables to any third party without the express * written consent of NVIDIA is prohibited. * * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THESE LICENSED DELIVERABLES. * * U.S. Government End Users. These Licensed Deliverables are a * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT * 1995), consisting of "commercial computer software" and "commercial * computer software documentation" as such terms are used in 48 * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government * only as a commercial end item. Consistent with 48 C.F.R.12.212 and * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all * U.S. Government End Users acquire the Licensed Deliverables with * only those rights set forth herein. * * Any use of the Licensed Deliverables in individual and commercial * software must include, in the user documentation and internal * comments to the code, the above Disclaimer and U.S. Government End * Users Notice. */ #ifndef __cuda_cuda_h__ #define __cuda_cuda_h__ #include <stdlib.h> #ifdef _MSC_VER typedef unsigned __int32 cuuint32_t; typedef unsigned __int64 cuuint64_t; #else #include <stdint.h> typedef uint32_t cuuint32_t; typedef uint64_t cuuint64_t; #endif #if defined(__CUDA_API_VERSION_INTERNAL) || defined(__DOXYGEN_ONLY__) || defined(CUDA_ENABLE_DEPRECATED) #define __CUDA_DEPRECATED #elif defined(_MSC_VER) #define __CUDA_DEPRECATED __declspec(deprecated) #elif defined(__GNUC__) #define __CUDA_DEPRECATED __attribute__((deprecated)) #else #define __CUDA_DEPRECATED #endif #if defined(CUDA_FORCE_API_VERSION) #error "CUDA_FORCE_API_VERSION is no longer supported." #endif #define cuDeviceTotalMem cuDeviceTotalMem_v2 #define cuCtxCreate cuCtxCreate_v2 #define cuCtxCreate_v3 cuCtxCreate_v3 #define cuModuleGetGlobal cuModuleGetGlobal_v2 #define cuMemGetInfo cuMemGetInfo_v2 #define cuMemAlloc cuMemAlloc_v2 #define cuMemAllocPitch cuMemAllocPitch_v2 #define cuMemFree cuMemFree_v2 #define cuMemGetAddressRange cuMemGetAddressRange_v2 #define cuMemAllocHost cuMemAllocHost_v2 #define cuMemHostGetDevicePointer cuMemHostGetDevicePointer_v2 #define cuMemcpyHtoD cuMemcpyHtoD_v2 #define cuMemcpyDtoH cuMemcpyDtoH_v2 #define cuMemcpyDtoD cuMemcpyDtoD_v2 #define cuMemcpyDtoA cuMemcpyDtoA_v2 #define cuMemcpyAtoD cuMemcpyAtoD_v2 #define cuMemcpyHtoA cuMemcpyHtoA_v2 #define cuMemcpyAtoH cuMemcpyAtoH_v2 #define cuMemcpyAtoA cuMemcpyAtoA_v2 #define cuMemcpyHtoAAsync cuMemcpyHtoAAsync_v2 #define cuMemcpyAtoHAsync cuMemcpyAtoHAsync_v2 #define cuMemcpy2D cuMemcpy2D_v2 #define cuMemcpy2DUnaligned cuMemcpy2DUnaligned_v2 #define cuMemcpy3D cuMemcpy3D_v2 #define cuMemcpyHtoDAsync cuMemcpyHtoDAsync_v2 #define cuMemcpyDtoHAsync cuMemcpyDtoHAsync_v2 #define cuMemcpyDtoDAsync cuMemcpyDtoDAsync_v2 #define cuMemcpy2DAsync cuMemcpy2DAsync_v2 #define cuMemcpy3DAsync cuMemcpy3DAsync_v2 #define cuMemsetD8 cuMemsetD8_v2 #define cuMemsetD16 cuMemsetD16_v2 #define cuMemsetD32 cuMemsetD32_v2 #define cuMemsetD2D8 cuMemsetD2D8_v2 #define cuMemsetD2D16 cuMemsetD2D16_v2 #define cuMemsetD2D32 cuMemsetD2D32_v2 #define cuArrayCreate cuArrayCreate_v2 #define cuArrayGetDescriptor cuArrayGetDescriptor_v2 #define cuArray3DCreate cuArray3DCreate_v2 #define cuArray3DGetDescriptor cuArray3DGetDescriptor_v2 #define cuTexRefSetAddress cuTexRefSetAddress_v2 #define cuTexRefGetAddress cuTexRefGetAddress_v2 #define cuGraphicsResourceGetMappedPointer cuGraphicsResourceGetMappedPointer_v2 #define cuCtxDestroy cuCtxDestroy_v2 #define cuCtxPopCurrent cuCtxPopCurrent_v2 #define cuCtxPushCurrent cuCtxPushCurrent_v2 #define cuStreamDestroy cuStreamDestroy_v2 #define cuEventDestroy cuEventDestroy_v2 #define cuTexRefSetAddress2D cuTexRefSetAddress2D_v3 #define cuLinkCreate cuLinkCreate_v2 #define cuLinkAddData cuLinkAddData_v2 #define cuLinkAddFile cuLinkAddFile_v2 #define cuMemHostRegister cuMemHostRegister_v2 #define cuGraphicsResourceSetMapFlags cuGraphicsResourceSetMapFlags_v2 #define cuStreamBeginCapture cuStreamBeginCapture_v2 #define cuDevicePrimaryCtxRelease cuDevicePrimaryCtxRelease_v2 #define cuDevicePrimaryCtxReset cuDevicePrimaryCtxReset_v2 #define cuDevicePrimaryCtxSetFlags cuDevicePrimaryCtxSetFlags_v2 #define cuDeviceGetUuid_v2 cuDeviceGetUuid_v2 #define cuIpcOpenMemHandle cuIpcOpenMemHandle_v2 #define cuGraphInstantiate cuGraphInstantiate_v2 #if defined(__CUDA_API_PER_THREAD_DEFAULT_STREAM) #define cuMemcpy cuMemcpy #define cuMemcpyAsync cuMemcpyAsync #define cuMemcpyPeer cuMemcpyPeer #define cuMemcpyPeerAsync cuMemcpyPeerAsync #define cuMemcpy3DPeer cuMemcpy3DPeer #define cuMemcpy3DPeerAsync cuMemcpy3DPeerAsync #define cuMemPrefetchAsync cuMemPrefetchAsync #define cuMemsetD8Async cuMemsetD8Async #define cuMemsetD16Async cuMemsetD16Async #define cuMemsetD32Async cuMemsetD32Async #define cuMemsetD2D8Async cuMemsetD2D8Async #define cuMemsetD2D16Async cuMemsetD2D16Async #define cuMemsetD2D32Async cuMemsetD2D32Async #define cuStreamGetPriority cuStreamGetPriority #define cuStreamGetFlags cuStreamGetFlags #define cuStreamGetCtx cuStreamGetCtx #define cuStreamWaitEvent cuStreamWaitEvent #define cuStreamEndCapture cuStreamEndCapture #define cuStreamIsCapturing cuStreamIsCapturing #define cuStreamGetCaptureInfo cuStreamGetCaptureInfo #define cuStreamGetCaptureInfo_v2 cuStreamGetCaptureInfo_v2 #define cuStreamUpdateCaptureDependencies cuStreamUpdateCaptureDependencies #define cuStreamAddCallback cuStreamAddCallback #define cuStreamAttachMemAsync cuStreamAttachMemAsync #define cuStreamQuery cuStreamQuery #define cuStreamSynchronize cuStreamSynchronize #define cuEventRecord cuEventRecord #define cuEventRecordWithFlags cuEventRecordWithFlags #define cuLaunchKernel cuLaunchKernel #define cuLaunchHostFunc cuLaunchHostFunc #define cuGraphicsMapResources cuGraphicsMapResources #define cuGraphicsUnmapResources cuGraphicsUnmapResources #define cuStreamWriteValue32 cuStreamWriteValue32 #define cuStreamWaitValue32 cuStreamWaitValue32 #define cuStreamWriteValue64 cuStreamWriteValue64 #define cuStreamWaitValue64 cuStreamWaitValue64 #define cuStreamBatchMemOp cuStreamBatchMemOp #define cuLaunchCooperativeKernel cuLaunchCooperativeKernel #define cuSignalExternalSemaphoresAsync cuSignalExternalSemaphoresAsync #define cuWaitExternalSemaphoresAsync cuWaitExternalSemaphoresAsync #define cuGraphUpload cuGraphUpload #define cuGraphLaunch cuGraphLaunch #define cuStreamCopyAttributes cuStreamCopyAttributes #define cuStreamGetAttribute cuStreamGetAttribute #define cuStreamSetAttribute cuStreamSetAttribute #define cuMemMapArrayAsync cuMemMapArrayAsync #define cuMemFreeAsync cuMemFreeAsync #define cuMemAllocAsync cuMemAllocAsync #define cuMemAllocFromPoolAsync cuMemAllocFromPoolAsync #endif /** * \file cuda.h * \brief Header file for the CUDA Toolkit application programming interface. * * \file cudaGL.h * \brief Header file for the OpenGL interoperability functions of the * low-level CUDA driver application programming interface. * * \file cudaD3D9.h * \brief Header file for the Direct3D 9 interoperability functions of the * low-level CUDA driver application programming interface. */ /** * \defgroup CUDA_TYPES Data types used by CUDA driver * @{ */ /** * CUDA API version number */ #define CUDA_VERSION 11060 #ifdef __cplusplus extern "C" { #endif /** * CUDA device pointer * CUdeviceptr is defined as an unsigned integer type whose size matches the size of a pointer on the target platform. */ #if defined(_WIN64) || defined(__LP64__) typedef unsigned long long CUdeviceptr_v2; #else typedef unsigned int CUdeviceptr_v2; #endif typedef CUdeviceptr_v2 CUdeviceptr; /**< CUDA device pointer */ typedef int CUdevice_v1; /**< CUDA device */ typedef CUdevice_v1 CUdevice; /**< CUDA device */ typedef struct CUctx_st *CUcontext; /**< CUDA context */ typedef struct CUmod_st *CUmodule; /**< CUDA module */ typedef struct CUfunc_st *CUfunction; /**< CUDA function */ typedef struct CUarray_st *CUarray; /**< CUDA array */ typedef struct CUmipmappedArray_st *CUmipmappedArray; /**< CUDA mipmapped array */ typedef struct CUtexref_st *CUtexref; /**< CUDA texture reference */ typedef struct CUsurfref_st *CUsurfref; /**< CUDA surface reference */ typedef struct CUevent_st *CUevent; /**< CUDA event */ typedef struct CUstream_st *CUstream; /**< CUDA stream */ typedef struct CUgraphicsResource_st *CUgraphicsResource; /**< CUDA graphics interop resource */ typedef unsigned long long CUtexObject_v1; /**< An opaque value that represents a CUDA texture object */ typedef CUtexObject_v1 CUtexObject; /**< An opaque value that represents a CUDA texture object */ typedef unsigned long long CUsurfObject_v1; /**< An opaque value that represents a CUDA surface object */ typedef CUsurfObject_v1 CUsurfObject; /**< An opaque value that represents a CUDA surface object */ typedef struct CUextMemory_st *CUexternalMemory; /**< CUDA external memory */ typedef struct CUextSemaphore_st *CUexternalSemaphore; /**< CUDA external semaphore */ typedef struct CUgraph_st *CUgraph; /**< CUDA graph */ typedef struct CUgraphNode_st *CUgraphNode; /**< CUDA graph node */ typedef struct CUgraphExec_st *CUgraphExec; /**< CUDA executable graph */ typedef struct CUmemPoolHandle_st *CUmemoryPool; /**< CUDA memory pool */ typedef struct CUuserObject_st *CUuserObject; /**< CUDA user object for graphs */ #ifndef CU_UUID_HAS_BEEN_DEFINED #define CU_UUID_HAS_BEEN_DEFINED typedef struct CUuuid_st { /**< CUDA definition of UUID */ char bytes[16]; } CUuuid; #endif /** * CUDA IPC handle size */ #define CU_IPC_HANDLE_SIZE 64 /** * CUDA IPC event handle */ typedef struct CUipcEventHandle_st { char reserved[CU_IPC_HANDLE_SIZE]; } CUipcEventHandle_v1; typedef CUipcEventHandle_v1 CUipcEventHandle; /** * CUDA IPC mem handle */ typedef struct CUipcMemHandle_st { char reserved[CU_IPC_HANDLE_SIZE]; } CUipcMemHandle_v1; typedef CUipcMemHandle_v1 CUipcMemHandle; /** * CUDA Ipc Mem Flags */ typedef enum CUipcMem_flags_enum { CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS = 0x1 /**< Automatically enable peer access between remote devices as needed */ } CUipcMem_flags; /** * CUDA Mem Attach Flags */ typedef enum CUmemAttach_flags_enum { CU_MEM_ATTACH_GLOBAL = 0x1, /**< Memory can be accessed by any stream on any device */ CU_MEM_ATTACH_HOST = 0x2, /**< Memory cannot be accessed by any stream on any device */ CU_MEM_ATTACH_SINGLE = 0x4 /**< Memory can only be accessed by a single stream on the associated device */ } CUmemAttach_flags; /** * Context creation flags */ typedef enum CUctx_flags_enum { CU_CTX_SCHED_AUTO = 0x00, /**< Automatic scheduling */ CU_CTX_SCHED_SPIN = 0x01, /**< Set spin as default scheduling */ CU_CTX_SCHED_YIELD = 0x02, /**< Set yield as default scheduling */ CU_CTX_SCHED_BLOCKING_SYNC = 0x04, /**< Set blocking synchronization as default scheduling */ CU_CTX_BLOCKING_SYNC = 0x04, /**< Set blocking synchronization as default scheduling * \deprecated This flag was deprecated as of CUDA 4.0 * and was replaced with ::CU_CTX_SCHED_BLOCKING_SYNC. */ CU_CTX_SCHED_MASK = 0x07, CU_CTX_MAP_HOST = 0x08, /**< \deprecated This flag was deprecated as of CUDA 11.0 * and it no longer has any effect. All contexts * as of CUDA 3.2 behave as though the flag is enabled. */ CU_CTX_LMEM_RESIZE_TO_MAX = 0x10, /**< Keep local memory allocation after launch */ CU_CTX_FLAGS_MASK = 0x1f } CUctx_flags; /** * Stream creation flags */ typedef enum CUstream_flags_enum { CU_STREAM_DEFAULT = 0x0, /**< Default stream flag */ CU_STREAM_NON_BLOCKING = 0x1 /**< Stream does not synchronize with stream 0 (the NULL stream) */ } CUstream_flags; /** * Legacy stream handle * * Stream handle that can be passed as a CUstream to use an implicit stream * with legacy synchronization behavior. * * See details of the \link_sync_behavior */ #define CU_STREAM_LEGACY ((CUstream)0x1) /** * Per-thread stream handle * * Stream handle that can be passed as a CUstream to use an implicit stream * with per-thread synchronization behavior. * * See details of the \link_sync_behavior */ #define CU_STREAM_PER_THREAD ((CUstream)0x2) /** * Event creation flags */ typedef enum CUevent_flags_enum { CU_EVENT_DEFAULT = 0x0, /**< Default event flag */ CU_EVENT_BLOCKING_SYNC = 0x1, /**< Event uses blocking synchronization */ CU_EVENT_DISABLE_TIMING = 0x2, /**< Event will not record timing data */ CU_EVENT_INTERPROCESS = 0x4 /**< Event is suitable for interprocess use. CU_EVENT_DISABLE_TIMING must be set */ } CUevent_flags; /** * Event record flags */ typedef enum CUevent_record_flags_enum { CU_EVENT_RECORD_DEFAULT = 0x0, /**< Default event record flag */ CU_EVENT_RECORD_EXTERNAL = 0x1 /**< When using stream capture, create an event record node * instead of the default behavior. This flag is invalid * when used outside of capture. */ } CUevent_record_flags; /** * Event wait flags */ typedef enum CUevent_wait_flags_enum { CU_EVENT_WAIT_DEFAULT = 0x0, /**< Default event wait flag */ CU_EVENT_WAIT_EXTERNAL = 0x1 /**< When using stream capture, create an event wait node * instead of the default behavior. This flag is invalid * when used outside of capture.*/ } CUevent_wait_flags; /** * Flags for ::cuStreamWaitValue32 and ::cuStreamWaitValue64 */ typedef enum CUstreamWaitValue_flags_enum { CU_STREAM_WAIT_VALUE_GEQ = 0x0, /**< Wait until (int32_t)(*addr - value) >= 0 (or int64_t for 64 bit values). Note this is a cyclic comparison which ignores wraparound. (Default behavior.) */ CU_STREAM_WAIT_VALUE_EQ = 0x1, /**< Wait until *addr == value. */ CU_STREAM_WAIT_VALUE_AND = 0x2, /**< Wait until (*addr & value) != 0. */ CU_STREAM_WAIT_VALUE_NOR = 0x3, /**< Wait until ~(*addr | value) != 0. Support for this operation can be queried with ::cuDeviceGetAttribute() and ::CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR.*/ CU_STREAM_WAIT_VALUE_FLUSH = 1<<30 /**< Follow the wait operation with a flush of outstanding remote writes. This means that, if a remote write operation is guaranteed to have reached the device before the wait can be satisfied, that write is guaranteed to be visible to downstream device work. The device is permitted to reorder remote writes internally. For example, this flag would be required if two remote writes arrive in a defined order, the wait is satisfied by the second write, and downstream work needs to observe the first write. Support for this operation is restricted to selected platforms and can be queried with ::CU_DEVICE_ATTRIBUTE_CAN_USE_WAIT_VALUE_FLUSH.*/ } CUstreamWaitValue_flags; /** * Flags for ::cuStreamWriteValue32 */ typedef enum CUstreamWriteValue_flags_enum { CU_STREAM_WRITE_VALUE_DEFAULT = 0x0, /**< Default behavior */ CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER = 0x1 /**< Permits the write to be reordered with writes which were issued before it, as a performance optimization. Normally, ::cuStreamWriteValue32 will provide a memory fence before the write, which has similar semantics to __threadfence_system() but is scoped to the stream rather than a CUDA thread. */ } CUstreamWriteValue_flags; /** * Operations for ::cuStreamBatchMemOp */ typedef enum CUstreamBatchMemOpType_enum { CU_STREAM_MEM_OP_WAIT_VALUE_32 = 1, /**< Represents a ::cuStreamWaitValue32 operation */ CU_STREAM_MEM_OP_WRITE_VALUE_32 = 2, /**< Represents a ::cuStreamWriteValue32 operation */ CU_STREAM_MEM_OP_WAIT_VALUE_64 = 4, /**< Represents a ::cuStreamWaitValue64 operation */ CU_STREAM_MEM_OP_WRITE_VALUE_64 = 5, /**< Represents a ::cuStreamWriteValue64 operation */ CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES = 3 /**< This has the same effect as ::CU_STREAM_WAIT_VALUE_FLUSH, but as a standalone operation. */ } CUstreamBatchMemOpType; /** * Per-operation parameters for ::cuStreamBatchMemOp */ typedef union CUstreamBatchMemOpParams_union { CUstreamBatchMemOpType operation; struct CUstreamMemOpWaitValueParams_st { CUstreamBatchMemOpType operation; CUdeviceptr address; union { cuuint32_t value; cuuint64_t value64; }; unsigned int flags; CUdeviceptr alias; /**< For driver internal use. Initial value is unimportant. */ } waitValue; struct CUstreamMemOpWriteValueParams_st { CUstreamBatchMemOpType operation; CUdeviceptr address; union { cuuint32_t value; cuuint64_t value64; }; unsigned int flags; CUdeviceptr alias; /**< For driver internal use. Initial value is unimportant. */ } writeValue; struct CUstreamMemOpFlushRemoteWritesParams_st { CUstreamBatchMemOpType operation; unsigned int flags; } flushRemoteWrites; cuuint64_t pad[6]; } CUstreamBatchMemOpParams_v1; typedef CUstreamBatchMemOpParams_v1 CUstreamBatchMemOpParams; /** * Occupancy calculator flag */ typedef enum CUoccupancy_flags_enum { CU_OCCUPANCY_DEFAULT = 0x0, /**< Default behavior */ CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE = 0x1 /**< Assume global caching is enabled and cannot be automatically turned off */ } CUoccupancy_flags; /** * Flags for ::cuStreamUpdateCaptureDependencies */ typedef enum CUstreamUpdateCaptureDependencies_flags_enum { CU_STREAM_ADD_CAPTURE_DEPENDENCIES = 0x0, /**< Add new nodes to the dependency set */ CU_STREAM_SET_CAPTURE_DEPENDENCIES = 0x1 /**< Replace the dependency set with the new nodes */ } CUstreamUpdateCaptureDependencies_flags; /** * Array formats */ typedef enum CUarray_format_enum { CU_AD_FORMAT_UNSIGNED_INT8 = 0x01, /**< Unsigned 8-bit integers */ CU_AD_FORMAT_UNSIGNED_INT16 = 0x02, /**< Unsigned 16-bit integers */ CU_AD_FORMAT_UNSIGNED_INT32 = 0x03, /**< Unsigned 32-bit integers */ CU_AD_FORMAT_SIGNED_INT8 = 0x08, /**< Signed 8-bit integers */ CU_AD_FORMAT_SIGNED_INT16 = 0x09, /**< Signed 16-bit integers */ CU_AD_FORMAT_SIGNED_INT32 = 0x0a, /**< Signed 32-bit integers */ CU_AD_FORMAT_HALF = 0x10, /**< 16-bit floating point */ CU_AD_FORMAT_FLOAT = 0x20, /**< 32-bit floating point */ CU_AD_FORMAT_NV12 = 0xb0, /**< 8-bit YUV planar format, with 4:2:0 sampling */ CU_AD_FORMAT_UNORM_INT8X1 = 0xc0, /**< 1 channel unsigned 8-bit normalized integer */ CU_AD_FORMAT_UNORM_INT8X2 = 0xc1, /**< 2 channel unsigned 8-bit normalized integer */ CU_AD_FORMAT_UNORM_INT8X4 = 0xc2, /**< 4 channel unsigned 8-bit normalized integer */ CU_AD_FORMAT_UNORM_INT16X1 = 0xc3, /**< 1 channel unsigned 16-bit normalized integer */ CU_AD_FORMAT_UNORM_INT16X2 = 0xc4, /**< 2 channel unsigned 16-bit normalized integer */ CU_AD_FORMAT_UNORM_INT16X4 = 0xc5, /**< 4 channel unsigned 16-bit normalized integer */ CU_AD_FORMAT_SNORM_INT8X1 = 0xc6, /**< 1 channel signed 8-bit normalized integer */ CU_AD_FORMAT_SNORM_INT8X2 = 0xc7, /**< 2 channel signed 8-bit normalized integer */ CU_AD_FORMAT_SNORM_INT8X4 = 0xc8, /**< 4 channel signed 8-bit normalized integer */ CU_AD_FORMAT_SNORM_INT16X1 = 0xc9, /**< 1 channel signed 16-bit normalized integer */ CU_AD_FORMAT_SNORM_INT16X2 = 0xca, /**< 2 channel signed 16-bit normalized integer */ CU_AD_FORMAT_SNORM_INT16X4 = 0xcb, /**< 4 channel signed 16-bit normalized integer */ CU_AD_FORMAT_BC1_UNORM = 0x91, /**< 4 channel unsigned normalized block-compressed (BC1 compression) format */ CU_AD_FORMAT_BC1_UNORM_SRGB = 0x92, /**< 4 channel unsigned normalized block-compressed (BC1 compression) format with sRGB encoding*/ CU_AD_FORMAT_BC2_UNORM = 0x93, /**< 4 channel unsigned normalized block-compressed (BC2 compression) format */ CU_AD_FORMAT_BC2_UNORM_SRGB = 0x94, /**< 4 channel unsigned normalized block-compressed (BC2 compression) format with sRGB encoding*/ CU_AD_FORMAT_BC3_UNORM = 0x95, /**< 4 channel unsigned normalized block-compressed (BC3 compression) format */ CU_AD_FORMAT_BC3_UNORM_SRGB = 0x96, /**< 4 channel unsigned normalized block-compressed (BC3 compression) format with sRGB encoding*/ CU_AD_FORMAT_BC4_UNORM = 0x97, /**< 1 channel unsigned normalized block-compressed (BC4 compression) format */ CU_AD_FORMAT_BC4_SNORM = 0x98, /**< 1 channel signed normalized block-compressed (BC4 compression) format */ CU_AD_FORMAT_BC5_UNORM = 0x99, /**< 2 channel unsigned normalized block-compressed (BC5 compression) format */ CU_AD_FORMAT_BC5_SNORM = 0x9a, /**< 2 channel signed normalized block-compressed (BC5 compression) format */ CU_AD_FORMAT_BC6H_UF16 = 0x9b, /**< 3 channel unsigned half-float block-compressed (BC6H compression) format */ CU_AD_FORMAT_BC6H_SF16 = 0x9c, /**< 3 channel signed half-float block-compressed (BC6H compression) format */ CU_AD_FORMAT_BC7_UNORM = 0x9d, /**< 4 channel unsigned normalized block-compressed (BC7 compression) format */ CU_AD_FORMAT_BC7_UNORM_SRGB = 0x9e /**< 4 channel unsigned normalized block-compressed (BC7 compression) format with sRGB encoding */ } CUarray_format; /** * Texture reference addressing modes */ typedef enum CUaddress_mode_enum { CU_TR_ADDRESS_MODE_WRAP = 0, /**< Wrapping address mode */ CU_TR_ADDRESS_MODE_CLAMP = 1, /**< Clamp to edge address mode */ CU_TR_ADDRESS_MODE_MIRROR = 2, /**< Mirror address mode */ CU_TR_ADDRESS_MODE_BORDER = 3 /**< Border address mode */ } CUaddress_mode; /** * Texture reference filtering modes */ typedef enum CUfilter_mode_enum { CU_TR_FILTER_MODE_POINT = 0, /**< Point filter mode */ CU_TR_FILTER_MODE_LINEAR = 1 /**< Linear filter mode */ } CUfilter_mode; /** * Device properties */ typedef enum CUdevice_attribute_enum { CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 1, /**< Maximum number of threads per block */ CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X = 2, /**< Maximum block dimension X */ CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y = 3, /**< Maximum block dimension Y */ CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z = 4, /**< Maximum block dimension Z */ CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = 5, /**< Maximum grid dimension X */ CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y = 6, /**< Maximum grid dimension Y */ CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z = 7, /**< Maximum grid dimension Z */ CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = 8, /**< Maximum shared memory available per block in bytes */ CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK = 8, /**< Deprecated, use CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK */ CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY = 9, /**< Memory available on device for __constant__ variables in a CUDA C kernel in bytes */ CU_DEVICE_ATTRIBUTE_WARP_SIZE = 10, /**< Warp size in threads */ CU_DEVICE_ATTRIBUTE_MAX_PITCH = 11, /**< Maximum pitch in bytes allowed by memory copies */ CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK = 12, /**< Maximum number of 32-bit registers available per block */ CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK = 12, /**< Deprecated, use CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK */ CU_DEVICE_ATTRIBUTE_CLOCK_RATE = 13, /**< Typical clock frequency in kilohertz */ CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT = 14, /**< Alignment requirement for textures */ CU_DEVICE_ATTRIBUTE_GPU_OVERLAP = 15, /**< Device can possibly copy memory and execute a kernel concurrently. Deprecated. Use instead CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT. */ CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = 16, /**< Number of multiprocessors on device */ CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT = 17, /**< Specifies whether there is a run time limit on kernels */ CU_DEVICE_ATTRIBUTE_INTEGRATED = 18, /**< Device is integrated with host memory */ CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY = 19, /**< Device can map host memory into CUDA address space */ CU_DEVICE_ATTRIBUTE_COMPUTE_MODE = 20, /**< Compute mode (See ::CUcomputemode for details) */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH = 21, /**< Maximum 1D texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH = 22, /**< Maximum 2D texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT = 23, /**< Maximum 2D texture height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH = 24, /**< Maximum 3D texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT = 25, /**< Maximum 3D texture height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH = 26, /**< Maximum 3D texture depth */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH = 27, /**< Maximum 2D layered texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT = 28, /**< Maximum 2D layered texture height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS = 29, /**< Maximum layers in a 2D layered texture */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH = 27, /**< Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT = 28, /**< Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES = 29, /**< Deprecated, use CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS */ CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT = 30, /**< Alignment requirement for surfaces */ CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS = 31, /**< Device can possibly execute multiple kernels concurrently */ CU_DEVICE_ATTRIBUTE_ECC_ENABLED = 32, /**< Device has ECC support enabled */ CU_DEVICE_ATTRIBUTE_PCI_BUS_ID = 33, /**< PCI bus ID of the device */ CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID = 34, /**< PCI device ID of the device */ CU_DEVICE_ATTRIBUTE_TCC_DRIVER = 35, /**< Device is using TCC driver model */ CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE = 36, /**< Peak memory clock frequency in kilohertz */ CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH = 37, /**< Global memory bus width in bits */ CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE = 38, /**< Size of L2 cache in bytes */ CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR = 39, /**< Maximum resident threads per multiprocessor */ CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT = 40, /**< Number of asynchronous engines */ CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING = 41, /**< Device shares a unified address space with the host */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH = 42, /**< Maximum 1D layered texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS = 43, /**< Maximum layers in a 1D layered texture */ CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER = 44, /**< Deprecated, do not use. */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH = 45, /**< Maximum 2D texture width if CUDA_ARRAY3D_TEXTURE_GATHER is set */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT = 46, /**< Maximum 2D texture height if CUDA_ARRAY3D_TEXTURE_GATHER is set */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE = 47, /**< Alternate maximum 3D texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE = 48, /**< Alternate maximum 3D texture height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE = 49, /**< Alternate maximum 3D texture depth */ CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID = 50, /**< PCI domain ID of the device */ CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT = 51, /**< Pitch alignment requirement for textures */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH = 52, /**< Maximum cubemap texture width/height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH = 53, /**< Maximum cubemap layered texture width/height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS = 54, /**< Maximum layers in a cubemap layered texture */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH = 55, /**< Maximum 1D surface width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH = 56, /**< Maximum 2D surface width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT = 57, /**< Maximum 2D surface height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH = 58, /**< Maximum 3D surface width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT = 59, /**< Maximum 3D surface height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH = 60, /**< Maximum 3D surface depth */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH = 61, /**< Maximum 1D layered surface width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS = 62, /**< Maximum layers in a 1D layered surface */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH = 63, /**< Maximum 2D layered surface width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT = 64, /**< Maximum 2D layered surface height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS = 65, /**< Maximum layers in a 2D layered surface */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH = 66, /**< Maximum cubemap surface width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH = 67, /**< Maximum cubemap layered surface width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS = 68, /**< Maximum layers in a cubemap layered surface */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH = 69, /**< Deprecated, do not use. Use cudaDeviceGetTexture1DLinearMaxWidth() or cuDeviceGetTexture1DLinearMaxWidth() instead. */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH = 70, /**< Maximum 2D linear texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT = 71, /**< Maximum 2D linear texture height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH = 72, /**< Maximum 2D linear texture pitch in bytes */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH = 73, /**< Maximum mipmapped 2D texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT = 74, /**< Maximum mipmapped 2D texture height */ CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75, /**< Major compute capability version number */ CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = 76, /**< Minor compute capability version number */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH = 77, /**< Maximum mipmapped 1D texture width */ CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED = 78, /**< Device supports stream priorities */ CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED = 79, /**< Device supports caching globals in L1 */ CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED = 80, /**< Device supports caching locals in L1 */ CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR = 81, /**< Maximum shared memory available per multiprocessor in bytes */ CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR = 82, /**< Maximum number of 32-bit registers available per multiprocessor */ CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY = 83, /**< Device can allocate managed memory on this system */ CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD = 84, /**< Device is on a multi-GPU board */ CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID = 85, /**< Unique id for a group of devices on the same multi-GPU board */ CU_DEVICE_ATTRIBUTE_HOST_NATIVE_ATOMIC_SUPPORTED = 86, /**< Link between the device and the host supports native atomic operations (this is a placeholder attribute, and is not supported on any current hardware)*/ CU_DEVICE_ATTRIBUTE_SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO = 87, /**< Ratio of single precision performance (in floating-point operations per second) to double precision performance */ CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS = 88, /**< Device supports coherently accessing pageable memory without calling cudaHostRegister on it */ CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS = 89, /**< Device can coherently access managed memory concurrently with the CPU */ CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED = 90, /**< Device supports compute preemption. */ CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM = 91, /**< Device can access host registered memory at the same virtual address as the CPU */ CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_MEM_OPS = 92, /**< ::cuStreamBatchMemOp and related APIs are supported. */ CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS = 93, /**< 64-bit operations are supported in ::cuStreamBatchMemOp and related APIs. */ CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR = 94, /**< ::CU_STREAM_WAIT_VALUE_NOR is supported. */ CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH = 95, /**< Device supports launching cooperative kernels via ::cuLaunchCooperativeKernel */ CU_DEVICE_ATTRIBUTE_COOPERATIVE_MULTI_DEVICE_LAUNCH = 96, /**< Deprecated, ::cuLaunchCooperativeKernelMultiDevice is deprecated. */ CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN = 97, /**< Maximum optin shared memory per block */ CU_DEVICE_ATTRIBUTE_CAN_FLUSH_REMOTE_WRITES = 98, /**< The ::CU_STREAM_WAIT_VALUE_FLUSH flag and the ::CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES MemOp are supported on the device. See \ref CUDA_MEMOP for additional details. */ CU_DEVICE_ATTRIBUTE_HOST_REGISTER_SUPPORTED = 99, /**< Device supports host memory registration via ::cudaHostRegister. */ CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES = 100, /**< Device accesses pageable memory via the host's page tables. */ CU_DEVICE_ATTRIBUTE_DIRECT_MANAGED_MEM_ACCESS_FROM_HOST = 101, /**< The host can directly access managed memory on the device without migration. */ CU_DEVICE_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED = 102, /**< Deprecated, Use CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED*/ CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED = 102, /**< Device supports virtual memory management APIs like ::cuMemAddressReserve, ::cuMemCreate, ::cuMemMap and related APIs */ CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR_SUPPORTED = 103, /**< Device supports exporting memory to a posix file descriptor with ::cuMemExportToShareableHandle, if requested via ::cuMemCreate */ CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_WIN32_HANDLE_SUPPORTED = 104, /**< Device supports exporting memory to a Win32 NT handle with ::cuMemExportToShareableHandle, if requested via ::cuMemCreate */ CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_WIN32_KMT_HANDLE_SUPPORTED = 105, /**< Device supports exporting memory to a Win32 KMT handle with ::cuMemExportToShareableHandle, if requested via ::cuMemCreate */ CU_DEVICE_ATTRIBUTE_MAX_BLOCKS_PER_MULTIPROCESSOR = 106, /**< Maximum number of blocks per multiprocessor */ CU_DEVICE_ATTRIBUTE_GENERIC_COMPRESSION_SUPPORTED = 107, /**< Device supports compression of memory */ CU_DEVICE_ATTRIBUTE_MAX_PERSISTING_L2_CACHE_SIZE = 108, /**< Maximum L2 persisting lines capacity setting in bytes. */ CU_DEVICE_ATTRIBUTE_MAX_ACCESS_POLICY_WINDOW_SIZE = 109, /**< Maximum value of CUaccessPolicyWindow::num_bytes. */ CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WITH_CUDA_VMM_SUPPORTED = 110, /**< Device supports specifying the GPUDirect RDMA flag with ::cuMemCreate */ CU_DEVICE_ATTRIBUTE_RESERVED_SHARED_MEMORY_PER_BLOCK = 111, /**< Shared memory reserved by CUDA driver per block in bytes */ CU_DEVICE_ATTRIBUTE_SPARSE_CUDA_ARRAY_SUPPORTED = 112, /**< Device supports sparse CUDA arrays and sparse CUDA mipmapped arrays */ CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED = 113, /**< Device supports using the ::cuMemHostRegister flag ::CU_MEMHOSTERGISTER_READ_ONLY to register memory that must be mapped as read-only to the GPU */ CU_DEVICE_ATTRIBUTE_TIMELINE_SEMAPHORE_INTEROP_SUPPORTED = 114, /**< External timeline semaphore interop is supported on the device */ CU_DEVICE_ATTRIBUTE_MEMORY_POOLS_SUPPORTED = 115, /**< Device supports using the ::cuMemAllocAsync and ::cuMemPool family of APIs */ CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_SUPPORTED = 116, /**< Device supports GPUDirect RDMA APIs, like nvidia_p2p_get_pages (see https://docs.nvidia.com/cuda/gpudirect-rdma for more information) */ CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_FLUSH_WRITES_OPTIONS = 117, /**< The returned attribute shall be interpreted as a bitmask, where the individual bits are described by the ::CUflushGPUDirectRDMAWritesOptions enum */ CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WRITES_ORDERING = 118, /**< GPUDirect RDMA writes to the device do not need to be flushed for consumers within the scope indicated by the returned attribute. See ::CUGPUDirectRDMAWritesOrdering for the numerical values returned here. */ CU_DEVICE_ATTRIBUTE_MEMPOOL_SUPPORTED_HANDLE_TYPES = 119, /**< Handle types supported with mempool based IPC */ CU_DEVICE_ATTRIBUTE_DEFERRED_MAPPING_CUDA_ARRAY_SUPPORTED = 121, /**< Device supports deferred mapping CUDA arrays and CUDA mipmapped arrays */ CU_DEVICE_ATTRIBUTE_MAX } CUdevice_attribute; /** * Legacy device properties */ typedef struct CUdevprop_st { int maxThreadsPerBlock; /**< Maximum number of threads per block */ int maxThreadsDim[3]; /**< Maximum size of each dimension of a block */ int maxGridSize[3]; /**< Maximum size of each dimension of a grid */ int sharedMemPerBlock; /**< Shared memory available per block in bytes */ int totalConstantMemory; /**< Constant memory available on device in bytes */ int SIMDWidth; /**< Warp size in threads */ int memPitch; /**< Maximum pitch in bytes allowed by memory copies */ int regsPerBlock; /**< 32-bit registers available per block */ int clockRate; /**< Clock frequency in kilohertz */ int textureAlign; /**< Alignment requirement for textures */ } CUdevprop_v1; typedef CUdevprop_v1 CUdevprop; /** * Pointer information */ typedef enum CUpointer_attribute_enum { CU_POINTER_ATTRIBUTE_CONTEXT = 1, /**< The ::CUcontext on which a pointer was allocated or registered */ CU_POINTER_ATTRIBUTE_MEMORY_TYPE = 2, /**< The ::CUmemorytype describing the physical location of a pointer */ CU_POINTER_ATTRIBUTE_DEVICE_POINTER = 3, /**< The address at which a pointer's memory may be accessed on the device */ CU_POINTER_ATTRIBUTE_HOST_POINTER = 4, /**< The address at which a pointer's memory may be accessed on the host */ CU_POINTER_ATTRIBUTE_P2P_TOKENS = 5, /**< A pair of tokens for use with the nv-p2p.h Linux kernel interface */ CU_POINTER_ATTRIBUTE_SYNC_MEMOPS = 6, /**< Synchronize every synchronous memory operation initiated on this region */ CU_POINTER_ATTRIBUTE_BUFFER_ID = 7, /**< A process-wide unique ID for an allocated memory region*/ CU_POINTER_ATTRIBUTE_IS_MANAGED = 8, /**< Indicates if the pointer points to managed memory */ CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL = 9, /**< A device ordinal of a device on which a pointer was allocated or registered */ CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE = 10, /**< 1 if this pointer maps to an allocation that is suitable for ::cudaIpcGetMemHandle, 0 otherwise **/ CU_POINTER_ATTRIBUTE_RANGE_START_ADDR = 11, /**< Starting address for this requested pointer */ CU_POINTER_ATTRIBUTE_RANGE_SIZE = 12, /**< Size of the address range for this requested pointer */ CU_POINTER_ATTRIBUTE_MAPPED = 13, /**< 1 if this pointer is in a valid address range that is mapped to a backing allocation, 0 otherwise **/ CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES = 14, /**< Bitmask of allowed ::CUmemAllocationHandleType for this allocation **/ CU_POINTER_ATTRIBUTE_IS_GPU_DIRECT_RDMA_CAPABLE = 15, /**< 1 if the memory this pointer is referencing can be used with the GPUDirect RDMA API **/ CU_POINTER_ATTRIBUTE_ACCESS_FLAGS = 16, /**< Returns the access flags the device associated with the current context has on the corresponding memory referenced by the pointer given */ CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE = 17 /**< Returns the mempool handle for the allocation if it was allocated from a mempool. Otherwise returns NULL. **/ } CUpointer_attribute; /** * Function properties */ typedef enum CUfunction_attribute_enum { /** * The maximum number of threads per block, beyond which a launch of the * function would fail. This number depends on both the function and the * device on which the function is currently loaded. */ CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 0, /** * The size in bytes of statically-allocated shared memory required by * this function. This does not include dynamically-allocated shared * memory requested by the user at runtime. */ CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES = 1, /** * The size in bytes of user-allocated constant memory required by this * function. */ CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES = 2, /** * The size in bytes of local memory used by each thread of this function. */ CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES = 3, /** * The number of registers used by each thread of this function. */ CU_FUNC_ATTRIBUTE_NUM_REGS = 4, /** * The PTX virtual architecture version for which the function was * compiled. This value is the major PTX version * 10 + the minor PTX * version, so a PTX version 1.3 function would return the value 13. * Note that this may return the undefined value of 0 for cubins * compiled prior to CUDA 3.0. */ CU_FUNC_ATTRIBUTE_PTX_VERSION = 5, /** * The binary architecture version for which the function was compiled. * This value is the major binary version * 10 + the minor binary version, * so a binary version 1.3 function would return the value 13. Note that * this will return a value of 10 for legacy cubins that do not have a * properly-encoded binary architecture version. */ CU_FUNC_ATTRIBUTE_BINARY_VERSION = 6, /** * The attribute to indicate whether the function has been compiled with * user specified option "-Xptxas --dlcm=ca" set . */ CU_FUNC_ATTRIBUTE_CACHE_MODE_CA = 7, /** * The maximum size in bytes of dynamically-allocated shared memory that can be used by * this function. If the user-specified dynamic shared memory size is larger than this * value, the launch will fail. * See ::cuFuncSetAttribute */ CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES = 8, /** * On devices where the L1 cache and shared memory use the same hardware resources, * this sets the shared memory carveout preference, in percent of the total shared memory. * Refer to ::CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR. * This is only a hint, and the driver can choose a different ratio if required to execute the function. * See ::cuFuncSetAttribute */ CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT = 9, CU_FUNC_ATTRIBUTE_MAX } CUfunction_attribute; /** * Function cache configurations */ typedef enum CUfunc_cache_enum { CU_FUNC_CACHE_PREFER_NONE = 0x00, /**< no preference for shared memory or L1 (default) */ CU_FUNC_CACHE_PREFER_SHARED = 0x01, /**< prefer larger shared memory and smaller L1 cache */ CU_FUNC_CACHE_PREFER_L1 = 0x02, /**< prefer larger L1 cache and smaller shared memory */ CU_FUNC_CACHE_PREFER_EQUAL = 0x03 /**< prefer equal sized L1 cache and shared memory */ } CUfunc_cache; /** * Shared memory configurations */ typedef enum CUsharedconfig_enum { CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE = 0x00, /**< set default shared memory bank size */ CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE = 0x01, /**< set shared memory bank width to four bytes */ CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE = 0x02 /**< set shared memory bank width to eight bytes */ } CUsharedconfig; /** * Shared memory carveout configurations. These may be passed to ::cuFuncSetAttribute */ typedef enum CUshared_carveout_enum { CU_SHAREDMEM_CARVEOUT_DEFAULT = -1, /**< No preference for shared memory or L1 (default) */ CU_SHAREDMEM_CARVEOUT_MAX_SHARED = 100, /**< Prefer maximum available shared memory, minimum L1 cache */ CU_SHAREDMEM_CARVEOUT_MAX_L1 = 0 /**< Prefer maximum available L1 cache, minimum shared memory */ } CUshared_carveout; /** * Memory types */ typedef enum CUmemorytype_enum { CU_MEMORYTYPE_HOST = 0x01, /**< Host memory */ CU_MEMORYTYPE_DEVICE = 0x02, /**< Device memory */ CU_MEMORYTYPE_ARRAY = 0x03, /**< Array memory */ CU_MEMORYTYPE_UNIFIED = 0x04 /**< Unified device or host memory */ } CUmemorytype; /** * Compute Modes */ typedef enum CUcomputemode_enum { CU_COMPUTEMODE_DEFAULT = 0, /**< Default compute mode (Multiple contexts allowed per device) */ CU_COMPUTEMODE_PROHIBITED = 2, /**< Compute-prohibited mode (No contexts can be created on this device at this time) */ CU_COMPUTEMODE_EXCLUSIVE_PROCESS = 3 /**< Compute-exclusive-process mode (Only one context used by a single process can be present on this device at a time) */ } CUcomputemode; /** * Memory advise values */ typedef enum CUmem_advise_enum { CU_MEM_ADVISE_SET_READ_MOSTLY = 1, /**< Data will mostly be read and only occassionally be written to */ CU_MEM_ADVISE_UNSET_READ_MOSTLY = 2, /**< Undo the effect of ::CU_MEM_ADVISE_SET_READ_MOSTLY */ CU_MEM_ADVISE_SET_PREFERRED_LOCATION = 3, /**< Set the preferred location for the data as the specified device */ CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION = 4, /**< Clear the preferred location for the data */ CU_MEM_ADVISE_SET_ACCESSED_BY = 5, /**< Data will be accessed by the specified device, so prevent page faults as much as possible */ CU_MEM_ADVISE_UNSET_ACCESSED_BY = 6 /**< Let the Unified Memory subsystem decide on the page faulting policy for the specified device */ } CUmem_advise; typedef enum CUmem_range_attribute_enum { CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY = 1, /**< Whether the range will mostly be read and only occassionally be written to */ CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION = 2, /**< The preferred location of the range */ CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY = 3, /**< Memory range has ::CU_MEM_ADVISE_SET_ACCESSED_BY set for specified device */ CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION = 4 /**< The last location to which the range was prefetched */ } CUmem_range_attribute; /** * Online compiler and linker options */ typedef enum CUjit_option_enum { /** * Max number of registers that a thread may use.\n * Option type: unsigned int\n * Applies to: compiler only */ CU_JIT_MAX_REGISTERS = 0, /** * IN: Specifies minimum number of threads per block to target compilation * for\n * OUT: Returns the number of threads the compiler actually targeted. * This restricts the resource utilization fo the compiler (e.g. max * registers) such that a block with the given number of threads should be * able to launch based on register limitations. Note, this option does not * currently take into account any other resource limitations, such as * shared memory utilization.\n * Cannot be combined with ::CU_JIT_TARGET.\n * Option type: unsigned int\n * Applies to: compiler only */ CU_JIT_THREADS_PER_BLOCK, /** * Overwrites the option value with the total wall clock time, in * milliseconds, spent in the compiler and linker\n * Option type: float\n * Applies to: compiler and linker */ CU_JIT_WALL_TIME, /** * Pointer to a buffer in which to print any log messages * that are informational in nature (the buffer size is specified via * option ::CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES)\n * Option type: char *\n * Applies to: compiler and linker */ CU_JIT_INFO_LOG_BUFFER, /** * IN: Log buffer size in bytes. Log messages will be capped at this size * (including null terminator)\n * OUT: Amount of log buffer filled with messages\n * Option type: unsigned int\n * Applies to: compiler and linker */ CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES, /** * Pointer to a buffer in which to print any log messages that * reflect errors (the buffer size is specified via option * ::CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES)\n * Option type: char *\n * Applies to: compiler and linker */ CU_JIT_ERROR_LOG_BUFFER, /** * IN: Log buffer size in bytes. Log messages will be capped at this size * (including null terminator)\n * OUT: Amount of log buffer filled with messages\n * Option type: unsigned int\n * Applies to: compiler and linker */ CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, /** * Level of optimizations to apply to generated code (0 - 4), with 4 * being the default and highest level of optimizations.\n * Option type: unsigned int\n * Applies to: compiler only */ CU_JIT_OPTIMIZATION_LEVEL, /** * No option value required. Determines the target based on the current * attached context (default)\n * Option type: No option value needed\n * Applies to: compiler and linker */ CU_JIT_TARGET_FROM_CUCONTEXT, /** * Target is chosen based on supplied ::CUjit_target. Cannot be * combined with ::CU_JIT_THREADS_PER_BLOCK.\n * Option type: unsigned int for enumerated type ::CUjit_target\n * Applies to: compiler and linker */ CU_JIT_TARGET, /** * Specifies choice of fallback strategy if matching cubin is not found. * Choice is based on supplied ::CUjit_fallback. This option cannot be * used with cuLink* APIs as the linker requires exact matches.\n * Option type: unsigned int for enumerated type ::CUjit_fallback\n * Applies to: compiler only */ CU_JIT_FALLBACK_STRATEGY, /** * Specifies whether to create debug information in output (-g) * (0: false, default)\n * Option type: int\n * Applies to: compiler and linker */ CU_JIT_GENERATE_DEBUG_INFO, /** * Generate verbose log messages (0: false, default)\n * Option type: int\n * Applies to: compiler and linker */ CU_JIT_LOG_VERBOSE, /** * Generate line number information (-lineinfo) (0: false, default)\n * Option type: int\n * Applies to: compiler only */ CU_JIT_GENERATE_LINE_INFO, /** * Specifies whether to enable caching explicitly (-dlcm) \n * Choice is based on supplied ::CUjit_cacheMode_enum.\n * Option type: unsigned int for enumerated type ::CUjit_cacheMode_enum\n * Applies to: compiler only */ CU_JIT_CACHE_MODE, /** * The below jit options are used for internal purposes only, in this version of CUDA */ CU_JIT_NEW_SM3X_OPT, CU_JIT_FAST_COMPILE, /** * Array of device symbol names that will be relocated to the corresponing * host addresses stored in ::CU_JIT_GLOBAL_SYMBOL_ADDRESSES.\n * Must contain ::CU_JIT_GLOBAL_SYMBOL_COUNT entries.\n * When loding a device module, driver will relocate all encountered * unresolved symbols to the host addresses.\n * It is only allowed to register symbols that correspond to unresolved * global variables.\n * It is illegal to register the same device symbol at multiple addresses.\n * Option type: const char **\n * Applies to: dynamic linker only */ CU_JIT_GLOBAL_SYMBOL_NAMES, /** * Array of host addresses that will be used to relocate corresponding * device symbols stored in ::CU_JIT_GLOBAL_SYMBOL_NAMES.\n * Must contain ::CU_JIT_GLOBAL_SYMBOL_COUNT entries.\n * Option type: void **\n * Applies to: dynamic linker only */ CU_JIT_GLOBAL_SYMBOL_ADDRESSES, /** * Number of entries in ::CU_JIT_GLOBAL_SYMBOL_NAMES and * ::CU_JIT_GLOBAL_SYMBOL_ADDRESSES arrays.\n * Option type: unsigned int\n * Applies to: dynamic linker only */ CU_JIT_GLOBAL_SYMBOL_COUNT, /** * Enable link-time optimization (-dlto) for device code (0: false, default).\n * This option is not supported on 32-bit platforms.\n * Option type: int\n * Applies to: compiler and linker */ CU_JIT_LTO, /** * Control single-precision denormals (-ftz) support (0: false, default). * 1 : flushes denormal values to zero * 0 : preserves denormal values * Option type: int\n * Applies to: link-time optimization specified with CU_JIT_LTO */ CU_JIT_FTZ, /** * Control single-precision floating-point division and reciprocals * (-prec-div) support (1: true, default). * 1 : Enables the IEEE round-to-nearest mode * 0 : Enables the fast approximation mode * Option type: int\n * Applies to: link-time optimization specified with CU_JIT_LTO */ CU_JIT_PREC_DIV, /** * Control single-precision floating-point square root * (-prec-sqrt) support (1: true, default). * 1 : Enables the IEEE round-to-nearest mode * 0 : Enables the fast approximation mode * Option type: int\n * Applies to: link-time optimization specified with CU_JIT_LTO */ CU_JIT_PREC_SQRT, /** * Enable/Disable the contraction of floating-point multiplies * and adds/subtracts into floating-point multiply-add (-fma) * operations (1: Enable, default; 0: Disable). * Option type: int\n * Applies to: link-time optimization specified with CU_JIT_LTO */ CU_JIT_FMA, CU_JIT_NUM_OPTIONS } CUjit_option; /** * Online compilation targets */ typedef enum CUjit_target_enum { CU_TARGET_COMPUTE_20 = 20, /**< Compute device class 2.0 */ CU_TARGET_COMPUTE_21 = 21, /**< Compute device class 2.1 */ CU_TARGET_COMPUTE_30 = 30, /**< Compute device class 3.0 */ CU_TARGET_COMPUTE_32 = 32, /**< Compute device class 3.2 */ CU_TARGET_COMPUTE_35 = 35, /**< Compute device class 3.5 */ CU_TARGET_COMPUTE_37 = 37, /**< Compute device class 3.7 */ CU_TARGET_COMPUTE_50 = 50, /**< Compute device class 5.0 */ CU_TARGET_COMPUTE_52 = 52, /**< Compute device class 5.2 */ CU_TARGET_COMPUTE_53 = 53, /**< Compute device class 5.3 */ CU_TARGET_COMPUTE_60 = 60, /**< Compute device class 6.0.*/ CU_TARGET_COMPUTE_61 = 61, /**< Compute device class 6.1.*/ CU_TARGET_COMPUTE_62 = 62, /**< Compute device class 6.2.*/ CU_TARGET_COMPUTE_70 = 70, /**< Compute device class 7.0.*/ CU_TARGET_COMPUTE_72 = 72, /**< Compute device class 7.2.*/ CU_TARGET_COMPUTE_75 = 75, /**< Compute device class 7.5.*/ CU_TARGET_COMPUTE_80 = 80, /**< Compute device class 8.0.*/ CU_TARGET_COMPUTE_86 = 86 /**< Compute device class 8.6.*/ } CUjit_target; /** * Cubin matching fallback strategies */ typedef enum CUjit_fallback_enum { CU_PREFER_PTX = 0, /**< Prefer to compile ptx if exact binary match not found */ CU_PREFER_BINARY /**< Prefer to fall back to compatible binary code if exact match not found */ } CUjit_fallback; /** * Caching modes for dlcm */ typedef enum CUjit_cacheMode_enum { CU_JIT_CACHE_OPTION_NONE = 0, /**< Compile with no -dlcm flag specified */ CU_JIT_CACHE_OPTION_CG, /**< Compile with L1 cache disabled */ CU_JIT_CACHE_OPTION_CA /**< Compile with L1 cache enabled */ } CUjit_cacheMode; /** * Device code formats */ typedef enum CUjitInputType_enum { /** * Compiled device-class-specific device code\n * Applicable options: none */ CU_JIT_INPUT_CUBIN = 0, /** * PTX source code\n * Applicable options: PTX compiler options */ CU_JIT_INPUT_PTX, /** * Bundle of multiple cubins and/or PTX of some device code\n * Applicable options: PTX compiler options, ::CU_JIT_FALLBACK_STRATEGY */ CU_JIT_INPUT_FATBINARY, /** * Host object with embedded device code\n * Applicable options: PTX compiler options, ::CU_JIT_FALLBACK_STRATEGY */ CU_JIT_INPUT_OBJECT, /** * Archive of host objects with embedded device code\n * Applicable options: PTX compiler options, ::CU_JIT_FALLBACK_STRATEGY */ CU_JIT_INPUT_LIBRARY, /** * High-level intermediate code for link-time optimization\n * Applicable options: NVVM compiler options, PTX compiler options */ CU_JIT_INPUT_NVVM, CU_JIT_NUM_INPUT_TYPES } CUjitInputType; typedef struct CUlinkState_st *CUlinkState; /** * Flags to register a graphics resource */ typedef enum CUgraphicsRegisterFlags_enum { CU_GRAPHICS_REGISTER_FLAGS_NONE = 0x00, CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY = 0x01, CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD = 0x02, CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST = 0x04, CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER = 0x08 } CUgraphicsRegisterFlags; /** * Flags for mapping and unmapping interop resources */ typedef enum CUgraphicsMapResourceFlags_enum { CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE = 0x00, CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY = 0x01, CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD = 0x02 } CUgraphicsMapResourceFlags; /** * Array indices for cube faces */ typedef enum CUarray_cubemap_face_enum { CU_CUBEMAP_FACE_POSITIVE_X = 0x00, /**< Positive X face of cubemap */ CU_CUBEMAP_FACE_NEGATIVE_X = 0x01, /**< Negative X face of cubemap */ CU_CUBEMAP_FACE_POSITIVE_Y = 0x02, /**< Positive Y face of cubemap */ CU_CUBEMAP_FACE_NEGATIVE_Y = 0x03, /**< Negative Y face of cubemap */ CU_CUBEMAP_FACE_POSITIVE_Z = 0x04, /**< Positive Z face of cubemap */ CU_CUBEMAP_FACE_NEGATIVE_Z = 0x05 /**< Negative Z face of cubemap */ } CUarray_cubemap_face; /** * Limits */ typedef enum CUlimit_enum { CU_LIMIT_STACK_SIZE = 0x00, /**< GPU thread stack size */ CU_LIMIT_PRINTF_FIFO_SIZE = 0x01, /**< GPU printf FIFO size */ CU_LIMIT_MALLOC_HEAP_SIZE = 0x02, /**< GPU malloc heap size */ CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH = 0x03, /**< GPU device runtime launch synchronize depth */ CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT = 0x04, /**< GPU device runtime pending launch count */ CU_LIMIT_MAX_L2_FETCH_GRANULARITY = 0x05, /**< A value between 0 and 128 that indicates the maximum fetch granularity of L2 (in Bytes). This is a hint */ CU_LIMIT_PERSISTING_L2_CACHE_SIZE = 0x06, /**< A size in bytes for L2 persisting lines cache size */ CU_LIMIT_MAX } CUlimit; /** * Resource types */ typedef enum CUresourcetype_enum { CU_RESOURCE_TYPE_ARRAY = 0x00, /**< Array resoure */ CU_RESOURCE_TYPE_MIPMAPPED_ARRAY = 0x01, /**< Mipmapped array resource */ CU_RESOURCE_TYPE_LINEAR = 0x02, /**< Linear resource */ CU_RESOURCE_TYPE_PITCH2D = 0x03 /**< Pitch 2D resource */ } CUresourcetype; #ifdef _WIN32 #define CUDA_CB __stdcall #else #define CUDA_CB #endif /** * CUDA host function * \param userData Argument value passed to the function */ typedef void (CUDA_CB *CUhostFn)(void *userData); /** * Specifies performance hint with ::CUaccessPolicyWindow for hitProp and missProp members. */ typedef enum CUaccessProperty_enum { CU_ACCESS_PROPERTY_NORMAL = 0, /**< Normal cache persistence. */ CU_ACCESS_PROPERTY_STREAMING = 1, /**< Streaming access is less likely to persit from cache. */ CU_ACCESS_PROPERTY_PERSISTING = 2 /**< Persisting access is more likely to persist in cache.*/ } CUaccessProperty; /** * Specifies an access policy for a window, a contiguous extent of memory * beginning at base_ptr and ending at base_ptr + num_bytes. * num_bytes is limited by CU_DEVICE_ATTRIBUTE_MAX_ACCESS_POLICY_WINDOW_SIZE. * Partition into many segments and assign segments such that: * sum of "hit segments" / window == approx. ratio. * sum of "miss segments" / window == approx 1-ratio. * Segments and ratio specifications are fitted to the capabilities of * the architecture. * Accesses in a hit segment apply the hitProp access policy. * Accesses in a miss segment apply the missProp access policy. */ typedef struct CUaccessPolicyWindow_st { void *base_ptr; /**< Starting address of the access policy window. CUDA driver may align it. */ size_t num_bytes; /**< Size in bytes of the window policy. CUDA driver may restrict the maximum size and alignment. */ float hitRatio; /**< hitRatio specifies percentage of lines assigned hitProp, rest are assigned missProp. */ CUaccessProperty hitProp; /**< ::CUaccessProperty set for hit. */ CUaccessProperty missProp; /**< ::CUaccessProperty set for miss. Must be either NORMAL or STREAMING */ } CUaccessPolicyWindow_v1; typedef CUaccessPolicyWindow_v1 CUaccessPolicyWindow; /** * GPU kernel node parameters */ typedef struct CUDA_KERNEL_NODE_PARAMS_st { CUfunction func; /**< Kernel to launch */ unsigned int gridDimX; /**< Width of grid in blocks */ unsigned int gridDimY; /**< Height of grid in blocks */ unsigned int gridDimZ; /**< Depth of grid in blocks */ unsigned int blockDimX; /**< X dimension of each thread block */ unsigned int blockDimY; /**< Y dimension of each thread block */ unsigned int blockDimZ; /**< Z dimension of each thread block */ unsigned int sharedMemBytes; /**< Dynamic shared-memory size per thread block in bytes */ void **kernelParams; /**< Array of pointers to kernel parameters */ void **extra; /**< Extra options */ } CUDA_KERNEL_NODE_PARAMS_v1; typedef CUDA_KERNEL_NODE_PARAMS_v1 CUDA_KERNEL_NODE_PARAMS; /** * Memset node parameters */ typedef struct CUDA_MEMSET_NODE_PARAMS_st { CUdeviceptr dst; /**< Destination device pointer */ size_t pitch; /**< Pitch of destination device pointer. Unused if height is 1 */ unsigned int value; /**< Value to be set */ unsigned int elementSize; /**< Size of each element in bytes. Must be 1, 2, or 4. */ size_t width; /**< Width of the row in elements */ size_t height; /**< Number of rows */ } CUDA_MEMSET_NODE_PARAMS_v1; typedef CUDA_MEMSET_NODE_PARAMS_v1 CUDA_MEMSET_NODE_PARAMS; /** * Host node parameters */ typedef struct CUDA_HOST_NODE_PARAMS_st { CUhostFn fn; /**< The function to call when the node executes */ void* userData; /**< Argument to pass to the function */ } CUDA_HOST_NODE_PARAMS_v1; typedef CUDA_HOST_NODE_PARAMS_v1 CUDA_HOST_NODE_PARAMS; /** * Graph node types */ typedef enum CUgraphNodeType_enum { CU_GRAPH_NODE_TYPE_KERNEL = 0, /**< GPU kernel node */ CU_GRAPH_NODE_TYPE_MEMCPY = 1, /**< Memcpy node */ CU_GRAPH_NODE_TYPE_MEMSET = 2, /**< Memset node */ CU_GRAPH_NODE_TYPE_HOST = 3, /**< Host (executable) node */ CU_GRAPH_NODE_TYPE_GRAPH = 4, /**< Node which executes an embedded graph */ CU_GRAPH_NODE_TYPE_EMPTY = 5, /**< Empty (no-op) node */ CU_GRAPH_NODE_TYPE_WAIT_EVENT = 6, /**< External event wait node */ CU_GRAPH_NODE_TYPE_EVENT_RECORD = 7, /**< External event record node */ CU_GRAPH_NODE_TYPE_EXT_SEMAS_SIGNAL = 8, /**< External semaphore signal node */ CU_GRAPH_NODE_TYPE_EXT_SEMAS_WAIT = 9, /**< External semaphore wait node */ CU_GRAPH_NODE_TYPE_MEM_ALLOC = 10,/**< Memory Allocation Node */ CU_GRAPH_NODE_TYPE_MEM_FREE = 11 /**< Memory Free Node */ } CUgraphNodeType; typedef enum CUsynchronizationPolicy_enum { CU_SYNC_POLICY_AUTO = 1, CU_SYNC_POLICY_SPIN = 2, CU_SYNC_POLICY_YIELD = 3, CU_SYNC_POLICY_BLOCKING_SYNC = 4 } CUsynchronizationPolicy; /** * Graph kernel node Attributes */ typedef enum CUkernelNodeAttrID_enum { CU_KERNEL_NODE_ATTRIBUTE_ACCESS_POLICY_WINDOW = 1, /**< Identifier for ::CUkernelNodeAttrValue::accessPolicyWindow. */ CU_KERNEL_NODE_ATTRIBUTE_COOPERATIVE = 2 /**< Allows a kernel node to be cooperative (see ::cuLaunchCooperativeKernel). */ } CUkernelNodeAttrID; /** * Graph kernel node attributes union, used with ::cuKernelNodeSetAttribute/::cuKernelNodeGetAttribute */ typedef union CUkernelNodeAttrValue_union { CUaccessPolicyWindow accessPolicyWindow; /**< Attribute ::CUaccessPolicyWindow. */ int cooperative; /**< Nonzero indicates a cooperative kernel (see ::cuLaunchCooperativeKernel). */ } CUkernelNodeAttrValue_v1; typedef CUkernelNodeAttrValue_v1 CUkernelNodeAttrValue; /** * Possible stream capture statuses returned by ::cuStreamIsCapturing */ typedef enum CUstreamCaptureStatus_enum { CU_STREAM_CAPTURE_STATUS_NONE = 0, /**< Stream is not capturing */ CU_STREAM_CAPTURE_STATUS_ACTIVE = 1, /**< Stream is actively capturing */ CU_STREAM_CAPTURE_STATUS_INVALIDATED = 2 /**< Stream is part of a capture sequence that has been invalidated, but not terminated */ } CUstreamCaptureStatus; /** * Possible modes for stream capture thread interactions. For more details see * ::cuStreamBeginCapture and ::cuThreadExchangeStreamCaptureMode */ typedef enum CUstreamCaptureMode_enum { CU_STREAM_CAPTURE_MODE_GLOBAL = 0, CU_STREAM_CAPTURE_MODE_THREAD_LOCAL = 1, CU_STREAM_CAPTURE_MODE_RELAXED = 2 } CUstreamCaptureMode; /** * Stream Attributes */ typedef enum CUstreamAttrID_enum { CU_STREAM_ATTRIBUTE_ACCESS_POLICY_WINDOW = 1, /**< Identifier for ::CUstreamAttrValue::accessPolicyWindow. */ CU_STREAM_ATTRIBUTE_SYNCHRONIZATION_POLICY = 3 /**< ::CUsynchronizationPolicy for work queued up in this stream */ } CUstreamAttrID; /** * Stream attributes union, used with ::cuStreamSetAttribute/::cuStreamGetAttribute */ typedef union CUstreamAttrValue_union { CUaccessPolicyWindow accessPolicyWindow; /**< Attribute ::CUaccessPolicyWindow. */ CUsynchronizationPolicy syncPolicy; /**< Value for ::CU_STREAM_ATTRIBUTE_SYNCHRONIZATION_POLICY. */ } CUstreamAttrValue_v1; typedef CUstreamAttrValue_v1 CUstreamAttrValue; /** * Flags to specify search options. For more details see ::cuGetProcAddress */ typedef enum CUdriverProcAddress_flags_enum { CU_GET_PROC_ADDRESS_DEFAULT = 0, /**< Default search mode for driver symbols. */ CU_GET_PROC_ADDRESS_LEGACY_STREAM = 1 << 0, /**< Search for legacy versions of driver symbols. */ CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM = 1 << 1 /**< Search for per-thread versions of driver symbols. */ } CUdriverProcAddress_flags; /** * Execution Affinity Types */ typedef enum CUexecAffinityType_enum { CU_EXEC_AFFINITY_TYPE_SM_COUNT = 0, /**< Create a context with limited SMs. */ CU_EXEC_AFFINITY_TYPE_MAX } CUexecAffinityType; /** * Value for ::CU_EXEC_AFFINITY_TYPE_SM_COUNT */ typedef struct CUexecAffinitySmCount_st { unsigned int val; /**< The number of SMs the context is limited to use. */ } CUexecAffinitySmCount_v1; typedef CUexecAffinitySmCount_v1 CUexecAffinitySmCount; /** * Execution Affinity Parameters */ typedef struct CUexecAffinityParam_st { CUexecAffinityType type; union { CUexecAffinitySmCount smCount; /** Value for ::CU_EXEC_AFFINITY_TYPE_SM_COUNT */ } param; } CUexecAffinityParam_v1; typedef CUexecAffinityParam_v1 CUexecAffinityParam; /** * Error codes */ typedef enum cudaError_enum { /** * The API call returned with no errors. In the case of query calls, this * also means that the operation being queried is complete (see * ::cuEventQuery() and ::cuStreamQuery()). */ CUDA_SUCCESS = 0, /** * This indicates that one or more of the parameters passed to the API call * is not within an acceptable range of values. */ CUDA_ERROR_INVALID_VALUE = 1, /** * The API call failed because it was unable to allocate enough memory to * perform the requested operation. */ CUDA_ERROR_OUT_OF_MEMORY = 2, /** * This indicates that the CUDA driver has not been initialized with * ::cuInit() or that initialization has failed. */ CUDA_ERROR_NOT_INITIALIZED = 3, /** * This indicates that the CUDA driver is in the process of shutting down. */ CUDA_ERROR_DEINITIALIZED = 4, /** * This indicates profiler is not initialized for this run. This can * happen when the application is running with external profiling tools * like visual profiler. */ CUDA_ERROR_PROFILER_DISABLED = 5, /** * \deprecated * This error return is deprecated as of CUDA 5.0. It is no longer an error * to attempt to enable/disable the profiling via ::cuProfilerStart or * ::cuProfilerStop without initialization. */ CUDA_ERROR_PROFILER_NOT_INITIALIZED = 6, /** * \deprecated * This error return is deprecated as of CUDA 5.0. It is no longer an error * to call cuProfilerStart() when profiling is already enabled. */ CUDA_ERROR_PROFILER_ALREADY_STARTED = 7, /** * \deprecated * This error return is deprecated as of CUDA 5.0. It is no longer an error * to call cuProfilerStop() when profiling is already disabled. */ CUDA_ERROR_PROFILER_ALREADY_STOPPED = 8, /** * This indicates that the CUDA driver that the application has loaded is a * stub library. Applications that run with the stub rather than a real * driver loaded will result in CUDA API returning this error. */ CUDA_ERROR_STUB_LIBRARY = 34, /** * This indicates that no CUDA-capable devices were detected by the installed * CUDA driver. */ CUDA_ERROR_NO_DEVICE = 100, /** * This indicates that the device ordinal supplied by the user does not * correspond to a valid CUDA device or that the action requested is * invalid for the specified device. */ CUDA_ERROR_INVALID_DEVICE = 101, /** * This error indicates that the Grid license is not applied. */ CUDA_ERROR_DEVICE_NOT_LICENSED = 102, /** * This indicates that the device kernel image is invalid. This can also * indicate an invalid CUDA module. */ CUDA_ERROR_INVALID_IMAGE = 200, /** * This most frequently indicates that there is no context bound to the * current thread. This can also be returned if the context passed to an * API call is not a valid handle (such as a context that has had * ::cuCtxDestroy() invoked on it). This can also be returned if a user * mixes different API versions (i.e. 3010 context with 3020 API calls). * See ::cuCtxGetApiVersion() for more details. */ CUDA_ERROR_INVALID_CONTEXT = 201, /** * This indicated that the context being supplied as a parameter to the * API call was already the active context. * \deprecated * This error return is deprecated as of CUDA 3.2. It is no longer an * error to attempt to push the active context via ::cuCtxPushCurrent(). */ CUDA_ERROR_CONTEXT_ALREADY_CURRENT = 202, /** * This indicates that a map or register operation has failed. */ CUDA_ERROR_MAP_FAILED = 205, /** * This indicates that an unmap or unregister operation has failed. */ CUDA_ERROR_UNMAP_FAILED = 206, /** * This indicates that the specified array is currently mapped and thus * cannot be destroyed. */ CUDA_ERROR_ARRAY_IS_MAPPED = 207, /** * This indicates that the resource is already mapped. */ CUDA_ERROR_ALREADY_MAPPED = 208, /** * This indicates that there is no kernel image available that is suitable * for the device. This can occur when a user specifies code generation * options for a particular CUDA source file that do not include the * corresponding device configuration. */ CUDA_ERROR_NO_BINARY_FOR_GPU = 209, /** * This indicates that a resource has already been acquired. */ CUDA_ERROR_ALREADY_ACQUIRED = 210, /** * This indicates that a resource is not mapped. */ CUDA_ERROR_NOT_MAPPED = 211, /** * This indicates that a mapped resource is not available for access as an * array. */ CUDA_ERROR_NOT_MAPPED_AS_ARRAY = 212, /** * This indicates that a mapped resource is not available for access as a * pointer. */ CUDA_ERROR_NOT_MAPPED_AS_POINTER = 213, /** * This indicates that an uncorrectable ECC error was detected during * execution. */ CUDA_ERROR_ECC_UNCORRECTABLE = 214, /** * This indicates that the ::CUlimit passed to the API call is not * supported by the active device. */ CUDA_ERROR_UNSUPPORTED_LIMIT = 215, /** * This indicates that the ::CUcontext passed to the API call can * only be bound to a single CPU thread at a time but is already * bound to a CPU thread. */ CUDA_ERROR_CONTEXT_ALREADY_IN_USE = 216, /** * This indicates that peer access is not supported across the given * devices. */ CUDA_ERROR_PEER_ACCESS_UNSUPPORTED = 217, /** * This indicates that a PTX JIT compilation failed. */ CUDA_ERROR_INVALID_PTX = 218, /** * This indicates an error with OpenGL or DirectX context. */ CUDA_ERROR_INVALID_GRAPHICS_CONTEXT = 219, /** * This indicates that an uncorrectable NVLink error was detected during the * execution. */ CUDA_ERROR_NVLINK_UNCORRECTABLE = 220, /** * This indicates that the PTX JIT compiler library was not found. */ CUDA_ERROR_JIT_COMPILER_NOT_FOUND = 221, /** * This indicates that the provided PTX was compiled with an unsupported toolchain. */ CUDA_ERROR_UNSUPPORTED_PTX_VERSION = 222, /** * This indicates that the PTX JIT compilation was disabled. */ CUDA_ERROR_JIT_COMPILATION_DISABLED = 223, /** * This indicates that the ::CUexecAffinityType passed to the API call is not * supported by the active device. */ CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY = 224, /** * This indicates that the device kernel source is invalid. This includes * compilation/linker errors encountered in device code or user error. */ CUDA_ERROR_INVALID_SOURCE = 300, /** * This indicates that the file specified was not found. */ CUDA_ERROR_FILE_NOT_FOUND = 301, /** * This indicates that a link to a shared object failed to resolve. */ CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND = 302, /** * This indicates that initialization of a shared object failed. */ CUDA_ERROR_SHARED_OBJECT_INIT_FAILED = 303, /** * This indicates that an OS call failed. */ CUDA_ERROR_OPERATING_SYSTEM = 304, /** * This indicates that a resource handle passed to the API call was not * valid. Resource handles are opaque types like ::CUstream and ::CUevent. */ CUDA_ERROR_INVALID_HANDLE = 400, /** * This indicates that a resource required by the API call is not in a * valid state to perform the requested operation. */ CUDA_ERROR_ILLEGAL_STATE = 401, /** * This indicates that a named symbol was not found. Examples of symbols * are global/constant variable names, driver function names, texture names, * and surface names. */ CUDA_ERROR_NOT_FOUND = 500, /** * This indicates that asynchronous operations issued previously have not * completed yet. This result is not actually an error, but must be indicated * differently than ::CUDA_SUCCESS (which indicates completion). Calls that * may return this value include ::cuEventQuery() and ::cuStreamQuery(). */ CUDA_ERROR_NOT_READY = 600, /** * While executing a kernel, the device encountered a * load or store instruction on an invalid memory address. * This leaves the process in an inconsistent state and any further CUDA work * will return the same error. To continue using CUDA, the process must be terminated * and relaunched. */ CUDA_ERROR_ILLEGAL_ADDRESS = 700, /** * This indicates that a launch did not occur because it did not have * appropriate resources. This error usually indicates that the user has * attempted to pass too many arguments to the device kernel, or the * kernel launch specifies too many threads for the kernel's register * count. Passing arguments of the wrong size (i.e. a 64-bit pointer * when a 32-bit int is expected) is equivalent to passing too many * arguments and can also result in this error. */ CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES = 701, /** * This indicates that the device kernel took too long to execute. This can * only occur if timeouts are enabled - see the device attribute * ::CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT for more information. * This leaves the process in an inconsistent state and any further CUDA work * will return the same error. To continue using CUDA, the process must be terminated * and relaunched. */ CUDA_ERROR_LAUNCH_TIMEOUT = 702, /** * This error indicates a kernel launch that uses an incompatible texturing * mode. */ CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING = 703, /** * This error indicates that a call to ::cuCtxEnablePeerAccess() is * trying to re-enable peer access to a context which has already * had peer access to it enabled. */ CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED = 704, /** * This error indicates that ::cuCtxDisablePeerAccess() is * trying to disable peer access which has not been enabled yet * via ::cuCtxEnablePeerAccess(). */ CUDA_ERROR_PEER_ACCESS_NOT_ENABLED = 705, /** * This error indicates that the primary context for the specified device * has already been initialized. */ CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE = 708, /** * This error indicates that the context current to the calling thread * has been destroyed using ::cuCtxDestroy, or is a primary context which * has not yet been initialized. */ CUDA_ERROR_CONTEXT_IS_DESTROYED = 709, /** * A device-side assert triggered during kernel execution. The context * cannot be used anymore, and must be destroyed. All existing device * memory allocations from this context are invalid and must be * reconstructed if the program is to continue using CUDA. */ CUDA_ERROR_ASSERT = 710, /** * This error indicates that the hardware resources required to enable * peer access have been exhausted for one or more of the devices * passed to ::cuCtxEnablePeerAccess(). */ CUDA_ERROR_TOO_MANY_PEERS = 711, /** * This error indicates that the memory range passed to ::cuMemHostRegister() * has already been registered. */ CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED = 712, /** * This error indicates that the pointer passed to ::cuMemHostUnregister() * does not correspond to any currently registered memory region. */ CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED = 713, /** * While executing a kernel, the device encountered a stack error. * This can be due to stack corruption or exceeding the stack size limit. * This leaves the process in an inconsistent state and any further CUDA work * will return the same error. To continue using CUDA, the process must be terminated * and relaunched. */ CUDA_ERROR_HARDWARE_STACK_ERROR = 714, /** * While executing a kernel, the device encountered an illegal instruction. * This leaves the process in an inconsistent state and any further CUDA work * will return the same error. To continue using CUDA, the process must be terminated * and relaunched. */ CUDA_ERROR_ILLEGAL_INSTRUCTION = 715, /** * While executing a kernel, the device encountered a load or store instruction * on a memory address which is not aligned. * This leaves the process in an inconsistent state and any further CUDA work * will return the same error. To continue using CUDA, the process must be terminated * and relaunched. */ CUDA_ERROR_MISALIGNED_ADDRESS = 716, /** * While executing a kernel, the device encountered an instruction * which can only operate on memory locations in certain address spaces * (global, shared, or local), but was supplied a memory address not * belonging to an allowed address space. * This leaves the process in an inconsistent state and any further CUDA work * will return the same error. To continue using CUDA, the process must be terminated * and relaunched. */ CUDA_ERROR_INVALID_ADDRESS_SPACE = 717, /** * While executing a kernel, the device program counter wrapped its address space. * This leaves the process in an inconsistent state and any further CUDA work * will return the same error. To continue using CUDA, the process must be terminated * and relaunched. */ CUDA_ERROR_INVALID_PC = 718, /** * An exception occurred on the device while executing a kernel. Common * causes include dereferencing an invalid device pointer and accessing * out of bounds shared memory. Less common cases can be system specific - more * information about these cases can be found in the system specific user guide. * This leaves the process in an inconsistent state and any further CUDA work * will return the same error. To continue using CUDA, the process must be terminated * and relaunched. */ CUDA_ERROR_LAUNCH_FAILED = 719, /** * This error indicates that the number of blocks launched per grid for a kernel that was * launched via either ::cuLaunchCooperativeKernel or ::cuLaunchCooperativeKernelMultiDevice * exceeds the maximum number of blocks as allowed by ::cuOccupancyMaxActiveBlocksPerMultiprocessor * or ::cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags times the number of multiprocessors * as specified by the device attribute ::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT. */ CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE = 720, /** * This error indicates that the attempted operation is not permitted. */ CUDA_ERROR_NOT_PERMITTED = 800, /** * This error indicates that the attempted operation is not supported * on the current system or device. */ CUDA_ERROR_NOT_SUPPORTED = 801, /** * This error indicates that the system is not yet ready to start any CUDA * work. To continue using CUDA, verify the system configuration is in a * valid state and all required driver daemons are actively running. * More information about this error can be found in the system specific * user guide. */ CUDA_ERROR_SYSTEM_NOT_READY = 802, /** * This error indicates that there is a mismatch between the versions of * the display driver and the CUDA driver. Refer to the compatibility documentation * for supported versions. */ CUDA_ERROR_SYSTEM_DRIVER_MISMATCH = 803, /** * This error indicates that the system was upgraded to run with forward compatibility * but the visible hardware detected by CUDA does not support this configuration. * Refer to the compatibility documentation for the supported hardware matrix or ensure * that only supported hardware is visible during initialization via the CUDA_VISIBLE_DEVICES * environment variable. */ CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE = 804, /** * This error indicates that the MPS client failed to connect to the MPS control daemon or the MPS server. */ CUDA_ERROR_MPS_CONNECTION_FAILED = 805, /** * This error indicates that the remote procedural call between the MPS server and the MPS client failed. */ CUDA_ERROR_MPS_RPC_FAILURE = 806, /** * This error indicates that the MPS server is not ready to accept new MPS client requests. * This error can be returned when the MPS server is in the process of recovering from a fatal failure. */ CUDA_ERROR_MPS_SERVER_NOT_READY = 807, /** * This error indicates that the hardware resources required to create MPS client have been exhausted. */ CUDA_ERROR_MPS_MAX_CLIENTS_REACHED = 808, /** * This error indicates the the hardware resources required to support device connections have been exhausted. */ CUDA_ERROR_MPS_MAX_CONNECTIONS_REACHED = 809, /** * This error indicates that the operation is not permitted when * the stream is capturing. */ CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED = 900, /** * This error indicates that the current capture sequence on the stream * has been invalidated due to a previous error. */ CUDA_ERROR_STREAM_CAPTURE_INVALIDATED = 901, /** * This error indicates that the operation would have resulted in a merge * of two independent capture sequences. */ CUDA_ERROR_STREAM_CAPTURE_MERGE = 902, /** * This error indicates that the capture was not initiated in this stream. */ CUDA_ERROR_STREAM_CAPTURE_UNMATCHED = 903, /** * This error indicates that the capture sequence contains a fork that was * not joined to the primary stream. */ CUDA_ERROR_STREAM_CAPTURE_UNJOINED = 904, /** * This error indicates that a dependency would have been created which * crosses the capture sequence boundary. Only implicit in-stream ordering * dependencies are allowed to cross the boundary. */ CUDA_ERROR_STREAM_CAPTURE_ISOLATION = 905, /** * This error indicates a disallowed implicit dependency on a current capture * sequence from cudaStreamLegacy. */ CUDA_ERROR_STREAM_CAPTURE_IMPLICIT = 906, /** * This error indicates that the operation is not permitted on an event which * was last recorded in a capturing stream. */ CUDA_ERROR_CAPTURED_EVENT = 907, /** * A stream capture sequence not initiated with the ::CU_STREAM_CAPTURE_MODE_RELAXED * argument to ::cuStreamBeginCapture was passed to ::cuStreamEndCapture in a * different thread. */ CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD = 908, /** * This error indicates that the timeout specified for the wait operation has lapsed. */ CUDA_ERROR_TIMEOUT = 909, /** * This error indicates that the graph update was not performed because it included * changes which violated constraints specific to instantiated graph update. */ CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE = 910, /** * This indicates that an async error has occurred in a device outside of CUDA. * If CUDA was waiting for an external device's signal before consuming shared data, * the external device signaled an error indicating that the data is not valid for * consumption. This leaves the process in an inconsistent state and any further CUDA * work will return the same error. To continue using CUDA, the process must be * terminated and relaunched. */ CUDA_ERROR_EXTERNAL_DEVICE = 911, /** * This indicates that an unknown internal error has occurred. */ CUDA_ERROR_UNKNOWN = 999 } CUresult; /** * P2P Attributes */ typedef enum CUdevice_P2PAttribute_enum { CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK = 0x01, /**< A relative value indicating the performance of the link between two devices */ CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED = 0x02, /**< P2P Access is enable */ CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED = 0x03, /**< Atomic operation over the link supported */ CU_DEVICE_P2P_ATTRIBUTE_ACCESS_ACCESS_SUPPORTED = 0x04, /**< \deprecated use CU_DEVICE_P2P_ATTRIBUTE_CUDA_ARRAY_ACCESS_SUPPORTED instead */ CU_DEVICE_P2P_ATTRIBUTE_CUDA_ARRAY_ACCESS_SUPPORTED = 0x04 /**< Accessing CUDA arrays over the link supported */ } CUdevice_P2PAttribute; /** * CUDA stream callback * \param hStream The stream the callback was added to, as passed to ::cuStreamAddCallback. May be NULL. * \param status ::CUDA_SUCCESS or any persistent error on the stream. * \param userData User parameter provided at registration. */ typedef void (CUDA_CB *CUstreamCallback)(CUstream hStream, CUresult status, void *userData); /** * Block size to per-block dynamic shared memory mapping for a certain * kernel \param blockSize Block size of the kernel. * * \return The dynamic shared memory needed by a block. */ typedef size_t (CUDA_CB *CUoccupancyB2DSize)(int blockSize); /** * If set, host memory is portable between CUDA contexts. * Flag for ::cuMemHostAlloc() */ #define CU_MEMHOSTALLOC_PORTABLE 0x01 /** * If set, host memory is mapped into CUDA address space and * ::cuMemHostGetDevicePointer() may be called on the host pointer. * Flag for ::cuMemHostAlloc() */ #define CU_MEMHOSTALLOC_DEVICEMAP 0x02 /** * If set, host memory is allocated as write-combined - fast to write, * faster to DMA, slow to read except via SSE4 streaming load instruction * (MOVNTDQA). * Flag for ::cuMemHostAlloc() */ #define CU_MEMHOSTALLOC_WRITECOMBINED 0x04 /** * If set, host memory is portable between CUDA contexts. * Flag for ::cuMemHostRegister() */ #define CU_MEMHOSTREGISTER_PORTABLE 0x01 /** * If set, host memory is mapped into CUDA address space and * ::cuMemHostGetDevicePointer() may be called on the host pointer. * Flag for ::cuMemHostRegister() */ #define CU_MEMHOSTREGISTER_DEVICEMAP 0x02 /** * If set, the passed memory pointer is treated as pointing to some * memory-mapped I/O space, e.g. belonging to a third-party PCIe device. * On Windows the flag is a no-op. * On Linux that memory is marked as non cache-coherent for the GPU and * is expected to be physically contiguous. It may return * ::CUDA_ERROR_NOT_PERMITTED if run as an unprivileged user, * ::CUDA_ERROR_NOT_SUPPORTED on older Linux kernel versions. * On all other platforms, it is not supported and ::CUDA_ERROR_NOT_SUPPORTED * is returned. * Flag for ::cuMemHostRegister() */ #define CU_MEMHOSTREGISTER_IOMEMORY 0x04 /** * If set, the passed memory pointer is treated as pointing to memory that is * considered read-only by the device. On platforms without * ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, this flag is * required in order to register memory mapped to the CPU as read-only. Support * for the use of this flag can be queried from the device attribute * ::CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED. Using this flag with * a current context associated with a device that does not have this attribute * set will cause ::cuMemHostRegister to error with ::CUDA_ERROR_NOT_SUPPORTED. */ #define CU_MEMHOSTREGISTER_READ_ONLY 0x08 /** * 2D memory copy parameters */ typedef struct CUDA_MEMCPY2D_st { size_t srcXInBytes; /**< Source X in bytes */ size_t srcY; /**< Source Y */ CUmemorytype srcMemoryType; /**< Source memory type (host, device, array) */ const void *srcHost; /**< Source host pointer */ CUdeviceptr srcDevice; /**< Source device pointer */ CUarray srcArray; /**< Source array reference */ size_t srcPitch; /**< Source pitch (ignored when src is array) */ size_t dstXInBytes; /**< Destination X in bytes */ size_t dstY; /**< Destination Y */ CUmemorytype dstMemoryType; /**< Destination memory type (host, device, array) */ void *dstHost; /**< Destination host pointer */ CUdeviceptr dstDevice; /**< Destination device pointer */ CUarray dstArray; /**< Destination array reference */ size_t dstPitch; /**< Destination pitch (ignored when dst is array) */ size_t WidthInBytes; /**< Width of 2D memory copy in bytes */ size_t Height; /**< Height of 2D memory copy */ } CUDA_MEMCPY2D_v2; typedef CUDA_MEMCPY2D_v2 CUDA_MEMCPY2D; /** * 3D memory copy parameters */ typedef struct CUDA_MEMCPY3D_st { size_t srcXInBytes; /**< Source X in bytes */ size_t srcY; /**< Source Y */ size_t srcZ; /**< Source Z */ size_t srcLOD; /**< Source LOD */ CUmemorytype srcMemoryType; /**< Source memory type (host, device, array) */ const void *srcHost; /**< Source host pointer */ CUdeviceptr srcDevice; /**< Source device pointer */ CUarray srcArray; /**< Source array reference */ void *reserved0; /**< Must be NULL */ size_t srcPitch; /**< Source pitch (ignored when src is array) */ size_t srcHeight; /**< Source height (ignored when src is array; may be 0 if Depth==1) */ size_t dstXInBytes; /**< Destination X in bytes */ size_t dstY; /**< Destination Y */ size_t dstZ; /**< Destination Z */ size_t dstLOD; /**< Destination LOD */ CUmemorytype dstMemoryType; /**< Destination memory type (host, device, array) */ void *dstHost; /**< Destination host pointer */ CUdeviceptr dstDevice; /**< Destination device pointer */ CUarray dstArray; /**< Destination array reference */ void *reserved1; /**< Must be NULL */ size_t dstPitch; /**< Destination pitch (ignored when dst is array) */ size_t dstHeight; /**< Destination height (ignored when dst is array; may be 0 if Depth==1) */ size_t WidthInBytes; /**< Width of 3D memory copy in bytes */ size_t Height; /**< Height of 3D memory copy */ size_t Depth; /**< Depth of 3D memory copy */ } CUDA_MEMCPY3D_v2; typedef CUDA_MEMCPY3D_v2 CUDA_MEMCPY3D; /** * 3D memory cross-context copy parameters */ typedef struct CUDA_MEMCPY3D_PEER_st { size_t srcXInBytes; /**< Source X in bytes */ size_t srcY; /**< Source Y */ size_t srcZ; /**< Source Z */ size_t srcLOD; /**< Source LOD */ CUmemorytype srcMemoryType; /**< Source memory type (host, device, array) */ const void *srcHost; /**< Source host pointer */ CUdeviceptr srcDevice; /**< Source device pointer */ CUarray srcArray; /**< Source array reference */ CUcontext srcContext; /**< Source context (ignored with srcMemoryType is ::CU_MEMORYTYPE_ARRAY) */ size_t srcPitch; /**< Source pitch (ignored when src is array) */ size_t srcHeight; /**< Source height (ignored when src is array; may be 0 if Depth==1) */ size_t dstXInBytes; /**< Destination X in bytes */ size_t dstY; /**< Destination Y */ size_t dstZ; /**< Destination Z */ size_t dstLOD; /**< Destination LOD */ CUmemorytype dstMemoryType; /**< Destination memory type (host, device, array) */ void *dstHost; /**< Destination host pointer */ CUdeviceptr dstDevice; /**< Destination device pointer */ CUarray dstArray; /**< Destination array reference */ CUcontext dstContext; /**< Destination context (ignored with dstMemoryType is ::CU_MEMORYTYPE_ARRAY) */ size_t dstPitch; /**< Destination pitch (ignored when dst is array) */ size_t dstHeight; /**< Destination height (ignored when dst is array; may be 0 if Depth==1) */ size_t WidthInBytes; /**< Width of 3D memory copy in bytes */ size_t Height; /**< Height of 3D memory copy */ size_t Depth; /**< Depth of 3D memory copy */ } CUDA_MEMCPY3D_PEER_v1; typedef CUDA_MEMCPY3D_PEER_v1 CUDA_MEMCPY3D_PEER; /** * Array descriptor */ typedef struct CUDA_ARRAY_DESCRIPTOR_st { size_t Width; /**< Width of array */ size_t Height; /**< Height of array */ CUarray_format Format; /**< Array format */ unsigned int NumChannels; /**< Channels per array element */ } CUDA_ARRAY_DESCRIPTOR_v2; typedef CUDA_ARRAY_DESCRIPTOR_v2 CUDA_ARRAY_DESCRIPTOR; /** * 3D array descriptor */ typedef struct CUDA_ARRAY3D_DESCRIPTOR_st { size_t Width; /**< Width of 3D array */ size_t Height; /**< Height of 3D array */ size_t Depth; /**< Depth of 3D array */ CUarray_format Format; /**< Array format */ unsigned int NumChannels; /**< Channels per array element */ unsigned int Flags; /**< Flags */ } CUDA_ARRAY3D_DESCRIPTOR_v2; typedef CUDA_ARRAY3D_DESCRIPTOR_v2 CUDA_ARRAY3D_DESCRIPTOR; /** * Indicates that the layered sparse CUDA array or CUDA mipmapped array has a single mip tail region for all layers */ #define CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL 0x1 /** * CUDA array sparse properties */ typedef struct CUDA_ARRAY_SPARSE_PROPERTIES_st { struct { unsigned int width; /**< Width of sparse tile in elements */ unsigned int height; /**< Height of sparse tile in elements */ unsigned int depth; /**< Depth of sparse tile in elements */ } tileExtent; /** * First mip level at which the mip tail begins. */ unsigned int miptailFirstLevel; /** * Total size of the mip tail. */ unsigned long long miptailSize; /** * Flags will either be zero or ::CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL */ unsigned int flags; unsigned int reserved[4]; } CUDA_ARRAY_SPARSE_PROPERTIES_v1; typedef CUDA_ARRAY_SPARSE_PROPERTIES_v1 CUDA_ARRAY_SPARSE_PROPERTIES; /** * CUDA array memory requirements */ typedef struct CUDA_ARRAY_MEMORY_REQUIREMENTS_st { size_t size; /**< Total required memory size */ size_t alignment; /**< alignment requirement */ unsigned int reserved[4]; } CUDA_ARRAY_MEMORY_REQUIREMENTS_v1; typedef CUDA_ARRAY_MEMORY_REQUIREMENTS_v1 CUDA_ARRAY_MEMORY_REQUIREMENTS; /** * CUDA Resource descriptor */ typedef struct CUDA_RESOURCE_DESC_st { CUresourcetype resType; /**< Resource type */ union { struct { CUarray hArray; /**< CUDA array */ } array; struct { CUmipmappedArray hMipmappedArray; /**< CUDA mipmapped array */ } mipmap; struct { CUdeviceptr devPtr; /**< Device pointer */ CUarray_format format; /**< Array format */ unsigned int numChannels; /**< Channels per array element */ size_t sizeInBytes; /**< Size in bytes */ } linear; struct { CUdeviceptr devPtr; /**< Device pointer */ CUarray_format format; /**< Array format */ unsigned int numChannels; /**< Channels per array element */ size_t width; /**< Width of the array in elements */ size_t height; /**< Height of the array in elements */ size_t pitchInBytes; /**< Pitch between two rows in bytes */ } pitch2D; struct { int reserved[32]; } reserved; } res; unsigned int flags; /**< Flags (must be zero) */ } CUDA_RESOURCE_DESC_v1; typedef CUDA_RESOURCE_DESC_v1 CUDA_RESOURCE_DESC; /** * Texture descriptor */ typedef struct CUDA_TEXTURE_DESC_st { CUaddress_mode addressMode[3]; /**< Address modes */ CUfilter_mode filterMode; /**< Filter mode */ unsigned int flags; /**< Flags */ unsigned int maxAnisotropy; /**< Maximum anisotropy ratio */ CUfilter_mode mipmapFilterMode; /**< Mipmap filter mode */ float mipmapLevelBias; /**< Mipmap level bias */ float minMipmapLevelClamp; /**< Mipmap minimum level clamp */ float maxMipmapLevelClamp; /**< Mipmap maximum level clamp */ float borderColor[4]; /**< Border Color */ int reserved[12]; } CUDA_TEXTURE_DESC_v1; typedef CUDA_TEXTURE_DESC_v1 CUDA_TEXTURE_DESC; /** * Resource view format */ typedef enum CUresourceViewFormat_enum { CU_RES_VIEW_FORMAT_NONE = 0x00, /**< No resource view format (use underlying resource format) */ CU_RES_VIEW_FORMAT_UINT_1X8 = 0x01, /**< 1 channel unsigned 8-bit integers */ CU_RES_VIEW_FORMAT_UINT_2X8 = 0x02, /**< 2 channel unsigned 8-bit integers */ CU_RES_VIEW_FORMAT_UINT_4X8 = 0x03, /**< 4 channel unsigned 8-bit integers */ CU_RES_VIEW_FORMAT_SINT_1X8 = 0x04, /**< 1 channel signed 8-bit integers */ CU_RES_VIEW_FORMAT_SINT_2X8 = 0x05, /**< 2 channel signed 8-bit integers */ CU_RES_VIEW_FORMAT_SINT_4X8 = 0x06, /**< 4 channel signed 8-bit integers */ CU_RES_VIEW_FORMAT_UINT_1X16 = 0x07, /**< 1 channel unsigned 16-bit integers */ CU_RES_VIEW_FORMAT_UINT_2X16 = 0x08, /**< 2 channel unsigned 16-bit integers */ CU_RES_VIEW_FORMAT_UINT_4X16 = 0x09, /**< 4 channel unsigned 16-bit integers */ CU_RES_VIEW_FORMAT_SINT_1X16 = 0x0a, /**< 1 channel signed 16-bit integers */ CU_RES_VIEW_FORMAT_SINT_2X16 = 0x0b, /**< 2 channel signed 16-bit integers */ CU_RES_VIEW_FORMAT_SINT_4X16 = 0x0c, /**< 4 channel signed 16-bit integers */ CU_RES_VIEW_FORMAT_UINT_1X32 = 0x0d, /**< 1 channel unsigned 32-bit integers */ CU_RES_VIEW_FORMAT_UINT_2X32 = 0x0e, /**< 2 channel unsigned 32-bit integers */ CU_RES_VIEW_FORMAT_UINT_4X32 = 0x0f, /**< 4 channel unsigned 32-bit integers */ CU_RES_VIEW_FORMAT_SINT_1X32 = 0x10, /**< 1 channel signed 32-bit integers */ CU_RES_VIEW_FORMAT_SINT_2X32 = 0x11, /**< 2 channel signed 32-bit integers */ CU_RES_VIEW_FORMAT_SINT_4X32 = 0x12, /**< 4 channel signed 32-bit integers */ CU_RES_VIEW_FORMAT_FLOAT_1X16 = 0x13, /**< 1 channel 16-bit floating point */ CU_RES_VIEW_FORMAT_FLOAT_2X16 = 0x14, /**< 2 channel 16-bit floating point */ CU_RES_VIEW_FORMAT_FLOAT_4X16 = 0x15, /**< 4 channel 16-bit floating point */ CU_RES_VIEW_FORMAT_FLOAT_1X32 = 0x16, /**< 1 channel 32-bit floating point */ CU_RES_VIEW_FORMAT_FLOAT_2X32 = 0x17, /**< 2 channel 32-bit floating point */ CU_RES_VIEW_FORMAT_FLOAT_4X32 = 0x18, /**< 4 channel 32-bit floating point */ CU_RES_VIEW_FORMAT_UNSIGNED_BC1 = 0x19, /**< Block compressed 1 */ CU_RES_VIEW_FORMAT_UNSIGNED_BC2 = 0x1a, /**< Block compressed 2 */ CU_RES_VIEW_FORMAT_UNSIGNED_BC3 = 0x1b, /**< Block compressed 3 */ CU_RES_VIEW_FORMAT_UNSIGNED_BC4 = 0x1c, /**< Block compressed 4 unsigned */ CU_RES_VIEW_FORMAT_SIGNED_BC4 = 0x1d, /**< Block compressed 4 signed */ CU_RES_VIEW_FORMAT_UNSIGNED_BC5 = 0x1e, /**< Block compressed 5 unsigned */ CU_RES_VIEW_FORMAT_SIGNED_BC5 = 0x1f, /**< Block compressed 5 signed */ CU_RES_VIEW_FORMAT_UNSIGNED_BC6H = 0x20, /**< Block compressed 6 unsigned half-float */ CU_RES_VIEW_FORMAT_SIGNED_BC6H = 0x21, /**< Block compressed 6 signed half-float */ CU_RES_VIEW_FORMAT_UNSIGNED_BC7 = 0x22 /**< Block compressed 7 */ } CUresourceViewFormat; /** * Resource view descriptor */ typedef struct CUDA_RESOURCE_VIEW_DESC_st { CUresourceViewFormat format; /**< Resource view format */ size_t width; /**< Width of the resource view */ size_t height; /**< Height of the resource view */ size_t depth; /**< Depth of the resource view */ unsigned int firstMipmapLevel; /**< First defined mipmap level */ unsigned int lastMipmapLevel; /**< Last defined mipmap level */ unsigned int firstLayer; /**< First layer index */ unsigned int lastLayer; /**< Last layer index */ unsigned int reserved[16]; } CUDA_RESOURCE_VIEW_DESC_v1; typedef CUDA_RESOURCE_VIEW_DESC_v1 CUDA_RESOURCE_VIEW_DESC; /** * GPU Direct v3 tokens */ typedef struct CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_st { unsigned long long p2pToken; unsigned int vaSpaceToken; } CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1; typedef CUDA_POINTER_ATTRIBUTE_P2P_TOKENS_v1 CUDA_POINTER_ATTRIBUTE_P2P_TOKENS; /** * Access flags that specify the level of access the current context's device has * on the memory referenced. */ typedef enum CUDA_POINTER_ATTRIBUTE_ACCESS_FLAGS_enum { CU_POINTER_ATTRIBUTE_ACCESS_FLAG_NONE = 0x0, /**< No access, meaning the device cannot access this memory at all, thus must be staged through accessible memory in order to complete certain operations */ CU_POINTER_ATTRIBUTE_ACCESS_FLAG_READ = 0x1, /**< Read-only access, meaning writes to this memory are considered invalid accesses and thus return error in that case. */ CU_POINTER_ATTRIBUTE_ACCESS_FLAG_READWRITE = 0x3 /**< Read-write access, the device has full read-write access to the memory */ } CUDA_POINTER_ATTRIBUTE_ACCESS_FLAGS; /** * Kernel launch parameters */ typedef struct CUDA_LAUNCH_PARAMS_st { CUfunction function; /**< Kernel to launch */ unsigned int gridDimX; /**< Width of grid in blocks */ unsigned int gridDimY; /**< Height of grid in blocks */ unsigned int gridDimZ; /**< Depth of grid in blocks */ unsigned int blockDimX; /**< X dimension of each thread block */ unsigned int blockDimY; /**< Y dimension of each thread block */ unsigned int blockDimZ; /**< Z dimension of each thread block */ unsigned int sharedMemBytes; /**< Dynamic shared-memory size per thread block in bytes */ CUstream hStream; /**< Stream identifier */ void **kernelParams; /**< Array of pointers to kernel parameters */ } CUDA_LAUNCH_PARAMS_v1; typedef CUDA_LAUNCH_PARAMS_v1 CUDA_LAUNCH_PARAMS; /** * External memory handle types */ typedef enum CUexternalMemoryHandleType_enum { /** * Handle is an opaque file descriptor */ CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD = 1, /** * Handle is an opaque shared NT handle */ CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32 = 2, /** * Handle is an opaque, globally shared handle */ CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT = 3, /** * Handle is a D3D12 heap object */ CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP = 4, /** * Handle is a D3D12 committed resource */ CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE = 5, /** * Handle is a shared NT handle to a D3D11 resource */ CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE = 6, /** * Handle is a globally shared handle to a D3D11 resource */ CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT = 7, /** * Handle is an NvSciBuf object */ CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF = 8 } CUexternalMemoryHandleType; /** * Indicates that the external memory object is a dedicated resource */ #define CUDA_EXTERNAL_MEMORY_DEDICATED 0x1 /** When the \p flags parameter of ::CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS * contains this flag, it indicates that signaling an external semaphore object * should skip performing appropriate memory synchronization operations over all * the external memory objects that are imported as ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF, * which otherwise are performed by default to ensure data coherency with other * importers of the same NvSciBuf memory objects. */ #define CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC 0x01 /** When the \p flags parameter of ::CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS * contains this flag, it indicates that waiting on an external semaphore object * should skip performing appropriate memory synchronization operations over all * the external memory objects that are imported as ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF, * which otherwise are performed by default to ensure data coherency with other * importers of the same NvSciBuf memory objects. */ #define CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC 0x02 /** * When \p flags of ::cuDeviceGetNvSciSyncAttributes is set to this, * it indicates that application needs signaler specific NvSciSyncAttr * to be filled by ::cuDeviceGetNvSciSyncAttributes. */ #define CUDA_NVSCISYNC_ATTR_SIGNAL 0x1 /** * When \p flags of ::cuDeviceGetNvSciSyncAttributes is set to this, * it indicates that application needs waiter specific NvSciSyncAttr * to be filled by ::cuDeviceGetNvSciSyncAttributes. */ #define CUDA_NVSCISYNC_ATTR_WAIT 0x2 /** * External memory handle descriptor */ typedef struct CUDA_EXTERNAL_MEMORY_HANDLE_DESC_st { /** * Type of the handle */ CUexternalMemoryHandleType type; union { /** * File descriptor referencing the memory object. Valid * when type is * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD */ int fd; /** * Win32 handle referencing the semaphore object. Valid when * type is one of the following: * - ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32 * - ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT * - ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP * - ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE * - ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE * - ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT * Exactly one of 'handle' and 'name' must be non-NULL. If * type is one of the following: * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT * then 'name' must be NULL. */ struct { /** * Valid NT handle. Must be NULL if 'name' is non-NULL */ void *handle; /** * Name of a valid memory object. * Must be NULL if 'handle' is non-NULL. */ const void *name; } win32; /** * A handle representing an NvSciBuf Object. Valid when type * is ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF */ const void *nvSciBufObject; } handle; /** * Size of the memory allocation */ unsigned long long size; /** * Flags must either be zero or ::CUDA_EXTERNAL_MEMORY_DEDICATED */ unsigned int flags; unsigned int reserved[16]; } CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1; typedef CUDA_EXTERNAL_MEMORY_HANDLE_DESC_v1 CUDA_EXTERNAL_MEMORY_HANDLE_DESC; /** * External memory buffer descriptor */ typedef struct CUDA_EXTERNAL_MEMORY_BUFFER_DESC_st { /** * Offset into the memory object where the buffer's base is */ unsigned long long offset; /** * Size of the buffer */ unsigned long long size; /** * Flags reserved for future use. Must be zero. */ unsigned int flags; unsigned int reserved[16]; } CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1; typedef CUDA_EXTERNAL_MEMORY_BUFFER_DESC_v1 CUDA_EXTERNAL_MEMORY_BUFFER_DESC; /** * External memory mipmap descriptor */ typedef struct CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_st { /** * Offset into the memory object where the base level of the * mipmap chain is. */ unsigned long long offset; /** * Format, dimension and type of base level of the mipmap chain */ CUDA_ARRAY3D_DESCRIPTOR arrayDesc; /** * Total number of levels in the mipmap chain */ unsigned int numLevels; unsigned int reserved[16]; } CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1; typedef CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_v1 CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC; /** * External semaphore handle types */ typedef enum CUexternalSemaphoreHandleType_enum { /** * Handle is an opaque file descriptor */ CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD = 1, /** * Handle is an opaque shared NT handle */ CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32 = 2, /** * Handle is an opaque, globally shared handle */ CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT = 3, /** * Handle is a shared NT handle referencing a D3D12 fence object */ CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE = 4, /** * Handle is a shared NT handle referencing a D3D11 fence object */ CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE = 5, /** * Opaque handle to NvSciSync Object */ CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC = 6, /** * Handle is a shared NT handle referencing a D3D11 keyed mutex object */ CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX = 7, /** * Handle is a globally shared handle referencing a D3D11 keyed mutex object */ CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT = 8, /** * Handle is an opaque file descriptor referencing a timeline semaphore */ CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD = 9, /** * Handle is an opaque shared NT handle referencing a timeline semaphore */ CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32 = 10 } CUexternalSemaphoreHandleType; /** * External semaphore handle descriptor */ typedef struct CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_st { /** * Type of the handle */ CUexternalSemaphoreHandleType type; union { /** * File descriptor referencing the semaphore object. Valid * when type is one of the following: * - ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD * - ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD */ int fd; /** * Win32 handle referencing the semaphore object. Valid when * type is one of the following: * - ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32 * - ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT * - ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE * - ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE * - ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX * - ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32 * Exactly one of 'handle' and 'name' must be non-NULL. If * type is one of the following: * - ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT * - ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT * then 'name' must be NULL. */ struct { /** * Valid NT handle. Must be NULL if 'name' is non-NULL */ void *handle; /** * Name of a valid synchronization primitive. * Must be NULL if 'handle' is non-NULL. */ const void *name; } win32; /** * Valid NvSciSyncObj. Must be non NULL */ const void* nvSciSyncObj; } handle; /** * Flags reserved for the future. Must be zero. */ unsigned int flags; unsigned int reserved[16]; } CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1; typedef CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_v1 CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC; /** * External semaphore signal parameters */ typedef struct CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_st { struct { /** * Parameters for fence objects */ struct { /** * Value of fence to be signaled */ unsigned long long value; } fence; union { /** * Pointer to NvSciSyncFence. Valid if ::CUexternalSemaphoreHandleType * is of type ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC. */ void *fence; unsigned long long reserved; } nvSciSync; /** * Parameters for keyed mutex objects */ struct { /** * Value of key to release the mutex with */ unsigned long long key; } keyedMutex; unsigned int reserved[12]; } params; /** * Only when ::CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS is used to * signal a ::CUexternalSemaphore of type * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, the valid flag is * ::CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC which indicates * that while signaling the ::CUexternalSemaphore, no memory synchronization * operations should be performed for any external memory object imported * as ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF. * For all other types of ::CUexternalSemaphore, flags must be zero. */ unsigned int flags; unsigned int reserved[16]; } CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1; typedef CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS_v1 CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS; /** * External semaphore wait parameters */ typedef struct CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_st { struct { /** * Parameters for fence objects */ struct { /** * Value of fence to be waited on */ unsigned long long value; } fence; /** * Pointer to NvSciSyncFence. Valid if CUexternalSemaphoreHandleType * is of type CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC. */ union { void *fence; unsigned long long reserved; } nvSciSync; /** * Parameters for keyed mutex objects */ struct { /** * Value of key to acquire the mutex with */ unsigned long long key; /** * Timeout in milliseconds to wait to acquire the mutex */ unsigned int timeoutMs; } keyedMutex; unsigned int reserved[10]; } params; /** * Only when ::CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS is used to wait on * a ::CUexternalSemaphore of type ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, * the valid flag is ::CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC * which indicates that while waiting for the ::CUexternalSemaphore, no memory * synchronization operations should be performed for any external memory * object imported as ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF. * For all other types of ::CUexternalSemaphore, flags must be zero. */ unsigned int flags; unsigned int reserved[16]; } CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1; typedef CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS_v1 CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS; /** * Semaphore signal node parameters */ typedef struct CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_st { CUexternalSemaphore* extSemArray; /**< Array of external semaphore handles. */ const CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS* paramsArray; /**< Array of external semaphore signal parameters. */ unsigned int numExtSems; /**< Number of handles and parameters supplied in extSemArray and paramsArray. */ } CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1; typedef CUDA_EXT_SEM_SIGNAL_NODE_PARAMS_v1 CUDA_EXT_SEM_SIGNAL_NODE_PARAMS; /** * Semaphore wait node parameters */ typedef struct CUDA_EXT_SEM_WAIT_NODE_PARAMS_st { CUexternalSemaphore* extSemArray; /**< Array of external semaphore handles. */ const CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS* paramsArray; /**< Array of external semaphore wait parameters. */ unsigned int numExtSems; /**< Number of handles and parameters supplied in extSemArray and paramsArray. */ } CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1; typedef CUDA_EXT_SEM_WAIT_NODE_PARAMS_v1 CUDA_EXT_SEM_WAIT_NODE_PARAMS; typedef unsigned long long CUmemGenericAllocationHandle_v1; typedef CUmemGenericAllocationHandle_v1 CUmemGenericAllocationHandle; /** * Flags for specifying particular handle types */ typedef enum CUmemAllocationHandleType_enum { CU_MEM_HANDLE_TYPE_NONE = 0x0, /**< Does not allow any export mechanism. > */ CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR = 0x1, /**< Allows a file descriptor to be used for exporting. Permitted only on POSIX systems. (int) */ CU_MEM_HANDLE_TYPE_WIN32 = 0x2, /**< Allows a Win32 NT handle to be used for exporting. (HANDLE) */ CU_MEM_HANDLE_TYPE_WIN32_KMT = 0x4, /**< Allows a Win32 KMT handle to be used for exporting. (D3DKMT_HANDLE) */ CU_MEM_HANDLE_TYPE_MAX = 0x7FFFFFFF } CUmemAllocationHandleType; /** * Specifies the memory protection flags for mapping. */ typedef enum CUmemAccess_flags_enum { CU_MEM_ACCESS_FLAGS_PROT_NONE = 0x0, /**< Default, make the address range not accessible */ CU_MEM_ACCESS_FLAGS_PROT_READ = 0x1, /**< Make the address range read accessible */ CU_MEM_ACCESS_FLAGS_PROT_READWRITE = 0x3, /**< Make the address range read-write accessible */ CU_MEM_ACCESS_FLAGS_PROT_MAX = 0x7FFFFFFF } CUmemAccess_flags; /** * Specifies the type of location */ typedef enum CUmemLocationType_enum { CU_MEM_LOCATION_TYPE_INVALID = 0x0, CU_MEM_LOCATION_TYPE_DEVICE = 0x1, /**< Location is a device location, thus id is a device ordinal */ CU_MEM_LOCATION_TYPE_MAX = 0x7FFFFFFF } CUmemLocationType; /** * Defines the allocation types available */ typedef enum CUmemAllocationType_enum { CU_MEM_ALLOCATION_TYPE_INVALID = 0x0, /** This allocation type is 'pinned', i.e. cannot migrate from its current * location while the application is actively using it */ CU_MEM_ALLOCATION_TYPE_PINNED = 0x1, CU_MEM_ALLOCATION_TYPE_MAX = 0x7FFFFFFF } CUmemAllocationType; /** * Flag for requesting different optimal and required granularities for an allocation. */ typedef enum CUmemAllocationGranularity_flags_enum { CU_MEM_ALLOC_GRANULARITY_MINIMUM = 0x0, /**< Minimum required granularity for allocation */ CU_MEM_ALLOC_GRANULARITY_RECOMMENDED = 0x1 /**< Recommended granularity for allocation for best performance */ } CUmemAllocationGranularity_flags; /** * Sparse subresource types */ typedef enum CUarraySparseSubresourceType_enum { CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SPARSE_LEVEL = 0, CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL = 1 } CUarraySparseSubresourceType; /** * Memory operation types */ typedef enum CUmemOperationType_enum { CU_MEM_OPERATION_TYPE_MAP = 1, CU_MEM_OPERATION_TYPE_UNMAP = 2 } CUmemOperationType; /** * Memory handle types */ typedef enum CUmemHandleType_enum { CU_MEM_HANDLE_TYPE_GENERIC = 0 } CUmemHandleType; /** * Specifies the CUDA array or CUDA mipmapped array memory mapping information */ typedef struct CUarrayMapInfo_st { CUresourcetype resourceType; /**< Resource type */ union { CUmipmappedArray mipmap; CUarray array; } resource; CUarraySparseSubresourceType subresourceType; /**< Sparse subresource type */ union { struct { unsigned int level; /**< For CUDA mipmapped arrays must a valid mipmap level. For CUDA arrays must be zero */ unsigned int layer; /**< For CUDA layered arrays must be a valid layer index. Otherwise, must be zero */ unsigned int offsetX; /**< Starting X offset in elements */ unsigned int offsetY; /**< Starting Y offset in elements */ unsigned int offsetZ; /**< Starting Z offset in elements */ unsigned int extentWidth; /**< Width in elements */ unsigned int extentHeight; /**< Height in elements */ unsigned int extentDepth; /**< Depth in elements */ } sparseLevel; struct { unsigned int layer; /**< For CUDA layered arrays must be a valid layer index. Otherwise, must be zero */ unsigned long long offset; /**< Offset within mip tail */ unsigned long long size; /**< Extent in bytes */ } miptail; } subresource; CUmemOperationType memOperationType; /**< Memory operation type */ CUmemHandleType memHandleType; /**< Memory handle type */ union { CUmemGenericAllocationHandle memHandle; } memHandle; unsigned long long offset; /**< Offset within the memory */ unsigned int deviceBitMask; /**< Device ordinal bit mask */ unsigned int flags; /**< flags for future use, must be zero now. */ unsigned int reserved[2]; /**< Reserved for future use, must be zero now. */ } CUarrayMapInfo_v1; typedef CUarrayMapInfo_v1 CUarrayMapInfo; /** * Specifies a memory location. */ typedef struct CUmemLocation_st { CUmemLocationType type; /**< Specifies the location type, which modifies the meaning of id. */ int id; /**< identifier for a given this location's ::CUmemLocationType. */ } CUmemLocation_v1; typedef CUmemLocation_v1 CUmemLocation; /** * Specifies compression attribute for an allocation. */ typedef enum CUmemAllocationCompType_enum { CU_MEM_ALLOCATION_COMP_NONE = 0x0, /**< Allocating non-compressible memory */ CU_MEM_ALLOCATION_COMP_GENERIC = 0x1 /**< Allocating compressible memory */ } CUmemAllocationCompType; /** * This flag if set indicates that the memory will be used as a tile pool. */ #define CU_MEM_CREATE_USAGE_TILE_POOL 0x1 /** * Specifies the allocation properties for a allocation. */ typedef struct CUmemAllocationProp_st { /** Allocation type */ CUmemAllocationType type; /** requested ::CUmemAllocationHandleType */ CUmemAllocationHandleType requestedHandleTypes; /** Location of allocation */ CUmemLocation location; /** * Windows-specific POBJECT_ATTRIBUTES required when * ::CU_MEM_HANDLE_TYPE_WIN32 is specified. This object atributes structure * includes security attributes that define * the scope of which exported allocations may be tranferred to other * processes. In all other cases, this field is required to be zero. */ void *win32HandleMetaData; struct { /** * Allocation hint for requesting compressible memory. * On devices that support Compute Data Compression, compressible * memory can be used to accelerate accesses to data with unstructured * sparsity and other compressible data patterns. Applications are * expected to query allocation property of the handle obtained with * ::cuMemCreate using ::cuMemGetAllocationPropertiesFromHandle to * validate if the obtained allocation is compressible or not. Note that * compressed memory may not be mappable on all devices. */ unsigned char compressionType; unsigned char gpuDirectRDMACapable; /** Bitmask indicating intended usage for this allocation */ unsigned short usage; unsigned char reserved[4]; } allocFlags; } CUmemAllocationProp_v1; typedef CUmemAllocationProp_v1 CUmemAllocationProp; /** * Memory access descriptor */ typedef struct CUmemAccessDesc_st { CUmemLocation location; /**< Location on which the request is to change it's accessibility */ CUmemAccess_flags flags; /**< ::CUmemProt accessibility flags to set on the request */ } CUmemAccessDesc_v1; typedef CUmemAccessDesc_v1 CUmemAccessDesc; typedef enum CUgraphExecUpdateResult_enum { CU_GRAPH_EXEC_UPDATE_SUCCESS = 0x0, /**< The update succeeded */ CU_GRAPH_EXEC_UPDATE_ERROR = 0x1, /**< The update failed for an unexpected reason which is described in the return value of the function */ CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED = 0x2, /**< The update failed because the topology changed */ CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED = 0x3, /**< The update failed because a node type changed */ CU_GRAPH_EXEC_UPDATE_ERROR_FUNCTION_CHANGED = 0x4, /**< The update failed because the function of a kernel node changed (CUDA driver < 11.2) */ CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED = 0x5, /**< The update failed because the parameters changed in a way that is not supported */ CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED = 0x6, /**< The update failed because something about the node is not supported */ CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE = 0x7, /**< The update failed because the function of a kernel node changed in an unsupported way */ CU_GRAPH_EXEC_UPDATE_ERROR_ATTRIBUTES_CHANGED = 0x8 /**< The update failed because the node attributes changed in a way that is not supported */ } CUgraphExecUpdateResult; /** * CUDA memory pool attributes */ typedef enum CUmemPool_attribute_enum { /** * (value type = int) * Allow cuMemAllocAsync to use memory asynchronously freed * in another streams as long as a stream ordering dependency * of the allocating stream on the free action exists. * Cuda events and null stream interactions can create the required * stream ordered dependencies. (default enabled) */ CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES = 1, /** * (value type = int) * Allow reuse of already completed frees when there is no dependency * between the free and allocation. (default enabled) */ CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC, /** * (value type = int) * Allow cuMemAllocAsync to insert new stream dependencies * in order to establish the stream ordering required to reuse * a piece of memory released by cuFreeAsync (default enabled). */ CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES, /** * (value type = cuuint64_t) * Amount of reserved memory in bytes to hold onto before trying * to release memory back to the OS. When more than the release * threshold bytes of memory are held by the memory pool, the * allocator will try to release memory back to the OS on the * next call to stream, event or context synchronize. (default 0) */ CU_MEMPOOL_ATTR_RELEASE_THRESHOLD, /** * (value type = cuuint64_t) * Amount of backing memory currently allocated for the mempool. */ CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT, /** * (value type = cuuint64_t) * High watermark of backing memory allocated for the mempool since the * last time it was reset. High watermark can only be reset to zero. */ CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH, /** * (value type = cuuint64_t) * Amount of memory from the pool that is currently in use by the application. */ CU_MEMPOOL_ATTR_USED_MEM_CURRENT, /** * (value type = cuuint64_t) * High watermark of the amount of memory from the pool that was in use by the application since * the last time it was reset. High watermark can only be reset to zero. */ CU_MEMPOOL_ATTR_USED_MEM_HIGH } CUmemPool_attribute; /** * Specifies the properties of allocations made from the pool. */ typedef struct CUmemPoolProps_st { CUmemAllocationType allocType; /**< Allocation type. Currently must be specified as CU_MEM_ALLOCATION_TYPE_PINNED */ CUmemAllocationHandleType handleTypes; /**< Handle types that will be supported by allocations from the pool. */ CUmemLocation location; /**< Location where allocations should reside. */ /** * Windows-specific LPSECURITYATTRIBUTES required when * ::CU_MEM_HANDLE_TYPE_WIN32 is specified. This security attribute defines * the scope of which exported allocations may be tranferred to other * processes. In all other cases, this field is required to be zero. */ void *win32SecurityAttributes; unsigned char reserved[64]; /**< reserved for future use, must be 0 */ } CUmemPoolProps_v1; typedef CUmemPoolProps_v1 CUmemPoolProps; /** * Opaque data for exporting a pool allocation */ typedef struct CUmemPoolPtrExportData_st { unsigned char reserved[64]; } CUmemPoolPtrExportData_v1; typedef CUmemPoolPtrExportData_v1 CUmemPoolPtrExportData; /** * Memory allocation node parameters */ typedef struct CUDA_MEM_ALLOC_NODE_PARAMS_st { /** * in: location where the allocation should reside (specified in ::location). * ::handleTypes must be ::CU_MEM_HANDLE_TYPE_NONE. IPC is not supported. */ CUmemPoolProps poolProps; const CUmemAccessDesc *accessDescs; /**< in: array of memory access descriptors. Used to describe peer GPU access */ size_t accessDescCount; /**< in: number of memory access descriptors. Must not exceed the number of GPUs. */ size_t bytesize; /**< in: size in bytes of the requested allocation */ CUdeviceptr dptr; /**< out: address of the allocation returned by CUDA */ } CUDA_MEM_ALLOC_NODE_PARAMS; typedef enum CUgraphMem_attribute_enum { /** * (value type = cuuint64_t) * Amount of memory, in bytes, currently associated with graphs */ CU_GRAPH_MEM_ATTR_USED_MEM_CURRENT, /** * (value type = cuuint64_t) * High watermark of memory, in bytes, associated with graphs since the * last time it was reset. High watermark can only be reset to zero. */ CU_GRAPH_MEM_ATTR_USED_MEM_HIGH, /** * (value type = cuuint64_t) * Amount of memory, in bytes, currently allocated for use by * the CUDA graphs asynchronous allocator. */ CU_GRAPH_MEM_ATTR_RESERVED_MEM_CURRENT, /** * (value type = cuuint64_t) * High watermark of memory, in bytes, currently allocated for use by * the CUDA graphs asynchronous allocator. */ CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH } CUgraphMem_attribute; /** * If set, each kernel launched as part of ::cuLaunchCooperativeKernelMultiDevice only * waits for prior work in the stream corresponding to that GPU to complete before the * kernel begins execution. */ #define CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_PRE_LAUNCH_SYNC 0x01 /** * If set, any subsequent work pushed in a stream that participated in a call to * ::cuLaunchCooperativeKernelMultiDevice will only wait for the kernel launched on * the GPU corresponding to that stream to complete before it begins execution. */ #define CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_POST_LAUNCH_SYNC 0x02 /** * If set, the CUDA array is a collection of layers, where each layer is either a 1D * or a 2D array and the Depth member of CUDA_ARRAY3D_DESCRIPTOR specifies the number * of layers, not the depth of a 3D array. */ #define CUDA_ARRAY3D_LAYERED 0x01 /** * Deprecated, use CUDA_ARRAY3D_LAYERED */ #define CUDA_ARRAY3D_2DARRAY 0x01 /** * This flag must be set in order to bind a surface reference * to the CUDA array */ #define CUDA_ARRAY3D_SURFACE_LDST 0x02 /** * If set, the CUDA array is a collection of six 2D arrays, representing faces of a cube. The * width of such a CUDA array must be equal to its height, and Depth must be six. * If ::CUDA_ARRAY3D_LAYERED flag is also set, then the CUDA array is a collection of cubemaps * and Depth must be a multiple of six. */ #define CUDA_ARRAY3D_CUBEMAP 0x04 /** * This flag must be set in order to perform texture gather operations * on a CUDA array. */ #define CUDA_ARRAY3D_TEXTURE_GATHER 0x08 /** * This flag if set indicates that the CUDA * array is a DEPTH_TEXTURE. */ #define CUDA_ARRAY3D_DEPTH_TEXTURE 0x10 /** * This flag indicates that the CUDA array may be bound as a color target * in an external graphics API */ #define CUDA_ARRAY3D_COLOR_ATTACHMENT 0x20 /** * This flag if set indicates that the CUDA array or CUDA mipmapped array * is a sparse CUDA array or CUDA mipmapped array respectively */ #define CUDA_ARRAY3D_SPARSE 0x40 /** * This flag if set indicates that the CUDA array or CUDA mipmapped array * will allow deferred memory mapping */ #define CUDA_ARRAY3D_DEFERRED_MAPPING 0x80 /** * Override the texref format with a format inferred from the array. * Flag for ::cuTexRefSetArray() */ #define CU_TRSA_OVERRIDE_FORMAT 0x01 /** * Read the texture as integers rather than promoting the values to floats * in the range [0,1]. * Flag for ::cuTexRefSetFlags() and ::cuTexObjectCreate() */ #define CU_TRSF_READ_AS_INTEGER 0x01 /** * Use normalized texture coordinates in the range [0,1) instead of [0,dim). * Flag for ::cuTexRefSetFlags() and ::cuTexObjectCreate() */ #define CU_TRSF_NORMALIZED_COORDINATES 0x02 /** * Perform sRGB->linear conversion during texture read. * Flag for ::cuTexRefSetFlags() and ::cuTexObjectCreate() */ #define CU_TRSF_SRGB 0x10 /** * Disable any trilinear filtering optimizations. * Flag for ::cuTexRefSetFlags() and ::cuTexObjectCreate() */ #define CU_TRSF_DISABLE_TRILINEAR_OPTIMIZATION 0x20 /** * Enable seamless cube map filtering. * Flag for ::cuTexObjectCreate() */ #define CU_TRSF_SEAMLESS_CUBEMAP 0x40 /** * End of array terminator for the \p extra parameter to * ::cuLaunchKernel */ #define CU_LAUNCH_PARAM_END ((void*)0x00) /** * Indicator that the next value in the \p extra parameter to * ::cuLaunchKernel will be a pointer to a buffer containing all kernel * parameters used for launching kernel \p f. This buffer needs to * honor all alignment/padding requirements of the individual parameters. * If ::CU_LAUNCH_PARAM_BUFFER_SIZE is not also specified in the * \p extra array, then ::CU_LAUNCH_PARAM_BUFFER_POINTER will have no * effect. */ #define CU_LAUNCH_PARAM_BUFFER_POINTER ((void*)0x01) /** * Indicator that the next value in the \p extra parameter to * ::cuLaunchKernel will be a pointer to a size_t which contains the * size of the buffer specified with ::CU_LAUNCH_PARAM_BUFFER_POINTER. * It is required that ::CU_LAUNCH_PARAM_BUFFER_POINTER also be specified * in the \p extra array if the value associated with * ::CU_LAUNCH_PARAM_BUFFER_SIZE is not zero. */ #define CU_LAUNCH_PARAM_BUFFER_SIZE ((void*)0x02) /** * For texture references loaded into the module, use default texunit from * texture reference. */ #define CU_PARAM_TR_DEFAULT -1 /** * Device that represents the CPU */ #define CU_DEVICE_CPU ((CUdevice)-1) /** * Device that represents an invalid device */ #define CU_DEVICE_INVALID ((CUdevice)-2) /** * Bitmasks for ::CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_FLUSH_WRITES_OPTIONS */ typedef enum CUflushGPUDirectRDMAWritesOptions_enum { CU_FLUSH_GPU_DIRECT_RDMA_WRITES_OPTION_HOST = 1<<0, /**< ::cuFlushGPUDirectRDMAWrites() and its CUDA Runtime API counterpart are supported on the device. */ CU_FLUSH_GPU_DIRECT_RDMA_WRITES_OPTION_MEMOPS = 1<<1 /**< The ::CU_STREAM_WAIT_VALUE_FLUSH flag and the ::CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES MemOp are supported on the device. */ } CUflushGPUDirectRDMAWritesOptions; /** * Platform native ordering for GPUDirect RDMA writes */ typedef enum CUGPUDirectRDMAWritesOrdering_enum { CU_GPU_DIRECT_RDMA_WRITES_ORDERING_NONE = 0, /**< The device does not natively support ordering of remote writes. ::cuFlushGPUDirectRDMAWrites() can be leveraged if supported. */ CU_GPU_DIRECT_RDMA_WRITES_ORDERING_OWNER = 100, /**< Natively, the device can consistently consume remote writes, although other CUDA devices may not. */ CU_GPU_DIRECT_RDMA_WRITES_ORDERING_ALL_DEVICES = 200 /**< Any CUDA device in the system can consistently consume remote writes to this device. */ } CUGPUDirectRDMAWritesOrdering; /** * The scopes for ::cuFlushGPUDirectRDMAWrites */ typedef enum CUflushGPUDirectRDMAWritesScope_enum { CU_FLUSH_GPU_DIRECT_RDMA_WRITES_TO_OWNER = 100, /**< Blocks until remote writes are visible to the CUDA device context owning the data. */ CU_FLUSH_GPU_DIRECT_RDMA_WRITES_TO_ALL_DEVICES = 200 /**< Blocks until remote writes are visible to all CUDA device contexts. */ } CUflushGPUDirectRDMAWritesScope; /** * The targets for ::cuFlushGPUDirectRDMAWrites */ typedef enum CUflushGPUDirectRDMAWritesTarget_enum { CU_FLUSH_GPU_DIRECT_RDMA_WRITES_TARGET_CURRENT_CTX = 0 /**< Sets the target for ::cuFlushGPUDirectRDMAWrites() to the currently active CUDA device context. */ } CUflushGPUDirectRDMAWritesTarget; /** * The additional write options for ::cuGraphDebugDotPrint */ typedef enum CUgraphDebugDot_flags_enum { CU_GRAPH_DEBUG_DOT_FLAGS_VERBOSE = 1<<0, /** Output all debug data as if every debug flag is enabled */ CU_GRAPH_DEBUG_DOT_FLAGS_RUNTIME_TYPES = 1<<1, /** Use CUDA Runtime structures for output */ CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_PARAMS = 1<<2, /** Adds CUDA_KERNEL_NODE_PARAMS values to output */ CU_GRAPH_DEBUG_DOT_FLAGS_MEMCPY_NODE_PARAMS = 1<<3, /** Adds CUDA_MEMCPY3D values to output */ CU_GRAPH_DEBUG_DOT_FLAGS_MEMSET_NODE_PARAMS = 1<<4, /** Adds CUDA_MEMSET_NODE_PARAMS values to output */ CU_GRAPH_DEBUG_DOT_FLAGS_HOST_NODE_PARAMS = 1<<5, /** Adds CUDA_HOST_NODE_PARAMS values to output */ CU_GRAPH_DEBUG_DOT_FLAGS_EVENT_NODE_PARAMS = 1<<6, /** Adds CUevent handle from record and wait nodes to output */ CU_GRAPH_DEBUG_DOT_FLAGS_EXT_SEMAS_SIGNAL_NODE_PARAMS = 1<<7, /** Adds CUDA_EXT_SEM_SIGNAL_NODE_PARAMS values to output */ CU_GRAPH_DEBUG_DOT_FLAGS_EXT_SEMAS_WAIT_NODE_PARAMS = 1<<8, /** Adds CUDA_EXT_SEM_WAIT_NODE_PARAMS values to output */ CU_GRAPH_DEBUG_DOT_FLAGS_KERNEL_NODE_ATTRIBUTES = 1<<9, /** Adds CUkernelNodeAttrValue values to output */ CU_GRAPH_DEBUG_DOT_FLAGS_HANDLES = 1<<10, /** Adds node handles and every kernel function handle to output */ CU_GRAPH_DEBUG_DOT_FLAGS_MEM_ALLOC_NODE_PARAMS = 1<<11, /** Adds memory alloc node parameters to output */ CU_GRAPH_DEBUG_DOT_FLAGS_MEM_FREE_NODE_PARAMS = 1<<12 /** Adds memory free node parameters to output */ } CUgraphDebugDot_flags; /** * Flags for user objects for graphs */ typedef enum CUuserObject_flags_enum { CU_USER_OBJECT_NO_DESTRUCTOR_SYNC = 1 /**< Indicates the destructor execution is not synchronized by any CUDA handle. */ } CUuserObject_flags; /** * Flags for retaining user object references for graphs */ typedef enum CUuserObjectRetain_flags_enum { CU_GRAPH_USER_OBJECT_MOVE = 1 /**< Transfer references from the caller rather than creating new references. */ } CUuserObjectRetain_flags; /** * Flags for instantiating a graph */ typedef enum CUgraphInstantiate_flags_enum { CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH = 1 /**< Automatically free memory allocated in a graph before relaunching. */ } CUgraphInstantiate_flags; /** @} */ /* END CUDA_TYPES */ #if defined(__GNUC__) #if defined(__CUDA_API_PUSH_VISIBILITY_DEFAULT) #pragma GCC visibility push(default) #endif #endif #ifdef _WIN32 #define CUDAAPI __stdcall #else #define CUDAAPI #endif /** * \defgroup CUDA_ERROR Error Handling * * ___MANBRIEF___ error handling functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the error handling functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Gets the string description of an error code * * Sets \p *pStr to the address of a NULL-terminated string description * of the error code \p error. * If the error code is not recognized, ::CUDA_ERROR_INVALID_VALUE * will be returned and \p *pStr will be set to the NULL address. * * \param error - Error code to convert to string * \param pStr - Address of the string pointer. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::CUresult, * ::cudaGetErrorString */ CUresult CUDAAPI cuGetErrorString(CUresult error, const char **pStr); /** * \brief Gets the string representation of an error code enum name * * Sets \p *pStr to the address of a NULL-terminated string representation * of the name of the enum error code \p error. * If the error code is not recognized, ::CUDA_ERROR_INVALID_VALUE * will be returned and \p *pStr will be set to the NULL address. * * \param error - Error code to convert to string * \param pStr - Address of the string pointer. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::CUresult, * ::cudaGetErrorName */ CUresult CUDAAPI cuGetErrorName(CUresult error, const char **pStr); /** @} */ /* END CUDA_ERROR */ /** * \defgroup CUDA_INITIALIZE Initialization * * ___MANBRIEF___ initialization functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the initialization functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Initialize the CUDA driver API * * Initializes the driver API and must be called before any other function from * the driver API. Currently, the \p Flags parameter must be 0. If ::cuInit() * has not been called, any function from the driver API will return * ::CUDA_ERROR_NOT_INITIALIZED. * * \param Flags - Initialization flag for CUDA. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_SYSTEM_DRIVER_MISMATCH, * ::CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE * \notefnerr */ CUresult CUDAAPI cuInit(unsigned int Flags); /** @} */ /* END CUDA_INITIALIZE */ /** * \defgroup CUDA_VERSION Version Management * * ___MANBRIEF___ version management functions of the low-level CUDA driver * API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the version management functions of the low-level * CUDA driver application programming interface. * * @{ */ /** * \brief Returns the latest CUDA version supported by driver * * Returns in \p *driverVersion the version of CUDA supported by * the driver. The version is returned as * (1000 &times; major + 10 &times; minor). For example, CUDA 9.2 * would be represented by 9020. * * This function automatically returns ::CUDA_ERROR_INVALID_VALUE if * \p driverVersion is NULL. * * \param driverVersion - Returns the CUDA driver version * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa * ::cudaDriverGetVersion, * ::cudaRuntimeGetVersion */ CUresult CUDAAPI cuDriverGetVersion(int *driverVersion); /** @} */ /* END CUDA_VERSION */ /** * \defgroup CUDA_DEVICE Device Management * * ___MANBRIEF___ device management functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the device management functions of the low-level * CUDA driver application programming interface. * * @{ */ /** * \brief Returns a handle to a compute device * * Returns in \p *device a device handle given an ordinal in the range <b>[0, * ::cuDeviceGetCount()-1]</b>. * * \param device - Returned device handle * \param ordinal - Device number to get handle for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetAttribute, * ::cuDeviceGetCount, * ::cuDeviceGetName, * ::cuDeviceGetUuid, * ::cuDeviceGetLuid, * ::cuDeviceTotalMem, * ::cuDeviceGetExecAffinitySupport */ CUresult CUDAAPI cuDeviceGet(CUdevice *device, int ordinal); /** * \brief Returns the number of compute-capable devices * * Returns in \p *count the number of devices with compute capability greater * than or equal to 2.0 that are available for execution. If there is no such * device, ::cuDeviceGetCount() returns 0. * * \param count - Returned number of compute-capable devices * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa * ::cuDeviceGetAttribute, * ::cuDeviceGetName, * ::cuDeviceGetUuid, * ::cuDeviceGetLuid, * ::cuDeviceGet, * ::cuDeviceTotalMem, * ::cuDeviceGetExecAffinitySupport, * ::cudaGetDeviceCount */ CUresult CUDAAPI cuDeviceGetCount(int *count); /** * \brief Returns an identifer string for the device * * Returns an ASCII string identifying the device \p dev in the NULL-terminated * string pointed to by \p name. \p len specifies the maximum length of the * string that may be returned. * * \param name - Returned identifier string for the device * \param len - Maximum length of string to store in \p name * \param dev - Device to get identifier string for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetAttribute, * ::cuDeviceGetUuid, * ::cuDeviceGetLuid, * ::cuDeviceGetCount, * ::cuDeviceGet, * ::cuDeviceTotalMem, * ::cuDeviceGetExecAffinitySupport, * ::cudaGetDeviceProperties */ CUresult CUDAAPI cuDeviceGetName(char *name, int len, CUdevice dev); /** * \brief Return an UUID for the device * * Note there is a later version of this API, ::cuDeviceGetUuid_v2. It will * supplant this version in 12.0, which is retained for minor version compatibility. * * Returns 16-octets identifing the device \p dev in the structure * pointed by the \p uuid. * * \param uuid - Returned UUID * \param dev - Device to get identifier string for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetUuid_v2 * ::cuDeviceGetAttribute, * ::cuDeviceGetCount, * ::cuDeviceGetName, * ::cuDeviceGetLuid, * ::cuDeviceGet, * ::cuDeviceTotalMem, * ::cuDeviceGetExecAffinitySupport, * ::cudaGetDeviceProperties */ CUresult CUDAAPI cuDeviceGetUuid(CUuuid *uuid, CUdevice dev); /** * \brief Return an UUID for the device (11.4+) * * Returns 16-octets identifing the device \p dev in the structure * pointed by the \p uuid. If the device is in MIG mode, returns its * MIG UUID which uniquely identifies the subscribed MIG compute instance. * * \param uuid - Returned UUID * \param dev - Device to get identifier string for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetAttribute, * ::cuDeviceGetCount, * ::cuDeviceGetName, * ::cuDeviceGetLuid, * ::cuDeviceGet, * ::cuDeviceTotalMem, * ::cudaGetDeviceProperties */ CUresult CUDAAPI cuDeviceGetUuid_v2(CUuuid *uuid, CUdevice dev); /** * \brief Return an LUID and device node mask for the device * * Return identifying information (\p luid and \p deviceNodeMask) to allow * matching device with graphics APIs. * * \param luid - Returned LUID * \param deviceNodeMask - Returned device node mask * \param dev - Device to get identifier string for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetAttribute, * ::cuDeviceGetCount, * ::cuDeviceGetName, * ::cuDeviceGet, * ::cuDeviceTotalMem, * ::cuDeviceGetExecAffinitySupport, * ::cudaGetDeviceProperties */ CUresult CUDAAPI cuDeviceGetLuid(char *luid, unsigned int *deviceNodeMask, CUdevice dev); /** * \brief Returns the total amount of memory on the device * * Returns in \p *bytes the total amount of memory available on the device * \p dev in bytes. * * \param bytes - Returned memory available on device in bytes * \param dev - Device handle * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetAttribute, * ::cuDeviceGetCount, * ::cuDeviceGetName, * ::cuDeviceGetUuid, * ::cuDeviceGet, * ::cuDeviceGetExecAffinitySupport, * ::cudaMemGetInfo */ CUresult CUDAAPI cuDeviceTotalMem(size_t *bytes, CUdevice dev); /** * \brief Returns the maximum number of elements allocatable in a 1D linear texture for a given texture element size. * * Returns in \p maxWidthInElements the maximum number of texture elements allocatable in a 1D linear texture * for given \p format and \p numChannels. * * \param maxWidthInElements - Returned maximum number of texture elements allocatable for given \p format and \p numChannels. * \param format - Texture format. * \param numChannels - Number of channels per texture element. * \param dev - Device handle. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetAttribute, * ::cuDeviceGetCount, * ::cuDeviceGetName, * ::cuDeviceGetUuid, * ::cuDeviceGet, * ::cudaMemGetInfo, * ::cuDeviceTotalMem */ CUresult CUDAAPI cuDeviceGetTexture1DLinearMaxWidth(size_t *maxWidthInElements, CUarray_format format, unsigned numChannels, CUdevice dev); /** * \brief Returns information about the device * * Returns in \p *pi the integer value of the attribute \p attrib on device * \p dev. The supported attributes are: * - ::CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK: Maximum number of threads per * block; * - ::CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X: Maximum x-dimension of a block * - ::CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y: Maximum y-dimension of a block * - ::CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z: Maximum z-dimension of a block * - ::CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X: Maximum x-dimension of a grid * - ::CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y: Maximum y-dimension of a grid * - ::CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z: Maximum z-dimension of a grid * - ::CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK: Maximum amount of * shared memory available to a thread block in bytes * - ::CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY: Memory available on device for * __constant__ variables in a CUDA C kernel in bytes * - ::CU_DEVICE_ATTRIBUTE_WARP_SIZE: Warp size in threads * - ::CU_DEVICE_ATTRIBUTE_MAX_PITCH: Maximum pitch in bytes allowed by the * memory copy functions that involve memory regions allocated through * ::cuMemAllocPitch() * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH: Maximum 1D * texture width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH: Maximum width * for a 1D texture bound to linear memory * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH: Maximum * mipmapped 1D texture width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH: Maximum 2D * texture width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT: Maximum 2D * texture height * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH: Maximum width * for a 2D texture bound to linear memory * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT: Maximum height * for a 2D texture bound to linear memory * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH: Maximum pitch * in bytes for a 2D texture bound to linear memory * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH: Maximum * mipmapped 2D texture width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT: Maximum * mipmapped 2D texture height * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH: Maximum 3D * texture width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT: Maximum 3D * texture height * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH: Maximum 3D * texture depth * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE: * Alternate maximum 3D texture width, 0 if no alternate * maximum 3D texture size is supported * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE: * Alternate maximum 3D texture height, 0 if no alternate * maximum 3D texture size is supported * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE: * Alternate maximum 3D texture depth, 0 if no alternate * maximum 3D texture size is supported * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH: * Maximum cubemap texture width or height * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH: * Maximum 1D layered texture width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS: * Maximum layers in a 1D layered texture * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH: * Maximum 2D layered texture width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT: * Maximum 2D layered texture height * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS: * Maximum layers in a 2D layered texture * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH: * Maximum cubemap layered texture width or height * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS: * Maximum layers in a cubemap layered texture * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH: * Maximum 1D surface width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH: * Maximum 2D surface width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT: * Maximum 2D surface height * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH: * Maximum 3D surface width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT: * Maximum 3D surface height * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH: * Maximum 3D surface depth * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH: * Maximum 1D layered surface width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS: * Maximum layers in a 1D layered surface * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH: * Maximum 2D layered surface width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT: * Maximum 2D layered surface height * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS: * Maximum layers in a 2D layered surface * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH: * Maximum cubemap surface width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH: * Maximum cubemap layered surface width * - ::CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS: * Maximum layers in a cubemap layered surface * - ::CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK: Maximum number of 32-bit * registers available to a thread block * - ::CU_DEVICE_ATTRIBUTE_CLOCK_RATE: The typical clock frequency in kilohertz * - ::CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT: Alignment requirement; texture * base addresses aligned to ::textureAlign bytes do not need an offset * applied to texture fetches * - ::CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT: Pitch alignment requirement * for 2D texture references bound to pitched memory * - ::CU_DEVICE_ATTRIBUTE_GPU_OVERLAP: 1 if the device can concurrently copy * memory between host and device while executing a kernel, or 0 if not * - ::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT: Number of multiprocessors on * the device * - ::CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT: 1 if there is a run time limit * for kernels executed on the device, or 0 if not * - ::CU_DEVICE_ATTRIBUTE_INTEGRATED: 1 if the device is integrated with the * memory subsystem, or 0 if not * - ::CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY: 1 if the device can map host * memory into the CUDA address space, or 0 if not * - ::CU_DEVICE_ATTRIBUTE_COMPUTE_MODE: Compute mode that device is currently * in. Available modes are as follows: * - ::CU_COMPUTEMODE_DEFAULT: Default mode - Device is not restricted and * can have multiple CUDA contexts present at a single time. * - ::CU_COMPUTEMODE_PROHIBITED: Compute-prohibited mode - Device is * prohibited from creating new CUDA contexts. * - ::CU_COMPUTEMODE_EXCLUSIVE_PROCESS: Compute-exclusive-process mode - Device * can have only one context used by a single process at a time. * - ::CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS: 1 if the device supports * executing multiple kernels within the same context simultaneously, or 0 if * not. It is not guaranteed that multiple kernels will be resident * on the device concurrently so this feature should not be relied upon for * correctness. * - ::CU_DEVICE_ATTRIBUTE_ECC_ENABLED: 1 if error correction is enabled on the * device, 0 if error correction is disabled or not supported by the device * - ::CU_DEVICE_ATTRIBUTE_PCI_BUS_ID: PCI bus identifier of the device * - ::CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID: PCI device (also known as slot) identifier * of the device * - ::CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID: PCI domain identifier of the device * - ::CU_DEVICE_ATTRIBUTE_TCC_DRIVER: 1 if the device is using a TCC driver. TCC * is only available on Tesla hardware running Windows Vista or later * - ::CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE: Peak memory clock frequency in kilohertz * - ::CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH: Global memory bus width in bits * - ::CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE: Size of L2 cache in bytes. 0 if the device doesn't have L2 cache * - ::CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR: Maximum resident threads per multiprocessor * - ::CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING: 1 if the device shares a unified address space with * the host, or 0 if not * - ::CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR: Major compute capability version number * - ::CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR: Minor compute capability version number * - ::CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED: 1 if device supports caching globals * in L1 cache, 0 if caching globals in L1 cache is not supported by the device * - ::CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED: 1 if device supports caching locals * in L1 cache, 0 if caching locals in L1 cache is not supported by the device * - ::CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR: Maximum amount of * shared memory available to a multiprocessor in bytes; this amount is shared * by all thread blocks simultaneously resident on a multiprocessor * - ::CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR: Maximum number of 32-bit * registers available to a multiprocessor; this number is shared by all thread * blocks simultaneously resident on a multiprocessor * - ::CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY: 1 if device supports allocating managed memory * on this system, 0 if allocating managed memory is not supported by the device on this system. * - ::CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD: 1 if device is on a multi-GPU board, 0 if not. * - ::CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID: Unique identifier for a group of devices * associated with the same board. Devices on the same multi-GPU board will share the same identifier. * - ::CU_DEVICE_ATTRIBUTE_HOST_NATIVE_ATOMIC_SUPPORTED: 1 if Link between the device and the host * supports native atomic operations. * - ::CU_DEVICE_ATTRIBUTE_SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO: Ratio of single precision performance * (in floating-point operations per second) to double precision performance. * - ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS: Device suppports coherently accessing * pageable memory without calling cudaHostRegister on it. * - ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS: Device can coherently access managed memory * concurrently with the CPU. * - ::CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED: Device supports Compute Preemption. * - ::CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM: Device can access host registered * memory at the same virtual address as the CPU. * - ::CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN: The maximum per block shared memory size * suported on this device. This is the maximum value that can be opted into when using the cuFuncSetAttribute() call. * For more details see ::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES * - ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES: Device accesses pageable memory via the host's * page tables. * - ::CU_DEVICE_ATTRIBUTE_DIRECT_MANAGED_MEM_ACCESS_FROM_HOST: The host can directly access managed memory on the device without migration. * - ::CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED: Device supports virtual memory management APIs like ::cuMemAddressReserve, ::cuMemCreate, ::cuMemMap and related APIs * - ::CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR_SUPPORTED: Device supports exporting memory to a posix file descriptor with ::cuMemExportToShareableHandle, if requested via ::cuMemCreate * - ::CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_WIN32_HANDLE_SUPPORTED: Device supports exporting memory to a Win32 NT handle with ::cuMemExportToShareableHandle, if requested via ::cuMemCreate * - ::CU_DEVICE_ATTRIBUTE_HANDLE_TYPE_WIN32_KMT_HANDLE_SUPPORTED: Device supports exporting memory to a Win32 KMT handle with ::cuMemExportToShareableHandle, if requested via ::cuMemCreate * - ::CU_DEVICE_ATTRIBUTE_MAX_BLOCKS_PER_MULTIPROCESSOR: Maximum number of thread blocks that can reside on a multiprocessor * - ::CU_DEVICE_ATTRIBUTE_GENERIC_COMPRESSION_SUPPORTED: Device supports compressible memory allocation via ::cuMemCreate * - ::CU_DEVICE_ATTRIBUTE_MAX_PERSISTING_L2_CACHE_SIZE: Maximum L2 persisting lines capacity setting in bytes * - ::CU_DEVICE_ATTRIBUTE_MAX_ACCESS_POLICY_WINDOW_SIZE: Maximum value of CUaccessPolicyWindow::num_bytes * - ::CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WITH_CUDA_VMM_SUPPORTED: Device supports specifying the GPUDirect RDMA flag with ::cuMemCreate. * - ::CU_DEVICE_ATTRIBUTE_RESERVED_SHARED_MEMORY_PER_BLOCK: Amount of shared memory per block reserved by CUDA driver in bytes * - ::CU_DEVICE_ATTRIBUTE_SPARSE_CUDA_ARRAY_SUPPORTED: Device supports sparse CUDA arrays and sparse CUDA mipmapped arrays. * - ::CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED: Device supports using the ::cuMemHostRegister flag ::CU_MEMHOSTERGISTER_READ_ONLY to register memory that must be mapped as read-only to the GPU * - ::CU_DEVICE_ATTRIBUTE_MEMORY_POOLS_SUPPORTED: Device supports using the ::cuMemAllocAsync and ::cuMemPool family of APIs * - ::CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_SUPPORTED: Device supports GPUDirect RDMA APIs, like nvidia_p2p_get_pages (see https://docs.nvidia.com/cuda/gpudirect-rdma for more information) * - ::CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_FLUSH_WRITES_OPTIONS: The returned attribute shall be interpreted as a bitmask, where the individual bits are described by the ::CUflushGPUDirectRDMAWritesOptions enum * - ::CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WRITES_ORDERING: GPUDirect RDMA writes to the device do not need to be flushed for consumers within the scope indicated by the returned attribute. See ::CUGPUDirectRDMAWritesOrdering for the numerical values returned here. * - ::CU_DEVICE_ATTRIBUTE_MEMPOOL_SUPPORTED_HANDLE_TYPES: Bitmask of handle types supported with mempool based IPC * - ::CU_DEVICE_ATTRIBUTE_DEFERRED_MAPPING_CUDA_ARRAY_SUPPORTED: Device supports deferred mapping CUDA arrays and CUDA mipmapped arrays. * * \param pi - Returned device attribute value * \param attrib - Device attribute to query * \param dev - Device handle * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetCount, * ::cuDeviceGetName, * ::cuDeviceGetUuid, * ::cuDeviceGet, * ::cuDeviceTotalMem, * ::cuDeviceGetExecAffinitySupport, * ::cudaDeviceGetAttribute, * ::cudaGetDeviceProperties */ CUresult CUDAAPI cuDeviceGetAttribute(int *pi, CUdevice_attribute attrib, CUdevice dev); /** * \brief Return NvSciSync attributes that this device can support. * * Returns in \p nvSciSyncAttrList, the properties of NvSciSync that * this CUDA device, \p dev can support. The returned \p nvSciSyncAttrList * can be used to create an NvSciSync object that matches this device's capabilities. * * If NvSciSyncAttrKey_RequiredPerm field in \p nvSciSyncAttrList is * already set this API will return ::CUDA_ERROR_INVALID_VALUE. * * The applications should set \p nvSciSyncAttrList to a valid * NvSciSyncAttrList failing which this API will return * ::CUDA_ERROR_INVALID_HANDLE. * * The \p flags controls how applications intends to use * the NvSciSync created from the \p nvSciSyncAttrList. The valid flags are: * - ::CUDA_NVSCISYNC_ATTR_SIGNAL, specifies that the applications intends to * signal an NvSciSync on this CUDA device. * - ::CUDA_NVSCISYNC_ATTR_WAIT, specifies that the applications intends to * wait on an NvSciSync on this CUDA device. * * At least one of these flags must be set, failing which the API * returns ::CUDA_ERROR_INVALID_VALUE. Both the flags are orthogonal * to one another: a developer may set both these flags that allows to * set both wait and signal specific attributes in the same \p nvSciSyncAttrList. * * \param nvSciSyncAttrList - Return NvSciSync attributes supported. * \param dev - Valid Cuda Device to get NvSciSync attributes for. * \param flags - flags describing NvSciSync usage. * * \return * * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_OUT_OF_MEMORY * * \sa * ::cuImportExternalSemaphore, * ::cuDestroyExternalSemaphore, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync */ CUresult CUDAAPI cuDeviceGetNvSciSyncAttributes(void *nvSciSyncAttrList, CUdevice dev, int flags); /** * \brief Sets the current memory pool of a device * * The memory pool must be local to the specified device. * ::cuMemAllocAsync allocates from the current mempool of the provided stream's device. * By default, a device's current memory pool is its default memory pool. * * \note Use ::cuMemAllocFromPoolAsync to specify asynchronous allocations from a device different * than the one the stream runs on. * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuDeviceGetDefaultMemPool, ::cuDeviceGetMemPool, ::cuMemPoolCreate, ::cuMemPoolDestroy, ::cuMemAllocFromPoolAsync */ CUresult CUDAAPI cuDeviceSetMemPool(CUdevice dev, CUmemoryPool pool); /** * \brief Gets the current mempool for a device * * Returns the last pool provided to ::cuDeviceSetMemPool for this device * or the device's default memory pool if ::cuDeviceSetMemPool has never been called. * By default the current mempool is the default mempool for a device. * Otherwise the returned pool must have been set with ::cuDeviceSetMemPool. * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuDeviceGetDefaultMemPool, ::cuMemPoolCreate, ::cuDeviceSetMemPool */ CUresult CUDAAPI cuDeviceGetMemPool(CUmemoryPool *pool, CUdevice dev); /** * \brief Returns the default mempool of a device * * The default mempool of a device contains device memory from that device. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa ::cuMemAllocAsync, ::cuMemPoolTrimTo, ::cuMemPoolGetAttribute, ::cuMemPoolSetAttribute, cuMemPoolSetAccess, ::cuDeviceGetMemPool, ::cuMemPoolCreate */ CUresult CUDAAPI cuDeviceGetDefaultMemPool(CUmemoryPool *pool_out, CUdevice dev); /** * \brief Blocks until remote writes are visible to the specified scope * * Blocks until GPUDirect RDMA writes to the target context via mappings * created through APIs like nvidia_p2p_get_pages (see * https://docs.nvidia.com/cuda/gpudirect-rdma for more information), are * visible to the specified scope. * * If the scope equals or lies within the scope indicated by * ::CU_DEVICE_ATTRIBUTE_GPU_DIRECT_RDMA_WRITES_ORDERING, the call * will be a no-op and can be safely omitted for performance. This can be * determined by comparing the numerical values between the two enums, with * smaller scopes having smaller values. * * Users may query support for this API via * ::CU_DEVICE_ATTRIBUTE_FLUSH_FLUSH_GPU_DIRECT_RDMA_OPTIONS. * * \param target - The target of the operation, see ::CUflushGPUDirectRDMAWritesTarget * \param scope - The scope of the operation, see ::CUflushGPUDirectRDMAWritesScope * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * \notefnerr * */ CUresult CUDAAPI cuFlushGPUDirectRDMAWrites(CUflushGPUDirectRDMAWritesTarget target, CUflushGPUDirectRDMAWritesScope scope); /** @} */ /* END CUDA_DEVICE */ /** * \defgroup CUDA_DEVICE_DEPRECATED Device Management [DEPRECATED] * * ___MANBRIEF___ deprecated device management functions of the low-level CUDA * driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the device management functions of the low-level * CUDA driver application programming interface. * * @{ */ /** * \brief Returns properties for a selected device * * \deprecated * * This function was deprecated as of CUDA 5.0 and replaced by ::cuDeviceGetAttribute(). * * Returns in \p *prop the properties of device \p dev. The ::CUdevprop * structure is defined as: * * \code typedef struct CUdevprop_st { int maxThreadsPerBlock; int maxThreadsDim[3]; int maxGridSize[3]; int sharedMemPerBlock; int totalConstantMemory; int SIMDWidth; int memPitch; int regsPerBlock; int clockRate; int textureAlign } CUdevprop; * \endcode * where: * * - ::maxThreadsPerBlock is the maximum number of threads per block; * - ::maxThreadsDim[3] is the maximum sizes of each dimension of a block; * - ::maxGridSize[3] is the maximum sizes of each dimension of a grid; * - ::sharedMemPerBlock is the total amount of shared memory available per * block in bytes; * - ::totalConstantMemory is the total amount of constant memory available on * the device in bytes; * - ::SIMDWidth is the warp size; * - ::memPitch is the maximum pitch allowed by the memory copy functions that * involve memory regions allocated through ::cuMemAllocPitch(); * - ::regsPerBlock is the total number of registers available per block; * - ::clockRate is the clock frequency in kilohertz; * - ::textureAlign is the alignment requirement; texture base addresses that * are aligned to ::textureAlign bytes do not need an offset applied to * texture fetches. * * \param prop - Returned properties of device * \param dev - Device to get properties for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetAttribute, * ::cuDeviceGetCount, * ::cuDeviceGetName, * ::cuDeviceGetUuid, * ::cuDeviceGet, * ::cuDeviceTotalMem */ __CUDA_DEPRECATED CUresult CUDAAPI cuDeviceGetProperties(CUdevprop *prop, CUdevice dev); /** * \brief Returns the compute capability of the device * * \deprecated * * This function was deprecated as of CUDA 5.0 and its functionality superceded * by ::cuDeviceGetAttribute(). * * Returns in \p *major and \p *minor the major and minor revision numbers that * define the compute capability of the device \p dev. * * \param major - Major revision number * \param minor - Minor revision number * \param dev - Device handle * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetAttribute, * ::cuDeviceGetCount, * ::cuDeviceGetName, * ::cuDeviceGetUuid, * ::cuDeviceGet, * ::cuDeviceTotalMem */ __CUDA_DEPRECATED CUresult CUDAAPI cuDeviceComputeCapability(int *major, int *minor, CUdevice dev); /** @} */ /* END CUDA_DEVICE_DEPRECATED */ /** * \defgroup CUDA_PRIMARY_CTX Primary Context Management * * ___MANBRIEF___ primary context management functions of the low-level CUDA driver * API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the primary context management functions of the low-level * CUDA driver application programming interface. * * The primary context is unique per device and shared with the CUDA runtime API. * These functions allow integration with other libraries using CUDA. * * @{ */ /** * \brief Retain the primary context on the GPU * * Retains the primary context on the device. * Once the user successfully retains the primary context, the primary context * will be active and available to the user until the user releases it * with ::cuDevicePrimaryCtxRelease() or resets it with ::cuDevicePrimaryCtxReset(). * Unlike ::cuCtxCreate() the newly retained context is not pushed onto the stack. * * Retaining the primary context for the first time will fail with ::CUDA_ERROR_UNKNOWN * if the compute mode of the device is ::CU_COMPUTEMODE_PROHIBITED. The function * ::cuDeviceGetAttribute() can be used with ::CU_DEVICE_ATTRIBUTE_COMPUTE_MODE to * determine the compute mode of the device. * The <i>nvidia-smi</i> tool can be used to set the compute mode for * devices. Documentation for <i>nvidia-smi</i> can be obtained by passing a * -h option to it. * * Please note that the primary context always supports pinned allocations. Other * flags can be specified by ::cuDevicePrimaryCtxSetFlags(). * * \param pctx - Returned context handle of the new context * \param dev - Device for which primary context is requested * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa ::cuDevicePrimaryCtxRelease, * ::cuDevicePrimaryCtxSetFlags, * ::cuCtxCreate, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize */ CUresult CUDAAPI cuDevicePrimaryCtxRetain(CUcontext *pctx, CUdevice dev); /** * \brief Release the primary context on the GPU * * Releases the primary context interop on the device. * A retained context should always be released once the user is done using * it. The context is automatically reset once the last reference to it is * released. This behavior is different when the primary context was retained * by the CUDA runtime from CUDA 4.0 and earlier. In this case, the primary * context remains always active. * * Releasing a primary context that has not been previously retained will * fail with ::CUDA_ERROR_INVALID_CONTEXT. * * Please note that unlike ::cuCtxDestroy() this method does not pop the context * from stack in any circumstances. * * \param dev - Device which primary context is released * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_INVALID_CONTEXT * \notefnerr * * \sa ::cuDevicePrimaryCtxRetain, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize */ CUresult CUDAAPI cuDevicePrimaryCtxRelease(CUdevice dev); /** * \brief Set flags for the primary context * * Sets the flags for the primary context on the device overwriting perviously * set ones. * * The three LSBs of the \p flags parameter can be used to control how the OS * thread, which owns the CUDA context at the time of an API call, interacts * with the OS scheduler when waiting for results from the GPU. Only one of * the scheduling flags can be set when creating a context. * * - ::CU_CTX_SCHED_SPIN: Instruct CUDA to actively spin when waiting for * results from the GPU. This can decrease latency when waiting for the GPU, * but may lower the performance of CPU threads if they are performing work in * parallel with the CUDA thread. * * - ::CU_CTX_SCHED_YIELD: Instruct CUDA to yield its thread when waiting for * results from the GPU. This can increase latency when waiting for the GPU, * but can increase the performance of CPU threads performing work in parallel * with the GPU. * * - ::CU_CTX_SCHED_BLOCKING_SYNC: Instruct CUDA to block the CPU thread on a * synchronization primitive when waiting for the GPU to finish work. * * - ::CU_CTX_BLOCKING_SYNC: Instruct CUDA to block the CPU thread on a * synchronization primitive when waiting for the GPU to finish work. <br> * <b>Deprecated:</b> This flag was deprecated as of CUDA 4.0 and was * replaced with ::CU_CTX_SCHED_BLOCKING_SYNC. * * - ::CU_CTX_SCHED_AUTO: The default value if the \p flags parameter is zero, * uses a heuristic based on the number of active CUDA contexts in the * process \e C and the number of logical processors in the system \e P. If * \e C > \e P, then CUDA will yield to other OS threads when waiting for * the GPU (::CU_CTX_SCHED_YIELD), otherwise CUDA will not yield while * waiting for results and actively spin on the processor (::CU_CTX_SCHED_SPIN). * Additionally, on Tegra devices, ::CU_CTX_SCHED_AUTO uses a heuristic based on * the power profile of the platform and may choose ::CU_CTX_SCHED_BLOCKING_SYNC * for low-powered devices. * * - ::CU_CTX_LMEM_RESIZE_TO_MAX: Instruct CUDA to not reduce local memory * after resizing local memory for a kernel. This can prevent thrashing by * local memory allocations when launching many kernels with high local * memory usage at the cost of potentially increased memory usage. <br> * <b>Deprecated:</b> This flag is deprecated and the behavior enabled * by this flag is now the default and cannot be disabled. * * \param dev - Device for which the primary context flags are set * \param flags - New flags for the device * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_INVALID_VALUE, * \notefnerr * * \sa ::cuDevicePrimaryCtxRetain, * ::cuDevicePrimaryCtxGetState, * ::cuCtxCreate, * ::cuCtxGetFlags, * ::cudaSetDeviceFlags */ CUresult CUDAAPI cuDevicePrimaryCtxSetFlags(CUdevice dev, unsigned int flags); /** * \brief Get the state of the primary context * * Returns in \p *flags the flags for the primary context of \p dev, and in * \p *active whether it is active. See ::cuDevicePrimaryCtxSetFlags for flag * values. * * \param dev - Device to get primary context flags for * \param flags - Pointer to store flags * \param active - Pointer to store context state; 0 = inactive, 1 = active * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_INVALID_VALUE, * \notefnerr * * \sa * ::cuDevicePrimaryCtxSetFlags, * ::cuCtxGetFlags, * ::cudaGetDeviceFlags */ CUresult CUDAAPI cuDevicePrimaryCtxGetState(CUdevice dev, unsigned int *flags, int *active); /** * \brief Destroy all allocations and reset all state on the primary context * * Explicitly destroys and cleans up all resources associated with the current * device in the current process. * * Note that it is responsibility of the calling function to ensure that no * other module in the process is using the device any more. For that reason * it is recommended to use ::cuDevicePrimaryCtxRelease() in most cases. * However it is safe for other modules to call ::cuDevicePrimaryCtxRelease() * even after resetting the device. * Resetting the primary context does not release it, an application that has * retained the primary context should explicitly release its usage. * * \param dev - Device for which primary context is destroyed * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE * \notefnerr * * \sa ::cuDevicePrimaryCtxRetain, * ::cuDevicePrimaryCtxRelease, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize, * ::cudaDeviceReset */ CUresult CUDAAPI cuDevicePrimaryCtxReset(CUdevice dev); /** @} */ /* END CUDA_PRIMARY_CTX */ /** * \brief Returns information about the execution affinity support of the device. * * Returns in \p *pi whether execution affinity type \p type is supported by device \p dev. * The supported types are: * - ::CU_EXEC_AFFINITY_TYPE_SM_COUNT: 1 if context with limited SMs is supported by the device, * or 0 if not; * * \param pi - 1 if the execution affinity type \p type is supported by the device, or 0 if not * \param type - Execution affinity type to query * \param dev - Device handle * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGetAttribute, * ::cuDeviceGetCount, * ::cuDeviceGetName, * ::cuDeviceGetUuid, * ::cuDeviceGet, * ::cuDeviceTotalMem */ CUresult CUDAAPI cuDeviceGetExecAffinitySupport(int *pi, CUexecAffinityType type, CUdevice dev); /** * \defgroup CUDA_CTX Context Management * * ___MANBRIEF___ context management functions of the low-level CUDA driver * API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the context management functions of the low-level * CUDA driver application programming interface. * * Please note that some functions are described in * \ref CUDA_PRIMARY_CTX "Primary Context Management" section. * * @{ */ /** * \brief Create a CUDA context * * \note In most cases it is recommended to use ::cuDevicePrimaryCtxRetain. * * Creates a new CUDA context and associates it with the calling thread. The * \p flags parameter is described below. The context is created with a usage * count of 1 and the caller of ::cuCtxCreate() must call ::cuCtxDestroy() or * when done using the context. If a context is already current to the thread, * it is supplanted by the newly created context and may be restored by a subsequent * call to ::cuCtxPopCurrent(). * * The three LSBs of the \p flags parameter can be used to control how the OS * thread, which owns the CUDA context at the time of an API call, interacts * with the OS scheduler when waiting for results from the GPU. Only one of * the scheduling flags can be set when creating a context. * * - ::CU_CTX_SCHED_SPIN: Instruct CUDA to actively spin when waiting for * results from the GPU. This can decrease latency when waiting for the GPU, * but may lower the performance of CPU threads if they are performing work in * parallel with the CUDA thread. * * - ::CU_CTX_SCHED_YIELD: Instruct CUDA to yield its thread when waiting for * results from the GPU. This can increase latency when waiting for the GPU, * but can increase the performance of CPU threads performing work in parallel * with the GPU. * * - ::CU_CTX_SCHED_BLOCKING_SYNC: Instruct CUDA to block the CPU thread on a * synchronization primitive when waiting for the GPU to finish work. * * - ::CU_CTX_BLOCKING_SYNC: Instruct CUDA to block the CPU thread on a * synchronization primitive when waiting for the GPU to finish work. <br> * <b>Deprecated:</b> This flag was deprecated as of CUDA 4.0 and was * replaced with ::CU_CTX_SCHED_BLOCKING_SYNC. * * - ::CU_CTX_SCHED_AUTO: The default value if the \p flags parameter is zero, * uses a heuristic based on the number of active CUDA contexts in the * process \e C and the number of logical processors in the system \e P. If * \e C > \e P, then CUDA will yield to other OS threads when waiting for * the GPU (::CU_CTX_SCHED_YIELD), otherwise CUDA will not yield while * waiting for results and actively spin on the processor (::CU_CTX_SCHED_SPIN). * Additionally, on Tegra devices, ::CU_CTX_SCHED_AUTO uses a heuristic based on * the power profile of the platform and may choose ::CU_CTX_SCHED_BLOCKING_SYNC * for low-powered devices. * * - ::CU_CTX_MAP_HOST: Instruct CUDA to support mapped pinned allocations. * This flag must be set in order to allocate pinned host memory that is * accessible to the GPU. * * - ::CU_CTX_LMEM_RESIZE_TO_MAX: Instruct CUDA to not reduce local memory * after resizing local memory for a kernel. This can prevent thrashing by * local memory allocations when launching many kernels with high local * memory usage at the cost of potentially increased memory usage. <br> * <b>Deprecated:</b> This flag is deprecated and the behavior enabled * by this flag is now the default and cannot be disabled. * Instead, the per-thread stack size can be controlled with ::cuCtxSetLimit(). * * Context creation will fail with ::CUDA_ERROR_UNKNOWN if the compute mode of * the device is ::CU_COMPUTEMODE_PROHIBITED. The function ::cuDeviceGetAttribute() * can be used with ::CU_DEVICE_ATTRIBUTE_COMPUTE_MODE to determine the * compute mode of the device. The <i>nvidia-smi</i> tool can be used to set * the compute mode for * devices. * Documentation for <i>nvidia-smi</i> can be obtained by passing a * -h option to it. * * \param pctx - Returned context handle of the new context * \param flags - Context creation flags * \param dev - Device to create context on * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize */ CUresult CUDAAPI cuCtxCreate(CUcontext *pctx, unsigned int flags, CUdevice dev); /** * \brief Create a CUDA context with execution affinity * * Creates a new CUDA context with execution affinity and associates it with * the calling thread. The \p paramsArray and \p flags parameter are described below. * The context is created with a usage count of 1 and the caller of ::cuCtxCreate() must * call ::cuCtxDestroy() or when done using the context. If a context is already * current to the thread, it is supplanted by the newly created context and may * be restored by a subsequent call to ::cuCtxPopCurrent(). * * The type and the amount of execution resource the context can use is limited by \p paramsArray * and \p numParams. The \p paramsArray is an array of \p CUexecAffinityParam and the \p numParams * describes the size of the array. If two \p CUexecAffinityParam in the array have the same type, * the latter execution affinity parameter overrides the former execution affinity parameter. * The supported execution affinity types are: * - ::CU_EXEC_AFFINITY_TYPE_SM_COUNT limits the portion of SMs that the context can use. The portion * of SMs is specified as the number of SMs via \p CUexecAffinitySmCount. This limit will be internally * rounded up to the next hardware-supported amount. Hence, it is imperative to query the actual execution * affinity of the context via \p cuCtxGetExecAffinity after context creation. Currently, this attribute * is only supported under Volta+ MPS. * * The three LSBs of the \p flags parameter can be used to control how the OS * thread, which owns the CUDA context at the time of an API call, interacts * with the OS scheduler when waiting for results from the GPU. Only one of * the scheduling flags can be set when creating a context. * * - ::CU_CTX_SCHED_SPIN: Instruct CUDA to actively spin when waiting for * results from the GPU. This can decrease latency when waiting for the GPU, * but may lower the performance of CPU threads if they are performing work in * parallel with the CUDA thread. * * - ::CU_CTX_SCHED_YIELD: Instruct CUDA to yield its thread when waiting for * results from the GPU. This can increase latency when waiting for the GPU, * but can increase the performance of CPU threads performing work in parallel * with the GPU. * * - ::CU_CTX_SCHED_BLOCKING_SYNC: Instruct CUDA to block the CPU thread on a * synchronization primitive when waiting for the GPU to finish work. * * - ::CU_CTX_BLOCKING_SYNC: Instruct CUDA to block the CPU thread on a * synchronization primitive when waiting for the GPU to finish work. <br> * <b>Deprecated:</b> This flag was deprecated as of CUDA 4.0 and was * replaced with ::CU_CTX_SCHED_BLOCKING_SYNC. * * - ::CU_CTX_SCHED_AUTO: The default value if the \p flags parameter is zero, * uses a heuristic based on the number of active CUDA contexts in the * process \e C and the number of logical processors in the system \e P. If * \e C > \e P, then CUDA will yield to other OS threads when waiting for * the GPU (::CU_CTX_SCHED_YIELD), otherwise CUDA will not yield while * waiting for results and actively spin on the processor (::CU_CTX_SCHED_SPIN). * Additionally, on Tegra devices, ::CU_CTX_SCHED_AUTO uses a heuristic based on * the power profile of the platform and may choose ::CU_CTX_SCHED_BLOCKING_SYNC * for low-powered devices. * * - ::CU_CTX_MAP_HOST: Instruct CUDA to support mapped pinned allocations. * This flag must be set in order to allocate pinned host memory that is * accessible to the GPU. * * - ::CU_CTX_LMEM_RESIZE_TO_MAX: Instruct CUDA to not reduce local memory * after resizing local memory for a kernel. This can prevent thrashing by * local memory allocations when launching many kernels with high local * memory usage at the cost of potentially increased memory usage. <br> * <b>Deprecated:</b> This flag is deprecated and the behavior enabled * by this flag is now the default and cannot be disabled. * Instead, the per-thread stack size can be controlled with ::cuCtxSetLimit(). * * Context creation will fail with ::CUDA_ERROR_UNKNOWN if the compute mode of * the device is ::CU_COMPUTEMODE_PROHIBITED. The function ::cuDeviceGetAttribute() * can be used with ::CU_DEVICE_ATTRIBUTE_COMPUTE_MODE to determine the * compute mode of the device. The <i>nvidia-smi</i> tool can be used to set * the compute mode for * devices. * Documentation for <i>nvidia-smi</i> can be obtained by passing a * -h option to it. * * \param pctx - Returned context handle of the new context * \param paramsArray - Execution affinity parameters * \param numParams - Number of execution affinity parameters * \param flags - Context creation flags * \param dev - Device to create context on * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize, * ::CUexecAffinityParam */ CUresult CUDAAPI cuCtxCreate_v3(CUcontext *pctx, CUexecAffinityParam *paramsArray, int numParams, unsigned int flags, CUdevice dev); /** * \brief Destroy a CUDA context * * Destroys the CUDA context specified by \p ctx. The context \p ctx will be * destroyed regardless of how many threads it is current to. * It is the responsibility of the calling function to ensure that no API * call issues using \p ctx while ::cuCtxDestroy() is executing. * * Destroys and cleans up all resources associated with the context. * It is the caller's responsibility to ensure that the context or its resources * are not accessed or passed in subsequent API calls and doing so will result in undefined behavior. * These resources include CUDA types such as ::CUmodule, ::CUfunction, ::CUstream, ::CUevent, * ::CUarray, ::CUmipmappedArray, ::CUtexObject, ::CUsurfObject, ::CUtexref, ::CUsurfref, * ::CUgraphicsResource, ::CUlinkState, ::CUexternalMemory and ::CUexternalSemaphore. * * If \p ctx is current to the calling thread then \p ctx will also be * popped from the current thread's context stack (as though ::cuCtxPopCurrent() * were called). If \p ctx is current to other threads, then \p ctx will * remain current to those threads, and attempting to access \p ctx from * those threads will result in the error ::CUDA_ERROR_CONTEXT_IS_DESTROYED. * * \param ctx - Context to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize */ CUresult CUDAAPI cuCtxDestroy(CUcontext ctx); /** * \brief Pushes a context on the current CPU thread * * Pushes the given context \p ctx onto the CPU thread's stack of current * contexts. The specified context becomes the CPU thread's current context, so * all CUDA functions that operate on the current context are affected. * * The previous current context may be made current again by calling * ::cuCtxDestroy() or ::cuCtxPopCurrent(). * * \param ctx - Context to push * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize */ CUresult CUDAAPI cuCtxPushCurrent(CUcontext ctx); /** * \brief Pops the current CUDA context from the current CPU thread. * * Pops the current CUDA context from the CPU thread and passes back the * old context handle in \p *pctx. That context may then be made current * to a different CPU thread by calling ::cuCtxPushCurrent(). * * If a context was current to the CPU thread before ::cuCtxCreate() or * ::cuCtxPushCurrent() was called, this function makes that context current to * the CPU thread again. * * \param pctx - Returned popped context handle * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize */ CUresult CUDAAPI cuCtxPopCurrent(CUcontext *pctx); /** * \brief Binds the specified CUDA context to the calling CPU thread * * Binds the specified CUDA context to the calling CPU thread. * If \p ctx is NULL then the CUDA context previously bound to the * calling CPU thread is unbound and ::CUDA_SUCCESS is returned. * * If there exists a CUDA context stack on the calling CPU thread, this * will replace the top of that stack with \p ctx. * If \p ctx is NULL then this will be equivalent to popping the top * of the calling CPU thread's CUDA context stack (or a no-op if the * calling CPU thread's CUDA context stack is empty). * * \param ctx - Context to bind to the calling CPU thread * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT * \notefnerr * * \sa * ::cuCtxGetCurrent, * ::cuCtxCreate, * ::cuCtxDestroy, * ::cudaSetDevice */ CUresult CUDAAPI cuCtxSetCurrent(CUcontext ctx); /** * \brief Returns the CUDA context bound to the calling CPU thread. * * Returns in \p *pctx the CUDA context bound to the calling CPU thread. * If no context is bound to the calling CPU thread then \p *pctx is * set to NULL and ::CUDA_SUCCESS is returned. * * \param pctx - Returned context handle * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * \notefnerr * * \sa * ::cuCtxSetCurrent, * ::cuCtxCreate, * ::cuCtxDestroy, * ::cudaGetDevice */ CUresult CUDAAPI cuCtxGetCurrent(CUcontext *pctx); /** * \brief Returns the device ID for the current context * * Returns in \p *device the ordinal of the current context's device. * * \param device - Returned device ID for the current context * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize, * ::cudaGetDevice */ CUresult CUDAAPI cuCtxGetDevice(CUdevice *device); /** * \brief Returns the flags for the current context * * Returns in \p *flags the flags of the current context. See ::cuCtxCreate * for flag values. * * \param flags - Pointer to store flags of current context * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetCurrent, * ::cuCtxGetDevice, * ::cuCtxGetLimit, * ::cuCtxGetSharedMemConfig, * ::cuCtxGetStreamPriorityRange, * ::cudaGetDeviceFlags */ CUresult CUDAAPI cuCtxGetFlags(unsigned int *flags); /** * \brief Block for a context's tasks to complete * * Blocks until the device has completed all preceding requested tasks. * ::cuCtxSynchronize() returns an error if one of the preceding tasks failed. * If the context was created with the ::CU_CTX_SCHED_BLOCKING_SYNC flag, the * CPU thread will block until the GPU context has finished its work. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cudaDeviceSynchronize */ CUresult CUDAAPI cuCtxSynchronize(void); /** * \brief Set resource limits * * Setting \p limit to \p value is a request by the application to update * the current limit maintained by the context. The driver is free to * modify the requested value to meet h/w requirements (this could be * clamping to minimum or maximum values, rounding up to nearest element * size, etc). The application can use ::cuCtxGetLimit() to find out exactly * what the limit has been set to. * * Setting each ::CUlimit has its own specific restrictions, so each is * discussed here. * * - ::CU_LIMIT_STACK_SIZE controls the stack size in bytes of each GPU thread. * The driver automatically increases the per-thread stack size * for each kernel launch as needed. This size isn't reset back to the * original value after each launch. Setting this value will take effect * immediately, and if necessary, the device will block until all preceding * requested tasks are complete. * * - ::CU_LIMIT_PRINTF_FIFO_SIZE controls the size in bytes of the FIFO used * by the ::printf() device system call. Setting ::CU_LIMIT_PRINTF_FIFO_SIZE * must be performed before launching any kernel that uses the ::printf() * device system call, otherwise ::CUDA_ERROR_INVALID_VALUE will be returned. * * - ::CU_LIMIT_MALLOC_HEAP_SIZE controls the size in bytes of the heap used * by the ::malloc() and ::free() device system calls. Setting * ::CU_LIMIT_MALLOC_HEAP_SIZE must be performed before launching any kernel * that uses the ::malloc() or ::free() device system calls, otherwise * ::CUDA_ERROR_INVALID_VALUE will be returned. * * - ::CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH controls the maximum nesting depth of * a grid at which a thread can safely call ::cudaDeviceSynchronize(). Setting * this limit must be performed before any launch of a kernel that uses the * device runtime and calls ::cudaDeviceSynchronize() above the default sync * depth, two levels of grids. Calls to ::cudaDeviceSynchronize() will fail * with error code ::cudaErrorSyncDepthExceeded if the limitation is * violated. This limit can be set smaller than the default or up the maximum * launch depth of 24. When setting this limit, keep in mind that additional * levels of sync depth require the driver to reserve large amounts of device * memory which can no longer be used for user allocations. If these * reservations of device memory fail, ::cuCtxSetLimit() will return * ::CUDA_ERROR_OUT_OF_MEMORY, and the limit can be reset to a lower value. * This limit is only applicable to devices of compute capability 3.5 and * higher. Attempting to set this limit on devices of compute capability less * than 3.5 will result in the error ::CUDA_ERROR_UNSUPPORTED_LIMIT being * returned. * * - ::CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT controls the maximum number of * outstanding device runtime launches that can be made from the current * context. A grid is outstanding from the point of launch up until the grid * is known to have been completed. Device runtime launches which violate * this limitation fail and return ::cudaErrorLaunchPendingCountExceeded when * ::cudaGetLastError() is called after launch. If more pending launches than * the default (2048 launches) are needed for a module using the device * runtime, this limit can be increased. Keep in mind that being able to * sustain additional pending launches will require the driver to reserve * larger amounts of device memory upfront which can no longer be used for * allocations. If these reservations fail, ::cuCtxSetLimit() will return * ::CUDA_ERROR_OUT_OF_MEMORY, and the limit can be reset to a lower value. * This limit is only applicable to devices of compute capability 3.5 and * higher. Attempting to set this limit on devices of compute capability less * than 3.5 will result in the error ::CUDA_ERROR_UNSUPPORTED_LIMIT being * returned. * * - ::CU_LIMIT_MAX_L2_FETCH_GRANULARITY controls the L2 cache fetch granularity. * Values can range from 0B to 128B. This is purely a performence hint and * it can be ignored or clamped depending on the platform. * * - ::CU_LIMIT_PERSISTING_L2_CACHE_SIZE controls size in bytes availabe for * persisting L2 cache. This is purely a performance hint and it can be * ignored or clamped depending on the platform. * * \param limit - Limit to set * \param value - Size of limit * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_UNSUPPORTED_LIMIT, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_INVALID_CONTEXT * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSynchronize, * ::cudaDeviceSetLimit */ CUresult CUDAAPI cuCtxSetLimit(CUlimit limit, size_t value); /** * \brief Returns resource limits * * Returns in \p *pvalue the current size of \p limit. The supported * ::CUlimit values are: * - ::CU_LIMIT_STACK_SIZE: stack size in bytes of each GPU thread. * - ::CU_LIMIT_PRINTF_FIFO_SIZE: size in bytes of the FIFO used by the * ::printf() device system call. * - ::CU_LIMIT_MALLOC_HEAP_SIZE: size in bytes of the heap used by the * ::malloc() and ::free() device system calls. * - ::CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH: maximum grid depth at which a thread * can issue the device runtime call ::cudaDeviceSynchronize() to wait on * child grid launches to complete. * - ::CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT: maximum number of outstanding * device runtime launches that can be made from this context. * - ::CU_LIMIT_MAX_L2_FETCH_GRANULARITY: L2 cache fetch granularity. * - ::CU_LIMIT_PERSISTING_L2_CACHE_SIZE: Persisting L2 cache size in bytes * * \param limit - Limit to query * \param pvalue - Returned size of limit * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_UNSUPPORTED_LIMIT * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize, * ::cudaDeviceGetLimit */ CUresult CUDAAPI cuCtxGetLimit(size_t *pvalue, CUlimit limit); /** * \brief Returns the preferred cache configuration for the current context. * * On devices where the L1 cache and shared memory use the same hardware * resources, this function returns through \p pconfig the preferred cache configuration * for the current context. This is only a preference. The driver will use * the requested configuration if possible, but it is free to choose a different * configuration if required to execute functions. * * This will return a \p pconfig of ::CU_FUNC_CACHE_PREFER_NONE on devices * where the size of the L1 cache and shared memory are fixed. * * The supported cache configurations are: * - ::CU_FUNC_CACHE_PREFER_NONE: no preference for shared memory or L1 (default) * - ::CU_FUNC_CACHE_PREFER_SHARED: prefer larger shared memory and smaller L1 cache * - ::CU_FUNC_CACHE_PREFER_L1: prefer larger L1 cache and smaller shared memory * - ::CU_FUNC_CACHE_PREFER_EQUAL: prefer equal sized L1 cache and shared memory * * \param pconfig - Returned cache configuration * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize, * ::cuFuncSetCacheConfig, * ::cudaDeviceGetCacheConfig */ CUresult CUDAAPI cuCtxGetCacheConfig(CUfunc_cache *pconfig); /** * \brief Sets the preferred cache configuration for the current context. * * On devices where the L1 cache and shared memory use the same hardware * resources, this sets through \p config the preferred cache configuration for * the current context. This is only a preference. The driver will use * the requested configuration if possible, but it is free to choose a different * configuration if required to execute the function. Any function preference * set via ::cuFuncSetCacheConfig() will be preferred over this context-wide * setting. Setting the context-wide cache configuration to * ::CU_FUNC_CACHE_PREFER_NONE will cause subsequent kernel launches to prefer * to not change the cache configuration unless required to launch the kernel. * * This setting does nothing on devices where the size of the L1 cache and * shared memory are fixed. * * Launching a kernel with a different preference than the most recent * preference setting may insert a device-side synchronization point. * * The supported cache configurations are: * - ::CU_FUNC_CACHE_PREFER_NONE: no preference for shared memory or L1 (default) * - ::CU_FUNC_CACHE_PREFER_SHARED: prefer larger shared memory and smaller L1 cache * - ::CU_FUNC_CACHE_PREFER_L1: prefer larger L1 cache and smaller shared memory * - ::CU_FUNC_CACHE_PREFER_EQUAL: prefer equal sized L1 cache and shared memory * * \param config - Requested cache configuration * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetLimit, * ::cuCtxSynchronize, * ::cuFuncSetCacheConfig, * ::cudaDeviceSetCacheConfig */ CUresult CUDAAPI cuCtxSetCacheConfig(CUfunc_cache config); /** * \brief Returns the current shared memory configuration for the current context. * * This function will return in \p pConfig the current size of shared memory banks * in the current context. On devices with configurable shared memory banks, * ::cuCtxSetSharedMemConfig can be used to change this setting, so that all * subsequent kernel launches will by default use the new bank size. When * ::cuCtxGetSharedMemConfig is called on devices without configurable shared * memory, it will return the fixed bank size of the hardware. * * The returned bank configurations can be either: * - ::CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE: shared memory bank width is * four bytes. * - ::CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE: shared memory bank width will * eight bytes. * * \param pConfig - returned shared memory configuration * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetLimit, * ::cuCtxSynchronize, * ::cuCtxGetSharedMemConfig, * ::cuFuncSetCacheConfig, * ::cudaDeviceGetSharedMemConfig */ CUresult CUDAAPI cuCtxGetSharedMemConfig(CUsharedconfig *pConfig); /** * \brief Sets the shared memory configuration for the current context. * * On devices with configurable shared memory banks, this function will set * the context's shared memory bank size which is used for subsequent kernel * launches. * * Changed the shared memory configuration between launches may insert a device * side synchronization point between those launches. * * Changing the shared memory bank size will not increase shared memory usage * or affect occupancy of kernels, but may have major effects on performance. * Larger bank sizes will allow for greater potential bandwidth to shared memory, * but will change what kinds of accesses to shared memory will result in bank * conflicts. * * This function will do nothing on devices with fixed shared memory bank size. * * The supported bank configurations are: * - ::CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE: set bank width to the default initial * setting (currently, four bytes). * - ::CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE: set shared memory bank width to * be natively four bytes. * - ::CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE: set shared memory bank width to * be natively eight bytes. * * \param config - requested shared memory configuration * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetLimit, * ::cuCtxSynchronize, * ::cuCtxGetSharedMemConfig, * ::cuFuncSetCacheConfig, * ::cudaDeviceSetSharedMemConfig */ CUresult CUDAAPI cuCtxSetSharedMemConfig(CUsharedconfig config); /** * \brief Gets the context's API version. * * Returns a version number in \p version corresponding to the capabilities of * the context (e.g. 3010 or 3020), which library developers can use to direct * callers to a specific API version. If \p ctx is NULL, returns the API version * used to create the currently bound context. * * Note that new API versions are only introduced when context capabilities are * changed that break binary compatibility, so the API version and driver version * may be different. For example, it is valid for the API version to be 3020 while * the driver version is 4020. * * \param ctx - Context to check * \param version - Pointer to version * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize */ CUresult CUDAAPI cuCtxGetApiVersion(CUcontext ctx, unsigned int *version); /** * \brief Returns numerical values that correspond to the least and * greatest stream priorities. * * Returns in \p *leastPriority and \p *greatestPriority the numerical values that correspond * to the least and greatest stream priorities respectively. Stream priorities * follow a convention where lower numbers imply greater priorities. The range of * meaningful stream priorities is given by [\p *greatestPriority, \p *leastPriority]. * If the user attempts to create a stream with a priority value that is * outside the meaningful range as specified by this API, the priority is * automatically clamped down or up to either \p *leastPriority or \p *greatestPriority * respectively. See ::cuStreamCreateWithPriority for details on creating a * priority stream. * A NULL may be passed in for \p *leastPriority or \p *greatestPriority if the value * is not desired. * * This function will return '0' in both \p *leastPriority and \p *greatestPriority if * the current context's device does not support stream priorities * (see ::cuDeviceGetAttribute). * * \param leastPriority - Pointer to an int in which the numerical value for least * stream priority is returned * \param greatestPriority - Pointer to an int in which the numerical value for greatest * stream priority is returned * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \notefnerr * * \sa ::cuStreamCreateWithPriority, * ::cuStreamGetPriority, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxSetLimit, * ::cuCtxSynchronize, * ::cudaDeviceGetStreamPriorityRange */ CUresult CUDAAPI cuCtxGetStreamPriorityRange(int *leastPriority, int *greatestPriority); /** * \brief Resets all persisting lines in cache to normal status. * * ::cuCtxResetPersistingL2Cache Resets all persisting lines in cache to normal * status. Takes effect on function return. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa * ::CUaccessPolicyWindow */ CUresult CUDAAPI cuCtxResetPersistingL2Cache(void); /** * \brief Returns the execution affinity setting for the current context. * * Returns in \p *pExecAffinity the current value of \p type. The supported * ::CUexecAffinityType values are: * - ::CU_EXEC_AFFINITY_TYPE_SM_COUNT: number of SMs the context is limited to use. * * \param type - Execution affinity type to query * \param pExecAffinity - Returned execution affinity * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY * \notefnerr * * \sa * ::CUexecAffinityParam */ CUresult CUDAAPI cuCtxGetExecAffinity(CUexecAffinityParam *pExecAffinity, CUexecAffinityType type); /** @} */ /* END CUDA_CTX */ /** * \defgroup CUDA_CTX_DEPRECATED Context Management [DEPRECATED] * * ___MANBRIEF___ deprecated context management functions of the low-level CUDA * driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the deprecated context management functions of the low-level * CUDA driver application programming interface. * * @{ */ /** * \brief Increment a context's usage-count * * \deprecated * * Note that this function is deprecated and should not be used. * * Increments the usage count of the context and passes back a context handle * in \p *pctx that must be passed to ::cuCtxDetach() when the application is * done with the context. ::cuCtxAttach() fails if there is no context current * to the thread. * * Currently, the \p flags parameter must be 0. * * \param pctx - Returned context handle of the current context * \param flags - Context attach flags (must be 0) * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxDetach, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize */ __CUDA_DEPRECATED CUresult CUDAAPI cuCtxAttach(CUcontext *pctx, unsigned int flags); /** * \brief Decrement a context's usage-count * * \deprecated * * Note that this function is deprecated and should not be used. * * Decrements the usage count of the context \p ctx, and destroys the context * if the usage count goes to 0. The context must be a handle that was passed * back by ::cuCtxCreate() or ::cuCtxAttach(), and must be current to the * calling thread. * * \param ctx - Context to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT * \notefnerr * * \sa ::cuCtxCreate, * ::cuCtxDestroy, * ::cuCtxGetApiVersion, * ::cuCtxGetCacheConfig, * ::cuCtxGetDevice, * ::cuCtxGetFlags, * ::cuCtxGetLimit, * ::cuCtxPopCurrent, * ::cuCtxPushCurrent, * ::cuCtxSetCacheConfig, * ::cuCtxSetLimit, * ::cuCtxSynchronize */ __CUDA_DEPRECATED CUresult CUDAAPI cuCtxDetach(CUcontext ctx); /** @} */ /* END CUDA_CTX_DEPRECATED */ /** * \defgroup CUDA_MODULE Module Management * * ___MANBRIEF___ module management functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the module management functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Loads a compute module * * Takes a filename \p fname and loads the corresponding module \p module into * the current context. The CUDA driver API does not attempt to lazily * allocate the resources needed by a module; if the memory for functions and * data (constant and global) needed by the module cannot be allocated, * ::cuModuleLoad() fails. The file should be a \e cubin file as output by * \b nvcc, or a \e PTX file either as output by \b nvcc or handwritten, or * a \e fatbin file as output by \b nvcc from toolchain 4.0 or later. * * \param module - Returned module * \param fname - Filename of module to load * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_PTX, * ::CUDA_ERROR_UNSUPPORTED_PTX_VERSION, * ::CUDA_ERROR_NOT_FOUND, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_FILE_NOT_FOUND, * ::CUDA_ERROR_NO_BINARY_FOR_GPU, * ::CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, * ::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, * ::CUDA_ERROR_JIT_COMPILER_NOT_FOUND * \notefnerr * * \sa ::cuModuleGetFunction, * ::cuModuleGetGlobal, * ::cuModuleGetTexRef, * ::cuModuleLoadData, * ::cuModuleLoadDataEx, * ::cuModuleLoadFatBinary, * ::cuModuleUnload */ CUresult CUDAAPI cuModuleLoad(CUmodule *module, const char *fname); /** * \brief Load a module's data * * Takes a pointer \p image and loads the corresponding module \p module into * the current context. The pointer may be obtained by mapping a \e cubin or * \e PTX or \e fatbin file, passing a \e cubin or \e PTX or \e fatbin file * as a NULL-terminated text string, or incorporating a \e cubin or \e fatbin * object into the executable resources and using operating system calls such * as Windows \c FindResource() to obtain the pointer. * * \param module - Returned module * \param image - Module data to load * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_PTX, * ::CUDA_ERROR_UNSUPPORTED_PTX_VERSION, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_NO_BINARY_FOR_GPU, * ::CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, * ::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, * ::CUDA_ERROR_JIT_COMPILER_NOT_FOUND * \notefnerr * * \sa ::cuModuleGetFunction, * ::cuModuleGetGlobal, * ::cuModuleGetTexRef, * ::cuModuleLoad, * ::cuModuleLoadDataEx, * ::cuModuleLoadFatBinary, * ::cuModuleUnload */ CUresult CUDAAPI cuModuleLoadData(CUmodule *module, const void *image); /** * \brief Load a module's data with options * * Takes a pointer \p image and loads the corresponding module \p module into * the current context. The pointer may be obtained by mapping a \e cubin or * \e PTX or \e fatbin file, passing a \e cubin or \e PTX or \e fatbin file * as a NULL-terminated text string, or incorporating a \e cubin or \e fatbin * object into the executable resources and using operating system calls such * as Windows \c FindResource() to obtain the pointer. Options are passed as * an array via \p options and any corresponding parameters are passed in * \p optionValues. The number of total options is supplied via \p numOptions. * Any outputs will be returned via \p optionValues. * * \param module - Returned module * \param image - Module data to load * \param numOptions - Number of options * \param options - Options for JIT * \param optionValues - Option values for JIT * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_PTX, * ::CUDA_ERROR_UNSUPPORTED_PTX_VERSION, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_NO_BINARY_FOR_GPU, * ::CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, * ::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, * ::CUDA_ERROR_JIT_COMPILER_NOT_FOUND * \notefnerr * * \sa ::cuModuleGetFunction, * ::cuModuleGetGlobal, * ::cuModuleGetTexRef, * ::cuModuleLoad, * ::cuModuleLoadData, * ::cuModuleLoadFatBinary, * ::cuModuleUnload */ CUresult CUDAAPI cuModuleLoadDataEx(CUmodule *module, const void *image, unsigned int numOptions, CUjit_option *options, void **optionValues); /** * \brief Load a module's data * * Takes a pointer \p fatCubin and loads the corresponding module \p module * into the current context. The pointer represents a <i>fat binary</i> object, * which is a collection of different \e cubin and/or \e PTX files, all * representing the same device code, but compiled and optimized for different * architectures. * * Prior to CUDA 4.0, there was no documented API for constructing and using * fat binary objects by programmers. Starting with CUDA 4.0, fat binary * objects can be constructed by providing the <i>-fatbin option</i> to \b nvcc. * More information can be found in the \b nvcc document. * * \param module - Returned module * \param fatCubin - Fat binary to load * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_PTX, * ::CUDA_ERROR_UNSUPPORTED_PTX_VERSION, * ::CUDA_ERROR_NOT_FOUND, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_NO_BINARY_FOR_GPU, * ::CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND, * ::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED, * ::CUDA_ERROR_JIT_COMPILER_NOT_FOUND * \notefnerr * * \sa ::cuModuleGetFunction, * ::cuModuleGetGlobal, * ::cuModuleGetTexRef, * ::cuModuleLoad, * ::cuModuleLoadData, * ::cuModuleLoadDataEx, * ::cuModuleUnload */ CUresult CUDAAPI cuModuleLoadFatBinary(CUmodule *module, const void *fatCubin); /** * \brief Unloads a module * * Unloads a module \p hmod from the current context. * * \param hmod - Module to unload * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_destroy_ub * * \sa ::cuModuleGetFunction, * ::cuModuleGetGlobal, * ::cuModuleGetTexRef, * ::cuModuleLoad, * ::cuModuleLoadData, * ::cuModuleLoadDataEx, * ::cuModuleLoadFatBinary */ CUresult CUDAAPI cuModuleUnload(CUmodule hmod); /** * \brief Returns a function handle * * Returns in \p *hfunc the handle of the function of name \p name located in * module \p hmod. If no function of that name exists, ::cuModuleGetFunction() * returns ::CUDA_ERROR_NOT_FOUND. * * \param hfunc - Returned function handle * \param hmod - Module to retrieve function from * \param name - Name of function to retrieve * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_FOUND * \notefnerr * * \sa ::cuModuleGetGlobal, * ::cuModuleGetTexRef, * ::cuModuleLoad, * ::cuModuleLoadData, * ::cuModuleLoadDataEx, * ::cuModuleLoadFatBinary, * ::cuModuleUnload */ CUresult CUDAAPI cuModuleGetFunction(CUfunction *hfunc, CUmodule hmod, const char *name); /** * \brief Returns a global pointer from a module * * Returns in \p *dptr and \p *bytes the base pointer and size of the * global of name \p name located in module \p hmod. If no variable of that name * exists, ::cuModuleGetGlobal() returns ::CUDA_ERROR_NOT_FOUND. Both * parameters \p dptr and \p bytes are optional. If one of them is * NULL, it is ignored. * * \param dptr - Returned global device pointer * \param bytes - Returned global size in bytes * \param hmod - Module to retrieve global from * \param name - Name of global to retrieve * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_FOUND * \notefnerr * * \sa ::cuModuleGetFunction, * ::cuModuleGetTexRef, * ::cuModuleLoad, * ::cuModuleLoadData, * ::cuModuleLoadDataEx, * ::cuModuleLoadFatBinary, * ::cuModuleUnload, * ::cudaGetSymbolAddress, * ::cudaGetSymbolSize */ CUresult CUDAAPI cuModuleGetGlobal(CUdeviceptr *dptr, size_t *bytes, CUmodule hmod, const char *name); /** * \brief Returns a handle to a texture reference * * Returns in \p *pTexRef the handle of the texture reference of name \p name * in the module \p hmod. If no texture reference of that name exists, * ::cuModuleGetTexRef() returns ::CUDA_ERROR_NOT_FOUND. This texture reference * handle should not be destroyed, since it will be destroyed when the module * is unloaded. * * \param pTexRef - Returned texture reference * \param hmod - Module to retrieve texture reference from * \param name - Name of texture reference to retrieve * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_FOUND * \notefnerr * * \sa ::cuModuleGetFunction, * ::cuModuleGetGlobal, * ::cuModuleGetSurfRef, * ::cuModuleLoad, * ::cuModuleLoadData, * ::cuModuleLoadDataEx, * ::cuModuleLoadFatBinary, * ::cuModuleUnload, * ::cudaGetTextureReference */ CUresult CUDAAPI cuModuleGetTexRef(CUtexref *pTexRef, CUmodule hmod, const char *name); /** * \brief Returns a handle to a surface reference * * Returns in \p *pSurfRef the handle of the surface reference of name \p name * in the module \p hmod. If no surface reference of that name exists, * ::cuModuleGetSurfRef() returns ::CUDA_ERROR_NOT_FOUND. * * \param pSurfRef - Returned surface reference * \param hmod - Module to retrieve surface reference from * \param name - Name of surface reference to retrieve * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_FOUND * \notefnerr * * \sa ::cuModuleGetFunction, * ::cuModuleGetGlobal, * ::cuModuleGetTexRef, * ::cuModuleLoad, * ::cuModuleLoadData, * ::cuModuleLoadDataEx, * ::cuModuleLoadFatBinary, * ::cuModuleUnload, * ::cudaGetSurfaceReference */ CUresult CUDAAPI cuModuleGetSurfRef(CUsurfref *pSurfRef, CUmodule hmod, const char *name); /** * \brief Creates a pending JIT linker invocation. * * If the call is successful, the caller owns the returned CUlinkState, which * should eventually be destroyed with ::cuLinkDestroy. The * device code machine size (32 or 64 bit) will match the calling application. * * Both linker and compiler options may be specified. Compiler options will * be applied to inputs to this linker action which must be compiled from PTX. * The options ::CU_JIT_WALL_TIME, * ::CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES, and ::CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES * will accumulate data until the CUlinkState is destroyed. * * \p optionValues must remain valid for the life of the CUlinkState if output * options are used. No other references to inputs are maintained after this * call returns. * * \param numOptions Size of options arrays * \param options Array of linker and compiler options * \param optionValues Array of option values, each cast to void * * \param stateOut On success, this will contain a CUlinkState to specify * and complete this action * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_JIT_COMPILER_NOT_FOUND * \notefnerr * * \sa ::cuLinkAddData, * ::cuLinkAddFile, * ::cuLinkComplete, * ::cuLinkDestroy */ CUresult CUDAAPI cuLinkCreate(unsigned int numOptions, CUjit_option *options, void **optionValues, CUlinkState *stateOut); /** * \brief Add an input to a pending linker invocation * * Ownership of \p data is retained by the caller. No reference is retained to any * inputs after this call returns. * * This method accepts only compiler options, which are used if the data must * be compiled from PTX, and does not accept any of * ::CU_JIT_WALL_TIME, ::CU_JIT_INFO_LOG_BUFFER, ::CU_JIT_ERROR_LOG_BUFFER, * ::CU_JIT_TARGET_FROM_CUCONTEXT, or ::CU_JIT_TARGET. * * \param state A pending linker action. * \param type The type of the input data. * \param data The input data. PTX must be NULL-terminated. * \param size The length of the input data. * \param name An optional name for this input in log messages. * \param numOptions Size of options. * \param options Options to be applied only for this input (overrides options from ::cuLinkCreate). * \param optionValues Array of option values, each cast to void *. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_IMAGE, * ::CUDA_ERROR_INVALID_PTX, * ::CUDA_ERROR_UNSUPPORTED_PTX_VERSION, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_NO_BINARY_FOR_GPU * * \sa ::cuLinkCreate, * ::cuLinkAddFile, * ::cuLinkComplete, * ::cuLinkDestroy */ CUresult CUDAAPI cuLinkAddData(CUlinkState state, CUjitInputType type, void *data, size_t size, const char *name, unsigned int numOptions, CUjit_option *options, void **optionValues); /** * \brief Add a file input to a pending linker invocation * * No reference is retained to any inputs after this call returns. * * This method accepts only compiler options, which are used if the input * must be compiled from PTX, and does not accept any of * ::CU_JIT_WALL_TIME, ::CU_JIT_INFO_LOG_BUFFER, ::CU_JIT_ERROR_LOG_BUFFER, * ::CU_JIT_TARGET_FROM_CUCONTEXT, or ::CU_JIT_TARGET. * * This method is equivalent to invoking ::cuLinkAddData on the contents * of the file. * * \param state A pending linker action * \param type The type of the input data * \param path Path to the input file * \param numOptions Size of options * \param options Options to be applied only for this input (overrides options from ::cuLinkCreate) * \param optionValues Array of option values, each cast to void * * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_FILE_NOT_FOUND * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_IMAGE, * ::CUDA_ERROR_INVALID_PTX, * ::CUDA_ERROR_UNSUPPORTED_PTX_VERSION, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_NO_BINARY_FOR_GPU * * \sa ::cuLinkCreate, * ::cuLinkAddData, * ::cuLinkComplete, * ::cuLinkDestroy */ CUresult CUDAAPI cuLinkAddFile(CUlinkState state, CUjitInputType type, const char *path, unsigned int numOptions, CUjit_option *options, void **optionValues); /** * \brief Complete a pending linker invocation * * Completes the pending linker action and returns the cubin image for the linked * device code, which can be used with ::cuModuleLoadData. The cubin is owned by * \p state, so it should be loaded before \p state is destroyed via ::cuLinkDestroy. * This call does not destroy \p state. * * \param state A pending linker invocation * \param cubinOut On success, this will point to the output image * \param sizeOut Optional parameter to receive the size of the generated image * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_OUT_OF_MEMORY * * \sa ::cuLinkCreate, * ::cuLinkAddData, * ::cuLinkAddFile, * ::cuLinkDestroy, * ::cuModuleLoadData */ CUresult CUDAAPI cuLinkComplete(CUlinkState state, void **cubinOut, size_t *sizeOut); /** * \brief Destroys state for a JIT linker invocation. * * \param state State object for the linker invocation * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_HANDLE * * \sa ::cuLinkCreate */ CUresult CUDAAPI cuLinkDestroy(CUlinkState state); /** @} */ /* END CUDA_MODULE */ /** * \defgroup CUDA_MEM Memory Management * * ___MANBRIEF___ memory management functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the memory management functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Gets free and total memory * * Returns in \p *total the total amount of memory available to the the current context. * Returns in \p *free the amount of memory on the device that is free according to the OS. * CUDA is not guaranteed to be able to allocate all of the memory that the OS reports as free. * In a multi-tenet situation, free estimate returned is prone to race condition where * a new allocation/free done by a different process or a different thread in the same * process between the time when free memory was estimated and reported, will result in * deviation in free value reported and actual free memory. * * The integrated GPU on Tegra shares memory with CPU and other component * of the SoC. The free and total values returned by the API excludes * the SWAP memory space maintained by the OS on some platforms. * The OS may move some of the memory pages into swap area as the GPU or * CPU allocate or access memory. See Tegra app note on how to calculate * total and free memory on Tegra. * * \param free - Returned free memory in bytes * \param total - Returned total memory in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemGetInfo */ CUresult CUDAAPI cuMemGetInfo(size_t *free, size_t *total); /** * \brief Allocates device memory * * Allocates \p bytesize bytes of linear memory on the device and returns in * \p *dptr a pointer to the allocated memory. The allocated memory is suitably * aligned for any kind of variable. The memory is not cleared. If \p bytesize * is 0, ::cuMemAlloc() returns ::CUDA_ERROR_INVALID_VALUE. * * \param dptr - Returned device pointer * \param bytesize - Requested allocation size in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMalloc */ CUresult CUDAAPI cuMemAlloc(CUdeviceptr *dptr, size_t bytesize); /** * \brief Allocates pitched device memory * * Allocates at least \p WidthInBytes * \p Height bytes of linear memory on * the device and returns in \p *dptr a pointer to the allocated memory. The * function may pad the allocation to ensure that corresponding pointers in * any given row will continue to meet the alignment requirements for * coalescing as the address is updated from row to row. \p ElementSizeBytes * specifies the size of the largest reads and writes that will be performed * on the memory range. \p ElementSizeBytes may be 4, 8 or 16 (since coalesced * memory transactions are not possible on other data sizes). If * \p ElementSizeBytes is smaller than the actual read/write size of a kernel, * the kernel will run correctly, but possibly at reduced speed. The pitch * returned in \p *pPitch by ::cuMemAllocPitch() is the width in bytes of the * allocation. The intended usage of pitch is as a separate parameter of the * allocation, used to compute addresses within the 2D array. Given the row * and column of an array element of type \b T, the address is computed as: * \code T* pElement = (T*)((char*)BaseAddress + Row * Pitch) + Column; * \endcode * * The pitch returned by ::cuMemAllocPitch() is guaranteed to work with * ::cuMemcpy2D() under all circumstances. For allocations of 2D arrays, it is * recommended that programmers consider performing pitch allocations using * ::cuMemAllocPitch(). Due to alignment restrictions in the hardware, this is * especially true if the application will be performing 2D memory copies * between different regions of device memory (whether linear memory or CUDA * arrays). * * The byte alignment of the pitch returned by ::cuMemAllocPitch() is guaranteed * to match or exceed the alignment requirement for texture binding with * ::cuTexRefSetAddress2D(). * * \param dptr - Returned device pointer * \param pPitch - Returned pitch of allocation in bytes * \param WidthInBytes - Requested allocation width in bytes * \param Height - Requested allocation height in rows * \param ElementSizeBytes - Size of largest reads/writes for range * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMallocPitch */ CUresult CUDAAPI cuMemAllocPitch(CUdeviceptr *dptr, size_t *pPitch, size_t WidthInBytes, size_t Height, unsigned int ElementSizeBytes); /** * \brief Frees device memory * * Frees the memory space pointed to by \p dptr, which must have been returned * by a previous call to ::cuMemAlloc() or ::cuMemAllocPitch(). * * \param dptr - Pointer to memory to free * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaFree */ CUresult CUDAAPI cuMemFree(CUdeviceptr dptr); /** * \brief Get information on memory allocations * * Returns the base address in \p *pbase and size in \p *psize of the * allocation by ::cuMemAlloc() or ::cuMemAllocPitch() that contains the input * pointer \p dptr. Both parameters \p pbase and \p psize are optional. If one * of them is NULL, it is ignored. * * \param pbase - Returned base address * \param psize - Returned size of device memory allocation * \param dptr - Device pointer to query * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_NOT_FOUND, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32 */ CUresult CUDAAPI cuMemGetAddressRange(CUdeviceptr *pbase, size_t *psize, CUdeviceptr dptr); /** * \brief Allocates page-locked host memory * * Allocates \p bytesize bytes of host memory that is page-locked and * accessible to the device. The driver tracks the virtual memory ranges * allocated with this function and automatically accelerates calls to * functions such as ::cuMemcpy(). Since the memory can be accessed directly by * the device, it can be read or written with much higher bandwidth than * pageable memory obtained with functions such as ::malloc(). Allocating * excessive amounts of memory with ::cuMemAllocHost() may degrade system * performance, since it reduces the amount of memory available to the system * for paging. As a result, this function is best used sparingly to allocate * staging areas for data exchange between host and device. * * Note all host memory allocated using ::cuMemHostAlloc() will automatically * be immediately accessible to all contexts on all devices which support unified * addressing (as may be queried using ::CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING). * The device pointer that may be used to access this host memory from those * contexts is always equal to the returned host pointer \p *pp. * See \ref CUDA_UNIFIED for additional details. * * \param pp - Returned host pointer to page-locked memory * \param bytesize - Requested allocation size in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMallocHost */ CUresult CUDAAPI cuMemAllocHost(void **pp, size_t bytesize); /** * \brief Frees page-locked host memory * * Frees the memory space pointed to by \p p, which must have been returned by * a previous call to ::cuMemAllocHost(). * * \param p - Pointer to memory to free * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaFreeHost */ CUresult CUDAAPI cuMemFreeHost(void *p); /** * \brief Allocates page-locked host memory * * Allocates \p bytesize bytes of host memory that is page-locked and accessible * to the device. The driver tracks the virtual memory ranges allocated with * this function and automatically accelerates calls to functions such as * ::cuMemcpyHtoD(). Since the memory can be accessed directly by the device, * it can be read or written with much higher bandwidth than pageable memory * obtained with functions such as ::malloc(). Allocating excessive amounts of * pinned memory may degrade system performance, since it reduces the amount * of memory available to the system for paging. As a result, this function is * best used sparingly to allocate staging areas for data exchange between * host and device. * * The \p Flags parameter enables different options to be specified that * affect the allocation, as follows. * * - ::CU_MEMHOSTALLOC_PORTABLE: The memory returned by this call will be * considered as pinned memory by all CUDA contexts, not just the one that * performed the allocation. * * - ::CU_MEMHOSTALLOC_DEVICEMAP: Maps the allocation into the CUDA address * space. The device pointer to the memory may be obtained by calling * ::cuMemHostGetDevicePointer(). * * - ::CU_MEMHOSTALLOC_WRITECOMBINED: Allocates the memory as write-combined * (WC). WC memory can be transferred across the PCI Express bus more * quickly on some system configurations, but cannot be read efficiently by * most CPUs. WC memory is a good option for buffers that will be written by * the CPU and read by the GPU via mapped pinned memory or host->device * transfers. * * All of these flags are orthogonal to one another: a developer may allocate * memory that is portable, mapped and/or write-combined with no restrictions. * * The ::CU_MEMHOSTALLOC_DEVICEMAP flag may be specified on CUDA contexts for * devices that do not support mapped pinned memory. The failure is deferred * to ::cuMemHostGetDevicePointer() because the memory may be mapped into * other CUDA contexts via the ::CU_MEMHOSTALLOC_PORTABLE flag. * * The memory allocated by this function must be freed with ::cuMemFreeHost(). * * Note all host memory allocated using ::cuMemHostAlloc() will automatically * be immediately accessible to all contexts on all devices which support unified * addressing (as may be queried using ::CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING). * Unless the flag ::CU_MEMHOSTALLOC_WRITECOMBINED is specified, the device pointer * that may be used to access this host memory from those contexts is always equal * to the returned host pointer \p *pp. If the flag ::CU_MEMHOSTALLOC_WRITECOMBINED * is specified, then the function ::cuMemHostGetDevicePointer() must be used * to query the device pointer, even if the context supports unified addressing. * See \ref CUDA_UNIFIED for additional details. * * \param pp - Returned host pointer to page-locked memory * \param bytesize - Requested allocation size in bytes * \param Flags - Flags for allocation request * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaHostAlloc */ CUresult CUDAAPI cuMemHostAlloc(void **pp, size_t bytesize, unsigned int Flags); /** * \brief Passes back device pointer of mapped pinned memory * * Passes back the device pointer \p pdptr corresponding to the mapped, pinned * host buffer \p p allocated by ::cuMemHostAlloc. * * ::cuMemHostGetDevicePointer() will fail if the ::CU_MEMHOSTALLOC_DEVICEMAP * flag was not specified at the time the memory was allocated, or if the * function is called on a GPU that does not support mapped pinned memory. * * For devices that have a non-zero value for the device attribute * ::CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, the memory * can also be accessed from the device using the host pointer \p p. * The device pointer returned by ::cuMemHostGetDevicePointer() may or may not * match the original host pointer \p p and depends on the devices visible to the * application. If all devices visible to the application have a non-zero value for the * device attribute, the device pointer returned by ::cuMemHostGetDevicePointer() * will match the original pointer \p p. If any device visible to the application * has a zero value for the device attribute, the device pointer returned by * ::cuMemHostGetDevicePointer() will not match the original host pointer \p p, * but it will be suitable for use on all devices provided Unified Virtual Addressing * is enabled. In such systems, it is valid to access the memory using either pointer * on devices that have a non-zero value for the device attribute. Note however that * such devices should access the memory using only one of the two pointers and not both. * * \p Flags provides for future releases. For now, it must be set to 0. * * \param pdptr - Returned device pointer * \param p - Host pointer * \param Flags - Options (must be 0) * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaHostGetDevicePointer */ CUresult CUDAAPI cuMemHostGetDevicePointer(CUdeviceptr *pdptr, void *p, unsigned int Flags); /** * \brief Passes back flags that were used for a pinned allocation * * Passes back the flags \p pFlags that were specified when allocating * the pinned host buffer \p p allocated by ::cuMemHostAlloc. * * ::cuMemHostGetFlags() will fail if the pointer does not reside in * an allocation performed by ::cuMemAllocHost() or ::cuMemHostAlloc(). * * \param pFlags - Returned flags word * \param p - Host pointer * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa * ::cuMemAllocHost, * ::cuMemHostAlloc, * ::cudaHostGetFlags */ CUresult CUDAAPI cuMemHostGetFlags(unsigned int *pFlags, void *p); /** * \brief Allocates memory that will be automatically managed by the Unified Memory system * * Allocates \p bytesize bytes of managed memory on the device and returns in * \p *dptr a pointer to the allocated memory. If the device doesn't support * allocating managed memory, ::CUDA_ERROR_NOT_SUPPORTED is returned. Support * for managed memory can be queried using the device attribute * ::CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY. The allocated memory is suitably * aligned for any kind of variable. The memory is not cleared. If \p bytesize * is 0, ::cuMemAllocManaged returns ::CUDA_ERROR_INVALID_VALUE. The pointer * is valid on the CPU and on all GPUs in the system that support managed memory. * All accesses to this pointer must obey the Unified Memory programming model. * * \p flags specifies the default stream association for this allocation. * \p flags must be one of ::CU_MEM_ATTACH_GLOBAL or ::CU_MEM_ATTACH_HOST. If * ::CU_MEM_ATTACH_GLOBAL is specified, then this memory is accessible from * any stream on any device. If ::CU_MEM_ATTACH_HOST is specified, then the * allocation should not be accessed from devices that have a zero value for the * device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS; an explicit call to * ::cuStreamAttachMemAsync will be required to enable access on such devices. * * If the association is later changed via ::cuStreamAttachMemAsync to * a single stream, the default association as specifed during ::cuMemAllocManaged * is restored when that stream is destroyed. For __managed__ variables, the * default association is always ::CU_MEM_ATTACH_GLOBAL. Note that destroying a * stream is an asynchronous operation, and as a result, the change to default * association won't happen until all work in the stream has completed. * * Memory allocated with ::cuMemAllocManaged should be released with ::cuMemFree. * * Device memory oversubscription is possible for GPUs that have a non-zero value for the * device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. Managed memory on * such GPUs may be evicted from device memory to host memory at any time by the Unified * Memory driver in order to make room for other allocations. * * In a multi-GPU system where all GPUs have a non-zero value for the device attribute * ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, managed memory may not be populated when this * API returns and instead may be populated on access. In such systems, managed memory can * migrate to any processor's memory at any time. The Unified Memory driver will employ heuristics to * maintain data locality and prevent excessive page faults to the extent possible. The application * can also guide the driver about memory usage patterns via ::cuMemAdvise. The application * can also explicitly migrate memory to a desired processor's memory via * ::cuMemPrefetchAsync. * * In a multi-GPU system where all of the GPUs have a zero value for the device attribute * ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS and all the GPUs have peer-to-peer support * with each other, the physical storage for managed memory is created on the GPU which is active * at the time ::cuMemAllocManaged is called. All other GPUs will reference the data at reduced * bandwidth via peer mappings over the PCIe bus. The Unified Memory driver does not migrate * memory among such GPUs. * * In a multi-GPU system where not all GPUs have peer-to-peer support with each other and * where the value of the device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS * is zero for at least one of those GPUs, the location chosen for physical storage of managed * memory is system-dependent. * - On Linux, the location chosen will be device memory as long as the current set of active * contexts are on devices that either have peer-to-peer support with each other or have a * non-zero value for the device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. * If there is an active context on a GPU that does not have a non-zero value for that device * attribute and it does not have peer-to-peer support with the other devices that have active * contexts on them, then the location for physical storage will be 'zero-copy' or host memory. * Note that this means that managed memory that is located in device memory is migrated to * host memory if a new context is created on a GPU that doesn't have a non-zero value for * the device attribute and does not support peer-to-peer with at least one of the other devices * that has an active context. This in turn implies that context creation may fail if there is * insufficient host memory to migrate all managed allocations. * - On Windows, the physical storage is always created in 'zero-copy' or host memory. * All GPUs will reference the data at reduced bandwidth over the PCIe bus. In these * circumstances, use of the environment variable CUDA_VISIBLE_DEVICES is recommended to * restrict CUDA to only use those GPUs that have peer-to-peer support. * Alternatively, users can also set CUDA_MANAGED_FORCE_DEVICE_ALLOC to a * non-zero value to force the driver to always use device memory for physical storage. * When this environment variable is set to a non-zero value, all contexts created in * that process on devices that support managed memory have to be peer-to-peer compatible * with each other. Context creation will fail if a context is created on a device that * supports managed memory and is not peer-to-peer compatible with any of the other * managed memory supporting devices on which contexts were previously created, even if * those contexts have been destroyed. These environment variables are described * in the CUDA programming guide under the "CUDA environment variables" section. * - On ARM, managed memory is not available on discrete gpu with Drive PX-2. * * \param dptr - Returned device pointer * \param bytesize - Requested allocation size in bytes * \param flags - Must be one of ::CU_MEM_ATTACH_GLOBAL or ::CU_MEM_ATTACH_HOST * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cuDeviceGetAttribute, ::cuStreamAttachMemAsync, * ::cudaMallocManaged */ CUresult CUDAAPI cuMemAllocManaged(CUdeviceptr *dptr, size_t bytesize, unsigned int flags); /** * \brief Returns a handle to a compute device * * Returns in \p *device a device handle given a PCI bus ID string. * * \param dev - Returned device handle * * \param pciBusId - String in one of the following forms: * [domain]:[bus]:[device].[function] * [domain]:[bus]:[device] * [bus]:[device].[function] * where \p domain, \p bus, \p device, and \p function are all hexadecimal values * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGet, * ::cuDeviceGetAttribute, * ::cuDeviceGetPCIBusId, * ::cudaDeviceGetByPCIBusId */ CUresult CUDAAPI cuDeviceGetByPCIBusId(CUdevice *dev, const char *pciBusId); /** * \brief Returns a PCI Bus Id string for the device * * Returns an ASCII string identifying the device \p dev in the NULL-terminated * string pointed to by \p pciBusId. \p len specifies the maximum length of the * string that may be returned. * * \param pciBusId - Returned identifier string for the device in the following format * [domain]:[bus]:[device].[function] * where \p domain, \p bus, \p device, and \p function are all hexadecimal values. * pciBusId should be large enough to store 13 characters including the NULL-terminator. * * \param len - Maximum length of string to store in \p name * * \param dev - Device to get identifier string for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuDeviceGet, * ::cuDeviceGetAttribute, * ::cuDeviceGetByPCIBusId, * ::cudaDeviceGetPCIBusId */ CUresult CUDAAPI cuDeviceGetPCIBusId(char *pciBusId, int len, CUdevice dev); /** * \brief Gets an interprocess handle for a previously allocated event * * Takes as input a previously allocated event. This event must have been * created with the ::CU_EVENT_INTERPROCESS and ::CU_EVENT_DISABLE_TIMING * flags set. This opaque handle may be copied into other processes and * opened with ::cuIpcOpenEventHandle to allow efficient hardware * synchronization between GPU work in different processes. * * After the event has been opened in the importing process, * ::cuEventRecord, ::cuEventSynchronize, ::cuStreamWaitEvent and * ::cuEventQuery may be used in either process. Performing operations * on the imported event after the exported event has been freed * with ::cuEventDestroy will result in undefined behavior. * * IPC functionality is restricted to devices with support for unified * addressing on Linux and Windows operating systems. * IPC functionality on Windows is restricted to GPUs in TCC mode * * \param pHandle - Pointer to a user allocated CUipcEventHandle * in which to return the opaque event handle * \param event - Event allocated with ::CU_EVENT_INTERPROCESS and * ::CU_EVENT_DISABLE_TIMING flags. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_MAP_FAILED, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuEventCreate, * ::cuEventDestroy, * ::cuEventSynchronize, * ::cuEventQuery, * ::cuStreamWaitEvent, * ::cuIpcOpenEventHandle, * ::cuIpcGetMemHandle, * ::cuIpcOpenMemHandle, * ::cuIpcCloseMemHandle, * ::cudaIpcGetEventHandle */ CUresult CUDAAPI cuIpcGetEventHandle(CUipcEventHandle *pHandle, CUevent event); /** * \brief Opens an interprocess event handle for use in the current process * * Opens an interprocess event handle exported from another process with * ::cuIpcGetEventHandle. This function returns a ::CUevent that behaves like * a locally created event with the ::CU_EVENT_DISABLE_TIMING flag specified. * This event must be freed with ::cuEventDestroy. * * Performing operations on the imported event after the exported event has * been freed with ::cuEventDestroy will result in undefined behavior. * * IPC functionality is restricted to devices with support for unified * addressing on Linux and Windows operating systems. * IPC functionality on Windows is restricted to GPUs in TCC mode * * \param phEvent - Returns the imported event * \param handle - Interprocess handle to open * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_MAP_FAILED, * ::CUDA_ERROR_PEER_ACCESS_UNSUPPORTED, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuEventCreate, * ::cuEventDestroy, * ::cuEventSynchronize, * ::cuEventQuery, * ::cuStreamWaitEvent, * ::cuIpcGetEventHandle, * ::cuIpcGetMemHandle, * ::cuIpcOpenMemHandle, * ::cuIpcCloseMemHandle, * ::cudaIpcOpenEventHandle */ CUresult CUDAAPI cuIpcOpenEventHandle(CUevent *phEvent, CUipcEventHandle handle); /** * \brief Gets an interprocess memory handle for an existing device memory * allocation * * Takes a pointer to the base of an existing device memory allocation created * with ::cuMemAlloc and exports it for use in another process. This is a * lightweight operation and may be called multiple times on an allocation * without adverse effects. * * If a region of memory is freed with ::cuMemFree and a subsequent call * to ::cuMemAlloc returns memory with the same device address, * ::cuIpcGetMemHandle will return a unique handle for the * new memory. * * IPC functionality is restricted to devices with support for unified * addressing on Linux and Windows operating systems. * IPC functionality on Windows is restricted to GPUs in TCC mode * * \param pHandle - Pointer to user allocated ::CUipcMemHandle to return * the handle in. * \param dptr - Base pointer to previously allocated device memory * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_MAP_FAILED, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuMemAlloc, * ::cuMemFree, * ::cuIpcGetEventHandle, * ::cuIpcOpenEventHandle, * ::cuIpcOpenMemHandle, * ::cuIpcCloseMemHandle, * ::cudaIpcGetMemHandle */ CUresult CUDAAPI cuIpcGetMemHandle(CUipcMemHandle *pHandle, CUdeviceptr dptr); /** * \brief Opens an interprocess memory handle exported from another process * and returns a device pointer usable in the local process. * * Maps memory exported from another process with ::cuIpcGetMemHandle into * the current device address space. For contexts on different devices * ::cuIpcOpenMemHandle can attempt to enable peer access between the * devices as if the user called ::cuCtxEnablePeerAccess. This behavior is * controlled by the ::CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS flag. * ::cuDeviceCanAccessPeer can determine if a mapping is possible. * * Contexts that may open ::CUipcMemHandles are restricted in the following way. * ::CUipcMemHandles from each ::CUdevice in a given process may only be opened * by one ::CUcontext per ::CUdevice per other process. * * If the memory handle has already been opened by the current context, the * reference count on the handle is incremented by 1 and the existing device pointer * is returned. * * Memory returned from ::cuIpcOpenMemHandle must be freed with * ::cuIpcCloseMemHandle. * * Calling ::cuMemFree on an exported memory region before calling * ::cuIpcCloseMemHandle in the importing context will result in undefined * behavior. * * IPC functionality is restricted to devices with support for unified * addressing on Linux and Windows operating systems. * IPC functionality on Windows is restricted to GPUs in TCC mode * * \param pdptr - Returned device pointer * \param handle - ::CUipcMemHandle to open * \param Flags - Flags for this operation. Must be specified as ::CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_MAP_FAILED, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_TOO_MANY_PEERS, * ::CUDA_ERROR_INVALID_VALUE * * \note No guarantees are made about the address returned in \p *pdptr. * In particular, multiple processes may not receive the same address for the same \p handle. * * \sa * ::cuMemAlloc, * ::cuMemFree, * ::cuIpcGetEventHandle, * ::cuIpcOpenEventHandle, * ::cuIpcGetMemHandle, * ::cuIpcCloseMemHandle, * ::cuCtxEnablePeerAccess, * ::cuDeviceCanAccessPeer, * ::cudaIpcOpenMemHandle */ CUresult CUDAAPI cuIpcOpenMemHandle(CUdeviceptr *pdptr, CUipcMemHandle handle, unsigned int Flags); /** * \brief Attempts to close memory mapped with ::cuIpcOpenMemHandle * * Decrements the reference count of the memory returned by ::cuIpcOpenMemHandle by 1. * When the reference count reaches 0, this API unmaps the memory. The original allocation * in the exporting process as well as imported mappings in other processes * will be unaffected. * * Any resources used to enable peer access will be freed if this is the * last mapping using them. * * IPC functionality is restricted to devices with support for unified * addressing on Linux and Windows operating systems. * IPC functionality on Windows is restricted to GPUs in TCC mode * * \param dptr - Device pointer returned by ::cuIpcOpenMemHandle * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_MAP_FAILED, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE * \sa * ::cuMemAlloc, * ::cuMemFree, * ::cuIpcGetEventHandle, * ::cuIpcOpenEventHandle, * ::cuIpcGetMemHandle, * ::cuIpcOpenMemHandle, * ::cudaIpcCloseMemHandle */ CUresult CUDAAPI cuIpcCloseMemHandle(CUdeviceptr dptr); /** * \brief Registers an existing host memory range for use by CUDA * * Page-locks the memory range specified by \p p and \p bytesize and maps it * for the device(s) as specified by \p Flags. This memory range also is added * to the same tracking mechanism as ::cuMemHostAlloc to automatically accelerate * calls to functions such as ::cuMemcpyHtoD(). Since the memory can be accessed * directly by the device, it can be read or written with much higher bandwidth * than pageable memory that has not been registered. Page-locking excessive * amounts of memory may degrade system performance, since it reduces the amount * of memory available to the system for paging. As a result, this function is * best used sparingly to register staging areas for data exchange between * host and device. * * This function has limited support on Mac OS X. OS 10.7 or higher is required. * * The \p Flags parameter enables different options to be specified that * affect the allocation, as follows. * * - ::CU_MEMHOSTREGISTER_PORTABLE: The memory returned by this call will be * considered as pinned memory by all CUDA contexts, not just the one that * performed the allocation. * * - ::CU_MEMHOSTREGISTER_DEVICEMAP: Maps the allocation into the CUDA address * space. The device pointer to the memory may be obtained by calling * ::cuMemHostGetDevicePointer(). * * - ::CU_MEMHOSTREGISTER_IOMEMORY: The pointer is treated as pointing to some * I/O memory space, e.g. the PCI Express resource of a 3rd party device. * * - ::CU_MEMHOSTREGISTER_READ_ONLY: The pointer is treated as pointing to memory * that is considered read-only by the device. On platforms without * ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, this flag is * required in order to register memory mapped to the CPU as read-only. Support * for the use of this flag can be queried from the device attribute * ::CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED. Using this flag with * a current context associated with a device that does not have this attribute * set will cause ::cuMemHostRegister to error with CUDA_ERROR_NOT_SUPPORTED. * * All of these flags are orthogonal to one another: a developer may page-lock * memory that is portable or mapped with no restrictions. * * The ::CU_MEMHOSTREGISTER_DEVICEMAP flag may be specified on CUDA contexts for * devices that do not support mapped pinned memory. The failure is deferred * to ::cuMemHostGetDevicePointer() because the memory may be mapped into * other CUDA contexts via the ::CU_MEMHOSTREGISTER_PORTABLE flag. * * For devices that have a non-zero value for the device attribute * ::CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM, the memory * can also be accessed from the device using the host pointer \p p. * The device pointer returned by ::cuMemHostGetDevicePointer() may or may not * match the original host pointer \p ptr and depends on the devices visible to the * application. If all devices visible to the application have a non-zero value for the * device attribute, the device pointer returned by ::cuMemHostGetDevicePointer() * will match the original pointer \p ptr. If any device visible to the application * has a zero value for the device attribute, the device pointer returned by * ::cuMemHostGetDevicePointer() will not match the original host pointer \p ptr, * but it will be suitable for use on all devices provided Unified Virtual Addressing * is enabled. In such systems, it is valid to access the memory using either pointer * on devices that have a non-zero value for the device attribute. Note however that * such devices should access the memory using only of the two pointers and not both. * * The memory page-locked by this function must be unregistered with * ::cuMemHostUnregister(). * * \param p - Host pointer to memory to page-lock * \param bytesize - Size in bytes of the address range to page-lock * \param Flags - Flags for allocation request * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa * ::cuMemHostUnregister, * ::cuMemHostGetFlags, * ::cuMemHostGetDevicePointer, * ::cudaHostRegister */ CUresult CUDAAPI cuMemHostRegister(void *p, size_t bytesize, unsigned int Flags); /** * \brief Unregisters a memory range that was registered with cuMemHostRegister. * * Unmaps the memory range whose base address is specified by \p p, and makes * it pageable again. * * The base address must be the same one specified to ::cuMemHostRegister(). * * \param p - Host pointer to memory to unregister * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED, * \notefnerr * * \sa * ::cuMemHostRegister, * ::cudaHostUnregister */ CUresult CUDAAPI cuMemHostUnregister(void *p); /** * \brief Copies memory * * Copies data between two pointers. * \p dst and \p src are base pointers of the destination and source, respectively. * \p ByteCount specifies the number of bytes to copy. * Note that this function infers the type of the transfer (host to host, host to * device, device to device, or device to host) from the pointer values. This * function is only allowed in contexts which support unified addressing. * * \param dst - Destination unified virtual address space pointer * \param src - Source unified virtual address space pointer * \param ByteCount - Size of memory copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * \note_memcpy * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpy, * ::cudaMemcpyToSymbol, * ::cudaMemcpyFromSymbol */ CUresult CUDAAPI cuMemcpy(CUdeviceptr dst, CUdeviceptr src, size_t ByteCount); /** * \brief Copies device memory between two contexts * * Copies from device memory in one context to device memory in another * context. \p dstDevice is the base device pointer of the destination memory * and \p dstContext is the destination context. \p srcDevice is the base * device pointer of the source memory and \p srcContext is the source pointer. * \p ByteCount specifies the number of bytes to copy. * * \param dstDevice - Destination device pointer * \param dstContext - Destination context * \param srcDevice - Source device pointer * \param srcContext - Source context * \param ByteCount - Size of memory copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * * \sa ::cuMemcpyDtoD, ::cuMemcpy3DPeer, ::cuMemcpyDtoDAsync, ::cuMemcpyPeerAsync, * ::cuMemcpy3DPeerAsync, * ::cudaMemcpyPeer */ CUresult CUDAAPI cuMemcpyPeer(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount); /** * \brief Copies memory from Host to Device * * Copies from host memory to device memory. \p dstDevice and \p srcHost are * the base addresses of the destination and source, respectively. \p ByteCount * specifies the number of bytes to copy. * * \param dstDevice - Destination device pointer * \param srcHost - Source host pointer * \param ByteCount - Size of memory copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * \note_memcpy * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpy, * ::cudaMemcpyToSymbol */ CUresult CUDAAPI cuMemcpyHtoD(CUdeviceptr dstDevice, const void *srcHost, size_t ByteCount); /** * \brief Copies memory from Device to Host * * Copies from device to host memory. \p dstHost and \p srcDevice specify the * base pointers of the destination and source, respectively. \p ByteCount * specifies the number of bytes to copy. * * \param dstHost - Destination host pointer * \param srcDevice - Source device pointer * \param ByteCount - Size of memory copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * \note_memcpy * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpy, * ::cudaMemcpyFromSymbol */ CUresult CUDAAPI cuMemcpyDtoH(void *dstHost, CUdeviceptr srcDevice, size_t ByteCount); /** * \brief Copies memory from Device to Device * * Copies from device memory to device memory. \p dstDevice and \p srcDevice * are the base pointers of the destination and source, respectively. * \p ByteCount specifies the number of bytes to copy. * * \param dstDevice - Destination device pointer * \param srcDevice - Source device pointer * \param ByteCount - Size of memory copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpy, * ::cudaMemcpyToSymbol, * ::cudaMemcpyFromSymbol */ CUresult CUDAAPI cuMemcpyDtoD(CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount); /** * \brief Copies memory from Device to Array * * Copies from device memory to a 1D CUDA array. \p dstArray and \p dstOffset * specify the CUDA array handle and starting index of the destination data. * \p srcDevice specifies the base pointer of the source. \p ByteCount * specifies the number of bytes to copy. * * \param dstArray - Destination array * \param dstOffset - Offset in bytes of destination array * \param srcDevice - Source device pointer * \param ByteCount - Size of memory copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpyToArray */ CUresult CUDAAPI cuMemcpyDtoA(CUarray dstArray, size_t dstOffset, CUdeviceptr srcDevice, size_t ByteCount); /** * \brief Copies memory from Array to Device * * Copies from one 1D CUDA array to device memory. \p dstDevice specifies the * base pointer of the destination and must be naturally aligned with the CUDA * array elements. \p srcArray and \p srcOffset specify the CUDA array handle * and the offset in bytes into the array where the copy is to begin. * \p ByteCount specifies the number of bytes to copy and must be evenly * divisible by the array element size. * * \param dstDevice - Destination device pointer * \param srcArray - Source array * \param srcOffset - Offset in bytes of source array * \param ByteCount - Size of memory copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpyFromArray */ CUresult CUDAAPI cuMemcpyAtoD(CUdeviceptr dstDevice, CUarray srcArray, size_t srcOffset, size_t ByteCount); /** * \brief Copies memory from Host to Array * * Copies from host memory to a 1D CUDA array. \p dstArray and \p dstOffset * specify the CUDA array handle and starting offset in bytes of the destination * data. \p pSrc specifies the base address of the source. \p ByteCount specifies * the number of bytes to copy. * * \param dstArray - Destination array * \param dstOffset - Offset in bytes of destination array * \param srcHost - Source host pointer * \param ByteCount - Size of memory copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * \note_memcpy * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpyToArray */ CUresult CUDAAPI cuMemcpyHtoA(CUarray dstArray, size_t dstOffset, const void *srcHost, size_t ByteCount); /** * \brief Copies memory from Array to Host * * Copies from one 1D CUDA array to host memory. \p dstHost specifies the base * pointer of the destination. \p srcArray and \p srcOffset specify the CUDA * array handle and starting offset in bytes of the source data. * \p ByteCount specifies the number of bytes to copy. * * \param dstHost - Destination device pointer * \param srcArray - Source array * \param srcOffset - Offset in bytes of source array * \param ByteCount - Size of memory copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * \note_memcpy * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpyFromArray */ CUresult CUDAAPI cuMemcpyAtoH(void *dstHost, CUarray srcArray, size_t srcOffset, size_t ByteCount); /** * \brief Copies memory from Array to Array * * Copies from one 1D CUDA array to another. \p dstArray and \p srcArray * specify the handles of the destination and source CUDA arrays for the copy, * respectively. \p dstOffset and \p srcOffset specify the destination and * source offsets in bytes into the CUDA arrays. \p ByteCount is the number of * bytes to be copied. The size of the elements in the CUDA arrays need not be * the same format, but the elements must be the same size; and count must be * evenly divisible by that size. * * \param dstArray - Destination array * \param dstOffset - Offset in bytes of destination array * \param srcArray - Source array * \param srcOffset - Offset in bytes of source array * \param ByteCount - Size of memory copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpyArrayToArray */ CUresult CUDAAPI cuMemcpyAtoA(CUarray dstArray, size_t dstOffset, CUarray srcArray, size_t srcOffset, size_t ByteCount); /** * \brief Copies memory for 2D arrays * * Perform a 2D memory copy according to the parameters specified in \p pCopy. * The ::CUDA_MEMCPY2D structure is defined as: * * \code typedef struct CUDA_MEMCPY2D_st { unsigned int srcXInBytes, srcY; CUmemorytype srcMemoryType; const void *srcHost; CUdeviceptr srcDevice; CUarray srcArray; unsigned int srcPitch; unsigned int dstXInBytes, dstY; CUmemorytype dstMemoryType; void *dstHost; CUdeviceptr dstDevice; CUarray dstArray; unsigned int dstPitch; unsigned int WidthInBytes; unsigned int Height; } CUDA_MEMCPY2D; * \endcode * where: * - ::srcMemoryType and ::dstMemoryType specify the type of memory of the * source and destination, respectively; ::CUmemorytype_enum is defined as: * * \code typedef enum CUmemorytype_enum { CU_MEMORYTYPE_HOST = 0x01, CU_MEMORYTYPE_DEVICE = 0x02, CU_MEMORYTYPE_ARRAY = 0x03, CU_MEMORYTYPE_UNIFIED = 0x04 } CUmemorytype; * \endcode * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_UNIFIED, ::srcDevice and ::srcPitch * specify the (unified virtual address space) base address of the source data * and the bytes per row to apply. ::srcArray is ignored. * This value may be used only if unified addressing is supported in the calling * context. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_HOST, ::srcHost and ::srcPitch * specify the (host) base address of the source data and the bytes per row to * apply. ::srcArray is ignored. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_DEVICE, ::srcDevice and ::srcPitch * specify the (device) base address of the source data and the bytes per row * to apply. ::srcArray is ignored. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_ARRAY, ::srcArray specifies the * handle of the source data. ::srcHost, ::srcDevice and ::srcPitch are * ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_HOST, ::dstHost and ::dstPitch * specify the (host) base address of the destination data and the bytes per * row to apply. ::dstArray is ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_UNIFIED, ::dstDevice and ::dstPitch * specify the (unified virtual address space) base address of the source data * and the bytes per row to apply. ::dstArray is ignored. * This value may be used only if unified addressing is supported in the calling * context. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_DEVICE, ::dstDevice and ::dstPitch * specify the (device) base address of the destination data and the bytes per * row to apply. ::dstArray is ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_ARRAY, ::dstArray specifies the * handle of the destination data. ::dstHost, ::dstDevice and ::dstPitch are * ignored. * * - ::srcXInBytes and ::srcY specify the base address of the source data for * the copy. * * \par * For host pointers, the starting address is * \code void* Start = (void*)((char*)srcHost+srcY*srcPitch + srcXInBytes); * \endcode * * \par * For device pointers, the starting address is * \code CUdeviceptr Start = srcDevice+srcY*srcPitch+srcXInBytes; * \endcode * * \par * For CUDA arrays, ::srcXInBytes must be evenly divisible by the array * element size. * * - ::dstXInBytes and ::dstY specify the base address of the destination data * for the copy. * * \par * For host pointers, the base address is * \code void* dstStart = (void*)((char*)dstHost+dstY*dstPitch + dstXInBytes); * \endcode * * \par * For device pointers, the starting address is * \code CUdeviceptr dstStart = dstDevice+dstY*dstPitch+dstXInBytes; * \endcode * * \par * For CUDA arrays, ::dstXInBytes must be evenly divisible by the array * element size. * * - ::WidthInBytes and ::Height specify the width (in bytes) and height of * the 2D copy being performed. * - If specified, ::srcPitch must be greater than or equal to ::WidthInBytes + * ::srcXInBytes, and ::dstPitch must be greater than or equal to * ::WidthInBytes + dstXInBytes. * * \par * ::cuMemcpy2D() returns an error if any pitch is greater than the maximum * allowed (::CU_DEVICE_ATTRIBUTE_MAX_PITCH). ::cuMemAllocPitch() passes back * pitches that always work with ::cuMemcpy2D(). On intra-device memory copies * (device to device, CUDA array to device, CUDA array to CUDA array), * ::cuMemcpy2D() may fail for pitches not computed by ::cuMemAllocPitch(). * ::cuMemcpy2DUnaligned() does not have this restriction, but may run * significantly slower in the cases where ::cuMemcpy2D() would have returned * an error code. * * \param pCopy - Parameters for the memory copy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpy2D, * ::cudaMemcpy2DToArray, * ::cudaMemcpy2DFromArray */ CUresult CUDAAPI cuMemcpy2D(const CUDA_MEMCPY2D *pCopy); /** * \brief Copies memory for 2D arrays * * Perform a 2D memory copy according to the parameters specified in \p pCopy. * The ::CUDA_MEMCPY2D structure is defined as: * * \code typedef struct CUDA_MEMCPY2D_st { unsigned int srcXInBytes, srcY; CUmemorytype srcMemoryType; const void *srcHost; CUdeviceptr srcDevice; CUarray srcArray; unsigned int srcPitch; unsigned int dstXInBytes, dstY; CUmemorytype dstMemoryType; void *dstHost; CUdeviceptr dstDevice; CUarray dstArray; unsigned int dstPitch; unsigned int WidthInBytes; unsigned int Height; } CUDA_MEMCPY2D; * \endcode * where: * - ::srcMemoryType and ::dstMemoryType specify the type of memory of the * source and destination, respectively; ::CUmemorytype_enum is defined as: * * \code typedef enum CUmemorytype_enum { CU_MEMORYTYPE_HOST = 0x01, CU_MEMORYTYPE_DEVICE = 0x02, CU_MEMORYTYPE_ARRAY = 0x03, CU_MEMORYTYPE_UNIFIED = 0x04 } CUmemorytype; * \endcode * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_UNIFIED, ::srcDevice and ::srcPitch * specify the (unified virtual address space) base address of the source data * and the bytes per row to apply. ::srcArray is ignored. * This value may be used only if unified addressing is supported in the calling * context. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_HOST, ::srcHost and ::srcPitch * specify the (host) base address of the source data and the bytes per row to * apply. ::srcArray is ignored. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_DEVICE, ::srcDevice and ::srcPitch * specify the (device) base address of the source data and the bytes per row * to apply. ::srcArray is ignored. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_ARRAY, ::srcArray specifies the * handle of the source data. ::srcHost, ::srcDevice and ::srcPitch are * ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_UNIFIED, ::dstDevice and ::dstPitch * specify the (unified virtual address space) base address of the source data * and the bytes per row to apply. ::dstArray is ignored. * This value may be used only if unified addressing is supported in the calling * context. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_HOST, ::dstHost and ::dstPitch * specify the (host) base address of the destination data and the bytes per * row to apply. ::dstArray is ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_DEVICE, ::dstDevice and ::dstPitch * specify the (device) base address of the destination data and the bytes per * row to apply. ::dstArray is ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_ARRAY, ::dstArray specifies the * handle of the destination data. ::dstHost, ::dstDevice and ::dstPitch are * ignored. * * - ::srcXInBytes and ::srcY specify the base address of the source data for * the copy. * * \par * For host pointers, the starting address is * \code void* Start = (void*)((char*)srcHost+srcY*srcPitch + srcXInBytes); * \endcode * * \par * For device pointers, the starting address is * \code CUdeviceptr Start = srcDevice+srcY*srcPitch+srcXInBytes; * \endcode * * \par * For CUDA arrays, ::srcXInBytes must be evenly divisible by the array * element size. * * - ::dstXInBytes and ::dstY specify the base address of the destination data * for the copy. * * \par * For host pointers, the base address is * \code void* dstStart = (void*)((char*)dstHost+dstY*dstPitch + dstXInBytes); * \endcode * * \par * For device pointers, the starting address is * \code CUdeviceptr dstStart = dstDevice+dstY*dstPitch+dstXInBytes; * \endcode * * \par * For CUDA arrays, ::dstXInBytes must be evenly divisible by the array * element size. * * - ::WidthInBytes and ::Height specify the width (in bytes) and height of * the 2D copy being performed. * - If specified, ::srcPitch must be greater than or equal to ::WidthInBytes + * ::srcXInBytes, and ::dstPitch must be greater than or equal to * ::WidthInBytes + dstXInBytes. * * \par * ::cuMemcpy2D() returns an error if any pitch is greater than the maximum * allowed (::CU_DEVICE_ATTRIBUTE_MAX_PITCH). ::cuMemAllocPitch() passes back * pitches that always work with ::cuMemcpy2D(). On intra-device memory copies * (device to device, CUDA array to device, CUDA array to CUDA array), * ::cuMemcpy2D() may fail for pitches not computed by ::cuMemAllocPitch(). * ::cuMemcpy2DUnaligned() does not have this restriction, but may run * significantly slower in the cases where ::cuMemcpy2D() would have returned * an error code. * * \param pCopy - Parameters for the memory copy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpy2D, * ::cudaMemcpy2DToArray, * ::cudaMemcpy2DFromArray */ CUresult CUDAAPI cuMemcpy2DUnaligned(const CUDA_MEMCPY2D *pCopy); /** * \brief Copies memory for 3D arrays * * Perform a 3D memory copy according to the parameters specified in * \p pCopy. The ::CUDA_MEMCPY3D structure is defined as: * * \code typedef struct CUDA_MEMCPY3D_st { unsigned int srcXInBytes, srcY, srcZ; unsigned int srcLOD; CUmemorytype srcMemoryType; const void *srcHost; CUdeviceptr srcDevice; CUarray srcArray; unsigned int srcPitch; // ignored when src is array unsigned int srcHeight; // ignored when src is array; may be 0 if Depth==1 unsigned int dstXInBytes, dstY, dstZ; unsigned int dstLOD; CUmemorytype dstMemoryType; void *dstHost; CUdeviceptr dstDevice; CUarray dstArray; unsigned int dstPitch; // ignored when dst is array unsigned int dstHeight; // ignored when dst is array; may be 0 if Depth==1 unsigned int WidthInBytes; unsigned int Height; unsigned int Depth; } CUDA_MEMCPY3D; * \endcode * where: * - ::srcMemoryType and ::dstMemoryType specify the type of memory of the * source and destination, respectively; ::CUmemorytype_enum is defined as: * * \code typedef enum CUmemorytype_enum { CU_MEMORYTYPE_HOST = 0x01, CU_MEMORYTYPE_DEVICE = 0x02, CU_MEMORYTYPE_ARRAY = 0x03, CU_MEMORYTYPE_UNIFIED = 0x04 } CUmemorytype; * \endcode * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_UNIFIED, ::srcDevice and ::srcPitch * specify the (unified virtual address space) base address of the source data * and the bytes per row to apply. ::srcArray is ignored. * This value may be used only if unified addressing is supported in the calling * context. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_HOST, ::srcHost, ::srcPitch and * ::srcHeight specify the (host) base address of the source data, the bytes * per row, and the height of each 2D slice of the 3D array. ::srcArray is * ignored. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_DEVICE, ::srcDevice, ::srcPitch and * ::srcHeight specify the (device) base address of the source data, the bytes * per row, and the height of each 2D slice of the 3D array. ::srcArray is * ignored. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_ARRAY, ::srcArray specifies the * handle of the source data. ::srcHost, ::srcDevice, ::srcPitch and * ::srcHeight are ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_UNIFIED, ::dstDevice and ::dstPitch * specify the (unified virtual address space) base address of the source data * and the bytes per row to apply. ::dstArray is ignored. * This value may be used only if unified addressing is supported in the calling * context. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_HOST, ::dstHost and ::dstPitch * specify the (host) base address of the destination data, the bytes per row, * and the height of each 2D slice of the 3D array. ::dstArray is ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_DEVICE, ::dstDevice and ::dstPitch * specify the (device) base address of the destination data, the bytes per * row, and the height of each 2D slice of the 3D array. ::dstArray is ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_ARRAY, ::dstArray specifies the * handle of the destination data. ::dstHost, ::dstDevice, ::dstPitch and * ::dstHeight are ignored. * * - ::srcXInBytes, ::srcY and ::srcZ specify the base address of the source * data for the copy. * * \par * For host pointers, the starting address is * \code void* Start = (void*)((char*)srcHost+(srcZ*srcHeight+srcY)*srcPitch + srcXInBytes); * \endcode * * \par * For device pointers, the starting address is * \code CUdeviceptr Start = srcDevice+(srcZ*srcHeight+srcY)*srcPitch+srcXInBytes; * \endcode * * \par * For CUDA arrays, ::srcXInBytes must be evenly divisible by the array * element size. * * - dstXInBytes, ::dstY and ::dstZ specify the base address of the * destination data for the copy. * * \par * For host pointers, the base address is * \code void* dstStart = (void*)((char*)dstHost+(dstZ*dstHeight+dstY)*dstPitch + dstXInBytes); * \endcode * * \par * For device pointers, the starting address is * \code CUdeviceptr dstStart = dstDevice+(dstZ*dstHeight+dstY)*dstPitch+dstXInBytes; * \endcode * * \par * For CUDA arrays, ::dstXInBytes must be evenly divisible by the array * element size. * * - ::WidthInBytes, ::Height and ::Depth specify the width (in bytes), height * and depth of the 3D copy being performed. * - If specified, ::srcPitch must be greater than or equal to ::WidthInBytes + * ::srcXInBytes, and ::dstPitch must be greater than or equal to * ::WidthInBytes + dstXInBytes. * - If specified, ::srcHeight must be greater than or equal to ::Height + * ::srcY, and ::dstHeight must be greater than or equal to ::Height + ::dstY. * * \par * ::cuMemcpy3D() returns an error if any pitch is greater than the maximum * allowed (::CU_DEVICE_ATTRIBUTE_MAX_PITCH). * * The ::srcLOD and ::dstLOD members of the ::CUDA_MEMCPY3D structure must be * set to 0. * * \param pCopy - Parameters for the memory copy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMemcpy3D */ CUresult CUDAAPI cuMemcpy3D(const CUDA_MEMCPY3D *pCopy); /** * \brief Copies memory between contexts * * Perform a 3D memory copy according to the parameters specified in * \p pCopy. See the definition of the ::CUDA_MEMCPY3D_PEER structure * for documentation of its parameters. * * \param pCopy - Parameters for the memory copy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_sync * * \sa ::cuMemcpyDtoD, ::cuMemcpyPeer, ::cuMemcpyDtoDAsync, ::cuMemcpyPeerAsync, * ::cuMemcpy3DPeerAsync, * ::cudaMemcpy3DPeer */ CUresult CUDAAPI cuMemcpy3DPeer(const CUDA_MEMCPY3D_PEER *pCopy); /** * \brief Copies memory asynchronously * * Copies data between two pointers. * \p dst and \p src are base pointers of the destination and source, respectively. * \p ByteCount specifies the number of bytes to copy. * Note that this function infers the type of the transfer (host to host, host to * device, device to device, or device to host) from the pointer values. This * function is only allowed in contexts which support unified addressing. * * \param dst - Destination unified virtual address space pointer * \param src - Source unified virtual address space pointer * \param ByteCount - Size of memory copy in bytes * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * \note_async * \note_null_stream * \note_memcpy * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemcpyAsync, * ::cudaMemcpyToSymbolAsync, * ::cudaMemcpyFromSymbolAsync */ CUresult CUDAAPI cuMemcpyAsync(CUdeviceptr dst, CUdeviceptr src, size_t ByteCount, CUstream hStream); /** * \brief Copies device memory between two contexts asynchronously. * * Copies from device memory in one context to device memory in another * context. \p dstDevice is the base device pointer of the destination memory * and \p dstContext is the destination context. \p srcDevice is the base * device pointer of the source memory and \p srcContext is the source pointer. * \p ByteCount specifies the number of bytes to copy. * * \param dstDevice - Destination device pointer * \param dstContext - Destination context * \param srcDevice - Source device pointer * \param srcContext - Source context * \param ByteCount - Size of memory copy in bytes * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * \note_async * \note_null_stream * * \sa ::cuMemcpyDtoD, ::cuMemcpyPeer, ::cuMemcpy3DPeer, ::cuMemcpyDtoDAsync, * ::cuMemcpy3DPeerAsync, * ::cudaMemcpyPeerAsync */ CUresult CUDAAPI cuMemcpyPeerAsync(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount, CUstream hStream); /** * \brief Copies memory from Host to Device * * Copies from host memory to device memory. \p dstDevice and \p srcHost are * the base addresses of the destination and source, respectively. \p ByteCount * specifies the number of bytes to copy. * * \param dstDevice - Destination device pointer * \param srcHost - Source host pointer * \param ByteCount - Size of memory copy in bytes * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * \note_async * \note_null_stream * \note_memcpy * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemcpyAsync, * ::cudaMemcpyToSymbolAsync */ CUresult CUDAAPI cuMemcpyHtoDAsync(CUdeviceptr dstDevice, const void *srcHost, size_t ByteCount, CUstream hStream); /** * \brief Copies memory from Device to Host * * Copies from device to host memory. \p dstHost and \p srcDevice specify the * base pointers of the destination and source, respectively. \p ByteCount * specifies the number of bytes to copy. * * \param dstHost - Destination host pointer * \param srcDevice - Source device pointer * \param ByteCount - Size of memory copy in bytes * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * \note_async * \note_null_stream * \note_memcpy * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemcpyAsync, * ::cudaMemcpyFromSymbolAsync */ CUresult CUDAAPI cuMemcpyDtoHAsync(void *dstHost, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream); /** * \brief Copies memory from Device to Device * * Copies from device memory to device memory. \p dstDevice and \p srcDevice * are the base pointers of the destination and source, respectively. * \p ByteCount specifies the number of bytes to copy. * * \param dstDevice - Destination device pointer * \param srcDevice - Source device pointer * \param ByteCount - Size of memory copy in bytes * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * \note_async * \note_null_stream * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemcpyAsync, * ::cudaMemcpyToSymbolAsync, * ::cudaMemcpyFromSymbolAsync */ CUresult CUDAAPI cuMemcpyDtoDAsync(CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream); /** * \brief Copies memory from Host to Array * * Copies from host memory to a 1D CUDA array. \p dstArray and \p dstOffset * specify the CUDA array handle and starting offset in bytes of the * destination data. \p srcHost specifies the base address of the source. * \p ByteCount specifies the number of bytes to copy. * * \param dstArray - Destination array * \param dstOffset - Offset in bytes of destination array * \param srcHost - Source host pointer * \param ByteCount - Size of memory copy in bytes * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * \note_async * \note_null_stream * \note_memcpy * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemcpyToArrayAsync */ CUresult CUDAAPI cuMemcpyHtoAAsync(CUarray dstArray, size_t dstOffset, const void *srcHost, size_t ByteCount, CUstream hStream); /** * \brief Copies memory from Array to Host * * Copies from one 1D CUDA array to host memory. \p dstHost specifies the base * pointer of the destination. \p srcArray and \p srcOffset specify the CUDA * array handle and starting offset in bytes of the source data. * \p ByteCount specifies the number of bytes to copy. * * \param dstHost - Destination pointer * \param srcArray - Source array * \param srcOffset - Offset in bytes of source array * \param ByteCount - Size of memory copy in bytes * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * \note_async * \note_null_stream * \note_memcpy * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemcpyFromArrayAsync */ CUresult CUDAAPI cuMemcpyAtoHAsync(void *dstHost, CUarray srcArray, size_t srcOffset, size_t ByteCount, CUstream hStream); /** * \brief Copies memory for 2D arrays * * Perform a 2D memory copy according to the parameters specified in \p pCopy. * The ::CUDA_MEMCPY2D structure is defined as: * * \code typedef struct CUDA_MEMCPY2D_st { unsigned int srcXInBytes, srcY; CUmemorytype srcMemoryType; const void *srcHost; CUdeviceptr srcDevice; CUarray srcArray; unsigned int srcPitch; unsigned int dstXInBytes, dstY; CUmemorytype dstMemoryType; void *dstHost; CUdeviceptr dstDevice; CUarray dstArray; unsigned int dstPitch; unsigned int WidthInBytes; unsigned int Height; } CUDA_MEMCPY2D; * \endcode * where: * - ::srcMemoryType and ::dstMemoryType specify the type of memory of the * source and destination, respectively; ::CUmemorytype_enum is defined as: * * \code typedef enum CUmemorytype_enum { CU_MEMORYTYPE_HOST = 0x01, CU_MEMORYTYPE_DEVICE = 0x02, CU_MEMORYTYPE_ARRAY = 0x03, CU_MEMORYTYPE_UNIFIED = 0x04 } CUmemorytype; * \endcode * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_HOST, ::srcHost and ::srcPitch * specify the (host) base address of the source data and the bytes per row to * apply. ::srcArray is ignored. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_UNIFIED, ::srcDevice and ::srcPitch * specify the (unified virtual address space) base address of the source data * and the bytes per row to apply. ::srcArray is ignored. * This value may be used only if unified addressing is supported in the calling * context. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_DEVICE, ::srcDevice and ::srcPitch * specify the (device) base address of the source data and the bytes per row * to apply. ::srcArray is ignored. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_ARRAY, ::srcArray specifies the * handle of the source data. ::srcHost, ::srcDevice and ::srcPitch are * ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_UNIFIED, ::dstDevice and ::dstPitch * specify the (unified virtual address space) base address of the source data * and the bytes per row to apply. ::dstArray is ignored. * This value may be used only if unified addressing is supported in the calling * context. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_HOST, ::dstHost and ::dstPitch * specify the (host) base address of the destination data and the bytes per * row to apply. ::dstArray is ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_DEVICE, ::dstDevice and ::dstPitch * specify the (device) base address of the destination data and the bytes per * row to apply. ::dstArray is ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_ARRAY, ::dstArray specifies the * handle of the destination data. ::dstHost, ::dstDevice and ::dstPitch are * ignored. * * - ::srcXInBytes and ::srcY specify the base address of the source data for * the copy. * * \par * For host pointers, the starting address is * \code void* Start = (void*)((char*)srcHost+srcY*srcPitch + srcXInBytes); * \endcode * * \par * For device pointers, the starting address is * \code CUdeviceptr Start = srcDevice+srcY*srcPitch+srcXInBytes; * \endcode * * \par * For CUDA arrays, ::srcXInBytes must be evenly divisible by the array * element size. * * - ::dstXInBytes and ::dstY specify the base address of the destination data * for the copy. * * \par * For host pointers, the base address is * \code void* dstStart = (void*)((char*)dstHost+dstY*dstPitch + dstXInBytes); * \endcode * * \par * For device pointers, the starting address is * \code CUdeviceptr dstStart = dstDevice+dstY*dstPitch+dstXInBytes; * \endcode * * \par * For CUDA arrays, ::dstXInBytes must be evenly divisible by the array * element size. * * - ::WidthInBytes and ::Height specify the width (in bytes) and height of * the 2D copy being performed. * - If specified, ::srcPitch must be greater than or equal to ::WidthInBytes + * ::srcXInBytes, and ::dstPitch must be greater than or equal to * ::WidthInBytes + dstXInBytes. * - If specified, ::srcPitch must be greater than or equal to ::WidthInBytes + * ::srcXInBytes, and ::dstPitch must be greater than or equal to * ::WidthInBytes + dstXInBytes. * - If specified, ::srcHeight must be greater than or equal to ::Height + * ::srcY, and ::dstHeight must be greater than or equal to ::Height + ::dstY. * * \par * ::cuMemcpy2DAsync() returns an error if any pitch is greater than the maximum * allowed (::CU_DEVICE_ATTRIBUTE_MAX_PITCH). ::cuMemAllocPitch() passes back * pitches that always work with ::cuMemcpy2D(). On intra-device memory copies * (device to device, CUDA array to device, CUDA array to CUDA array), * ::cuMemcpy2DAsync() may fail for pitches not computed by ::cuMemAllocPitch(). * * \param pCopy - Parameters for the memory copy * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * \note_async * \note_null_stream * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemcpy2DAsync, * ::cudaMemcpy2DToArrayAsync, * ::cudaMemcpy2DFromArrayAsync */ CUresult CUDAAPI cuMemcpy2DAsync(const CUDA_MEMCPY2D *pCopy, CUstream hStream); /** * \brief Copies memory for 3D arrays * * Perform a 3D memory copy according to the parameters specified in * \p pCopy. The ::CUDA_MEMCPY3D structure is defined as: * * \code typedef struct CUDA_MEMCPY3D_st { unsigned int srcXInBytes, srcY, srcZ; unsigned int srcLOD; CUmemorytype srcMemoryType; const void *srcHost; CUdeviceptr srcDevice; CUarray srcArray; unsigned int srcPitch; // ignored when src is array unsigned int srcHeight; // ignored when src is array; may be 0 if Depth==1 unsigned int dstXInBytes, dstY, dstZ; unsigned int dstLOD; CUmemorytype dstMemoryType; void *dstHost; CUdeviceptr dstDevice; CUarray dstArray; unsigned int dstPitch; // ignored when dst is array unsigned int dstHeight; // ignored when dst is array; may be 0 if Depth==1 unsigned int WidthInBytes; unsigned int Height; unsigned int Depth; } CUDA_MEMCPY3D; * \endcode * where: * - ::srcMemoryType and ::dstMemoryType specify the type of memory of the * source and destination, respectively; ::CUmemorytype_enum is defined as: * * \code typedef enum CUmemorytype_enum { CU_MEMORYTYPE_HOST = 0x01, CU_MEMORYTYPE_DEVICE = 0x02, CU_MEMORYTYPE_ARRAY = 0x03, CU_MEMORYTYPE_UNIFIED = 0x04 } CUmemorytype; * \endcode * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_UNIFIED, ::srcDevice and ::srcPitch * specify the (unified virtual address space) base address of the source data * and the bytes per row to apply. ::srcArray is ignored. * This value may be used only if unified addressing is supported in the calling * context. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_HOST, ::srcHost, ::srcPitch and * ::srcHeight specify the (host) base address of the source data, the bytes * per row, and the height of each 2D slice of the 3D array. ::srcArray is * ignored. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_DEVICE, ::srcDevice, ::srcPitch and * ::srcHeight specify the (device) base address of the source data, the bytes * per row, and the height of each 2D slice of the 3D array. ::srcArray is * ignored. * * \par * If ::srcMemoryType is ::CU_MEMORYTYPE_ARRAY, ::srcArray specifies the * handle of the source data. ::srcHost, ::srcDevice, ::srcPitch and * ::srcHeight are ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_UNIFIED, ::dstDevice and ::dstPitch * specify the (unified virtual address space) base address of the source data * and the bytes per row to apply. ::dstArray is ignored. * This value may be used only if unified addressing is supported in the calling * context. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_HOST, ::dstHost and ::dstPitch * specify the (host) base address of the destination data, the bytes per row, * and the height of each 2D slice of the 3D array. ::dstArray is ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_DEVICE, ::dstDevice and ::dstPitch * specify the (device) base address of the destination data, the bytes per * row, and the height of each 2D slice of the 3D array. ::dstArray is ignored. * * \par * If ::dstMemoryType is ::CU_MEMORYTYPE_ARRAY, ::dstArray specifies the * handle of the destination data. ::dstHost, ::dstDevice, ::dstPitch and * ::dstHeight are ignored. * * - ::srcXInBytes, ::srcY and ::srcZ specify the base address of the source * data for the copy. * * \par * For host pointers, the starting address is * \code void* Start = (void*)((char*)srcHost+(srcZ*srcHeight+srcY)*srcPitch + srcXInBytes); * \endcode * * \par * For device pointers, the starting address is * \code CUdeviceptr Start = srcDevice+(srcZ*srcHeight+srcY)*srcPitch+srcXInBytes; * \endcode * * \par * For CUDA arrays, ::srcXInBytes must be evenly divisible by the array * element size. * * - dstXInBytes, ::dstY and ::dstZ specify the base address of the * destination data for the copy. * * \par * For host pointers, the base address is * \code void* dstStart = (void*)((char*)dstHost+(dstZ*dstHeight+dstY)*dstPitch + dstXInBytes); * \endcode * * \par * For device pointers, the starting address is * \code CUdeviceptr dstStart = dstDevice+(dstZ*dstHeight+dstY)*dstPitch+dstXInBytes; * \endcode * * \par * For CUDA arrays, ::dstXInBytes must be evenly divisible by the array * element size. * * - ::WidthInBytes, ::Height and ::Depth specify the width (in bytes), height * and depth of the 3D copy being performed. * - If specified, ::srcPitch must be greater than or equal to ::WidthInBytes + * ::srcXInBytes, and ::dstPitch must be greater than or equal to * ::WidthInBytes + dstXInBytes. * - If specified, ::srcHeight must be greater than or equal to ::Height + * ::srcY, and ::dstHeight must be greater than or equal to ::Height + ::dstY. * * \par * ::cuMemcpy3DAsync() returns an error if any pitch is greater than the maximum * allowed (::CU_DEVICE_ATTRIBUTE_MAX_PITCH). * * The ::srcLOD and ::dstLOD members of the ::CUDA_MEMCPY3D structure must be * set to 0. * * \param pCopy - Parameters for the memory copy * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * \note_async * \note_null_stream * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemcpy3DAsync */ CUresult CUDAAPI cuMemcpy3DAsync(const CUDA_MEMCPY3D *pCopy, CUstream hStream); /** * \brief Copies memory between contexts asynchronously. * * Perform a 3D memory copy according to the parameters specified in * \p pCopy. See the definition of the ::CUDA_MEMCPY3D_PEER structure * for documentation of its parameters. * * \param pCopy - Parameters for the memory copy * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_async * \note_null_stream * * \sa ::cuMemcpyDtoD, ::cuMemcpyPeer, ::cuMemcpyDtoDAsync, ::cuMemcpyPeerAsync, * ::cuMemcpy3DPeerAsync, * ::cudaMemcpy3DPeerAsync */ CUresult CUDAAPI cuMemcpy3DPeerAsync(const CUDA_MEMCPY3D_PEER *pCopy, CUstream hStream); /** * \brief Initializes device memory * * Sets the memory range of \p N 8-bit values to the specified value * \p uc. * * \param dstDevice - Destination device pointer * \param uc - Value to set * \param N - Number of elements * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemset */ CUresult CUDAAPI cuMemsetD8(CUdeviceptr dstDevice, unsigned char uc, size_t N); /** * \brief Initializes device memory * * Sets the memory range of \p N 16-bit values to the specified value * \p us. The \p dstDevice pointer must be two byte aligned. * * \param dstDevice - Destination device pointer * \param us - Value to set * \param N - Number of elements * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemset */ CUresult CUDAAPI cuMemsetD16(CUdeviceptr dstDevice, unsigned short us, size_t N); /** * \brief Initializes device memory * * Sets the memory range of \p N 32-bit values to the specified value * \p ui. The \p dstDevice pointer must be four byte aligned. * * \param dstDevice - Destination device pointer * \param ui - Value to set * \param N - Number of elements * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32Async, * ::cudaMemset */ CUresult CUDAAPI cuMemsetD32(CUdeviceptr dstDevice, unsigned int ui, size_t N); /** * \brief Initializes device memory * * Sets the 2D memory range of \p Width 8-bit values to the specified value * \p uc. \p Height specifies the number of rows to set, and \p dstPitch * specifies the number of bytes between each row. This function performs * fastest when the pitch is one that has been passed back by * ::cuMemAllocPitch(). * * \param dstDevice - Destination device pointer * \param dstPitch - Pitch of destination device pointer(Unused if \p Height is 1) * \param uc - Value to set * \param Width - Width of row * \param Height - Number of rows * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemset2D */ CUresult CUDAAPI cuMemsetD2D8(CUdeviceptr dstDevice, size_t dstPitch, unsigned char uc, size_t Width, size_t Height); /** * \brief Initializes device memory * * Sets the 2D memory range of \p Width 16-bit values to the specified value * \p us. \p Height specifies the number of rows to set, and \p dstPitch * specifies the number of bytes between each row. The \p dstDevice pointer * and \p dstPitch offset must be two byte aligned. This function performs * fastest when the pitch is one that has been passed back by * ::cuMemAllocPitch(). * * \param dstDevice - Destination device pointer * \param dstPitch - Pitch of destination device pointer(Unused if \p Height is 1) * \param us - Value to set * \param Width - Width of row * \param Height - Number of rows * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemset2D */ CUresult CUDAAPI cuMemsetD2D16(CUdeviceptr dstDevice, size_t dstPitch, unsigned short us, size_t Width, size_t Height); /** * \brief Initializes device memory * * Sets the 2D memory range of \p Width 32-bit values to the specified value * \p ui. \p Height specifies the number of rows to set, and \p dstPitch * specifies the number of bytes between each row. The \p dstDevice pointer * and \p dstPitch offset must be four byte aligned. This function performs * fastest when the pitch is one that has been passed back by * ::cuMemAllocPitch(). * * \param dstDevice - Destination device pointer * \param dstPitch - Pitch of destination device pointer(Unused if \p Height is 1) * \param ui - Value to set * \param Width - Width of row * \param Height - Number of rows * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemset2D */ CUresult CUDAAPI cuMemsetD2D32(CUdeviceptr dstDevice, size_t dstPitch, unsigned int ui, size_t Width, size_t Height); /** * \brief Sets device memory * * Sets the memory range of \p N 8-bit values to the specified value * \p uc. * * \param dstDevice - Destination device pointer * \param uc - Value to set * \param N - Number of elements * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * \note_null_stream * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemsetAsync */ CUresult CUDAAPI cuMemsetD8Async(CUdeviceptr dstDevice, unsigned char uc, size_t N, CUstream hStream); /** * \brief Sets device memory * * Sets the memory range of \p N 16-bit values to the specified value * \p us. The \p dstDevice pointer must be two byte aligned. * * \param dstDevice - Destination device pointer * \param us - Value to set * \param N - Number of elements * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * \note_null_stream * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemsetAsync */ CUresult CUDAAPI cuMemsetD16Async(CUdeviceptr dstDevice, unsigned short us, size_t N, CUstream hStream); /** * \brief Sets device memory * * Sets the memory range of \p N 32-bit values to the specified value * \p ui. The \p dstDevice pointer must be four byte aligned. * * \param dstDevice - Destination device pointer * \param ui - Value to set * \param N - Number of elements * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * \note_null_stream * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, ::cuMemsetD32, * ::cudaMemsetAsync */ CUresult CUDAAPI cuMemsetD32Async(CUdeviceptr dstDevice, unsigned int ui, size_t N, CUstream hStream); /** * \brief Sets device memory * * Sets the 2D memory range of \p Width 8-bit values to the specified value * \p uc. \p Height specifies the number of rows to set, and \p dstPitch * specifies the number of bytes between each row. This function performs * fastest when the pitch is one that has been passed back by * ::cuMemAllocPitch(). * * \param dstDevice - Destination device pointer * \param dstPitch - Pitch of destination device pointer(Unused if \p Height is 1) * \param uc - Value to set * \param Width - Width of row * \param Height - Number of rows * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * \note_null_stream * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemset2DAsync */ CUresult CUDAAPI cuMemsetD2D8Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned char uc, size_t Width, size_t Height, CUstream hStream); /** * \brief Sets device memory * * Sets the 2D memory range of \p Width 16-bit values to the specified value * \p us. \p Height specifies the number of rows to set, and \p dstPitch * specifies the number of bytes between each row. The \p dstDevice pointer * and \p dstPitch offset must be two byte aligned. This function performs * fastest when the pitch is one that has been passed back by * ::cuMemAllocPitch(). * * \param dstDevice - Destination device pointer * \param dstPitch - Pitch of destination device pointer(Unused if \p Height is 1) * \param us - Value to set * \param Width - Width of row * \param Height - Number of rows * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * \note_null_stream * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D32, ::cuMemsetD2D32Async, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemset2DAsync */ CUresult CUDAAPI cuMemsetD2D16Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned short us, size_t Width, size_t Height, CUstream hStream); /** * \brief Sets device memory * * Sets the 2D memory range of \p Width 32-bit values to the specified value * \p ui. \p Height specifies the number of rows to set, and \p dstPitch * specifies the number of bytes between each row. The \p dstDevice pointer * and \p dstPitch offset must be four byte aligned. This function performs * fastest when the pitch is one that has been passed back by * ::cuMemAllocPitch(). * * \param dstDevice - Destination device pointer * \param dstPitch - Pitch of destination device pointer(Unused if \p Height is 1) * \param ui - Value to set * \param Width - Width of row * \param Height - Number of rows * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * \note_memset * \note_null_stream * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D8Async, * ::cuMemsetD2D16, ::cuMemsetD2D16Async, ::cuMemsetD2D32, * ::cuMemsetD8, ::cuMemsetD8Async, ::cuMemsetD16, ::cuMemsetD16Async, * ::cuMemsetD32, ::cuMemsetD32Async, * ::cudaMemset2DAsync */ CUresult CUDAAPI cuMemsetD2D32Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned int ui, size_t Width, size_t Height, CUstream hStream); /** * \brief Creates a 1D or 2D CUDA array * * Creates a CUDA array according to the ::CUDA_ARRAY_DESCRIPTOR structure * \p pAllocateArray and returns a handle to the new CUDA array in \p *pHandle. * The ::CUDA_ARRAY_DESCRIPTOR is defined as: * * \code typedef struct { unsigned int Width; unsigned int Height; CUarray_format Format; unsigned int NumChannels; } CUDA_ARRAY_DESCRIPTOR; * \endcode * where: * * - \p Width, and \p Height are the width, and height of the CUDA array (in * elements); the CUDA array is one-dimensional if height is 0, two-dimensional * otherwise; * - ::Format specifies the format of the elements; ::CUarray_format is * defined as: * \code typedef enum CUarray_format_enum { CU_AD_FORMAT_UNSIGNED_INT8 = 0x01, CU_AD_FORMAT_UNSIGNED_INT16 = 0x02, CU_AD_FORMAT_UNSIGNED_INT32 = 0x03, CU_AD_FORMAT_SIGNED_INT8 = 0x08, CU_AD_FORMAT_SIGNED_INT16 = 0x09, CU_AD_FORMAT_SIGNED_INT32 = 0x0a, CU_AD_FORMAT_HALF = 0x10, CU_AD_FORMAT_FLOAT = 0x20 } CUarray_format; * \endcode * - \p NumChannels specifies the number of packed components per CUDA array * element; it may be 1, 2, or 4; * * Here are examples of CUDA array descriptions: * * Description for a CUDA array of 2048 floats: * \code CUDA_ARRAY_DESCRIPTOR desc; desc.Format = CU_AD_FORMAT_FLOAT; desc.NumChannels = 1; desc.Width = 2048; desc.Height = 1; * \endcode * * Description for a 64 x 64 CUDA array of floats: * \code CUDA_ARRAY_DESCRIPTOR desc; desc.Format = CU_AD_FORMAT_FLOAT; desc.NumChannels = 1; desc.Width = 64; desc.Height = 64; * \endcode * * Description for a \p width x \p height CUDA array of 64-bit, 4x16-bit * float16's: * \code CUDA_ARRAY_DESCRIPTOR desc; desc.Format = CU_AD_FORMAT_HALF; desc.NumChannels = 4; desc.Width = width; desc.Height = height; * \endcode * * Description for a \p width x \p height CUDA array of 16-bit elements, each * of which is two 8-bit unsigned chars: * \code CUDA_ARRAY_DESCRIPTOR arrayDesc; desc.Format = CU_AD_FORMAT_UNSIGNED_INT8; desc.NumChannels = 2; desc.Width = width; desc.Height = height; * \endcode * * \param pHandle - Returned array * \param pAllocateArray - Array descriptor * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMallocArray */ CUresult CUDAAPI cuArrayCreate(CUarray *pHandle, const CUDA_ARRAY_DESCRIPTOR *pAllocateArray); /** * \brief Get a 1D or 2D CUDA array descriptor * * Returns in \p *pArrayDescriptor a descriptor containing information on the * format and dimensions of the CUDA array \p hArray. It is useful for * subroutines that have been passed a CUDA array, but need to know the CUDA * array parameters for validation or other purposes. * * \param pArrayDescriptor - Returned array descriptor * \param hArray - Array to get descriptor of * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaArrayGetInfo */ CUresult CUDAAPI cuArrayGetDescriptor(CUDA_ARRAY_DESCRIPTOR *pArrayDescriptor, CUarray hArray); /** * \brief Returns the layout properties of a sparse CUDA array * * Returns the layout properties of a sparse CUDA array in \p sparseProperties * If the CUDA array is not allocated with flag ::CUDA_ARRAY3D_SPARSE * ::CUDA_ERROR_INVALID_VALUE will be returned. * * If the returned value in ::CUDA_ARRAY_SPARSE_PROPERTIES::flags contains ::CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL, * then ::CUDA_ARRAY_SPARSE_PROPERTIES::miptailSize represents the total size of the array. Otherwise, it will be zero. * Also, the returned value in ::CUDA_ARRAY_SPARSE_PROPERTIES::miptailFirstLevel is always zero. * Note that the \p array must have been allocated using ::cuArrayCreate or ::cuArray3DCreate. For CUDA arrays obtained * using ::cuMipmappedArrayGetLevel, ::CUDA_ERROR_INVALID_VALUE will be returned. Instead, ::cuMipmappedArrayGetSparseProperties * must be used to obtain the sparse properties of the entire CUDA mipmapped array to which \p array belongs to. * * \return * ::CUDA_SUCCESS * ::CUDA_ERROR_INVALID_VALUE * * \param[out] sparseProperties - Pointer to ::CUDA_ARRAY_SPARSE_PROPERTIES * \param[in] array - CUDA array to get the sparse properties of * \sa ::cuMipmappedArrayGetSparseProperties, ::cuMemMapArrayAsync */ CUresult CUDAAPI cuArrayGetSparseProperties(CUDA_ARRAY_SPARSE_PROPERTIES *sparseProperties, CUarray array); /** * \brief Returns the layout properties of a sparse CUDA mipmapped array * * Returns the sparse array layout properties in \p sparseProperties * If the CUDA mipmapped array is not allocated with flag ::CUDA_ARRAY3D_SPARSE * ::CUDA_ERROR_INVALID_VALUE will be returned. * * For non-layered CUDA mipmapped arrays, ::CUDA_ARRAY_SPARSE_PROPERTIES::miptailSize returns the * size of the mip tail region. The mip tail region includes all mip levels whose width, height or depth * is less than that of the tile. * For layered CUDA mipmapped arrays, if ::CUDA_ARRAY_SPARSE_PROPERTIES::flags contains ::CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL, * then ::CUDA_ARRAY_SPARSE_PROPERTIES::miptailSize specifies the size of the mip tail of all layers combined. * Otherwise, ::CUDA_ARRAY_SPARSE_PROPERTIES::miptailSize specifies mip tail size per layer. * The returned value of ::CUDA_ARRAY_SPARSE_PROPERTIES::miptailFirstLevel is valid only if ::CUDA_ARRAY_SPARSE_PROPERTIES::miptailSize is non-zero. * * \return * ::CUDA_SUCCESS * ::CUDA_ERROR_INVALID_VALUE * * \param[out] sparseProperties - Pointer to ::CUDA_ARRAY_SPARSE_PROPERTIES * \param[in] mipmap - CUDA mipmapped array to get the sparse properties of * \sa ::cuArrayGetSparseProperties, ::cuMemMapArrayAsync */ CUresult CUDAAPI cuMipmappedArrayGetSparseProperties(CUDA_ARRAY_SPARSE_PROPERTIES *sparseProperties, CUmipmappedArray mipmap); /** * \brief Returns the memory requirements of a CUDA array * * Returns the memory requirements of a CUDA array in \p memoryRequirements * If the CUDA array is not allocated with flag ::CUDA_ARRAY3D_DEFERRED_MAPPING * ::CUDA_ERROR_INVALID_VALUE will be returned. * * The returned value in ::CUDA_ARRAY_MEMORY_REQUIREMENTS::size * represents the total size of the CUDA array. * The returned value in ::CUDA_ARRAY_MEMORY_REQUIREMENTS::alignment * represents the alignment necessary for mapping the CUDA array. * * \return * ::CUDA_SUCCESS * ::CUDA_ERROR_INVALID_VALUE * * \param[out] memoryRequirements - Pointer to ::CUDA_ARRAY_MEMORY_REQUIREMENTS * \param[in] array - CUDA array to get the memory requirements of * \param[in] device - Device to get the memory requirements for * \sa ::cuMipmappedArrayGetMemoryRequirements, ::cuMemMapArrayAsync */ CUresult CUDAAPI cuArrayGetMemoryRequirements(CUDA_ARRAY_MEMORY_REQUIREMENTS *memoryRequirements, CUarray array, CUdevice device); /** * \brief Returns the memory requirements of a CUDA mipmapped array * * Returns the memory requirements of a CUDA mipmapped array in \p memoryRequirements * If the CUDA mipmapped array is not allocated with flag ::CUDA_ARRAY3D_DEFERRED_MAPPING * ::CUDA_ERROR_INVALID_VALUE will be returned. * * The returned value in ::CUDA_ARRAY_MEMORY_REQUIREMENTS::size * represents the total size of the CUDA mipmapped array. * The returned value in ::CUDA_ARRAY_MEMORY_REQUIREMENTS::alignment * represents the alignment necessary for mapping the CUDA mipmapped * array. * * \return * ::CUDA_SUCCESS * ::CUDA_ERROR_INVALID_VALUE * * \param[out] memoryRequirements - Pointer to ::CUDA_ARRAY_MEMORY_REQUIREMENTS * \param[in] mipmap - CUDA mipmapped array to get the memory requirements of * \param[in] device - Device to get the memory requirements for * \sa ::cuArrayGetMemoryRequirements, ::cuMemMapArrayAsync */ CUresult CUDAAPI cuMipmappedArrayGetMemoryRequirements(CUDA_ARRAY_MEMORY_REQUIREMENTS *memoryRequirements, CUmipmappedArray mipmap, CUdevice device); /** * \brief Gets a CUDA array plane from a CUDA array * * Returns in \p pPlaneArray a CUDA array that represents a single format plane * of the CUDA array \p hArray. * * If \p planeIdx is greater than the maximum number of planes in this array or if the array does * not have a multi-planar format e.g: ::CU_AD_FORMAT_NV12, then ::CUDA_ERROR_INVALID_VALUE is returned. * * Note that if the \p hArray has format ::CU_AD_FORMAT_NV12, then passing in 0 for \p planeIdx returns * a CUDA array of the same size as \p hArray but with one channel and ::CU_AD_FORMAT_UNSIGNED_INT8 as its format. * If 1 is passed for \p planeIdx, then the returned CUDA array has half the height and width * of \p hArray with two channels and ::CU_AD_FORMAT_UNSIGNED_INT8 as its format. * * \param pPlaneArray - Returned CUDA array referenced by the \p planeIdx * \param hArray - Multiplanar CUDA array * \param planeIdx - Plane index * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa * ::cuArrayCreate, * ::cudaGetArrayPlane */ CUresult CUDAAPI cuArrayGetPlane(CUarray *pPlaneArray, CUarray hArray, unsigned int planeIdx); /** * \brief Destroys a CUDA array * * Destroys the CUDA array \p hArray. * * \param hArray - Array to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_ARRAY_IS_MAPPED, * ::CUDA_ERROR_CONTEXT_IS_DESTROYED * \notefnerr * * \sa ::cuArray3DCreate, ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaFreeArray */ CUresult CUDAAPI cuArrayDestroy(CUarray hArray); /** * \brief Creates a 3D CUDA array * * Creates a CUDA array according to the ::CUDA_ARRAY3D_DESCRIPTOR structure * \p pAllocateArray and returns a handle to the new CUDA array in \p *pHandle. * The ::CUDA_ARRAY3D_DESCRIPTOR is defined as: * * \code typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; CUarray_format Format; unsigned int NumChannels; unsigned int Flags; } CUDA_ARRAY3D_DESCRIPTOR; * \endcode * where: * * - \p Width, \p Height, and \p Depth are the width, height, and depth of the * CUDA array (in elements); the following types of CUDA arrays can be allocated: * - A 1D array is allocated if \p Height and \p Depth extents are both zero. * - A 2D array is allocated if only \p Depth extent is zero. * - A 3D array is allocated if all three extents are non-zero. * - A 1D layered CUDA array is allocated if only \p Height is zero and the * ::CUDA_ARRAY3D_LAYERED flag is set. Each layer is a 1D array. The number * of layers is determined by the depth extent. * - A 2D layered CUDA array is allocated if all three extents are non-zero and * the ::CUDA_ARRAY3D_LAYERED flag is set. Each layer is a 2D array. The number * of layers is determined by the depth extent. * - A cubemap CUDA array is allocated if all three extents are non-zero and the * ::CUDA_ARRAY3D_CUBEMAP flag is set. \p Width must be equal to \p Height, and * \p Depth must be six. A cubemap is a special type of 2D layered CUDA array, * where the six layers represent the six faces of a cube. The order of the six * layers in memory is the same as that listed in ::CUarray_cubemap_face. * - A cubemap layered CUDA array is allocated if all three extents are non-zero, * and both, ::CUDA_ARRAY3D_CUBEMAP and ::CUDA_ARRAY3D_LAYERED flags are set. * \p Width must be equal to \p Height, and \p Depth must be a multiple of six. * A cubemap layered CUDA array is a special type of 2D layered CUDA array that * consists of a collection of cubemaps. The first six layers represent the first * cubemap, the next six layers form the second cubemap, and so on. * * - ::Format specifies the format of the elements; ::CUarray_format is * defined as: * \code typedef enum CUarray_format_enum { CU_AD_FORMAT_UNSIGNED_INT8 = 0x01, CU_AD_FORMAT_UNSIGNED_INT16 = 0x02, CU_AD_FORMAT_UNSIGNED_INT32 = 0x03, CU_AD_FORMAT_SIGNED_INT8 = 0x08, CU_AD_FORMAT_SIGNED_INT16 = 0x09, CU_AD_FORMAT_SIGNED_INT32 = 0x0a, CU_AD_FORMAT_HALF = 0x10, CU_AD_FORMAT_FLOAT = 0x20 } CUarray_format; * \endcode * * - \p NumChannels specifies the number of packed components per CUDA array * element; it may be 1, 2, or 4; * * - ::Flags may be set to * - ::CUDA_ARRAY3D_LAYERED to enable creation of layered CUDA arrays. If this flag is set, * \p Depth specifies the number of layers, not the depth of a 3D array. * - ::CUDA_ARRAY3D_SURFACE_LDST to enable surface references to be bound to the CUDA array. * If this flag is not set, ::cuSurfRefSetArray will fail when attempting to bind the CUDA array * to a surface reference. * - ::CUDA_ARRAY3D_CUBEMAP to enable creation of cubemaps. If this flag is set, \p Width must be * equal to \p Height, and \p Depth must be six. If the ::CUDA_ARRAY3D_LAYERED flag is also set, * then \p Depth must be a multiple of six. * - ::CUDA_ARRAY3D_TEXTURE_GATHER to indicate that the CUDA array will be used for texture gather. * Texture gather can only be performed on 2D CUDA arrays. * * \p Width, \p Height and \p Depth must meet certain size requirements as listed in the following table. * All values are specified in elements. Note that for brevity's sake, the full name of the device attribute * is not specified. For ex., TEXTURE1D_WIDTH refers to the device attribute * ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH. * * Note that 2D CUDA arrays have different size requirements if the ::CUDA_ARRAY3D_TEXTURE_GATHER flag * is set. \p Width and \p Height must not be greater than ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH * and ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT respectively, in that case. * * <table> * <tr><td><b>CUDA array type</b></td> * <td><b>Valid extents that must always be met<br>{(width range in elements), (height range), * (depth range)}</b></td> * <td><b>Valid extents with CUDA_ARRAY3D_SURFACE_LDST set<br> * {(width range in elements), (height range), (depth range)}</b></td></tr> * <tr><td>1D</td> * <td><small>{ (1,TEXTURE1D_WIDTH), 0, 0 }</small></td> * <td><small>{ (1,SURFACE1D_WIDTH), 0, 0 }</small></td></tr> * <tr><td>2D</td> * <td><small>{ (1,TEXTURE2D_WIDTH), (1,TEXTURE2D_HEIGHT), 0 }</small></td> * <td><small>{ (1,SURFACE2D_WIDTH), (1,SURFACE2D_HEIGHT), 0 }</small></td></tr> * <tr><td>3D</td> * <td><small>{ (1,TEXTURE3D_WIDTH), (1,TEXTURE3D_HEIGHT), (1,TEXTURE3D_DEPTH) } * <br>OR<br>{ (1,TEXTURE3D_WIDTH_ALTERNATE), (1,TEXTURE3D_HEIGHT_ALTERNATE), * (1,TEXTURE3D_DEPTH_ALTERNATE) }</small></td> * <td><small>{ (1,SURFACE3D_WIDTH), (1,SURFACE3D_HEIGHT), * (1,SURFACE3D_DEPTH) }</small></td></tr> * <tr><td>1D Layered</td> * <td><small>{ (1,TEXTURE1D_LAYERED_WIDTH), 0, * (1,TEXTURE1D_LAYERED_LAYERS) }</small></td> * <td><small>{ (1,SURFACE1D_LAYERED_WIDTH), 0, * (1,SURFACE1D_LAYERED_LAYERS) }</small></td></tr> * <tr><td>2D Layered</td> * <td><small>{ (1,TEXTURE2D_LAYERED_WIDTH), (1,TEXTURE2D_LAYERED_HEIGHT), * (1,TEXTURE2D_LAYERED_LAYERS) }</small></td> * <td><small>{ (1,SURFACE2D_LAYERED_WIDTH), (1,SURFACE2D_LAYERED_HEIGHT), * (1,SURFACE2D_LAYERED_LAYERS) }</small></td></tr> * <tr><td>Cubemap</td> * <td><small>{ (1,TEXTURECUBEMAP_WIDTH), (1,TEXTURECUBEMAP_WIDTH), 6 }</small></td> * <td><small>{ (1,SURFACECUBEMAP_WIDTH), * (1,SURFACECUBEMAP_WIDTH), 6 }</small></td></tr> * <tr><td>Cubemap Layered</td> * <td><small>{ (1,TEXTURECUBEMAP_LAYERED_WIDTH), (1,TEXTURECUBEMAP_LAYERED_WIDTH), * (1,TEXTURECUBEMAP_LAYERED_LAYERS) }</small></td> * <td><small>{ (1,SURFACECUBEMAP_LAYERED_WIDTH), (1,SURFACECUBEMAP_LAYERED_WIDTH), * (1,SURFACECUBEMAP_LAYERED_LAYERS) }</small></td></tr> * </table> * * Here are examples of CUDA array descriptions: * * Description for a CUDA array of 2048 floats: * \code CUDA_ARRAY3D_DESCRIPTOR desc; desc.Format = CU_AD_FORMAT_FLOAT; desc.NumChannels = 1; desc.Width = 2048; desc.Height = 0; desc.Depth = 0; * \endcode * * Description for a 64 x 64 CUDA array of floats: * \code CUDA_ARRAY3D_DESCRIPTOR desc; desc.Format = CU_AD_FORMAT_FLOAT; desc.NumChannels = 1; desc.Width = 64; desc.Height = 64; desc.Depth = 0; * \endcode * * Description for a \p width x \p height x \p depth CUDA array of 64-bit, * 4x16-bit float16's: * \code CUDA_ARRAY3D_DESCRIPTOR desc; desc.Format = CU_AD_FORMAT_HALF; desc.NumChannels = 4; desc.Width = width; desc.Height = height; desc.Depth = depth; * \endcode * * \param pHandle - Returned array * \param pAllocateArray - 3D array descriptor * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa ::cuArray3DGetDescriptor, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaMalloc3DArray */ CUresult CUDAAPI cuArray3DCreate(CUarray *pHandle, const CUDA_ARRAY3D_DESCRIPTOR *pAllocateArray); /** * \brief Get a 3D CUDA array descriptor * * Returns in \p *pArrayDescriptor a descriptor containing information on the * format and dimensions of the CUDA array \p hArray. It is useful for * subroutines that have been passed a CUDA array, but need to know the CUDA * array parameters for validation or other purposes. * * This function may be called on 1D and 2D arrays, in which case the \p Height * and/or \p Depth members of the descriptor struct will be set to 0. * * \param pArrayDescriptor - Returned 3D array descriptor * \param hArray - 3D array to get descriptor of * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_CONTEXT_IS_DESTROYED * \notefnerr * * \sa ::cuArray3DCreate, ::cuArrayCreate, * ::cuArrayDestroy, ::cuArrayGetDescriptor, ::cuMemAlloc, ::cuMemAllocHost, * ::cuMemAllocPitch, ::cuMemcpy2D, ::cuMemcpy2DAsync, ::cuMemcpy2DUnaligned, * ::cuMemcpy3D, ::cuMemcpy3DAsync, ::cuMemcpyAtoA, ::cuMemcpyAtoD, * ::cuMemcpyAtoH, ::cuMemcpyAtoHAsync, ::cuMemcpyDtoA, ::cuMemcpyDtoD, ::cuMemcpyDtoDAsync, * ::cuMemcpyDtoH, ::cuMemcpyDtoHAsync, ::cuMemcpyHtoA, ::cuMemcpyHtoAAsync, * ::cuMemcpyHtoD, ::cuMemcpyHtoDAsync, ::cuMemFree, ::cuMemFreeHost, * ::cuMemGetAddressRange, ::cuMemGetInfo, ::cuMemHostAlloc, * ::cuMemHostGetDevicePointer, ::cuMemsetD2D8, ::cuMemsetD2D16, * ::cuMemsetD2D32, ::cuMemsetD8, ::cuMemsetD16, ::cuMemsetD32, * ::cudaArrayGetInfo */ CUresult CUDAAPI cuArray3DGetDescriptor(CUDA_ARRAY3D_DESCRIPTOR *pArrayDescriptor, CUarray hArray); /** * \brief Creates a CUDA mipmapped array * * Creates a CUDA mipmapped array according to the ::CUDA_ARRAY3D_DESCRIPTOR structure * \p pMipmappedArrayDesc and returns a handle to the new CUDA mipmapped array in \p *pHandle. * \p numMipmapLevels specifies the number of mipmap levels to be allocated. This value is * clamped to the range [1, 1 + floor(log2(max(width, height, depth)))]. * * The ::CUDA_ARRAY3D_DESCRIPTOR is defined as: * * \code typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; CUarray_format Format; unsigned int NumChannels; unsigned int Flags; } CUDA_ARRAY3D_DESCRIPTOR; * \endcode * where: * * - \p Width, \p Height, and \p Depth are the width, height, and depth of the * CUDA array (in elements); the following types of CUDA arrays can be allocated: * - A 1D mipmapped array is allocated if \p Height and \p Depth extents are both zero. * - A 2D mipmapped array is allocated if only \p Depth extent is zero. * - A 3D mipmapped array is allocated if all three extents are non-zero. * - A 1D layered CUDA mipmapped array is allocated if only \p Height is zero and the * ::CUDA_ARRAY3D_LAYERED flag is set. Each layer is a 1D array. The number * of layers is determined by the depth extent. * - A 2D layered CUDA mipmapped array is allocated if all three extents are non-zero and * the ::CUDA_ARRAY3D_LAYERED flag is set. Each layer is a 2D array. The number * of layers is determined by the depth extent. * - A cubemap CUDA mipmapped array is allocated if all three extents are non-zero and the * ::CUDA_ARRAY3D_CUBEMAP flag is set. \p Width must be equal to \p Height, and * \p Depth must be six. A cubemap is a special type of 2D layered CUDA array, * where the six layers represent the six faces of a cube. The order of the six * layers in memory is the same as that listed in ::CUarray_cubemap_face. * - A cubemap layered CUDA mipmapped array is allocated if all three extents are non-zero, * and both, ::CUDA_ARRAY3D_CUBEMAP and ::CUDA_ARRAY3D_LAYERED flags are set. * \p Width must be equal to \p Height, and \p Depth must be a multiple of six. * A cubemap layered CUDA array is a special type of 2D layered CUDA array that * consists of a collection of cubemaps. The first six layers represent the first * cubemap, the next six layers form the second cubemap, and so on. * * - ::Format specifies the format of the elements; ::CUarray_format is * defined as: * \code typedef enum CUarray_format_enum { CU_AD_FORMAT_UNSIGNED_INT8 = 0x01, CU_AD_FORMAT_UNSIGNED_INT16 = 0x02, CU_AD_FORMAT_UNSIGNED_INT32 = 0x03, CU_AD_FORMAT_SIGNED_INT8 = 0x08, CU_AD_FORMAT_SIGNED_INT16 = 0x09, CU_AD_FORMAT_SIGNED_INT32 = 0x0a, CU_AD_FORMAT_HALF = 0x10, CU_AD_FORMAT_FLOAT = 0x20 } CUarray_format; * \endcode * * - \p NumChannels specifies the number of packed components per CUDA array * element; it may be 1, 2, or 4; * * - ::Flags may be set to * - ::CUDA_ARRAY3D_LAYERED to enable creation of layered CUDA mipmapped arrays. If this flag is set, * \p Depth specifies the number of layers, not the depth of a 3D array. * - ::CUDA_ARRAY3D_SURFACE_LDST to enable surface references to be bound to individual mipmap levels of * the CUDA mipmapped array. If this flag is not set, ::cuSurfRefSetArray will fail when attempting to * bind a mipmap level of the CUDA mipmapped array to a surface reference. * - ::CUDA_ARRAY3D_CUBEMAP to enable creation of mipmapped cubemaps. If this flag is set, \p Width must be * equal to \p Height, and \p Depth must be six. If the ::CUDA_ARRAY3D_LAYERED flag is also set, * then \p Depth must be a multiple of six. * - ::CUDA_ARRAY3D_TEXTURE_GATHER to indicate that the CUDA mipmapped array will be used for texture gather. * Texture gather can only be performed on 2D CUDA mipmapped arrays. * * \p Width, \p Height and \p Depth must meet certain size requirements as listed in the following table. * All values are specified in elements. Note that for brevity's sake, the full name of the device attribute * is not specified. For ex., TEXTURE1D_MIPMAPPED_WIDTH refers to the device attribute * ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH. * * <table> * <tr><td><b>CUDA array type</b></td> * <td><b>Valid extents that must always be met<br>{(width range in elements), (height range), * (depth range)}</b></td> * <td><b>Valid extents with CUDA_ARRAY3D_SURFACE_LDST set<br> * {(width range in elements), (height range), (depth range)}</b></td></tr> * <tr><td>1D</td> * <td><small>{ (1,TEXTURE1D_MIPMAPPED_WIDTH), 0, 0 }</small></td> * <td><small>{ (1,SURFACE1D_WIDTH), 0, 0 }</small></td></tr> * <tr><td>2D</td> * <td><small>{ (1,TEXTURE2D_MIPMAPPED_WIDTH), (1,TEXTURE2D_MIPMAPPED_HEIGHT), 0 }</small></td> * <td><small>{ (1,SURFACE2D_WIDTH), (1,SURFACE2D_HEIGHT), 0 }</small></td></tr> * <tr><td>3D</td> * <td><small>{ (1,TEXTURE3D_WIDTH), (1,TEXTURE3D_HEIGHT), (1,TEXTURE3D_DEPTH) } * <br>OR<br>{ (1,TEXTURE3D_WIDTH_ALTERNATE), (1,TEXTURE3D_HEIGHT_ALTERNATE), * (1,TEXTURE3D_DEPTH_ALTERNATE) }</small></td> * <td><small>{ (1,SURFACE3D_WIDTH), (1,SURFACE3D_HEIGHT), * (1,SURFACE3D_DEPTH) }</small></td></tr> * <tr><td>1D Layered</td> * <td><small>{ (1,TEXTURE1D_LAYERED_WIDTH), 0, * (1,TEXTURE1D_LAYERED_LAYERS) }</small></td> * <td><small>{ (1,SURFACE1D_LAYERED_WIDTH), 0, * (1,SURFACE1D_LAYERED_LAYERS) }</small></td></tr> * <tr><td>2D Layered</td> * <td><small>{ (1,TEXTURE2D_LAYERED_WIDTH), (1,TEXTURE2D_LAYERED_HEIGHT), * (1,TEXTURE2D_LAYERED_LAYERS) }</small></td> * <td><small>{ (1,SURFACE2D_LAYERED_WIDTH), (1,SURFACE2D_LAYERED_HEIGHT), * (1,SURFACE2D_LAYERED_LAYERS) }</small></td></tr> * <tr><td>Cubemap</td> * <td><small>{ (1,TEXTURECUBEMAP_WIDTH), (1,TEXTURECUBEMAP_WIDTH), 6 }</small></td> * <td><small>{ (1,SURFACECUBEMAP_WIDTH), * (1,SURFACECUBEMAP_WIDTH), 6 }</small></td></tr> * <tr><td>Cubemap Layered</td> * <td><small>{ (1,TEXTURECUBEMAP_LAYERED_WIDTH), (1,TEXTURECUBEMAP_LAYERED_WIDTH), * (1,TEXTURECUBEMAP_LAYERED_LAYERS) }</small></td> * <td><small>{ (1,SURFACECUBEMAP_LAYERED_WIDTH), (1,SURFACECUBEMAP_LAYERED_WIDTH), * (1,SURFACECUBEMAP_LAYERED_LAYERS) }</small></td></tr> * </table> * * * \param pHandle - Returned mipmapped array * \param pMipmappedArrayDesc - mipmapped array descriptor * \param numMipmapLevels - Number of mipmap levels * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa * ::cuMipmappedArrayDestroy, * ::cuMipmappedArrayGetLevel, * ::cuArrayCreate, * ::cudaMallocMipmappedArray */ CUresult CUDAAPI cuMipmappedArrayCreate(CUmipmappedArray *pHandle, const CUDA_ARRAY3D_DESCRIPTOR *pMipmappedArrayDesc, unsigned int numMipmapLevels); /** * \brief Gets a mipmap level of a CUDA mipmapped array * * Returns in \p *pLevelArray a CUDA array that represents a single mipmap level * of the CUDA mipmapped array \p hMipmappedArray. * * If \p level is greater than the maximum number of levels in this mipmapped array, * ::CUDA_ERROR_INVALID_VALUE is returned. * * \param pLevelArray - Returned mipmap level CUDA array * \param hMipmappedArray - CUDA mipmapped array * \param level - Mipmap level * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa * ::cuMipmappedArrayCreate, * ::cuMipmappedArrayDestroy, * ::cuArrayCreate, * ::cudaGetMipmappedArrayLevel */ CUresult CUDAAPI cuMipmappedArrayGetLevel(CUarray *pLevelArray, CUmipmappedArray hMipmappedArray, unsigned int level); /** * \brief Destroys a CUDA mipmapped array * * Destroys the CUDA mipmapped array \p hMipmappedArray. * * \param hMipmappedArray - Mipmapped array to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_ARRAY_IS_MAPPED, * ::CUDA_ERROR_CONTEXT_IS_DESTROYED * \notefnerr * * \sa * ::cuMipmappedArrayCreate, * ::cuMipmappedArrayGetLevel, * ::cuArrayCreate, * ::cudaFreeMipmappedArray */ CUresult CUDAAPI cuMipmappedArrayDestroy(CUmipmappedArray hMipmappedArray); /** @} */ /* END CUDA_MEM */ /** * \defgroup CUDA_VA Virtual Memory Management * * ___MANBRIEF___ virtual memory management functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the virtual memory management functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Allocate an address range reservation. * * Reserves a virtual address range based on the given parameters, giving * the starting address of the range in \p ptr. This API requires a system that * supports UVA. The size and address parameters must be a multiple of the * host page size and the alignment must be a power of two or zero for default * alignment. * * \param[out] ptr - Resulting pointer to start of virtual address range allocated * \param[in] size - Size of the reserved virtual address range requested * \param[in] alignment - Alignment of the reserved virtual address range requested * \param[in] addr - Fixed starting address range requested * \param[in] flags - Currently unused, must be zero * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * * \sa ::cuMemAddressFree */ CUresult CUDAAPI cuMemAddressReserve(CUdeviceptr *ptr, size_t size, size_t alignment, CUdeviceptr addr, unsigned long long flags); /** * \brief Free an address range reservation. * * Frees a virtual address range reserved by cuMemAddressReserve. The size * must match what was given to memAddressReserve and the ptr given must * match what was returned from memAddressReserve. * * \param[in] ptr - Starting address of the virtual address range to free * \param[in] size - Size of the virtual address region to free * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * * \sa ::cuMemAddressReserve */ CUresult CUDAAPI cuMemAddressFree(CUdeviceptr ptr, size_t size); /** * \brief Create a CUDA memory handle representing a memory allocation of a given size described by the given properties * * This creates a memory allocation on the target device specified through the * \p prop strcuture. The created allocation will not have any device or host * mappings. The generic memory \p handle for the allocation can be * mapped to the address space of calling process via ::cuMemMap. This handle * cannot be transmitted directly to other processes (see * ::cuMemExportToShareableHandle). On Windows, the caller must also pass * an LPSECURITYATTRIBUTE in \p prop to be associated with this handle which * limits or allows access to this handle for a recepient process (see * ::CUmemAllocationProp::win32HandleMetaData for more). The \p size of this * allocation must be a multiple of the the value given via * ::cuMemGetAllocationGranularity with the ::CU_MEM_ALLOC_GRANULARITY_MINIMUM * flag. * If ::CUmemAllocationProp::allocFlags::usage contains ::CU_MEM_CREATE_USAGE_TILE_POOL flag then * the memory allocation is intended only to be used as backing tile pool for sparse CUDA arrays * and sparse CUDA mipmapped arrays. * (see ::cuMemMapArrayAsync). * * \param[out] handle - Value of handle returned. All operations on this allocation are to be performed using this handle. * \param[in] size - Size of the allocation requested * \param[in] prop - Properties of the allocation to create. * \param[in] flags - flags for future use, must be zero now. * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa ::cuMemRelease, ::cuMemExportToShareableHandle, ::cuMemImportFromShareableHandle */ CUresult CUDAAPI cuMemCreate(CUmemGenericAllocationHandle *handle, size_t size, const CUmemAllocationProp *prop, unsigned long long flags); /** * \brief Release a memory handle representing a memory allocation which was previously allocated through cuMemCreate. * * Frees the memory that was allocated on a device through cuMemCreate. * * The memory allocation will be freed when all outstanding mappings to the memory * are unmapped and when all outstanding references to the handle (including it's * shareable counterparts) are also released. The generic memory handle can be * freed when there are still outstanding mappings made with this handle. Each * time a recepient process imports a shareable handle, it needs to pair it with * ::cuMemRelease for the handle to be freed. If \p handle is not a valid handle * the behavior is undefined. * * \param[in] handle Value of handle which was returned previously by cuMemCreate. * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa ::cuMemCreate */ CUresult CUDAAPI cuMemRelease(CUmemGenericAllocationHandle handle); /** * \brief Maps an allocation handle to a reserved virtual address range. * * Maps bytes of memory represented by \p handle starting from byte \p offset to * \p size to address range [\p addr, \p addr + \p size]. This range must be an * address reservation previously reserved with ::cuMemAddressReserve, and * \p offset + \p size must be less than the size of the memory allocation. * Both \p ptr, \p size, and \p offset must be a multiple of the value given via * ::cuMemGetAllocationGranularity with the ::CU_MEM_ALLOC_GRANULARITY_MINIMUM flag. * * Please note calling ::cuMemMap does not make the address accessible, * the caller needs to update accessibility of a contiguous mapped VA * range by calling ::cuMemSetAccess. * * Once a recipient process obtains a shareable memory handle * from ::cuMemImportFromShareableHandle, the process must * use ::cuMemMap to map the memory into its address ranges before * setting accessibility with ::cuMemSetAccess. * * ::cuMemMap can only create mappings on VA range reservations * that are not currently mapped. * * \param[in] ptr - Address where memory will be mapped. * \param[in] size - Size of the memory mapping. * \param[in] offset - Offset into the memory represented by * - \p handle from which to start mapping * - Note: currently must be zero. * \param[in] handle - Handle to a shareable memory * \param[in] flags - flags for future use, must be zero now. * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa ::cuMemUnmap, ::cuMemSetAccess, ::cuMemCreate, ::cuMemAddressReserve, ::cuMemImportFromShareableHandle */ CUresult CUDAAPI cuMemMap(CUdeviceptr ptr, size_t size, size_t offset, CUmemGenericAllocationHandle handle, unsigned long long flags); /** * \brief Maps or unmaps subregions of sparse CUDA arrays and sparse CUDA mipmapped arrays * * Performs map or unmap operations on subregions of sparse CUDA arrays and sparse CUDA mipmapped arrays. * Each operation is specified by a ::CUarrayMapInfo entry in the \p mapInfoList array of size \p count. * The structure ::CUarrayMapInfo is defined as follow: \code typedef struct CUarrayMapInfo_st { CUresourcetype resourceType; union { CUmipmappedArray mipmap; CUarray array; } resource; CUarraySparseSubresourceType subresourceType; union { struct { unsigned int level; unsigned int layer; unsigned int offsetX; unsigned int offsetY; unsigned int offsetZ; unsigned int extentWidth; unsigned int extentHeight; unsigned int extentDepth; } sparseLevel; struct { unsigned int layer; unsigned long long offset; unsigned long long size; } miptail; } subresource; CUmemOperationType memOperationType; CUmemHandleType memHandleType; union { CUmemGenericAllocationHandle memHandle; } memHandle; unsigned long long offset; unsigned int deviceBitMask; unsigned int flags; unsigned int reserved[2]; } CUarrayMapInfo; \endcode * * where ::CUarrayMapInfo::resourceType specifies the type of resource to be operated on. * If ::CUarrayMapInfo::resourceType is set to ::CUresourcetype::CU_RESOURCE_TYPE_ARRAY then * ::CUarrayMapInfo::resource::array must be set to a valid sparse CUDA array handle. * The CUDA array must be either a 2D, 2D layered or 3D CUDA array and must have been allocated using * ::cuArrayCreate or ::cuArray3DCreate with the flag ::CUDA_ARRAY3D_SPARSE * or ::CUDA_ARRAY3D_DEFERRED_MAPPING. * For CUDA arrays obtained using ::cuMipmappedArrayGetLevel, ::CUDA_ERROR_INVALID_VALUE will be returned. * If ::CUarrayMapInfo::resourceType is set to ::CUresourcetype::CU_RESOURCE_TYPE_MIPMAPPED_ARRAY * then ::CUarrayMapInfo::resource::mipmap must be set to a valid sparse CUDA mipmapped array handle. * The CUDA mipmapped array must be either a 2D, 2D layered or 3D CUDA mipmapped array and must have been * allocated using ::cuMipmappedArrayCreate with the flag ::CUDA_ARRAY3D_SPARSE * or ::CUDA_ARRAY3D_DEFERRED_MAPPING. * * ::CUarrayMapInfo::subresourceType specifies the type of subresource within the resource. * ::CUarraySparseSubresourceType_enum is defined as: \code typedef enum CUarraySparseSubresourceType_enum { CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SPARSE_LEVEL = 0, CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL = 1 } CUarraySparseSubresourceType; \endcode * * where ::CUarraySparseSubresourceType::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SPARSE_LEVEL indicates a * sparse-miplevel which spans at least one tile in every dimension. The remaining miplevels which * are too small to span at least one tile in any dimension constitute the mip tail region as indicated by * ::CUarraySparseSubresourceType::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL subresource type. * * If ::CUarrayMapInfo::subresourceType is set to ::CUarraySparseSubresourceType::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_SPARSE_LEVEL * then ::CUarrayMapInfo::subresource::sparseLevel struct must contain valid array subregion offsets and extents. * The ::CUarrayMapInfo::subresource::sparseLevel::offsetX, ::CUarrayMapInfo::subresource::sparseLevel::offsetY * and ::CUarrayMapInfo::subresource::sparseLevel::offsetZ must specify valid X, Y and Z offsets respectively. * The ::CUarrayMapInfo::subresource::sparseLevel::extentWidth, ::CUarrayMapInfo::subresource::sparseLevel::extentHeight * and ::CUarrayMapInfo::subresource::sparseLevel::extentDepth must specify valid width, height and depth extents respectively. * These offsets and extents must be aligned to the corresponding tile dimension. * For CUDA mipmapped arrays ::CUarrayMapInfo::subresource::sparseLevel::level must specify a valid mip level index. Otherwise, * must be zero. * For layered CUDA arrays and layered CUDA mipmapped arrays ::CUarrayMapInfo::subresource::sparseLevel::layer must specify a valid layer index. Otherwise, * must be zero. * ::CUarrayMapInfo::subresource::sparseLevel::offsetZ must be zero and ::CUarrayMapInfo::subresource::sparseLevel::extentDepth * must be set to 1 for 2D and 2D layered CUDA arrays and CUDA mipmapped arrays. * Tile extents can be obtained by calling ::cuArrayGetSparseProperties and ::cuMipmappedArrayGetSparseProperties * * If ::CUarrayMapInfo::subresourceType is set to ::CUarraySparseSubresourceType::CU_ARRAY_SPARSE_SUBRESOURCE_TYPE_MIPTAIL * then ::CUarrayMapInfo::subresource::miptail struct must contain valid mip tail offset in * ::CUarrayMapInfo::subresource::miptail::offset and size in ::CUarrayMapInfo::subresource::miptail::size. * Both, mip tail offset and mip tail size must be aligned to the tile size. * For layered CUDA mipmapped arrays which don't have the flag ::CU_ARRAY_SPARSE_PROPERTIES_SINGLE_MIPTAIL set in ::CUDA_ARRAY_SPARSE_PROPERTIES::flags * as returned by ::cuMipmappedArrayGetSparseProperties, ::CUarrayMapInfo::subresource::miptail::layer must specify a valid layer index. * Otherwise, must be zero. * * If ::CUarrayMapInfo::resource::array or ::CUarrayMapInfo::resource::mipmap was created with ::CUDA_ARRAY3D_DEFERRED_MAPPING * flag set the ::CUarrayMapInfo::subresourceType and the contents of ::CUarrayMapInfo::subresource will be ignored. * * ::CUarrayMapInfo::memOperationType specifies the type of operation. ::CUmemOperationType is defined as: \code typedef enum CUmemOperationType_enum { CU_MEM_OPERATION_TYPE_MAP = 1, CU_MEM_OPERATION_TYPE_UNMAP = 2 } CUmemOperationType; \endcode * If ::CUarrayMapInfo::memOperationType is set to ::CUmemOperationType::CU_MEM_OPERATION_TYPE_MAP then the subresource * will be mapped onto the tile pool memory specified by ::CUarrayMapInfo::memHandle at offset ::CUarrayMapInfo::offset. * The tile pool allocation has to be created by specifying the ::CU_MEM_CREATE_USAGE_TILE_POOL flag when calling ::cuMemCreate. Also, * ::CUarrayMapInfo::memHandleType must be set to ::CUmemHandleType::CU_MEM_HANDLE_TYPE_GENERIC. * * If ::CUarrayMapInfo::memOperationType is set to ::CUmemOperationType::CU_MEM_OPERATION_TYPE_UNMAP then an unmapping operation * is performed. ::CUarrayMapInfo::memHandle must be NULL. * * ::CUarrayMapInfo::deviceBitMask specifies the list of devices that must map or unmap physical memory. * Currently, this mask must have exactly one bit set, and the corresponding device must match the device associated with the stream. * If ::CUarrayMapInfo::memOperationType is set to ::CUmemOperationType::CU_MEM_OPERATION_TYPE_MAP, the device must also match * the device associated with the tile pool memory allocation as specified by ::CUarrayMapInfo::memHandle. * * ::CUarrayMapInfo::flags and ::CUarrayMapInfo::reserved[] are unused and must be set to zero. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * * \param[in] mapInfoList - List of ::CUarrayMapInfo * \param[in] count - Count of ::CUarrayMapInfo in \p mapInfoList * \param[in] hStream - Stream identifier for the stream to use for map or unmap operations * * \sa ::cuMipmappedArrayCreate, ::cuArrayCreate, ::cuArray3DCreate, ::cuMemCreate, ::cuArrayGetSparseProperties, ::cuMipmappedArrayGetSparseProperties */ CUresult CUDAAPI cuMemMapArrayAsync(CUarrayMapInfo *mapInfoList, unsigned int count, CUstream hStream); /** * \brief Unmap the backing memory of a given address range. * * The range must be the entire contiguous address range that was mapped to. In * other words, ::cuMemUnmap cannot unmap a sub-range of an address range mapped * by ::cuMemCreate / ::cuMemMap. Any backing memory allocations will be freed * if there are no existing mappings and there are no unreleased memory handles. * * When ::cuMemUnmap returns successfully the address range is converted to an * address reservation and can be used for a future calls to ::cuMemMap. Any new * mapping to this virtual address will need to have access granted through * ::cuMemSetAccess, as all mappings start with no accessibility setup. * * \param[in] ptr - Starting address for the virtual address range to unmap * \param[in] size - Size of the virtual address range to unmap * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * \note_sync * * \sa ::cuMemCreate, ::cuMemAddressReserve */ CUresult CUDAAPI cuMemUnmap(CUdeviceptr ptr, size_t size); /** * \brief Set the access flags for each location specified in \p desc for the given virtual address range * * Given the virtual address range via \p ptr and \p size, and the locations * in the array given by \p desc and \p count, set the access flags for the * target locations. The range must be a fully mapped address range * containing all allocations created by ::cuMemMap / ::cuMemCreate. * * \param[in] ptr - Starting address for the virtual address range * \param[in] size - Length of the virtual address range * \param[in] desc - Array of ::CUmemAccessDesc that describe how to change the * - mapping for each location specified * \param[in] count - Number of ::CUmemAccessDesc in \p desc * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * \note_sync * * \sa ::cuMemSetAccess, ::cuMemCreate, :cuMemMap */ CUresult CUDAAPI cuMemSetAccess(CUdeviceptr ptr, size_t size, const CUmemAccessDesc *desc, size_t count); /** * \brief Get the access \p flags set for the given \p location and \p ptr * * \param[out] flags - Flags set for this location * \param[in] location - Location in which to check the flags for * \param[in] ptr - Address in which to check the access flags for * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * * \sa ::cuMemSetAccess */ CUresult CUDAAPI cuMemGetAccess(unsigned long long *flags, const CUmemLocation *location, CUdeviceptr ptr); /** * \brief Exports an allocation to a requested shareable handle type * * Given a CUDA memory handle, create a shareable memory * allocation handle that can be used to share the memory with other * processes. The recipient process can convert the shareable handle back into a * CUDA memory handle using ::cuMemImportFromShareableHandle and map * it with ::cuMemMap. The implementation of what this handle is and how it * can be transferred is defined by the requested handle type in \p handleType * * Once all shareable handles are closed and the allocation is released, the allocated * memory referenced will be released back to the OS and uses of the CUDA handle afterward * will lead to undefined behavior. * * This API can also be used in conjunction with other APIs (e.g. Vulkan, OpenGL) * that support importing memory from the shareable type * * \param[out] shareableHandle - Pointer to the location in which to store the requested handle type * \param[in] handle - CUDA handle for the memory allocation * \param[in] handleType - Type of shareable handle requested (defines type and size of the \p shareableHandle output parameter) * \param[in] flags - Reserved, must be zero * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * * \sa ::cuMemImportFromShareableHandle */ CUresult CUDAAPI cuMemExportToShareableHandle(void *shareableHandle, CUmemGenericAllocationHandle handle, CUmemAllocationHandleType handleType, unsigned long long flags); /** * \brief Imports an allocation from a requested shareable handle type. * * If the current process cannot support the memory described by this shareable * handle, this API will error as CUDA_ERROR_NOT_SUPPORTED. * * \note Importing shareable handles exported from some graphics APIs(VUlkan, OpenGL, etc) * created on devices under an SLI group may not be supported, and thus this API will * return CUDA_ERROR_NOT_SUPPORTED. * There is no guarantee that the contents of \p handle will be the same CUDA memory handle * for the same given OS shareable handle, or the same underlying allocation. * * \param[out] handle - CUDA Memory handle for the memory allocation. * \param[in] osHandle - Shareable Handle representing the memory allocation that is to be imported. * \param[in] shHandleType - handle type of the exported handle ::CUmemAllocationHandleType. * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * * \sa ::cuMemExportToShareableHandle, ::cuMemMap, ::cuMemRelease */ CUresult CUDAAPI cuMemImportFromShareableHandle(CUmemGenericAllocationHandle *handle, void *osHandle, CUmemAllocationHandleType shHandleType); /** * \brief Calculates either the minimal or recommended granularity * * Calculates either the minimal or recommended granularity * for a given allocation specification and returns it in granularity. This * granularity can be used as a multiple for alignment, size, or address mapping. * * \param[out] granularity Returned granularity. * \param[in] prop Property for which to determine the granularity for * \param[in] option Determines which granularity to return * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * * \sa ::cuMemCreate, ::cuMemMap */ CUresult CUDAAPI cuMemGetAllocationGranularity(size_t *granularity, const CUmemAllocationProp *prop, CUmemAllocationGranularity_flags option); /** * \brief Retrieve the contents of the property structure defining properties for this handle * * \param[out] prop - Pointer to a properties structure which will hold the information about this handle * \param[in] handle - Handle which to perform the query on * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * * \sa ::cuMemCreate, ::cuMemImportFromShareableHandle */ CUresult CUDAAPI cuMemGetAllocationPropertiesFromHandle(CUmemAllocationProp *prop, CUmemGenericAllocationHandle handle); /** * \brief Given an address \p addr, returns the allocation handle of the backing memory allocation. * * The handle is guaranteed to be the same handle value used to map the memory. If the address * requested is not mapped, the function will fail. The returned handle must be released with * corresponding number of calls to ::cuMemRelease. * * \note The address \p addr, can be any address in a range previously mapped * by ::cuMemMap, and not necessarily the start address. * * \param[out] handle CUDA Memory handle for the backing memory allocation. * \param[in] addr Memory address to query, that has been mapped previously. * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_PERMITTED, * ::CUDA_ERROR_NOT_SUPPORTED * * \sa ::cuMemCreate, ::cuMemRelease, ::cuMemMap */ CUresult CUDAAPI cuMemRetainAllocationHandle(CUmemGenericAllocationHandle *handle, void *addr); /** @} */ /* END CUDA_VA */ /** * \defgroup CUDA_MALLOC_ASYNC Stream Ordered Memory Allocator * * ___MANBRIEF___ Functions for performing allocation and free operations in stream order. * Functions for controlling the behavior of the underlying allocator. * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the stream ordered memory allocator exposed by the * low-level CUDA driver application programming interface. * * @{ * * \section CUDA_MALLOC_ASYNC_overview overview * * The asynchronous allocator allows the user to allocate and free in stream order. * All asynchronous accesses of the allocation must happen between * the stream executions of the allocation and the free. If the memory is accessed * outside of the promised stream order, a use before allocation / use after free error * will cause undefined behavior. * * The allocator is free to reallocate the memory as long as it can guarantee * that compliant memory accesses will not overlap temporally. * The allocator may refer to internal stream ordering as well as inter-stream dependencies * (such as CUDA events and null stream dependencies) when establishing the temporal guarantee. * The allocator may also insert inter-stream dependencies to establish the temporal guarantee. * * \section CUDA_MALLOC_ASYNC_support Supported Platforms * * Whether or not a device supports the integrated stream ordered memory allocator * may be queried by calling ::cuDeviceGetAttribute() with the device attribute * ::CU_DEVICE_ATTRIBUTE_MEMORY_POOLS_SUPPORTED */ /** * \brief Frees memory with stream ordered semantics * * Inserts a free operation into \p hStream. * The allocation must not be accessed after stream execution reaches the free. * After this API returns, accessing the memory from any subsequent work launched on the GPU * or querying its pointer attributes results in undefined behavior. * * \note During stream capture, this function results in the creation of a free node and * must therefore be passed the address of a graph allocation. * * \param dptr - memory to free * \param hStream - The stream establishing the stream ordering contract. * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT (default stream specified with no current context), * ::CUDA_ERROR_NOT_SUPPORTED */ CUresult CUDAAPI cuMemFreeAsync(CUdeviceptr dptr, CUstream hStream); /** * \brief Allocates memory with stream ordered semantics * * Inserts an allocation operation into \p hStream. * A pointer to the allocated memory is returned immediately in *dptr. * The allocation must not be accessed until the the allocation operation completes. * The allocation comes from the memory pool current to the stream's device. * * \note The default memory pool of a device contains device memory from that device. * \note Basic stream ordering allows future work submitted into the same stream to use the allocation. * Stream query, stream synchronize, and CUDA events can be used to guarantee that the allocation * operation completes before work submitted in a separate stream runs. * \note During stream capture, this function results in the creation of an allocation node. In this case, * the allocation is owned by the graph instead of the memory pool. The memory pool's properties * are used to set the node's creation parameters. * * \param[out] dptr - Returned device pointer * \param[in] bytesize - Number of bytes to allocate * \param[in] hStream - The stream establishing the stream ordering contract and the memory pool to allocate from * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT (default stream specified with no current context), * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_OUT_OF_MEMORY * * \sa ::cuMemAllocFromPoolAsync, ::cuMemFreeAsync, ::cuDeviceSetMemPool, * ::cuDeviceGetDefaultMemPool, ::cuDeviceGetMemPool, ::cuMemPoolCreate, * ::cuMemPoolSetAccess, ::cuMemPoolSetAttribute */ CUresult CUDAAPI cuMemAllocAsync(CUdeviceptr *dptr, size_t bytesize, CUstream hStream); /** * \brief Tries to release memory back to the OS * * Releases memory back to the OS until the pool contains fewer than minBytesToKeep * reserved bytes, or there is no more memory that the allocator can safely release. * The allocator cannot release OS allocations that back outstanding asynchronous allocations. * The OS allocations may happen at different granularity from the user allocations. * * \note: Allocations that have not been freed count as outstanding. * \note: Allocations that have been asynchronously freed but whose completion has * not been observed on the host (eg. by a synchronize) can count as outstanding. * * \param[in] pool - The memory pool to trim * \param[in] minBytesToKeep - If the pool has less than minBytesToKeep reserved, * the TrimTo operation is a no-op. Otherwise the pool will be guaranteed to have * at least minBytesToKeep bytes reserved after the operation. * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuMemAllocAsync, ::cuMemFreeAsync, ::cuDeviceGetDefaultMemPool, * ::cuDeviceGetMemPool, ::cuMemPoolCreate */ CUresult CUDAAPI cuMemPoolTrimTo(CUmemoryPool pool, size_t minBytesToKeep); /** * \brief Sets attributes of a memory pool * * Supported attributes are: * - ::CU_MEMPOOL_ATTR_RELEASE_THRESHOLD: (value type = cuuint64_t) * Amount of reserved memory in bytes to hold onto before trying * to release memory back to the OS. When more than the release * threshold bytes of memory are held by the memory pool, the * allocator will try to release memory back to the OS on the * next call to stream, event or context synchronize. (default 0) * - ::CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES: (value type = int) * Allow ::cuMemAllocAsync to use memory asynchronously freed * in another stream as long as a stream ordering dependency * of the allocating stream on the free action exists. * Cuda events and null stream interactions can create the required * stream ordered dependencies. (default enabled) * - ::CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC: (value type = int) * Allow reuse of already completed frees when there is no dependency * between the free and allocation. (default enabled) * - ::CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES: (value type = int) * Allow ::cuMemAllocAsync to insert new stream dependencies * in order to establish the stream ordering required to reuse * a piece of memory released by ::cuMemFreeAsync (default enabled). * - ::CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH: (value type = cuuint64_t) * Reset the high watermark that tracks the amount of backing memory that was * allocated for the memory pool. It is illegal to set this attribute to a non-zero value. * - ::CU_MEMPOOL_ATTR_USED_MEM_HIGH: (value type = cuuint64_t) * Reset the high watermark that tracks the amount of used memory that was * allocated for the memory pool. * * \param[in] pool - The memory pool to modify * \param[in] attr - The attribute to modify * \param[in] value - Pointer to the value to assign * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuMemAllocAsync, ::cuMemFreeAsync, ::cuDeviceGetDefaultMemPool, * ::cuDeviceGetMemPool, ::cuMemPoolCreate */ CUresult CUDAAPI cuMemPoolSetAttribute(CUmemoryPool pool, CUmemPool_attribute attr, void *value); /** * \brief Gets attributes of a memory pool * * Supported attributes are: * - ::CU_MEMPOOL_ATTR_RELEASE_THRESHOLD: (value type = cuuint64_t) * Amount of reserved memory in bytes to hold onto before trying * to release memory back to the OS. When more than the release * threshold bytes of memory are held by the memory pool, the * allocator will try to release memory back to the OS on the * next call to stream, event or context synchronize. (default 0) * - ::CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES: (value type = int) * Allow ::cuMemAllocAsync to use memory asynchronously freed * in another stream as long as a stream ordering dependency * of the allocating stream on the free action exists. * Cuda events and null stream interactions can create the required * stream ordered dependencies. (default enabled) * - ::CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC: (value type = int) * Allow reuse of already completed frees when there is no dependency * between the free and allocation. (default enabled) * - ::CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES: (value type = int) * Allow ::cuMemAllocAsync to insert new stream dependencies * in order to establish the stream ordering required to reuse * a piece of memory released by ::cuMemFreeAsync (default enabled). * - ::CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT: (value type = cuuint64_t) * Amount of backing memory currently allocated for the mempool * - ::CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH: (value type = cuuint64_t) * High watermark of backing memory allocated for the mempool since the * last time it was reset. * - ::CU_MEMPOOL_ATTR_USED_MEM_CURRENT: (value type = cuuint64_t) * Amount of memory from the pool that is currently in use by the application. * - ::CU_MEMPOOL_ATTR_USED_MEM_HIGH: (value type = cuuint64_t) * High watermark of the amount of memory from the pool that was in use by the application. * * \param[in] pool - The memory pool to get attributes of * \param[in] attr - The attribute to get * \param[out] value - Retrieved value * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuMemAllocAsync, ::cuMemFreeAsync, ::cuDeviceGetDefaultMemPool, * ::cuDeviceGetMemPool, ::cuMemPoolCreate */ CUresult CUDAAPI cuMemPoolGetAttribute(CUmemoryPool pool, CUmemPool_attribute attr, void *value); /** * \brief Controls visibility of pools between devices * * \param[in] pool - The pool being modified * \param[in] map - Array of access descriptors. Each descriptor instructs the access to enable for a single gpu. * \param[in] count - Number of descriptors in the map array. * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuMemAllocAsync, ::cuMemFreeAsync, ::cuDeviceGetDefaultMemPool, * ::cuDeviceGetMemPool, ::cuMemPoolCreate */ CUresult CUDAAPI cuMemPoolSetAccess(CUmemoryPool pool, const CUmemAccessDesc *map, size_t count); /** * \brief Returns the accessibility of a pool from a device * * Returns the accessibility of the pool's memory from the specified location. * * \param[out] flags - the accessibility of the pool from the specified location * \param[in] memPool - the pool being queried * \param[in] location - the location accessing the pool * * \sa ::cuMemAllocAsync, ::cuMemFreeAsync, ::cuDeviceGetDefaultMemPool, * ::cuDeviceGetMemPool, ::cuMemPoolCreate */ CUresult CUDAAPI cuMemPoolGetAccess(CUmemAccess_flags *flags, CUmemoryPool memPool, CUmemLocation *location); /** * \brief Creates a memory pool * * Creates a CUDA memory pool and returns the handle in \p pool. The \p poolProps determines * the properties of the pool such as the backing device and IPC capabilities. * * By default, the pool's memory will be accessible from the device it is allocated on. * * \note Specifying CU_MEM_HANDLE_TYPE_NONE creates a memory pool that will not support IPC. * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY, * ::CUDA_ERROR_NOT_SUPPORTED * * \sa ::cuDeviceSetMemPool, ::cuDeviceGetMemPool, ::cuDeviceGetDefaultMemPool, * ::cuMemAllocFromPoolAsync, ::cuMemPoolExportToShareableHandle */ CUresult CUDAAPI cuMemPoolCreate(CUmemoryPool *pool, const CUmemPoolProps *poolProps); /** * \brief Destroys the specified memory pool * * If any pointers obtained from this pool haven't been freed or * the pool has free operations that haven't completed * when ::cuMemPoolDestroy is invoked, the function will return immediately and the * resources associated with the pool will be released automatically * once there are no more outstanding allocations. * * Destroying the current mempool of a device sets the default mempool of * that device as the current mempool for that device. * * \note A device's default memory pool cannot be destroyed. * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuMemFreeAsync, ::cuDeviceSetMemPool, ::cuDeviceGetMemPool, * ::cuDeviceGetDefaultMemPool, ::cuMemPoolCreate */ CUresult CUDAAPI cuMemPoolDestroy(CUmemoryPool pool); /** * \brief Allocates memory from a specified pool with stream ordered semantics. * * Inserts an allocation operation into \p hStream. * A pointer to the allocated memory is returned immediately in *dptr. * The allocation must not be accessed until the the allocation operation completes. * The allocation comes from the specified memory pool. * * \note * - The specified memory pool may be from a device different than that of the specified \p hStream. * * - Basic stream ordering allows future work submitted into the same stream to use the allocation. * Stream query, stream synchronize, and CUDA events can be used to guarantee that the allocation * operation completes before work submitted in a separate stream runs. * * \note During stream capture, this function results in the creation of an allocation node. In this case, * the allocation is owned by the graph instead of the memory pool. The memory pool's properties * are used to set the node's creation parameters. * * \param[out] dptr - Returned device pointer * \param[in] bytesize - Number of bytes to allocate * \param[in] pool - The pool to allocate from * \param[in] hStream - The stream establishing the stream ordering semantic * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT (default stream specified with no current context), * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_OUT_OF_MEMORY * * \sa ::cuMemAllocAsync, ::cuMemFreeAsync, ::cuDeviceGetDefaultMemPool, * ::cuDeviceGetMemPool, ::cuMemPoolCreate, ::cuMemPoolSetAccess, * ::cuMemPoolSetAttribute */ CUresult CUDAAPI cuMemAllocFromPoolAsync(CUdeviceptr *dptr, size_t bytesize, CUmemoryPool pool, CUstream hStream); /** * \brief Exports a memory pool to the requested handle type. * * Given an IPC capable mempool, create an OS handle to share the pool with another process. * A recipient process can convert the shareable handle into a mempool with ::cuMemPoolImportFromShareableHandle. * Individual pointers can then be shared with the ::cuMemPoolExportPointer and ::cuMemPoolImportPointer APIs. * The implementation of what the shareable handle is and how it can be transferred is defined by the requested * handle type. * * \note: To create an IPC capable mempool, create a mempool with a CUmemAllocationHandleType other than CU_MEM_HANDLE_TYPE_NONE. * * \param[out] handle_out - Returned OS handle * \param[in] pool - pool to export * \param[in] handleType - the type of handle to create * \param[in] flags - must be 0 * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_OUT_OF_MEMORY * * \sa ::cuMemPoolImportFromShareableHandle, ::cuMemPoolExportPointer, * ::cuMemPoolImportPointer, ::cuMemAllocAsync, ::cuMemFreeAsync, * ::cuDeviceGetDefaultMemPool, ::cuDeviceGetMemPool, ::cuMemPoolCreate, * ::cuMemPoolSetAccess, ::cuMemPoolSetAttribute */ CUresult CUDAAPI cuMemPoolExportToShareableHandle(void *handle_out, CUmemoryPool pool, CUmemAllocationHandleType handleType, unsigned long long flags); /** * \brief imports a memory pool from a shared handle. * * Specific allocations can be imported from the imported pool with cuMemPoolImportPointer. * * \note Imported memory pools do not support creating new allocations. * As such imported memory pools may not be used in cuDeviceSetMemPool * or ::cuMemAllocFromPoolAsync calls. * * \param[out] pool_out - Returned memory pool * \param[in] handle - OS handle of the pool to open * \param[in] handleType - The type of handle being imported * \param[in] flags - must be 0 * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_OUT_OF_MEMORY * * \sa ::cuMemPoolExportToShareableHandle, ::cuMemPoolExportPointer, ::cuMemPoolImportPointer */ CUresult CUDAAPI cuMemPoolImportFromShareableHandle( CUmemoryPool *pool_out, void *handle, CUmemAllocationHandleType handleType, unsigned long long flags); /** * \brief Export data to share a memory pool allocation between processes. * * Constructs \p shareData_out for sharing a specific allocation from an already shared memory pool. * The recipient process can import the allocation with the ::cuMemPoolImportPointer api. * The data is not a handle and may be shared through any IPC mechanism. * * \param[out] shareData_out - Returned export data * \param[in] ptr - pointer to memory being exported * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_OUT_OF_MEMORY * * \sa ::cuMemPoolExportToShareableHandle, ::cuMemPoolImportFromShareableHandle, ::cuMemPoolImportPointer */ CUresult CUDAAPI cuMemPoolExportPointer(CUmemPoolPtrExportData *shareData_out, CUdeviceptr ptr); /** * \brief Import a memory pool allocation from another process. * * Returns in \p ptr_out a pointer to the imported memory. * The imported memory must not be accessed before the allocation operation completes * in the exporting process. The imported memory must be freed from all importing processes before * being freed in the exporting process. The pointer may be freed with cuMemFree * or cuMemFreeAsync. If cuMemFreeAsync is used, the free must be completed * on the importing process before the free operation on the exporting process. * * \note The cuMemFreeAsync api may be used in the exporting process before * the cuMemFreeAsync operation completes in its stream as long as the * cuMemFreeAsync in the exporting process specifies a stream with * a stream dependency on the importing process's cuMemFreeAsync. * * \param[out] ptr_out - pointer to imported memory * \param[in] pool - pool from which to import * \param[in] shareData - data specifying the memory to import * * \returns * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_OUT_OF_MEMORY * * \sa ::cuMemPoolExportToShareableHandle, ::cuMemPoolImportFromShareableHandle, ::cuMemPoolExportPointer */ CUresult CUDAAPI cuMemPoolImportPointer(CUdeviceptr *ptr_out, CUmemoryPool pool, CUmemPoolPtrExportData *shareData); /** @} */ /* END CUDA_MALLOC_ASYNC */ /** * \defgroup CUDA_UNIFIED Unified Addressing * * ___MANBRIEF___ unified addressing functions of the low-level CUDA driver * API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the unified addressing functions of the * low-level CUDA driver application programming interface. * * @{ * * \section CUDA_UNIFIED_overview Overview * * CUDA devices can share a unified address space with the host. * For these devices there is no distinction between a device * pointer and a host pointer -- the same pointer value may be * used to access memory from the host program and from a kernel * running on the device (with exceptions enumerated below). * * \section CUDA_UNIFIED_support Supported Platforms * * Whether or not a device supports unified addressing may be * queried by calling ::cuDeviceGetAttribute() with the device * attribute ::CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING. * * Unified addressing is automatically enabled in 64-bit processes * * \section CUDA_UNIFIED_lookup Looking Up Information from Pointer Values * * It is possible to look up information about the memory which backs a * pointer value. For instance, one may want to know if a pointer points * to host or device memory. As another example, in the case of device * memory, one may want to know on which CUDA device the memory * resides. These properties may be queried using the function * ::cuPointerGetAttribute() * * Since pointers are unique, it is not necessary to specify information * about the pointers specified to the various copy functions in the * CUDA API. The function ::cuMemcpy() may be used to perform a copy * between two pointers, ignoring whether they point to host or device * memory (making ::cuMemcpyHtoD(), ::cuMemcpyDtoD(), and ::cuMemcpyDtoH() * unnecessary for devices supporting unified addressing). For * multidimensional copies, the memory type ::CU_MEMORYTYPE_UNIFIED may be * used to specify that the CUDA driver should infer the location of the * pointer from its value. * * \section CUDA_UNIFIED_automaphost Automatic Mapping of Host Allocated Host Memory * * All host memory allocated in all contexts using ::cuMemAllocHost() and * ::cuMemHostAlloc() is always directly accessible from all contexts on * all devices that support unified addressing. This is the case regardless * of whether or not the flags ::CU_MEMHOSTALLOC_PORTABLE and * ::CU_MEMHOSTALLOC_DEVICEMAP are specified. * * The pointer value through which allocated host memory may be accessed * in kernels on all devices that support unified addressing is the same * as the pointer value through which that memory is accessed on the host, * so it is not necessary to call ::cuMemHostGetDevicePointer() to get the device * pointer for these allocations. * * Note that this is not the case for memory allocated using the flag * ::CU_MEMHOSTALLOC_WRITECOMBINED, as discussed below. * * \section CUDA_UNIFIED_autopeerregister Automatic Registration of Peer Memory * * Upon enabling direct access from a context that supports unified addressing * to another peer context that supports unified addressing using * ::cuCtxEnablePeerAccess() all memory allocated in the peer context using * ::cuMemAlloc() and ::cuMemAllocPitch() will immediately be accessible * by the current context. The device pointer value through * which any peer memory may be accessed in the current context * is the same pointer value through which that memory may be * accessed in the peer context. * * \section CUDA_UNIFIED_exceptions Exceptions, Disjoint Addressing * * Not all memory may be accessed on devices through the same pointer * value through which they are accessed on the host. These exceptions * are host memory registered using ::cuMemHostRegister() and host memory * allocated using the flag ::CU_MEMHOSTALLOC_WRITECOMBINED. For these * exceptions, there exists a distinct host and device address for the * memory. The device address is guaranteed to not overlap any valid host * pointer range and is guaranteed to have the same value across all * contexts that support unified addressing. * * This device address may be queried using ::cuMemHostGetDevicePointer() * when a context using unified addressing is current. Either the host * or the unified device pointer value may be used to refer to this memory * through ::cuMemcpy() and similar functions using the * ::CU_MEMORYTYPE_UNIFIED memory type. * */ /** * \brief Returns information about a pointer * * The supported attributes are: * * - ::CU_POINTER_ATTRIBUTE_CONTEXT: * * Returns in \p *data the ::CUcontext in which \p ptr was allocated or * registered. * The type of \p data must be ::CUcontext *. * * If \p ptr was not allocated by, mapped by, or registered with * a ::CUcontext which uses unified virtual addressing then * ::CUDA_ERROR_INVALID_VALUE is returned. * * - ::CU_POINTER_ATTRIBUTE_MEMORY_TYPE: * * Returns in \p *data the physical memory type of the memory that * \p ptr addresses as a ::CUmemorytype enumerated value. * The type of \p data must be unsigned int. * * If \p ptr addresses device memory then \p *data is set to * ::CU_MEMORYTYPE_DEVICE. The particular ::CUdevice on which the * memory resides is the ::CUdevice of the ::CUcontext returned by the * ::CU_POINTER_ATTRIBUTE_CONTEXT attribute of \p ptr. * * If \p ptr addresses host memory then \p *data is set to * ::CU_MEMORYTYPE_HOST. * * If \p ptr was not allocated by, mapped by, or registered with * a ::CUcontext which uses unified virtual addressing then * ::CUDA_ERROR_INVALID_VALUE is returned. * * If the current ::CUcontext does not support unified virtual * addressing then ::CUDA_ERROR_INVALID_CONTEXT is returned. * * - ::CU_POINTER_ATTRIBUTE_DEVICE_POINTER: * * Returns in \p *data the device pointer value through which * \p ptr may be accessed by kernels running in the current * ::CUcontext. * The type of \p data must be CUdeviceptr *. * * If there exists no device pointer value through which * kernels running in the current ::CUcontext may access * \p ptr then ::CUDA_ERROR_INVALID_VALUE is returned. * * If there is no current ::CUcontext then * ::CUDA_ERROR_INVALID_CONTEXT is returned. * * Except in the exceptional disjoint addressing cases discussed * below, the value returned in \p *data will equal the input * value \p ptr. * * - ::CU_POINTER_ATTRIBUTE_HOST_POINTER: * * Returns in \p *data the host pointer value through which * \p ptr may be accessed by by the host program. * The type of \p data must be void **. * If there exists no host pointer value through which * the host program may directly access \p ptr then * ::CUDA_ERROR_INVALID_VALUE is returned. * * Except in the exceptional disjoint addressing cases discussed * below, the value returned in \p *data will equal the input * value \p ptr. * * - ::CU_POINTER_ATTRIBUTE_P2P_TOKENS: * * Returns in \p *data two tokens for use with the nv-p2p.h Linux * kernel interface. \p data must be a struct of type * CUDA_POINTER_ATTRIBUTE_P2P_TOKENS. * * \p ptr must be a pointer to memory obtained from :cuMemAlloc(). * Note that p2pToken and vaSpaceToken are only valid for the * lifetime of the source allocation. A subsequent allocation at * the same address may return completely different tokens. * Querying this attribute has a side effect of setting the attribute * ::CU_POINTER_ATTRIBUTE_SYNC_MEMOPS for the region of memory that * \p ptr points to. * * - ::CU_POINTER_ATTRIBUTE_SYNC_MEMOPS: * * A boolean attribute which when set, ensures that synchronous memory operations * initiated on the region of memory that \p ptr points to will always synchronize. * See further documentation in the section titled "API synchronization behavior" * to learn more about cases when synchronous memory operations can * exhibit asynchronous behavior. * * - ::CU_POINTER_ATTRIBUTE_BUFFER_ID: * * Returns in \p *data a buffer ID which is guaranteed to be unique within the process. * \p data must point to an unsigned long long. * * \p ptr must be a pointer to memory obtained from a CUDA memory allocation API. * Every memory allocation from any of the CUDA memory allocation APIs will * have a unique ID over a process lifetime. Subsequent allocations do not reuse IDs * from previous freed allocations. IDs are only unique within a single process. * * * - ::CU_POINTER_ATTRIBUTE_IS_MANAGED: * * Returns in \p *data a boolean that indicates whether the pointer points to * managed memory or not. * * If \p ptr is not a valid CUDA pointer then ::CUDA_ERROR_INVALID_VALUE is returned. * * - ::CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL: * * Returns in \p *data an integer representing a device ordinal of a device against * which the memory was allocated or registered. * * - ::CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE: * * Returns in \p *data a boolean that indicates if this pointer maps to * an allocation that is suitable for ::cudaIpcGetMemHandle. * * - ::CU_POINTER_ATTRIBUTE_RANGE_START_ADDR: * * Returns in \p *data the starting address for the allocation referenced * by the device pointer \p ptr. Note that this is not necessarily the * address of the mapped region, but the address of the mappable address * range \p ptr references (e.g. from ::cuMemAddressReserve). * * - ::CU_POINTER_ATTRIBUTE_RANGE_SIZE: * * Returns in \p *data the size for the allocation referenced by the device * pointer \p ptr. Note that this is not necessarily the size of the mapped * region, but the size of the mappable address range \p ptr references * (e.g. from ::cuMemAddressReserve). To retrieve the size of the mapped * region, see ::cuMemGetAddressRange * * - ::CU_POINTER_ATTRIBUTE_MAPPED: * * Returns in \p *data a boolean that indicates if this pointer is in a * valid address range that is mapped to a backing allocation. * * - ::CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES: * * Returns a bitmask of the allowed handle types for an allocation that may * be passed to ::cuMemExportToShareableHandle. * * - ::CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE: * * Returns in \p *data the handle to the mempool that the allocation was obtained from. * * \par * * Note that for most allocations in the unified virtual address space * the host and device pointer for accessing the allocation will be the * same. The exceptions to this are * - user memory registered using ::cuMemHostRegister * - host memory allocated using ::cuMemHostAlloc with the * ::CU_MEMHOSTALLOC_WRITECOMBINED flag * For these types of allocation there will exist separate, disjoint host * and device addresses for accessing the allocation. In particular * - The host address will correspond to an invalid unmapped device address * (which will result in an exception if accessed from the device) * - The device address will correspond to an invalid unmapped host address * (which will result in an exception if accessed from the host). * For these types of allocations, querying ::CU_POINTER_ATTRIBUTE_HOST_POINTER * and ::CU_POINTER_ATTRIBUTE_DEVICE_POINTER may be used to retrieve the host * and device addresses from either address. * * \param data - Returned pointer attribute value * \param attribute - Pointer attribute to query * \param ptr - Pointer * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuPointerSetAttribute, * ::cuMemAlloc, * ::cuMemFree, * ::cuMemAllocHost, * ::cuMemFreeHost, * ::cuMemHostAlloc, * ::cuMemHostRegister, * ::cuMemHostUnregister, * ::cudaPointerGetAttributes */ CUresult CUDAAPI cuPointerGetAttribute(void *data, CUpointer_attribute attribute, CUdeviceptr ptr); /** * \brief Prefetches memory to the specified destination device * * Prefetches memory to the specified destination device. \p devPtr is the * base device pointer of the memory to be prefetched and \p dstDevice is the * destination device. \p count specifies the number of bytes to copy. \p hStream * is the stream in which the operation is enqueued. The memory range must refer * to managed memory allocated via ::cuMemAllocManaged or declared via __managed__ variables. * * Passing in CU_DEVICE_CPU for \p dstDevice will prefetch the data to host memory. If * \p dstDevice is a GPU, then the device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS * must be non-zero. Additionally, \p hStream must be associated with a device that has a * non-zero value for the device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. * * The start address and end address of the memory range will be rounded down and rounded up * respectively to be aligned to CPU page size before the prefetch operation is enqueued * in the stream. * * If no physical memory has been allocated for this region, then this memory region * will be populated and mapped on the destination device. If there's insufficient * memory to prefetch the desired region, the Unified Memory driver may evict pages from other * ::cuMemAllocManaged allocations to host memory in order to make room. Device memory * allocated using ::cuMemAlloc or ::cuArrayCreate will not be evicted. * * By default, any mappings to the previous location of the migrated pages are removed and * mappings for the new location are only setup on \p dstDevice. The exact behavior however * also depends on the settings applied to this memory range via ::cuMemAdvise as described * below: * * If ::CU_MEM_ADVISE_SET_READ_MOSTLY was set on any subset of this memory range, * then that subset will create a read-only copy of the pages on \p dstDevice. * * If ::CU_MEM_ADVISE_SET_PREFERRED_LOCATION was called on any subset of this memory * range, then the pages will be migrated to \p dstDevice even if \p dstDevice is not the * preferred location of any pages in the memory range. * * If ::CU_MEM_ADVISE_SET_ACCESSED_BY was called on any subset of this memory range, * then mappings to those pages from all the appropriate processors are updated to * refer to the new location if establishing such a mapping is possible. Otherwise, * those mappings are cleared. * * Note that this API is not required for functionality and only serves to improve performance * by allowing the application to migrate data to a suitable location before it is accessed. * Memory accesses to this range are always coherent and are allowed even when the data is * actively being migrated. * * Note that this function is asynchronous with respect to the host and all work * on other devices. * * \param devPtr - Pointer to be prefetched * \param count - Size in bytes * \param dstDevice - Destination device to prefetch to * \param hStream - Stream to enqueue prefetch operation * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * \note_async * \note_null_stream * * \sa ::cuMemcpy, ::cuMemcpyPeer, ::cuMemcpyAsync, * ::cuMemcpy3DPeerAsync, ::cuMemAdvise, * ::cudaMemPrefetchAsync */ CUresult CUDAAPI cuMemPrefetchAsync(CUdeviceptr devPtr, size_t count, CUdevice dstDevice, CUstream hStream); /** * \brief Advise about the usage of a given memory range * * Advise the Unified Memory subsystem about the usage pattern for the memory range * starting at \p devPtr with a size of \p count bytes. The start address and end address of the memory * range will be rounded down and rounded up respectively to be aligned to CPU page size before the * advice is applied. The memory range must refer to managed memory allocated via ::cuMemAllocManaged * or declared via __managed__ variables. The memory range could also refer to system-allocated pageable * memory provided it represents a valid, host-accessible region of memory and all additional constraints * imposed by \p advice as outlined below are also satisfied. Specifying an invalid system-allocated pageable * memory range results in an error being returned. * * The \p advice parameter can take the following values: * - ::CU_MEM_ADVISE_SET_READ_MOSTLY: This implies that the data is mostly going to be read * from and only occasionally written to. Any read accesses from any processor to this region will create a * read-only copy of at least the accessed pages in that processor's memory. Additionally, if ::cuMemPrefetchAsync * is called on this region, it will create a read-only copy of the data on the destination processor. * If any processor writes to this region, all copies of the corresponding page will be invalidated * except for the one where the write occurred. The \p device argument is ignored for this advice. * Note that for a page to be read-duplicated, the accessing processor must either be the CPU or a GPU * that has a non-zero value for the device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. * Also, if a context is created on a device that does not have the device attribute * ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS set, then read-duplication will not occur until * all such contexts are destroyed. * If the memory region refers to valid system-allocated pageable memory, then the accessing device must * have a non-zero value for the device attribute ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS for a read-only * copy to be created on that device. Note however that if the accessing device also has a non-zero value for the * device attribute ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, then setting this advice * will not create a read-only copy when that device accesses this memory region. * * - ::CU_MEM_ADVISE_UNSET_READ_MOSTLY: Undoes the effect of ::CU_MEM_ADVISE_SET_READ_MOSTLY and also prevents the * Unified Memory driver from attempting heuristic read-duplication on the memory range. Any read-duplicated * copies of the data will be collapsed into a single copy. The location for the collapsed * copy will be the preferred location if the page has a preferred location and one of the read-duplicated * copies was resident at that location. Otherwise, the location chosen is arbitrary. * * - ::CU_MEM_ADVISE_SET_PREFERRED_LOCATION: This advice sets the preferred location for the * data to be the memory belonging to \p device. Passing in CU_DEVICE_CPU for \p device sets the * preferred location as host memory. If \p device is a GPU, then it must have a non-zero value for the * device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. Setting the preferred location * does not cause data to migrate to that location immediately. Instead, it guides the migration policy * when a fault occurs on that memory region. If the data is already in its preferred location and the * faulting processor can establish a mapping without requiring the data to be migrated, then * data migration will be avoided. On the other hand, if the data is not in its preferred location * or if a direct mapping cannot be established, then it will be migrated to the processor accessing * it. It is important to note that setting the preferred location does not prevent data prefetching * done using ::cuMemPrefetchAsync. * Having a preferred location can override the page thrash detection and resolution logic in the Unified * Memory driver. Normally, if a page is detected to be constantly thrashing between for example host and device * memory, the page may eventually be pinned to host memory by the Unified Memory driver. But * if the preferred location is set as device memory, then the page will continue to thrash indefinitely. * If ::CU_MEM_ADVISE_SET_READ_MOSTLY is also set on this memory region or any subset of it, then the * policies associated with that advice will override the policies of this advice, unless read accesses from * \p device will not result in a read-only copy being created on that device as outlined in description for * the advice ::CU_MEM_ADVISE_SET_READ_MOSTLY. * If the memory region refers to valid system-allocated pageable memory, then \p device must have a non-zero * value for the device attribute ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. Additionally, if \p device has * a non-zero value for the device attribute ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, * then this call has no effect. Note however that this behavior may change in the future. * * - ::CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION: Undoes the effect of ::CU_MEM_ADVISE_SET_PREFERRED_LOCATION * and changes the preferred location to none. * * - ::CU_MEM_ADVISE_SET_ACCESSED_BY: This advice implies that the data will be accessed by \p device. * Passing in ::CU_DEVICE_CPU for \p device will set the advice for the CPU. If \p device is a GPU, then * the device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS must be non-zero. * This advice does not cause data migration and has no impact on the location of the data per se. Instead, * it causes the data to always be mapped in the specified processor's page tables, as long as the * location of the data permits a mapping to be established. If the data gets migrated for any reason, * the mappings are updated accordingly. * This advice is recommended in scenarios where data locality is not important, but avoiding faults is. * Consider for example a system containing multiple GPUs with peer-to-peer access enabled, where the * data located on one GPU is occasionally accessed by peer GPUs. In such scenarios, migrating data * over to the other GPUs is not as important because the accesses are infrequent and the overhead of * migration may be too high. But preventing faults can still help improve performance, and so having * a mapping set up in advance is useful. Note that on CPU access of this data, the data may be migrated * to host memory because the CPU typically cannot access device memory directly. Any GPU that had the * ::CU_MEM_ADVISE_SET_ACCESSED_BY flag set for this data will now have its mapping updated to point to the * page in host memory. * If ::CU_MEM_ADVISE_SET_READ_MOSTLY is also set on this memory region or any subset of it, then the * policies associated with that advice will override the policies of this advice. Additionally, if the * preferred location of this memory region or any subset of it is also \p device, then the policies * associated with ::CU_MEM_ADVISE_SET_PREFERRED_LOCATION will override the policies of this advice. * If the memory region refers to valid system-allocated pageable memory, then \p device must have a non-zero * value for the device attribute ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. Additionally, if \p device has * a non-zero value for the device attribute ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, * then this call has no effect. * * - ::CU_MEM_ADVISE_UNSET_ACCESSED_BY: Undoes the effect of ::CU_MEM_ADVISE_SET_ACCESSED_BY. Any mappings to * the data from \p device may be removed at any time causing accesses to result in non-fatal page faults. * If the memory region refers to valid system-allocated pageable memory, then \p device must have a non-zero * value for the device attribute ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. Additionally, if \p device has * a non-zero value for the device attribute ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES, * then this call has no effect. * * \param devPtr - Pointer to memory to set the advice for * \param count - Size in bytes of the memory range * \param advice - Advice to be applied for the specified memory range * \param device - Device to apply the advice for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * \note_async * \note_null_stream * * \sa ::cuMemcpy, ::cuMemcpyPeer, ::cuMemcpyAsync, * ::cuMemcpy3DPeerAsync, ::cuMemPrefetchAsync, * ::cudaMemAdvise */ CUresult CUDAAPI cuMemAdvise(CUdeviceptr devPtr, size_t count, CUmem_advise advice, CUdevice device); /** * \brief Query an attribute of a given memory range * * Query an attribute about the memory range starting at \p devPtr with a size of \p count bytes. The * memory range must refer to managed memory allocated via ::cuMemAllocManaged or declared via * __managed__ variables. * * The \p attribute parameter can take the following values: * - ::CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY: If this attribute is specified, \p data will be interpreted * as a 32-bit integer, and \p dataSize must be 4. The result returned will be 1 if all pages in the given * memory range have read-duplication enabled, or 0 otherwise. * - ::CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION: If this attribute is specified, \p data will be * interpreted as a 32-bit integer, and \p dataSize must be 4. The result returned will be a GPU device * id if all pages in the memory range have that GPU as their preferred location, or it will be CU_DEVICE_CPU * if all pages in the memory range have the CPU as their preferred location, or it will be CU_DEVICE_INVALID * if either all the pages don't have the same preferred location or some of the pages don't have a * preferred location at all. Note that the actual location of the pages in the memory range at the time of * the query may be different from the preferred location. * - ::CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY: If this attribute is specified, \p data will be interpreted * as an array of 32-bit integers, and \p dataSize must be a non-zero multiple of 4. The result returned * will be a list of device ids that had ::CU_MEM_ADVISE_SET_ACCESSED_BY set for that entire memory range. * If any device does not have that advice set for the entire memory range, that device will not be included. * If \p data is larger than the number of devices that have that advice set for that memory range, * CU_DEVICE_INVALID will be returned in all the extra space provided. For ex., if \p dataSize is 12 * (i.e. \p data has 3 elements) and only device 0 has the advice set, then the result returned will be * { 0, CU_DEVICE_INVALID, CU_DEVICE_INVALID }. If \p data is smaller than the number of devices that have * that advice set, then only as many devices will be returned as can fit in the array. There is no * guarantee on which specific devices will be returned, however. * - ::CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION: If this attribute is specified, \p data will be * interpreted as a 32-bit integer, and \p dataSize must be 4. The result returned will be the last location * to which all pages in the memory range were prefetched explicitly via ::cuMemPrefetchAsync. This will either be * a GPU id or CU_DEVICE_CPU depending on whether the last location for prefetch was a GPU or the CPU * respectively. If any page in the memory range was never explicitly prefetched or if all pages were not * prefetched to the same location, CU_DEVICE_INVALID will be returned. Note that this simply returns the * last location that the applicaton requested to prefetch the memory range to. It gives no indication as to * whether the prefetch operation to that location has completed or even begun. * * \param data - A pointers to a memory location where the result * of each attribute query will be written to. * \param dataSize - Array containing the size of data * \param attribute - The attribute to query * \param devPtr - Start of the range to query * \param count - Size of the range to query * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * \note_async * \note_null_stream * * \sa ::cuMemRangeGetAttributes, ::cuMemPrefetchAsync, * ::cuMemAdvise, * ::cudaMemRangeGetAttribute */ CUresult CUDAAPI cuMemRangeGetAttribute(void *data, size_t dataSize, CUmem_range_attribute attribute, CUdeviceptr devPtr, size_t count); /** * \brief Query attributes of a given memory range. * * Query attributes of the memory range starting at \p devPtr with a size of \p count bytes. The * memory range must refer to managed memory allocated via ::cuMemAllocManaged or declared via * __managed__ variables. The \p attributes array will be interpreted to have \p numAttributes * entries. The \p dataSizes array will also be interpreted to have \p numAttributes entries. * The results of the query will be stored in \p data. * * The list of supported attributes are given below. Please refer to ::cuMemRangeGetAttribute for * attribute descriptions and restrictions. * * - ::CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY * - ::CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION * - ::CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY * - ::CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION * * \param data - A two-dimensional array containing pointers to memory * locations where the result of each attribute query will be written to. * \param dataSizes - Array containing the sizes of each result * \param attributes - An array of attributes to query * (numAttributes and the number of attributes in this array should match) * \param numAttributes - Number of attributes to query * \param devPtr - Start of the range to query * \param count - Size of the range to query * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa ::cuMemRangeGetAttribute, ::cuMemAdvise, * ::cuMemPrefetchAsync, * ::cudaMemRangeGetAttributes */ CUresult CUDAAPI cuMemRangeGetAttributes(void **data, size_t *dataSizes, CUmem_range_attribute *attributes, size_t numAttributes, CUdeviceptr devPtr, size_t count); /** * \brief Set attributes on a previously allocated memory region * * The supported attributes are: * * - ::CU_POINTER_ATTRIBUTE_SYNC_MEMOPS: * * A boolean attribute that can either be set (1) or unset (0). When set, * the region of memory that \p ptr points to is guaranteed to always synchronize * memory operations that are synchronous. If there are some previously initiated * synchronous memory operations that are pending when this attribute is set, the * function does not return until those memory operations are complete. * See further documentation in the section titled "API synchronization behavior" * to learn more about cases when synchronous memory operations can * exhibit asynchronous behavior. * \p value will be considered as a pointer to an unsigned integer to which this attribute is to be set. * * \param value - Pointer to memory containing the value to be set * \param attribute - Pointer attribute to set * \param ptr - Pointer to a memory region allocated using CUDA memory allocation APIs * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa ::cuPointerGetAttribute, * ::cuPointerGetAttributes, * ::cuMemAlloc, * ::cuMemFree, * ::cuMemAllocHost, * ::cuMemFreeHost, * ::cuMemHostAlloc, * ::cuMemHostRegister, * ::cuMemHostUnregister */ CUresult CUDAAPI cuPointerSetAttribute(const void *value, CUpointer_attribute attribute, CUdeviceptr ptr); /** * \brief Returns information about a pointer. * * The supported attributes are (refer to ::cuPointerGetAttribute for attribute descriptions and restrictions): * * - ::CU_POINTER_ATTRIBUTE_CONTEXT * - ::CU_POINTER_ATTRIBUTE_MEMORY_TYPE * - ::CU_POINTER_ATTRIBUTE_DEVICE_POINTER * - ::CU_POINTER_ATTRIBUTE_HOST_POINTER * - ::CU_POINTER_ATTRIBUTE_SYNC_MEMOPS * - ::CU_POINTER_ATTRIBUTE_BUFFER_ID * - ::CU_POINTER_ATTRIBUTE_IS_MANAGED * - ::CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL * - ::CU_POINTER_ATTRIBUTE_RANGE_START_ADDR * - ::CU_POINTER_ATTRIBUTE_RANGE_SIZE * - ::CU_POINTER_ATTRIBUTE_MAPPED * - ::CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE * - ::CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES * - ::CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE * * \param numAttributes - Number of attributes to query * \param attributes - An array of attributes to query * (numAttributes and the number of attributes in this array should match) * \param data - A two-dimensional array containing pointers to memory * locations where the result of each attribute query will be written to. * \param ptr - Pointer to query * * Unlike ::cuPointerGetAttribute, this function will not return an error when the \p ptr * encountered is not a valid CUDA pointer. Instead, the attributes are assigned default NULL values * and CUDA_SUCCESS is returned. * * If \p ptr was not allocated by, mapped by, or registered with a ::CUcontext which uses UVA * (Unified Virtual Addressing), ::CUDA_ERROR_INVALID_CONTEXT is returned. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuPointerGetAttribute, * ::cuPointerSetAttribute, * ::cudaPointerGetAttributes */ CUresult CUDAAPI cuPointerGetAttributes(unsigned int numAttributes, CUpointer_attribute *attributes, void **data, CUdeviceptr ptr); /** @} */ /* END CUDA_UNIFIED */ /** * \defgroup CUDA_STREAM Stream Management * * ___MANBRIEF___ stream management functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the stream management functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Create a stream * * Creates a stream and returns a handle in \p phStream. The \p Flags argument * determines behaviors of the stream. * * Valid values for \p Flags are: * - ::CU_STREAM_DEFAULT: Default stream creation flag. * - ::CU_STREAM_NON_BLOCKING: Specifies that work running in the created * stream may run concurrently with work in stream 0 (the NULL stream), and that * the created stream should perform no implicit synchronization with stream 0. * * \param phStream - Returned newly created stream * \param Flags - Parameters for stream creation * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY * \notefnerr * * \sa ::cuStreamDestroy, * ::cuStreamCreateWithPriority, * ::cuStreamGetPriority, * ::cuStreamGetFlags, * ::cuStreamWaitEvent, * ::cuStreamQuery, * ::cuStreamSynchronize, * ::cuStreamAddCallback, * ::cudaStreamCreate, * ::cudaStreamCreateWithFlags */ CUresult CUDAAPI cuStreamCreate(CUstream *phStream, unsigned int Flags); /** * \brief Create a stream with the given priority * * Creates a stream with the specified priority and returns a handle in \p phStream. * This API alters the scheduler priority of work in the stream. Work in a higher * priority stream may preempt work already executing in a low priority stream. * * \p priority follows a convention where lower numbers represent higher priorities. * '0' represents default priority. The range of meaningful numerical priorities can * be queried using ::cuCtxGetStreamPriorityRange. If the specified priority is * outside the numerical range returned by ::cuCtxGetStreamPriorityRange, * it will automatically be clamped to the lowest or the highest number in the range. * * \param phStream - Returned newly created stream * \param flags - Flags for stream creation. See ::cuStreamCreate for a list of * valid flags * \param priority - Stream priority. Lower numbers represent higher priorities. * See ::cuCtxGetStreamPriorityRange for more information about * meaningful stream priorities that can be passed. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY * \notefnerr * * \note Stream priorities are supported only on GPUs * with compute capability 3.5 or higher. * * \note In the current implementation, only compute kernels launched in * priority streams are affected by the stream's priority. Stream priorities have * no effect on host-to-device and device-to-host memory operations. * * \sa ::cuStreamDestroy, * ::cuStreamCreate, * ::cuStreamGetPriority, * ::cuCtxGetStreamPriorityRange, * ::cuStreamGetFlags, * ::cuStreamWaitEvent, * ::cuStreamQuery, * ::cuStreamSynchronize, * ::cuStreamAddCallback, * ::cudaStreamCreateWithPriority */ CUresult CUDAAPI cuStreamCreateWithPriority(CUstream *phStream, unsigned int flags, int priority); /** * \brief Query the priority of a given stream * * Query the priority of a stream created using ::cuStreamCreate or ::cuStreamCreateWithPriority * and return the priority in \p priority. Note that if the stream was created with a * priority outside the numerical range returned by ::cuCtxGetStreamPriorityRange, * this function returns the clamped priority. * See ::cuStreamCreateWithPriority for details about priority clamping. * * \param hStream - Handle to the stream to be queried * \param priority - Pointer to a signed integer in which the stream's priority is returned * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_OUT_OF_MEMORY * \notefnerr * * \sa ::cuStreamDestroy, * ::cuStreamCreate, * ::cuStreamCreateWithPriority, * ::cuCtxGetStreamPriorityRange, * ::cuStreamGetFlags, * ::cudaStreamGetPriority */ CUresult CUDAAPI cuStreamGetPriority(CUstream hStream, int *priority); /** * \brief Query the flags of a given stream * * Query the flags of a stream created using ::cuStreamCreate or ::cuStreamCreateWithPriority * and return the flags in \p flags. * * \param hStream - Handle to the stream to be queried * \param flags - Pointer to an unsigned integer in which the stream's flags are returned * The value returned in \p flags is a logical 'OR' of all flags that * were used while creating this stream. See ::cuStreamCreate for the list * of valid flags * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_OUT_OF_MEMORY * \notefnerr * * \sa ::cuStreamDestroy, * ::cuStreamCreate, * ::cuStreamGetPriority, * ::cudaStreamGetFlags */ CUresult CUDAAPI cuStreamGetFlags(CUstream hStream, unsigned int *flags); /** * \brief Query the context associated with a stream * * Returns the CUDA context that the stream is associated with. * * The stream handle \p hStream can refer to any of the following: * <ul> * <li>a stream created via any of the CUDA driver APIs such as ::cuStreamCreate * and ::cuStreamCreateWithPriority, or their runtime API equivalents such as * ::cudaStreamCreate, ::cudaStreamCreateWithFlags and ::cudaStreamCreateWithPriority. * The returned context is the context that was active in the calling thread when the * stream was created. Passing an invalid handle will result in undefined behavior.</li> * <li>any of the special streams such as the NULL stream, ::CU_STREAM_LEGACY and * ::CU_STREAM_PER_THREAD. The runtime API equivalents of these are also accepted, * which are NULL, ::cudaStreamLegacy and ::cudaStreamPerThread respectively. * Specifying any of the special handles will return the context current to the * calling thread. If no context is current to the calling thread, * ::CUDA_ERROR_INVALID_CONTEXT is returned.</li> * </ul> * * \param hStream - Handle to the stream to be queried * \param pctx - Returned context associated with the stream * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * \notefnerr * * \sa ::cuStreamDestroy, * ::cuStreamCreateWithPriority, * ::cuStreamGetPriority, * ::cuStreamGetFlags, * ::cuStreamWaitEvent, * ::cuStreamQuery, * ::cuStreamSynchronize, * ::cuStreamAddCallback, * ::cudaStreamCreate, * ::cudaStreamCreateWithFlags */ CUresult CUDAAPI cuStreamGetCtx(CUstream hStream, CUcontext *pctx); /** * \brief Make a compute stream wait on an event * * Makes all future work submitted to \p hStream wait for all work captured in * \p hEvent. See ::cuEventRecord() for details on what is captured by an event. * The synchronization will be performed efficiently on the device when applicable. * \p hEvent may be from a different context or device than \p hStream. * * flags include: * - ::CU_EVENT_WAIT_DEFAULT: Default event creation flag. * - ::CU_EVENT_WAIT_EXTERNAL: Event is captured in the graph as an external * event node when performing stream capture. This flag is invalid outside * of stream capture. * * \param hStream - Stream to wait * \param hEvent - Event to wait on (may not be NULL) * \param Flags - See ::CUevent_capture_flags * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * \note_null_stream * \notefnerr * * \sa ::cuStreamCreate, * ::cuEventRecord, * ::cuStreamQuery, * ::cuStreamSynchronize, * ::cuStreamAddCallback, * ::cuStreamDestroy, * ::cudaStreamWaitEvent */ CUresult CUDAAPI cuStreamWaitEvent(CUstream hStream, CUevent hEvent, unsigned int Flags); /** * \brief Add a callback to a compute stream * * \note This function is slated for eventual deprecation and removal. If * you do not require the callback to execute in case of a device error, * consider using ::cuLaunchHostFunc. Additionally, this function is not * supported with ::cuStreamBeginCapture and ::cuStreamEndCapture, unlike * ::cuLaunchHostFunc. * * Adds a callback to be called on the host after all currently enqueued * items in the stream have completed. For each * cuStreamAddCallback call, the callback will be executed exactly once. * The callback will block later work in the stream until it is finished. * * The callback may be passed ::CUDA_SUCCESS or an error code. In the event * of a device error, all subsequently executed callbacks will receive an * appropriate ::CUresult. * * Callbacks must not make any CUDA API calls. Attempting to use a CUDA API * will result in ::CUDA_ERROR_NOT_PERMITTED. Callbacks must not perform any * synchronization that may depend on outstanding device work or other callbacks * that are not mandated to run earlier. Callbacks without a mandated order * (in independent streams) execute in undefined order and may be serialized. * * For the purposes of Unified Memory, callback execution makes a number of * guarantees: * <ul> * <li>The callback stream is considered idle for the duration of the * callback. Thus, for example, a callback may always use memory attached * to the callback stream.</li> * <li>The start of execution of a callback has the same effect as * synchronizing an event recorded in the same stream immediately prior to * the callback. It thus synchronizes streams which have been "joined" * prior to the callback.</li> * <li>Adding device work to any stream does not have the effect of making * the stream active until all preceding host functions and stream callbacks * have executed. Thus, for * example, a callback might use global attached memory even if work has * been added to another stream, if the work has been ordered behind the * callback with an event.</li> * <li>Completion of a callback does not cause a stream to become * active except as described above. The callback stream will remain idle * if no device work follows the callback, and will remain idle across * consecutive callbacks without device work in between. Thus, for example, * stream synchronization can be done by signaling from a callback at the * end of the stream.</li> * </ul> * * \param hStream - Stream to add callback to * \param callback - The function to call once preceding stream operations are complete * \param userData - User specified data to be passed to the callback function * \param flags - Reserved for future use, must be 0 * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_SUPPORTED * \note_null_stream * \notefnerr * * \sa ::cuStreamCreate, * ::cuStreamQuery, * ::cuStreamSynchronize, * ::cuStreamWaitEvent, * ::cuStreamDestroy, * ::cuMemAllocManaged, * ::cuStreamAttachMemAsync, * ::cuStreamLaunchHostFunc, * ::cudaStreamAddCallback */ CUresult CUDAAPI cuStreamAddCallback(CUstream hStream, CUstreamCallback callback, void *userData, unsigned int flags); /** * \brief Begins graph capture on a stream * * Begin graph capture on \p hStream. When a stream is in capture mode, all operations * pushed into the stream will not be executed, but will instead be captured into * a graph, which will be returned via ::cuStreamEndCapture. Capture may not be initiated * if \p stream is CU_STREAM_LEGACY. Capture must be ended on the same stream in which * it was initiated, and it may only be initiated if the stream is not already in capture * mode. The capture mode may be queried via ::cuStreamIsCapturing. A unique id * representing the capture sequence may be queried via ::cuStreamGetCaptureInfo. * * If \p mode is not ::CU_STREAM_CAPTURE_MODE_RELAXED, ::cuStreamEndCapture must be * called on this stream from the same thread. * * \param hStream - Stream in which to initiate capture * \param mode - Controls the interaction of this capture sequence with other API * calls that are potentially unsafe. For more details see * ::cuThreadExchangeStreamCaptureMode. * * \note Kernels captured using this API must not use texture and surface references. * Reading or writing through any texture or surface reference is undefined * behavior. This restriction does not apply to texture and surface objects. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa * ::cuStreamCreate, * ::cuStreamIsCapturing, * ::cuStreamEndCapture, * ::cuThreadExchangeStreamCaptureMode */ CUresult CUDAAPI cuStreamBeginCapture(CUstream hStream, CUstreamCaptureMode mode); /** * \brief Swaps the stream capture interaction mode for a thread * * Sets the calling thread's stream capture interaction mode to the value contained * in \p *mode, and overwrites \p *mode with the previous mode for the thread. To * facilitate deterministic behavior across function or module boundaries, callers * are encouraged to use this API in a push-pop fashion: \code CUstreamCaptureMode mode = desiredMode; cuThreadExchangeStreamCaptureMode(&mode); ... cuThreadExchangeStreamCaptureMode(&mode); // restore previous mode * \endcode * * During stream capture (see ::cuStreamBeginCapture), some actions, such as a call * to ::cudaMalloc, may be unsafe. In the case of ::cudaMalloc, the operation is * not enqueued asynchronously to a stream, and is not observed by stream capture. * Therefore, if the sequence of operations captured via ::cuStreamBeginCapture * depended on the allocation being replayed whenever the graph is launched, the * captured graph would be invalid. * * Therefore, stream capture places restrictions on API calls that can be made within * or concurrently to a ::cuStreamBeginCapture-::cuStreamEndCapture sequence. This * behavior can be controlled via this API and flags to ::cuStreamBeginCapture. * * A thread's mode is one of the following: * - \p CU_STREAM_CAPTURE_MODE_GLOBAL: This is the default mode. If the local thread has * an ongoing capture sequence that was not initiated with * \p CU_STREAM_CAPTURE_MODE_RELAXED at \p cuStreamBeginCapture, or if any other thread * has a concurrent capture sequence initiated with \p CU_STREAM_CAPTURE_MODE_GLOBAL, * this thread is prohibited from potentially unsafe API calls. * - \p CU_STREAM_CAPTURE_MODE_THREAD_LOCAL: If the local thread has an ongoing capture * sequence not initiated with \p CU_STREAM_CAPTURE_MODE_RELAXED, it is prohibited * from potentially unsafe API calls. Concurrent capture sequences in other threads * are ignored. * - \p CU_STREAM_CAPTURE_MODE_RELAXED: The local thread is not prohibited from potentially * unsafe API calls. Note that the thread is still prohibited from API calls which * necessarily conflict with stream capture, for example, attempting ::cuEventQuery * on an event that was last recorded inside a capture sequence. * * \param mode - Pointer to mode value to swap with the current mode * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa * ::cuStreamBeginCapture */ CUresult CUDAAPI cuThreadExchangeStreamCaptureMode(CUstreamCaptureMode *mode); /** * \brief Ends capture on a stream, returning the captured graph * * End capture on \p hStream, returning the captured graph via \p phGraph. * Capture must have been initiated on \p hStream via a call to ::cuStreamBeginCapture. * If capture was invalidated, due to a violation of the rules of stream capture, then * a NULL graph will be returned. * * If the \p mode argument to ::cuStreamBeginCapture was not * ::CU_STREAM_CAPTURE_MODE_RELAXED, this call must be from the same thread as * ::cuStreamBeginCapture. * * \param hStream - Stream to query * \param phGraph - The captured graph * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD * \notefnerr * * \sa * ::cuStreamCreate, * ::cuStreamBeginCapture, * ::cuStreamIsCapturing */ CUresult CUDAAPI cuStreamEndCapture(CUstream hStream, CUgraph *phGraph); /** * \brief Returns a stream's capture status * * Return the capture status of \p hStream via \p captureStatus. After a successful * call, \p *captureStatus will contain one of the following: * - ::CU_STREAM_CAPTURE_STATUS_NONE: The stream is not capturing. * - ::CU_STREAM_CAPTURE_STATUS_ACTIVE: The stream is capturing. * - ::CU_STREAM_CAPTURE_STATUS_INVALIDATED: The stream was capturing but an error * has invalidated the capture sequence. The capture sequence must be terminated * with ::cuStreamEndCapture on the stream where it was initiated in order to * continue using \p hStream. * * Note that, if this is called on ::CU_STREAM_LEGACY (the "null stream") while * a blocking stream in the same context is capturing, it will return * ::CUDA_ERROR_STREAM_CAPTURE_IMPLICIT and \p *captureStatus is unspecified * after the call. The blocking stream capture is not invalidated. * * When a blocking stream is capturing, the legacy stream is in an * unusable state until the blocking stream capture is terminated. The legacy * stream is not supported for stream capture, but attempted use would have an * implicit dependency on the capturing stream(s). * * \param hStream - Stream to query * \param captureStatus - Returns the stream's capture status * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_STREAM_CAPTURE_IMPLICIT * \notefnerr * * \sa * ::cuStreamCreate, * ::cuStreamBeginCapture, * ::cuStreamEndCapture */ CUresult CUDAAPI cuStreamIsCapturing(CUstream hStream, CUstreamCaptureStatus *captureStatus); /** * \brief Query capture status of a stream * * Note there is a later version of this API, ::cuStreamGetCaptureInfo_v2. It will * supplant this version in 12.0, which is retained for minor version compatibility. * * Query the capture status of a stream and and get an id for * the capture sequence, which is unique over the lifetime of the process. * * If called on ::CU_STREAM_LEGACY (the "null stream") while a stream not created * with ::CU_STREAM_NON_BLOCKING is capturing, returns ::CUDA_ERROR_STREAM_CAPTURE_IMPLICIT. * * A valid id is returned only if both of the following are true: * - the call returns CUDA_SUCCESS * - captureStatus is set to ::CU_STREAM_CAPTURE_STATUS_ACTIVE * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_STREAM_CAPTURE_IMPLICIT * \notefnerr * * \sa * ::cuStreamGetCaptureInfo_v2, * ::cuStreamBeginCapture, * ::cuStreamIsCapturing */ CUresult CUDAAPI cuStreamGetCaptureInfo(CUstream hStream, CUstreamCaptureStatus *captureStatus_out, cuuint64_t *id_out); /** * \brief Query a stream's capture state (11.3+) * * Query stream state related to stream capture. * * If called on ::CU_STREAM_LEGACY (the "null stream") while a stream not created * with ::CU_STREAM_NON_BLOCKING is capturing, returns ::CUDA_ERROR_STREAM_CAPTURE_IMPLICIT. * * Valid data (other than capture status) is returned only if both of the following are true: * - the call returns CUDA_SUCCESS * - the returned capture status is ::CU_STREAM_CAPTURE_STATUS_ACTIVE * * This version of cuStreamGetCaptureInfo is introduced in CUDA 11.3 and will supplant the * previous version in 12.0. Developers requiring compatibility across minor versions to * CUDA 11.0 (driver version 445) should use ::cuStreamGetCaptureInfo or include a fallback * path. * * \param hStream - The stream to query * \param captureStatus_out - Location to return the capture status of the stream; required * \param id_out - Optional location to return an id for the capture sequence, which is * unique over the lifetime of the process * \param graph_out - Optional location to return the graph being captured into. All * operations other than destroy and node removal are permitted on the graph * while the capture sequence is in progress. This API does not transfer * ownership of the graph, which is transferred or destroyed at * ::cuStreamEndCapture. Note that the graph handle may be invalidated before * end of capture for certain errors. Nodes that are or become * unreachable from the original stream at ::cuStreamEndCapture due to direct * actions on the graph do not trigger ::CUDA_ERROR_STREAM_CAPTURE_UNJOINED. * \param dependencies_out - Optional location to store a pointer to an array of nodes. * The next node to be captured in the stream will depend on this set of nodes, * absent operations such as event wait which modify this set. The array pointer * is valid until the next API call which operates on the stream or until end of * capture. The node handles may be copied out and are valid until they or the * graph is destroyed. The driver-owned array may also be passed directly to * APIs that operate on the graph (not the stream) without copying. * \param numDependencies_out - Optional location to store the size of the array * returned in dependencies_out. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_STREAM_CAPTURE_IMPLICIT * \note_graph_thread_safety * \notefnerr * * \sa * ::cuStreamGetCaptureInfo, * ::cuStreamBeginCapture, * ::cuStreamIsCapturing, * ::cuStreamUpdateCaptureDependencies */ CUresult CUDAAPI cuStreamGetCaptureInfo_v2(CUstream hStream, CUstreamCaptureStatus *captureStatus_out, cuuint64_t *id_out, CUgraph *graph_out, const CUgraphNode **dependencies_out, size_t *numDependencies_out); /** * \brief Update the set of dependencies in a capturing stream (11.3+) * * Modifies the dependency set of a capturing stream. The dependency set is the set * of nodes that the next captured node in the stream will depend on. * * Valid flags are ::CU_STREAM_ADD_CAPTURE_DEPENDENCIES and * ::CU_STREAM_SET_CAPTURE_DEPENDENCIES. These control whether the set passed to * the API is added to the existing set or replaces it. A flags value of 0 defaults * to ::CU_STREAM_ADD_CAPTURE_DEPENDENCIES. * * Nodes that are removed from the dependency set via this API do not result in * ::CUDA_ERROR_STREAM_CAPTURE_UNJOINED if they are unreachable from the stream at * ::cuStreamEndCapture. * * Returns ::CUDA_ERROR_ILLEGAL_STATE if the stream is not capturing. * * This API is new in CUDA 11.3. Developers requiring compatibility across minor * versions to CUDA 11.0 should not use this API or provide a fallback. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_ILLEGAL_STATE * * \sa * ::cuStreamBeginCapture, * ::cuStreamGetCaptureInfo, * ::cuStreamGetCaptureInfo_v2 */ CUresult CUDAAPI cuStreamUpdateCaptureDependencies(CUstream hStream, CUgraphNode *dependencies, size_t numDependencies, unsigned int flags); /** * \brief Attach memory to a stream asynchronously * * Enqueues an operation in \p hStream to specify stream association of * \p length bytes of memory starting from \p dptr. This function is a * stream-ordered operation, meaning that it is dependent on, and will * only take effect when, previous work in stream has completed. Any * previous association is automatically replaced. * * \p dptr must point to one of the following types of memories: * - managed memory declared using the __managed__ keyword or allocated with * ::cuMemAllocManaged. * - a valid host-accessible region of system-allocated pageable memory. This * type of memory may only be specified if the device associated with the * stream reports a non-zero value for the device attribute * ::CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS. * * For managed allocations, \p length must be either zero or the entire * allocation's size. Both indicate that the entire allocation's stream * association is being changed. Currently, it is not possible to change stream * association for a portion of a managed allocation. * * For pageable host allocations, \p length must be non-zero. * * The stream association is specified using \p flags which must be * one of ::CUmemAttach_flags. * If the ::CU_MEM_ATTACH_GLOBAL flag is specified, the memory can be accessed * by any stream on any device. * If the ::CU_MEM_ATTACH_HOST flag is specified, the program makes a guarantee * that it won't access the memory on the device from any stream on a device that * has a zero value for the device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. * If the ::CU_MEM_ATTACH_SINGLE flag is specified and \p hStream is associated with * a device that has a zero value for the device attribute ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, * the program makes a guarantee that it will only access the memory on the device * from \p hStream. It is illegal to attach singly to the NULL stream, because the * NULL stream is a virtual global stream and not a specific stream. An error will * be returned in this case. * * When memory is associated with a single stream, the Unified Memory system will * allow CPU access to this memory region so long as all operations in \p hStream * have completed, regardless of whether other streams are active. In effect, * this constrains exclusive ownership of the managed memory region by * an active GPU to per-stream activity instead of whole-GPU activity. * * Accessing memory on the device from streams that are not associated with * it will produce undefined results. No error checking is performed by the * Unified Memory system to ensure that kernels launched into other streams * do not access this region. * * It is a program's responsibility to order calls to ::cuStreamAttachMemAsync * via events, synchronization or other means to ensure legal access to memory * at all times. Data visibility and coherency will be changed appropriately * for all kernels which follow a stream-association change. * * If \p hStream is destroyed while data is associated with it, the association is * removed and the association reverts to the default visibility of the allocation * as specified at ::cuMemAllocManaged. For __managed__ variables, the default * association is always ::CU_MEM_ATTACH_GLOBAL. Note that destroying a stream is an * asynchronous operation, and as a result, the change to default association won't * happen until all work in the stream has completed. * * \param hStream - Stream in which to enqueue the attach operation * \param dptr - Pointer to memory (must be a pointer to managed memory or * to a valid host-accessible region of system-allocated * pageable memory) * \param length - Length of memory * \param flags - Must be one of ::CUmemAttach_flags * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_SUPPORTED * \note_null_stream * \notefnerr * * \sa ::cuStreamCreate, * ::cuStreamQuery, * ::cuStreamSynchronize, * ::cuStreamWaitEvent, * ::cuStreamDestroy, * ::cuMemAllocManaged, * ::cudaStreamAttachMemAsync */ CUresult CUDAAPI cuStreamAttachMemAsync(CUstream hStream, CUdeviceptr dptr, size_t length, unsigned int flags); /** * \brief Determine status of a compute stream * * Returns ::CUDA_SUCCESS if all operations in the stream specified by * \p hStream have completed, or ::CUDA_ERROR_NOT_READY if not. * * For the purposes of Unified Memory, a return value of ::CUDA_SUCCESS * is equivalent to having called ::cuStreamSynchronize(). * * \param hStream - Stream to query status of * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_READY * \note_null_stream * \notefnerr * * \sa ::cuStreamCreate, * ::cuStreamWaitEvent, * ::cuStreamDestroy, * ::cuStreamSynchronize, * ::cuStreamAddCallback, * ::cudaStreamQuery */ CUresult CUDAAPI cuStreamQuery(CUstream hStream); /** * \brief Wait until a stream's tasks are completed * * Waits until the device has completed all operations in the stream specified * by \p hStream. If the context was created with the * ::CU_CTX_SCHED_BLOCKING_SYNC flag, the CPU thread will block until the * stream is finished with all of its tasks. * * \param hStream - Stream to wait for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE * \note_null_stream * \notefnerr * * \sa ::cuStreamCreate, * ::cuStreamDestroy, * ::cuStreamWaitEvent, * ::cuStreamQuery, * ::cuStreamAddCallback, * ::cudaStreamSynchronize */ CUresult CUDAAPI cuStreamSynchronize(CUstream hStream); /** * \brief Destroys a stream * * Destroys the stream specified by \p hStream. * * In case the device is still doing work in the stream \p hStream * when ::cuStreamDestroy() is called, the function will return immediately * and the resources associated with \p hStream will be released automatically * once the device has completed all work in \p hStream. * * \param hStream - Stream to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa ::cuStreamCreate, * ::cuStreamWaitEvent, * ::cuStreamQuery, * ::cuStreamSynchronize, * ::cuStreamAddCallback, * ::cudaStreamDestroy */ CUresult CUDAAPI cuStreamDestroy(CUstream hStream); /** * \brief Copies attributes from source stream to destination stream. * * Copies attributes from source stream \p src to destination stream \p dst. * Both streams must have the same context. * * \param[out] dst Destination stream * \param[in] src Source stream * For list of attributes see ::CUstreamAttrID * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa * ::CUaccessPolicyWindow */ CUresult CUDAAPI cuStreamCopyAttributes(CUstream dst, CUstream src); /** * \brief Queries stream attribute. * * Queries attribute \p attr from \p hStream and stores it in corresponding * member of \p value_out. * * \param[in] hStream * \param[in] attr * \param[out] value_out * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa * ::CUaccessPolicyWindow */ CUresult CUDAAPI cuStreamGetAttribute(CUstream hStream, CUstreamAttrID attr, CUstreamAttrValue *value_out); /** * \brief Sets stream attribute. * * Sets attribute \p attr on \p hStream from corresponding attribute of * \p value. The updated attribute will be applied to subsequent work * submitted to the stream. It will not affect previously submitted work. * * \param[out] hStream * \param[in] attr * \param[in] value * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa * ::CUaccessPolicyWindow */ CUresult CUDAAPI cuStreamSetAttribute(CUstream hStream, CUstreamAttrID attr, const CUstreamAttrValue *value); /** @} */ /* END CUDA_STREAM */ /** * \defgroup CUDA_EVENT Event Management * * ___MANBRIEF___ event management functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the event management functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Creates an event * * Creates an event *phEvent for the current context with the flags specified via * \p Flags. Valid flags include: * - ::CU_EVENT_DEFAULT: Default event creation flag. * - ::CU_EVENT_BLOCKING_SYNC: Specifies that the created event should use blocking * synchronization. A CPU thread that uses ::cuEventSynchronize() to wait on * an event created with this flag will block until the event has actually * been recorded. * - ::CU_EVENT_DISABLE_TIMING: Specifies that the created event does not need * to record timing data. Events created with this flag specified and * the ::CU_EVENT_BLOCKING_SYNC flag not specified will provide the best * performance when used with ::cuStreamWaitEvent() and ::cuEventQuery(). * - ::CU_EVENT_INTERPROCESS: Specifies that the created event may be used as an * interprocess event by ::cuIpcGetEventHandle(). ::CU_EVENT_INTERPROCESS must * be specified along with ::CU_EVENT_DISABLE_TIMING. * * \param phEvent - Returns newly created event * \param Flags - Event creation flags * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY * \notefnerr * * \sa * ::cuEventRecord, * ::cuEventQuery, * ::cuEventSynchronize, * ::cuEventDestroy, * ::cuEventElapsedTime, * ::cudaEventCreate, * ::cudaEventCreateWithFlags */ CUresult CUDAAPI cuEventCreate(CUevent *phEvent, unsigned int Flags); /** * \brief Records an event * * Captures in \p hEvent the contents of \p hStream at the time of this call. * \p hEvent and \p hStream must be from the same context. * Calls such as ::cuEventQuery() or ::cuStreamWaitEvent() will then * examine or wait for completion of the work that was captured. Uses of * \p hStream after this call do not modify \p hEvent. See note on default * stream behavior for what is captured in the default case. * * ::cuEventRecord() can be called multiple times on the same event and * will overwrite the previously captured state. Other APIs such as * ::cuStreamWaitEvent() use the most recently captured state at the time * of the API call, and are not affected by later calls to * ::cuEventRecord(). Before the first call to ::cuEventRecord(), an * event represents an empty set of work, so for example ::cuEventQuery() * would return ::CUDA_SUCCESS. * * \param hEvent - Event to record * \param hStream - Stream to record event for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE * \note_null_stream * \notefnerr * * \sa ::cuEventCreate, * ::cuEventQuery, * ::cuEventSynchronize, * ::cuStreamWaitEvent, * ::cuEventDestroy, * ::cuEventElapsedTime, * ::cudaEventRecord, * ::cuEventRecordWithFlags */ CUresult CUDAAPI cuEventRecord(CUevent hEvent, CUstream hStream); /** * \brief Records an event * * Captures in \p hEvent the contents of \p hStream at the time of this call. * \p hEvent and \p hStream must be from the same context. * Calls such as ::cuEventQuery() or ::cuStreamWaitEvent() will then * examine or wait for completion of the work that was captured. Uses of * \p hStream after this call do not modify \p hEvent. See note on default * stream behavior for what is captured in the default case. * * ::cuEventRecordWithFlags() can be called multiple times on the same event and * will overwrite the previously captured state. Other APIs such as * ::cuStreamWaitEvent() use the most recently captured state at the time * of the API call, and are not affected by later calls to * ::cuEventRecordWithFlags(). Before the first call to ::cuEventRecordWithFlags(), an * event represents an empty set of work, so for example ::cuEventQuery() * would return ::CUDA_SUCCESS. * * flags include: * - ::CU_EVENT_RECORD_DEFAULT: Default event creation flag. * - ::CU_EVENT_RECORD_EXTERNAL: Event is captured in the graph as an external * event node when performing stream capture. This flag is invalid outside * of stream capture. * * \param hEvent - Event to record * \param hStream - Stream to record event for * \param flags - See ::CUevent_capture_flags * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE * \note_null_stream * \notefnerr * * \sa ::cuEventCreate, * ::cuEventQuery, * ::cuEventSynchronize, * ::cuStreamWaitEvent, * ::cuEventDestroy, * ::cuEventElapsedTime, * ::cuEventRecord, * ::cudaEventRecord */ CUresult CUDAAPI cuEventRecordWithFlags(CUevent hEvent, CUstream hStream, unsigned int flags); /** * \brief Queries an event's status * * Queries the status of all work currently captured by \p hEvent. See * ::cuEventRecord() for details on what is captured by an event. * * Returns ::CUDA_SUCCESS if all captured work has been completed, or * ::CUDA_ERROR_NOT_READY if any captured work is incomplete. * * For the purposes of Unified Memory, a return value of ::CUDA_SUCCESS * is equivalent to having called ::cuEventSynchronize(). * * \param hEvent - Event to query * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_READY * \notefnerr * * \sa ::cuEventCreate, * ::cuEventRecord, * ::cuEventSynchronize, * ::cuEventDestroy, * ::cuEventElapsedTime, * ::cudaEventQuery */ CUresult CUDAAPI cuEventQuery(CUevent hEvent); /** * \brief Waits for an event to complete * * Waits until the completion of all work currently captured in \p hEvent. * See ::cuEventRecord() for details on what is captured by an event. * * Waiting for an event that was created with the ::CU_EVENT_BLOCKING_SYNC * flag will cause the calling CPU thread to block until the event has * been completed by the device. If the ::CU_EVENT_BLOCKING_SYNC flag has * not been set, then the CPU thread will busy-wait until the event has * been completed by the device. * * \param hEvent - Event to wait for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa ::cuEventCreate, * ::cuEventRecord, * ::cuEventQuery, * ::cuEventDestroy, * ::cuEventElapsedTime, * ::cudaEventSynchronize */ CUresult CUDAAPI cuEventSynchronize(CUevent hEvent); /** * \brief Destroys an event * * Destroys the event specified by \p hEvent. * * An event may be destroyed before it is complete (i.e., while * ::cuEventQuery() would return ::CUDA_ERROR_NOT_READY). In this case, the * call does not block on completion of the event, and any associated * resources will automatically be released asynchronously at completion. * * \param hEvent - Event to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa ::cuEventCreate, * ::cuEventRecord, * ::cuEventQuery, * ::cuEventSynchronize, * ::cuEventElapsedTime, * ::cudaEventDestroy */ CUresult CUDAAPI cuEventDestroy(CUevent hEvent); /** * \brief Computes the elapsed time between two events * * Computes the elapsed time between two events (in milliseconds with a * resolution of around 0.5 microseconds). * * If either event was last recorded in a non-NULL stream, the resulting time * may be greater than expected (even if both used the same stream handle). This * happens because the ::cuEventRecord() operation takes place asynchronously * and there is no guarantee that the measured latency is actually just between * the two events. Any number of other different stream operations could execute * in between the two measured events, thus altering the timing in a significant * way. * * If ::cuEventRecord() has not been called on either event then * ::CUDA_ERROR_INVALID_HANDLE is returned. If ::cuEventRecord() has been called * on both events but one or both of them has not yet been completed (that is, * ::cuEventQuery() would return ::CUDA_ERROR_NOT_READY on at least one of the * events), ::CUDA_ERROR_NOT_READY is returned. If either event was created with * the ::CU_EVENT_DISABLE_TIMING flag, then this function will return * ::CUDA_ERROR_INVALID_HANDLE. * * \param pMilliseconds - Time between \p hStart and \p hEnd in ms * \param hStart - Starting event * \param hEnd - Ending event * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_READY * \notefnerr * * \sa ::cuEventCreate, * ::cuEventRecord, * ::cuEventQuery, * ::cuEventSynchronize, * ::cuEventDestroy, * ::cudaEventElapsedTime */ CUresult CUDAAPI cuEventElapsedTime(float *pMilliseconds, CUevent hStart, CUevent hEnd); /** @} */ /* END CUDA_EVENT */ /** * \defgroup CUDA_EXTRES_INTEROP External Resource Interoperability * * ___MANBRIEF___ External resource interoperability functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the external resource interoperability functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Imports an external memory object * * Imports an externally allocated memory object and returns * a handle to that in \p extMem_out. * * The properties of the handle being imported must be described in * \p memHandleDesc. The ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC structure * is defined as follows: * * \code typedef struct CUDA_EXTERNAL_MEMORY_HANDLE_DESC_st { CUexternalMemoryHandleType type; union { int fd; struct { void *handle; const void *name; } win32; const void *nvSciBufObject; } handle; unsigned long long size; unsigned int flags; } CUDA_EXTERNAL_MEMORY_HANDLE_DESC; * \endcode * * where ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type specifies the type * of handle being imported. ::CUexternalMemoryHandleType is * defined as: * * \code typedef enum CUexternalMemoryHandleType_enum { CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD = 1, CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32 = 2, CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT = 3, CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP = 4, CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE = 5, CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE = 6, CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT = 7, CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF = 8 } CUexternalMemoryHandleType; * \endcode * * If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD, then * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::fd must be a valid * file descriptor referencing a memory object. Ownership of * the file descriptor is transferred to the CUDA driver when the * handle is imported successfully. Performing any operations on the * file descriptor after it is imported results in undefined behavior. * * If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32, then exactly one * of ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle and * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name must not be * NULL. If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle * is not NULL, then it must represent a valid shared NT handle that * references a memory object. Ownership of this handle is * not transferred to CUDA after the import operation, so the * application must release the handle using the appropriate system * call. If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name * is not NULL, then it must point to a NULL-terminated array of * UTF-16 characters that refers to a memory object. * * If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT, then * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle must * be non-NULL and * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name * must be NULL. The handle specified must be a globally shared KMT * handle. This handle does not hold a reference to the underlying * object, and thus will be invalid when all references to the * memory object are destroyed. * * If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP, then exactly one * of ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle and * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name must not be * NULL. If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle * is not NULL, then it must represent a valid shared NT handle that * is returned by ID3D12Device::CreateSharedHandle when referring to a * ID3D12Heap object. This handle holds a reference to the underlying * object. If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name * is not NULL, then it must point to a NULL-terminated array of * UTF-16 characters that refers to a ID3D12Heap object. * * If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE, then exactly one * of ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle and * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name must not be * NULL. If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle * is not NULL, then it must represent a valid shared NT handle that * is returned by ID3D12Device::CreateSharedHandle when referring to a * ID3D12Resource object. This handle holds a reference to the * underlying object. If * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name * is not NULL, then it must point to a NULL-terminated array of * UTF-16 characters that refers to a ID3D12Resource object. * * If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE, then * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle must * represent a valid shared NT handle that is returned by * IDXGIResource1::CreateSharedHandle when referring to a * ID3D11Resource object. If * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name * is not NULL, then it must point to a NULL-terminated array of * UTF-16 characters that refers to a ID3D11Resource object. * * If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT, then * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::handle must * represent a valid shared KMT handle that is returned by * IDXGIResource::GetSharedHandle when referring to a * ID3D11Resource object and * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::win32::name * must be NULL. * * If ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type is * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF, then * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::handle::nvSciBufObject must be non-NULL * and reference a valid NvSciBuf object. * If the NvSciBuf object imported into CUDA is also mapped by other drivers, then the * application must use ::cuWaitExternalSemaphoresAsync or ::cuSignalExternalSemaphoresAsync * as appropriate barriers to maintain coherence between CUDA and the other drivers. * See ::CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC and ::CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC * for memory synchronization. * * * The size of the memory object must be specified in * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::size. * * Specifying the flag ::CUDA_EXTERNAL_MEMORY_DEDICATED in * ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::flags indicates that the * resource is a dedicated resource. The definition of what a * dedicated resource is outside the scope of this extension. * This flag must be set if ::CUDA_EXTERNAL_MEMORY_HANDLE_DESC::type * is one of the following: * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_RESOURCE_KMT * * \param extMem_out - Returned handle to an external memory object * \param memHandleDesc - Memory import handle descriptor * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \note If the Vulkan memory imported into CUDA is mapped on the CPU then the * application must use vkInvalidateMappedMemoryRanges/vkFlushMappedMemoryRanges * as well as appropriate Vulkan pipeline barriers to maintain coherence between * CPU and GPU. For more information on these APIs, please refer to "Synchronization * and Cache Control" chapter from Vulkan specification. * * \sa ::cuDestroyExternalMemory, * ::cuExternalMemoryGetMappedBuffer, * ::cuExternalMemoryGetMappedMipmappedArray */ CUresult CUDAAPI cuImportExternalMemory(CUexternalMemory *extMem_out, const CUDA_EXTERNAL_MEMORY_HANDLE_DESC *memHandleDesc); /** * \brief Maps a buffer onto an imported memory object * * Maps a buffer onto an imported memory object and returns a device * pointer in \p devPtr. * * The properties of the buffer being mapped must be described in * \p bufferDesc. The ::CUDA_EXTERNAL_MEMORY_BUFFER_DESC structure is * defined as follows: * * \code typedef struct CUDA_EXTERNAL_MEMORY_BUFFER_DESC_st { unsigned long long offset; unsigned long long size; unsigned int flags; } CUDA_EXTERNAL_MEMORY_BUFFER_DESC; * \endcode * * where ::CUDA_EXTERNAL_MEMORY_BUFFER_DESC::offset is the offset in * the memory object where the buffer's base address is. * ::CUDA_EXTERNAL_MEMORY_BUFFER_DESC::size is the size of the buffer. * ::CUDA_EXTERNAL_MEMORY_BUFFER_DESC::flags must be zero. * * The offset and size have to be suitably aligned to match the * requirements of the external API. Mapping two buffers whose ranges * overlap may or may not result in the same virtual address being * returned for the overlapped portion. In such cases, the application * must ensure that all accesses to that region from the GPU are * volatile. Otherwise writes made via one address are not guaranteed * to be visible via the other address, even if they're issued by the * same thread. It is recommended that applications map the combined * range instead of mapping separate buffers and then apply the * appropriate offsets to the returned pointer to derive the * individual buffers. * * The returned pointer \p devPtr must be freed using ::cuMemFree. * * \param devPtr - Returned device pointer to buffer * \param extMem - Handle to external memory object * \param bufferDesc - Buffer descriptor * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa ::cuImportExternalMemory, * ::cuDestroyExternalMemory, * ::cuExternalMemoryGetMappedMipmappedArray */ CUresult CUDAAPI cuExternalMemoryGetMappedBuffer(CUdeviceptr *devPtr, CUexternalMemory extMem, const CUDA_EXTERNAL_MEMORY_BUFFER_DESC *bufferDesc); /** * \brief Maps a CUDA mipmapped array onto an external memory object * * Maps a CUDA mipmapped array onto an external object and returns a * handle to it in \p mipmap. * * The properties of the CUDA mipmapped array being mapped must be * described in \p mipmapDesc. The structure * ::CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC is defined as follows: * * \code typedef struct CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC_st { unsigned long long offset; CUDA_ARRAY3D_DESCRIPTOR arrayDesc; unsigned int numLevels; } CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC; * \endcode * * where ::CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC::offset is the * offset in the memory object where the base level of the mipmap * chain is. * ::CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC::arrayDesc describes * the format, dimensions and type of the base level of the mipmap * chain. For further details on these parameters, please refer to the * documentation for ::cuMipmappedArrayCreate. Note that if the mipmapped * array is bound as a color target in the graphics API, then the flag * ::CUDA_ARRAY3D_COLOR_ATTACHMENT must be specified in * ::CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC::arrayDesc::Flags. * ::CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC::numLevels specifies * the total number of levels in the mipmap chain. * * If \p extMem was imported from a handle of type ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF, then * ::CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC::numLevels must be equal to 1. * * The returned CUDA mipmapped array must be freed using ::cuMipmappedArrayDestroy. * * \param mipmap - Returned CUDA mipmapped array * \param extMem - Handle to external memory object * \param mipmapDesc - CUDA array descriptor * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa ::cuImportExternalMemory, * ::cuDestroyExternalMemory, * ::cuExternalMemoryGetMappedBuffer */ CUresult CUDAAPI cuExternalMemoryGetMappedMipmappedArray(CUmipmappedArray *mipmap, CUexternalMemory extMem, const CUDA_EXTERNAL_MEMORY_MIPMAPPED_ARRAY_DESC *mipmapDesc); /** * \brief Destroys an external memory object. * * Destroys the specified external memory object. Any existing buffers * and CUDA mipmapped arrays mapped onto this object must no longer be * used and must be explicitly freed using ::cuMemFree and * ::cuMipmappedArrayDestroy respectively. * * \param extMem - External memory object to be destroyed * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa ::cuImportExternalMemory, * ::cuExternalMemoryGetMappedBuffer, * ::cuExternalMemoryGetMappedMipmappedArray */ CUresult CUDAAPI cuDestroyExternalMemory(CUexternalMemory extMem); /** * \brief Imports an external semaphore * * Imports an externally allocated synchronization object and returns * a handle to that in \p extSem_out. * * The properties of the handle being imported must be described in * \p semHandleDesc. The ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC is * defined as follows: * * \code typedef struct CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC_st { CUexternalSemaphoreHandleType type; union { int fd; struct { void *handle; const void *name; } win32; const void* NvSciSyncObj; } handle; unsigned int flags; } CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC; * \endcode * * where ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type specifies the type of * handle being imported. ::CUexternalSemaphoreHandleType is defined * as: * * \code typedef enum CUexternalSemaphoreHandleType_enum { CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD = 1, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32 = 2, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT = 3, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE = 4, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE = 5, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC = 6, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX = 7, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT = 8, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD = 9, CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32 = 10 } CUexternalSemaphoreHandleType; * \endcode * * If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD, then * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::fd must be a valid * file descriptor referencing a synchronization object. Ownership of * the file descriptor is transferred to the CUDA driver when the * handle is imported successfully. Performing any operations on the * file descriptor after it is imported results in undefined behavior. * * If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32, then exactly one * of ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle and * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name must not be * NULL. If * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle * is not NULL, then it must represent a valid shared NT handle that * references a synchronization object. Ownership of this handle is * not transferred to CUDA after the import operation, so the * application must release the handle using the appropriate system * call. If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name * is not NULL, then it must name a valid synchronization object. * * If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT, then * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle must * be non-NULL and * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name * must be NULL. The handle specified must be a globally shared KMT * handle. This handle does not hold a reference to the underlying * object, and thus will be invalid when all references to the * synchronization object are destroyed. * * If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE, then exactly one * of ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle and * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name must not be * NULL. If * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle * is not NULL, then it must represent a valid shared NT handle that * is returned by ID3D12Device::CreateSharedHandle when referring to a * ID3D12Fence object. This handle holds a reference to the underlying * object. If * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name * is not NULL, then it must name a valid synchronization object that * refers to a valid ID3D12Fence object. * * If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE, then * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle * represents a valid shared NT handle that is returned by * ID3D11Fence::CreateSharedHandle. If * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name * is not NULL, then it must name a valid synchronization object that * refers to a valid ID3D11Fence object. * * If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, then * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::nvSciSyncObj * represents a valid NvSciSyncObj. * * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX, then * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle * represents a valid shared NT handle that * is returned by IDXGIResource1::CreateSharedHandle when referring to * a IDXGIKeyedMutex object. If * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name * is not NULL, then it must name a valid synchronization object that * refers to a valid IDXGIKeyedMutex object. * * If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT, then * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle * represents a valid shared KMT handle that * is returned by IDXGIResource::GetSharedHandle when referring to * a IDXGIKeyedMutex object and * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name must be NULL. * * If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD, then * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::fd must be a valid * file descriptor referencing a synchronization object. Ownership of * the file descriptor is transferred to the CUDA driver when the * handle is imported successfully. Performing any operations on the * file descriptor after it is imported results in undefined behavior. * * If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::type is * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32, then exactly one * of ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle and * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name must not be * NULL. If * ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::handle * is not NULL, then it must represent a valid shared NT handle that * references a synchronization object. Ownership of this handle is * not transferred to CUDA after the import operation, so the * application must release the handle using the appropriate system * call. If ::CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC::handle::win32::name * is not NULL, then it must name a valid synchronization object. * * \param extSem_out - Returned handle to an external semaphore * \param semHandleDesc - Semaphore import handle descriptor * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa ::cuDestroyExternalSemaphore, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync */ CUresult CUDAAPI cuImportExternalSemaphore(CUexternalSemaphore *extSem_out, const CUDA_EXTERNAL_SEMAPHORE_HANDLE_DESC *semHandleDesc); /** * \brief Signals a set of external semaphore objects * * Enqueues a signal operation on a set of externally allocated * semaphore object in the specified stream. The operations will be * executed when all prior operations in the stream complete. * * The exact semantics of signaling a semaphore depends on the type of * the object. * * If the semaphore object is any one of the following types: * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT * then signaling the semaphore will set it to the signaled state. * * If the semaphore object is any one of the following types: * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32 * then the semaphore will be set to the value specified in * ::CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS::params::fence::value. * * If the semaphore object is of the type ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC * this API sets ::CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS::params::nvSciSync::fence * to a value that can be used by subsequent waiters of the same NvSciSync object * to order operations with those currently submitted in \p stream. Such an update * will overwrite previous contents of * ::CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS::params::nvSciSync::fence. By default, * signaling such an external semaphore object causes appropriate memory synchronization * operations to be performed over all external memory objects that are imported as * ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF. This ensures that any subsequent accesses * made by other importers of the same set of NvSciBuf memory object(s) are coherent. * These operations can be skipped by specifying the flag * ::CUDA_EXTERNAL_SEMAPHORE_SIGNAL_SKIP_NVSCIBUF_MEMSYNC, which can be used as a * performance optimization when data coherency is not required. But specifying this * flag in scenarios where data coherency is required results in undefined behavior. * Also, for semaphore object of the type ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, * if the NvSciSyncAttrList used to create the NvSciSyncObj had not set the flags in * ::cuDeviceGetNvSciSyncAttributes to CUDA_NVSCISYNC_ATTR_SIGNAL, this API will return * CUDA_ERROR_NOT_SUPPORTED. * * If the semaphore object is any one of the following types: * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT * then the keyed mutex will be released with the key specified in * ::CUDA_EXTERNAL_SEMAPHORE_PARAMS::params::keyedmutex::key. * * \param extSemArray - Set of external semaphores to be signaled * \param paramsArray - Array of semaphore parameters * \param numExtSems - Number of semaphores to signal * \param stream - Stream to enqueue the signal operations in * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa ::cuImportExternalSemaphore, * ::cuDestroyExternalSemaphore, * ::cuWaitExternalSemaphoresAsync */ CUresult CUDAAPI cuSignalExternalSemaphoresAsync(const CUexternalSemaphore *extSemArray, const CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS *paramsArray, unsigned int numExtSems, CUstream stream); /** * \brief Waits on a set of external semaphore objects * * Enqueues a wait operation on a set of externally allocated * semaphore object in the specified stream. The operations will be * executed when all prior operations in the stream complete. * * The exact semantics of waiting on a semaphore depends on the type * of the object. * * If the semaphore object is any one of the following types: * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT * then waiting on the semaphore will wait until the semaphore reaches * the signaled state. The semaphore will then be reset to the * unsignaled state. Therefore for every signal operation, there can * only be one wait operation. * * If the semaphore object is any one of the following types: * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_FENCE, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_FD, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_TIMELINE_SEMAPHORE_WIN32 * then waiting on the semaphore will wait until the value of the * semaphore is greater than or equal to * ::CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS::params::fence::value. * * If the semaphore object is of the type ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC * then, waiting on the semaphore will wait until the * ::CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS::params::nvSciSync::fence is signaled by the * signaler of the NvSciSyncObj that was associated with this semaphore object. * By default, waiting on such an external semaphore object causes appropriate * memory synchronization operations to be performed over all external memory objects * that are imported as ::CU_EXTERNAL_MEMORY_HANDLE_TYPE_NVSCIBUF. This ensures that * any subsequent accesses made by other importers of the same set of NvSciBuf memory * object(s) are coherent. These operations can be skipped by specifying the flag * ::CUDA_EXTERNAL_SEMAPHORE_WAIT_SKIP_NVSCIBUF_MEMSYNC, which can be used as a * performance optimization when data coherency is not required. But specifying this * flag in scenarios where data coherency is required results in undefined behavior. * Also, for semaphore object of the type ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_NVSCISYNC, * if the NvSciSyncAttrList used to create the NvSciSyncObj had not set the flags in * ::cuDeviceGetNvSciSyncAttributes to CUDA_NVSCISYNC_ATTR_WAIT, this API will return * CUDA_ERROR_NOT_SUPPORTED. * * If the semaphore object is any one of the following types: * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX, * ::CU_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D11_KEYED_MUTEX_KMT * then the keyed mutex will be acquired when it is released with the key * specified in ::CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS::params::keyedmutex::key * or until the timeout specified by * ::CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS::params::keyedmutex::timeoutMs * has lapsed. The timeout interval can either be a finite value * specified in milliseconds or an infinite value. In case an infinite * value is specified the timeout never elapses. The windows INFINITE * macro must be used to specify infinite timeout. * * \param extSemArray - External semaphores to be waited on * \param paramsArray - Array of semaphore parameters * \param numExtSems - Number of semaphores to wait on * \param stream - Stream to enqueue the wait operations in * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_TIMEOUT * \notefnerr * * \sa ::cuImportExternalSemaphore, * ::cuDestroyExternalSemaphore, * ::cuSignalExternalSemaphoresAsync */ CUresult CUDAAPI cuWaitExternalSemaphoresAsync(const CUexternalSemaphore *extSemArray, const CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS *paramsArray, unsigned int numExtSems, CUstream stream); /** * \brief Destroys an external semaphore * * Destroys an external semaphore object and releases any references * to the underlying resource. Any outstanding signals or waits must * have completed before the semaphore is destroyed. * * \param extSem - External semaphore to be destroyed * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa ::cuImportExternalSemaphore, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync */ CUresult CUDAAPI cuDestroyExternalSemaphore(CUexternalSemaphore extSem); /** @} */ /* END CUDA_EXTRES_INTEROP */ /** * \defgroup CUDA_MEMOP Stream memory operations * * ___MANBRIEF___ Stream memory operations of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the stream memory operations of the low-level CUDA * driver application programming interface. * * The whole set of operations is disabled by default. Users are required * to explicitly enable them, e.g. on Linux by passing the kernel module * parameter shown below: * modprobe nvidia NVreg_EnableStreamMemOPs=1 * There is currently no way to enable these operations on other operating * systems. * * Users can programmatically query whether the device supports these * operations with ::cuDeviceGetAttribute() and * ::CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_MEM_OPS. * * Support for the ::CU_STREAM_WAIT_VALUE_NOR flag can be queried with * ::CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR. * * Support for the ::cuStreamWriteValue64() and ::cuStreamWaitValue64() * functions, as well as for the ::CU_STREAM_MEM_OP_WAIT_VALUE_64 and * ::CU_STREAM_MEM_OP_WRITE_VALUE_64 flags, can be queried with * ::CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS. * * Support for both ::CU_STREAM_WAIT_VALUE_FLUSH and * ::CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES requires dedicated platform * hardware features and can be queried with ::cuDeviceGetAttribute() and * ::CU_DEVICE_ATTRIBUTE_CAN_FLUSH_REMOTE_WRITES. * * Note that all memory pointers passed as parameters to these operations * are device pointers. Where necessary a device pointer should be * obtained, for example with ::cuMemHostGetDevicePointer(). * * None of the operations accepts pointers to managed memory buffers * (::cuMemAllocManaged). * * @{ */ /** * \brief Wait on a memory location * * Enqueues a synchronization of the stream on the given memory location. Work * ordered after the operation will block until the given condition on the * memory is satisfied. By default, the condition is to wait for * (int32_t)(*addr - value) >= 0, a cyclic greater-or-equal. * Other condition types can be specified via \p flags. * * If the memory was registered via ::cuMemHostRegister(), the device pointer * should be obtained with ::cuMemHostGetDevicePointer(). This function cannot * be used with managed memory (::cuMemAllocManaged). * * Support for this can be queried with ::cuDeviceGetAttribute() and * ::CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_MEM_OPS. * * Support for CU_STREAM_WAIT_VALUE_NOR can be queried with ::cuDeviceGetAttribute() and * ::CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_WAIT_VALUE_NOR. * * \param stream The stream to synchronize on the memory location. * \param addr The memory location to wait on. * \param value The value to compare with the memory location. * \param flags See ::CUstreamWaitValue_flags. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa ::cuStreamWaitValue64, * ::cuStreamWriteValue32, * ::cuStreamWriteValue64, * ::cuStreamBatchMemOp, * ::cuMemHostRegister, * ::cuStreamWaitEvent */ CUresult CUDAAPI cuStreamWaitValue32(CUstream stream, CUdeviceptr addr, cuuint32_t value, unsigned int flags); /** * \brief Wait on a memory location * * Enqueues a synchronization of the stream on the given memory location. Work * ordered after the operation will block until the given condition on the * memory is satisfied. By default, the condition is to wait for * (int64_t)(*addr - value) >= 0, a cyclic greater-or-equal. * Other condition types can be specified via \p flags. * * If the memory was registered via ::cuMemHostRegister(), the device pointer * should be obtained with ::cuMemHostGetDevicePointer(). * * Support for this can be queried with ::cuDeviceGetAttribute() and * ::CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS. * * \param stream The stream to synchronize on the memory location. * \param addr The memory location to wait on. * \param value The value to compare with the memory location. * \param flags See ::CUstreamWaitValue_flags. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa ::cuStreamWaitValue32, * ::cuStreamWriteValue32, * ::cuStreamWriteValue64, * ::cuStreamBatchMemOp, * ::cuMemHostRegister, * ::cuStreamWaitEvent */ CUresult CUDAAPI cuStreamWaitValue64(CUstream stream, CUdeviceptr addr, cuuint64_t value, unsigned int flags); /** * \brief Write a value to memory * * Write a value to memory. Unless the ::CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER * flag is passed, the write is preceded by a system-wide memory fence, * equivalent to a __threadfence_system() but scoped to the stream * rather than a CUDA thread. * * If the memory was registered via ::cuMemHostRegister(), the device pointer * should be obtained with ::cuMemHostGetDevicePointer(). This function cannot * be used with managed memory (::cuMemAllocManaged). * * Support for this can be queried with ::cuDeviceGetAttribute() and * ::CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_MEM_OPS. * * \param stream The stream to do the write in. * \param addr The device address to write to. * \param value The value to write. * \param flags See ::CUstreamWriteValue_flags. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa ::cuStreamWriteValue64, * ::cuStreamWaitValue32, * ::cuStreamWaitValue64, * ::cuStreamBatchMemOp, * ::cuMemHostRegister, * ::cuEventRecord */ CUresult CUDAAPI cuStreamWriteValue32(CUstream stream, CUdeviceptr addr, cuuint32_t value, unsigned int flags); /** * \brief Write a value to memory * * Write a value to memory. Unless the ::CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER * flag is passed, the write is preceded by a system-wide memory fence, * equivalent to a __threadfence_system() but scoped to the stream * rather than a CUDA thread. * * If the memory was registered via ::cuMemHostRegister(), the device pointer * should be obtained with ::cuMemHostGetDevicePointer(). * * Support for this can be queried with ::cuDeviceGetAttribute() and * ::CU_DEVICE_ATTRIBUTE_CAN_USE_64_BIT_STREAM_MEM_OPS. * * \param stream The stream to do the write in. * \param addr The device address to write to. * \param value The value to write. * \param flags See ::CUstreamWriteValue_flags. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa ::cuStreamWriteValue32, * ::cuStreamWaitValue32, * ::cuStreamWaitValue64, * ::cuStreamBatchMemOp, * ::cuMemHostRegister, * ::cuEventRecord */ CUresult CUDAAPI cuStreamWriteValue64(CUstream stream, CUdeviceptr addr, cuuint64_t value, unsigned int flags); /** * \brief Batch operations to synchronize the stream via memory operations * * This is a batch version of ::cuStreamWaitValue32() and ::cuStreamWriteValue32(). * Batching operations may avoid some performance overhead in both the API call * and the device execution versus adding them to the stream in separate API * calls. The operations are enqueued in the order they appear in the array. * * See ::CUstreamBatchMemOpType for the full set of supported operations, and * ::cuStreamWaitValue32(), ::cuStreamWaitValue64(), ::cuStreamWriteValue32(), * and ::cuStreamWriteValue64() for details of specific operations. * * Basic support for this can be queried with ::cuDeviceGetAttribute() and * ::CU_DEVICE_ATTRIBUTE_CAN_USE_STREAM_MEM_OPS. See related APIs for details * on querying support for specific operations. * * \param stream The stream to enqueue the operations in. * \param count The number of operations in the array. Must be less than 256. * \param paramArray The types and parameters of the individual operations. * \param flags Reserved for future expansion; must be 0. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_SUPPORTED * \notefnerr * * \sa ::cuStreamWaitValue32, * ::cuStreamWaitValue64, * ::cuStreamWriteValue32, * ::cuStreamWriteValue64, * ::cuMemHostRegister */ CUresult CUDAAPI cuStreamBatchMemOp(CUstream stream, unsigned int count, CUstreamBatchMemOpParams *paramArray, unsigned int flags); /** @} */ /* END CUDA_MEMOP */ /** * \defgroup CUDA_EXEC Execution Control * * ___MANBRIEF___ execution control functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the execution control functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Returns information about a function * * Returns in \p *pi the integer value of the attribute \p attrib on the kernel * given by \p hfunc. The supported attributes are: * - ::CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK: The maximum number of threads * per block, beyond which a launch of the function would fail. This number * depends on both the function and the device on which the function is * currently loaded. * - ::CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES: The size in bytes of * statically-allocated shared memory per block required by this function. * This does not include dynamically-allocated shared memory requested by * the user at runtime. * - ::CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES: The size in bytes of user-allocated * constant memory required by this function. * - ::CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES: The size in bytes of local memory * used by each thread of this function. * - ::CU_FUNC_ATTRIBUTE_NUM_REGS: The number of registers used by each thread * of this function. * - ::CU_FUNC_ATTRIBUTE_PTX_VERSION: The PTX virtual architecture version for * which the function was compiled. This value is the major PTX version * 10 * + the minor PTX version, so a PTX version 1.3 function would return the * value 13. Note that this may return the undefined value of 0 for cubins * compiled prior to CUDA 3.0. * - ::CU_FUNC_ATTRIBUTE_BINARY_VERSION: The binary architecture version for * which the function was compiled. This value is the major binary * version * 10 + the minor binary version, so a binary version 1.3 function * would return the value 13. Note that this will return a value of 10 for * legacy cubins that do not have a properly-encoded binary architecture * version. * - ::CU_FUNC_CACHE_MODE_CA: The attribute to indicate whether the function has * been compiled with user specified option "-Xptxas --dlcm=ca" set . * - ::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES: The maximum size in bytes of * dynamically-allocated shared memory. * - ::CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT: Preferred shared memory-L1 * cache split ratio in percent of total shared memory. * * \param pi - Returned attribute value * \param attrib - Attribute requested * \param hfunc - Function to query attribute of * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuCtxGetCacheConfig, * ::cuCtxSetCacheConfig, * ::cuFuncSetCacheConfig, * ::cuLaunchKernel, * ::cudaFuncGetAttributes, * ::cudaFuncSetAttribute */ CUresult CUDAAPI cuFuncGetAttribute(int *pi, CUfunction_attribute attrib, CUfunction hfunc); /** * \brief Sets information about a function * * This call sets the value of a specified attribute \p attrib on the kernel given * by \p hfunc to an integer value specified by \p val * This function returns CUDA_SUCCESS if the new value of the attribute could be * successfully set. If the set fails, this call will return an error. * Not all attributes can have values set. Attempting to set a value on a read-only * attribute will result in an error (CUDA_ERROR_INVALID_VALUE) * * Supported attributes for the cuFuncSetAttribute call are: * - ::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES: This maximum size in bytes of * dynamically-allocated shared memory. The value should contain the requested * maximum size of dynamically-allocated shared memory. The sum of this value and * the function attribute ::CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES cannot exceed the * device attribute ::CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN. * The maximal size of requestable dynamic shared memory may differ by GPU * architecture. * - ::CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT: On devices where the L1 * cache and shared memory use the same hardware resources, this sets the shared memory * carveout preference, in percent of the total shared memory. * See ::CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR * This is only a hint, and the driver can choose a different ratio if required to execute the function. * * \param hfunc - Function to query attribute of * \param attrib - Attribute requested * \param value - The value to set * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuCtxGetCacheConfig, * ::cuCtxSetCacheConfig, * ::cuFuncSetCacheConfig, * ::cuLaunchKernel, * ::cudaFuncGetAttributes, * ::cudaFuncSetAttribute */ CUresult CUDAAPI cuFuncSetAttribute(CUfunction hfunc, CUfunction_attribute attrib, int value); /** * \brief Sets the preferred cache configuration for a device function * * On devices where the L1 cache and shared memory use the same hardware * resources, this sets through \p config the preferred cache configuration for * the device function \p hfunc. This is only a preference. The driver will use * the requested configuration if possible, but it is free to choose a different * configuration if required to execute \p hfunc. Any context-wide preference * set via ::cuCtxSetCacheConfig() will be overridden by this per-function * setting unless the per-function setting is ::CU_FUNC_CACHE_PREFER_NONE. In * that case, the current context-wide setting will be used. * * This setting does nothing on devices where the size of the L1 cache and * shared memory are fixed. * * Launching a kernel with a different preference than the most recent * preference setting may insert a device-side synchronization point. * * * The supported cache configurations are: * - ::CU_FUNC_CACHE_PREFER_NONE: no preference for shared memory or L1 (default) * - ::CU_FUNC_CACHE_PREFER_SHARED: prefer larger shared memory and smaller L1 cache * - ::CU_FUNC_CACHE_PREFER_L1: prefer larger L1 cache and smaller shared memory * - ::CU_FUNC_CACHE_PREFER_EQUAL: prefer equal sized L1 cache and shared memory * * \param hfunc - Kernel to configure cache for * \param config - Requested cache configuration * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT * \notefnerr * * \sa ::cuCtxGetCacheConfig, * ::cuCtxSetCacheConfig, * ::cuFuncGetAttribute, * ::cuLaunchKernel, * ::cudaFuncSetCacheConfig */ CUresult CUDAAPI cuFuncSetCacheConfig(CUfunction hfunc, CUfunc_cache config); /** * \brief Sets the shared memory configuration for a device function. * * On devices with configurable shared memory banks, this function will * force all subsequent launches of the specified device function to have * the given shared memory bank size configuration. On any given launch of the * function, the shared memory configuration of the device will be temporarily * changed if needed to suit the function's preferred configuration. Changes in * shared memory configuration between subsequent launches of functions, * may introduce a device side synchronization point. * * Any per-function setting of shared memory bank size set via * ::cuFuncSetSharedMemConfig will override the context wide setting set with * ::cuCtxSetSharedMemConfig. * * Changing the shared memory bank size will not increase shared memory usage * or affect occupancy of kernels, but may have major effects on performance. * Larger bank sizes will allow for greater potential bandwidth to shared memory, * but will change what kinds of accesses to shared memory will result in bank * conflicts. * * This function will do nothing on devices with fixed shared memory bank size. * * The supported bank configurations are: * - ::CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE: use the context's shared memory * configuration when launching this function. * - ::CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE: set shared memory bank width to * be natively four bytes when launching this function. * - ::CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE: set shared memory bank width to * be natively eight bytes when launching this function. * * \param hfunc - kernel to be given a shared memory config * \param config - requested shared memory configuration * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT * \notefnerr * * \sa ::cuCtxGetCacheConfig, * ::cuCtxSetCacheConfig, * ::cuCtxGetSharedMemConfig, * ::cuCtxSetSharedMemConfig, * ::cuFuncGetAttribute, * ::cuLaunchKernel, * ::cudaFuncSetSharedMemConfig */ CUresult CUDAAPI cuFuncSetSharedMemConfig(CUfunction hfunc, CUsharedconfig config); /** * \brief Returns a module handle * * Returns in \p *hmod the handle of the module that function \p hfunc * is located in. The lifetime of the module corresponds to the lifetime of * the context it was loaded in or until the module is explicitly unloaded. * * The CUDA runtime manages its own modules loaded into the primary context. * If the handle returned by this API refers to a module loaded by the CUDA runtime, * calling ::cuModuleUnload() on that module will result in undefined behavior. * * \param hmod - Returned module handle * \param hfunc - Function to retrieve module for * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_FOUND * \notefnerr * */ CUresult CUDAAPI cuFuncGetModule(CUmodule *hmod, CUfunction hfunc); /** * \brief Launches a CUDA function * * Invokes the kernel \p f on a \p gridDimX x \p gridDimY x \p gridDimZ * grid of blocks. Each block contains \p blockDimX x \p blockDimY x * \p blockDimZ threads. * * \p sharedMemBytes sets the amount of dynamic shared memory that will be * available to each thread block. * * Kernel parameters to \p f can be specified in one of two ways: * * 1) Kernel parameters can be specified via \p kernelParams. If \p f * has N parameters, then \p kernelParams needs to be an array of N * pointers. Each of \p kernelParams[0] through \p kernelParams[N-1] * must point to a region of memory from which the actual kernel * parameter will be copied. The number of kernel parameters and their * offsets and sizes do not need to be specified as that information is * retrieved directly from the kernel's image. * * 2) Kernel parameters can also be packaged by the application into * a single buffer that is passed in via the \p extra parameter. * This places the burden on the application of knowing each kernel * parameter's size and alignment/padding within the buffer. Here is * an example of using the \p extra parameter in this manner: * \code size_t argBufferSize; char argBuffer[256]; // populate argBuffer and argBufferSize void *config[] = { CU_LAUNCH_PARAM_BUFFER_POINTER, argBuffer, CU_LAUNCH_PARAM_BUFFER_SIZE, &argBufferSize, CU_LAUNCH_PARAM_END }; status = cuLaunchKernel(f, gx, gy, gz, bx, by, bz, sh, s, NULL, config); * \endcode * * The \p extra parameter exists to allow ::cuLaunchKernel to take * additional less commonly used arguments. \p extra specifies a list of * names of extra settings and their corresponding values. Each extra * setting name is immediately followed by the corresponding value. The * list must be terminated with either NULL or ::CU_LAUNCH_PARAM_END. * * - ::CU_LAUNCH_PARAM_END, which indicates the end of the \p extra * array; * - ::CU_LAUNCH_PARAM_BUFFER_POINTER, which specifies that the next * value in \p extra will be a pointer to a buffer containing all * the kernel parameters for launching kernel \p f; * - ::CU_LAUNCH_PARAM_BUFFER_SIZE, which specifies that the next * value in \p extra will be a pointer to a size_t containing the * size of the buffer specified with ::CU_LAUNCH_PARAM_BUFFER_POINTER; * * The error ::CUDA_ERROR_INVALID_VALUE will be returned if kernel * parameters are specified with both \p kernelParams and \p extra * (i.e. both \p kernelParams and \p extra are non-NULL). * * Calling ::cuLaunchKernel() invalidates the persistent function state * set through the following deprecated APIs: * ::cuFuncSetBlockShape(), * ::cuFuncSetSharedSize(), * ::cuParamSetSize(), * ::cuParamSeti(), * ::cuParamSetf(), * ::cuParamSetv(). * * Note that to use ::cuLaunchKernel(), the kernel \p f must either have * been compiled with toolchain version 3.2 or later so that it will * contain kernel parameter information, or have no kernel parameters. * If either of these conditions is not met, then ::cuLaunchKernel() will * return ::CUDA_ERROR_INVALID_IMAGE. * * \param f - Kernel to launch * \param gridDimX - Width of grid in blocks * \param gridDimY - Height of grid in blocks * \param gridDimZ - Depth of grid in blocks * \param blockDimX - X dimension of each thread block * \param blockDimY - Y dimension of each thread block * \param blockDimZ - Z dimension of each thread block * \param sharedMemBytes - Dynamic shared-memory size per thread block in bytes * \param hStream - Stream identifier * \param kernelParams - Array of pointers to kernel parameters * \param extra - Extra options * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_IMAGE, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_LAUNCH_FAILED, * ::CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, * ::CUDA_ERROR_LAUNCH_TIMEOUT, * ::CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, * ::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED * \note_null_stream * \notefnerr * * \sa ::cuCtxGetCacheConfig, * ::cuCtxSetCacheConfig, * ::cuFuncSetCacheConfig, * ::cuFuncGetAttribute, * ::cudaLaunchKernel */ CUresult CUDAAPI cuLaunchKernel(CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hStream, void **kernelParams, void **extra); /** * \brief Launches a CUDA function where thread blocks can cooperate and synchronize as they execute * * Invokes the kernel \p f on a \p gridDimX x \p gridDimY x \p gridDimZ * grid of blocks. Each block contains \p blockDimX x \p blockDimY x * \p blockDimZ threads. * * \p sharedMemBytes sets the amount of dynamic shared memory that will be * available to each thread block. * * The device on which this kernel is invoked must have a non-zero value for * the device attribute ::CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH. * * The total number of blocks launched cannot exceed the maximum number of blocks per * multiprocessor as returned by ::cuOccupancyMaxActiveBlocksPerMultiprocessor (or * ::cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags) times the number of multiprocessors * as specified by the device attribute ::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT. * * The kernel cannot make use of CUDA dynamic parallelism. * * Kernel parameters must be specified via \p kernelParams. If \p f * has N parameters, then \p kernelParams needs to be an array of N * pointers. Each of \p kernelParams[0] through \p kernelParams[N-1] * must point to a region of memory from which the actual kernel * parameter will be copied. The number of kernel parameters and their * offsets and sizes do not need to be specified as that information is * retrieved directly from the kernel's image. * * Calling ::cuLaunchCooperativeKernel() sets persistent function state that is * the same as function state set through ::cuLaunchKernel API * * When the kernel \p f is launched via ::cuLaunchCooperativeKernel(), the previous * block shape, shared size and parameter info associated with \p f * is overwritten. * * Note that to use ::cuLaunchCooperativeKernel(), the kernel \p f must either have * been compiled with toolchain version 3.2 or later so that it will * contain kernel parameter information, or have no kernel parameters. * If either of these conditions is not met, then ::cuLaunchCooperativeKernel() will * return ::CUDA_ERROR_INVALID_IMAGE. * * \param f - Kernel to launch * \param gridDimX - Width of grid in blocks * \param gridDimY - Height of grid in blocks * \param gridDimZ - Depth of grid in blocks * \param blockDimX - X dimension of each thread block * \param blockDimY - Y dimension of each thread block * \param blockDimZ - Z dimension of each thread block * \param sharedMemBytes - Dynamic shared-memory size per thread block in bytes * \param hStream - Stream identifier * \param kernelParams - Array of pointers to kernel parameters * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_IMAGE, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_LAUNCH_FAILED, * ::CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, * ::CUDA_ERROR_LAUNCH_TIMEOUT, * ::CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, * ::CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE, * ::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED * \note_null_stream * \notefnerr * * \sa ::cuCtxGetCacheConfig, * ::cuCtxSetCacheConfig, * ::cuFuncSetCacheConfig, * ::cuFuncGetAttribute, * ::cuLaunchCooperativeKernelMultiDevice, * ::cudaLaunchCooperativeKernel */ CUresult CUDAAPI cuLaunchCooperativeKernel(CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hStream, void **kernelParams); /** * \brief Launches CUDA functions on multiple devices where thread blocks can cooperate and synchronize as they execute * * \deprecated This function is deprecated as of CUDA 11.3. * * Invokes kernels as specified in the \p launchParamsList array where each element * of the array specifies all the parameters required to perform a single kernel launch. * These kernels can cooperate and synchronize as they execute. The size of the array is * specified by \p numDevices. * * No two kernels can be launched on the same device. All the devices targeted by this * multi-device launch must be identical. All devices must have a non-zero value for the * device attribute ::CU_DEVICE_ATTRIBUTE_COOPERATIVE_MULTI_DEVICE_LAUNCH. * * All kernels launched must be identical with respect to the compiled code. Note that * any __device__, __constant__ or __managed__ variables present in the module that owns * the kernel launched on each device, are independently instantiated on every device. * It is the application's responsiblity to ensure these variables are initialized and * used appropriately. * * The size of the grids as specified in blocks, the size of the blocks themselves * and the amount of shared memory used by each thread block must also match across * all launched kernels. * * The streams used to launch these kernels must have been created via either ::cuStreamCreate * or ::cuStreamCreateWithPriority. The NULL stream or ::CU_STREAM_LEGACY or ::CU_STREAM_PER_THREAD * cannot be used. * * The total number of blocks launched per kernel cannot exceed the maximum number of blocks * per multiprocessor as returned by ::cuOccupancyMaxActiveBlocksPerMultiprocessor (or * ::cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags) times the number of multiprocessors * as specified by the device attribute ::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT. Since the * total number of blocks launched per device has to match across all devices, the maximum * number of blocks that can be launched per device will be limited by the device with the * least number of multiprocessors. * * The kernels cannot make use of CUDA dynamic parallelism. * * The ::CUDA_LAUNCH_PARAMS structure is defined as: * \code typedef struct CUDA_LAUNCH_PARAMS_st { CUfunction function; unsigned int gridDimX; unsigned int gridDimY; unsigned int gridDimZ; unsigned int blockDimX; unsigned int blockDimY; unsigned int blockDimZ; unsigned int sharedMemBytes; CUstream hStream; void **kernelParams; } CUDA_LAUNCH_PARAMS; * \endcode * where: * - ::CUDA_LAUNCH_PARAMS::function specifies the kernel to be launched. All functions must * be identical with respect to the compiled code. * - ::CUDA_LAUNCH_PARAMS::gridDimX is the width of the grid in blocks. This must match across * all kernels launched. * - ::CUDA_LAUNCH_PARAMS::gridDimY is the height of the grid in blocks. This must match across * all kernels launched. * - ::CUDA_LAUNCH_PARAMS::gridDimZ is the depth of the grid in blocks. This must match across * all kernels launched. * - ::CUDA_LAUNCH_PARAMS::blockDimX is the X dimension of each thread block. This must match across * all kernels launched. * - ::CUDA_LAUNCH_PARAMS::blockDimX is the Y dimension of each thread block. This must match across * all kernels launched. * - ::CUDA_LAUNCH_PARAMS::blockDimZ is the Z dimension of each thread block. This must match across * all kernels launched. * - ::CUDA_LAUNCH_PARAMS::sharedMemBytes is the dynamic shared-memory size per thread block in bytes. * This must match across all kernels launched. * - ::CUDA_LAUNCH_PARAMS::hStream is the handle to the stream to perform the launch in. This cannot * be the NULL stream or ::CU_STREAM_LEGACY or ::CU_STREAM_PER_THREAD. The CUDA context associated * with this stream must match that associated with ::CUDA_LAUNCH_PARAMS::function. * - ::CUDA_LAUNCH_PARAMS::kernelParams is an array of pointers to kernel parameters. If * ::CUDA_LAUNCH_PARAMS::function has N parameters, then ::CUDA_LAUNCH_PARAMS::kernelParams * needs to be an array of N pointers. Each of ::CUDA_LAUNCH_PARAMS::kernelParams[0] through * ::CUDA_LAUNCH_PARAMS::kernelParams[N-1] must point to a region of memory from which the actual * kernel parameter will be copied. The number of kernel parameters and their offsets and sizes * do not need to be specified as that information is retrieved directly from the kernel's image. * * By default, the kernel won't begin execution on any GPU until all prior work in all the specified * streams has completed. This behavior can be overridden by specifying the flag * ::CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_PRE_LAUNCH_SYNC. When this flag is specified, each kernel * will only wait for prior work in the stream corresponding to that GPU to complete before it begins * execution. * * Similarly, by default, any subsequent work pushed in any of the specified streams will not begin * execution until the kernels on all GPUs have completed. This behavior can be overridden by specifying * the flag ::CUDA_COOPERATIVE_LAUNCH_MULTI_DEVICE_NO_POST_LAUNCH_SYNC. When this flag is specified, * any subsequent work pushed in any of the specified streams will only wait for the kernel launched * on the GPU corresponding to that stream to complete before it begins execution. * * Calling ::cuLaunchCooperativeKernelMultiDevice() sets persistent function state that is * the same as function state set through ::cuLaunchKernel API when called individually for each * element in \p launchParamsList. * * When kernels are launched via ::cuLaunchCooperativeKernelMultiDevice(), the previous * block shape, shared size and parameter info associated with each ::CUDA_LAUNCH_PARAMS::function * in \p launchParamsList is overwritten. * * Note that to use ::cuLaunchCooperativeKernelMultiDevice(), the kernels must either have * been compiled with toolchain version 3.2 or later so that it will * contain kernel parameter information, or have no kernel parameters. * If either of these conditions is not met, then ::cuLaunchCooperativeKernelMultiDevice() will * return ::CUDA_ERROR_INVALID_IMAGE. * * \param launchParamsList - List of launch parameters, one per device * \param numDevices - Size of the \p launchParamsList array * \param flags - Flags to control launch behavior * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_IMAGE, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_LAUNCH_FAILED, * ::CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, * ::CUDA_ERROR_LAUNCH_TIMEOUT, * ::CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, * ::CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE, * ::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED * \note_null_stream * \notefnerr * * \sa ::cuCtxGetCacheConfig, * ::cuCtxSetCacheConfig, * ::cuFuncSetCacheConfig, * ::cuFuncGetAttribute, * ::cuLaunchCooperativeKernel, * ::cudaLaunchCooperativeKernelMultiDevice */ __CUDA_DEPRECATED CUresult CUDAAPI cuLaunchCooperativeKernelMultiDevice(CUDA_LAUNCH_PARAMS *launchParamsList, unsigned int numDevices, unsigned int flags); /** * \brief Enqueues a host function call in a stream * * Enqueues a host function to run in a stream. The function will be called * after currently enqueued work and will block work added after it. * * The host function must not make any CUDA API calls. Attempting to use a * CUDA API may result in ::CUDA_ERROR_NOT_PERMITTED, but this is not required. * The host function must not perform any synchronization that may depend on * outstanding CUDA work not mandated to run earlier. Host functions without a * mandated order (such as in independent streams) execute in undefined order * and may be serialized. * * For the purposes of Unified Memory, execution makes a number of guarantees: * <ul> * <li>The stream is considered idle for the duration of the function's * execution. Thus, for example, the function may always use memory attached * to the stream it was enqueued in.</li> * <li>The start of execution of the function has the same effect as * synchronizing an event recorded in the same stream immediately prior to * the function. It thus synchronizes streams which have been "joined" * prior to the function.</li> * <li>Adding device work to any stream does not have the effect of making * the stream active until all preceding host functions and stream callbacks * have executed. Thus, for * example, a function might use global attached memory even if work has * been added to another stream, if the work has been ordered behind the * function call with an event.</li> * <li>Completion of the function does not cause a stream to become * active except as described above. The stream will remain idle * if no device work follows the function, and will remain idle across * consecutive host functions or stream callbacks without device work in * between. Thus, for example, * stream synchronization can be done by signaling from a host function at the * end of the stream.</li> * </ul> * * Note that, in contrast to ::cuStreamAddCallback, the function will not be * called in the event of an error in the CUDA context. * * \param hStream - Stream to enqueue function call in * \param fn - The function to call once preceding stream operations are complete * \param userData - User-specified data to be passed to the function * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_SUPPORTED * \note_null_stream * \notefnerr * * \sa ::cuStreamCreate, * ::cuStreamQuery, * ::cuStreamSynchronize, * ::cuStreamWaitEvent, * ::cuStreamDestroy, * ::cuMemAllocManaged, * ::cuStreamAttachMemAsync, * ::cuStreamAddCallback */ CUresult CUDAAPI cuLaunchHostFunc(CUstream hStream, CUhostFn fn, void *userData); /** @} */ /* END CUDA_EXEC */ /** * \defgroup CUDA_EXEC_DEPRECATED Execution Control [DEPRECATED] * * ___MANBRIEF___ deprecated execution control functions of the low-level CUDA * driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the deprecated execution control functions of the * low-level CUDA driver application programming interface. * * @{ */ /** * \brief Sets the block-dimensions for the function * * \deprecated * * Specifies the \p x, \p y, and \p z dimensions of the thread blocks that are * created when the kernel given by \p hfunc is launched. * * \param hfunc - Kernel to specify dimensions of * \param x - X dimension * \param y - Y dimension * \param z - Z dimension * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuFuncSetSharedSize, * ::cuFuncSetCacheConfig, * ::cuFuncGetAttribute, * ::cuParamSetSize, * ::cuParamSeti, * ::cuParamSetf, * ::cuParamSetv, * ::cuLaunch, * ::cuLaunchGrid, * ::cuLaunchGridAsync, * ::cuLaunchKernel */ __CUDA_DEPRECATED CUresult CUDAAPI cuFuncSetBlockShape(CUfunction hfunc, int x, int y, int z); /** * \brief Sets the dynamic shared-memory size for the function * * \deprecated * * Sets through \p bytes the amount of dynamic shared memory that will be * available to each thread block when the kernel given by \p hfunc is launched. * * \param hfunc - Kernel to specify dynamic shared-memory size for * \param bytes - Dynamic shared-memory size per thread in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuFuncSetBlockShape, * ::cuFuncSetCacheConfig, * ::cuFuncGetAttribute, * ::cuParamSetSize, * ::cuParamSeti, * ::cuParamSetf, * ::cuParamSetv, * ::cuLaunch, * ::cuLaunchGrid, * ::cuLaunchGridAsync, * ::cuLaunchKernel */ __CUDA_DEPRECATED CUresult CUDAAPI cuFuncSetSharedSize(CUfunction hfunc, unsigned int bytes); /** * \brief Sets the parameter size for the function * * \deprecated * * Sets through \p numbytes the total size in bytes needed by the function * parameters of the kernel corresponding to \p hfunc. * * \param hfunc - Kernel to set parameter size for * \param numbytes - Size of parameter list in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuFuncSetBlockShape, * ::cuFuncSetSharedSize, * ::cuFuncGetAttribute, * ::cuParamSetf, * ::cuParamSeti, * ::cuParamSetv, * ::cuLaunch, * ::cuLaunchGrid, * ::cuLaunchGridAsync, * ::cuLaunchKernel */ __CUDA_DEPRECATED CUresult CUDAAPI cuParamSetSize(CUfunction hfunc, unsigned int numbytes); /** * \brief Adds an integer parameter to the function's argument list * * \deprecated * * Sets an integer parameter that will be specified the next time the * kernel corresponding to \p hfunc will be invoked. \p offset is a byte offset. * * \param hfunc - Kernel to add parameter to * \param offset - Offset to add parameter to argument list * \param value - Value of parameter * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuFuncSetBlockShape, * ::cuFuncSetSharedSize, * ::cuFuncGetAttribute, * ::cuParamSetSize, * ::cuParamSetf, * ::cuParamSetv, * ::cuLaunch, * ::cuLaunchGrid, * ::cuLaunchGridAsync, * ::cuLaunchKernel */ __CUDA_DEPRECATED CUresult CUDAAPI cuParamSeti(CUfunction hfunc, int offset, unsigned int value); /** * \brief Adds a floating-point parameter to the function's argument list * * \deprecated * * Sets a floating-point parameter that will be specified the next time the * kernel corresponding to \p hfunc will be invoked. \p offset is a byte offset. * * \param hfunc - Kernel to add parameter to * \param offset - Offset to add parameter to argument list * \param value - Value of parameter * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuFuncSetBlockShape, * ::cuFuncSetSharedSize, * ::cuFuncGetAttribute, * ::cuParamSetSize, * ::cuParamSeti, * ::cuParamSetv, * ::cuLaunch, * ::cuLaunchGrid, * ::cuLaunchGridAsync, * ::cuLaunchKernel */ __CUDA_DEPRECATED CUresult CUDAAPI cuParamSetf(CUfunction hfunc, int offset, float value); /** * \brief Adds arbitrary data to the function's argument list * * \deprecated * * Copies an arbitrary amount of data (specified in \p numbytes) from \p ptr * into the parameter space of the kernel corresponding to \p hfunc. \p offset * is a byte offset. * * \param hfunc - Kernel to add data to * \param offset - Offset to add data to argument list * \param ptr - Pointer to arbitrary data * \param numbytes - Size of data to copy in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa ::cuFuncSetBlockShape, * ::cuFuncSetSharedSize, * ::cuFuncGetAttribute, * ::cuParamSetSize, * ::cuParamSetf, * ::cuParamSeti, * ::cuLaunch, * ::cuLaunchGrid, * ::cuLaunchGridAsync, * ::cuLaunchKernel */ __CUDA_DEPRECATED CUresult CUDAAPI cuParamSetv(CUfunction hfunc, int offset, void *ptr, unsigned int numbytes); /** * \brief Launches a CUDA function * * \deprecated * * Invokes the kernel \p f on a 1 x 1 x 1 grid of blocks. The block * contains the number of threads specified by a previous call to * ::cuFuncSetBlockShape(). * * The block shape, dynamic shared memory size, and parameter information * must be set using * ::cuFuncSetBlockShape(), * ::cuFuncSetSharedSize(), * ::cuParamSetSize(), * ::cuParamSeti(), * ::cuParamSetf(), and * ::cuParamSetv() * prior to calling this function. * * Launching a function via ::cuLaunchKernel() invalidates the function's * block shape, dynamic shared memory size, and parameter information. After * launching via cuLaunchKernel, this state must be re-initialized prior to * calling this function. Failure to do so results in undefined behavior. * * \param f - Kernel to launch * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_LAUNCH_FAILED, * ::CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, * ::CUDA_ERROR_LAUNCH_TIMEOUT, * ::CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, * ::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED * \notefnerr * * \sa ::cuFuncSetBlockShape, * ::cuFuncSetSharedSize, * ::cuFuncGetAttribute, * ::cuParamSetSize, * ::cuParamSetf, * ::cuParamSeti, * ::cuParamSetv, * ::cuLaunchGrid, * ::cuLaunchGridAsync, * ::cuLaunchKernel */ __CUDA_DEPRECATED CUresult CUDAAPI cuLaunch(CUfunction f); /** * \brief Launches a CUDA function * * \deprecated * * Invokes the kernel \p f on a \p grid_width x \p grid_height grid of * blocks. Each block contains the number of threads specified by a previous * call to ::cuFuncSetBlockShape(). * * The block shape, dynamic shared memory size, and parameter information * must be set using * ::cuFuncSetBlockShape(), * ::cuFuncSetSharedSize(), * ::cuParamSetSize(), * ::cuParamSeti(), * ::cuParamSetf(), and * ::cuParamSetv() * prior to calling this function. * * Launching a function via ::cuLaunchKernel() invalidates the function's * block shape, dynamic shared memory size, and parameter information. After * launching via cuLaunchKernel, this state must be re-initialized prior to * calling this function. Failure to do so results in undefined behavior. * * \param f - Kernel to launch * \param grid_width - Width of grid in blocks * \param grid_height - Height of grid in blocks * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_LAUNCH_FAILED, * ::CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, * ::CUDA_ERROR_LAUNCH_TIMEOUT, * ::CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, * ::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED * \notefnerr * * \sa ::cuFuncSetBlockShape, * ::cuFuncSetSharedSize, * ::cuFuncGetAttribute, * ::cuParamSetSize, * ::cuParamSetf, * ::cuParamSeti, * ::cuParamSetv, * ::cuLaunch, * ::cuLaunchGridAsync, * ::cuLaunchKernel */ __CUDA_DEPRECATED CUresult CUDAAPI cuLaunchGrid(CUfunction f, int grid_width, int grid_height); /** * \brief Launches a CUDA function * * \deprecated * * Invokes the kernel \p f on a \p grid_width x \p grid_height grid of * blocks. Each block contains the number of threads specified by a previous * call to ::cuFuncSetBlockShape(). * * The block shape, dynamic shared memory size, and parameter information * must be set using * ::cuFuncSetBlockShape(), * ::cuFuncSetSharedSize(), * ::cuParamSetSize(), * ::cuParamSeti(), * ::cuParamSetf(), and * ::cuParamSetv() * prior to calling this function. * * Launching a function via ::cuLaunchKernel() invalidates the function's * block shape, dynamic shared memory size, and parameter information. After * launching via cuLaunchKernel, this state must be re-initialized prior to * calling this function. Failure to do so results in undefined behavior. * * \param f - Kernel to launch * \param grid_width - Width of grid in blocks * \param grid_height - Height of grid in blocks * \param hStream - Stream identifier * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_LAUNCH_FAILED, * ::CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES, * ::CUDA_ERROR_LAUNCH_TIMEOUT, * ::CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING, * ::CUDA_ERROR_SHARED_OBJECT_INIT_FAILED * * \note In certain cases where cubins are created with no ABI (i.e., using \p ptxas \p --abi-compile \p no), * this function may serialize kernel launches. The CUDA driver retains asynchronous behavior by * growing the per-thread stack as needed per launch and not shrinking it afterwards. * * \note_null_stream * \notefnerr * * \sa ::cuFuncSetBlockShape, * ::cuFuncSetSharedSize, * ::cuFuncGetAttribute, * ::cuParamSetSize, * ::cuParamSetf, * ::cuParamSeti, * ::cuParamSetv, * ::cuLaunch, * ::cuLaunchGrid, * ::cuLaunchKernel */ __CUDA_DEPRECATED CUresult CUDAAPI cuLaunchGridAsync(CUfunction f, int grid_width, int grid_height, CUstream hStream); /** * \brief Adds a texture-reference to the function's argument list * * \deprecated * * Makes the CUDA array or linear memory bound to the texture reference * \p hTexRef available to a device program as a texture. In this version of * CUDA, the texture-reference must be obtained via ::cuModuleGetTexRef() and * the \p texunit parameter must be set to ::CU_PARAM_TR_DEFAULT. * * \param hfunc - Kernel to add texture-reference to * \param texunit - Texture unit (must be ::CU_PARAM_TR_DEFAULT) * \param hTexRef - Texture-reference to add to argument list * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr */ __CUDA_DEPRECATED CUresult CUDAAPI cuParamSetTexRef(CUfunction hfunc, int texunit, CUtexref hTexRef); /** @} */ /* END CUDA_EXEC_DEPRECATED */ /** * \defgroup CUDA_GRAPH Graph Management * * ___MANBRIEF___ graph management functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the graph management functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Creates a graph * * Creates an empty graph, which is returned via \p phGraph. * * \param phGraph - Returns newly created graph * \param flags - Graph creation flags, must be 0 * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddKernelNode, * ::cuGraphAddHostNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode, * ::cuGraphInstantiate, * ::cuGraphDestroy, * ::cuGraphGetNodes, * ::cuGraphGetRootNodes, * ::cuGraphGetEdges, * ::cuGraphClone */ CUresult CUDAAPI cuGraphCreate(CUgraph *phGraph, unsigned int flags); /** * \brief Creates a kernel execution node and adds it to a graph * * Creates a new kernel execution node and adds it to \p hGraph with \p numDependencies * dependencies specified via \p dependencies and arguments specified in \p nodeParams. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. * A handle to the new node will be returned in \p phGraphNode. * * The CUDA_KERNEL_NODE_PARAMS structure is defined as: * * \code * typedef struct CUDA_KERNEL_NODE_PARAMS_st { * CUfunction func; * unsigned int gridDimX; * unsigned int gridDimY; * unsigned int gridDimZ; * unsigned int blockDimX; * unsigned int blockDimY; * unsigned int blockDimZ; * unsigned int sharedMemBytes; * void **kernelParams; * void **extra; * } CUDA_KERNEL_NODE_PARAMS; * \endcode * * When the graph is launched, the node will invoke kernel \p func on a (\p gridDimX x * \p gridDimY x \p gridDimZ) grid of blocks. Each block contains * (\p blockDimX x \p blockDimY x \p blockDimZ) threads. * * \p sharedMemBytes sets the amount of dynamic shared memory that will be * available to each thread block. * * Kernel parameters to \p func can be specified in one of two ways: * * 1) Kernel parameters can be specified via \p kernelParams. If the kernel has N * parameters, then \p kernelParams needs to be an array of N pointers. Each pointer, * from \p kernelParams[0] to \p kernelParams[N-1], points to the region of memory from which the actual * parameter will be copied. The number of kernel parameters and their offsets and sizes do not need * to be specified as that information is retrieved directly from the kernel's image. * * 2) Kernel parameters for non-cooperative kernels can also be packaged by the application into a single * buffer that is passed in via \p extra. This places the burden on the application of knowing each * kernel parameter's size and alignment/padding within the buffer. The \p extra parameter exists * to allow this function to take additional less commonly used arguments. \p extra specifies * a list of names of extra settings and their corresponding values. Each extra setting name is * immediately followed by the corresponding value. The list must be terminated with either NULL or * CU_LAUNCH_PARAM_END. * * - ::CU_LAUNCH_PARAM_END, which indicates the end of the \p extra * array; * - ::CU_LAUNCH_PARAM_BUFFER_POINTER, which specifies that the next * value in \p extra will be a pointer to a buffer * containing all the kernel parameters for launching kernel * \p func; * - ::CU_LAUNCH_PARAM_BUFFER_SIZE, which specifies that the next * value in \p extra will be a pointer to a size_t * containing the size of the buffer specified with * ::CU_LAUNCH_PARAM_BUFFER_POINTER; * * The error ::CUDA_ERROR_INVALID_VALUE will be returned if kernel parameters are specified with both * \p kernelParams and \p extra (i.e. both \p kernelParams and \p extra are non-NULL). * ::CUDA_ERROR_INVALID_VALUE will be returned if \p extra is used for a cooperative kernel. * * The \p kernelParams or \p extra array, as well as the argument values it points to, * are copied during this call. * * \note Kernels launched using graphs must not use texture and surface references. Reading or * writing through any texture or surface reference is undefined behavior. * This restriction does not apply to texture and surface objects. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param nodeParams - Parameters for the GPU execution node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuLaunchKernel, * ::cuLaunchCooperativeKernel, * ::cuGraphKernelNodeGetParams, * ::cuGraphKernelNodeSetParams, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddHostNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode */ CUresult CUDAAPI cuGraphAddKernelNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, const CUDA_KERNEL_NODE_PARAMS *nodeParams); /** * \brief Returns a kernel node's parameters * * Returns the parameters of kernel node \p hNode in \p nodeParams. * The \p kernelParams or \p extra array returned in \p nodeParams, * as well as the argument values it points to, are owned by the node. * This memory remains valid until the node is destroyed or its * parameters are modified, and should not be modified * directly. Use ::cuGraphKernelNodeSetParams to update the * parameters of this node. * * The params will contain either \p kernelParams or \p extra, * according to which of these was most recently set on the node. * * \param hNode - Node to get the parameters for * \param nodeParams - Pointer to return the parameters * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuLaunchKernel, * ::cuGraphAddKernelNode, * ::cuGraphKernelNodeSetParams */ CUresult CUDAAPI cuGraphKernelNodeGetParams(CUgraphNode hNode, CUDA_KERNEL_NODE_PARAMS *nodeParams); /** * \brief Sets a kernel node's parameters * * Sets the parameters of kernel node \p hNode to \p nodeParams. * * \param hNode - Node to set the parameters for * \param nodeParams - Parameters to copy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_OUT_OF_MEMORY * \note_graph_thread_safety * \notefnerr * * \sa * ::cuLaunchKernel, * ::cuGraphAddKernelNode, * ::cuGraphKernelNodeGetParams */ CUresult CUDAAPI cuGraphKernelNodeSetParams(CUgraphNode hNode, const CUDA_KERNEL_NODE_PARAMS *nodeParams); /** * \brief Creates a memcpy node and adds it to a graph * * Creates a new memcpy node and adds it to \p hGraph with \p numDependencies * dependencies specified via \p dependencies. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. * A handle to the new node will be returned in \p phGraphNode. * * When the graph is launched, the node will perform the memcpy described by \p copyParams. * See ::cuMemcpy3D() for a description of the structure and its restrictions. * * Memcpy nodes have some additional restrictions with regards to managed memory, if the * system contains at least one device which has a zero value for the device attribute * ::CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS. If one or more of the operands refer * to managed memory, then using the memory type ::CU_MEMORYTYPE_UNIFIED is disallowed * for those operand(s). The managed memory will be treated as residing on either the * host or the device, depending on which memory type is specified. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param copyParams - Parameters for the memory copy * \param ctx - Context on which to run the node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuMemcpy3D, * ::cuGraphMemcpyNodeGetParams, * ::cuGraphMemcpyNodeSetParams, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddKernelNode, * ::cuGraphAddHostNode, * ::cuGraphAddMemsetNode */ CUresult CUDAAPI cuGraphAddMemcpyNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, const CUDA_MEMCPY3D *copyParams, CUcontext ctx); /** * \brief Returns a memcpy node's parameters * * Returns the parameters of memcpy node \p hNode in \p nodeParams. * * \param hNode - Node to get the parameters for * \param nodeParams - Pointer to return the parameters * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuMemcpy3D, * ::cuGraphAddMemcpyNode, * ::cuGraphMemcpyNodeSetParams */ CUresult CUDAAPI cuGraphMemcpyNodeGetParams(CUgraphNode hNode, CUDA_MEMCPY3D *nodeParams); /** * \brief Sets a memcpy node's parameters * * Sets the parameters of memcpy node \p hNode to \p nodeParams. * * \param hNode - Node to set the parameters for * \param nodeParams - Parameters to copy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuMemcpy3D, * ::cuGraphAddMemcpyNode, * ::cuGraphMemcpyNodeGetParams */ CUresult CUDAAPI cuGraphMemcpyNodeSetParams(CUgraphNode hNode, const CUDA_MEMCPY3D *nodeParams); /** * \brief Creates a memset node and adds it to a graph * * Creates a new memset node and adds it to \p hGraph with \p numDependencies * dependencies specified via \p dependencies. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. * A handle to the new node will be returned in \p phGraphNode. * * The element size must be 1, 2, or 4 bytes. * When the graph is launched, the node will perform the memset described by \p memsetParams. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param memsetParams - Parameters for the memory set * \param ctx - Context on which to run the node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_CONTEXT * \note_graph_thread_safety * \notefnerr * * \sa * ::cuMemsetD2D32, * ::cuGraphMemsetNodeGetParams, * ::cuGraphMemsetNodeSetParams, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddKernelNode, * ::cuGraphAddHostNode, * ::cuGraphAddMemcpyNode */ CUresult CUDAAPI cuGraphAddMemsetNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, const CUDA_MEMSET_NODE_PARAMS *memsetParams, CUcontext ctx); /** * \brief Returns a memset node's parameters * * Returns the parameters of memset node \p hNode in \p nodeParams. * * \param hNode - Node to get the parameters for * \param nodeParams - Pointer to return the parameters * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuMemsetD2D32, * ::cuGraphAddMemsetNode, * ::cuGraphMemsetNodeSetParams */ CUresult CUDAAPI cuGraphMemsetNodeGetParams(CUgraphNode hNode, CUDA_MEMSET_NODE_PARAMS *nodeParams); /** * \brief Sets a memset node's parameters * * Sets the parameters of memset node \p hNode to \p nodeParams. * * \param hNode - Node to set the parameters for * \param nodeParams - Parameters to copy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuMemsetD2D32, * ::cuGraphAddMemsetNode, * ::cuGraphMemsetNodeGetParams */ CUresult CUDAAPI cuGraphMemsetNodeSetParams(CUgraphNode hNode, const CUDA_MEMSET_NODE_PARAMS *nodeParams); /** * \brief Creates a host execution node and adds it to a graph * * Creates a new CPU execution node and adds it to \p hGraph with \p numDependencies * dependencies specified via \p dependencies and arguments specified in \p nodeParams. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. * A handle to the new node will be returned in \p phGraphNode. * * When the graph is launched, the node will invoke the specified CPU function. * Host nodes are not supported under MPS with pre-Volta GPUs. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param nodeParams - Parameters for the host node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuLaunchHostFunc, * ::cuGraphHostNodeGetParams, * ::cuGraphHostNodeSetParams, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddKernelNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode */ CUresult CUDAAPI cuGraphAddHostNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, const CUDA_HOST_NODE_PARAMS *nodeParams); /** * \brief Returns a host node's parameters * * Returns the parameters of host node \p hNode in \p nodeParams. * * \param hNode - Node to get the parameters for * \param nodeParams - Pointer to return the parameters * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuLaunchHostFunc, * ::cuGraphAddHostNode, * ::cuGraphHostNodeSetParams */ CUresult CUDAAPI cuGraphHostNodeGetParams(CUgraphNode hNode, CUDA_HOST_NODE_PARAMS *nodeParams); /** * \brief Sets a host node's parameters * * Sets the parameters of host node \p hNode to \p nodeParams. * * \param hNode - Node to set the parameters for * \param nodeParams - Parameters to copy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuLaunchHostFunc, * ::cuGraphAddHostNode, * ::cuGraphHostNodeGetParams */ CUresult CUDAAPI cuGraphHostNodeSetParams(CUgraphNode hNode, const CUDA_HOST_NODE_PARAMS *nodeParams); /** * \brief Creates a child graph node and adds it to a graph * * Creates a new node which executes an embedded graph, and adds it to \p hGraph with * \p numDependencies dependencies specified via \p dependencies. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. * A handle to the new node will be returned in \p phGraphNode. * * If \p hGraph contains allocation or free nodes, this call will return an error. * * The node executes an embedded child graph. The child graph is cloned in this call. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param childGraph - The graph to clone into this node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphChildGraphNodeGetGraph, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddKernelNode, * ::cuGraphAddHostNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode, * ::cuGraphClone */ CUresult CUDAAPI cuGraphAddChildGraphNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, CUgraph childGraph); /** * \brief Gets a handle to the embedded graph of a child graph node * * Gets a handle to the embedded graph in a child graph node. This call * does not clone the graph. Changes to the graph will be reflected in * the node, and the node retains ownership of the graph. * * Allocation and free nodes cannot be added to the returned graph. * Attempting to do so will return an error. * * \param hNode - Node to get the embedded graph for * \param phGraph - Location to store a handle to the graph * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddChildGraphNode, * ::cuGraphNodeFindInClone */ CUresult CUDAAPI cuGraphChildGraphNodeGetGraph(CUgraphNode hNode, CUgraph *phGraph); /** * \brief Creates an empty node and adds it to a graph * * Creates a new node which performs no operation, and adds it to \p hGraph with * \p numDependencies dependencies specified via \p dependencies. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. * A handle to the new node will be returned in \p phGraphNode. * * An empty node performs no operation during execution, but can be used for * transitive ordering. For example, a phased execution graph with 2 groups of n * nodes with a barrier between them can be represented using an empty node and * 2*n dependency edges, rather than no empty node and n^2 dependency edges. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddKernelNode, * ::cuGraphAddHostNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode */ CUresult CUDAAPI cuGraphAddEmptyNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies); /** * \brief Creates an event record node and adds it to a graph * * Creates a new event record node and adds it to \p hGraph with \p numDependencies * dependencies specified via \p dependencies and event specified in \p event. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. * A handle to the new node will be returned in \p phGraphNode. * * Each launch of the graph will record \p event to capture execution of the * node's dependencies. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param event - Event for the node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddEventWaitNode, * ::cuEventRecordWithFlags, * ::cuStreamWaitEvent, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddKernelNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode, */ CUresult CUDAAPI cuGraphAddEventRecordNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, CUevent event); /** * \brief Returns the event associated with an event record node * * Returns the event of event record node \p hNode in \p event_out. * * \param hNode - Node to get the event for * \param event_out - Pointer to return the event * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddEventRecordNode, * ::cuGraphEventRecordNodeSetEvent, * ::cuGraphEventWaitNodeGetEvent, * ::cuEventRecordWithFlags, * ::cuStreamWaitEvent */ CUresult CUDAAPI cuGraphEventRecordNodeGetEvent(CUgraphNode hNode, CUevent *event_out); /** * \brief Sets an event record node's event * * Sets the event of event record node \p hNode to \p event. * * \param hNode - Node to set the event for * \param event - Event to use * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_OUT_OF_MEMORY * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddEventRecordNode, * ::cuGraphEventRecordNodeGetEvent, * ::cuGraphEventWaitNodeSetEvent, * ::cuEventRecordWithFlags, * ::cuStreamWaitEvent */ CUresult CUDAAPI cuGraphEventRecordNodeSetEvent(CUgraphNode hNode, CUevent event); /** * \brief Creates an event wait node and adds it to a graph * * Creates a new event wait node and adds it to \p hGraph with \p numDependencies * dependencies specified via \p dependencies and event specified in \p event. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. * A handle to the new node will be returned in \p phGraphNode. * * The graph node will wait for all work captured in \p event. See ::cuEventRecord() * for details on what is captured by an event. \p event may be from a different context * or device than the launch stream. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param event - Event for the node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddEventRecordNode, * ::cuEventRecordWithFlags, * ::cuStreamWaitEvent, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddKernelNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode, */ CUresult CUDAAPI cuGraphAddEventWaitNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, CUevent event); /** * \brief Returns the event associated with an event wait node * * Returns the event of event wait node \p hNode in \p event_out. * * \param hNode - Node to get the event for * \param event_out - Pointer to return the event * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddEventWaitNode, * ::cuGraphEventWaitNodeSetEvent, * ::cuGraphEventRecordNodeGetEvent, * ::cuEventRecordWithFlags, * ::cuStreamWaitEvent */ CUresult CUDAAPI cuGraphEventWaitNodeGetEvent(CUgraphNode hNode, CUevent *event_out); /** * \brief Sets an event wait node's event * * Sets the event of event wait node \p hNode to \p event. * * \param hNode - Node to set the event for * \param event - Event to use * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_OUT_OF_MEMORY * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddEventWaitNode, * ::cuGraphEventWaitNodeGetEvent, * ::cuGraphEventRecordNodeSetEvent, * ::cuEventRecordWithFlags, * ::cuStreamWaitEvent */ CUresult CUDAAPI cuGraphEventWaitNodeSetEvent(CUgraphNode hNode, CUevent event); /** * \brief Creates an external semaphore signal node and adds it to a graph * * Creates a new external semaphore signal node and adds it to \p hGraph with \p * numDependencies dependencies specified via \p dependencies and arguments specified * in \p nodeParams. It is possible for \p numDependencies to be 0, in which case the * node will be placed at the root of the graph. \p dependencies may not have any * duplicate entries. A handle to the new node will be returned in \p phGraphNode. * * Performs a signal operation on a set of externally allocated semaphore objects * when the node is launched. The operation(s) will occur after all of the node's * dependencies have completed. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param nodeParams - Parameters for the node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphExternalSemaphoresSignalNodeGetParams, * ::cuGraphExternalSemaphoresSignalNodeSetParams, * ::cuGraphExecExternalSemaphoresSignalNodeSetParams, * ::cuGraphAddExternalSemaphoresWaitNode, * ::cuImportExternalSemaphore, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddEventRecordNode, * ::cuGraphAddEventWaitNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddKernelNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode, */ CUresult CUDAAPI cuGraphAddExternalSemaphoresSignalNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, const CUDA_EXT_SEM_SIGNAL_NODE_PARAMS *nodeParams); /** * \brief Returns an external semaphore signal node's parameters * * Returns the parameters of an external semaphore signal node \p hNode in \p params_out. * The \p extSemArray and \p paramsArray returned in \p params_out, * are owned by the node. This memory remains valid until the node is destroyed or its * parameters are modified, and should not be modified * directly. Use ::cuGraphExternalSemaphoresSignalNodeSetParams to update the * parameters of this node. * * \param hNode - Node to get the parameters for * \param params_out - Pointer to return the parameters * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuLaunchKernel, * ::cuGraphAddExternalSemaphoresSignalNode, * ::cuGraphExternalSemaphoresSignalNodeSetParams, * ::cuGraphAddExternalSemaphoresWaitNode, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync */ CUresult CUDAAPI cuGraphExternalSemaphoresSignalNodeGetParams(CUgraphNode hNode, CUDA_EXT_SEM_SIGNAL_NODE_PARAMS *params_out); /** * \brief Sets an external semaphore signal node's parameters * * Sets the parameters of an external semaphore signal node \p hNode to \p nodeParams. * * \param hNode - Node to set the parameters for * \param nodeParams - Parameters to copy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_OUT_OF_MEMORY * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddExternalSemaphoresSignalNode, * ::cuGraphExternalSemaphoresSignalNodeSetParams, * ::cuGraphAddExternalSemaphoresWaitNode, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync */ CUresult CUDAAPI cuGraphExternalSemaphoresSignalNodeSetParams(CUgraphNode hNode, const CUDA_EXT_SEM_SIGNAL_NODE_PARAMS *nodeParams); /** * \brief Creates an external semaphore wait node and adds it to a graph * * Creates a new external semaphore wait node and adds it to \p hGraph with \p numDependencies * dependencies specified via \p dependencies and arguments specified in \p nodeParams. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. A handle * to the new node will be returned in \p phGraphNode. * * Performs a wait operation on a set of externally allocated semaphore objects * when the node is launched. The node's dependencies will not be launched until * the wait operation has completed. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param nodeParams - Parameters for the node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphExternalSemaphoresWaitNodeGetParams, * ::cuGraphExternalSemaphoresWaitNodeSetParams, * ::cuGraphExecExternalSemaphoresWaitNodeSetParams, * ::cuGraphAddExternalSemaphoresSignalNode, * ::cuImportExternalSemaphore, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddEventRecordNode, * ::cuGraphAddEventWaitNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddKernelNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode, */ CUresult CUDAAPI cuGraphAddExternalSemaphoresWaitNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, const CUDA_EXT_SEM_WAIT_NODE_PARAMS *nodeParams); /** * \brief Returns an external semaphore wait node's parameters * * Returns the parameters of an external semaphore wait node \p hNode in \p params_out. * The \p extSemArray and \p paramsArray returned in \p params_out, * are owned by the node. This memory remains valid until the node is destroyed or its * parameters are modified, and should not be modified * directly. Use ::cuGraphExternalSemaphoresSignalNodeSetParams to update the * parameters of this node. * * \param hNode - Node to get the parameters for * \param params_out - Pointer to return the parameters * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuLaunchKernel, * ::cuGraphAddExternalSemaphoresWaitNode, * ::cuGraphExternalSemaphoresWaitNodeSetParams, * ::cuGraphAddExternalSemaphoresWaitNode, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync */ CUresult CUDAAPI cuGraphExternalSemaphoresWaitNodeGetParams(CUgraphNode hNode, CUDA_EXT_SEM_WAIT_NODE_PARAMS *params_out); /** * \brief Sets an external semaphore wait node's parameters * * Sets the parameters of an external semaphore wait node \p hNode to \p nodeParams. * * \param hNode - Node to set the parameters for * \param nodeParams - Parameters to copy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_OUT_OF_MEMORY * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddExternalSemaphoresWaitNode, * ::cuGraphExternalSemaphoresWaitNodeSetParams, * ::cuGraphAddExternalSemaphoresWaitNode, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync */ CUresult CUDAAPI cuGraphExternalSemaphoresWaitNodeSetParams(CUgraphNode hNode, const CUDA_EXT_SEM_WAIT_NODE_PARAMS *nodeParams); /** * \brief Creates an allocation node and adds it to a graph * * Creates a new allocation node and adds it to \p hGraph with \p numDependencies * dependencies specified via \p dependencies and arguments specified in \p nodeParams. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. A handle * to the new node will be returned in \p phGraphNode. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param nodeParams - Parameters for the node * * When ::cuGraphAddMemAllocNode creates an allocation node, it returns the address of the allocation in * \p nodeParams.dptr. The allocation's address remains fixed across instantiations and launches. * * If the allocation is freed in the same graph, by creating a free node using ::cuGraphAddMemFreeNode, * the allocation can be accessed by nodes ordered after the allocation node but before the free node. * These allocations cannot be freed outside the owning graph, and they can only be freed once in the * owning graph. * * If the allocation is not freed in the same graph, then it can be accessed not only by nodes in the * graph which are ordered after the allocation node, but also by stream operations ordered after the * graph's execution but before the allocation is freed. * * Allocations which are not freed in the same graph can be freed by: * - passing the allocation to ::cuMemFreeAsync or ::cuMemFree; * - launching a graph with a free node for that allocation; or * - specifying ::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH during instantiation, which makes * each launch behave as though it called ::cuMemFreeAsync for every unfreed allocation. * * It is not possible to free an allocation in both the owning graph and another graph. If the allocation * is freed in the same graph, a free node cannot be added to another graph. If the allocation is freed * in another graph, a free node can no longer be added to the owning graph. * * The following restrictions apply to graphs which contain allocation and/or memory free nodes: * - Nodes and edges of the graph cannot be deleted. * - The graph cannot be used in a child node. * - Only one instantiation of the graph may exist at any point in time. * - The graph cannot be cloned. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddMemFreeNode, * ::cuGraphMemAllocNodeGetParams, * ::cuDeviceGraphMemTrim, * ::cuDeviceGetGraphMemAttribute, * ::cuDeviceSetGraphMemAttribute, * ::cuMemAllocAsync, * ::cuMemFreeAsync, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddEventRecordNode, * ::cuGraphAddEventWaitNode, * ::cuGraphAddExternalSemaphoresSignalNode, * ::cuGraphAddExternalSemaphoresWaitNode, * ::cuGraphAddKernelNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode */ CUresult CUDAAPI cuGraphAddMemAllocNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, CUDA_MEM_ALLOC_NODE_PARAMS *nodeParams); /** * \brief Returns a memory alloc node's parameters * * Returns the parameters of a memory alloc node \p hNode in \p params_out. * The \p poolProps and \p accessDescs returned in \p params_out, are owned by the * node. This memory remains valid until the node is destroyed. The returned * parameters must not be modified. * * \param hNode - Node to get the parameters for * \param params_out - Pointer to return the parameters * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddMemAllocNode, * ::cuGraphMemFreeNodeGetParams */ CUresult CUDAAPI cuGraphMemAllocNodeGetParams(CUgraphNode hNode, CUDA_MEM_ALLOC_NODE_PARAMS *params_out); /** * \brief Creates a memory free node and adds it to a graph * * Creates a new memory free node and adds it to \p hGraph with \p numDependencies * dependencies specified via \p dependencies and arguments specified in \p nodeParams. * It is possible for \p numDependencies to be 0, in which case the node will be placed * at the root of the graph. \p dependencies may not have any duplicate entries. A handle * to the new node will be returned in \p phGraphNode. * * \param phGraphNode - Returns newly created node * \param hGraph - Graph to which to add the node * \param dependencies - Dependencies of the node * \param numDependencies - Number of dependencies * \param dptr - Address of memory to free * * ::cuGraphAddMemFreeNode will return ::CUDA_ERROR_INVALID_VALUE if the user attempts to free: * - an allocation twice in the same graph. * - an address that was not returned by an allocation node. * - an invalid address. * * The following restrictions apply to graphs which contain allocation and/or memory free nodes: * - Nodes and edges of the graph cannot be deleted. * - The graph cannot be used in a child node. * - Only one instantiation of the graph may exist at any point in time. * - The graph cannot be cloned. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddMemAllocNode, * ::cuGraphMemFreeNodeGetParams, * ::cuDeviceGraphMemTrim, * ::cuDeviceGetGraphMemAttribute, * ::cuDeviceSetGraphMemAttribute, * ::cuMemAllocAsync, * ::cuMemFreeAsync, * ::cuGraphCreate, * ::cuGraphDestroyNode, * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddEventRecordNode, * ::cuGraphAddEventWaitNode, * ::cuGraphAddExternalSemaphoresSignalNode, * ::cuGraphAddExternalSemaphoresWaitNode, * ::cuGraphAddKernelNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode */ CUresult CUDAAPI cuGraphAddMemFreeNode(CUgraphNode *phGraphNode, CUgraph hGraph, const CUgraphNode *dependencies, size_t numDependencies, CUdeviceptr dptr); /** * \brief Returns a memory free node's parameters * * Returns the address of a memory free node \p hNode in \p dptr_out. * * \param hNode - Node to get the parameters for * \param dptr_out - Pointer to return the device address * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddMemFreeNode, * ::cuGraphMemAllocNodeGetParams */ CUresult CUDAAPI cuGraphMemFreeNodeGetParams(CUgraphNode hNode, CUdeviceptr *dptr_out); /** * \brief Free unused memory that was cached on the specified device for use with graphs back to the OS. * * Blocks which are not in use by a graph that is either currently executing or scheduled to execute are * freed back to the operating system. * * \param device - The device for which cached memory should be freed. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_DEVICE * * \sa * ::cuGraphAddMemAllocNode, * ::cuGraphAddMemFreeNode, * ::cuDeviceSetGraphMemAttribute, * ::cuDeviceGetGraphMemAttribute */ CUresult CUDAAPI cuDeviceGraphMemTrim(CUdevice device); /** * \brief Query asynchronous allocation attributes related to graphs * * Valid attributes are: * * - ::CU_GRAPH_MEM_ATTR_USED_MEM_CURRENT: Amount of memory, in bytes, currently associated with graphs * - ::CU_GRAPH_MEM_ATTR_USED_MEM_HIGH: High watermark of memory, in bytes, associated with graphs since the * last time it was reset. High watermark can only be reset to zero. * - ::CU_GRAPH_MEM_ATTR_RESERVED_MEM_CURRENT: Amount of memory, in bytes, currently allocated for use by * the CUDA graphs asynchronous allocator. * - ::CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH: High watermark of memory, in bytes, currently allocated for use by * the CUDA graphs asynchronous allocator. * * \param device - Specifies the scope of the query * \param attr - attribute to get * \param value - retrieved value * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_DEVICE * * \sa * ::cuDeviceSetGraphMemAttribute, * ::cuGraphAddMemAllocNode, * ::cuGraphAddMemFreeNode */ CUresult CUDAAPI cuDeviceGetGraphMemAttribute(CUdevice device, CUgraphMem_attribute attr, void* value); /** * \brief Set asynchronous allocation attributes related to graphs * * Valid attributes are: * * - ::CU_GRAPH_MEM_ATTR_USED_MEM_HIGH: High watermark of memory, in bytes, associated with graphs since the * last time it was reset. High watermark can only be reset to zero. * - ::CU_GRAPH_MEM_ATTR_RESERVED_MEM_HIGH: High watermark of memory, in bytes, currently allocated for use by * the CUDA graphs asynchronous allocator. * * \param device - Specifies the scope of the query * \param attr - attribute to get * \param value - pointer to value to set * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_DEVICE * * \sa * ::cuDeviceGetGraphMemAttribute, * ::cuGraphAddMemAllocNode, * ::cuGraphAddMemFreeNode */ CUresult CUDAAPI cuDeviceSetGraphMemAttribute(CUdevice device, CUgraphMem_attribute attr, void* value); /** * \brief Clones a graph * * This function creates a copy of \p originalGraph and returns it in \p phGraphClone. * All parameters are copied into the cloned graph. The original graph may be modified * after this call without affecting the clone. * * Child graph nodes in the original graph are recursively copied into the clone. * * \param phGraphClone - Returns newly created cloned graph * \param originalGraph - Graph to clone * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OUT_OF_MEMORY * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphCreate, * ::cuGraphNodeFindInClone */ CUresult CUDAAPI cuGraphClone(CUgraph *phGraphClone, CUgraph originalGraph); /** * \brief Finds a cloned version of a node * * This function returns the node in \p hClonedGraph corresponding to \p hOriginalNode * in the original graph. * * \p hClonedGraph must have been cloned from \p hOriginalGraph via ::cuGraphClone. * \p hOriginalNode must have been in \p hOriginalGraph at the time of the call to * ::cuGraphClone, and the corresponding cloned node in \p hClonedGraph must not have * been removed. The cloned node is then returned via \p phClonedNode. * * \param phNode - Returns handle to the cloned node * \param hOriginalNode - Handle to the original node * \param hClonedGraph - Cloned graph to query * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphClone */ CUresult CUDAAPI cuGraphNodeFindInClone(CUgraphNode *phNode, CUgraphNode hOriginalNode, CUgraph hClonedGraph); /** * \brief Returns a node's type * * Returns the node type of \p hNode in \p type. * * \param hNode - Node to query * \param type - Pointer to return the node type * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphGetNodes, * ::cuGraphGetRootNodes, * ::cuGraphChildGraphNodeGetGraph, * ::cuGraphKernelNodeGetParams, * ::cuGraphKernelNodeSetParams, * ::cuGraphHostNodeGetParams, * ::cuGraphHostNodeSetParams, * ::cuGraphMemcpyNodeGetParams, * ::cuGraphMemcpyNodeSetParams, * ::cuGraphMemsetNodeGetParams, * ::cuGraphMemsetNodeSetParams */ CUresult CUDAAPI cuGraphNodeGetType(CUgraphNode hNode, CUgraphNodeType *type); /** * \brief Returns a graph's nodes * * Returns a list of \p hGraph's nodes. \p nodes may be NULL, in which case this * function will return the number of nodes in \p numNodes. Otherwise, * \p numNodes entries will be filled in. If \p numNodes is higher than the actual * number of nodes, the remaining entries in \p nodes will be set to NULL, and the * number of nodes actually obtained will be returned in \p numNodes. * * \param hGraph - Graph to query * \param nodes - Pointer to return the nodes * \param numNodes - See description * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphCreate, * ::cuGraphGetRootNodes, * ::cuGraphGetEdges, * ::cuGraphNodeGetType, * ::cuGraphNodeGetDependencies, * ::cuGraphNodeGetDependentNodes */ CUresult CUDAAPI cuGraphGetNodes(CUgraph hGraph, CUgraphNode *nodes, size_t *numNodes); /** * \brief Returns a graph's root nodes * * Returns a list of \p hGraph's root nodes. \p rootNodes may be NULL, in which case this * function will return the number of root nodes in \p numRootNodes. Otherwise, * \p numRootNodes entries will be filled in. If \p numRootNodes is higher than the actual * number of root nodes, the remaining entries in \p rootNodes will be set to NULL, and the * number of nodes actually obtained will be returned in \p numRootNodes. * * \param hGraph - Graph to query * \param rootNodes - Pointer to return the root nodes * \param numRootNodes - See description * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphCreate, * ::cuGraphGetNodes, * ::cuGraphGetEdges, * ::cuGraphNodeGetType, * ::cuGraphNodeGetDependencies, * ::cuGraphNodeGetDependentNodes */ CUresult CUDAAPI cuGraphGetRootNodes(CUgraph hGraph, CUgraphNode *rootNodes, size_t *numRootNodes); /** * \brief Returns a graph's dependency edges * * Returns a list of \p hGraph's dependency edges. Edges are returned via corresponding * indices in \p from and \p to; that is, the node in \p to[i] has a dependency on the * node in \p from[i]. \p from and \p to may both be NULL, in which * case this function only returns the number of edges in \p numEdges. Otherwise, * \p numEdges entries will be filled in. If \p numEdges is higher than the actual * number of edges, the remaining entries in \p from and \p to will be set to NULL, and * the number of edges actually returned will be written to \p numEdges. * * \param hGraph - Graph to get the edges from * \param from - Location to return edge endpoints * \param to - Location to return edge endpoints * \param numEdges - See description * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphGetNodes, * ::cuGraphGetRootNodes, * ::cuGraphAddDependencies, * ::cuGraphRemoveDependencies, * ::cuGraphNodeGetDependencies, * ::cuGraphNodeGetDependentNodes */ CUresult CUDAAPI cuGraphGetEdges(CUgraph hGraph, CUgraphNode *from, CUgraphNode *to, size_t *numEdges); /** * \brief Returns a node's dependencies * * Returns a list of \p node's dependencies. \p dependencies may be NULL, in which case this * function will return the number of dependencies in \p numDependencies. Otherwise, * \p numDependencies entries will be filled in. If \p numDependencies is higher than the actual * number of dependencies, the remaining entries in \p dependencies will be set to NULL, and the * number of nodes actually obtained will be returned in \p numDependencies. * * \param hNode - Node to query * \param dependencies - Pointer to return the dependencies * \param numDependencies - See description * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphNodeGetDependentNodes, * ::cuGraphGetNodes, * ::cuGraphGetRootNodes, * ::cuGraphGetEdges, * ::cuGraphAddDependencies, * ::cuGraphRemoveDependencies */ CUresult CUDAAPI cuGraphNodeGetDependencies(CUgraphNode hNode, CUgraphNode *dependencies, size_t *numDependencies); /** * \brief Returns a node's dependent nodes * * Returns a list of \p node's dependent nodes. \p dependentNodes may be NULL, in which * case this function will return the number of dependent nodes in \p numDependentNodes. * Otherwise, \p numDependentNodes entries will be filled in. If \p numDependentNodes is * higher than the actual number of dependent nodes, the remaining entries in * \p dependentNodes will be set to NULL, and the number of nodes actually obtained will * be returned in \p numDependentNodes. * * \param hNode - Node to query * \param dependentNodes - Pointer to return the dependent nodes * \param numDependentNodes - See description * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphNodeGetDependencies, * ::cuGraphGetNodes, * ::cuGraphGetRootNodes, * ::cuGraphGetEdges, * ::cuGraphAddDependencies, * ::cuGraphRemoveDependencies */ CUresult CUDAAPI cuGraphNodeGetDependentNodes(CUgraphNode hNode, CUgraphNode *dependentNodes, size_t *numDependentNodes); /** * \brief Adds dependency edges to a graph * * The number of dependencies to be added is defined by \p numDependencies * Elements in \p from and \p to at corresponding indices define a dependency. * Each node in \p from and \p to must belong to \p hGraph. * * If \p numDependencies is 0, elements in \p from and \p to will be ignored. * Specifying an existing dependency will return an error. * * \param hGraph - Graph to which dependencies are added * \param from - Array of nodes that provide the dependencies * \param to - Array of dependent nodes * \param numDependencies - Number of dependencies to be added * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphRemoveDependencies, * ::cuGraphGetEdges, * ::cuGraphNodeGetDependencies, * ::cuGraphNodeGetDependentNodes */ CUresult CUDAAPI cuGraphAddDependencies(CUgraph hGraph, const CUgraphNode *from, const CUgraphNode *to, size_t numDependencies); /** * \brief Removes dependency edges from a graph * * The number of \p dependencies to be removed is defined by \p numDependencies. * Elements in \p from and \p to at corresponding indices define a dependency. * Each node in \p from and \p to must belong to \p hGraph. * * If \p numDependencies is 0, elements in \p from and \p to will be ignored. * Specifying a non-existing dependency will return an error. * * Dependencies cannot be removed from graphs which contain allocation or free nodes. * Any attempt to do so will return an error. * * \param hGraph - Graph from which to remove dependencies * \param from - Array of nodes that provide the dependencies * \param to - Array of dependent nodes * \param numDependencies - Number of dependencies to be removed * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddDependencies, * ::cuGraphGetEdges, * ::cuGraphNodeGetDependencies, * ::cuGraphNodeGetDependentNodes */ CUresult CUDAAPI cuGraphRemoveDependencies(CUgraph hGraph, const CUgraphNode *from, const CUgraphNode *to, size_t numDependencies); /** * \brief Remove a node from the graph * * Removes \p hNode from its graph. This operation also severs any dependencies of other nodes * on \p hNode and vice versa. * * Nodes which belong to a graph which contains allocation or free nodes cannot be destroyed. * Any attempt to do so will return an error. * * \param hNode - Node to remove * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddChildGraphNode, * ::cuGraphAddEmptyNode, * ::cuGraphAddKernelNode, * ::cuGraphAddHostNode, * ::cuGraphAddMemcpyNode, * ::cuGraphAddMemsetNode */ CUresult CUDAAPI cuGraphDestroyNode(CUgraphNode hNode); /** * \brief Creates an executable graph from a graph * * Instantiates \p hGraph as an executable graph. The graph is validated for any * structural constraints or intra-node constraints which were not previously * validated. If instantiation is successful, a handle to the instantiated graph * is returned in \p phGraphExec. * * If there are any errors, diagnostic information may be returned in \p errorNode and * \p logBuffer. This is the primary way to inspect instantiation errors. The output * will be null terminated unless the diagnostics overflow * the buffer. In this case, they will be truncated, and the last byte can be * inspected to determine if truncation occurred. * * \param phGraphExec - Returns instantiated graph * \param hGraph - Graph to instantiate * \param phErrorNode - In case of an instantiation error, this may be modified to * indicate a node contributing to the error * \param logBuffer - A character buffer to store diagnostic messages * \param bufferSize - Size of the log buffer in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphInstantiateWithFlags, * ::cuGraphCreate, * ::cuGraphUpload, * ::cuGraphLaunch, * ::cuGraphExecDestroy */ CUresult CUDAAPI cuGraphInstantiate(CUgraphExec *phGraphExec, CUgraph hGraph, CUgraphNode *phErrorNode, char *logBuffer, size_t bufferSize); /** * \brief Creates an executable graph from a graph * * Instantiates \p hGraph as an executable graph. The graph is validated for any * structural constraints or intra-node constraints which were not previously * validated. If instantiation is successful, a handle to the instantiated graph * is returned in \p phGraphExec. * * The \p flags parameter controls the behavior of instantiation and subsequent * graph launches. Valid flags are: * * - ::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH, which configures a * graph containing memory allocation nodes to automatically free any * unfreed memory allocations before the graph is relaunched. * * If \p hGraph contains any allocation or free nodes, there can be at most one * executable graph in existence for that graph at a time. * * An attempt to instantiate a second executable graph before destroying the first * with ::cuGraphExecDestroy will result in an error. * * \param phGraphExec - Returns instantiated graph * \param hGraph - Graph to instantiate * \param flags - Flags to control instantiation. See ::CUgraphInstantiate_flags. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphInstantiate, * ::cuGraphCreate, * ::cuGraphUpload, * ::cuGraphLaunch, * ::cuGraphExecDestroy */ CUresult CUDAAPI cuGraphInstantiateWithFlags(CUgraphExec *phGraphExec, CUgraph hGraph, unsigned long long flags); /** * \brief Sets the parameters for a kernel node in the given graphExec * * Sets the parameters of a kernel node in an executable graph \p hGraphExec. * The node is identified by the corresponding node \p hNode in the * non-executable graph, from which the executable graph was instantiated. * * \p hNode must not have been removed from the original graph. All \p nodeParams * fields may change, but the following restrictions apply to \p func updates: * * - The owning context of the function cannot change. * - A node whose function originally did not use CUDA dynamic parallelism cannot be updated * to a function which uses CDP * * The modifications only affect future launches of \p hGraphExec. Already * enqueued or running launches of \p hGraphExec are not affected by this call. * \p hNode is also not modified by this call. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - kernel node from the graph from which graphExec was instantiated * \param nodeParams - Updated Parameters to set * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddKernelNode, * ::cuGraphKernelNodeSetParams, * ::cuGraphExecMemcpyNodeSetParams, * ::cuGraphExecMemsetNodeSetParams, * ::cuGraphExecHostNodeSetParams, * ::cuGraphExecChildGraphNodeSetParams, * ::cuGraphExecEventRecordNodeSetEvent, * ::cuGraphExecEventWaitNodeSetEvent, * ::cuGraphExecExternalSemaphoresSignalNodeSetParams, * ::cuGraphExecExternalSemaphoresWaitNodeSetParams, * ::cuGraphExecUpdate, * ::cuGraphInstantiate */ CUresult CUDAAPI cuGraphExecKernelNodeSetParams(CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_KERNEL_NODE_PARAMS *nodeParams); /** * \brief Sets the parameters for a memcpy node in the given graphExec. * * Updates the work represented by \p hNode in \p hGraphExec as though \p hNode had * contained \p copyParams at instantiation. hNode must remain in the graph which was * used to instantiate \p hGraphExec. Changed edges to and from hNode are ignored. * * The source and destination memory in \p copyParams must be allocated from the same * contexts as the original source and destination memory. Both the instantiation-time * memory operands and the memory operands in \p copyParams must be 1-dimensional. * Zero-length operations are not supported. * * The modifications only affect future launches of \p hGraphExec. Already enqueued * or running launches of \p hGraphExec are not affected by this call. hNode is also * not modified by this call. * * Returns CUDA_ERROR_INVALID_VALUE if the memory operands' mappings changed or * either the original or new memory operands are multidimensional. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - Memcpy node from the graph which was used to instantiate graphExec * \param copyParams - The updated parameters to set * \param ctx - Context on which to run the node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddMemcpyNode, * ::cuGraphMemcpyNodeSetParams, * ::cuGraphExecKernelNodeSetParams, * ::cuGraphExecMemsetNodeSetParams, * ::cuGraphExecHostNodeSetParams, * ::cuGraphExecChildGraphNodeSetParams, * ::cuGraphExecEventRecordNodeSetEvent, * ::cuGraphExecEventWaitNodeSetEvent, * ::cuGraphExecExternalSemaphoresSignalNodeSetParams, * ::cuGraphExecExternalSemaphoresWaitNodeSetParams, * ::cuGraphExecUpdate, * ::cuGraphInstantiate */ CUresult CUDAAPI cuGraphExecMemcpyNodeSetParams(CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_MEMCPY3D *copyParams, CUcontext ctx); /** * \brief Sets the parameters for a memset node in the given graphExec. * * Updates the work represented by \p hNode in \p hGraphExec as though \p hNode had * contained \p memsetParams at instantiation. hNode must remain in the graph which was * used to instantiate \p hGraphExec. Changed edges to and from hNode are ignored. * * The destination memory in \p memsetParams must be allocated from the same * contexts as the original destination memory. Both the instantiation-time * memory operand and the memory operand in \p memsetParams must be 1-dimensional. * Zero-length operations are not supported. * * The modifications only affect future launches of \p hGraphExec. Already enqueued * or running launches of \p hGraphExec are not affected by this call. hNode is also * not modified by this call. * * Returns CUDA_ERROR_INVALID_VALUE if the memory operand's mappings changed or * either the original or new memory operand are multidimensional. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - Memset node from the graph which was used to instantiate graphExec * \param memsetParams - The updated parameters to set * \param ctx - Context on which to run the node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddMemsetNode, * ::cuGraphMemsetNodeSetParams, * ::cuGraphExecKernelNodeSetParams, * ::cuGraphExecMemcpyNodeSetParams, * ::cuGraphExecHostNodeSetParams, * ::cuGraphExecChildGraphNodeSetParams, * ::cuGraphExecEventRecordNodeSetEvent, * ::cuGraphExecEventWaitNodeSetEvent, * ::cuGraphExecExternalSemaphoresSignalNodeSetParams, * ::cuGraphExecExternalSemaphoresWaitNodeSetParams, * ::cuGraphExecUpdate, * ::cuGraphInstantiate */ CUresult CUDAAPI cuGraphExecMemsetNodeSetParams(CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_MEMSET_NODE_PARAMS *memsetParams, CUcontext ctx); /** * \brief Sets the parameters for a host node in the given graphExec. * * Updates the work represented by \p hNode in \p hGraphExec as though \p hNode had * contained \p nodeParams at instantiation. hNode must remain in the graph which was * used to instantiate \p hGraphExec. Changed edges to and from hNode are ignored. * * The modifications only affect future launches of \p hGraphExec. Already enqueued * or running launches of \p hGraphExec are not affected by this call. hNode is also * not modified by this call. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - Host node from the graph which was used to instantiate graphExec * \param nodeParams - The updated parameters to set * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddHostNode, * ::cuGraphHostNodeSetParams, * ::cuGraphExecKernelNodeSetParams, * ::cuGraphExecMemcpyNodeSetParams, * ::cuGraphExecMemsetNodeSetParams, * ::cuGraphExecChildGraphNodeSetParams, * ::cuGraphExecEventRecordNodeSetEvent, * ::cuGraphExecEventWaitNodeSetEvent, * ::cuGraphExecExternalSemaphoresSignalNodeSetParams, * ::cuGraphExecExternalSemaphoresWaitNodeSetParams, * ::cuGraphExecUpdate, * ::cuGraphInstantiate */ CUresult CUDAAPI cuGraphExecHostNodeSetParams(CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_HOST_NODE_PARAMS *nodeParams); /** * \brief Updates node parameters in the child graph node in the given graphExec. * * Updates the work represented by \p hNode in \p hGraphExec as though the nodes contained * in \p hNode's graph had the parameters contained in \p childGraph's nodes at instantiation. * \p hNode must remain in the graph which was used to instantiate \p hGraphExec. * Changed edges to and from \p hNode are ignored. * * The modifications only affect future launches of \p hGraphExec. Already enqueued * or running launches of \p hGraphExec are not affected by this call. \p hNode is also * not modified by this call. * * The topology of \p childGraph, as well as the node insertion order, must match that * of the graph contained in \p hNode. See ::cuGraphExecUpdate() for a list of restrictions * on what can be updated in an instantiated graph. The update is recursive, so child graph * nodes contained within the top level child graph will also be updated. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - Host node from the graph which was used to instantiate graphExec * \param childGraph - The graph supplying the updated parameters * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddChildGraphNode, * ::cuGraphChildGraphNodeGetGraph, * ::cuGraphExecKernelNodeSetParams, * ::cuGraphExecMemcpyNodeSetParams, * ::cuGraphExecMemsetNodeSetParams, * ::cuGraphExecHostNodeSetParams, * ::cuGraphExecEventRecordNodeSetEvent, * ::cuGraphExecEventWaitNodeSetEvent, * ::cuGraphExecExternalSemaphoresSignalNodeSetParams, * ::cuGraphExecExternalSemaphoresWaitNodeSetParams, * ::cuGraphExecUpdate, * ::cuGraphInstantiate */ CUresult CUDAAPI cuGraphExecChildGraphNodeSetParams(CUgraphExec hGraphExec, CUgraphNode hNode, CUgraph childGraph); /** * \brief Sets the event for an event record node in the given graphExec * * Sets the event of an event record node in an executable graph \p hGraphExec. * The node is identified by the corresponding node \p hNode in the * non-executable graph, from which the executable graph was instantiated. * * The modifications only affect future launches of \p hGraphExec. Already * enqueued or running launches of \p hGraphExec are not affected by this call. * \p hNode is also not modified by this call. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - event record node from the graph from which graphExec was instantiated * \param event - Updated event to use * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddEventRecordNode, * ::cuGraphEventRecordNodeGetEvent, * ::cuGraphEventWaitNodeSetEvent, * ::cuEventRecordWithFlags, * ::cuStreamWaitEvent, * ::cuGraphExecKernelNodeSetParams, * ::cuGraphExecMemcpyNodeSetParams, * ::cuGraphExecMemsetNodeSetParams, * ::cuGraphExecHostNodeSetParams, * ::cuGraphExecChildGraphNodeSetParams, * ::cuGraphExecEventWaitNodeSetEvent, * ::cuGraphExecExternalSemaphoresSignalNodeSetParams, * ::cuGraphExecExternalSemaphoresWaitNodeSetParams, * ::cuGraphExecUpdate, * ::cuGraphInstantiate */ CUresult CUDAAPI cuGraphExecEventRecordNodeSetEvent(CUgraphExec hGraphExec, CUgraphNode hNode, CUevent event); /** * \brief Sets the event for an event wait node in the given graphExec * * Sets the event of an event wait node in an executable graph \p hGraphExec. * The node is identified by the corresponding node \p hNode in the * non-executable graph, from which the executable graph was instantiated. * * The modifications only affect future launches of \p hGraphExec. Already * enqueued or running launches of \p hGraphExec are not affected by this call. * \p hNode is also not modified by this call. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - event wait node from the graph from which graphExec was instantiated * \param event - Updated event to use * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddEventWaitNode, * ::cuGraphEventWaitNodeGetEvent, * ::cuGraphEventRecordNodeSetEvent, * ::cuEventRecordWithFlags, * ::cuStreamWaitEvent, * ::cuGraphExecKernelNodeSetParams, * ::cuGraphExecMemcpyNodeSetParams, * ::cuGraphExecMemsetNodeSetParams, * ::cuGraphExecHostNodeSetParams, * ::cuGraphExecChildGraphNodeSetParams, * ::cuGraphExecEventRecordNodeSetEvent, * ::cuGraphExecExternalSemaphoresSignalNodeSetParams, * ::cuGraphExecExternalSemaphoresWaitNodeSetParams, * ::cuGraphExecUpdate, * ::cuGraphInstantiate */ CUresult CUDAAPI cuGraphExecEventWaitNodeSetEvent(CUgraphExec hGraphExec, CUgraphNode hNode, CUevent event); /** * \brief Sets the parameters for an external semaphore signal node in the given graphExec * * Sets the parameters of an external semaphore signal node in an executable graph \p hGraphExec. * The node is identified by the corresponding node \p hNode in the * non-executable graph, from which the executable graph was instantiated. * * \p hNode must not have been removed from the original graph. * * The modifications only affect future launches of \p hGraphExec. Already * enqueued or running launches of \p hGraphExec are not affected by this call. * \p hNode is also not modified by this call. * * Changing \p nodeParams->numExtSems is not supported. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - semaphore signal node from the graph from which graphExec was instantiated * \param nodeParams - Updated Parameters to set * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddExternalSemaphoresSignalNode, * ::cuImportExternalSemaphore, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync, * ::cuGraphExecKernelNodeSetParams, * ::cuGraphExecMemcpyNodeSetParams, * ::cuGraphExecMemsetNodeSetParams, * ::cuGraphExecHostNodeSetParams, * ::cuGraphExecChildGraphNodeSetParams, * ::cuGraphExecEventRecordNodeSetEvent, * ::cuGraphExecEventWaitNodeSetEvent, * ::cuGraphExecExternalSemaphoresWaitNodeSetParams, * ::cuGraphExecUpdate, * ::cuGraphInstantiate */ CUresult CUDAAPI cuGraphExecExternalSemaphoresSignalNodeSetParams(CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_EXT_SEM_SIGNAL_NODE_PARAMS *nodeParams); /** * \brief Sets the parameters for an external semaphore wait node in the given graphExec * * Sets the parameters of an external semaphore wait node in an executable graph \p hGraphExec. * The node is identified by the corresponding node \p hNode in the * non-executable graph, from which the executable graph was instantiated. * * \p hNode must not have been removed from the original graph. * * The modifications only affect future launches of \p hGraphExec. Already * enqueued or running launches of \p hGraphExec are not affected by this call. * \p hNode is also not modified by this call. * * Changing \p nodeParams->numExtSems is not supported. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - semaphore wait node from the graph from which graphExec was instantiated * \param nodeParams - Updated Parameters to set * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphAddExternalSemaphoresWaitNode, * ::cuImportExternalSemaphore, * ::cuSignalExternalSemaphoresAsync, * ::cuWaitExternalSemaphoresAsync, * ::cuGraphExecKernelNodeSetParams, * ::cuGraphExecMemcpyNodeSetParams, * ::cuGraphExecMemsetNodeSetParams, * ::cuGraphExecHostNodeSetParams, * ::cuGraphExecChildGraphNodeSetParams, * ::cuGraphExecEventRecordNodeSetEvent, * ::cuGraphExecEventWaitNodeSetEvent, * ::cuGraphExecExternalSemaphoresSignalNodeSetParams, * ::cuGraphExecUpdate, * ::cuGraphInstantiate */ CUresult CUDAAPI cuGraphExecExternalSemaphoresWaitNodeSetParams(CUgraphExec hGraphExec, CUgraphNode hNode, const CUDA_EXT_SEM_WAIT_NODE_PARAMS *nodeParams); /** * \brief Enables or disables the specified node in the given graphExec * * Sets \p hNode to be either enabled or disabled. Disabled nodes are functionally equivalent * to empty nodes until they are reenabled. Existing node parameters are not affected by * disabling/enabling the node. * * The node is identified by the corresponding node \p hNode in the non-executable * graph, from which the executable graph was instantiated. * * \p hNode must not have been removed from the original graph. * * The modifications only affect future launches of \p hGraphExec. Already * enqueued or running launches of \p hGraphExec are not affected by this call. * \p hNode is also not modified by this call. * * \note Currently only kernel nodes are supported. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - Node from the graph from which graphExec was instantiated * \param isEnabled - Node is enabled if != 0, otherwise the node is disabled * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphNodeGetEnabled, * ::cuGraphExecUpdate, * ::cuGraphInstantiate * ::cuGraphLaunch */ CUresult CUDAAPI cuGraphNodeSetEnabled(CUgraphExec hGraphExec, CUgraphNode hNode, unsigned int isEnabled); /** * \brief Query whether a node in the given graphExec is enabled * * Sets isEnabled to 1 if \p hNode is enabled, or 0 if \p hNode is disabled. * * The node is identified by the corresponding node \p hNode in the non-executable * graph, from which the executable graph was instantiated. * * \p hNode must not have been removed from the original graph. * * \note Currently only kernel nodes are supported. * * \param hGraphExec - The executable graph in which to set the specified node * \param hNode - Node from the graph from which graphExec was instantiated * \param isEnabled - Location to return the enabled status of the node * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphNodeSetEnabled, * ::cuGraphExecUpdate, * ::cuGraphInstantiate * ::cuGraphLaunch */ CUresult CUDAAPI cuGraphNodeGetEnabled(CUgraphExec hGraphExec, CUgraphNode hNode, unsigned int *isEnabled); /** * \brief Uploads an executable graph in a stream * * Uploads \p hGraphExec to the device in \p hStream without executing it. Uploads of * the same \p hGraphExec will be serialized. Each upload is ordered behind both any * previous work in \p hStream and any previous launches of \p hGraphExec. * Uses memory cached by \p stream to back the allocations owned by \p hGraphExec. * * \param hGraphExec - Executable graph to upload * \param hStream - Stream in which to upload the graph * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphInstantiate, * ::cuGraphLaunch, * ::cuGraphExecDestroy */ CUresult CUDAAPI cuGraphUpload(CUgraphExec hGraphExec, CUstream hStream); /** * \brief Launches an executable graph in a stream * * Executes \p hGraphExec in \p hStream. Only one instance of \p hGraphExec may be executing * at a time. Each launch is ordered behind both any previous work in \p hStream * and any previous launches of \p hGraphExec. To execute a graph concurrently, it must be * instantiated multiple times into multiple executable graphs. * * If any allocations created by \p hGraphExec remain unfreed (from a previous launch) and * \p hGraphExec was not instantiated with ::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH, * the launch will fail with ::CUDA_ERROR_INVALID_VALUE. * * \param hGraphExec - Executable graph to launch * \param hStream - Stream in which to launch the graph * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphInstantiate, * ::cuGraphUpload, * ::cuGraphExecDestroy */ CUresult CUDAAPI cuGraphLaunch(CUgraphExec hGraphExec, CUstream hStream); /** * \brief Destroys an executable graph * * Destroys the executable graph specified by \p hGraphExec, as well * as all of its executable nodes. If the executable graph is * in-flight, it will not be terminated, but rather freed * asynchronously on completion. * * \param hGraphExec - Executable graph to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphInstantiate, * ::cuGraphUpload, * ::cuGraphLaunch */ CUresult CUDAAPI cuGraphExecDestroy(CUgraphExec hGraphExec); /** * \brief Destroys a graph * * Destroys the graph specified by \p hGraph, as well as all of its nodes. * * \param hGraph - Graph to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_VALUE * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphCreate */ CUresult CUDAAPI cuGraphDestroy(CUgraph hGraph); /** * \brief Check whether an executable graph can be updated with a graph and perform the update if possible * * Updates the node parameters in the instantiated graph specified by \p hGraphExec with the * node parameters in a topologically identical graph specified by \p hGraph. * * Limitations: * * - Kernel nodes: * - The owning context of the function cannot change. * - A node whose function originally did not use CUDA dynamic parallelism cannot be updated * to a function which uses CDP. * - A cooperative node cannot be updated to a non-cooperative node, and vice-versa. * - Memset and memcpy nodes: * - The CUDA device(s) to which the operand(s) was allocated/mapped cannot change. * - The source/destination memory must be allocated from the same contexts as the original * source/destination memory. * - Only 1D memsets can be changed. * - Additional memcpy node restrictions: * - Changing either the source or destination memory type(i.e. CU_MEMORYTYPE_DEVICE, * CU_MEMORYTYPE_ARRAY, etc.) is not supported. * - External semaphore wait nodes and record nodes: * - Changing the number of semaphores is not supported. * * Note: The API may add further restrictions in future releases. The return code should always be checked. * * cuGraphExecUpdate sets \p updateResult_out to CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED under * the following conditions: * * - The count of nodes directly in \p hGraphExec and \p hGraph differ, in which case \p hErrorNode_out * is NULL. * - A node is deleted in \p hGraph but not not its pair from \p hGraphExec, in which case \p hErrorNode_out * is NULL. * - A node is deleted in \p hGraphExec but not its pair from \p hGraph, in which case \p hErrorNode_out is * the pairless node from \p hGraph. * - The dependent nodes of a pair differ, in which case \p hErrorNode_out is the node from \p hGraph. * * cuGraphExecUpdate sets \p updateResult_out to: * - CU_GRAPH_EXEC_UPDATE_ERROR if passed an invalid value. * - CU_GRAPH_EXEC_UPDATE_ERROR_TOPOLOGY_CHANGED if the graph topology changed * - CU_GRAPH_EXEC_UPDATE_ERROR_NODE_TYPE_CHANGED if the type of a node changed, in which case * \p hErrorNode_out is set to the node from \p hGraph. * - CU_GRAPH_EXEC_UPDATE_ERROR_UNSUPPORTED_FUNCTION_CHANGE if the function changed in an unsupported * way(see note above), in which case \p hErrorNode_out is set to the node from \p hGraph * - CU_GRAPH_EXEC_UPDATE_ERROR_PARAMETERS_CHANGED if any parameters to a node changed in a way * that is not supported, in which case \p hErrorNode_out is set to the node from \p hGraph. * - CU_GRAPH_EXEC_UPDATE_ERROR_ATTRIBUTES_CHANGED if any attributes of a node changed in a way * that is not supported, in which case \p hErrorNode_out is set to the node from \p hGraph. * - CU_GRAPH_EXEC_UPDATE_ERROR_NOT_SUPPORTED if something about a node is unsupported, like * the node's type or configuration, in which case \p hErrorNode_out is set to the node from \p hGraph * * If \p updateResult_out isn't set in one of the situations described above, the update check passes * and cuGraphExecUpdate updates \p hGraphExec to match the contents of \p hGraph. If an error happens * during the update, \p updateResult_out will be set to CU_GRAPH_EXEC_UPDATE_ERROR; otherwise, * \p updateResult_out is set to CU_GRAPH_EXEC_UPDATE_SUCCESS. * * cuGraphExecUpdate returns CUDA_SUCCESS when the updated was performed successfully. It returns * CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE if the graph update was not performed because it included * changes which violated constraints specific to instantiated graph update. * * \param hGraphExec The instantiated graph to be updated * \param hGraph The graph containing the updated parameters * \param hErrorNode_out The node which caused the permissibility check to forbid the update, if any * \param updateResult_out Whether the graph update was permitted. If was forbidden, the reason why * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE, * \note_graph_thread_safety * \notefnerr * * \sa * ::cuGraphInstantiate, */ CUresult CUDAAPI cuGraphExecUpdate(CUgraphExec hGraphExec, CUgraph hGraph, CUgraphNode *hErrorNode_out, CUgraphExecUpdateResult *updateResult_out); /** * \brief Copies attributes from source node to destination node. * * Copies attributes from source node \p src to destination node \p dst. * Both node must have the same context. * * \param[out] dst Destination node * \param[in] src Source node * For list of attributes see ::CUkernelNodeAttrID * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa * ::CUaccessPolicyWindow */ CUresult CUDAAPI cuGraphKernelNodeCopyAttributes(CUgraphNode dst, CUgraphNode src); /** * \brief Queries node attribute. * * Queries attribute \p attr from node \p hNode and stores it in corresponding * member of \p value_out. * * \param[in] hNode * \param[in] attr * \param[out] value_out * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa * ::CUaccessPolicyWindow */ CUresult CUDAAPI cuGraphKernelNodeGetAttribute(CUgraphNode hNode, CUkernelNodeAttrID attr, CUkernelNodeAttrValue *value_out); /** * \brief Sets node attribute. * * Sets attribute \p attr on node \p hNode from corresponding attribute of * \p value. * * \param[out] hNode * \param[in] attr * \param[out] value * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE * \notefnerr * * \sa * ::CUaccessPolicyWindow */ CUresult CUDAAPI cuGraphKernelNodeSetAttribute(CUgraphNode hNode, CUkernelNodeAttrID attr, const CUkernelNodeAttrValue *value); /** * \brief Write a DOT file describing graph structure * * Using the provided \p hGraph, write to \p path a DOT formatted description of the graph. * By default this includes the graph topology, node types, node id, kernel names and memcpy direction. * \p flags can be specified to write more detailed information about each node type such as * parameter values, kernel attributes, node and function handles. * * \param hGraph - The graph to create a DOT file from * \param path - The path to write the DOT file to * \param flags - Flags from CUgraphDebugDot_flags for specifying which additional node information to write * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_OPERATING_SYSTEM */ CUresult CUDAAPI cuGraphDebugDotPrint(CUgraph hGraph, const char *path, unsigned int flags); /** * \brief Create a user object * * Create a user object with the specified destructor callback and initial reference count. The * initial references are owned by the caller. * * Destructor callbacks cannot make CUDA API calls and should avoid blocking behavior, as they * are executed by a shared internal thread. Another thread may be signaled to perform such * actions, if it does not block forward progress of tasks scheduled through CUDA. * * See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects. * * \param object_out - Location to return the user object handle * \param ptr - The pointer to pass to the destroy function * \param destroy - Callback to free the user object when it is no longer in use * \param initialRefcount - The initial refcount to create the object with, typically 1. The * initial references are owned by the calling thread. * \param flags - Currently it is required to pass ::CU_USER_OBJECT_NO_DESTRUCTOR_SYNC, * which is the only defined flag. This indicates that the destroy * callback cannot be waited on by any CUDA API. Users requiring * synchronization of the callback should signal its completion * manually. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuUserObjectRetain, * ::cuUserObjectRelease, * ::cuGraphRetainUserObject, * ::cuGraphReleaseUserObject, * ::cuGraphCreate */ CUresult CUDAAPI cuUserObjectCreate(CUuserObject *object_out, void *ptr, CUhostFn destroy, unsigned int initialRefcount, unsigned int flags); /** * \brief Retain a reference to a user object * * Retains new references to a user object. The new references are owned by the caller. * * See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects. * * \param object - The object to retain * \param count - The number of references to retain, typically 1. Must be nonzero * and not larger than INT_MAX. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuUserObjectCreate, * ::cuUserObjectRelease, * ::cuGraphRetainUserObject, * ::cuGraphReleaseUserObject, * ::cuGraphCreate */ CUresult CUDAAPI cuUserObjectRetain(CUuserObject object, unsigned int count); /** * \brief Release a reference to a user object * * Releases user object references owned by the caller. The object's destructor is invoked if * the reference count reaches zero. * * It is undefined behavior to release references not owned by the caller, or to use a user * object handle after all references are released. * * See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects. * * \param object - The object to release * \param count - The number of references to release, typically 1. Must be nonzero * and not larger than INT_MAX. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuUserObjectCreate, * ::cuUserObjectRetain, * ::cuGraphRetainUserObject, * ::cuGraphReleaseUserObject, * ::cuGraphCreate */ CUresult CUDAAPI cuUserObjectRelease(CUuserObject object, unsigned int count); /** * \brief Retain a reference to a user object from a graph * * Creates or moves user object references that will be owned by a CUDA graph. * * See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects. * * \param graph - The graph to associate the reference with * \param object - The user object to retain a reference for * \param count - The number of references to add to the graph, typically 1. Must be * nonzero and not larger than INT_MAX. * \param flags - The optional flag ::CU_GRAPH_USER_OBJECT_MOVE transfers references * from the calling thread, rather than create new references. Pass 0 * to create new references. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuUserObjectCreate, * ::cuUserObjectRetain, * ::cuUserObjectRelease, * ::cuGraphReleaseUserObject, * ::cuGraphCreate */ CUresult CUDAAPI cuGraphRetainUserObject(CUgraph graph, CUuserObject object, unsigned int count, unsigned int flags); /** * \brief Release a user object reference from a graph * * Releases user object references owned by a graph. * * See CUDA User Objects in the CUDA C++ Programming Guide for more information on user objects. * * \param graph - The graph that will release the reference * \param object - The user object to release a reference for * \param count - The number of references to release, typically 1. Must be nonzero * and not larger than INT_MAX. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuUserObjectCreate, * ::cuUserObjectRetain, * ::cuUserObjectRelease, * ::cuGraphRetainUserObject, * ::cuGraphCreate */ CUresult CUDAAPI cuGraphReleaseUserObject(CUgraph graph, CUuserObject object, unsigned int count); /** @} */ /* END CUDA_GRAPH */ /** * \defgroup CUDA_OCCUPANCY Occupancy * * ___MANBRIEF___ occupancy calculation functions of the low-level CUDA driver * API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the occupancy calculation functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Returns occupancy of a function * * Returns in \p *numBlocks the number of the maximum active blocks per * streaming multiprocessor. * * \param numBlocks - Returned occupancy * \param func - Kernel for which occupancy is calculated * \param blockSize - Block size the kernel is intended to be launched with * \param dynamicSMemSize - Per-block dynamic shared memory usage intended, in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa * ::cudaOccupancyMaxActiveBlocksPerMultiprocessor */ CUresult CUDAAPI cuOccupancyMaxActiveBlocksPerMultiprocessor(int *numBlocks, CUfunction func, int blockSize, size_t dynamicSMemSize); /** * \brief Returns occupancy of a function * * Returns in \p *numBlocks the number of the maximum active blocks per * streaming multiprocessor. * * The \p Flags parameter controls how special cases are handled. The * valid flags are: * * - ::CU_OCCUPANCY_DEFAULT, which maintains the default behavior as * ::cuOccupancyMaxActiveBlocksPerMultiprocessor; * * - ::CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE, which suppresses the * default behavior on platform where global caching affects * occupancy. On such platforms, if caching is enabled, but * per-block SM resource usage would result in zero occupancy, the * occupancy calculator will calculate the occupancy as if caching * is disabled. Setting ::CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE makes * the occupancy calculator to return 0 in such cases. More information * can be found about this feature in the "Unified L1/Texture Cache" * section of the Maxwell tuning guide. * * \param numBlocks - Returned occupancy * \param func - Kernel for which occupancy is calculated * \param blockSize - Block size the kernel is intended to be launched with * \param dynamicSMemSize - Per-block dynamic shared memory usage intended, in bytes * \param flags - Requested behavior for the occupancy calculator * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa * ::cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags */ CUresult CUDAAPI cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(int *numBlocks, CUfunction func, int blockSize, size_t dynamicSMemSize, unsigned int flags); /** * \brief Suggest a launch configuration with reasonable occupancy * * Returns in \p *blockSize a reasonable block size that can achieve * the maximum occupancy (or, the maximum number of active warps with * the fewest blocks per multiprocessor), and in \p *minGridSize the * minimum grid size to achieve the maximum occupancy. * * If \p blockSizeLimit is 0, the configurator will use the maximum * block size permitted by the device / function instead. * * If per-block dynamic shared memory allocation is not needed, the * user should leave both \p blockSizeToDynamicSMemSize and \p * dynamicSMemSize as 0. * * If per-block dynamic shared memory allocation is needed, then if * the dynamic shared memory size is constant regardless of block * size, the size should be passed through \p dynamicSMemSize, and \p * blockSizeToDynamicSMemSize should be NULL. * * Otherwise, if the per-block dynamic shared memory size varies with * different block sizes, the user needs to provide a unary function * through \p blockSizeToDynamicSMemSize that computes the dynamic * shared memory needed by \p func for any given block size. \p * dynamicSMemSize is ignored. An example signature is: * * \code * // Take block size, returns dynamic shared memory needed * size_t blockToSmem(int blockSize); * \endcode * * \param minGridSize - Returned minimum grid size needed to achieve the maximum occupancy * \param blockSize - Returned maximum block size that can achieve the maximum occupancy * \param func - Kernel for which launch configuration is calculated * \param blockSizeToDynamicSMemSize - A function that calculates how much per-block dynamic shared memory \p func uses based on the block size * \param dynamicSMemSize - Dynamic shared memory usage intended, in bytes * \param blockSizeLimit - The maximum block size \p func is designed to handle * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa * ::cudaOccupancyMaxPotentialBlockSize */ CUresult CUDAAPI cuOccupancyMaxPotentialBlockSize(int *minGridSize, int *blockSize, CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, size_t dynamicSMemSize, int blockSizeLimit); /** * \brief Suggest a launch configuration with reasonable occupancy * * An extended version of ::cuOccupancyMaxPotentialBlockSize. In * addition to arguments passed to ::cuOccupancyMaxPotentialBlockSize, * ::cuOccupancyMaxPotentialBlockSizeWithFlags also takes a \p Flags * parameter. * * The \p Flags parameter controls how special cases are handled. The * valid flags are: * * - ::CU_OCCUPANCY_DEFAULT, which maintains the default behavior as * ::cuOccupancyMaxPotentialBlockSize; * * - ::CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE, which suppresses the * default behavior on platform where global caching affects * occupancy. On such platforms, the launch configurations that * produces maximal occupancy might not support global * caching. Setting ::CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE * guarantees that the the produced launch configuration is global * caching compatible at a potential cost of occupancy. More information * can be found about this feature in the "Unified L1/Texture Cache" * section of the Maxwell tuning guide. * * \param minGridSize - Returned minimum grid size needed to achieve the maximum occupancy * \param blockSize - Returned maximum block size that can achieve the maximum occupancy * \param func - Kernel for which launch configuration is calculated * \param blockSizeToDynamicSMemSize - A function that calculates how much per-block dynamic shared memory \p func uses based on the block size * \param dynamicSMemSize - Dynamic shared memory usage intended, in bytes * \param blockSizeLimit - The maximum block size \p func is designed to handle * \param flags - Options * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa * ::cudaOccupancyMaxPotentialBlockSizeWithFlags */ CUresult CUDAAPI cuOccupancyMaxPotentialBlockSizeWithFlags(int *minGridSize, int *blockSize, CUfunction func, CUoccupancyB2DSize blockSizeToDynamicSMemSize, size_t dynamicSMemSize, int blockSizeLimit, unsigned int flags); /** * \brief Returns dynamic shared memory available per block when launching \p numBlocks blocks on SM * * Returns in \p *dynamicSmemSize the maximum size of dynamic shared memory to allow \p numBlocks blocks per SM. * * \param dynamicSmemSize - Returned maximum dynamic shared memory * \param func - Kernel function for which occupancy is calculated * \param numBlocks - Number of blocks to fit on SM * \param blockSize - Size of the blocks * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa */ CUresult CUDAAPI cuOccupancyAvailableDynamicSMemPerBlock(size_t *dynamicSmemSize, CUfunction func, int numBlocks, int blockSize); /** @} */ /* END CUDA_OCCUPANCY */ /** * \defgroup CUDA_TEXREF_DEPRECATED Texture Reference Management [DEPRECATED] * * ___MANBRIEF___ deprecated texture reference management functions of the * low-level CUDA driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the deprecated texture reference management * functions of the low-level CUDA driver application programming interface. * * @{ */ /** * \brief Binds an array as a texture reference * * \deprecated * * Binds the CUDA array \p hArray to the texture reference \p hTexRef. Any * previous address or CUDA array state associated with the texture reference * is superseded by this function. \p Flags must be set to * ::CU_TRSA_OVERRIDE_FORMAT. Any CUDA array previously bound to \p hTexRef is * unbound. * * \param hTexRef - Texture reference to bind * \param hArray - Array to bind * \param Flags - Options (must be ::CU_TRSA_OVERRIDE_FORMAT) * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTextureToArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetArray(CUtexref hTexRef, CUarray hArray, unsigned int Flags); /** * \brief Binds a mipmapped array to a texture reference * * \deprecated * * Binds the CUDA mipmapped array \p hMipmappedArray to the texture reference \p hTexRef. * Any previous address or CUDA array state associated with the texture reference * is superseded by this function. \p Flags must be set to ::CU_TRSA_OVERRIDE_FORMAT. * Any CUDA array previously bound to \p hTexRef is unbound. * * \param hTexRef - Texture reference to bind * \param hMipmappedArray - Mipmapped array to bind * \param Flags - Options (must be ::CU_TRSA_OVERRIDE_FORMAT) * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTextureToMipmappedArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetMipmappedArray(CUtexref hTexRef, CUmipmappedArray hMipmappedArray, unsigned int Flags); /** * \brief Binds an address as a texture reference * * \deprecated * * Binds a linear address range to the texture reference \p hTexRef. Any * previous address or CUDA array state associated with the texture reference * is superseded by this function. Any memory previously bound to \p hTexRef * is unbound. * * Since the hardware enforces an alignment requirement on texture base * addresses, ::cuTexRefSetAddress() passes back a byte offset in * \p *ByteOffset that must be applied to texture fetches in order to read from * the desired memory. This offset must be divided by the texel size and * passed to kernels that read from the texture so they can be applied to the * ::tex1Dfetch() function. * * If the device memory pointer was returned from ::cuMemAlloc(), the offset * is guaranteed to be 0 and NULL may be passed as the \p ByteOffset parameter. * * The total number of elements (or texels) in the linear address range * cannot exceed ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH. * The number of elements is computed as (\p bytes / bytesPerElement), * where bytesPerElement is determined from the data format and number of * components set using ::cuTexRefSetFormat(). * * \param ByteOffset - Returned byte offset * \param hTexRef - Texture reference to bind * \param dptr - Device pointer to bind * \param bytes - Size of memory to bind in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTexture */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetAddress(size_t *ByteOffset, CUtexref hTexRef, CUdeviceptr dptr, size_t bytes); /** * \brief Binds an address as a 2D texture reference * * \deprecated * * Binds a linear address range to the texture reference \p hTexRef. Any * previous address or CUDA array state associated with the texture reference * is superseded by this function. Any memory previously bound to \p hTexRef * is unbound. * * Using a ::tex2D() function inside a kernel requires a call to either * ::cuTexRefSetArray() to bind the corresponding texture reference to an * array, or ::cuTexRefSetAddress2D() to bind the texture reference to linear * memory. * * Function calls to ::cuTexRefSetFormat() cannot follow calls to * ::cuTexRefSetAddress2D() for the same texture reference. * * It is required that \p dptr be aligned to the appropriate hardware-specific * texture alignment. You can query this value using the device attribute * ::CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT. If an unaligned \p dptr is * supplied, ::CUDA_ERROR_INVALID_VALUE is returned. * * \p Pitch has to be aligned to the hardware-specific texture pitch alignment. * This value can be queried using the device attribute * ::CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT. If an unaligned \p Pitch is * supplied, ::CUDA_ERROR_INVALID_VALUE is returned. * * Width and Height, which are specified in elements (or texels), cannot exceed * ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH and * ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT respectively. * \p Pitch, which is specified in bytes, cannot exceed * ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH. * * \param hTexRef - Texture reference to bind * \param desc - Descriptor of CUDA array * \param dptr - Device pointer to bind * \param Pitch - Line pitch in bytes * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTexture2D */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetAddress2D(CUtexref hTexRef, const CUDA_ARRAY_DESCRIPTOR *desc, CUdeviceptr dptr, size_t Pitch); /** * \brief Sets the format for a texture reference * * \deprecated * * Specifies the format of the data to be read by the texture reference * \p hTexRef. \p fmt and \p NumPackedComponents are exactly analogous to the * ::Format and ::NumChannels members of the ::CUDA_ARRAY_DESCRIPTOR structure: * They specify the format of each component and the number of components per * array element. * * \param hTexRef - Texture reference * \param fmt - Format to set * \param NumPackedComponents - Number of components per array element * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaCreateChannelDesc, * ::cudaBindTexture, * ::cudaBindTexture2D, * ::cudaBindTextureToArray, * ::cudaBindTextureToMipmappedArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetFormat(CUtexref hTexRef, CUarray_format fmt, int NumPackedComponents); /** * \brief Sets the addressing mode for a texture reference * * \deprecated * * Specifies the addressing mode \p am for the given dimension \p dim of the * texture reference \p hTexRef. If \p dim is zero, the addressing mode is * applied to the first parameter of the functions used to fetch from the * texture; if \p dim is 1, the second, and so on. ::CUaddress_mode is defined * as: * \code typedef enum CUaddress_mode_enum { CU_TR_ADDRESS_MODE_WRAP = 0, CU_TR_ADDRESS_MODE_CLAMP = 1, CU_TR_ADDRESS_MODE_MIRROR = 2, CU_TR_ADDRESS_MODE_BORDER = 3 } CUaddress_mode; * \endcode * * Note that this call has no effect if \p hTexRef is bound to linear memory. * Also, if the flag, ::CU_TRSF_NORMALIZED_COORDINATES, is not set, the only * supported address mode is ::CU_TR_ADDRESS_MODE_CLAMP. * * \param hTexRef - Texture reference * \param dim - Dimension * \param am - Addressing mode to set * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTexture, * ::cudaBindTexture2D, * ::cudaBindTextureToArray, * ::cudaBindTextureToMipmappedArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetAddressMode(CUtexref hTexRef, int dim, CUaddress_mode am); /** * \brief Sets the filtering mode for a texture reference * * \deprecated * * Specifies the filtering mode \p fm to be used when reading memory through * the texture reference \p hTexRef. ::CUfilter_mode_enum is defined as: * * \code typedef enum CUfilter_mode_enum { CU_TR_FILTER_MODE_POINT = 0, CU_TR_FILTER_MODE_LINEAR = 1 } CUfilter_mode; * \endcode * * Note that this call has no effect if \p hTexRef is bound to linear memory. * * \param hTexRef - Texture reference * \param fm - Filtering mode to set * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTextureToArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetFilterMode(CUtexref hTexRef, CUfilter_mode fm); /** * \brief Sets the mipmap filtering mode for a texture reference * * \deprecated * * Specifies the mipmap filtering mode \p fm to be used when reading memory through * the texture reference \p hTexRef. ::CUfilter_mode_enum is defined as: * * \code typedef enum CUfilter_mode_enum { CU_TR_FILTER_MODE_POINT = 0, CU_TR_FILTER_MODE_LINEAR = 1 } CUfilter_mode; * \endcode * * Note that this call has no effect if \p hTexRef is not bound to a mipmapped array. * * \param hTexRef - Texture reference * \param fm - Filtering mode to set * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTextureToMipmappedArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetMipmapFilterMode(CUtexref hTexRef, CUfilter_mode fm); /** * \brief Sets the mipmap level bias for a texture reference * * \deprecated * * Specifies the mipmap level bias \p bias to be added to the specified mipmap level when * reading memory through the texture reference \p hTexRef. * * Note that this call has no effect if \p hTexRef is not bound to a mipmapped array. * * \param hTexRef - Texture reference * \param bias - Mipmap level bias * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTextureToMipmappedArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetMipmapLevelBias(CUtexref hTexRef, float bias); /** * \brief Sets the mipmap min/max mipmap level clamps for a texture reference * * \deprecated * * Specifies the min/max mipmap level clamps, \p minMipmapLevelClamp and \p maxMipmapLevelClamp * respectively, to be used when reading memory through the texture reference * \p hTexRef. * * Note that this call has no effect if \p hTexRef is not bound to a mipmapped array. * * \param hTexRef - Texture reference * \param minMipmapLevelClamp - Mipmap min level clamp * \param maxMipmapLevelClamp - Mipmap max level clamp * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTextureToMipmappedArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetMipmapLevelClamp(CUtexref hTexRef, float minMipmapLevelClamp, float maxMipmapLevelClamp); /** * \brief Sets the maximum anisotropy for a texture reference * * \deprecated * * Specifies the maximum anisotropy \p maxAniso to be used when reading memory through * the texture reference \p hTexRef. * * Note that this call has no effect if \p hTexRef is bound to linear memory. * * \param hTexRef - Texture reference * \param maxAniso - Maximum anisotropy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTextureToArray, * ::cudaBindTextureToMipmappedArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetMaxAnisotropy(CUtexref hTexRef, unsigned int maxAniso); /** * \brief Sets the border color for a texture reference * * \deprecated * * Specifies the value of the RGBA color via the \p pBorderColor to the texture reference * \p hTexRef. The color value supports only float type and holds color components in * the following sequence: * pBorderColor[0] holds 'R' component * pBorderColor[1] holds 'G' component * pBorderColor[2] holds 'B' component * pBorderColor[3] holds 'A' component * * Note that the color values can be set only when the Address mode is set to * CU_TR_ADDRESS_MODE_BORDER using ::cuTexRefSetAddressMode. * Applications using integer border color values have to "reinterpret_cast" their values to float. * * \param hTexRef - Texture reference * \param pBorderColor - RGBA color * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddressMode, * ::cuTexRefGetAddressMode, ::cuTexRefGetBorderColor, * ::cudaBindTexture, * ::cudaBindTexture2D, * ::cudaBindTextureToArray, * ::cudaBindTextureToMipmappedArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetBorderColor(CUtexref hTexRef, float *pBorderColor); /** * \brief Sets the flags for a texture reference * * \deprecated * * Specifies optional flags via \p Flags to specify the behavior of data * returned through the texture reference \p hTexRef. The valid flags are: * * - ::CU_TRSF_READ_AS_INTEGER, which suppresses the default behavior of * having the texture promote integer data to floating point data in the * range [0, 1]. Note that texture with 32-bit integer format * would not be promoted, regardless of whether or not this * flag is specified; * - ::CU_TRSF_NORMALIZED_COORDINATES, which suppresses the * default behavior of having the texture coordinates range * from [0, Dim) where Dim is the width or height of the CUDA * array. Instead, the texture coordinates [0, 1.0) reference * the entire breadth of the array dimension; * - ::CU_TRSF_DISABLE_TRILINEAR_OPTIMIZATION, which disables any trilinear * filtering optimizations. Trilinear optimizations improve texture filtering * performance by allowing bilinear filtering on textures in scenarios where * it can closely approximate the expected results. * * \param hTexRef - Texture reference * \param Flags - Optional flags to set * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat, * ::cudaBindTexture, * ::cudaBindTexture2D, * ::cudaBindTextureToArray, * ::cudaBindTextureToMipmappedArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefSetFlags(CUtexref hTexRef, unsigned int Flags); /** * \brief Gets the address associated with a texture reference * * \deprecated * * Returns in \p *pdptr the base address bound to the texture reference * \p hTexRef, or returns ::CUDA_ERROR_INVALID_VALUE if the texture reference * is not bound to any device memory range. * * \param pdptr - Returned device address * \param hTexRef - Texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetAddress(CUdeviceptr *pdptr, CUtexref hTexRef); /** * \brief Gets the array bound to a texture reference * * \deprecated * * Returns in \p *phArray the CUDA array bound to the texture reference * \p hTexRef, or returns ::CUDA_ERROR_INVALID_VALUE if the texture reference * is not bound to any CUDA array. * * \param phArray - Returned array * \param hTexRef - Texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetArray(CUarray *phArray, CUtexref hTexRef); /** * \brief Gets the mipmapped array bound to a texture reference * * \deprecated * * Returns in \p *phMipmappedArray the CUDA mipmapped array bound to the texture * reference \p hTexRef, or returns ::CUDA_ERROR_INVALID_VALUE if the texture reference * is not bound to any CUDA mipmapped array. * * \param phMipmappedArray - Returned mipmapped array * \param hTexRef - Texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetMipmappedArray(CUmipmappedArray *phMipmappedArray, CUtexref hTexRef); /** * \brief Gets the addressing mode used by a texture reference * * \deprecated * * Returns in \p *pam the addressing mode corresponding to the * dimension \p dim of the texture reference \p hTexRef. Currently, the only * valid value for \p dim are 0 and 1. * * \param pam - Returned addressing mode * \param hTexRef - Texture reference * \param dim - Dimension * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetAddressMode(CUaddress_mode *pam, CUtexref hTexRef, int dim); /** * \brief Gets the filter-mode used by a texture reference * * \deprecated * * Returns in \p *pfm the filtering mode of the texture reference * \p hTexRef. * * \param pfm - Returned filtering mode * \param hTexRef - Texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFlags, ::cuTexRefGetFormat */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetFilterMode(CUfilter_mode *pfm, CUtexref hTexRef); /** * \brief Gets the format used by a texture reference * * \deprecated * * Returns in \p *pFormat and \p *pNumChannels the format and number * of components of the CUDA array bound to the texture reference \p hTexRef. * If \p pFormat or \p pNumChannels is NULL, it will be ignored. * * \param pFormat - Returned format * \param pNumChannels - Returned number of components * \param hTexRef - Texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetFormat(CUarray_format *pFormat, int *pNumChannels, CUtexref hTexRef); /** * \brief Gets the mipmap filtering mode for a texture reference * * \deprecated * * Returns the mipmap filtering mode in \p pfm that's used when reading memory through * the texture reference \p hTexRef. * * \param pfm - Returned mipmap filtering mode * \param hTexRef - Texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetMipmapFilterMode(CUfilter_mode *pfm, CUtexref hTexRef); /** * \brief Gets the mipmap level bias for a texture reference * * \deprecated * * Returns the mipmap level bias in \p pBias that's added to the specified mipmap * level when reading memory through the texture reference \p hTexRef. * * \param pbias - Returned mipmap level bias * \param hTexRef - Texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetMipmapLevelBias(float *pbias, CUtexref hTexRef); /** * \brief Gets the min/max mipmap level clamps for a texture reference * * \deprecated * * Returns the min/max mipmap level clamps in \p pminMipmapLevelClamp and \p pmaxMipmapLevelClamp * that's used when reading memory through the texture reference \p hTexRef. * * \param pminMipmapLevelClamp - Returned mipmap min level clamp * \param pmaxMipmapLevelClamp - Returned mipmap max level clamp * \param hTexRef - Texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetMipmapLevelClamp(float *pminMipmapLevelClamp, float *pmaxMipmapLevelClamp, CUtexref hTexRef); /** * \brief Gets the maximum anisotropy for a texture reference * * \deprecated * * Returns the maximum anisotropy in \p pmaxAniso that's used when reading memory through * the texture reference \p hTexRef. * * \param pmaxAniso - Returned maximum anisotropy * \param hTexRef - Texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFlags, ::cuTexRefGetFormat */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetMaxAnisotropy(int *pmaxAniso, CUtexref hTexRef); /** * \brief Gets the border color used by a texture reference * * \deprecated * * Returns in \p pBorderColor, values of the RGBA color used by * the texture reference \p hTexRef. * The color value is of type float and holds color components in * the following sequence: * pBorderColor[0] holds 'R' component * pBorderColor[1] holds 'G' component * pBorderColor[2] holds 'B' component * pBorderColor[3] holds 'A' component * * \param hTexRef - Texture reference * \param pBorderColor - Returned Type and Value of RGBA color * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddressMode, * ::cuTexRefSetAddressMode, ::cuTexRefSetBorderColor */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetBorderColor(float *pBorderColor, CUtexref hTexRef); /** * \brief Gets the flags used by a texture reference * * \deprecated * * Returns in \p *pFlags the flags of the texture reference \p hTexRef. * * \param pFlags - Returned flags * \param hTexRef - Texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefSetAddress, * ::cuTexRefSetAddress2D, ::cuTexRefSetAddressMode, ::cuTexRefSetArray, * ::cuTexRefSetFilterMode, ::cuTexRefSetFlags, ::cuTexRefSetFormat, * ::cuTexRefGetAddress, ::cuTexRefGetAddressMode, ::cuTexRefGetArray, * ::cuTexRefGetFilterMode, ::cuTexRefGetFormat */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefGetFlags(unsigned int *pFlags, CUtexref hTexRef); /** * \brief Creates a texture reference * * \deprecated * * Creates a texture reference and returns its handle in \p *pTexRef. Once * created, the application must call ::cuTexRefSetArray() or * ::cuTexRefSetAddress() to associate the reference with allocated memory. * Other texture reference functions are used to specify the format and * interpretation (addressing, filtering, etc.) to be used when the memory is * read through this texture reference. * * \param pTexRef - Returned texture reference * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefDestroy */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefCreate(CUtexref *pTexRef); /** * \brief Destroys a texture reference * * \deprecated * * Destroys the texture reference specified by \p hTexRef. * * \param hTexRef - Texture reference to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuTexRefCreate */ __CUDA_DEPRECATED CUresult CUDAAPI cuTexRefDestroy(CUtexref hTexRef); /** @} */ /* END CUDA_TEXREF_DEPRECATED */ /** * \defgroup CUDA_SURFREF_DEPRECATED Surface Reference Management [DEPRECATED] * * ___MANBRIEF___ surface reference management functions of the low-level CUDA * driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the surface reference management functions of the * low-level CUDA driver application programming interface. * * @{ */ /** * \brief Sets the CUDA array for a surface reference. * * \deprecated * * Sets the CUDA array \p hArray to be read and written by the surface reference * \p hSurfRef. Any previous CUDA array state associated with the surface * reference is superseded by this function. \p Flags must be set to 0. * The ::CUDA_ARRAY3D_SURFACE_LDST flag must have been set for the CUDA array. * Any CUDA array previously bound to \p hSurfRef is unbound. * \param hSurfRef - Surface reference handle * \param hArray - CUDA array handle * \param Flags - set to 0 * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuModuleGetSurfRef, * ::cuSurfRefGetArray, * ::cudaBindSurfaceToArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuSurfRefSetArray(CUsurfref hSurfRef, CUarray hArray, unsigned int Flags); /** * \brief Passes back the CUDA array bound to a surface reference. * * \deprecated * * Returns in \p *phArray the CUDA array bound to the surface reference * \p hSurfRef, or returns ::CUDA_ERROR_INVALID_VALUE if the surface reference * is not bound to any CUDA array. * \param phArray - Surface reference handle * \param hSurfRef - Surface reference handle * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa ::cuModuleGetSurfRef, ::cuSurfRefSetArray */ __CUDA_DEPRECATED CUresult CUDAAPI cuSurfRefGetArray(CUarray *phArray, CUsurfref hSurfRef); /** @} */ /* END CUDA_SURFREF_DEPRECATED */ /** * \defgroup CUDA_TEXOBJECT Texture Object Management * * ___MANBRIEF___ texture object management functions of the low-level CUDA * driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the texture object management functions of the * low-level CUDA driver application programming interface. The texture * object API is only supported on devices of compute capability 3.0 or higher. * * @{ */ /** * \brief Creates a texture object * * Creates a texture object and returns it in \p pTexObject. \p pResDesc describes * the data to texture from. \p pTexDesc describes how the data should be sampled. * \p pResViewDesc is an optional argument that specifies an alternate format for * the data described by \p pResDesc, and also describes the subresource region * to restrict access to when texturing. \p pResViewDesc can only be specified if * the type of resource is a CUDA array or a CUDA mipmapped array. * * Texture objects are only supported on devices of compute capability 3.0 or higher. * Additionally, a texture object is an opaque value, and, as such, should only be * accessed through CUDA API calls. * * The ::CUDA_RESOURCE_DESC structure is defined as: * \code typedef struct CUDA_RESOURCE_DESC_st { CUresourcetype resType; union { struct { CUarray hArray; } array; struct { CUmipmappedArray hMipmappedArray; } mipmap; struct { CUdeviceptr devPtr; CUarray_format format; unsigned int numChannels; size_t sizeInBytes; } linear; struct { CUdeviceptr devPtr; CUarray_format format; unsigned int numChannels; size_t width; size_t height; size_t pitchInBytes; } pitch2D; } res; unsigned int flags; } CUDA_RESOURCE_DESC; * \endcode * where: * - ::CUDA_RESOURCE_DESC::resType specifies the type of resource to texture from. * CUresourceType is defined as: * \code typedef enum CUresourcetype_enum { CU_RESOURCE_TYPE_ARRAY = 0x00, CU_RESOURCE_TYPE_MIPMAPPED_ARRAY = 0x01, CU_RESOURCE_TYPE_LINEAR = 0x02, CU_RESOURCE_TYPE_PITCH2D = 0x03 } CUresourcetype; * \endcode * * \par * If ::CUDA_RESOURCE_DESC::resType is set to ::CU_RESOURCE_TYPE_ARRAY, ::CUDA_RESOURCE_DESC::res::array::hArray * must be set to a valid CUDA array handle. * * \par * If ::CUDA_RESOURCE_DESC::resType is set to ::CU_RESOURCE_TYPE_MIPMAPPED_ARRAY, ::CUDA_RESOURCE_DESC::res::mipmap::hMipmappedArray * must be set to a valid CUDA mipmapped array handle. * * \par * If ::CUDA_RESOURCE_DESC::resType is set to ::CU_RESOURCE_TYPE_LINEAR, ::CUDA_RESOURCE_DESC::res::linear::devPtr * must be set to a valid device pointer, that is aligned to ::CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT. * ::CUDA_RESOURCE_DESC::res::linear::format and ::CUDA_RESOURCE_DESC::res::linear::numChannels * describe the format of each component and the number of components per array element. ::CUDA_RESOURCE_DESC::res::linear::sizeInBytes * specifies the size of the array in bytes. The total number of elements in the linear address range cannot exceed * ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH. The number of elements is computed as (sizeInBytes / (sizeof(format) * numChannels)). * * \par * If ::CUDA_RESOURCE_DESC::resType is set to ::CU_RESOURCE_TYPE_PITCH2D, ::CUDA_RESOURCE_DESC::res::pitch2D::devPtr * must be set to a valid device pointer, that is aligned to ::CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT. * ::CUDA_RESOURCE_DESC::res::pitch2D::format and ::CUDA_RESOURCE_DESC::res::pitch2D::numChannels * describe the format of each component and the number of components per array element. ::CUDA_RESOURCE_DESC::res::pitch2D::width * and ::CUDA_RESOURCE_DESC::res::pitch2D::height specify the width and height of the array in elements, and cannot exceed * ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH and ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT respectively. * ::CUDA_RESOURCE_DESC::res::pitch2D::pitchInBytes specifies the pitch between two rows in bytes and has to be aligned to * ::CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT. Pitch cannot exceed ::CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH. * * - ::flags must be set to zero. * * * The ::CUDA_TEXTURE_DESC struct is defined as * \code typedef struct CUDA_TEXTURE_DESC_st { CUaddress_mode addressMode[3]; CUfilter_mode filterMode; unsigned int flags; unsigned int maxAnisotropy; CUfilter_mode mipmapFilterMode; float mipmapLevelBias; float minMipmapLevelClamp; float maxMipmapLevelClamp; } CUDA_TEXTURE_DESC; * \endcode * where * - ::CUDA_TEXTURE_DESC::addressMode specifies the addressing mode for each dimension of the texture data. ::CUaddress_mode is defined as: * \code typedef enum CUaddress_mode_enum { CU_TR_ADDRESS_MODE_WRAP = 0, CU_TR_ADDRESS_MODE_CLAMP = 1, CU_TR_ADDRESS_MODE_MIRROR = 2, CU_TR_ADDRESS_MODE_BORDER = 3 } CUaddress_mode; * \endcode * This is ignored if ::CUDA_RESOURCE_DESC::resType is ::CU_RESOURCE_TYPE_LINEAR. Also, if the flag, ::CU_TRSF_NORMALIZED_COORDINATES * is not set, the only supported address mode is ::CU_TR_ADDRESS_MODE_CLAMP. * * - ::CUDA_TEXTURE_DESC::filterMode specifies the filtering mode to be used when fetching from the texture. CUfilter_mode is defined as: * \code typedef enum CUfilter_mode_enum { CU_TR_FILTER_MODE_POINT = 0, CU_TR_FILTER_MODE_LINEAR = 1 } CUfilter_mode; * \endcode * This is ignored if ::CUDA_RESOURCE_DESC::resType is ::CU_RESOURCE_TYPE_LINEAR. * * - ::CUDA_TEXTURE_DESC::flags can be any combination of the following: * - ::CU_TRSF_READ_AS_INTEGER, which suppresses the default behavior of * having the texture promote integer data to floating point data in the * range [0, 1]. Note that texture with 32-bit integer format would not be * promoted, regardless of whether or not this flag is specified. * - ::CU_TRSF_NORMALIZED_COORDINATES, which suppresses the default behavior * of having the texture coordinates range from [0, Dim) where Dim is the * width or height of the CUDA array. Instead, the texture coordinates * [0, 1.0) reference the entire breadth of the array dimension; Note that * for CUDA mipmapped arrays, this flag has to be set. * - ::CU_TRSF_DISABLE_TRILINEAR_OPTIMIZATION, which disables any trilinear * filtering optimizations. Trilinear optimizations improve texture filtering * performance by allowing bilinear filtering on textures in scenarios where * it can closely approximate the expected results. * - ::CU_TRSF_SEAMLESS_CUBEMAP, which enables seamless cube map filtering. * This flag can only be specified if the underlying resource is a CUDA array * or a CUDA mipmapped array that was created with the flag ::CUDA_ARRAY3D_CUBEMAP. * When seamless cube map filtering is enabled, texture address modes specified * by ::CUDA_TEXTURE_DESC::addressMode are ignored. Instead, if the ::CUDA_TEXTURE_DESC::filterMode * is set to ::CU_TR_FILTER_MODE_POINT the address mode ::CU_TR_ADDRESS_MODE_CLAMP * will be applied for all dimensions. If the ::CUDA_TEXTURE_DESC::filterMode is * set to ::CU_TR_FILTER_MODE_LINEAR seamless cube map filtering will be performed * when sampling along the cube face borders. * * - ::CUDA_TEXTURE_DESC::maxAnisotropy specifies the maximum anisotropy ratio to be used when doing anisotropic filtering. This value will be * clamped to the range [1,16]. * * - ::CUDA_TEXTURE_DESC::mipmapFilterMode specifies the filter mode when the calculated mipmap level lies between two defined mipmap levels. * * - ::CUDA_TEXTURE_DESC::mipmapLevelBias specifies the offset to be applied to the calculated mipmap level. * * - ::CUDA_TEXTURE_DESC::minMipmapLevelClamp specifies the lower end of the mipmap level range to clamp access to. * * - ::CUDA_TEXTURE_DESC::maxMipmapLevelClamp specifies the upper end of the mipmap level range to clamp access to. * * * The ::CUDA_RESOURCE_VIEW_DESC struct is defined as * \code typedef struct CUDA_RESOURCE_VIEW_DESC_st { CUresourceViewFormat format; size_t width; size_t height; size_t depth; unsigned int firstMipmapLevel; unsigned int lastMipmapLevel; unsigned int firstLayer; unsigned int lastLayer; } CUDA_RESOURCE_VIEW_DESC; * \endcode * where: * - ::CUDA_RESOURCE_VIEW_DESC::format specifies how the data contained in the CUDA array or CUDA mipmapped array should * be interpreted. Note that this can incur a change in size of the texture data. If the resource view format is a block * compressed format, then the underlying CUDA array or CUDA mipmapped array has to have a base of format ::CU_AD_FORMAT_UNSIGNED_INT32. * with 2 or 4 channels, depending on the block compressed format. For ex., BC1 and BC4 require the underlying CUDA array to have * a format of ::CU_AD_FORMAT_UNSIGNED_INT32 with 2 channels. The other BC formats require the underlying resource to have the same base * format but with 4 channels. * * - ::CUDA_RESOURCE_VIEW_DESC::width specifies the new width of the texture data. If the resource view format is a block * compressed format, this value has to be 4 times the original width of the resource. For non block compressed formats, * this value has to be equal to that of the original resource. * * - ::CUDA_RESOURCE_VIEW_DESC::height specifies the new height of the texture data. If the resource view format is a block * compressed format, this value has to be 4 times the original height of the resource. For non block compressed formats, * this value has to be equal to that of the original resource. * * - ::CUDA_RESOURCE_VIEW_DESC::depth specifies the new depth of the texture data. This value has to be equal to that of the * original resource. * * - ::CUDA_RESOURCE_VIEW_DESC::firstMipmapLevel specifies the most detailed mipmap level. This will be the new mipmap level zero. * For non-mipmapped resources, this value has to be zero.::CUDA_TEXTURE_DESC::minMipmapLevelClamp and ::CUDA_TEXTURE_DESC::maxMipmapLevelClamp * will be relative to this value. For ex., if the firstMipmapLevel is set to 2, and a minMipmapLevelClamp of 1.2 is specified, * then the actual minimum mipmap level clamp will be 3.2. * * - ::CUDA_RESOURCE_VIEW_DESC::lastMipmapLevel specifies the least detailed mipmap level. For non-mipmapped resources, this value * has to be zero. * * - ::CUDA_RESOURCE_VIEW_DESC::firstLayer specifies the first layer index for layered textures. This will be the new layer zero. * For non-layered resources, this value has to be zero. * * - ::CUDA_RESOURCE_VIEW_DESC::lastLayer specifies the last layer index for layered textures. For non-layered resources, * this value has to be zero. * * * \param pTexObject - Texture object to create * \param pResDesc - Resource descriptor * \param pTexDesc - Texture descriptor * \param pResViewDesc - Resource view descriptor * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuTexObjectDestroy, * ::cudaCreateTextureObject */ CUresult CUDAAPI cuTexObjectCreate(CUtexObject *pTexObject, const CUDA_RESOURCE_DESC *pResDesc, const CUDA_TEXTURE_DESC *pTexDesc, const CUDA_RESOURCE_VIEW_DESC *pResViewDesc); /** * \brief Destroys a texture object * * Destroys the texture object specified by \p texObject. * * \param texObject - Texture object to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuTexObjectCreate, * ::cudaDestroyTextureObject */ CUresult CUDAAPI cuTexObjectDestroy(CUtexObject texObject); /** * \brief Returns a texture object's resource descriptor * * Returns the resource descriptor for the texture object specified by \p texObject. * * \param pResDesc - Resource descriptor * \param texObject - Texture object * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuTexObjectCreate, * ::cudaGetTextureObjectResourceDesc, */ CUresult CUDAAPI cuTexObjectGetResourceDesc(CUDA_RESOURCE_DESC *pResDesc, CUtexObject texObject); /** * \brief Returns a texture object's texture descriptor * * Returns the texture descriptor for the texture object specified by \p texObject. * * \param pTexDesc - Texture descriptor * \param texObject - Texture object * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuTexObjectCreate, * ::cudaGetTextureObjectTextureDesc */ CUresult CUDAAPI cuTexObjectGetTextureDesc(CUDA_TEXTURE_DESC *pTexDesc, CUtexObject texObject); /** * \brief Returns a texture object's resource view descriptor * * Returns the resource view descriptor for the texture object specified by \p texObject. * If no resource view was set for \p texObject, the ::CUDA_ERROR_INVALID_VALUE is returned. * * \param pResViewDesc - Resource view descriptor * \param texObject - Texture object * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuTexObjectCreate, * ::cudaGetTextureObjectResourceViewDesc */ CUresult CUDAAPI cuTexObjectGetResourceViewDesc(CUDA_RESOURCE_VIEW_DESC *pResViewDesc, CUtexObject texObject); /** @} */ /* END CUDA_TEXOBJECT */ /** * \defgroup CUDA_SURFOBJECT Surface Object Management * * ___MANBRIEF___ surface object management functions of the low-level CUDA * driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the surface object management functions of the * low-level CUDA driver application programming interface. The surface * object API is only supported on devices of compute capability 3.0 or higher. * * @{ */ /** * \brief Creates a surface object * * Creates a surface object and returns it in \p pSurfObject. \p pResDesc describes * the data to perform surface load/stores on. ::CUDA_RESOURCE_DESC::resType must be * ::CU_RESOURCE_TYPE_ARRAY and ::CUDA_RESOURCE_DESC::res::array::hArray * must be set to a valid CUDA array handle. ::CUDA_RESOURCE_DESC::flags must be set to zero. * * Surface objects are only supported on devices of compute capability 3.0 or higher. * Additionally, a surface object is an opaque value, and, as such, should only be * accessed through CUDA API calls. * * \param pSurfObject - Surface object to create * \param pResDesc - Resource descriptor * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuSurfObjectDestroy, * ::cudaCreateSurfaceObject */ CUresult CUDAAPI cuSurfObjectCreate(CUsurfObject *pSurfObject, const CUDA_RESOURCE_DESC *pResDesc); /** * \brief Destroys a surface object * * Destroys the surface object specified by \p surfObject. * * \param surfObject - Surface object to destroy * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuSurfObjectCreate, * ::cudaDestroySurfaceObject */ CUresult CUDAAPI cuSurfObjectDestroy(CUsurfObject surfObject); /** * \brief Returns a surface object's resource descriptor * * Returns the resource descriptor for the surface object specified by \p surfObject. * * \param pResDesc - Resource descriptor * \param surfObject - Surface object * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE * * \sa * ::cuSurfObjectCreate, * ::cudaGetSurfaceObjectResourceDesc */ CUresult CUDAAPI cuSurfObjectGetResourceDesc(CUDA_RESOURCE_DESC *pResDesc, CUsurfObject surfObject); /** @} */ /* END CUDA_SURFOBJECT */ /** * \defgroup CUDA_PEER_ACCESS Peer Context Memory Access * * ___MANBRIEF___ direct peer context memory access functions of the low-level * CUDA driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the direct peer context memory access functions * of the low-level CUDA driver application programming interface. * * @{ */ /** * \brief Queries if a device may directly access a peer device's memory. * * Returns in \p *canAccessPeer a value of 1 if contexts on \p dev are capable of * directly accessing memory from contexts on \p peerDev and 0 otherwise. * If direct access of \p peerDev from \p dev is possible, then access may be * enabled on two specific contexts by calling ::cuCtxEnablePeerAccess(). * * \param canAccessPeer - Returned access capability * \param dev - Device from which allocations on \p peerDev are to * be directly accessed. * \param peerDev - Device on which the allocations to be directly accessed * by \p dev reside. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_DEVICE * \notefnerr * * \sa * ::cuCtxEnablePeerAccess, * ::cuCtxDisablePeerAccess, * ::cudaDeviceCanAccessPeer */ CUresult CUDAAPI cuDeviceCanAccessPeer(int *canAccessPeer, CUdevice dev, CUdevice peerDev); /** * \brief Enables direct access to memory allocations in a peer context. * * If both the current context and \p peerContext are on devices which support unified * addressing (as may be queried using ::CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING) and same * major compute capability, then on success all allocations from \p peerContext will * immediately be accessible by the current context. See \ref CUDA_UNIFIED for additional * details. * * Note that access granted by this call is unidirectional and that in order to access * memory from the current context in \p peerContext, a separate symmetric call * to ::cuCtxEnablePeerAccess() is required. * * Note that there are both device-wide and system-wide limitations per system * configuration, as noted in the CUDA Programming Guide under the section * "Peer-to-Peer Memory Access". * * Returns ::CUDA_ERROR_PEER_ACCESS_UNSUPPORTED if ::cuDeviceCanAccessPeer() indicates * that the ::CUdevice of the current context cannot directly access memory * from the ::CUdevice of \p peerContext. * * Returns ::CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED if direct access of * \p peerContext from the current context has already been enabled. * * Returns ::CUDA_ERROR_TOO_MANY_PEERS if direct peer access is not possible * because hardware resources required for peer access have been exhausted. * * Returns ::CUDA_ERROR_INVALID_CONTEXT if there is no current context, \p peerContext * is not a valid context, or if the current context is \p peerContext. * * Returns ::CUDA_ERROR_INVALID_VALUE if \p Flags is not 0. * * \param peerContext - Peer context to enable direct access to from the current context * \param Flags - Reserved for future use and must be set to 0 * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED, * ::CUDA_ERROR_TOO_MANY_PEERS, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_PEER_ACCESS_UNSUPPORTED, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa * ::cuDeviceCanAccessPeer, * ::cuCtxDisablePeerAccess, * ::cudaDeviceEnablePeerAccess */ CUresult CUDAAPI cuCtxEnablePeerAccess(CUcontext peerContext, unsigned int Flags); /** * \brief Disables direct access to memory allocations in a peer context and * unregisters any registered allocations. * Returns ::CUDA_ERROR_PEER_ACCESS_NOT_ENABLED if direct peer access has * not yet been enabled from \p peerContext to the current context. * * Returns ::CUDA_ERROR_INVALID_CONTEXT if there is no current context, or if * \p peerContext is not a valid context. * * \param peerContext - Peer context to disable direct access to * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_PEER_ACCESS_NOT_ENABLED, * ::CUDA_ERROR_INVALID_CONTEXT, * \notefnerr * * \sa * ::cuDeviceCanAccessPeer, * ::cuCtxEnablePeerAccess, * ::cudaDeviceDisablePeerAccess */ CUresult CUDAAPI cuCtxDisablePeerAccess(CUcontext peerContext); /** * \brief Queries attributes of the link between two devices. * * Returns in \p *value the value of the requested attribute \p attrib of the * link between \p srcDevice and \p dstDevice. The supported attributes are: * - ::CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK: A relative value indicating the * performance of the link between two devices. * - ::CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED P2P: 1 if P2P Access is enable. * - ::CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED: 1 if Atomic operations over * the link are supported. * - ::CU_DEVICE_P2P_ATTRIBUTE_CUDA_ARRAY_ACCESS_SUPPORTED: 1 if cudaArray can * be accessed over the link. * * Returns ::CUDA_ERROR_INVALID_DEVICE if \p srcDevice or \p dstDevice are not valid * or if they represent the same device. * * Returns ::CUDA_ERROR_INVALID_VALUE if \p attrib is not valid or if \p value is * a null pointer. * * \param value - Returned value of the requested attribute * \param attrib - The requested attribute of the link between \p srcDevice and \p dstDevice. * \param srcDevice - The source device of the target link. * \param dstDevice - The destination device of the target link. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_DEVICE, * ::CUDA_ERROR_INVALID_VALUE * \notefnerr * * \sa * ::cuCtxEnablePeerAccess, * ::cuCtxDisablePeerAccess, * ::cuDeviceCanAccessPeer, * ::cudaDeviceGetP2PAttribute */ CUresult CUDAAPI cuDeviceGetP2PAttribute(int* value, CUdevice_P2PAttribute attrib, CUdevice srcDevice, CUdevice dstDevice); /** @} */ /* END CUDA_PEER_ACCESS */ /** * \defgroup CUDA_GRAPHICS Graphics Interoperability * * ___MANBRIEF___ graphics interoperability functions of the low-level CUDA * driver API (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the graphics interoperability functions of the * low-level CUDA driver application programming interface. * * @{ */ /** * \brief Unregisters a graphics resource for access by CUDA * * Unregisters the graphics resource \p resource so it is not accessible by * CUDA unless registered again. * * If \p resource is invalid then ::CUDA_ERROR_INVALID_HANDLE is * returned. * * \param resource - Resource to unregister * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_UNKNOWN * \notefnerr * * \sa * ::cuGraphicsD3D9RegisterResource, * ::cuGraphicsD3D10RegisterResource, * ::cuGraphicsD3D11RegisterResource, * ::cuGraphicsGLRegisterBuffer, * ::cuGraphicsGLRegisterImage, * ::cudaGraphicsUnregisterResource */ CUresult CUDAAPI cuGraphicsUnregisterResource(CUgraphicsResource resource); /** * \brief Get an array through which to access a subresource of a mapped graphics resource. * * Returns in \p *pArray an array through which the subresource of the mapped * graphics resource \p resource which corresponds to array index \p arrayIndex * and mipmap level \p mipLevel may be accessed. The value set in \p *pArray may * change every time that \p resource is mapped. * * If \p resource is not a texture then it cannot be accessed via an array and * ::CUDA_ERROR_NOT_MAPPED_AS_ARRAY is returned. * If \p arrayIndex is not a valid array index for \p resource then * ::CUDA_ERROR_INVALID_VALUE is returned. * If \p mipLevel is not a valid mipmap level for \p resource then * ::CUDA_ERROR_INVALID_VALUE is returned. * If \p resource is not mapped then ::CUDA_ERROR_NOT_MAPPED is returned. * * \param pArray - Returned array through which a subresource of \p resource may be accessed * \param resource - Mapped resource to access * \param arrayIndex - Array index for array textures or cubemap face * index as defined by ::CUarray_cubemap_face for * cubemap textures for the subresource to access * \param mipLevel - Mipmap level for the subresource to access * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_MAPPED, * ::CUDA_ERROR_NOT_MAPPED_AS_ARRAY * \notefnerr * * \sa * ::cuGraphicsResourceGetMappedPointer, * ::cudaGraphicsSubResourceGetMappedArray */ CUresult CUDAAPI cuGraphicsSubResourceGetMappedArray(CUarray *pArray, CUgraphicsResource resource, unsigned int arrayIndex, unsigned int mipLevel); /** * \brief Get a mipmapped array through which to access a mapped graphics resource. * * Returns in \p *pMipmappedArray a mipmapped array through which the mapped graphics * resource \p resource. The value set in \p *pMipmappedArray may change every time * that \p resource is mapped. * * If \p resource is not a texture then it cannot be accessed via a mipmapped array and * ::CUDA_ERROR_NOT_MAPPED_AS_ARRAY is returned. * If \p resource is not mapped then ::CUDA_ERROR_NOT_MAPPED is returned. * * \param pMipmappedArray - Returned mipmapped array through which \p resource may be accessed * \param resource - Mapped resource to access * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_MAPPED, * ::CUDA_ERROR_NOT_MAPPED_AS_ARRAY * \notefnerr * * \sa * ::cuGraphicsResourceGetMappedPointer, * ::cudaGraphicsResourceGetMappedMipmappedArray */ CUresult CUDAAPI cuGraphicsResourceGetMappedMipmappedArray(CUmipmappedArray *pMipmappedArray, CUgraphicsResource resource); /** * \brief Get a device pointer through which to access a mapped graphics resource. * * Returns in \p *pDevPtr a pointer through which the mapped graphics resource * \p resource may be accessed. * Returns in \p pSize the size of the memory in bytes which may be accessed from that pointer. * The value set in \p pPointer may change every time that \p resource is mapped. * * If \p resource is not a buffer then it cannot be accessed via a pointer and * ::CUDA_ERROR_NOT_MAPPED_AS_POINTER is returned. * If \p resource is not mapped then ::CUDA_ERROR_NOT_MAPPED is returned. * * * \param pDevPtr - Returned pointer through which \p resource may be accessed * \param pSize - Returned size of the buffer accessible starting at \p *pPointer * \param resource - Mapped resource to access * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_MAPPED, * ::CUDA_ERROR_NOT_MAPPED_AS_POINTER * \notefnerr * * \sa * ::cuGraphicsMapResources, * ::cuGraphicsSubResourceGetMappedArray, * ::cudaGraphicsResourceGetMappedPointer */ CUresult CUDAAPI cuGraphicsResourceGetMappedPointer(CUdeviceptr *pDevPtr, size_t *pSize, CUgraphicsResource resource); /** * \brief Set usage flags for mapping a graphics resource * * Set \p flags for mapping the graphics resource \p resource. * * Changes to \p flags will take effect the next time \p resource is mapped. * The \p flags argument may be any of the following: * - ::CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE: Specifies no hints about how this * resource will be used. It is therefore assumed that this resource will be * read from and written to by CUDA kernels. This is the default value. * - ::CU_GRAPHICS_MAP_RESOURCE_FLAGS_READONLY: Specifies that CUDA kernels which * access this resource will not write to this resource. * - ::CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITEDISCARD: Specifies that CUDA kernels * which access this resource will not read from this resource and will * write over the entire contents of the resource, so none of the data * previously stored in the resource will be preserved. * * If \p resource is presently mapped for access by CUDA then * ::CUDA_ERROR_ALREADY_MAPPED is returned. * If \p flags is not one of the above values then ::CUDA_ERROR_INVALID_VALUE is returned. * * \param resource - Registered resource to set flags for * \param flags - Parameters for resource mapping * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_ALREADY_MAPPED * \notefnerr * * \sa * ::cuGraphicsMapResources, * ::cudaGraphicsResourceSetMapFlags */ CUresult CUDAAPI cuGraphicsResourceSetMapFlags(CUgraphicsResource resource, unsigned int flags); /** * \brief Map graphics resources for access by CUDA * * Maps the \p count graphics resources in \p resources for access by CUDA. * * The resources in \p resources may be accessed by CUDA until they * are unmapped. The graphics API from which \p resources were registered * should not access any resources while they are mapped by CUDA. If an * application does so, the results are undefined. * * This function provides the synchronization guarantee that any graphics calls * issued before ::cuGraphicsMapResources() will complete before any subsequent CUDA * work issued in \p stream begins. * * If \p resources includes any duplicate entries then ::CUDA_ERROR_INVALID_HANDLE is returned. * If any of \p resources are presently mapped for access by CUDA then ::CUDA_ERROR_ALREADY_MAPPED is returned. * * \param count - Number of resources to map * \param resources - Resources to map for CUDA usage * \param hStream - Stream with which to synchronize * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_ALREADY_MAPPED, * ::CUDA_ERROR_UNKNOWN * \note_null_stream * \notefnerr * * \sa * ::cuGraphicsResourceGetMappedPointer, * ::cuGraphicsSubResourceGetMappedArray, * ::cuGraphicsUnmapResources, * ::cudaGraphicsMapResources */ CUresult CUDAAPI cuGraphicsMapResources(unsigned int count, CUgraphicsResource *resources, CUstream hStream); /** * \brief Unmap graphics resources. * * Unmaps the \p count graphics resources in \p resources. * * Once unmapped, the resources in \p resources may not be accessed by CUDA * until they are mapped again. * * This function provides the synchronization guarantee that any CUDA work issued * in \p stream before ::cuGraphicsUnmapResources() will complete before any * subsequently issued graphics work begins. * * * If \p resources includes any duplicate entries then ::CUDA_ERROR_INVALID_HANDLE is returned. * If any of \p resources are not presently mapped for access by CUDA then ::CUDA_ERROR_NOT_MAPPED is returned. * * \param count - Number of resources to unmap * \param resources - Resources to unmap * \param hStream - Stream with which to synchronize * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_DEINITIALIZED, * ::CUDA_ERROR_NOT_INITIALIZED, * ::CUDA_ERROR_INVALID_CONTEXT, * ::CUDA_ERROR_INVALID_HANDLE, * ::CUDA_ERROR_NOT_MAPPED, * ::CUDA_ERROR_UNKNOWN * \note_null_stream * \notefnerr * * \sa * ::cuGraphicsMapResources, * ::cudaGraphicsUnmapResources */ CUresult CUDAAPI cuGraphicsUnmapResources(unsigned int count, CUgraphicsResource *resources, CUstream hStream); /** @} */ /* END CUDA_GRAPHICS */ /** * \defgroup CUDA_DRIVER_ENTRY_POINT Driver Entry Point Access * * ___MANBRIEF___ driver entry point access functions of the low-level CUDA driver API * (___CURRENT_FILE___) ___ENDMANBRIEF___ * * This section describes the driver entry point access functions of the low-level CUDA * driver application programming interface. * * @{ */ /** * \brief Returns the requested driver API function pointer * * Returns in \p **pfn the address of the CUDA driver function for the requested * CUDA version and flags. * * The CUDA version is specified as (1000 * major + 10 * minor), so CUDA 11.2 * should be specified as 11020. For a requested driver symbol, if the specified * CUDA version is greater than or equal to the CUDA version in which the driver symbol * was introduced, this API will return the function pointer to the corresponding * versioned function. * * The pointer returned by the API should be cast to a function pointer matching the * requested driver function's definition in the API header file. The function pointer * typedef can be picked up from the corresponding typedefs header file. For example, * cudaTypedefs.h consists of function pointer typedefs for driver APIs defined in cuda.h. * * The API will return ::CUDA_ERROR_NOT_FOUND if the requested driver function is not * supported on the platform, no ABI compatible driver function exists for the specified * \p cudaVersion or if the driver symbol is invalid. * * The requested flags can be: * - ::CU_GET_PROC_ADDRESS_DEFAULT: This is the default mode. This is equivalent to * ::CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM if the code is compiled with * --default-stream per-thread compilation flag or the macro CUDA_API_PER_THREAD_DEFAULT_STREAM * is defined; ::CU_GET_PROC_ADDRESS_LEGACY_STREAM otherwise. * - ::CU_GET_PROC_ADDRESS_LEGACY_STREAM: This will enable the search for all driver symbols * that match the requested driver symbol name except the corresponding per-thread versions. * - ::CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM: This will enable the search for all * driver symbols that match the requested driver symbol name including the per-thread * versions. If a per-thread version is not found, the API will return the legacy version * of the driver function. * * \param symbol - The base name of the driver API function to look for. As an example, * for the driver API ::cuMemAlloc_v2, \p symbol would be cuMemAlloc and * \p cudaVersion would be the ABI compatible CUDA version for the _v2 variant. * \param pfn - Location to return the function pointer to the requested driver function * \param cudaVersion - The CUDA version to look for the requested driver symbol * \param flags - Flags to specify search options. * * \return * ::CUDA_SUCCESS, * ::CUDA_ERROR_INVALID_VALUE, * ::CUDA_ERROR_NOT_SUPPORTED, * ::CUDA_ERROR_NOT_FOUND * \note_version_mixing * * \sa * ::cudaGetDriverEntryPoint */ CUresult CUDAAPI cuGetProcAddress(const char *symbol, void **pfn, int cudaVersion, cuuint64_t flags); /** @} */ /* END CUDA_DRIVER_ENTRY_POINT */ CUresult CUDAAPI cuGetExportTable(const void **ppExportTable, const CUuuid *pExportTableId); /** * CUDA API versioning support */ #if defined(__CUDA_API_VERSION_INTERNAL) #undef cuMemHostRegister #undef cuGraphicsResourceSetMapFlags #undef cuLinkCreate #undef cuLinkAddData #undef cuLinkAddFile #undef cuDeviceTotalMem #undef cuCtxCreate #undef cuModuleGetGlobal #undef cuMemGetInfo #undef cuMemAlloc #undef cuMemAllocPitch #undef cuMemFree #undef cuMemGetAddressRange #undef cuMemAllocHost #undef cuMemHostGetDevicePointer #undef cuMemcpyHtoD #undef cuMemcpyDtoH #undef cuMemcpyDtoD #undef cuMemcpyDtoA #undef cuMemcpyAtoD #undef cuMemcpyHtoA #undef cuMemcpyAtoH #undef cuMemcpyAtoA #undef cuMemcpyHtoAAsync #undef cuMemcpyAtoHAsync #undef cuMemcpy2D #undef cuMemcpy2DUnaligned #undef cuMemcpy3D #undef cuMemcpyHtoDAsync #undef cuMemcpyDtoHAsync #undef cuMemcpyDtoDAsync #undef cuMemcpy2DAsync #undef cuMemcpy3DAsync #undef cuMemsetD8 #undef cuMemsetD16 #undef cuMemsetD32 #undef cuMemsetD2D8 #undef cuMemsetD2D16 #undef cuMemsetD2D32 #undef cuArrayCreate #undef cuArrayGetDescriptor #undef cuArray3DCreate #undef cuArray3DGetDescriptor #undef cuTexRefSetAddress #undef cuTexRefSetAddress2D #undef cuTexRefGetAddress #undef cuGraphicsResourceGetMappedPointer #undef cuCtxDestroy #undef cuCtxPopCurrent #undef cuCtxPushCurrent #undef cuStreamDestroy #undef cuEventDestroy #undef cuMemcpy #undef cuMemcpyAsync #undef cuMemcpyPeer #undef cuMemcpyPeerAsync #undef cuMemcpy3DPeer #undef cuMemcpy3DPeerAsync #undef cuMemsetD8Async #undef cuMemsetD16Async #undef cuMemsetD32Async #undef cuMemsetD2D8Async #undef cuMemsetD2D16Async #undef cuMemsetD2D32Async #undef cuStreamGetPriority #undef cuStreamGetFlags #undef cuStreamGetCtx #undef cuStreamWaitEvent #undef cuStreamAddCallback #undef cuStreamAttachMemAsync #undef cuStreamQuery #undef cuStreamSynchronize #undef cuEventRecord #undef cuEventRecordWithFlags #undef cuLaunchKernel #undef cuLaunchHostFunc #undef cuGraphicsMapResources #undef cuGraphicsUnmapResources #undef cuStreamWriteValue32 #undef cuStreamWaitValue32 #undef cuStreamWriteValue64 #undef cuStreamWaitValue64 #undef cuStreamBatchMemOp #undef cuMemPrefetchAsync #undef cuLaunchCooperativeKernel #undef cuSignalExternalSemaphoresAsync #undef cuWaitExternalSemaphoresAsync #undef cuStreamBeginCapture #undef cuStreamEndCapture #undef cuStreamIsCapturing #undef cuStreamGetCaptureInfo #undef cuStreamGetCaptureInfo_v2 #undef cuGraphUpload #undef cuGraphLaunch #undef cuDevicePrimaryCtxRelease #undef cuDevicePrimaryCtxReset #undef cuDevicePrimaryCtxSetFlags #undef cuIpcOpenMemHandle #undef cuStreamCopyAttributes #undef cuStreamSetAttribute #undef cuStreamGetAttribute #undef cuGraphInstantiate #undef cuMemMapArrayAsync #undef cuMemFreeAsync #undef cuMemAllocAsync #undef cuMemAllocFromPoolAsync #undef cuStreamUpdateCaptureDependencies CUresult CUDAAPI cuMemHostRegister(void *p, size_t bytesize, unsigned int Flags); CUresult CUDAAPI cuGraphicsResourceSetMapFlags(CUgraphicsResource resource, unsigned int flags); CUresult CUDAAPI cuLinkCreate(unsigned int numOptions, CUjit_option *options, void **optionValues, CUlinkState *stateOut); CUresult CUDAAPI cuLinkAddData(CUlinkState state, CUjitInputType type, void *data, size_t size, const char *name, unsigned int numOptions, CUjit_option *options, void **optionValues); CUresult CUDAAPI cuLinkAddFile(CUlinkState state, CUjitInputType type, const char *path, unsigned int numOptions, CUjit_option *options, void **optionValues); CUresult CUDAAPI cuTexRefSetAddress2D_v2(CUtexref hTexRef, const CUDA_ARRAY_DESCRIPTOR *desc, CUdeviceptr dptr, size_t Pitch); typedef unsigned int CUdeviceptr_v1; typedef struct CUDA_MEMCPY2D_v1_st { unsigned int srcXInBytes; /**< Source X in bytes */ unsigned int srcY; /**< Source Y */ CUmemorytype srcMemoryType; /**< Source memory type (host, device, array) */ const void *srcHost; /**< Source host pointer */ CUdeviceptr_v1 srcDevice; /**< Source device pointer */ CUarray srcArray; /**< Source array reference */ unsigned int srcPitch; /**< Source pitch (ignored when src is array) */ unsigned int dstXInBytes; /**< Destination X in bytes */ unsigned int dstY; /**< Destination Y */ CUmemorytype dstMemoryType; /**< Destination memory type (host, device, array) */ void *dstHost; /**< Destination host pointer */ CUdeviceptr_v1 dstDevice; /**< Destination device pointer */ CUarray dstArray; /**< Destination array reference */ unsigned int dstPitch; /**< Destination pitch (ignored when dst is array) */ unsigned int WidthInBytes; /**< Width of 2D memory copy in bytes */ unsigned int Height; /**< Height of 2D memory copy */ } CUDA_MEMCPY2D_v1; typedef struct CUDA_MEMCPY3D_v1_st { unsigned int srcXInBytes; /**< Source X in bytes */ unsigned int srcY; /**< Source Y */ unsigned int srcZ; /**< Source Z */ unsigned int srcLOD; /**< Source LOD */ CUmemorytype srcMemoryType; /**< Source memory type (host, device, array) */ const void *srcHost; /**< Source host pointer */ CUdeviceptr_v1 srcDevice; /**< Source device pointer */ CUarray srcArray; /**< Source array reference */ void *reserved0; /**< Must be NULL */ unsigned int srcPitch; /**< Source pitch (ignored when src is array) */ unsigned int srcHeight; /**< Source height (ignored when src is array; may be 0 if Depth==1) */ unsigned int dstXInBytes; /**< Destination X in bytes */ unsigned int dstY; /**< Destination Y */ unsigned int dstZ; /**< Destination Z */ unsigned int dstLOD; /**< Destination LOD */ CUmemorytype dstMemoryType; /**< Destination memory type (host, device, array) */ void *dstHost; /**< Destination host pointer */ CUdeviceptr_v1 dstDevice; /**< Destination device pointer */ CUarray dstArray; /**< Destination array reference */ void *reserved1; /**< Must be NULL */ unsigned int dstPitch; /**< Destination pitch (ignored when dst is array) */ unsigned int dstHeight; /**< Destination height (ignored when dst is array; may be 0 if Depth==1) */ unsigned int WidthInBytes; /**< Width of 3D memory copy in bytes */ unsigned int Height; /**< Height of 3D memory copy */ unsigned int Depth; /**< Depth of 3D memory copy */ } CUDA_MEMCPY3D_v1; typedef struct CUDA_ARRAY_DESCRIPTOR_v1_st { unsigned int Width; /**< Width of array */ unsigned int Height; /**< Height of array */ CUarray_format Format; /**< Array format */ unsigned int NumChannels; /**< Channels per array element */ } CUDA_ARRAY_DESCRIPTOR_v1; typedef struct CUDA_ARRAY3D_DESCRIPTOR_v1_st { unsigned int Width; /**< Width of 3D array */ unsigned int Height; /**< Height of 3D array */ unsigned int Depth; /**< Depth of 3D array */ CUarray_format Format; /**< Array format */ unsigned int NumChannels; /**< Channels per array element */ unsigned int Flags; /**< Flags */ } CUDA_ARRAY3D_DESCRIPTOR_v1; CUresult CUDAAPI cuDeviceTotalMem(unsigned int *bytes, CUdevice dev); CUresult CUDAAPI cuCtxCreate(CUcontext *pctx, unsigned int flags, CUdevice dev); CUresult CUDAAPI cuModuleGetGlobal(CUdeviceptr_v1 *dptr, unsigned int *bytes, CUmodule hmod, const char *name); CUresult CUDAAPI cuMemGetInfo(unsigned int *free, unsigned int *total); CUresult CUDAAPI cuMemAlloc(CUdeviceptr_v1 *dptr, unsigned int bytesize); CUresult CUDAAPI cuMemAllocPitch(CUdeviceptr_v1 *dptr, unsigned int *pPitch, unsigned int WidthInBytes, unsigned int Height, unsigned int ElementSizeBytes); CUresult CUDAAPI cuMemFree(CUdeviceptr_v1 dptr); CUresult CUDAAPI cuMemGetAddressRange(CUdeviceptr_v1 *pbase, unsigned int *psize, CUdeviceptr_v1 dptr); CUresult CUDAAPI cuMemAllocHost(void **pp, unsigned int bytesize); CUresult CUDAAPI cuMemHostGetDevicePointer(CUdeviceptr_v1 *pdptr, void *p, unsigned int Flags); CUresult CUDAAPI cuMemcpyHtoD(CUdeviceptr_v1 dstDevice, const void *srcHost, unsigned int ByteCount); CUresult CUDAAPI cuMemcpyDtoH(void *dstHost, CUdeviceptr_v1 srcDevice, unsigned int ByteCount); CUresult CUDAAPI cuMemcpyDtoD(CUdeviceptr_v1 dstDevice, CUdeviceptr_v1 srcDevice, unsigned int ByteCount); CUresult CUDAAPI cuMemcpyDtoA(CUarray dstArray, unsigned int dstOffset, CUdeviceptr_v1 srcDevice, unsigned int ByteCount); CUresult CUDAAPI cuMemcpyAtoD(CUdeviceptr_v1 dstDevice, CUarray srcArray, unsigned int srcOffset, unsigned int ByteCount); CUresult CUDAAPI cuMemcpyHtoA(CUarray dstArray, unsigned int dstOffset, const void *srcHost, unsigned int ByteCount); CUresult CUDAAPI cuMemcpyAtoH(void *dstHost, CUarray srcArray, unsigned int srcOffset, unsigned int ByteCount); CUresult CUDAAPI cuMemcpyAtoA(CUarray dstArray, unsigned int dstOffset, CUarray srcArray, unsigned int srcOffset, unsigned int ByteCount); CUresult CUDAAPI cuMemcpyHtoAAsync(CUarray dstArray, unsigned int dstOffset, const void *srcHost, unsigned int ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpyAtoHAsync(void *dstHost, CUarray srcArray, unsigned int srcOffset, unsigned int ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpy2D(const CUDA_MEMCPY2D_v1 *pCopy); CUresult CUDAAPI cuMemcpy2DUnaligned(const CUDA_MEMCPY2D_v1 *pCopy); CUresult CUDAAPI cuMemcpy3D(const CUDA_MEMCPY3D_v1 *pCopy); CUresult CUDAAPI cuMemcpyHtoDAsync(CUdeviceptr_v1 dstDevice, const void *srcHost, unsigned int ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpyDtoHAsync(void *dstHost, CUdeviceptr_v1 srcDevice, unsigned int ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpyDtoDAsync(CUdeviceptr_v1 dstDevice, CUdeviceptr_v1 srcDevice, unsigned int ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpy2DAsync(const CUDA_MEMCPY2D_v1 *pCopy, CUstream hStream); CUresult CUDAAPI cuMemcpy3DAsync(const CUDA_MEMCPY3D_v1 *pCopy, CUstream hStream); CUresult CUDAAPI cuMemsetD8(CUdeviceptr_v1 dstDevice, unsigned char uc, unsigned int N); CUresult CUDAAPI cuMemsetD16(CUdeviceptr_v1 dstDevice, unsigned short us, unsigned int N); CUresult CUDAAPI cuMemsetD32(CUdeviceptr_v1 dstDevice, unsigned int ui, unsigned int N); CUresult CUDAAPI cuMemsetD2D8(CUdeviceptr_v1 dstDevice, unsigned int dstPitch, unsigned char uc, unsigned int Width, unsigned int Height); CUresult CUDAAPI cuMemsetD2D16(CUdeviceptr_v1 dstDevice, unsigned int dstPitch, unsigned short us, unsigned int Width, unsigned int Height); CUresult CUDAAPI cuMemsetD2D32(CUdeviceptr_v1 dstDevice, unsigned int dstPitch, unsigned int ui, unsigned int Width, unsigned int Height); CUresult CUDAAPI cuArrayCreate(CUarray *pHandle, const CUDA_ARRAY_DESCRIPTOR_v1 *pAllocateArray); CUresult CUDAAPI cuArrayGetDescriptor(CUDA_ARRAY_DESCRIPTOR_v1 *pArrayDescriptor, CUarray hArray); CUresult CUDAAPI cuArray3DCreate(CUarray *pHandle, const CUDA_ARRAY3D_DESCRIPTOR_v1 *pAllocateArray); CUresult CUDAAPI cuArray3DGetDescriptor(CUDA_ARRAY3D_DESCRIPTOR_v1 *pArrayDescriptor, CUarray hArray); CUresult CUDAAPI cuTexRefSetAddress(unsigned int *ByteOffset, CUtexref hTexRef, CUdeviceptr_v1 dptr, unsigned int bytes); CUresult CUDAAPI cuTexRefSetAddress2D(CUtexref hTexRef, const CUDA_ARRAY_DESCRIPTOR_v1 *desc, CUdeviceptr_v1 dptr, unsigned int Pitch); CUresult CUDAAPI cuTexRefGetAddress(CUdeviceptr_v1 *pdptr, CUtexref hTexRef); CUresult CUDAAPI cuGraphicsResourceGetMappedPointer(CUdeviceptr_v1 *pDevPtr, unsigned int *pSize, CUgraphicsResource resource); CUresult CUDAAPI cuCtxDestroy(CUcontext ctx); CUresult CUDAAPI cuCtxPopCurrent(CUcontext *pctx); CUresult CUDAAPI cuCtxPushCurrent(CUcontext ctx); CUresult CUDAAPI cuStreamDestroy(CUstream hStream); CUresult CUDAAPI cuEventDestroy(CUevent hEvent); CUresult CUDAAPI cuDevicePrimaryCtxRelease(CUdevice dev); CUresult CUDAAPI cuDevicePrimaryCtxReset(CUdevice dev); CUresult CUDAAPI cuDevicePrimaryCtxSetFlags(CUdevice dev, unsigned int flags); CUresult CUDAAPI cuMemcpyHtoD_v2(CUdeviceptr dstDevice, const void *srcHost, size_t ByteCount); CUresult CUDAAPI cuMemcpyDtoH_v2(void *dstHost, CUdeviceptr srcDevice, size_t ByteCount); CUresult CUDAAPI cuMemcpyDtoD_v2(CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount); CUresult CUDAAPI cuMemcpyDtoA_v2(CUarray dstArray, size_t dstOffset, CUdeviceptr srcDevice, size_t ByteCount); CUresult CUDAAPI cuMemcpyAtoD_v2(CUdeviceptr dstDevice, CUarray srcArray, size_t srcOffset, size_t ByteCount); CUresult CUDAAPI cuMemcpyHtoA_v2(CUarray dstArray, size_t dstOffset, const void *srcHost, size_t ByteCount); CUresult CUDAAPI cuMemcpyAtoH_v2(void *dstHost, CUarray srcArray, size_t srcOffset, size_t ByteCount); CUresult CUDAAPI cuMemcpyAtoA_v2(CUarray dstArray, size_t dstOffset, CUarray srcArray, size_t srcOffset, size_t ByteCount); CUresult CUDAAPI cuMemcpyHtoAAsync_v2(CUarray dstArray, size_t dstOffset, const void *srcHost, size_t ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpyAtoHAsync_v2(void *dstHost, CUarray srcArray, size_t srcOffset, size_t ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpy2D_v2(const CUDA_MEMCPY2D *pCopy); CUresult CUDAAPI cuMemcpy2DUnaligned_v2(const CUDA_MEMCPY2D *pCopy); CUresult CUDAAPI cuMemcpy3D_v2(const CUDA_MEMCPY3D *pCopy); CUresult CUDAAPI cuMemcpyHtoDAsync_v2(CUdeviceptr dstDevice, const void *srcHost, size_t ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpyDtoHAsync_v2(void *dstHost, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpyDtoDAsync_v2(CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpy2DAsync_v2(const CUDA_MEMCPY2D *pCopy, CUstream hStream); CUresult CUDAAPI cuMemcpy3DAsync_v2(const CUDA_MEMCPY3D *pCopy, CUstream hStream); CUresult CUDAAPI cuMemsetD8_v2(CUdeviceptr dstDevice, unsigned char uc, size_t N); CUresult CUDAAPI cuMemsetD16_v2(CUdeviceptr dstDevice, unsigned short us, size_t N); CUresult CUDAAPI cuMemsetD32_v2(CUdeviceptr dstDevice, unsigned int ui, size_t N); CUresult CUDAAPI cuMemsetD2D8_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned char uc, size_t Width, size_t Height); CUresult CUDAAPI cuMemsetD2D16_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned short us, size_t Width, size_t Height); CUresult CUDAAPI cuMemsetD2D32_v2(CUdeviceptr dstDevice, size_t dstPitch, unsigned int ui, size_t Width, size_t Height); CUresult CUDAAPI cuMemcpy(CUdeviceptr dst, CUdeviceptr src, size_t ByteCount); CUresult CUDAAPI cuMemcpyAsync(CUdeviceptr dst, CUdeviceptr src, size_t ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpyPeer(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount); CUresult CUDAAPI cuMemcpyPeerAsync(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount, CUstream hStream); CUresult CUDAAPI cuMemcpy3DPeer(const CUDA_MEMCPY3D_PEER *pCopy); CUresult CUDAAPI cuMemcpy3DPeerAsync(const CUDA_MEMCPY3D_PEER *pCopy, CUstream hStream); CUresult CUDAAPI cuMemsetD8Async(CUdeviceptr dstDevice, unsigned char uc, size_t N, CUstream hStream); CUresult CUDAAPI cuMemsetD16Async(CUdeviceptr dstDevice, unsigned short us, size_t N, CUstream hStream); CUresult CUDAAPI cuMemsetD32Async(CUdeviceptr dstDevice, unsigned int ui, size_t N, CUstream hStream); CUresult CUDAAPI cuMemsetD2D8Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned char uc, size_t Width, size_t Height, CUstream hStream); CUresult CUDAAPI cuMemsetD2D16Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned short us, size_t Width, size_t Height, CUstream hStream); CUresult CUDAAPI cuMemsetD2D32Async(CUdeviceptr dstDevice, size_t dstPitch, unsigned int ui, size_t Width, size_t Height, CUstream hStream); CUresult CUDAAPI cuStreamGetPriority(CUstream hStream, int *priority); CUresult CUDAAPI cuStreamGetFlags(CUstream hStream, unsigned int *flags); CUresult CUDAAPI cuStreamGetCtx(CUstream hStream, CUcontext *pctx); CUresult CUDAAPI cuStreamWaitEvent(CUstream hStream, CUevent hEvent, unsigned int Flags); CUresult CUDAAPI cuStreamAddCallback(CUstream hStream, CUstreamCallback callback, void *userData, unsigned int flags); CUresult CUDAAPI cuStreamAttachMemAsync(CUstream hStream, CUdeviceptr dptr, size_t length, unsigned int flags); CUresult CUDAAPI cuStreamQuery(CUstream hStream); CUresult CUDAAPI cuStreamSynchronize(CUstream hStream); CUresult CUDAAPI cuEventRecord(CUevent hEvent, CUstream hStream); CUresult CUDAAPI cuEventRecordWithFlags(CUevent hEvent, CUstream hStream, unsigned int flags); CUresult CUDAAPI cuLaunchKernel(CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hStream, void **kernelParams, void **extra); CUresult CUDAAPI cuLaunchHostFunc(CUstream hStream, CUhostFn fn, void *userData); CUresult CUDAAPI cuGraphicsMapResources(unsigned int count, CUgraphicsResource *resources, CUstream hStream); CUresult CUDAAPI cuGraphicsUnmapResources(unsigned int count, CUgraphicsResource *resources, CUstream hStream); CUresult CUDAAPI cuStreamWriteValue32(CUstream stream, CUdeviceptr addr, cuuint32_t value, unsigned int flags); CUresult CUDAAPI cuStreamWaitValue32(CUstream stream, CUdeviceptr addr, cuuint32_t value, unsigned int flags); CUresult CUDAAPI cuStreamWriteValue64(CUstream stream, CUdeviceptr addr, cuuint64_t value, unsigned int flags); CUresult CUDAAPI cuStreamWaitValue64(CUstream stream, CUdeviceptr addr, cuuint64_t value, unsigned int flags); CUresult CUDAAPI cuStreamBatchMemOp(CUstream stream, unsigned int count, CUstreamBatchMemOpParams *paramArray, unsigned int flags); CUresult CUDAAPI cuMemPrefetchAsync(CUdeviceptr devPtr, size_t count, CUdevice dstDevice, CUstream hStream); CUresult CUDAAPI cuLaunchCooperativeKernel(CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hStream, void **kernelParams); CUresult CUDAAPI cuSignalExternalSemaphoresAsync(const CUexternalSemaphore *extSemArray, const CUDA_EXTERNAL_SEMAPHORE_SIGNAL_PARAMS *paramsArray, unsigned int numExtSems, CUstream stream); CUresult CUDAAPI cuWaitExternalSemaphoresAsync(const CUexternalSemaphore *extSemArray, const CUDA_EXTERNAL_SEMAPHORE_WAIT_PARAMS *paramsArray, unsigned int numExtSems, CUstream stream); CUresult CUDAAPI cuStreamBeginCapture(CUstream hStream); CUresult CUDAAPI cuStreamBeginCapture_ptsz(CUstream hStream); CUresult CUDAAPI cuStreamBeginCapture_v2(CUstream hStream, CUstreamCaptureMode mode); CUresult CUDAAPI cuStreamEndCapture(CUstream hStream, CUgraph *phGraph); CUresult CUDAAPI cuStreamIsCapturing(CUstream hStream, CUstreamCaptureStatus *captureStatus); CUresult CUDAAPI cuStreamGetCaptureInfo(CUstream hStream, CUstreamCaptureStatus *captureStatus_out, cuuint64_t *id_out); CUresult CUDAAPI cuStreamGetCaptureInfo_v2(CUstream hStream, CUstreamCaptureStatus *captureStatus_out, cuuint64_t *id_out, CUgraph *graph_out, const CUgraphNode **dependencies_out, size_t *numDependencies_out); CUresult CUDAAPI cuGraphUpload(CUgraphExec hGraph, CUstream hStream); CUresult CUDAAPI cuGraphLaunch(CUgraphExec hGraph, CUstream hStream); CUresult CUDAAPI cuStreamCopyAttributes(CUstream dstStream, CUstream srcStream); CUresult CUDAAPI cuStreamGetAttribute(CUstream hStream, CUstreamAttrID attr, CUstreamAttrValue *value); CUresult CUDAAPI cuStreamSetAttribute(CUstream hStream, CUstreamAttrID attr, const CUstreamAttrValue *param); CUresult CUDAAPI cuIpcOpenMemHandle(CUdeviceptr *pdptr, CUipcMemHandle handle, unsigned int Flags); CUresult CUDAAPI cuGraphInstantiate(CUgraphExec *phGraphExec, CUgraph hGraph, CUgraphNode *phErrorNode, char *logBuffer, size_t bufferSize); CUresult CUDAAPI cuMemMapArrayAsync(CUarrayMapInfo *mapInfoList, unsigned int count, CUstream hStream); CUresult CUDAAPI cuMemFreeAsync(CUdeviceptr dptr, CUstream hStream); CUresult CUDAAPI cuMemAllocAsync(CUdeviceptr *dptr, size_t bytesize, CUstream hStream); CUresult CUDAAPI cuMemAllocFromPoolAsync(CUdeviceptr *dptr, size_t bytesize, CUmemoryPool pool, CUstream hStream); CUresult CUDAAPI cuStreamUpdateCaptureDependencies(CUstream hStream, CUgraphNode *dependencies, size_t numDependencies, unsigned int flags); #elif defined(__CUDA_API_PER_THREAD_DEFAULT_STREAM) static inline CUresult cuGetProcAddress_ptsz(const char *symbol, void **funcPtr, int driverVersion, cuuint64_t flags) { const int procAddressMask = (CU_GET_PROC_ADDRESS_LEGACY_STREAM| CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM); if ((flags & procAddressMask) == 0) { flags |= CU_GET_PROC_ADDRESS_PER_THREAD_DEFAULT_STREAM; } return cuGetProcAddress(symbol, funcPtr, driverVersion, flags); } #define cuGetProcAddress cuGetProcAddress_ptsz #endif #ifdef __cplusplus } #endif #if defined(__GNUC__) #if defined(__CUDA_API_PUSH_VISIBILITY_DEFAULT) #pragma GCC visibility pop #endif #endif #undef __CUDA_DEPRECATED #endif /* __cuda_cuda_h__ */
0
repos
repos/calctax/README.md
# calctax Simple tax calculator for employees in Poland after Nowy Lad changes in 2022. My wife asked me to figure out some tax questions for her, and it was easier to implement a simple calculator in Zig than fighting with a spreadsheet, so there you go... ## Example ``` zig build run -- 7800 info: 1: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 2: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 3: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 4: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 5: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 6: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 7: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 8: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 9: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 10: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 11: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 info: 12: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 0.0000, tax_base = 6480.6201, tax_due = 676.7054, net = 5448.1587 ``` It is also possible to include the monthly tax relief in your calculations by setting `-r` flag: ``` zig build run -- 7800 -r info: 1: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 2: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 3: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 4: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 5: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 6: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 7: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 8: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 9: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 10: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 11: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 info: 12: gross = 7800.0000, zus = 1069.3800, health = 605.7559, tax_relief = 826.7057, tax_base = 5653.9146, tax_due = 536.1655, net = 5588.6987 ```
0
repos
repos/calctax/build.zig
const std = @import("std"); pub fn build(b: *std.build.Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const exe = b.addExecutable("pit", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const exe_tests = b.addTest("src/main.zig"); exe_tests.setTarget(target); exe_tests.setBuildMode(mode); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&exe_tests.step); }
0
repos/calctax
repos/calctax/src/main.zig
const std = @import("std"); const fmt = std.fmt; const io = std.io; const mem = std.mem; const process = std.process; var gpa_allocator = std.heap.GeneralPurposeAllocator(.{}){}; var is_zus_paid_in_full: bool = false; var is_second_clif: bool = false; fn usage() !void { const msg = \\Usage: pit <gross_income> [-r] \\ pit -f <file_path> [-r] \\ pit -h,--help \\ \\General options: \\-f Parse gross income from text file \\-r Apply tax relief \\-h, --help Print this help message and exit ; return io.getStdOut().writeAll(msg); } fn fatal(comptime format: []const u8, args: anytype) noreturn { const msg = fmt.allocPrint(gpa_allocator.allocator(), "fatal: " ++ format ++ "\n", args) catch process.exit(1); defer gpa_allocator.allocator().free(msg); io.getStdErr().writeAll(msg) catch process.exit(1); process.exit(1); } pub fn main() anyerror!void { var arena_allocator = std.heap.ArenaAllocator.init(gpa_allocator.allocator()); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); const args = try process.argsAlloc(arena); if (args.len == 1) { fatal("no arguments specified", .{}); } var input_file: ?[]const u8 = null; var gross_income: f32 = 0; var use_relief: bool = false; var i: usize = 1; while (i < args.len) : (i += 1) { const arg = args[i]; if (mem.eql(u8, arg, "-f")) { if (args.len == i + 1) fatal("expected argument after '-f'", .{}); input_file = args[i + 1]; i += 1; } else if (mem.eql(u8, arg, "-r")) { use_relief = true; } else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { try usage(); return; } else { gross_income = @intToFloat(f32, try fmt.parseInt(u32, args[1], 10)); } } const standard_income_cost: f32 = 250.0; var month: usize = 0; var prev_income_sum: f32 = 0; var prev_tax_sum: f32 = 0; while (month < 12) : ({ month += 1; prev_income_sum += gross_income; }) { const zus_due = calcZus(gross_income, prev_income_sum); const health_ins_due = (gross_income - zus_due) * 0.09; const tax_relief = if (use_relief) calcRelief(gross_income) else 0; const tax_base = gross_income - zus_due - standard_income_cost - tax_relief; const tax_due = calcTax(tax_base, prev_tax_sum); const net_pay = gross_income - zus_due - health_ins_due - tax_due; prev_tax_sum += tax_base; std.log.info("{d}: gross = {d:.4}, zus = {d:.4}, health = {d:.4}, tax_relief = {d:.4}, tax_base = {d:.4}, tax_due = {d:.4}, net = {d:.4}", .{ month + 1, gross_income, zus_due, health_ins_due, tax_relief, tax_base, tax_due, net_pay, }); } } fn calcZus(gross_income: f32, prev_income_sum: f32) f32 { const max_zus: f32 = 177660; const zus_calc_base: f32 = if (prev_income_sum + gross_income > max_zus) blk: { if (is_zus_paid_in_full) break :blk 0; is_zus_paid_in_full = true; break :blk max_zus - prev_income_sum; } else gross_income; return zus_calc_base * (0.0976 + 0.015) + gross_income * 0.0245; } fn calcTax(tax_base: f32, prev_tax_sum: f32) f32 { const clif: f32 = 120000; const tax: f32 = if (tax_base + prev_tax_sum > clif) blk: { if (is_second_clif) break :blk tax_base * 0.32; is_second_clif = true; break :blk (clif - prev_tax_sum) * 0.17 + (tax_base - clif + prev_tax_sum) * 0.32; } else tax_base * 0.17; return if (tax - 425 < 0) 0 else tax - 425; } fn calcRelief(gross_income: f32) f32 { const relief: f32 = blk: { if (gross_income >= 5701 and gross_income < 8549) { break :blk (gross_income * 0.0668 - 380.50) / 0.17; } else if (gross_income >= 8549 and gross_income < 11141) { break :blk (gross_income * (-0.0735) + 819.08) / 0.17; } break :blk 0; }; return relief; }
0
repos
repos/zfltk/build_utils.zig
const std = @import("std"); const Build = std.Build; const CompileStep = Build.Step.Compile; pub const FinalOpts = struct { use_wayland: bool = false, system_jpeg: bool = false, system_png: bool = false, system_zlib: bool = false, build_examples: bool = false, use_fltk_config: bool = false, }; pub inline fn thisDir() []const u8 { return comptime std.fs.path.dirname(@src().file) orelse @panic("error"); } const Example = struct { description: ?[]const u8, output: []const u8, input: []const u8, pub fn init(output: []const u8, input: []const u8, desc: ?[]const u8) Example { return Example{ .description = desc, .output = output, .input = input, }; } }; pub const examples = &[_]Example{ Example.init("simple", "examples/simple.zig", "A simple hello world app"), Example.init("capi", "examples/capi.zig", "Using the C-api directly"), Example.init("customwidget", "examples/customwidget.zig", "Custom widget example"), Example.init("image", "examples/image.zig", "Simple image example"), Example.init("input", "examples/input.zig", "Simple input example"), Example.init("mixed", "examples/mixed.zig", "Mixing both c and zig apis"), Example.init("editor", "examples/editor.zig", "More complex example"), Example.init("layout", "examples/layout.zig", "Layout example"), Example.init("valuators", "examples/valuators.zig", "valuators example"), Example.init("channels", "examples/channels.zig", "Use messages to handle events"), Example.init("editormsgs", "examples/editormsgs.zig", "Use messages in the editor example"), Example.init("browser", "examples/browser.zig", "Browser example"), Example.init("flex", "examples/flex.zig", "Flex example"), Example.init("threadawake", "examples/threadawake.zig", "Thread awake example"), Example.init("handle", "examples/handle.zig", "Handle example"), Example.init("flutterlike", "examples/flutterlike.zig", "Flutter-like example"), Example.init("glwin", "examples/glwin.zig", "OpenGL window example"), Example.init("tile", "examples/tile.zig", "Tile group example"), }; pub fn cfltk_build_from_source(b: *Build, finalize_cfltk: *Build.Step, install_prefix: []const u8, opts: FinalOpts) !void { const target = b.host.result; var buf: [1024]u8 = undefined; const sdk_lib_dir = try std.fmt.bufPrint(buf[0..], "{s}/cfltk/lib", .{install_prefix}); _ = std.fs.cwd().openDir(sdk_lib_dir, .{}) catch |err| { std.debug.print("Warning: {!}. The cfltk library will be rebuilt from source!\n", .{err}); var bin_buf: [250]u8 = undefined; var src_buf: [250]u8 = undefined; var inst_buf: [250]u8 = undefined; const cmake_bin_path = try std.fmt.bufPrint(bin_buf[0..], "{s}/cfltk/bin", .{install_prefix}); const cmake_src_path = try std.fmt.bufPrint(src_buf[0..], "{s}/cfltk", .{install_prefix}); const cmake_inst_path = try std.fmt.bufPrint(inst_buf[0..], "-DCMAKE_INSTALL_PREFIX={s}/cfltk/lib", .{install_prefix}); var zfltk_config: *std.Build.Step.Run = undefined; const which_png = switch (opts.system_png) { false => "-DFLTK_USE_SYSTEM_LIBPNG=OFF", true => "-DFLTK_USE_SYSTEM_LIBPNG=ON", }; const which_jpeg = switch (opts.system_jpeg) { false => "-DFLTK_USE_SYSTEM_LIBJPEG=OFF", true => "-DFLTK_USE_SYSTEM_LIBJPEG=ON", }; const which_zlib = switch (opts.system_zlib) { false => "-DFLTK_USE_SYSTEM_ZLIB=OFF", true => "-DFLTK_USE_SYSTEM_ZLIB=ON", }; if (target.os.tag == .windows) { zfltk_config = b.addSystemCommand(&[_][]const u8{ "cmake", "-B", cmake_bin_path, "-S", cmake_src_path, "-GNinja", "-DCMAKE_BUILD_TYPE=Release", cmake_inst_path, "-DFLTK_BUILD_TEST=OFF", which_png, which_jpeg, which_zlib, "-DFLTK_BUILD_GL=ON", "-DCFLTK_USE_OPENGL=ON", "-DFLTK_BUILD_FLUID=OFF", "-DFLTK_BUILD_FLTK_OPTIONS=OFF", }); } else if (target.isDarwin()) { zfltk_config = b.addSystemCommand(&[_][]const u8{ "cmake", "-B", cmake_bin_path, "-S", cmake_src_path, "-DCMAKE_BUILD_TYPE=Release", cmake_inst_path, "-DFLTK_BUILD_TEST=OFF", which_png, which_jpeg, which_zlib, "-DFLTK_BUILD_GL=ON", "-DCFLTK_USE_OPENGL=ON", "-DFLTK_BUILD_FLUID=OFF", "-DFLTK_BUILD_FLTK_OPTIONS=OFF", }); } else { if (opts.use_wayland) { zfltk_config = b.addSystemCommand(&[_][]const u8{ "cmake", "-B", cmake_bin_path, "-S", cmake_src_path, "-DCMAKE_BUILD_TYPE=Release", cmake_inst_path, "-DFLTK_BUILD_TEST=OFF", which_png, which_jpeg, which_zlib, "-DFLTK_BUILD_GL=ON", "-DCFLTK_USE_OPENGL=ON", "-DFLTK_BACKEND_WAYLAND=ON", "-DFLTK_BUILD_FLUID=OFF", "-DFLTK_BUILD_FLTK_OPTIONS=OFF", "-DFLTK_USE_LIBDECOR_GTK=OFF", }); } else { zfltk_config = b.addSystemCommand(&[_][]const u8{ "cmake", "-B", cmake_bin_path, "-S", cmake_src_path, "-DCMAKE_BUILD_TYPE=Release", cmake_inst_path, "-DFLTK_BUILD_TEST=OFF", which_png, which_jpeg, which_zlib, "-DFLTK_USE_PANGO=ON", // enable if rtl/cjk font support is needed "-DFLTK_BUILD_GL=ON", "-DCFLTK_USE_OPENGL=ON", "-DFLTK_BACKEND_WAYLAND=OFF", "-DFLTK_GRAPHICS_CAIRO=ON", "-DFLTK_BUILD_FLUID=OFF", "-DFLTK_BUILD_FLTK_OPTIONS=OFF", }); } } zfltk_config.setCwd(b.path("zig-out/cfltk")); _ = std.fs.cwd().openDir(cmake_src_path, .{}) catch |git_err| { std.debug.print("Warning: {!}. The cfltk library will be grabbed!\n", .{git_err}); const cfltk_fetch = b.addSystemCommand(&[_][]const u8{ "git", "clone", "https://github.com/MoAlyousef/cfltk", cmake_src_path, "--depth=1", "--recurse-submodules" }); zfltk_config.step.dependOn(&cfltk_fetch.step); }; const cpu_count = try std.Thread.getCpuCount(); const jobs = try std.fmt.allocPrint(b.allocator, "{d}", .{cpu_count}); defer b.allocator.free(jobs); const zfltk_build = b.addSystemCommand(&[_][]const u8{ "cmake", "--build", cmake_bin_path, "--config", "Release", "--parallel", jobs, }); zfltk_build.setCwd(b.path("zig-out/cfltk")); zfltk_build.step.dependOn(&zfltk_config.step); // This only needs to run once! const zfltk_install = b.addSystemCommand(&[_][]const u8{ "cmake", "--install", cmake_bin_path, }); zfltk_install.setCwd(b.path("zig-out/cfltk")); zfltk_install.step.dependOn(&zfltk_build.step); finalize_cfltk.dependOn(&zfltk_install.step); }; } pub fn cfltk_link(exe: *CompileStep, install_prefix: []const u8, opts: FinalOpts) !void { var buf: [1024]u8 = undefined; const target = exe.root_module.resolved_target.?.result; const inc_dir = try std.fmt.bufPrint(buf[0..], "{s}/cfltk/include", .{install_prefix}); exe.addIncludePath(.{ .cwd_relative = inc_dir }); const lib_dir = try std.fmt.bufPrint(buf[0..], "{s}/cfltk/lib/lib", .{install_prefix}); exe.addLibraryPath(.{ .cwd_relative = lib_dir }); const lib64_dir = try std.fmt.bufPrint(buf[0..], "{s}/cfltk/lib/lib64", .{install_prefix}); exe.addLibraryPath(.{ .cwd_relative = lib64_dir }); exe.linkSystemLibrary("cfltk"); exe.linkSystemLibrary("fltk"); exe.linkSystemLibrary("fltk_images"); if (opts.system_png) { exe.linkSystemLibrary("png"); } else { exe.linkSystemLibrary("fltk_png"); } if (opts.system_jpeg) { exe.linkSystemLibrary("jpeg"); } else { exe.linkSystemLibrary("fltk_jpeg"); } if (opts.system_zlib) { exe.linkSystemLibrary("z"); } else { exe.linkSystemLibrary("fltk_z"); } exe.linkSystemLibrary("fltk_gl"); exe.linkLibC(); exe.linkLibCpp(); if (target.os.tag == .windows) { exe.linkSystemLibrary("ws2_32"); exe.linkSystemLibrary("comctl32"); exe.linkSystemLibrary("gdi32"); exe.linkSystemLibrary("oleaut32"); exe.linkSystemLibrary("ole32"); exe.linkSystemLibrary("uuid"); exe.linkSystemLibrary("shell32"); exe.linkSystemLibrary("advapi32"); exe.linkSystemLibrary("comdlg32"); exe.linkSystemLibrary("winspool"); exe.linkSystemLibrary("user32"); exe.linkSystemLibrary("kernel32"); exe.linkSystemLibrary("odbc32"); exe.linkSystemLibrary("gdiplus"); exe.linkSystemLibrary("opengl32"); exe.linkSystemLibrary("glu32"); } else if (target.isDarwin()) { exe.linkFramework("Carbon"); exe.linkFramework("Cocoa"); exe.linkFramework("ApplicationServices"); exe.linkFramework("OpenGL"); exe.linkFramework("UniformTypeIdentifiers"); } else { if (opts.use_wayland) { exe.linkSystemLibrary("wayland-client"); exe.linkSystemLibrary("wayland-cursor"); exe.linkSystemLibrary("xkbcommon"); exe.linkSystemLibrary("dbus-1"); exe.linkSystemLibrary("EGL"); exe.linkSystemLibrary("wayland-egl"); } exe.linkSystemLibrary("GL"); exe.linkSystemLibrary("GLU"); exe.linkSystemLibrary("pthread"); exe.linkSystemLibrary("X11"); exe.linkSystemLibrary("Xext"); exe.linkSystemLibrary("Xinerama"); exe.linkSystemLibrary("Xcursor"); exe.linkSystemLibrary("Xrender"); exe.linkSystemLibrary("Xfixes"); exe.linkSystemLibrary("Xft"); exe.linkSystemLibrary("fontconfig"); exe.linkSystemLibrary("pango-1.0"); exe.linkSystemLibrary("pangoxft-1.0"); exe.linkSystemLibrary("gobject-2.0"); exe.linkSystemLibrary("cairo"); exe.linkSystemLibrary("pangocairo-1.0"); } } pub fn link_using_fltk_config(b: *Build, exe: *CompileStep, finalize_cfltk: *Build.Step, install_prefix: []const u8) !void { const target = exe.root_module.resolved_target.?.result; exe.linkLibC(); exe.linkLibCpp(); var buf: [1024]u8 = undefined; const inc_dir = try std.fmt.bufPrint(buf[0..], "{s}/cfltk/include", .{install_prefix}); exe.addIncludePath(b.path(inc_dir)); const cmake_src_path = try std.fmt.allocPrint(b.allocator, "{s}/cfltk", .{install_prefix}); _ = std.fs.cwd().openDir(cmake_src_path, .{}) catch |git_err| { std.debug.print("Warning: {!}. The cfltk library will be grabbed!\n", .{git_err}); const cfltk_fetch = b.addSystemCommand(&[_][]const u8{ "git", "clone", "https://github.com/MoAlyousef/cfltk", cmake_src_path, "--depth=1" }); finalize_cfltk.dependOn(&cfltk_fetch.step); }; var lib = b.addStaticLibrary(.{ .name = "cfltk", .target = exe.root_module.resolved_target.?, .optimize = exe.root_module.optimize.?, .use_llvm = false, }); const proc = try std.process.Child.run(.{ .allocator = b.allocator, .argv = &[_][]const u8{ "fltk-config", "--use-images", "--use-gl", "--cflags" }, }); const out = proc.stdout; var cflags = std.ArrayList([]const u8).init(b.allocator); var it = std.mem.tokenize(u8, out, " "); while (it.next()) |x| { try cflags.append(x); } cflags.clearAndFree(); // why does the above not work?! try cflags.append("-I/usr/local/include"); try cflags.append(try std.fmt.allocPrint(b.allocator, "-I{s}", .{inc_dir})); try cflags.append("-DCFLTK_USE_GL"); lib.addCSourceFiles(.{.files = &[_][]const u8{ try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_new.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_lock.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_window.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_button.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_widget.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_group.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_text.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_box.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_input.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_menu.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_dialog.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_valuator.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_browser.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_misc.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_image.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_draw.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_table.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_tree.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_surface.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_font.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_utils.cpp", .{install_prefix}), try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_printer.cpp", .{install_prefix}), }, .flags = cflags.items}); if (target.isDarwin()) { lib.addCSourceFile(.{ .file = b.path(try std.fmt.allocPrint(b.allocator, "{s}/cfltk/src/cfl_nswindow.m", .{install_prefix})), .flags = cflags.items }); } const proc2 = try std.process.Child.run(.{ .allocator = b.allocator, .argv = &[_][]const u8{ "fltk-config", "--use-images", "--use-gl", "--ldflags" }, }); const out2 = proc2.stdout; var lflags = std.ArrayList([]const u8).init(b.allocator); var Lflags = std.ArrayList([]const u8).init(b.allocator); var it2 = std.mem.tokenize(u8, out2, " "); while (it2.next()) |x| { if (std.mem.startsWith(u8, x, "-l") and !std.mem.startsWith(u8, x, "-ldl")) try lflags.append(x[2..]); if (std.mem.startsWith(u8, x, "-L")) try Lflags.append(x[2..]); } for (Lflags.items) |f| { lib.addLibraryPath(b.path(f)); } for (lflags.items) |f| { lib.linkSystemLibrary(f); } lib.linkLibC(); lib.linkLibCpp(); lib.step.dependOn(finalize_cfltk); exe.step.dependOn(&lib.step); exe.linkLibrary(lib); }
0
repos
repos/zfltk/README.md
# zfltk A Zig wrapper for the FLTK gui library. ## Building the package from source ``` git clone https://github.com/MoAlyousef/zfltk cd zfltk zig build ``` To build the examples, pass `-Dzfltk-build-examples=true` to your `zig build` command. ## Usage zfltk supports the zig package manager. You can add it as a dependency to your project in your build.zig.zon: ```zig .{ .name = "app", .version = "0.0.1", .paths = .{ "src", "build.zig", "build.zig.zon", }, .dependencies = .{ .zfltk = .{ .url = "https://github.com/MoAlyousef/zfltk/archive/refs/tags/pkg0.6.0.tar.gz", }, } } ``` (This is missing the hash, zig build will give you the correct hash, which you should add after the url) In your build.zig: ```zig const std = @import("std"); const Sdk = @import("zfltk"); const Build = std.Build; pub fn build(b: *Build) !void { const target = b.standardTargetOptions(.{}); const mode = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "app", .root_source_file = b.path("src/main.zig"), .optimize = mode, .target = target, }); const sdk = try Sdk.init(b); const zfltk_module = sdk.getZfltkModule(b); exe.root_module.addImport("zfltk", zfltk_module); try sdk.link(exe); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); } ``` Then you can run: ``` zig build run ``` ## Dependencies This repo tracks cfltk, the C bindings to FLTK. It (along with FLTK) is statically linked to your application. This requires CMake (and Ninja on Windows) as a build system, and is only required once. - Windows: No dependencies. - MacOS: No dependencies. - Linux: X11 and OpenGL development headers need to be installed for development. The libraries themselves are available on linux distros with a graphical user interface. For Debian-based GUI distributions, that means running: ``` sudo apt-get install libx11-dev libxext-dev libxft-dev libxinerama-dev libxcursor-dev libxrender-dev libxfixes-dev libpango1.0-dev libpng-dev libgl1-mesa-dev libglu1-mesa-dev ``` For RHEL-based GUI distributions, that means running: ``` sudo yum groupinstall "X Software Development" && yum install pango-devel libXinerama-devel libpng-devel libstdc++-static ``` For Arch-based GUI distributions, that means running: ``` sudo pacman -S libx11 libxext libxft libxinerama libxcursor libxrender libxfixes libpng pango cairo libgl mesa --needed ``` For Alpine linux: ``` apk add pango-dev fontconfig-dev libxinerama-dev libxfixes-dev libxcursor-dev libpng-dev mesa-gl ``` For nixos: ``` nix-shell --packages rustc cmake git gcc xorg.libXext xorg.libXft xorg.libXinerama xorg.libXcursor xorg.libXrender xorg.libXfixes libcerf pango cairo libGL mesa pkg-config ``` ## API Using the Zig wrapper (under development): ```zig const zfltk = @import("zfltk"); const app = zfltk.app; const Window = zfltk.window.Window; const Button = zfltk.button.Button; const Box = zfltk.box.Box; const Color = zfltk.enums.Color; fn butCb(but: *Button, data: ?*anyopaque) void { var box = Box.fromRaw(data.?); box.setLabel("Hello World!"); but.setColor(Color.fromName(.cyan)); } pub fn main() !void { try app.init(); app.setScheme(.gtk); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Hello", }); win.freePosition(); var but = try Button.init(.{ .x = 160, .y = 220, .w = 80, .h = 40, .label = "Click me!", }); but.setDownBox(.flat); var box = try Box.init(.{ .x = 10, .y = 10, .w = 380, .h = 180, .boxtype = .up, }); box.setLabelFont(.courier); box.setLabelSize(18); win.end(); win.show(); but.setCallbackEx(butCb, box); try app.run(); } ``` The messaging api can also be used: ```zig const zfltk = @import("zfltk"); const app = zfltk.app; const Window = zfltk.window.Window; const Button = zfltk.button.Button; const Box = zfltk.box.Box; const enums = zfltk.enums; pub const Message = enum(usize) { // Can't begin with Zero! first = 1, second, }; pub fn main() !void { try app.init(); app.setScheme(.gtk); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Hello", }); var but1 = try Button.init(.{ .x = 100, .y = 220, .w = 80, .h = 40, .label = "Button 1", }); var but2 = try Button.init(.{ .x = 200, .y = 220, .w = 80, .h = 40, .label = "Button 2", }); var mybox = try Box.init(.{ .x = 10, .y = 10, .w = 380, .h = 180, .boxtype = .up, }); mybox.setLabelFont(.courier); mybox.setLabelSize(18); win.end(); win.show(); but1.emit(Message, .first); but2.emit(Message, .second); while (app.wait()) { if (app.recv(Message)) |msg| switch (msg) { .first => mybox.setLabel("Button 1 Clicked!"), .second => mybox.setLabel("Button 2 Clicked!"), }; } } ``` Using the C Api directly: ```zig const c = @cImport({ @cInclude("cfl.h"); // Fl_init_all, Fl_run @cInclude("cfl_enums.h"); // Fl_Color_* @cInclude("cfl_image.h"); // Fl_register_images @cInclude("cfl_button.h"); // Fl_Button @cInclude("cfl_box.h"); // Fl_Box @cInclude("cfl_window.h"); // Fl_Window }); // fltk initizialization of optional functionalities pub fn fltkInit() void { c.Fl_init_all(); // inits all styles, if needed c.Fl_register_images(); // register image types supported by fltk, if needed _ = c.Fl_lock(); // enable multithreading, if needed } // Button callback pub fn butCb(w: ?*c.Fl_Widget, data: ?*anyopaque) callconv(.C) void { c.Fl_Box_set_label(@ptrCast(data), "Hello World!"); c.Fl_Button_set_color(@ptrCast(w), c.Fl_Color_Cyan); } pub fn main() !void { fltkInit(); _ = c.Fl_set_scheme("gtk+"); const win = c.Fl_Window_new(100, 100, 400, 300, "Hello"); const but = c.Fl_Button_new(160, 220, 80, 40, "Click me!"); const box = c.Fl_Box_new(10, 10, 380, 180, ""); c.Fl_Box_set_box(box, c.Fl_BoxType_UpBox); c.Fl_Box_set_label_size(box, 18); c.Fl_Box_set_label_font(box, c.Fl_Font_Courier); c.Fl_Window_end(win); c.Fl_Window_show(win); c.Fl_Button_set_callback(but, butCb, box); _ = c.Fl_run(); } ``` You can also mix and match for any missing functionalities in the Zig wrapper (see examples/mixed.zig). Widgets also provide a `call` method which allows to call any method that wasn't wrapped yet in the bindings: ```zig var flex = try Flex.init(.{ .w = 400, .h = 300, .orientation = .vertical, }); flex.call("set_margins", .{10, 20, 10, 20}); ``` ![alt_test](screenshots/image.jpg) ![alt_test](screenshots/editor.jpg) [video tutorial](https://youtu.be/D2ijlrDStdM)
0
repos
repos/zfltk/build.zig.zon
.{ .name = "zfltk", .version = "0.0.3", // zig 0.13.0 .paths = .{ "src", "build.zig", "build_utils.zig", "build.zig.zon", "LICENSE", "README.md", } }
0
repos
repos/zfltk/build.zig
const std = @import("std"); const Build = std.Build; const CompileStep = Build.Step.Compile; const utils = @import("build_utils.zig"); pub const SdkOpts = struct { use_wayland: bool = false, system_jpeg: bool = false, system_png: bool = false, system_zlib: bool = false, use_fltk_config: bool = false, build_examples: bool = false, fn finalOpts(self: SdkOpts) utils.FinalOpts { return utils.FinalOpts{ .use_wayland = self.use_wayland, .system_jpeg = self.system_jpeg, .system_png = self.system_png, .system_zlib = self.system_zlib, .build_examples = self.build_examples, .use_fltk_config = self.use_fltk_config, }; } }; const Sdk = @This(); builder: *Build, install_prefix: []const u8, finalize_cfltk: *std.Build.Step, opts: SdkOpts, pub fn init(b: *Build) !*Sdk { return initWithOpts(b, .{}); } pub fn initWithOpts(b: *Build, opts: SdkOpts) !*Sdk { var final_opts = opts; final_opts.use_wayland = b.option(bool, "zfltk-use-wayland", "build zfltk for wayland") orelse opts.use_wayland; final_opts.system_jpeg = b.option(bool, "zfltk-system-libjpeg", "link system libjpeg") orelse opts.system_jpeg; final_opts.system_png = b.option(bool, "zfltk-system-libpng", "link system libpng") orelse opts.system_png; final_opts.system_zlib = b.option(bool, "zfltk-system-zlib", "link system zlib") orelse opts.system_zlib; final_opts.build_examples = b.option(bool, "zfltk-build-examples", "Build zfltk examples") orelse opts.build_examples; final_opts.use_fltk_config = b.option(bool, "zfltk-use-fltk-config", "use fltk-config instead of building fltk from source") orelse opts.use_fltk_config; const install_prefix = b.install_prefix; const finalize_cfltk = b.step("finalize cfltk install", "Installs cfltk"); try utils.cfltk_build_from_source(b, finalize_cfltk, install_prefix, final_opts.finalOpts()); b.default_step.dependOn(finalize_cfltk); const sdk = b.allocator.create(Sdk) catch @panic("out of memory"); sdk.* = .{ .builder = b, .install_prefix = install_prefix, .finalize_cfltk = finalize_cfltk, .opts = final_opts, }; return sdk; } pub fn getZfltkModule(sdk: *Sdk, b: *Build) *Build.Module { _ = sdk; const prefix = comptime std.fs.path.dirname(@src().file) orelse unreachable; var mod = b.addModule("zfltk", .{ .root_source_file = .{ .cwd_relative = prefix ++ "/src/zfltk.zig" }, }); mod.addIncludePath(b.path("zig-out/cfltk/include")); return mod; } pub fn link(sdk: *Sdk, exe: *CompileStep) !void { exe.step.dependOn(sdk.finalize_cfltk); const install_prefix = sdk.install_prefix; if (sdk.opts.use_fltk_config) { try utils.link_using_fltk_config(sdk.builder, exe, sdk.finalize_cfltk, sdk.install_prefix); } else { try utils.cfltk_link(exe, install_prefix, sdk.opts.finalOpts()); } } pub fn build(b: *Build) !void { const target = b.standardTargetOptions(.{}); const mode = b.standardOptimizeOption(.{}); const sdk = try Sdk.init(b); const zfltk_module = sdk.getZfltkModule(b); if (sdk.opts.build_examples) { const examples_step = b.step("examples", "build the examples"); b.default_step.dependOn(examples_step); for (utils.examples) |example| { const exe = b.addExecutable(.{ .name = example.output, .root_source_file = b.path(example.input), .optimize = mode, .target = target, }); exe.root_module.addImport("zfltk", zfltk_module); try sdk.link(exe); examples_step.dependOn(&exe.step); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); const run_step = b.step(b.fmt("run-{s}", .{example.output}), example.description.?); run_step.dependOn(&run_cmd.step); } } }
0
repos/zfltk
repos/zfltk/src/button.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const widget = @import("widget.zig"); const Widget = widget.Widget; const enums = @import("enums.zig"); const Event = enums.Event; const std = @import("std"); const c = zfltk.c; pub const Button = ButtonType(.normal); pub const RadioButton = ButtonType(.radio); pub const CheckButton = ButtonType(.check); pub const RoundButton = ButtonType(.round); pub const RepeatButton = ButtonType(.repeat); pub const LightButton = ButtonType(.light); pub const EnterButton = ButtonType(.enter); const ButtonKind = enum { normal, radio, check, round, repeat, light, enter, }; fn ButtonType(comptime kind: ButtonKind) type { return struct { const Self = @This(); pub usingnamespace zfltk.widget.methods(Self, RawPtr); pub usingnamespace methods(Self); const RawPtr = switch (kind) { .normal => *c.Fl_Button, .radio => *c.Fl_Radio_Button, .check => *c.Fl_Check_Button, .round => *c.Fl_Round_Button, .repeat => *c.Fl_Repeat_Button, .light => *c.Fl_Light_Button, .enter => *c.Fl_Return_Button, }; pub inline fn init(opts: Widget.Options) !*Self { const init_func = switch (kind) { .normal => c.Fl_Button_new, .radio => c.Fl_Radio_Button_new, .check => c.Fl_Check_Button_new, .round => c.Fl_Round_Button_new, .repeat => c.Fl_Repeat_Button_new, .light => c.Fl_Light_Button_new, .enter => c.Fl_Return_Button_new, }; const label = if (opts.label != null) opts.label.?.ptr else null; if (init_func(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { return Self.fromRaw(ptr); } unreachable; } pub inline fn deinit(self: *Self) void { const deinit_func = switch (kind) { .normal => c.Fl_Button_delete, .radio => c.Fl_Radio_Button_delete, .check => c.Fl_Check_Button_delete, .round => c.Fl_Round_Button_delete, .repeat => c.Fl_Repeat_Button_delete, .light => c.Fl_Light_Button_delete, .enter => c.Fl_Return_Button_delete, }; deinit_func(self.raw()); app.allocator.destroy(self); } }; } fn methods(comptime Self: type) type { return struct { pub inline fn button(self: *Self) *ButtonType(.normal) { return @ptrCast(self); } pub fn shortcut(self: *Self) i32 { return c.Fl_Button_shortcut(self.button().raw()); } pub fn setShortcut(self: *Self, shrtct: i32) void { c.Fl_Button_set_shortcut(self.button().raw(), shrtct); } pub fn clear(self: *Self) void { c.Fl_Button_clear(self.button().raw()); } pub fn value(self: *Self) bool { return c.Fl_Button_value(self.button().raw()) != 0; } pub fn setValue(self: *Self, flag: bool) void { c.Fl_Button_set_value(self.button().raw(), @intFromBool(flag)); } pub fn setDownBox(self: *Self, f: enums.BoxType) void { c.Fl_Button_set_down_box(self.button().raw(), @intFromEnum(f)); } pub fn downBox(self: *Self) enums.BoxType { return @enumFromInt(c.Fl_Button_down_box(self.button().raw())); } }; } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/browser.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const Widget = @import("widget.zig").Widget; const Valuator = @import("valuator.zig").Valuator; const enums = @import("enums.zig"); const c = zfltk.c; const std = @import("std"); pub const Browser = BrowserType(.normal); pub const SelectBrowser = BrowserType(.select); pub const HoldBrowser = BrowserType(.hold); pub const MultiBrowser = BrowserType(.multi); pub const FileBrowser = BrowserType(.file); const BrowserKind = enum { normal, select, hold, multi, file, }; fn BrowserType(comptime kind: BrowserKind) type { return struct { const Self = @This(); const BrowserRawPtr = *c.Fl_Browser; pub const RawPtr = switch (kind) { .normal => *c.Fl_Browser, .select => *c.Fl_Select_Browser, .hold => *c.Fl_Hold_Browser, .multi => *c.Fl_Multi_Browser, .file => *c.Fl_File_Browser, }; pub usingnamespace zfltk.widget.methods(Self, RawPtr); pub inline fn init(opts: Widget.Options) !*Self { const init_func = switch (kind) { .normal => c.Fl_Browser_new, .select => c.Fl_Select_Browser_new, .hold => c.Fl_Hold_Browser_new, .multi => c.Fl_Multi_Browser_new, .file => c.Fl_File_Browser_new, }; const label = if (opts.label != null) opts.label.?.ptr else null; if (init_func(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { return Self.fromRaw(ptr); } unreachable; } pub inline fn deinit(self: *Self) void { const deinit_func = switch (kind) { .normal => c.Fl_Browser_delete, .select => c.Fl_Select_Browser_delete, .hold => c.Fl_Hold_Browser_delete, .multi => c.Fl_Multi_Browser_delete, .file => c.Fl_File_Browser_delete, }; deinit_func(self.raw()); } pub fn remove(self: *Self, line: u32) void { return c.Fl_Browser_remove(@ptrCast(self.raw()), line); } pub fn add(self: *Self, item: [:0]const u8) void { return c.Fl_Browser_add(@ptrCast(self.raw()), item.ptr); } pub fn insert(self: *Self, line: u32, item: [:0]const u8) void { return c.Fl_Browser_insert(@ptrCast(self.raw()), line, item.ptr); } pub fn moveItem(self: *Self, to: u32, from: u32) void { return c.Fl_Browser_move_item(@ptrCast(self.raw()), to, from); } pub fn swap(self: *Self, a: u32, b: u32) void { return c.Fl_Browser_swap(@ptrCast(self.raw()), a, b); } pub fn clear(self: *Self) void { return c.Fl_Browser_clear(@ptrCast(self.raw())); } pub fn size(self: *Self) u32 { return c.Fl_Browser_size(@ptrCast(self.raw())); } pub fn setSize(self: *Self, w: i32, h: i32) void { return c.Fl_Browser_set_size(@ptrCast(self.raw()), w, h); } pub fn select(self: *Self, line: u32) void { if (line <= self.size()) return c.Fl_Browser_select(@ptrCast(self.raw()), line); } pub fn selected(self: *Self, line: u32) bool { return c.Fl_Browser_selected(@ptrCast(self.raw()), line) != 0; } pub fn text(self: *Self, line: u32) [:0]const u8 { return c.Fl_Browser_text(@ptrCast(self.raw()), line); } pub fn setText(self: *Self, line: u32, txt: [*c]const u8) void { return c.Fl_Browser_set_text(@ptrCast(self.raw()), line, txt); } pub fn load(self: *Self, path: [*c]const u8) void { return c.Fl_Browser_load_file(@ptrCast(self.raw()), path); } pub fn textSize(self: *Self) u32 { return c.Fl_Browser_text_size(@ptrCast(self.raw())); } pub fn setTextSize(self: *Self, val: u32) void { return c.Fl_Browser_set_text_size(@ptrCast(self.raw()), val); } pub fn topline(self: *Self, line: u32) void { return c.Fl_Browser_topline(@ptrCast(self.raw()), line); } pub fn bottomline(self: *Self, line: u32) void { return c.Fl_Browser_bottomline(@ptrCast(self.raw()), line); } pub fn middleline(self: *Self, line: u32) void { return c.Fl_Browser_middleline(@ptrCast(self.raw()), line); } pub fn formatChar(self: *Self) u8 { return c.Fl_Browser_format_char(@ptrCast(self.raw())); } pub fn setFormatChar(self: *Self, char: u8) void { return c.Fl_Browser_set_format_char(@ptrCast(self.raw()), char); } pub fn columnChar(self: *Self) u8 { return c.Fl_Browser_column_char(@ptrCast(self.raw())); } pub fn setColumnChar(self: *Self, char: u8) void { return c.Fl_Browser_set_column_char(@ptrCast(self.raw()), char); } pub fn setColumnWidths(self: *Self, arr: [:0]const i32) void { return c.Fl_Browser_set_column_widths(@ptrCast(self.raw()), arr.ptr); } pub fn displayed(self: *Self, line: u31) bool { return c.Fl_Browser_displayed(@ptrCast(self.raw()), line) != 0; } pub fn makeVisible(self: *Self, line: u31) void { return c.Fl_Browser_make_visible(@ptrCast(self.raw()), line); } pub fn position(self: *Self) u31 { return c.Fl_Browser_position(@ptrCast(self.raw())); } pub fn setPosition(self: *Self, pos: u31) void { return c.Fl_Browser_set_position(@ptrCast(self.raw()), pos); } pub fn hposition(self: *Self) u31 { return c.Fl_Browser_hposition(@ptrCast(self.raw())); } pub fn setHposition(self: *Self, pos: u31) void { return c.Fl_Browser_set_hposition(@ptrCast(self.raw()), pos); } pub fn hasScrollbar(self: *Self) enums.BrowserScrollbar { return c.Fl_Browser_has_scrollbar(@ptrCast(self.raw())); } pub fn setHasScrollbar(self: *Self, mode: enums.BrowserScrollbar) void { return c.Fl_Browser_set_has_scrollbar(@ptrCast(self.raw()), mode); } pub fn scrollbarSize(self: *Self) u31 { return c.Fl_Browser_scrollbar_size(@ptrCast(self.raw())); } pub fn setScrollbarSize(self: *Self, new_size: u31) void { return c.Fl_Browser_set_scrollbar_size(@ptrCast(self.raw()), new_size); } pub fn sort(self: *Self) void { return c.Fl_Browser_sort(@ptrCast(self.raw())); } pub fn scrollbar(self: *Self) Valuator { return .{ .inner = c.Fl_Browser_scrollbar(@ptrCast(self.raw())) }; } pub fn hscrollbar(self: *Self) .Valuator { return .{ .inner = c.Fl_Browser_hscrollbar(@ptrCast(self.raw())) }; } }; } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/widget.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const std = @import("std"); const enums = zfltk.enums; const Group = zfltk.group.Group; const Image = zfltk.image.Image; const c = zfltk.c; pub const Widget = struct { pub usingnamespace methods(Widget, *c.Fl_Widget); pub fn OptionsImpl(comptime ctx: type) type { _ = ctx; return struct { x: i32 = 0, y: i32 = 0, w: u31 = 0, h: u31 = 0, label: ?[:0]const u8 = null, }; } pub const Options = OptionsImpl(Widget); pub inline fn init(opts: Options) !*Widget { const _label = if (opts.label != null) opts.label.?.ptr else null; if (c.Fl_Widget_new(opts.x, opts.y, opts.w, opts.h, _label)) |ptr| { return Widget.fromRaw(ptr); } unreachable; } pub inline fn deinit(self: *Widget) void { c.Fl_Widget_delete(self.raw()); } }; /// Methods to be used in everything derived from `Widget` pub fn methods(comptime Self: type, comptime RawPtr: type) type { return struct { const type_name = @typeName(RawPtr); const ptr_name = type_name[(std.mem.indexOf(u8, type_name, "struct_Fl_") orelse 0) + 7 .. type_name.len]; pub inline fn widget(self: *Self) *Widget { return @ptrCast(self); } pub inline fn fromWidget(wid: *Widget) *Self { return @ptrCast(wid); } pub inline fn raw(self: *Self) RawPtr { return @ptrCast(@alignCast(self)); } pub inline fn fromRaw(ptr: *anyopaque) *Self { return @ptrCast(ptr); } pub inline fn fromDynWidget(other: anytype) ?*Self { if (@field(c, ptr_name ++ "_from_dyn_ptr")(@ptrCast(@alignCast(other)))) |o| { return Self.fromRaw(o); } return null; } /// Sets a function to be called upon `activation` of a widget such as /// pushing a button pub inline fn setCallback(self: *Self, f: *const fn (*Self) void) void { c.Fl_Widget_set_callback( self.widget().raw(), &zfltk_cb_handler, @ptrFromInt(@intFromPtr(f)), ); } /// Like `setCallback` but allows passing data pub fn setCallbackEx(self: *Self, f: *const fn (*Self, data: ?*anyopaque) void, data: ?*anyopaque) void { if (data) |d| { // TODO: Make this an ArrayList or something more efficient var container = app.allocator.alloc(usize, 2) catch unreachable; container[0] = @intFromPtr(f); container[1] = @intFromPtr(d); c.Fl_Widget_set_callback( self.widget().raw(), zfltk_cb_handler_ex, @ptrCast(container.ptr), ); } else { c.Fl_Widget_set_callback( self.widget().raw(), zfltk_cb_handler, @ptrFromInt(@intFromPtr(f)), ); } } pub inline fn emit(self: *Self, comptime T: type, msg: T) void { c.Fl_Widget_set_callback(self.widget().raw(), shim, @ptrFromInt(@intFromEnum(msg))); } pub inline fn show(self: *Self) void { @field(c, ptr_name ++ "_show")(self.raw()); } pub inline fn hide(self: *Self) void { @field(c, ptr_name ++ "_hide")(self.raw()); } pub inline fn resize(self: *Self, _x: i32, _y: i32, _w: u31, _h: u31) void { @field(c, ptr_name ++ "_resize")(self.raw(), _x, _y, _w, _h); } pub inline fn redraw(self: *Self) void { c.Fl_Widget_redraw(self.widget().raw()); } pub inline fn x(self: *Self) i32 { return @intCast(c.Fl_Widget_x(self.widget().raw())); } pub inline fn y(self: *Self) i32 { return @intCast(c.Fl_Widget_y(self.widget().raw())); } pub inline fn w(self: *Self) u31 { return @intCast(c.Fl_Widget_width(self.widget().raw())); } pub inline fn h(self: *Self) u31 { return @intCast(c.Fl_Widget_height(self.widget().raw())); } pub inline fn label(self: *Self) [:0]const u8 { return std.mem.span(c.Fl_Widget_label(self.widget().raw())); } pub inline fn setLabel(self: *Self, _label: [:0]const u8) void { @field(c, ptr_name ++ "_set_label")(self.raw(), _label.ptr); } pub inline fn kind(self: *Self, comptime T: type) T { return @enumFromInt(c.Fl_Widget_set_type(self.widget().raw())); } pub inline fn setKind(self: *Self, comptime T: type, t: T) void { c.Fl_Widget_set_type(self.widget().raw(), @intFromEnum(t)); } pub inline fn color(self: *Self) enums.Color { return enums.Color.fromRgbi(c.Fl_Widget_color(self.widget().raw())); } pub inline fn setColor(self: *Self, col: enums.Color) void { c.Fl_Widget_set_color(self.widget().raw(), col.toRgbi()); } pub inline fn labelColor(self: *Self) enums.Color { return enums.Color.fromRgbi(c.Fl_Widget_label_color(self.widget().raw())); } pub inline fn setLabelColor(self: *Self, col: enums.Color) void { c.Fl_Widget_set_label_color(self.widget().raw(), col.toRgbi()); } pub inline fn labelFont(self: *Self) enums.Font { return @enumFromInt(c.Fl_Widget_label_font(self.widget().raw())); } pub inline fn setLabelFont(self: *Self, font: enums.Font) void { c.Fl_Widget_set_label_font(self.widget().raw(), @intFromEnum(font)); } pub inline fn labelSize(self: *Self) u31 { return @intCast(c.Fl_Widget_label_size(self.widget().raw())); } pub inline fn setLabelSize(self: *Self, size: u31) void { c.Fl_Widget_set_label_size(self.widget().raw(), size); } // TODO: make alignment and trigger enums pub inline fn labelAlign(self: *Self) i32 { return @intCast(c.Fl_Widget_align(self.widget().raw())); } pub inline fn setLabelAlign(self: *Self, alignment: i32) void { c.Fl_Widget_set_align(self.widget().raw(), @intCast(alignment)); } pub inline fn trigger(self: *Self) i32 { return c.Fl_Widget_trigger(self.widget().raw()); } pub inline fn setTrigger(self: *Self, cb_trigger: i32) void { c.Fl_Widget_set_trigger(self.widget().raw(), @intCast(cb_trigger)); } pub inline fn box(self: *Self) enums.BoxType { return @enumFromInt(c.Fl_Widget_box(self.widget().raw())); } pub inline fn setBox(self: *Self, boxtype: enums.BoxType) void { c.Fl_Widget_set_box(self.widget().raw(), @intFromEnum(boxtype)); } pub inline fn setImage(self: *Self, img: Image) void { c.Fl_Widget_set_image(self.widget().raw(), img.inner); } pub inline fn removeImage(self: *Self) void { c.Fl_Widget_set_image(self.widget().raw(), null); } pub inline fn setDeimage(self: *Self, img: Image) void { c.Fl_Widget_set_deimage(self.widget().raw(), img.inner); } pub inline fn removeDeimage(self: *Self) void { c.Fl_Widget_set_deimage(self.widget().raw(), null); } // TODO: fix, this causes pointer issues pub inline fn parent(self: *Self) ?*Group { const ptr = c.Fl_Widget_parent(self.widget().raw()); if (ptr) |p| { return Group.fromRaw(p); } else { return null; } } pub inline fn selectionColor(self: *Self) enums.Color { return enums.Color.fromRgbi(c.Fl_Widget_selection_color(self.widget().raw())); } pub inline fn setSelectionColor(self: *Self, col: enums.Color) void { c.Fl_Widget_set_selection_color(self.widget().raw(), @intCast(col.toRgbi())); } pub inline fn doCallback(self: *Self) void { c.Fl_Widget_do_callback(self.widget().raw()); } pub inline fn clearVisibleFocus(self: *Self) void { c.Fl_Widget_clear_visible_focus(self.widget().raw()); } pub inline fn setVisibleFocus(self: *Self, v: bool) void { c.Fl_Widget_visible_focus(self.widget().raw(), @intFromBool(v)); } pub inline fn setLabelKind(self: *Self, typ: enums.LabelType) void { c.Fl_Widget_set_label_type(self.widget().raw(), @intFromEnum(typ)); } pub inline fn tooltip(self: *Self) [:0]const u8 { return std.mem.span(c.Fl_Widget_tooltip(self.widget().raw())); } pub inline fn setTooltip(self: *Self, _label: [:0]const u8) void { c.Fl_Widget_set_tooltip(self.widget().raw(), _label.ptr); } pub inline fn takeFocus(self: *Self) void { c.Fl_set_focus(self.widget().raw()); } pub inline fn setEventHandler(self: *Self, f: *const fn (*Self, enums.Event) bool) void { @field(c, ptr_name ++ "_handle")( self.raw(), zfltk_event_handler, @ptrFromInt(@intFromPtr(f)), ); } pub inline fn setEventHandlerEx(self: *Self, f: *const fn (*Self, enums.Event, ?*anyopaque) bool, data: ?*anyopaque) void { if (data) |d| { var container = app.allocator.alloc(usize, 2) catch unreachable; container[0] = @intFromPtr(f); container[1] = @intFromPtr(d); @field(c, ptr_name ++ "_handle")( self.raw(), zfltk_event_handler_ex, @ptrCast(container.ptr), ); } else { @field(c, ptr_name ++ "_handle")( self.raw(), zfltk_event_handler, @ptrFromInt(@intFromPtr(f)), ); } } pub inline fn setDrawHandler(self: *Self, f: *const fn (*Self) void) void { @field(c, ptr_name ++ "_draw")( self.raw(), zfltk_draw_handler, @ptrFromInt(@intFromPtr(f)), ); } pub inline fn setDrawHandlerEx(self: *Self, f: *const fn (*Self, ?*anyopaque) void, data: ?*anyopaque) void { if (data) |d| { var allocator = std.heap.c_allocator; var container = allocator.alloc(usize, 2) catch unreachable; container[0] = @intFromPtr(f); container[1] = @intFromPtr(d); @field(c, ptr_name ++ "_draw")( self.raw(), zfltk_draw_handler_ex, @ptrCast(container.ptr), ); } else { @field(c, ptr_name ++ "_draw")( self.raw(), zfltk_draw_handler, @ptrFromInt(@intFromPtr(f)), ); } } pub inline fn call(self: *Self, comptime method: []const u8, args: anytype) @TypeOf(@call(.auto, @field(c, ptr_name ++ "_" ++ method), .{self.raw()} ++ args)) { return @call(.auto, @field(c, ptr_name ++ "_" ++ method), .{self.raw()} ++ args); } pub fn asWindow(self: *Self) ?*zfltk.window.Window { const ptr = @field(c, ptr_name ++ "_as_window")(self.raw()); if (ptr) |p| { return zfltk.window.Window.fromRaw(p); } else { return null; } } pub fn centerOf(self: *Self, wid: anytype) void { if (!comptime zfltk.isWidget(@TypeOf(wid))) { return; } std.debug.assert(wid.w() != 0 and wid.h() != 0); const sw: f64 = @floatFromInt(self.w()); const sh: f64 = @floatFromInt(self.h()); const ww: f64 = @floatFromInt(wid.w()); const wh: f64 = @floatFromInt(wid.h()); const sx = (ww - sw) / 2.0; const sy = (wh - sh) / 2.0; var wx: i32 = 0; var wy: i32 = 0; if (wid.asWindow()) |win| { _ = win; wx = 0; wy = 0; } else { wx = wid.x(); wy = wid.y(); } self.resize(@as(i32, @intFromFloat(sx)) + wx, @as(i32, @intFromFloat(sy)) + wy, @as(u31, @intFromFloat(sw)), @as(u31, @intFromFloat(sh))); self.redraw(); } pub fn centerOfParent(self: *Self) void { const par = self.parent(); if (par) |p| { self.centerOf(p); } } pub fn centerY(self: *Self, wid: anytype) void { if (!comptime zfltk.isWidget(@TypeOf(wid))) { return; } std.debug.assert(wid.w() != 0 and wid.h() != 0); const sw: f64 = @floatFromInt(self.w()); const sh: f64 = @floatFromInt(self.h()); const wh: f64 = @floatFromInt(wid.h()); const sx = self.x(); const sy = (wh - sh) / 2.0; var wx: i32 = 0; var wy: i32 = 0; if (wid.asWindow()) |win| { _ = win; wx = 0; wy = 0; } else { wx = wid.x(); wy = wid.y(); } self.resize(@as(i32, @intFromFloat(sx)) + wx, sy, @as(u31, @intFromFloat(sw)), @as(u31, @intFromFloat(sh))); self.redraw(); } pub fn centerX(self: *Self, wid: anytype) void { if (!comptime zfltk.isWidget(@TypeOf(wid))) { return; } std.debug.assert(wid.w() != 0 and wid.h() != 0); const sw: f64 = @floatFromInt(self.w()); const sh: f64 = @floatFromInt(self.h()); const ww: f64 = @floatFromInt(wid.w()); const sx = (ww - sw) / 2.0; const sy = self.y(); var wx: i32 = 0; var wy: i32 = 0; if (wid.asWindow()) |win| { _ = win; wx = 0; wy = 0; } else { wx = wid.x(); wy = wid.y(); } self.resize(sx, @as(i32, @intFromFloat(sy)) + wy, @as(u31, @intFromFloat(sw)), @as(u31, @intFromFloat(sh))); self.redraw(); } pub fn sizeOf(self: *Self, wid: anytype) void { if (!comptime zfltk.isWidget(@TypeOf(wid))) { return; } std.debug.assert(wid.w() != 0 and wid.h() != 0); self.resize(self.x(), self.y(), wid.w(), wid.h()); } pub fn sizeOfParent(self: *Self) void { const par = self.parent(); if (par) |p| self.sizeOf(p); } pub fn belowOf( self: *Self, wid: anytype, padding: i32, ) void { if (!comptime zfltk.isWidget(@TypeOf(wid))) { return; } std.debug.assert( self.w() != 0 and self.h() != 0, ); self.resize(wid.x(), wid.y() + wid.h() + padding, self.w(), self.h()); } pub fn aboveOf( self: *Self, wid: anytype, padding: i32, ) void { if (!comptime zfltk.isWidget(@TypeOf(wid))) { return; } std.debug.assert( self.w() != 0 and self.h() != 0, ); self.resize(wid.x(), wid.y() - wid.h() - padding, self.w(), self.h()); } pub fn rightOf( self: *Self, wid: anytype, padding: i32, ) void { if (!comptime zfltk.isWidget(@TypeOf(wid))) { return; } std.debug.assert( self.w() != 0 and self.h() != 0, ); self.resize(wid.x() + wid.w() + padding, wid.y(), self.w(), self.h()); } pub fn leftOf( self: *Self, wid: anytype, padding: i32, ) void { if (!comptime zfltk.isWidget(@TypeOf(wid))) { return; } std.debug.assert( self.w() != 0 and self.h() != 0, ); self.resize(wid.x() - self.w() - padding, wid.y(), self.w(), self.h()); } }; } pub fn shim(_: ?*c.Fl_Widget, data: ?*anyopaque) callconv(.C) void { c.Fl_awake_msg(data); } // Small wrapper utilizing FLTK's `data` argument to use non-callconv(.C) // functions as callbacks safely pub fn zfltk_cb_handler(wid: ?*c.Fl_Widget, data: ?*anyopaque) callconv(.C) void { // Fetch function pointer from the data. This is added to the data // pointer on `setCallback`. const cb: *const fn (*Widget) void = @ptrCast(data); if (wid) |ptr| { cb(Widget.fromRaw(ptr)); } else { unreachable; } } pub fn zfltk_cb_handler_ex(wid: ?*c.Fl_Widget, data: ?*anyopaque) callconv(.C) void { const container: *[2]usize = @ptrCast(@alignCast(data)); const cb: *const fn (*Widget, ?*anyopaque) void = @ptrFromInt(container[0]); if (wid) |ptr| { cb(Widget.fromRaw(ptr), @ptrFromInt(container[1])); } else { unreachable; } } pub fn zfltk_event_handler(wid: ?*c.Fl_Widget, event: c_int, data: ?*anyopaque) callconv(.C) c_int { const cb: *const fn (*Widget, enums.Event, ?*anyopaque) bool = @ptrCast( data, ); return @intFromBool(cb( Widget.fromRaw(wid.?), @enumFromInt(event), null, )); } pub fn zfltk_event_handler_ex(wid: ?*c.Fl_Widget, ev: c_int, data: ?*anyopaque) callconv(.C) c_int { const container: *[2]usize = @ptrCast(@alignCast(data)); const cb: *const fn (*Widget, enums.Event, ?*anyopaque) bool = @ptrFromInt( container[0], ); return @intFromBool(cb( Widget.fromRaw(wid.?), @enumFromInt(ev), @ptrFromInt(container[1]), )); } pub fn zfltk_draw_handler(wid: ?*c.Fl_Widget, data: ?*anyopaque) callconv(.C) void { const cb: *const fn (*Widget, ?*anyopaque) void = @ptrCast( data, ); cb( Widget.fromRaw(wid.?), null, ); } pub fn zfltk_draw_handler_ex(wid: ?*c.Fl_Widget, data: ?*anyopaque) callconv(.C) void { const container: *[2]usize = @ptrCast(@alignCast(data)); const cb: *const fn (*Widget, ?*anyopaque) void = @ptrFromInt( container[0], ); cb( Widget.fromRaw(wid.?), @ptrFromInt(container[1]), ); } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/draw.zig
const c = @cImport({ @cInclude("cfl_draw.h"); }); const Font = @import("enums.zig").Font; const BoxType = @import("enums.zig").BoxType; const Cursor = @import("enums.zig").Cursor; const Color = @import("enums.zig").Color; pub const LineStyle = enum(i32) { /// Solid line Solid = 0, /// Dash Dash, /// Dot Dot, /// Dash dot DashDot, /// Dash dot dot DashDotDot, /// Cap flat CapFlat = 100, /// Cap round CapRound = 200, /// Cap square CapSquare = 300, /// Join miter JoinMiter = 1000, /// Join round JoinRound = 2000, /// Join bevel JoinBevel = 3000, }; /// Opaque type around Fl_Region pub const Region = ?*anyopaque; /// Opaque type around Fl_Offscreen pub const Offscreen = struct { inner: ?*anyopaque, pub fn new(w: i32, h: i32) Offscreen { return Offscreen{ .inner = c.Fl_create_offscreen(w, h) }; } /// Begins drawing in the offscreen pub fn begin(self: *Offscreen) void { c.Fl_begin_offscreen(self.inner); } /// Ends drawing in the offscreen pub fn end() void { c.Fl_end_offscreen(); } /// Copies the offscreen pub fn copy(self: *Offscreen, x: i32, y: i32, w: i32, h: i32, srcx: i32, srcy: i32) void { c.Fl_copy_offscreen(x, y, w, h, self.inner, srcx, srcy); } /// Rescales the offscreen pub fn rescale(self: *Offscreen) void { c.Fl_rescale_offscreen(&self.inner); } pub fn delete(self: *Offscreen) void { c.Fl_delete_offscreen(self.inner); } }; /// Shows a color map and returns the selected color pub fn showColorMap(old_color: Color) Color { return Color.fromRgbi(c.Fl_show_colormap(old_color.toRgbi())); } /// Change the draw color pub fn setColor(col: Color) void { c.Fl_set_color_int(col.toRgbi()); } /// Gets the last used color pub fn color() Color { return Color.fromRgbi(c.Fl_get_color()); } /// Draws a line pub fn line(x1: i32, y1: i32, x2: i32, y2: i32) void { c.Fl_line(x1, y1, x2, y2); } /// Draws a point pub fn point(x: i32, y: i32) void { c.Fl_point(x, y); } /// Draws a rectangle pub fn rect(x: i32, y: i32, w: i32, h: i32) void { c.Fl_rect(x, y, w, h); } /// Draws a rectangle with border color pub fn rectWithColor(x: i32, y: i32, w: i32, h: i32, col: Color) void { c.Fl_rect_with_color(x, y, w, h, col.toRgbi()); } /// Draws a non-filled 3-sided polygon pub fn loop(x1: i32, y1: i32, x2: i32, y2: i32, x3: i32, y3: i32) void { c.Fl_loop(x1, y1, x2, y2, x3, y3); } /// Draws a filled rectangle pub fn rectFill(x: i32, y: i32, w: i32, h: i32) void { c.Fl_rectf(x, y, w, h); } /// Draws a filled rectangle pub fn rectFillWithColor(x: i32, y: i32, w: i32, h: i32, col: Color) void { c.Fl_rectf_with_color(x, y, w, h, col.toRgbi()); } /// Draws a focus rectangle pub fn focusRect(x: i32, y: i32, w: i32, h: i32) void { c.Fl_focus_rect(x, y, w, h); } /// Draws a circle pub fn circle(x: f64, y: f64, r: f64) void { c.Fl_circle(x, y, r); } /// Draws an arc pub fn arc(x: i32, y: i32, w: i32, h: i32, a: f64, b: f64) void { c.Fl_arc(x, y, w, h, a, b); } /// Draws an arc pub fn arc2(x: f64, y: f64, r: f64, start: f64, end: f64) void { c.Fl_arc2(x, y, r, start, end); } /// Draws a filled pie pub fn pie(x: i32, y: i32, w: i32, h: i32, a: f64, b: f64) void { c.Fl_pie(x, y, w, h, a, b); } /// Sets the line style pub fn setLineStyle(style: LineStyle, thickness: i32) void { c.Fl_line_style( @intFromEnum(style), thickness, null, ); } /// Limits drawing to a region pub fn pushClip(x: i32, y: i32, w: i32, h: i32) void { c.Fl_push_clip(x, y, w, h); } /// Puts the drawing back pub fn popClip() void { c.Fl_pop_clip(); } /// Sets the clip region pub fn setClipRegion(r: Region) void { c.Fl_set_clip_region(r); } /// Gets the clip region pub fn clipRegion() Region { return c.Fl_clip_region(); } /// Pushes an empty clip region onto the stack so nothing will be clipped pub fn pushNoClip() void { c.Fl_push_no_clip(); } /// Returns whether the rectangle intersect with the current clip region pub fn notClipped(x: i32, y: i32, w: i32, h: i32) bool { return c.Fl_not_clipped(x, y, w, h) != 0; } /// Restores the clip region pub fn resoreClip() void { c.Fl_restore_clip(); } /// Transforms coordinate using the current transformation matrix pub fn transformX(x: f64, y: f64) f64 { return c.Fl_transform_x(x, y); } /// Transforms coordinate using the current transformation matrix pub fn transformY(x: f64, y: f64) f64 { return c.Fl_transform_y(x, y); } /// Transforms distance using current transformation matrix pub fn transformDX(x: f64, y: f64) f64 { return c.Fl_transform_dx(x, y); } /// Transforms distance using current transformation matrix pub fn transformDY(x: f64, y: f64) f64 { return c.Fl_transform_dy(x, y); } /// Adds coordinate pair to the vertex list without further transformations pub fn transformedVertex(xf: f64, yf: f64) void { c.Fl_transformed_vertex(xf, yf); } /// Fills a 3-sided polygon. The polygon must be convex pub fn polygon(x: i32, y: i32, x1: i32, y1: i32, x2: i32, y2: i32) void { c.Fl_polygon(x, y, x1, y1, x2, y2); } /// Draws a horizontal line from (x,y) to (x1,y) // Maybe the API shouldn't be changed? I think this looks better when following // Zig's conventions though pub fn lineXY(x: i32, y: i32, x1: i32) void { c.Fl_xyline(x, y, x1); } /// Draws a horizontal line from (x,y) to (x1,y), then vertical from (x1,y) to (x1,y2) pub fn lineXY2(x: i32, y: i32, x1: i32, y2: i32) void { c.Fl_xyline2(x, y, x1, y2); } /// Draws a horizontal line from (x,y) to (x1,y), then a vertical from (x1,y) to (x1,y2) /// and then another horizontal from (x1,y2) to (x3,y2) pub fn lineXY3(x: i32, y: i32, x1: i32, y2: i32, x3: i32) void { c.Fl_xyline3(x, y, x1, y2, x3); } /// Draws a vertical line from (x,y) to (x,y1) pub fn lineYX(x: i32, y: i32, y1: i32) void { c.Fl_yxline(x, y, y1); } /// Draws a vertical line from (x,y) to (x,y1), then a horizontal from (x,y1) to (x2,y1) pub fn lineYX2(x: i32, y: i32, y1: i32, x2: i32) void { c.Fl_yxline2(x, y, y1, x2); } /// Draws a vertical line from (x,y) to (x,y1) then a horizontal from (x,y1) /// to (x2,y1), then another vertical from (x2,y1) to (x2,y3) pub fn lineYX3(x: i32, y: i32, y1: i32, x2: i32, y3: i32) void { c.Fl_yxline3(x, y, y1, x2, y3); } /// Saves the current transformation matrix on the stack pub fn pushMatrix() void { c.Fl_push_matrix(); } /// Pops the current transformation matrix from the stack pub fn popMatrix() void { c.Fl_pop_matrix(); } /// Concatenates scaling transformation onto the current one pub fn scale(x: f64, y: f64) void { c.Fl_scale(x, y); } /// Concatenates scaling transformation onto the current one pub fn scale2(x: f64) void { c.Fl_scale2(x); } /// Concatenates translation transformation onto the current one pub fn translate(x: f64, y: f64) void { c.Fl_translate(x, y); } /// Concatenates rotation transformation onto the current one pub fn rotate(d: f64) void { c.Fl_rotate(d); } /// Concatenates another transformation onto the current one pub fn multMatrix(val_a: f64, val_b: f64, val_c: f64, val_d: f64, x: f64, y: f64) void { c.Fl_mult_matrix(val_a, val_b, val_c, val_d, x, y); } /// Starts drawing a list of points. Points are added to the list with fl_vertex() pub fn beginPoints() void { c.Fl_begin_points(); } /// Starts drawing a list of lines pub fn beginLine() void { c.Fl_begin_line(); } /// Starts drawing a closed sequence of lines pub fn beginLoop() void { c.Fl_begin_loop(); } /// Starts drawing a convex filled polygon pub fn beginPolygon() void { c.Fl_begin_polygon(); } /// Adds a single vertex to the current path pub fn vertex(x: f64, y: f64) void { c.Fl_vertex(x, y); } /// Ends list of points, and draws pub fn endPoints() void { c.Fl_end_points(); } /// Ends list of lines, and draws pub fn endLine() void { c.Fl_end_line(); } /// Ends closed sequence of lines, and draws pub fn endLoop() void { c.Fl_end_loop(); } /// Ends closed sequence of lines, and draws pub fn endPolygon() void { c.Fl_end_polygon(); } /// Starts drawing a complex filled polygon pub fn beginComplexPolygon() void { c.Fl_begin_complex_polygon(); } /// Call gap() to separate loops of the path pub fn gap() void { c.Fl_gap(); } /// Ends complex filled polygon, and draws pub fn endComplexPolygon() void { c.Fl_end_complex_polygon(); } /// Sets the current font, which is then used in various drawing routines pub fn setFont(face: Font, fsize: u32) void { c.Fl_set_draw_font(@intFromEnum(face), @intCast(fsize)); } /// Gets the current font, which is used in various drawing routines pub fn font() Font { return @enumFromInt(c.Fl_font()); } /// Gets the current font size, which is used in various drawing routines pub fn size() u32 { return @intCast(c.Fl_size()); } /// Returns the recommended minimum line spacing for the current font pub fn height() i32 { return c.Fl_height(); } /// Sets the line spacing for the current font pub fn setHeight(f: Font, sz: u32) void { _ = c.Fl_set_height(@intFromEnum(f), @intCast(sz)); } /// Returns the recommended distance above the bottom of a height() tall box to /// draw the text at so it looks centered vertically in that box pub fn descent() i32 { return c.Fl_descent(); } pub fn width(txt: [*c]const u8) f64 { return c.Fl_width(txt); } /// Returns the typographical width of a sequence of n characters pub fn width2(txt: [*c]const u8, n: i32) f64 { return c.Fl_width2(txt, n); } /// Returns the typographical width of a single character pub fn charWidth(val: u8) f64 { return c.Fl_width3(val); } /// Converts text from Windows/X11 latin1 character set to local encoding pub fn latin1ToLocal(txt: [*c]const u8, n: i32) [*c]const u8 { return c.Fl_latin1_to_local(txt, n); } /// Converts text from local encoding to Windowx/X11 latin1 character set pub fn localToLatin1(txt: [*c]const u8, n: i32) [*c]const u8 { return c.Fl_local_to_latin1(txt, n); } /// Draws a string starting at the given x, y location pub fn drawText(txt: [*c]const u8, x: i32, y: i32) void { c.Fl_draw(txt, x, y); } /// Draws a string starting at the given x, y location with width and height and alignment pub fn drawText2(string: [*c]const u8, x: i32, y: i32, w: i32, h: i32, al: i32) void { c.Fl_draw_text2(string, x, y, w, h, al); } /// Draws a string starting at the given x, y location, rotated to an angle pub fn drawTextAngled(angle: i32, txt: [*c]const u8, x: i32, y: i32) void { c.Fl_draw2(angle, txt, x, y); } /// Draws a frame with text pub fn drawFrame(string: [*c]const u8, x: i32, y: i32, w: i32, h: i32) void { c.Fl_frame(string, x, y, w, h); } /// Draws a frame with text. /// Differs from frame() by the order of the line segments pub fn drawFrame2(string: [*c]const u8, x: i32, y: i32, w: i32, h: i32) void { c.Fl_frame2(string, x, y, w, h); } /// Draws a box given the box type, size, position and color pub fn box(box_type: BoxType, x: i32, y: i32, w: i32, h: i32, col: Color) void { c.Fl_draw_box(@intFromEnum(box_type), x, y, w, h, col.toRgbi()); } /// Checks whether platform supports true alpha blending for RGBA images pub fn canDoAlphaBlending() bool { return c.Fl_can_do_alpha_blending() != 0; } /// Get a human-readable string from a shortcut value pub fn shortcutLabel(shortcut: i32) [*c]const u8 { return c.Fl_shortcut_label(@intCast(shortcut)); } /// Draws a selection rectangle, erasing a previous one by XOR'ing it first. pub fn overlayRect(x: i32, y: i32, w: i32, h: i32) void { c.Fl_overlay_rect(x, y, w, h); } /// Erase a selection rectangle without drawing a new one pub fn overlayClear() void { c.Fl_overlay_clear(); } /// Sets the cursor style pub fn setCursor(cursor: Cursor) void { c.Fl_set_cursor(@intFromEnum(cursor)); } /// Sets the cursor style pub fn setCursorWithColor(cursor: Cursor, fg: Color, bg: Color) void { c.Fl_set_cursor2(@intFromEnum(cursor), @intCast(fg.toRgbi()), @intCast(bg.toRgbi())); } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/output.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const Widget = zfltk.Widget; const enums = zfltk.enums; const Event = enums.Event; const Color = enums.Color; const Font = enums.Font; const std = @import("std"); const c = zfltk.c; const widget = zfltk.widget; const OutputKind = enum { normal, multiline, }; pub const Output = OutputType(.normal); pub const MultilineOutput = OutputType(.multiline); fn OutputType(comptime kind: OutputKind) type { return struct { const Self = @This(); pub usingnamespace zfltk.widget.methods(Self, RawPtr); const OutputRawPtr = *c.Fl_Output; pub const RawPtr = switch (kind) { .normal => *c.Fl_Output, .multiline => *c.Fl_Multiline_Output, }; pub fn init(opts: Widget.Options) !*Self { const initFn = switch (kind) { .normal => c.Fl_Output_new, .multiline => c.Fl_Multiline_Output_new, }; const label = if (opts.label != null) opts.label.?.ptr else null; if (initFn(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { return Self.fromRaw(ptr); } unreachable; } pub inline fn deinit(self: *Self) void { const deinitFn = switch (kind) { .normal => c.Fl_Output_delete, .multiline => c.Fl_Multiline_Output_delete, }; deinitFn(self.raw()); app.allocator.destroy(self); } pub inline fn input(self: *Self) *OutputType(.normal) { return @ptrCast(self); } pub fn value(self: *Self) [:0]const u8 { return std.mem.span(c.Fl_Output_value(self.input().raw())); } pub fn insert(self: *Output, val: [*c]const u8, idx: u16) !void { _ = c.Fl_Output_insert(self.input().raw(), val, idx); } // TODO: handle errors pub fn setValue(self: *Output, val: [*c]const u8) !void { _ = c.Fl_Output_set_value(self.input().raw(), val); } pub fn position(self: *Output) u16 { return @intCast(c.Fl_Output_position(self.input().raw())); } pub fn setPosition(self: *Output, sz: u16) !void { _ = c.Fl_Output_set_position(self.input().raw(), sz); } pub fn setTextFont(self: *Output, font: Font) void { c.Fl_Output_set_text_font(self.input().raw(), @intFromEnum(font)); } pub fn setTextColor(self: *Output, col: Color) void { c.Fl_Output_set_text_color(self.input().raw(), col.toRgbi()); } pub fn setTextSize(self: *Output, sz: i32) void { c.Fl_Output_set_text_size(self.input().raw(), sz); } }; } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/input.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const Widget = zfltk.widget.Widget; const enums = zfltk.enums; const Event = enums.Event; const Color = enums.Color; const Font = enums.Font; const std = @import("std"); const widget = zfltk.widget; const c = zfltk.c; pub const Input = InputType(.normal); pub const MultilineInput = InputType(.multiline); pub const IntInput = InputType(.int); pub const FloatInput = InputType(.float); pub const Secret = InputType(.secret); const InputKind = enum { normal, multiline, int, float, secret, }; fn InputType(comptime kind: InputKind) type { return struct { const Self = @This(); pub usingnamespace zfltk.widget.methods(Self, RawPtr); const InputRawPtr = *c.Fl_Input; pub const RawPtr = switch (kind) { .normal => *c.Fl_Input, .multiline => *c.Fl_Multiline_Input, .int => *c.Fl_Int_Input, .float => *c.Fl_Float_Input, .secret => *c.Fl_Secret_Input, }; pub fn init(opts: Widget.Options) !*Self { const initFn = switch (kind) { .normal => c.Fl_Input_new, .multiline => c.Fl_Multiline_Input_new, .int => c.Fl_Int_Input_new, .float => c.Fl_Float_Input_new, .secret => c.Fl_Secret_Input_new, }; const label = if (opts.label != null) opts.label.?.ptr else null; if (initFn(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { return Self.fromRaw(ptr); } unreachable; } pub inline fn deinit(self: *Self) void { const deinitFn = switch (kind) { .normal => c.Fl_Input_delete, .multiline => c.Fl_Multiline_Input_delete, .int => c.Fl_Int_Input_delete, .float => c.Fl_Float_Input_delete, .secret => c.Fl_Secret_Input_delete, }; deinitFn(self.raw()); app.allocator.destroy(self); } pub inline fn input(self: *Self) *InputType(.normal) { return @ptrCast(self); } pub fn value(self: *Self) [:0]const u8 { return std.mem.span(c.Fl_Input_value(self.input().raw())); } pub fn insert(self: *Input, val: [*c]const u8, idx: u16) !void { _ = c.Fl_Input_insert(self.input().raw(), val, idx); } // TODO: handle errors pub fn setValue(self: *Input, val: [*c]const u8) !void { _ = c.Fl_Input_set_value(self.input().raw(), val); } pub fn position(self: *Input) u16 { return @intCast(c.Fl_Input_position(self.input().raw())); } pub fn setPosition(self: *Input, sz: u16) !void { _ = c.Fl_Input_set_position(self.input().raw(), sz); } pub fn setTextFont(self: *Input, font: Font) void { c.Fl_Input_set_text_font(self.input().raw(), @intFromEnum(font)); } pub fn setTextColor(self: *Input, col: Color) void { c.Fl_Input_set_text_color(self.input().raw(), col.toRgbi()); } pub fn setTextSize(self: *Input, sz: i32) void { c.Fl_Input_set_text_size(self.input().raw(), sz); } }; } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/valuator.zig
const zfltk = @import("zfltk.zig"); const Widget = zfltk.Widget; const c = zfltk.c; const widget = zfltk.widget; const enums = zfltk.enums; const std = @import("std"); const app = zfltk.app; pub const Slider = ValuatorType(.slider); pub const Dial = ValuatorType(.dial); pub const Counter = ValuatorType(.counter); pub const Scrollbar = ValuatorType(.scrollbar); pub const Adjuster = ValuatorType(.adjuster); pub const Roller = ValuatorType(.roller); const ValuatorKind = enum { slider, dial, counter, scrollbar, adjuster, roller, }; pub const SliderType = enum(i32) { /// vertical slider vertical = 0, /// horizontal slider horizontal = 1, /// vertical fill slider vertical_fill = 2, /// horizontal fill slider horizontal_fill = 3, /// vertical nice slider vertical_nice = 4, /// horizontal nice slider horizontal_nice = 5, }; pub const ScrollbarType = enum(i32) { /// vertical scrollbar vertical = 0, /// horizontal scrollbar horizontal = 1, /// vertical fill scrollbar vertical_fill = 2, /// horizontal fill scrollbar horizontal_fill = 3, /// vertical nice scrollbar vertical_nice = 4, /// horizontal nice scrollbar horizontal_nice = 5, }; pub const DialType = enum(i32) { /// normal dial normal = 0, /// line dial line = 1, /// filled dial fill = 2, }; pub const CounterType = enum(i32) { /// normal counter normal = 0, /// simple counter simple = 1, }; fn ValuatorType(comptime kind: ValuatorKind) type { return struct { const Self = @This(); pub usingnamespace zfltk.widget.methods(Self, RawPtr); pub usingnamespace methods(Self, RawPtr); pub const RawPtr = switch (kind) { .slider => *c.Fl_Slider, .dial => *c.Fl_Dial, .counter => *c.Fl_Counter, .scrollbar => *c.Fl_Scrollbar, .adjuster => *c.Fl_Adjuster, .roller => *c.Fl_Roller, }; const type_name = @typeName(RawPtr); const ptr_name = type_name[(std.mem.indexOf(u8, type_name, "struct_Fl_") orelse 0) + 7 .. type_name.len]; pub const Options = struct { x: i32 = 0, y: i32 = 0, w: u31 = 0, h: u31 = 0, label: ?[:0]const u8 = null, orientation: Orientation = switch (kind) { .slider, .scrollbar => .vertical, else => .FILLER, }, style: Style = switch (kind) { .slider, .scrollbar, .counter => .normal, else => .FILLER, }, pub const Orientation = switch (kind) { .slider, .scrollbar => enum(c_int) { vertical = 0, horizontal = 1, }, else => enum(c_int) { FILLER = 0 }, }; pub const Style = switch (kind) { .slider, .scrollbar => enum(c_int) { normal = 0, fill = 2, nice = 4, }, .counter => enum(c_int) { normal = 0, simple = 1, }, else => enum(c_int) { FILLER = 0 }, }; }; pub inline fn init(opts: Options) !*Self { const initFn = @field(c, ptr_name ++ "_new"); const label = if (opts.label != null) opts.label.?.ptr else null; if (initFn(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { var self = Self.fromRaw(ptr); const orientation = @intFromEnum(opts.orientation); const style = @intFromEnum(opts.style); c.Fl_Widget_set_type(self.widget().raw(), orientation + style); return self; } unreachable; } pub inline fn deinit(self: *Self) void { const deinitFn = @field(c, ptr_name ++ "_delete"); deinitFn(self.raw()); app.allocator.destroy(self); } }; } fn methods(comptime Self: type, comptime RawPtr: type) type { const type_name = @typeName(RawPtr); const ptr_name = type_name[(std.mem.indexOf(u8, type_name, "struct_Fl_") orelse 0) + 7 .. type_name.len]; return struct { pub inline fn valuator(self: *Self) *ValuatorType(.slider) { return @ptrCast(self); } pub inline fn setBounds(self: *Self, a: f64, b: f64) void { return @field(c, ptr_name ++ "_set_bounds")(self.raw(), a, b); } pub inline fn minimum(self: *Self) f64 { return @field(c, ptr_name ++ "_minimum")(self.raw()); } pub inline fn setMinimum(self: *Self, a: f64) void { @field(c, ptr_name ++ "_set_minimum")(self.raw(), a); } pub inline fn maximum(self: *Self) f64 { return @field(c, ptr_name ++ "_maximum")(self.raw()); } pub inline fn setMaximum(self: *Self, a: f64) void { @field(c, ptr_name ++ "_set_maximum")(self.raw(), a); } pub inline fn setRange(self: *Self, a: f64, b: f64) void { return @field(c, ptr_name ++ "_set_range")(self.raw(), a, b); } pub inline fn setStep(self: *Self, a: f64, b: i32) void { return @field(c, ptr_name ++ "_set_step")(self.raw(), a, b); } pub inline fn step(self: *Self) f64 { return @field(c, ptr_name ++ "_step")(self.raw()); } pub inline fn setPrecision(self: *Self, digits: i32) void { return @field(c, ptr_name ++ "_set_precision")(self.raw(), digits); } pub inline fn value(self: *Self) f64 { return @field(c, ptr_name ++ "_value")(self.raw()); } pub inline fn setValue(self: *Self, arg2: f64) void { return @field(c, ptr_name ++ "_set_value")(self.raw(), arg2); } pub inline fn format(self: *Self, arg2: [*c]const u8) void { return @field(c, ptr_name ++ "_format")(self.raw(), arg2); } pub inline fn round(self: *Self, arg2: f64) f64 { return @field(c, ptr_name ++ "_round")(self.raw(), arg2); } pub inline fn clamp(self: *Self, arg2: f64) f64 { return @field(c, ptr_name ++ "_clamp")(self.raw(), arg2); } pub inline fn increment(self: *Self, arg2: f64, arg3: i32) f64 { return @field(c, ptr_name ++ "_increment")(self.raw(), arg2, arg3); } }; } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/app.zig
const zfltk = @import("zfltk.zig"); const Widget = @import("widget.zig").Widget; const enums = @import("enums.zig"); const Color = enums.Color; const Font = enums.Font; const std = @import("std"); const c = zfltk.c; const Scheme = enum { base, gtk, plastic, gleam, oxy, }; // TODO: allow setting this pub var allocator: std.mem.Allocator = std.heap.c_allocator; // TODO: Add more error types pub const AppError = error{ Error, }; // Converts a C error code to a Zig error enum inline fn AppErrorFromInt(err: c_int) AppError!void { return switch (err) { 0 => {}, else => AppError.Error, }; } // fltk initizialization of optional functionalities pub fn init() !void { c.Fl_init_all(); // inits all styles, if needed c.Fl_register_images(); // register image types supported by fltk, if needed // Enable multithreading if (c.Fl_lock() != 0) return error.LockError; } pub inline fn run() !void { return AppErrorFromInt(c.Fl_run()); } pub inline fn setScheme(scheme: Scheme) void { _ = c.Fl_set_scheme(switch (scheme) { .base => "base", .gtk => "gtk+", .plastic => "plastic", .gleam => "gleam", .oxy => "oxy", }); } pub inline fn lock() !void { if (c.Fl_lock() != 0) return error.LockError; } pub inline fn unlock() void { c.Fl_unlock(); } // Set the boxtype's draw callback pub inline fn setBoxTypeEx( box: enums.BoxType, f: *const fn (i32, i32, i32, i32, enums.Color) callconv(.C) void, off_x: i32, off_y: i32, off_w: i32, off_h: i32, ) void { c.Fl_set_box_type_cb( @intFromEnum(box), @ptrCast(f), off_x, off_y, off_w, off_h, ); } // Simplified version of setBoxTypeEx to keep code a bit cleaner when offsets // are unneeded pub inline fn setBoxType( box: enums.BoxType, f: *const fn (i32, i32, i32, i32, enums.Color) callconv(.C) void, ) void { setBoxTypeEx(box, f, 0, 0, 0, 0); } // Overriding the boxtype's draw is probably more likely to be a usecase than // copying an existing box, and because C++ allows multiple APIs to have the // same function name, one must be renamed to allow it to be used in Zig pub inline fn copyBoxType(destBox: enums.BoxType, srcBox: enums.BoxType) void { c.Fl_set_box_type(@intFromEnum(destBox), @intFromEnum(srcBox)); } pub inline fn setVisibleFocus(focus: bool) void { c.Fl_set_visible_focus(@intFromBool(focus)); } /// Sets a `free` color in the FLTK color table. These are meant to be /// user-defined pub inline fn setColor(idx: u4, col: enums.Color) void { // FLTK enumerations.H defines `FREE_COLOR` as 16 setColorAny(@as(u8, idx) + 16, col); } /// Allows setting any color in the color table /// Most colors are not intended to be overridden, `setColor` should be /// preferred unless the goal is to override the theme's color scheme. /// Overriding these may cause display elements to look incorrect pub inline fn setColorAny(idx: u8, col: enums.Color) void { c.Fl_set_color(idx, col.r, col.g, col.b); } pub inline fn loadFont(path: [:0]const u8) !void { _ = c.Fl_load_font(path.ptr); } pub inline fn unloadFont(path: [:0]const u8) !void { c.Fl_unload_font(path.ptr); } pub inline fn setFont(face: Font, name: [:0]const u8) void { c.Fl_set_font2(@intFromEnum(face), name.ptr); } pub inline fn setFontSize(sz: u31) void { c.Fl_set_font_size(sz); } pub inline fn event() enums.Event { return @enumFromInt(c.Fl_event()); } pub inline fn eventX() i32 { return c.Fl_event_x(); } pub inline fn eventY() i32 { return c.Fl_event_y(); } // TODO: Implement as an enum (maybe have another function for unknown keys?) pub inline fn eventKey() i32 { return c.Fl_event_key(); } pub inline fn setBackground(col: Color) void { c.Fl_background(col.r, col.g, col.b); } pub inline fn setBackground2(col: Color) void { c.Fl_background2(col.r, col.g, col.b); } pub inline fn setForeground(col: Color) void { c.Fl_foreground(col.r, col.g, col.b); } pub const WidgetTracker = struct { inner: RawPointer, pub const RawPointer = *c.Fl_Widget_Tracker; pub fn init(w: *Widget) WidgetTracker { if (c.Fl_Widget_Tracker_new(w.raw())) |ptr| { return WidgetTracker{ .inner = ptr }; } unreachable; } pub fn deleted(self: *WidgetTracker) bool { return c.Fl_Widget_Tracker_deleted(self.inner) != 0; } pub fn delete(self: WidgetTracker) void { c.Fl_Widget_Tracker_delete(self.inner); } }; pub inline fn awake() void { c.Fl_awake(); } pub inline fn wait() bool { return c.Fl_wait() != 0; } pub inline fn waitFor(v: f64) bool { return c.Fl_wait_for(v) != 0; } pub inline fn check() i32 { return c.Fl_check(); } pub inline fn send(comptime T: type, t: T) void { c.Fl_awake_msg(@ptrFromInt(@intFromEnum(t))); } pub fn recv(comptime T: type) ?T { const temp = c.Fl_thread_msg(); if (temp) |ptr| { return @enumFromInt(@intFromPtr(ptr)); } return null; } // Executes the callback function after `d` (duration in seconds) has passed // TODO: refactor these like `Widget.setCallback` pub fn addTimeout(d: f32, f: *const fn () void) void { c.Fl_add_timeout(d, &zfltk_timeout_handler, @ptrFromInt(@intFromPtr(f))); } fn zfltk_timeout_handler(data: ?*anyopaque) callconv(.C) void { const cb: *const fn () void = @ptrCast(data); cb(); } // The same as `timeout` but allows for data to be passed in pub fn addTimeoutEx(d: f32, f: *const fn (?*anyopaque) void, data: ?*anyopaque) void { var container = allocator.alloc(usize, 2) catch unreachable; container[0] = @intFromPtr(f); container[1] = @intFromPtr(data); c.Fl_add_timeout(d, &zfltk_timeout_handler_ex, @ptrCast(container.ptr)); } fn zfltk_timeout_handler_ex(data: ?*anyopaque) callconv(.C) void { const container: *[2]usize = @ptrCast(@alignCast(data)); const cb: *const fn (?*anyopaque) void = @ptrFromInt(container[0]); // std.debug.print("test1 {d}\n", .{container[0]}); cb(@ptrFromInt(container[1])); } pub fn setMenuLinespacing(h: i32) void { c.Fl_set_menu_linespacing(h); } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/dialog.zig
// TODO: update to new API const zfltk = @import("zfltk.zig"); const c = zfltk.c; const std = @import("std"); pub const FileDialogKind = enum(c_int) { file = 0, dir, multi_file, multi_dir, save_file, save_dir, }; // TODO: refactor to contain all dialog types pub fn FileDialog(comptime kind: FileDialogKind) type { // _ = kind; return struct { const Self = @This(); pub const Options = struct { save_as_confirm: bool = false, new_folder: bool = false, preview: bool = false, use_filter_extension: bool = false, filter: ?[:0]const u8 = null, }; pub inline fn init(opts: Options) !*Self { // Convert bools to OR'd int const save_as_confirm = @as(c_int, @intFromBool(opts.save_as_confirm)); const new_folder = @as(c_int, @intFromBool(opts.new_folder)) << 1; const preview = @as(c_int, @intFromBool(opts.preview)) << 2; const use_filter_extension = @as(c_int, @intFromBool(opts.use_filter_extension)) << 3; const flags = save_as_confirm | new_folder | preview | use_filter_extension; if (c.Fl_Native_File_Chooser_new(flags)) |ptr| { const self = Self.fromRaw(ptr); if (opts.filter) |filter| { self.setFilter(filter); } self.setType(kind); return Self.fromRaw(ptr); } unreachable; } pub inline fn dialog(self: *Self) *Self { return self; } pub fn setType(self: *Self, opt: FileDialogKind) void { c.Fl_Native_File_Chooser_set_type(self.raw(), @intFromEnum(opt)); } pub fn filename(self: *Self) [:0]const u8 { if (self.count() > 0) { return std.mem.span(c.Fl_Native_File_Chooser_filenames(self.raw(), 0)); } else { return ""; } } pub fn filenameAt(self: *Self, idx: u32) [*c]const u8 { return c.Fl_Native_File_Chooser_filenames(self.raw(), idx); } pub fn count(self: *Self) u32 { return @intCast(c.Fl_Native_File_Chooser_count(self.raw())); } pub fn setDirectory(self: *Self, dir: [:0]const u8) void { c.Fl_Native_File_Chooser_set_directory(self.raw(), dir.ptr); } pub fn directory(self: *Self) [*c][]const u8 { return c.Fl_Native_File_Chooser_directory(self.raw()); } /// Sets the filter for the dialog, can be: /// A single wildcard (eg. "*.txt") /// Multiple wildcards (eg. "*.{cxx,h,H}") /// A descriptive name followed by a "\t" and a wildcard (eg. "Text Files\t*.txt") /// A list of separate wildcards with a "\n" between each (eg. "*.{cxx,H}\n*.txt") /// A list of descriptive names and wildcards (eg. "C++ Files\t*.{cxx,H}\nTxt Files\t*.txt") pub inline fn setFilter(self: *Self, f: [:0]const u8) void { c.Fl_Native_File_Chooser_set_filter(self.dialog().raw(), f.ptr); } /// Sets the preset filter for the dialog pub inline fn setPresetFile(self: *Self, f: [:0]const u8) void { c.Fl_Native_File_Chooser_set_preset_file(self.raw(), f.ptr); } pub inline fn show(self: *Self) void { _ = c.Fl_Native_File_Chooser_show(self.raw()); } pub inline fn fromRaw(ptr: *anyopaque) *Self { return @ptrCast(ptr); } pub inline fn raw(self: *Self) *c.Fl_Native_File_Chooser { return @ptrCast(@alignCast(self)); } }; } /// Displays an message box pub fn message(x: i32, y: i32, msg: [*c]const u8) void { c.Fl_message(x, y, msg); } /// Displays an alert box pub fn alert(x: i32, y: i32, txt: [*c]const u8) void { c.Fl_alert(x, y, txt); } /// Displays a choice box with upto three choices /// An empty choice will not be shown pub fn choice(x: i32, y: i32, txt: [*c]const u8, b0: [*c]const u8, b1: [*c]const u8, b2: [*c]const u8) u32 { return @intCast(c.Fl_choice(x, y, txt, b0, b1, b2)); } /// Displays an input box, which returns the inputted string. /// Can be used for gui io pub fn input(x: i32, y: i32, txt: [*c]const u8, deflt: [*c]const u8) [*c]const u8 { return c.Fl_input(x, y, txt, deflt); } /// Shows an input box, but with hidden string pub fn password(x: i32, y: i32, txt: [*c]const u8, deflt: [*c]const u8) [*c]const u8 { return c.Fl_password(x, y, txt, deflt); } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/text.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const Widget = zfltk.Widget; const enums = zfltk.enums; const widget = zfltk.widget; const c = zfltk.c; const std = @import("std"); pub const StyleTableEntry = struct { /// Font color color: enums.Color, /// Font type font: enums.Font, /// Font size size: i32, }; const TextKind = enum { normal, editor, }; pub const TextDisplay = TextDisplayType(.normal); pub const TextEditor = TextDisplayType(.editor); pub const TextBuffer = struct { const Self = @This(); pub usingnamespace zfltk.widget.methods(TextBuffer, RawPtr); pub const RawPtr = *c.Fl_Text_Buffer; pub inline fn init() !*TextBuffer { if (c.Fl_Text_Buffer_new()) |ptr| { return Self.fromRaw(ptr); } unreachable; } pub inline fn deinit(self: *Self) void { c.Fl_Text_Buffer_delete(self.raw()); app.allocator.destroy(self); } // TODO: find a fast way to implement these methods using slices /// Sets the text of the buffer pub fn setText(self: *TextBuffer, txt: [:0]const u8) void { return c.Fl_Text_Buffer_set_text(self.raw(), txt); } /// Returns the text of the buffer pub fn text(self: *TextBuffer) [:0]const u8 { return c.Fl_Text_Buffer_text(self.raw()); } /// Appends to the buffer pub fn append(self: *TextBuffer, str: [:0]const u8) void { return c.Fl_Text_Buffer_append(self.raw(), str); } /// Get the length of the buffer pub fn length(self: *TextBuffer) u31 { return @intCast(c.Fl_Text_Buffer_length(self.raw())); } /// Removes from the buffer pub fn remove(self: *TextBuffer, start: u32, end: u32) void { return c.Fl_Text_Buffer_remove(self.raw(), @intCast(start), @intCast(end)); } /// Returns the text within the range pub fn textRange(self: *TextBuffer, start: u32, end: u32) [:0]const u8 { return c.Fl_Text_Buffer_text_range(self.raw(), @intCast(start), @intCast(end)); } /// Inserts text into a position pub fn insert(self: *TextBuffer, pos: u32, str: [:0]const u8) void { c.Fl_Text_Buffer_insert(self.raw(), @intCast(pos), str); } /// Replaces text from position ```start``` to ```end``` pub fn replace(self: *TextBuffer, start: u32, end: u32, txt: [:0]const u8) void { c.Fl_Text_Buffer_replace(self.raw(), @intCast(start), @intCast(end), txt); } /// Copies text from a source buffer into the current buffer pub fn copyFrom(self: *TextBuffer, source_buf: *TextBuffer, start: u31, end: u31, to: u31) void { c.Fl_Text_Buffer_copy( self.raw(), source_buf.raw(), @intCast(start), end, to, ); } /// Copies whole text from a source buffer into a new buffer pub fn copy(self: *TextBuffer) !*TextBuffer { var temp = try TextBuffer.init(); temp.copyFrom(self, 0, 0, self.length()); return temp; } /// Performs an undo operation on the buffer pub fn undo(self: *TextBuffer) void { _ = c.Fl_Text_Buffer_undo(self.raw(), null); } /// Sets whether the buffer can undo pub fn canUndo(self: *TextBuffer, flag: bool) void { c.Fl_Text_Buffer_canUndo(self.raw(), @intFromBool(flag)); } pub fn lineStart(self: *TextBuffer, pos: u32) u32 { return @intCast(c.Fl_Text_Buffer_line_start(self.raw(), @intCast(pos))); } /// Loads a file into the buffer pub fn loadFile(self: *TextBuffer, path: [:0]const u8) !void { const ret = c.Fl_Text_Buffer_load_file(self.raw(), path.ptr); if (ret != 0) return error.InvalidParameter; } /// Saves a buffer into a file pub fn saveFile(self: *TextBuffer, path: [:0]const u8) !void { const ret = c.Fl_Text_Buffer_save_file(self.raw(), path.ptr); if (ret != 0) return error.InvalidParameter; } /// Returns the tab distance for the buffer pub fn tabDistance(self: *TextBuffer) u32 { return @intCast(c.Fl_Text_Buffer_tab_distance(self.raw())); } /// Sets the tab distance pub fn setTabDistance(self: *TextBuffer, tab_dist: u32) void { c.Fl_Text_Buffer_set_tab_distance(self.raw(), @intCast(tab_dist)); } /// Selects the text from start to end pub fn select(self: *TextBuffer, start: u32, end: u32) void { c.Fl_Text_Buffer_select(self.raw(), @intCast(start), @intCast(end)); } /// Returns whether text is selected pub fn selected(self: *TextBuffer) bool { return c.Fl_Text_Buffer_selected(self.raw()) != 0; } /// Unselects text pub fn unselect(self: *TextBuffer) void { return c.Fl_Text_Buffer_unselect(self.raw()); } }; fn TextDisplayType(comptime kind: TextKind) type { return struct { const Self = @This(); // Expose methods from `inherited` structs pub usingnamespace zfltk.widget.methods(Self, RawPtr); pub usingnamespace methods(Self); const TextDisplayRawPtr = *c.Fl_Text_Display; pub const RawPtr = switch (kind) { .normal => *c.Fl_Text_Display, .editor => *c.Fl_Text_Editor, }; pub const Options = struct { x: i32 = 0, y: i32 = 0, w: i32 = 0, h: i32 = 0, label: ?[:0]const u8 = null, // Whether or not to automatically attach a TextBuffer buffer: bool = true, }; pub inline fn init(opts: Options) !*Self { const initFn = switch (kind) { .normal => c.Fl_Text_Display_new, .editor => c.Fl_Text_Editor_new, }; const label = if (opts.label != null) opts.label.?.ptr else null; if (initFn(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { var self = Self.fromRaw(ptr); if (opts.buffer) { const buf = try TextBuffer.init(); self.setBuffer(buf); } return self; } unreachable; } pub inline fn deinit(self: *Self) void { const deinitFn = switch (kind) { .normal => c.Fl_Text_Display_delete, .editor => c.Fl_Text_Editor_delete, }; deinitFn(self.raw()); app.allocator.destroy(self); } }; } fn methods(comptime Self: type) type { return struct { pub inline fn textDisplay(self: *Self) *TextDisplayType(.normal) { return @ptrCast(self); } pub inline fn buffer(self: *Self) ?*TextBuffer { if (c.Fl_Text_Display_get_buffer(self.textDisplay().raw())) |ptr| { return TextBuffer.fromRaw(ptr); } return null; } pub inline fn styleBuffer(self: *Self) ?*TextBuffer { if (c.Fl_Text_Display_get_style_buffer(self.textDisplay().raw())) |ptr| { return TextBuffer.fromRaw(ptr); } return null; } pub inline fn setBuffer(self: *Self, buf: *TextBuffer) void { c.Fl_Text_Display_set_buffer(self.textDisplay().textDisplay().raw(), buf.raw()); } pub fn setHighlightData(self: *Self, sbuf: *TextBuffer, entries: []const StyleTableEntry) void { const sz = entries.len; var colors: [28]c_uint = undefined; var fonts: [28]i32 = undefined; var fontszs: [28]i32 = undefined; var attrs: [28]c_uint = undefined; var bgcolors: [28]c_uint = undefined; var i: usize = 0; for (entries) |e| { colors[i] = @bitCast(e.color); fonts[i] = @intFromEnum(e.font); fontszs[i] = e.size; attrs[i] = 0; bgcolors[i] = 0; i += 1; } c.Fl_Text_Display_set_highlight_data(self.textDisplay().raw(), sbuf.raw(), &colors, &fonts, &fontszs, &attrs, &bgcolors, @intCast(sz)); } pub fn setTextFont(self: *Self, font: enums.Font) void { c.Fl_Text_Display_set_text_font(self.textDisplay().raw(), @intFromEnum(font)); } pub fn setTextColor(self: *Self, col: enums.Color) void { c.Fl_Text_Display_set_text_color(self.textDisplay().raw(), @intCast(col.toRgbi())); } pub fn setTextSize(self: *Self, sz: i32) void { c.Fl_Text_Display_set_text_size(self.textDisplay().raw(), sz); } pub fn scroll(self: *Self, topLineNum: i32, horizOffset: i32) void { c.Fl_Text_Display_scroll(self.textDisplay().raw(), topLineNum, horizOffset); } pub fn insert(self: *Self, text: [*c]const u8) void { c.Fl_Text_Display_insert(self.textDisplay().raw(), text); } pub fn setInsertPosition(self: *Self, newPos: u32) void { c.Fl_Text_Display_set_insert_position(self.textDisplay().raw(), newPos); } pub fn insertPosition(self: *Self) u32 { return c.Fl_Text_Display_insert_position(self.textDisplay().raw()); } pub fn countLines(self: *Self, start: u32, end: u32, is_line_start: bool) u32 { return c.Fl_Text_Display_count_lines(self.textDisplay().raw(), @intCast(start), end, @intFromBool(is_line_start)); } pub fn moveRight(self: *Self) void { _ = c.Fl_Text_Display_move_right(self.textDisplay().raw()); } pub fn moveLeft(self: *Self) void { _ = c.Fl_Text_Display_move_left(self.textDisplay().raw()); } pub fn moveUp(self: *Self) void { _ = c.Fl_Text_Display_move_up(self.textDisplay().raw()); } pub fn moveDown(self: *Self) void { _ = c.Fl_Text_Display_move_down(self.textDisplay().raw()); } pub fn showCursor(self: *Self, val: bool) void { c.Fl_Text_Display_show_cursor(self.textDisplay().raw(), @intFromBool(val)); } pub fn setCursorStyle(self: *Self, style: enums.TextCursor) void { c.Fl_Text_Display_set_cursor_style(self.textDisplay().raw(), @intFromEnum(style)); } pub fn setCursorColor(self: *Self, col: enums.Color) void { c.Fl_Text_Display_set_cursor_color(self.textDisplay().raw(), @intCast(col.toRgbi())); } pub fn setScrollbarSize(self: *Self, size: u32) void { c.Fl_Text_Display_set_scrollbar_size(self.textDisplay().raw(), size); } pub fn setScrollbarAlign(self: *Self, a: i32) void { c.Fl_Text_Display_set_scrollbar_align(self.textDisplay().raw(), a); } pub fn setLinenumberWidth(self: *Self, w: i32) void { c.Fl_Text_Display_set_linenumber_width(self.textDisplay().raw(), w); } // Text editor only methods pub fn cut(self: *TextDisplayType(.editor)) void { _ = c.Fl_Text_Editor_kf_cut(self.raw()); } pub fn paste(self: *TextDisplayType(.editor)) void { _ = c.Fl_Text_Editor_kf_paste(self.raw()); } pub fn copy(self: *TextDisplayType(.editor)) void { _ = c.Fl_Text_Editor_kf_copy(self.raw()); } }; } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/window.zig
const std = @import("std"); const zfltk = @import("zfltk.zig"); const app = zfltk.app; const c = zfltk.c; const Widget = zfltk.widget.Widget; const Group = zfltk.Group; const enums = zfltk.enums; pub const Window = struct { // Expose methods from `inherited` structs pub usingnamespace zfltk.widget.methods(Window, RawPtr); pub usingnamespace zfltk.group.methods(Window, RawPtr); pub usingnamespace methods(Window); pub const RawPtr = *c.Fl_Double_Window; const type_name = @typeName(RawPtr); const ptr_name = type_name[(std.mem.indexOf(u8, type_name, "struct_Fl_") orelse 0) + 7 .. type_name.len]; pub inline fn init(opts: Widget.Options) !*Window { const label = if (opts.label != null) opts.label.?.ptr else null; if (c.Fl_Double_Window_new(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { return @ptrCast(ptr); } unreachable; } pub inline fn deinit(self: *Window) void { c.Fl_Double_Window_delete(self.raw()); } pub fn freePosition(self: *Window) void { @field(c, ptr_name ++ "_free_position")(self.raw()); } pub fn flush(self: *Window) void { c.Fl_Double_Window_flush(self.raw()); } }; pub const GlutWindow = struct { // Expose methods from `inherited` structs pub usingnamespace zfltk.widget.methods(GlutWindow, RawPtr); pub usingnamespace zfltk.group.methods(GlutWindow, RawPtr); pub usingnamespace methods(GlutWindow); pub const RawPtr = *c.Fl_Glut_Window; pub inline fn init(opts: Widget.Options) !*GlutWindow { const label = if (opts.label != null) opts.label.?.ptr else null; if (c.Fl_Glut_Window_new(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { return @ptrCast(ptr); } unreachable; } pub inline fn deinit(self: *GlutWindow) void { c.Fl_Glut_Window_delete(self.raw()); } pub fn getProcAddress(self: *GlutWindow, s: [:0]const u8) ?*anyopaque { return c.Fl_Glut_Window_get_proc_address(self.raw(), s); } pub fn flush(self: *GlutWindow) void { c.Fl_Glut_Window_flush(self.raw()); } pub fn setMode(self: *GlutWindow, mode: i32) void { c.Fl_Glut_Window_set_mode(self.raw(), mode); } /// Returns the pixels per unit/point pub fn pixelsPerUnit(self: *GlutWindow) f32 { return c.Fl_Glut_Window_pixels_per_unit(self.raw()); } /// Gets the window's width in pixels pub fn pixelW(self: *GlutWindow) i32 { return c.Fl_Glut_Window_pixel_w(self.raw()); } /// Gets the window's height in pixels pub fn pixelH(self: *GlutWindow) i32 { return c.Fl_Glut_Window_pixel_h(self.raw()); } /// Swaps the back and front buffers pub fn swapBuffers(self: *GlutWindow) void { c.Fl_Glut_Window_swap_buffers(self.raw()); } /// Sets the projection so 0,0 is in the lower left of the window /// and each pixel is 1 unit wide/tall. pub fn ortho(self: *GlutWindow) void { c.Fl_Glut_Window_ortho(self.raw()); } pub fn makeCurrent(self: *GlutWindow) void { c.Fl_Glut_Window_make_current(self.raw()); } /// Returns whether the OpeGL context is still valid pub fn valid(self: *GlutWindow) bool { return c.Fl_Glut_Window_valid(self.raw()) != 0; } /// Mark the OpeGL context as still valid pub fn setValid(self: *GlutWindow, v: bool) void { return c.Fl_Glut_Window_set_valid(self.raw(), @intFromBool(v)); } /// Returns whether the context is valid upon creation pub fn contextValid(self: *GlutWindow) bool { return c.Fl_Glut_Window_context_valid(self.raw()) != 0; } /// Mark the context as valid upon creation pub fn setContextValid(self: *GlutWindow, v: bool) void { c.Fl_Glut_Window_set_context_valid(self.raw(), @intFromBool(v)); } /// Returns the GlContext pub fn context(self: *GlutWindow) ?*anyopaque { return c.Fl_Glut_Window_context(self.raw()); } /// Sets the GlContext pub fn setContext(self: *GlutWindow, ctx: ?*anyopaque, destroy_flag: bool) void { c.Fl_Glut_Window_set_context(self.raw(), ctx, @intFromBool(destroy_flag)); } }; fn methods(comptime Self: type) type { return struct { pub fn setSizeRange(self: *Self, min_w: u31, min_h: u31, max_w: u31, max_h: u31) void { return c.Fl_Window_size_range(@ptrCast(self.raw()), min_w, min_h, max_w, max_h); } pub fn iconize(self: *Self) void { c.Fl_Window_iconize(@ptrCast(self.raw())); } pub fn setCursor(self: *Self, cursor: enums.Cursor) void { return c.Fl_Window_set_cursor(@ptrCast(self.raw()), @intFromEnum(cursor)); } pub fn makeModal(self: *Self, val: bool) void { return c.Fl_Window_make_modal(@ptrCast(self.raw()), @intFromBool(val)); } pub fn setFullscreen(self: *Window, val: bool) void { return c.Fl_Window_fullscreen(@ptrCast(self.raw()), @intFromBool(val)); } }; } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/box.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const std = @import("std"); const Widget = @import("widget.zig").Widget; const Event = @import("enums.zig").Event; const widget = zfltk.widget; const enums = zfltk.enums; const c = zfltk.c; pub const Box = struct { const Self = @This(); pub const RawPtr = *c.Fl_Box; pub usingnamespace zfltk.widget.methods(Self, *c.Fl_Box); pub const Options = struct { x: u31 = 0, y: u31 = 0, w: u31 = 0, h: u31 = 0, label: ?[:0]const u8 = null, boxtype: enums.BoxType = .none, }; pub inline fn init(opts: Options) !*Self { const label = if (opts.label != null) opts.label.?.ptr else null; if (c.Fl_Box_new(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { if (opts.boxtype != .none) { c.Fl_Widget_set_box(@ptrCast(ptr), @intFromEnum(opts.boxtype)); } return @ptrCast(ptr); } unreachable; } pub inline fn deinit(self: *Self) void { c.Fl_Box_delete(self.raw()); app.allocator.destroy(self); } }; test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/tree.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const widget = @import("widget.zig"); const Widget = widget.Widget; const enums = @import("enums.zig"); const Event = enums.Event; const std = @import("std"); const c = zfltk.c; pub const Tree = struct { const Self = @This(); pub usingnamespace zfltk.widget.methods(Self, RawPtr); pub usingnamespace methods(Self); pub const RawPtr = *c.Fl_Tree; pub const Options = struct { x: i32 = 0, y: i32 = 0, w: u31 = 0, h: u31 = 0, label: ?[:0]const u8 = null, }; pub inline fn init(opts: Options) !*Self { const initFn = c.Fl_Tree_new; const label = if (opts.label != null) opts.label.?.ptr else null; if (initFn(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { const self = Self.fromRaw(ptr); return self; } unreachable; } pub inline fn deinit(self: *Self) void { c.Fl_Tree_delete(self.RawPtr); app.allocator.destroy(self); } }; fn methods(comptime Self: type) type { return struct { pub inline fn tree(self: *Self) *Tree { return @ptrCast(self); } }; } pub const TreeItem = struct { inner: ?*c.Fl_Tree_Item, pub fn raw(self: *const TreeItem) ?*c.Fl_Tree_Item { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Tree_Item) TreeItem { return TreeItem{ .inner = ptr, }; } pub fn fromVoidPtr(ptr: ?*anyopaque) TreeItem { return TreeItem{ .inner = @ptrCast(ptr), }; } pub fn toVoidPtr(self: *const TreeItem) ?*anyopaque { return @ptrCast(self.inner); } }; test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/group.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const Widget = zfltk.Widget; const widget = zfltk.widget; const c = zfltk.c; const std = @import("std"); const widget_methods = zfltk.widget_methods; const enums = zfltk.enums; pub const GroupPtr = ?*c.Fl_Group; pub const Group = GroupType(.normal); pub const Pack = GroupType(.pack); pub const Tabs = GroupType(.tabs); pub const Scroll = GroupType(.scroll); pub const Flex = GroupType(.flex); pub const Tile = GroupType(.tile); const GroupKind = enum { normal, pack, tabs, scroll, flex, tile, }; pub const ScrollType = enum(c_int) { /// Never show bars none = 0, /// Show vertical bar horizontal = 1, /// Show vertical bar vertical = 2, /// Show both horizontal and vertical bars both = 3, /// Always show bars always_on = 4, /// Show horizontal bar always horizontal_always = 5, /// Show vertical bar always vertical_always = 6, /// Always show both horizontal and vertical bars both_always = 7, }; fn GroupType(comptime kind: GroupKind) type { return struct { const Self = @This(); // Expose methods from `inherited` structs pub usingnamespace zfltk.widget.methods(Self, RawPtr); pub usingnamespace methods(Self, RawPtr); const GroupRawPtr = *c.Fl_Group; pub const RawPtr = switch (kind) { .normal => *c.Fl_Group, .pack => *c.Fl_Pack, .tabs => *c.Fl_Tabs, .scroll => *c.Fl_Scroll, .flex => *c.Fl_Flex, .tile => *c.Fl_Tile, }; const type_name = @typeName(RawPtr); const ptr_name = type_name[(std.mem.indexOf(u8, type_name, "struct_Fl_") orelse 0) + 7 .. type_name.len]; pub const Options = struct { x: i32 = 0, y: i32 = 0, w: u31 = 0, h: u31 = 0, spacing: u31 = 0, label: ?[:0]const u8 = null, orientation: Orientation = .vertical, pub const Orientation = enum { vertical, horizontal, }; }; pub inline fn init(opts: Options) !*Self { const initFn = @field(c, ptr_name ++ "_new"); const label = if (opts.label != null) opts.label.?.ptr else null; if (initFn(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { var self = Self.fromRaw(ptr); switch (kind) { .pack, .flex => { self.setSpacing(opts.spacing); if (opts.orientation == .horizontal) { c.Fl_Widget_set_type(self.widget().raw(), 1); } }, else => {}, } return self; } unreachable; } }; } pub fn methods(comptime Self: type, comptime RawPtr: type) type { const type_name = @typeName(RawPtr); const ptr_name = type_name[(std.mem.indexOf(u8, type_name, "struct_Fl_") orelse 0) + 7 .. type_name.len]; return struct { pub inline fn group(self: *Self) *GroupType(.normal) { return @ptrCast(self); } pub inline fn current() Self { if (c.Fl_Group_current()) |grp| { return Self.fromRaw(grp); } unreachable; } pub fn begin(self: *Self) void { @field(c, ptr_name ++ "_begin")(self.raw()); } pub fn end(self: *Self) void { @field(c, ptr_name ++ "_end")(self.raw()); } pub fn find(self: *Self, wid: *Widget) u32 { return @intCast(@field(c, ptr_name ++ "_find")(self.raw(), wid.raw())); } pub fn add(self: *Self, widgets: anytype) void { const T = @TypeOf(widgets); const type_info = @typeInfo(T); if (type_info != .Struct) { @compileError("expected tuple or struct argument, found " ++ @typeName(T)); } inline for (type_info.Struct.fields) |w| { const wid = @as(w.type, @field(widgets, w.name)); if (!comptime zfltk.isWidget(w.type)) { @compileError("expected FLTK widget, found " ++ @typeName(w.type)); } @field(c, ptr_name ++ "_add")(self.raw(), wid.widget().raw()); } } pub fn insert(self: *Self, wid: anytype, index: u32) void { const T = @TypeOf(wid); if (!comptime zfltk.isWidget(T)) { @compileError("expected FLTK widget, found " ++ @typeName(T)); } return @field(c, ptr_name ++ "_insert")(self.raw(), wid.raw(), index); } pub fn remove(self: *Self, wid: anytype) void { const T = @TypeOf(wid); if (!comptime zfltk.isWidget(T)) { @compileError("expected FLTK widget, found " ++ @typeName(T)); } return @field(c, ptr_name ++ "_remove")(self.raw(), wid.raw()); } pub fn resizable(self: *Self, wid: anytype) void { const T = @TypeOf(wid); if (!comptime zfltk.isWidget(T)) { @compileError("expected FLTK widget, found " ++ @typeName(T)); } return @field(c, ptr_name ++ "_resizable")(self.raw(), wid.widget().raw()); } pub fn clear(self: *Self) void { @field(c, ptr_name ++ "_clear")(self.raw()); } pub fn children(self: *Self) u31 { return @intCast(@field(c, ptr_name ++ "_children")(self.raw())); } pub fn child(self: *Self, idx: u31) ?*Widget { if (@field(c, ptr_name ++ "_child")(self.raw(), idx)) |ptr| { return Widget.fromRaw(ptr); } return null; } pub fn spacing(self: *Self) u31 { const spacingFn = switch (Self) { GroupType(.flex) => c.Fl_Flex_pad, GroupType(.pack) => c.Fl_Pack_spacing, else => @compileError("method `spacing` only usable with flex and pack groups"), }; return @intCast(spacingFn(self.raw())); } pub fn setSpacing(self: *Self, sz: u31) void { const spacingFn = switch (Self) { GroupType(.flex) => c.Fl_Flex_set_pad, GroupType(.pack) => c.Fl_Pack_set_spacing, else => @compileError("method `setSpacing` only usable with flex and pack groups"), }; spacingFn(self.raw(), sz); } pub inline fn fixed(self: *Self, wid: anytype, sz: i32) void { if (Self != GroupType(.flex)) { @compileError("method `fixed` only usable with flex groups"); } const T = @TypeOf(wid); if (!comptime zfltk.isWidget(T)) { @compileError("expected FLTK widget, found " ++ @typeName(T)); } c.Fl_Flex_set_size(self.raw(), wid.widget().raw(), sz); } pub fn setMargin(self: *Self, sz: u31) void { const marginFn = switch (Self) { GroupType(.flex) => c.Fl_Flex_set_margin, else => @compileError("method `setMargin` only usable with flex groups"), }; marginFn(self.raw(), @intCast(sz)); } pub fn setMargins(self: *Self, left: u31, top: u31, right: u31, bottom: u31) void { const marginsFn = switch (Self) { GroupType(.flex) => c.Fl_Flex_set_margins, else => @compileError("method `setMargin` only usable with flex groups"), }; marginsFn(self.raw(), @intCast(left), @intCast(top), @intCast(right), @intCast(bottom)); } pub inline fn setScrollbar(self: *Self, scrollbar: ScrollType) void { if (Self != GroupType(.scroll)) { @compileError("method `setScrollbar` only usable with scroll groups"); } self.setKind(ScrollType, scrollbar); } pub inline fn setScrollbarSize(self: *Self, size: u31) void { if (Self != GroupType(.scroll)) { @compileError("method `setScrollbarSize` only usable with scroll groups"); } c.Fl_Scroll_set_scrollbar_size(self.raw(), size); } }; } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/image.zig
// TODO: update to new API const zfltk = @import("zfltk.zig"); const c = zfltk.c; const std = @import("std"); // TODO: Add more error types pub const ImageError = error{ NoImage, FileAccess, InvalidFormat, MemoryAccess, Error, }; // Converts a C error code to a Zig error enum inline fn ImageErrorFromInt(err: c_int) ImageError!void { return switch (err) { 0 => {}, -1 => ImageError.NoImage, -2 => ImageError.FileAccess, -3 => ImageError.InvalidFormat, -4 => ImageError.MemoryAccess, else => ImageError.Error, }; } pub const Image = struct { inner: RawPtr, pub const RawPtr = *c.Fl_Image; pub const RawImageOptions = struct { data: []const u8, w: u31, h: u31, depth: enum(c_int) { grayscale = 0, grayscale_alpha, rgb, rgba, }, line_data: u31 = 0, }; pub const Kind = enum { shared, svg, jpeg, bmp, raw, png, gif, tiled, }; pub fn load(comptime kind: Kind, path: [:0]const u8) !Image { const loadFn = switch (kind) { .shared => c.Fl_Shared_Image_get, .svg => c.Fl_SVG_Image_new, .jpeg => c.Fl_JPEG_Image_new, .bmp => c.Fl_BMP_Image_new, .png => c.Fl_PNG_Image_new, .gif => c.Fl_GIF_Image_new, else => @compileError("this image type cannot be loaded from file"), }; const failFn = switch (kind) { .shared => c.Fl_Shared_Image_fail, .svg => c.Fl_SVG_Image_fail, .jpeg => c.Fl_JPEG_Image_fail, .bmp => c.Fl_BMP_Image_fail, .png => c.Fl_PNG_Image_fail, .gif => c.Fl_GIF_Image_fail, else => unreachable, }; switch (kind) { .shared => { if (loadFn(path.ptr, 0, 0)) |ptr| { try ImageErrorFromInt(failFn(ptr)); return Image.fromRaw(@ptrCast(ptr)); } }, else => { if (loadFn(path.ptr)) |ptr| { try ImageErrorFromInt(failFn(ptr)); return Image.fromRaw(@ptrCast(ptr)); } }, } unreachable; } pub inline fn init(comptime kind: Kind, data: []const u8) !Image { const loadFn = switch (kind) { .svg => c.Fl_SVG_Image_from, .jpeg => c.Fl_JPEG_Image_from, .bmp => c.Fl_BMP_Image_from, .png => c.Fl_PNG_Image_from, .gif => c.Fl_GIF_Image_from, .raw => @compileError("use `fromRawData` instead"), else => @compileError("this image type cannot be loaded from data"), }; const failFn = switch (kind) { .svg => c.Fl_SVG_Image_fail, .jpeg => c.Fl_JPEG_Image_fail, .bmp => c.Fl_BMP_Image_fail, .png => c.Fl_PNG_Image_fail, .gif => c.Fl_GIF_Image_fail, else => unreachable, }; // JPEG and SVG currently do not use a length arg in cfltk switch (kind) { .jpeg, .svg => { if (loadFn(data.ptr)) |ptr| { try ImageErrorFromInt(failFn(ptr)); return Image.fromRaw(@ptrCast(ptr)); } }, else => { if (loadFn(data.ptr, @intCast(data.len))) |ptr| { try ImageErrorFromInt(failFn(ptr)); return Image.fromRaw(@ptrCast(ptr)); } }, } unreachable; } /// Only used on raw image types (grayscale, RGB, RGBA) pub inline fn fromRawData(opts: RawImageOptions) Image { // TODO error handling if (c.Fl_RGB_Image_new(opts.data.ptr, opts.w, opts.h, @intFromEnum(opts.depth), opts.line_data)) |ptr| { try ImageErrorFromInt(c.Fl_RGB_Image_fail(ptr)); return Image.fromRaw(ptr); } unreachable; } pub inline fn scale(self: *Image, width: u31, height: u31, proportional: bool, can_expand: bool) void { c.Fl_Image_scale(@ptrCast(self.inner), width, height, @intFromBool(proportional), @intFromBool(can_expand)); } pub inline fn raw(self: *Image) RawPtr { return self.inner; } pub inline fn fromRaw(ptr: RawPtr) Image { return .{ .inner = ptr }; } pub inline fn fromVoidPtr(ptr: *anyopaque) Image { return Image.fromRaw(@ptrCast(ptr)); } pub inline fn toVoidPtr(self: *Image) ?*anyopaque { return @ptrCast(self.inner); } pub inline fn deinit(self: *Image) void { c.Fl_Image_delete(@ptrCast(self.inner)); } /// Returns a tiled version of the input image pub inline fn tile(self: *Image, _w: u31, _h: u31) Image { if (c.Fl_Tiled_Image_new(self.inner, _w, _h)) |ptr| { return Image.fromRaw(@ptrCast(ptr)); } unreachable; } pub inline fn copy(self: *Image) Image { if (c.Fl_Image_copy(self.inner)) |ptr| { return Image.fromRaw(ptr); } unreachable; } pub fn draw(self: *Image, arg2: u31, arg3: u31, arg4: u31, arg5: u31) void { return c.Fl_Image_draw(self.inner, arg2, arg3, arg4, arg5); } pub fn w(self: *Image) u31 { return @intCast(c.Fl_Image_width(self.inner)); } pub fn h(self: *Image) u31 { return @intCast(c.Fl_Image_height(self.inner)); } pub fn count(self: *Image) u31 { return @intCast(c.Fl_Image_count(self.inner)); } pub fn dataW(self: *Image) u31 { return @intCast(c.Fl_Image_data_w(self.inner)); } pub fn dataH(self: *Image) u31 { return @intCast(c.Fl_Image_data_h(self.inner)); } pub fn depth(self: *Image) u31 { return @intCast(c.Fl_Image_d(self.inner)); } pub fn ld(self: *Image) u31 { return @intCast(c.Fl_Image_ld(self.inner)); } }; test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/enums.zig
// TODO: rename enums to snake_case to match Zig style guide // <https://github.com/ziglang/zig/issues/2101> const std = @import("std"); const draw = @import("draw.zig"); const builtin = @import("builtin"); const native_endian = builtin.cpu.arch.endian(); const c = @cImport({ @cInclude("cfl.h"); }); // DO NOT add more elements to this stuct. // Using 4 `u8`s in a packed struct makes an identical memory layout to a u32 // (the color format FLTK uses) so this trick can be used to make Colors both // efficient and easy to use pub const Color = switch (native_endian) { .big => packed struct { r: u8 = 0, g: u8 = 0, b: u8 = 0, i: u8 = 0, pub usingnamespace methods; }, .little => packed struct { i: u8 = 0, b: u8 = 0, g: u8 = 0, r: u8 = 0, pub usingnamespace methods; }, }; pub const methods = packed struct { pub const Names = enum(u8) { foreground = 0, background2 = 7, inactive = 8, selection = 15, gray0 = 32, dark3 = 39, dark2 = 45, dark1 = 47, background = 49, light1 = 50, light2 = 52, light3 = 54, black = 56, red = 88, green = 63, yellow = 95, blue = 216, magenta = 248, cyan = 223, dark_red = 72, dark_green = 60, dark_yellow = 76, dark_blue = 136, dark_magenta = 152, dark_cyan = 140, white = 255, }; pub fn fromName(name: Names) Color { return Color.fromIndex(@intFromEnum(name)); } pub fn fromIndex(idx: u8) Color { var col = Color{ .r = undefined, .g = undefined, .b = undefined, .i = idx, }; c.Fl_get_color_rgb(idx, &col.r, &col.g, &col.b); return col; } pub fn mapSelection(col: Color) Color { return draw.showColorMap(col); } pub fn fromRgb(r: u8, g: u8, b: u8) Color { // This is a special exception as FLTK's `0` index is the // foreground for some reason. Eg: if you override the foreground // color then try to set another color to black, it would set it to // the new foreground color if (r | g | b == 0) { return Color.fromName(.black); } return Color{ .r = r, .g = g, .b = b, .i = 0, }; } pub fn toRgbi(col: Color) u32 { // Drop the RGB bytes if color is indexed // This is because colors where both the index byte and color u24 are // non-0 are reserved if (col.i != 0) { return col.i; } return @bitCast(col); } pub fn fromRgbi(val: u32) Color { var col: Color = @bitCast(val); // If the color is indexed, set find out what the R, G and B values // are and set the struct's fields if (col.i != 0) { c.Fl_get_color_rgb(col.i, &col.r, &col.g, &col.b); } return col; } pub fn toHex(col: Color) u24 { const temp: u32 = @bitCast(col); return @truncate(temp >> 8); } pub fn fromHex(val: u24) Color { if (val == 0) { return Color.fromName(.black); } return @bitCast(std.mem.nativeToLittle(u32, @as(u32, val) << 8)); } // Seems really redundant and the FLTK docs don't even appear to document // how much a color gets darkened/lightened // pub fn darker(col: Color) Color { // return Color.fromRgbi(c.Fl_darker(col.toRgbi())); // } pub fn darken(col: Color, val: u8) Color { var new_col = col; new_col.r -|= val; new_col.g -|= val; new_col.b -|= val; return new_col; } pub fn lighten(col: Color, val: u8) Color { var new_col = col; new_col.r +|= val; new_col.g +|= val; new_col.b +|= val; return new_col; } }; pub const Align = struct { pub const center = 0; pub const top = 1; pub const bottom = 2; pub const left = 4; pub const right = 8; pub const inside = 16; pub const text_over_image = 20; pub const clip = 40; pub const wrap = 80; pub const image_next_to_text = 100; pub const text_next_to_image = 120; pub const image_backdrop = 200; pub const top_left = 1 | 4; pub const top_right = 1 | 8; pub const bottom_left = 2 | 4; pub const bottom_right = 2 | 8; pub const left_top = 7; pub const right_top = 11; pub const left_bottom = 13; pub const right_bottom = 14; pub const position_mask = 15; pub const image_mask = 320; }; pub const LabelType = enum(i32) { normal = 0, none, shadow, engraved, embossed, multi, icon, image, free, }; pub const BoxType = enum(c_int) { none = 0, flat, up, down, up_frame, down_frame, thin_up, thin_down, thin_up_frame, thin_down_frame, engraved, embossed, engraved_frame, embossed_frame, border, shadow, border_frame, shadow_frame, rounded, rshadow, rounded_frame, rflat, round_up, round_down, diamand_up, diamond_down, oval, oshadow, oval_frame, oflat, plastic_up, plastic_down, plastic_up_frame, plastic_down_frame, plastic_thin_up, plastic_thin_down, plastic_round_up, plsatic_round_down, gtk_up, gtk_down, gtk_up_frame, gtk_down_frame, gtk_thin_up, gtk_thin_down_box, gtk_thin_up_frame, gtk_thin_down_frame, gtk_round_up_frame, gtk_round_down_frame, gleam_up_box, gleam_down_box, gleam_up_frame, gleam_down_frame, gleam_thin_up_box, gleam_thin_down_box, gleam_round_up_box, gleam_round_down_box, free, }; pub const BrowserScrollbar = enum(i32) { none = 0, horizontal = 1, vertical = 2, both = 3, always = 4, horizontal_always = 5, vertical_always = 6, both_always = 7, }; pub const Event = enum(c_int) { none = 0, push, release, enter, leave, drag, focus, unfocus, key_down, key_up, close, move, shortcut, deactivate, activate, hide, show, paste, selection_clear, mouse_wheel, dnd_enter, dnd_drag, dnd_leave, dnd_release, screen_config_changed, fullscreen, zoom_gesture, zoom_event, FILLER, // FLTK sends `28` as an event occasionally and this doesn't appear // to be documented anywhere. This is only included to keep // programs from crashing from a non-existent enum }; pub const Font = enum(c_int) { helvetica = 0, helvetica_bold, helvetica_italic, helvetica_bold_italic, courier, courier_bold, courier_italic, courier_bold_italic, times, times_bold, times_italic, times_bold_italic, symbol, screen, screen_bold, zapfdingbats, }; pub const Key = struct { pub const None = 0; pub const Button = 0xfee8; pub const BackSpace = 0xff08; pub const Tab = 0xff09; pub const IsoKey = 0xff0c; pub const Enter = 0xff0d; pub const Pause = 0xff13; pub const ScrollLock = 0xff14; pub const Escape = 0xff1b; pub const Kana = 0xff2e; pub const Eisu = 0xff2f; pub const Yen = 0xff30; pub const JISUnderscore = 0xff31; pub const Home = 0xff50; pub const Left = 0xff51; pub const Up = 0xff52; pub const Right = 0xff53; pub const Down = 0xff54; pub const PageUp = 0xff55; pub const PageDown = 0xff56; pub const End = 0xff57; pub const Print = 0xff61; pub const Insert = 0xff63; pub const Menu = 0xff67; pub const Help = 0xff68; pub const NumLock = 0xff7f; pub const KP = 0xff80; pub const KPEnter = 0xff8d; pub const KPLast = 0xffbd; pub const FLast = 0xffe0; pub const ShiftL = 0xffe1; pub const ShiftR = 0xffe2; pub const ControlL = 0xffe3; pub const ControlR = 0xffe4; pub const CapsLock = 0xffe5; pub const MetaL = 0xffe7; pub const MetaR = 0xffe8; pub const AltL = 0xffe9; pub const AltR = 0xffea; pub const Delete = 0xffff; // TODO: add `fromName` and related methods }; pub const Shortcut = struct { pub const None = 0; pub const Shift = 0x00010000; pub const CapsLock = 0x00020000; pub const Ctrl = 0x00040000; pub const Alt = 0x00080000; }; pub const CallbackTrigger = struct { pub const Never = 0; pub const Changed = 1; pub const NotChanged = 2; pub const Release = 4; pub const ReleaseAlways = 6; pub const EnterKey = 8; pub const EnterKeyAlways = 10; pub const EnterKeyChanged = 11; }; pub const Cursor = enum(i32) { default = 0, arrow = 35, cross = 66, wait = 76, insert = 77, hand = 31, help = 47, move = 27, ns = 78, we = 79, nwse = 80, nesw = 81, n = 70, ne = 69, e = 49, se = 8, s = 9, sw = 7, w = 36, nw = 68, none = 255, }; pub const TextCursor = enum(u8) { normal, caret, dim, block, heavy, simple, }; pub const Mode = struct { /// Rgb color (not indexed) pub const rgb = 0; /// Single buffered pub const single = 0; /// Indexed mode pub const index = 1; /// Double buffered pub const double = 2; /// Accumulation buffer pub const accum = 4; /// Alpha channel in color pub const alpha = 8; /// Depth buffer pub const depth = 16; /// Stencil buffer pub const stencil = 32; /// Rgb8 color with at least 8 bits of each color pub const rgb8 = 64; /// MultiSample anti-aliasing pub const multi_sample = 128; /// Stereoscopic rendering pub const stereo = 256; /// Fake single buffered windows using double-buffer pub const fake_single = 512; /// Use OpenGL version 3.0 or more pub const opengl3 = 1024; }; test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/menu.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const widget = @import("widget.zig"); const Widget = widget.Widget; const enums = @import("enums.zig"); const Event = enums.Event; const std = @import("std"); const c = zfltk.c; pub const MenuFlag = enum(i32) { /// normal item normal = 0, /// inactive item inactive = 1, /// item is a checkbox toggle (shows checkbox for on/off state) toggle = 2, /// the on/off state for checkbox/radio buttons (if set, state is 'on') value = 4, /// item is a radio button radio = 8, /// invisible item invisible = 0x10, /// indicates user_data() is a pointer to another menu array (unused with rust) submenu_pointer = 0x20, /// menu item is a submenu submenu = 0x40, /// menu divider menu_divider = 0x80, /// horizontal menu (actually reserved for future use) menu_horizontal = 0x100, }; pub const MenuBar = MenuType(.menu_bar); pub const SysMenuBar = MenuType(.sys_menu_bar); pub const Choice = MenuType(.choice); const MenuKind = enum { menu_bar, sys_menu_bar, choice, }; fn MenuType(comptime kind: MenuKind) type { return struct { const Self = @This(); pub usingnamespace zfltk.widget.methods(Self, RawPtr); pub usingnamespace methods(Self, RawPtr); pub const RawPtr = switch (kind) { .menu_bar => *c.Fl_Menu_Bar, .choice => *c.Fl_Choice, .sys_menu_bar => *c.Fl_Sys_Menu_Bar, }; const type_name = @typeName(RawPtr); const ptr_name = type_name[(std.mem.indexOf(u8, type_name, "struct_Fl_") orelse 0) + 7 .. type_name.len]; pub const Options = struct { x: i32 = 0, y: i32 = 0, w: u31 = 0, h: u31 = 0, label: ?[:0]const u8 = null, }; pub inline fn init(opts: Options) !*Self { const initFn = @field(c, ptr_name ++ "_new"); const label = if (opts.label != null) opts.label.?.ptr else null; if (initFn(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { const self = Self.fromRaw(ptr); return self; } unreachable; } pub inline fn deinit(self: *Self) void { const deinitFn = @field(c, ptr_name ++ "_delete"); deinitFn(self.raw()); app.allocator.destroy(self); } }; } fn methods(comptime Self: type, comptime RawPtr: type) type { const type_name = @typeName(RawPtr); const ptr_name = type_name[(std.mem.indexOf(u8, type_name, "struct_Fl_") orelse 0) + 7 .. type_name.len]; return struct { pub inline fn menu(self: *Self) *MenuType(.menu_bar) { return @ptrCast(self); } pub fn add(self: *Self, name: [*c]const u8, shortcut: i32, flag: MenuFlag, f: *const fn (w: *Self) void) void { _ = @field(c, ptr_name ++ "_add")(self.raw(), name, shortcut, &widget.zfltk_cb_handler, @ptrFromInt(@intFromPtr(f)), @intFromEnum(flag)); } pub fn addEx(self: *Self, name: [*c]const u8, shortcut: i32, flag: MenuFlag, f: *const fn (w: *Self, data: ?*anyopaque) void, data: ?*anyopaque) void { var container = app.allocator.alloc(usize, 2) catch unreachable; container[0] = @intFromPtr(f); container[1] = @intFromPtr(data); _ = @field(c, ptr_name ++ "_add")(self.raw(), name, shortcut, widget.zfltk_cb_handler_ex, @ptrCast(container.ptr), @intFromEnum(flag)); } pub fn insert(self: *Self, idx: u32, name: [*c]const u8, shortcut: i32, flag: MenuFlag, f: *const fn (w: *Self) void) void { _ = @field(c, ptr_name ++ "_insert")(self.raw(), @intCast(idx), name, shortcut, &widget.zfltk_cb_handler, @ptrFromInt(@intFromPtr(f)), @intFromEnum(flag)); } pub fn addEmit(self: *Self, name: [*c]const u8, shortcut: i32, flag: MenuFlag, comptime T: type, msg: T) void { _ = @field(c, ptr_name ++ "_add")(self.raw(), name, shortcut, widget.shim, @ptrFromInt(@intFromEnum(msg)), @intFromEnum(flag)); } pub fn insertEmit(self: *Self, idx: u32, name: [*c]const u8, shortcut: i32, flag: MenuFlag, comptime T: type, msg: T) void { _ = @field(c, ptr_name ++ "_insert")(self.raw(), @intCast(idx), name, shortcut, widget.shim, @as(usize, @bitCast(msg)), @intFromEnum(flag)); } pub fn remove(self: *Self, idx: i32) void { _ = @field(c, ptr_name ++ "_remove")(self.raw(), @intCast(idx)); } pub fn findItem(self: *Self, path: [*c]const u8) MenuItem { return MenuItem{ .inner = @field(c, ptr_name ++ "_get_item")(self.raw(), path) }; } pub fn clear(self: *Self) void { @field(c, ptr_name ++ "_clear")(self.raw()); } pub fn setTextFont(self: *Self, font: enums.Font) void { @field(c, ptr_name ++ "_set_text_font")(self.raw(), @intFromEnum(font)); } pub fn setTextColor(self: *Self, col: enums.Color) void { @field(c, ptr_name ++ "_set_text_color")(self.raw(), @intCast(col.toRgbi())); } pub fn setTextSize(self: *Self, sz: i32) void { @field(c, ptr_name ++ "_set_text_size")(self.raw(), @intCast(sz)); } }; } pub const MenuItem = struct { inner: ?*c.Fl_Menu_Item, pub fn setCallback(self: *MenuItem, comptime cb: fn (w: ?*c.Fl_Widget, data: ?*anyopaque) callconv(.C) void, data: ?*anyopaque) void { c.Fl_Menu_Item_set_callback(self.inner, cb, data); } pub fn setLabel(self: *MenuItem, str: [*c]const u8) void { c.Fl_Menu_Item_set_label(self.inner, str); } pub fn labelColor(self: *MenuItem) enums.Color { return enums.Color.fromRgbi(c.Fl_Menu_Item_label_color(self.inner)); } pub fn setLabelColor(self: *MenuItem, col: enums.Color) void { c.Fl_Menu_Item_set_label_color(self.inner, @intCast(col.toRgbi())); } pub fn labelFont(self: *MenuItem) enums.Font { return @enumFromInt(c.Fl_Menu_Item_label_font(self.inner)); } pub fn setLabelFont(self: *MenuItem, font: enums.Font) void { c.Fl_Menu_Item_set_label_font(self.inner, @intFromEnum(font)); } pub fn labelSize(self: *MenuItem) i32 { return c.Fl_Menu_Item_label_size(self.inner); } pub fn setLabelSize(self: *MenuItem, sz: i32) void { c.Fl_Menu_Item_set_label_size(self.inner, @intCast(sz)); } pub fn show(self: *MenuItem) void { c.Fl_Menu_Item_show(self.inner); } pub fn hide(self: *MenuItem) void { c.Fl_Menu_Item_hide(self.inner); } }; test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/table.zig
const zfltk = @import("zfltk.zig"); const app = zfltk.app; const widget = @import("widget.zig"); const Widget = widget.Widget; const enums = @import("enums.zig"); const Event = enums.Event; const std = @import("std"); const c = zfltk.c; const TableKind = enum { table, table_row, }; pub const Table = TableType(.table); pub const TableRow = TableType(.table_row); fn TableType(comptime kind: TableKind) type { return struct { const Self = @This(); pub usingnamespace zfltk.widget.methods(Self, RawPtr); pub usingnamespace methods(Self); pub const RawPtr = switch (kind) { .table => *c.Fl_Table, .table_row => *c.Fl_Table_Row, }; pub const Options = struct { x: i32 = 0, y: i32 = 0, w: u31 = 0, h: u31 = 0, label: ?[:0]const u8 = null, }; pub inline fn init(opts: Options) !*Self { const initFn = switch (kind) { .table => c.Fl_Table_new, .table_row => c.Fl_Table_Row_new, }; const label = if (opts.label != null) opts.label.?.ptr else null; if (initFn(opts.x, opts.y, opts.w, opts.h, label)) |ptr| { const self = Self.fromRaw(ptr); return self; } unreachable; } pub inline fn deinit(self: *Self) void { const deinitFn = switch (kind) { .table => c.Fl_Table_delete, .table_row => c.Fl_Table_Row_delete, }; deinitFn(self.raw()); app.allocator.destroy(self); } }; } fn methods(comptime Self: type) type { return struct { pub inline fn table(self: *Self) *TableType(.table) { return @ptrCast(self); } }; } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/src/zfltk.zig
const std = @import("std"); pub const app = @import("app.zig"); pub const image = @import("image.zig"); pub const widget = @import("widget.zig"); pub const group = @import("group.zig"); pub const window = @import("window.zig"); pub const button = @import("button.zig"); pub const box = @import("box.zig"); pub const enums = @import("enums.zig"); pub const input = @import("input.zig"); pub const output = @import("output.zig"); pub const menu = @import("menu.zig"); pub const text = @import("text.zig"); pub const dialog = @import("dialog.zig"); pub const valuator = @import("valuator.zig"); pub const browser = @import("browser.zig"); pub const table = @import("table.zig"); pub const tree = @import("tree.zig"); pub const draw = @import("draw.zig"); const Widget = widget.Widget; pub const c = @cImport({ @cInclude("cfl.h"); @cInclude("cfl_widget.h"); @cInclude("cfl_box.h"); @cInclude("cfl_button.h"); @cInclude("cfl_window.h"); @cInclude("cfl_browser.h"); @cInclude("cfl_menu.h"); @cInclude("cfl_input.h"); @cInclude("cfl_text.h"); @cInclude("cfl_image.h"); @cInclude("cfl_enums.h"); @cInclude("cfl_dialog.h"); @cInclude("cfl_group.h"); @cInclude("cfl_draw.h"); @cInclude("cfl_table.h"); @cInclude("cfl_valuator.h"); @cInclude("cfl_tree.h"); }); pub fn widgetCast(comptime T: type, wid: anytype) T { return @ptrCast(@alignCast(wid)); } // TODO: improve helper function // currently can get it sorta working if `comptime T: type` is used as a param // but I currently can't figure out a way to verify the return value of // `x.widget()` is equal to type `Widget`. This would make any type with a decl // of the name `widget` pass the test, which is suboptimal pub fn isWidget(comptime T: type) bool { if (T == *Widget) return true; const tfo = @typeInfo(T); if (tfo != .Pointer) return false; const Child = tfo.Pointer.child; if (!@hasDecl(Child, "widget")) { return false; } return true; } test "all" { @import("std").testing.refAllDeclsRecursive(@This()); }
0
repos/zfltk
repos/zfltk/examples/flex.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const Window = zfltk.window.Window; const Box = zfltk.box.Box; const Button = zfltk.button.Button; const Flex = zfltk.group.Flex; const Color = zfltk.enums.Color; pub fn main() !void { try app.init(); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Hello", }); var flex = try Flex.init(.{ .w = 400, .h = 300, // The orientation is vertical by default so this isn't necessary to // set; this is just for reference .orientation = .vertical, .spacing = 6, }); win.resizable(flex); var btn = try Button.init(.{ .h = 48, .label = "Button", }); // This demonstrates how you can add inline widgets which have no purpose // besides aesthetics. This could be useful for spacers and whatnot flex.add(.{ try Box.init(.{ .boxtype = .down }), btn, try Box.init(.{ .boxtype = .down }), }); flex.fixed(btn, btn.h()); // Flex has its own `end` method which recalculates layouts but the API // remains consistent by utilizing Zig's comptime flex.end(); win.end(); win.show(); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/capi.zig
const c = @cImport({ @cInclude("cfl.h"); // Fl_init_all, Fl_run @cInclude("cfl_enums.h"); // Fl_Color_* @cInclude("cfl_image.h"); // Fl_register_images @cInclude("cfl_button.h"); // Fl_Button @cInclude("cfl_box.h"); // Fl_Box @cInclude("cfl_window.h"); // Fl_Window }); // fltk initizialization of optional functionalities pub fn fltkInit() void { c.Fl_init_all(); // inits all styles, if needed c.Fl_register_images(); // register image types supported by fltk, if needed _ = c.Fl_lock(); // enable multithreading, if needed } // Button callback pub fn butCb(w: ?*c.Fl_Widget, data: ?*anyopaque) callconv(.C) void { c.Fl_Box_set_label(@ptrCast(data), "Hello World!"); c.Fl_Button_set_color(@ptrCast(w), c.Fl_Color_Cyan); } pub fn main() !void { fltkInit(); _ = c.Fl_set_scheme("gtk+"); const win = c.Fl_Window_new(100, 100, 400, 300, "Hello"); const but = c.Fl_Button_new(160, 220, 80, 40, "Click me!"); const box = c.Fl_Box_new(10, 10, 380, 180, ""); c.Fl_Box_set_box(box, c.Fl_BoxType_UpBox); c.Fl_Box_set_label_size(box, 18); c.Fl_Box_set_label_font(box, c.Fl_Font_Courier); c.Fl_Window_end(win); c.Fl_Window_show(win); c.Fl_Button_set_callback(but, butCb, box); _ = c.Fl_run(); }
0
repos/zfltk
repos/zfltk/examples/customwidget.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const draw = zfltk.draw; const Window = zfltk.window.Window; const Widget = zfltk.widget.Widget; const Button = zfltk.button.Button; const Box = zfltk.box.Box; const enums = zfltk.enums; const Color = enums.Color; const Event = enums.Event; const Align = enums.Align; const std = @import("std"); pub fn main() !void { try app.init(); app.setScheme(.oxy); app.setVisibleFocus(false); var win = try Window.init(.{ .w = 400, .h = 284, .label = "Custom widget example", }); var sw1 = try Switch.init(.{ .x = 10, .y = 200, .w = 380, .label = "Very important feature", }); var sw2 = try Switch.init(.{ .x = 10, .y = 242, .w = 380, .h = 32, .label = "Enable animation for the first switch", }); var box = try Box.init(.{ .x = 10, .y = 10, .w = 380, .h = 180, .boxtype = .up, .label = "Off", }); box.setLabelFont(.courier); box.setLabelSize(24); sw1.setCallbackEx(switch1Cb, box); sw1.widget().setColor(Color.fromName(.cyan)); sw2.setValue(true); sw2.setCallbackEx(switch2Cb, sw1); //_ = sw2; win.end(); win.show(); try app.run(); } fn switch1Cb(sw: *Switch, data: ?*anyopaque) void { var box = Box.fromRaw(data.?); const str = if (sw.value()) "On" else "Off"; box.setLabel(str); } fn switch2Cb(sw2: *Switch, data: ?*anyopaque) void { var sw1 = Switch.fromVoidPtr(data.?); const color = if (sw2.value()) Color.fromName(.cyan) else Color.fromName(.background); sw1.widget().setColor(color); sw1.setAnimation(sw2.value()); } const Switch = struct { box1: *Box, box2: *Box, label: *Box, on: bool, opts: Options, animated: bool, callback_data: ?*anyopaque, callback: union(enum) { normal: ?*const fn (*Switch) void, extended: ?*const fn (*Switch, ?*anyopaque) void, }, pub const Options = struct { x: u31 = 0, y: u31 = 0, w: u31 = 64, h: u31 = 32, label: ?[:0]const u8 = null, }; fn drawBox(x1: i32, y1: i32, x2: i32, y2: i32, col: Color) callconv(.C) void { draw.box(.down, x1 + 4, y1 + 4, x2 - 12, y2 - 8, col); } fn drawBox2(x1: i32, y1: i32, x2: i32, y2: i32, col: Color) callconv(.C) void { draw.box(.up, x1, y1, x2, y2, col); draw.box(.down, x1 + 4, y1 + 4, x2 - 8, y2 - 8, col); } pub fn init(opts: Options) !*Switch { var self = try app.allocator.create(Switch); self.opts = opts; self.animated = true; self.callback = .{ .normal = null }; app.setBoxTypeEx(.free, drawBox, 4, 4, -8, -8); //app.setBoxTypeEx(.border_frame, drawBox2, 4, 4, -8, -8); // draw.box(.free, 0, 0, self.opts.w, self.opts.h, Color.fromName(.red)); self.box2 = try Box.init(.{ .x = opts.x, .y = opts.y, .w = (opts.h * 2) + 4, .h = opts.h, .boxtype = .free, }); self.box1 = try Box.init(.{ .x = opts.x, .y = opts.y, .w = opts.h, .h = opts.h, .boxtype = .up, }); self.label = try Box.init(.{ .x = opts.x + (opts.h * 2) + 4, .y = opts.y, .w = opts.w - (opts.h * 2), .h = opts.h, .label = opts.label, //.boxtype = .up, }); self.label.setLabelAlign(Align.left | Align.inside); self.box1.setEventHandlerEx(clickEventHandle, self); self.box2.setEventHandlerEx(clickEventHandle, self); self.label.setEventHandlerEx(clickEventHandle, self); return self; } pub fn deinit(self: *Switch) void { self.box1.deinit(); self.box2.deinit(); self.label.deinit(); app.allocator.destroy(self); } fn clickEventHandle(_: *Box, ev: Event, data: ?*anyopaque) bool { var self = Switch.fromVoidPtr(data.?); // var e = self.box1.x(); // self.box1.parent().redraw(); // _ = e; // self.box1.resize(0, 0, 200, 200); switch (ev) { .push => { const h = self.box1.h(); const x = if (self.on) self.opts.x + h else self.opts.x; const y = self.box1.y(); const w = self.box1.w(); // const w2 = self.options.w; const new_x = if (self.on) x - (h) else x + (h); self.on = !self.on; // Activate callback switch (self.callback) { .normal => { if (self.callback.normal) |cb| cb(self); }, .extended => { if (self.callback.extended) |cb| cb(self, self.callback_data); }, } // Sliding animation if (self.animated) { if (self.on) { while (self.box1.x() < new_x) { var x1 = self.box1.x() +| h / 6; if (x1 > new_x) x1 = new_x; // One frame at 60fps (what FLTK uses) std.time.sleep(16_666_666); self.box1.resize(x1, y, w, h); self.box1.parent().?.redraw(); _ = app.check(); // draw.box(.down, x, y, w, h, Color.fromName(.background)); } } else { while (self.box1.x() > new_x) { var x1 = self.box1.x() -| h / 6; if (x1 < new_x) x1 = new_x; std.time.sleep(16_666_666); self.box1.resize(x1, y, w, h); self.box1.parent().?.redraw(); _ = app.check(); } } } else { self.box1.resize(new_x, y, w, h); self.box1.parent().?.redraw(); _ = app.check(); } return true; }, // .push => return true, else => return false, } return false; } pub fn fromVoidPtr(ptr: *anyopaque) *Switch { return @ptrCast(@alignCast(ptr)); } pub fn widget(self: *Switch) *Widget { //return @ptrCast(self); return self.box1.widget(); } pub fn setCallback(self: *Switch, f: *const fn (*Switch) void) void { self.callback = .{ .normal = f }; } pub fn setCallbackEx(self: *Switch, f: *const fn (*Switch, ?*anyopaque) void, data: ?*anyopaque) void { self.callback = .{ .extended = f }; self.callback_data = data; } pub fn value(self: *const Switch) bool { return self.on; } pub fn setValue(self: *Switch, val: bool) void { const x = self.box1.x(); const y = self.box1.y(); const w = self.box1.w(); const h = self.box1.h(); const new_x = if (self.on) x - (h) else x + (h); self.on = val; self.box1.resize(new_x, y, w, h); self.box1.parent().?.redraw(); _ = app.check(); } pub fn setAnimation(self: *Switch, val: bool) void { self.animated = val; } };
0
repos/zfltk
repos/zfltk/examples/tile.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const Window = zfltk.window.Window; const Box = zfltk.box.Box; const Button = zfltk.button.Button; const Tile = zfltk.group.Tile; const Color = zfltk.enums.Color; pub fn main() !void { try app.init(); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Tile group", }); var tile = try Tile.init(.{ .w = 400, .h = 300, }); win.resizable(tile); const btn = try Button.init(.{ .x = 0, .y = 48, .w = tile.w() - 48, .h = 48, .label = "Button", }); // This demonstrates how you can add inline widgets which have no purpose // besides aesthetics. This could be useful for spacers and whatnot tile.add(.{ try Box.init(.{ .x = 0, .y = 0, .w = tile.w() - 48, .h = 48, .boxtype = .down, }), btn, try Box.init(.{ .x = 0, .y = 96, .w = tile.w() - 48, .h = tile.h() - 96, .boxtype = .down, .label = "Try dragging between\nwidget borders!", }), try Box.init(.{ .x = tile.w() - 48, .y = 0, .w = 48, .h = tile.h(), .boxtype = .down, }), }); tile.end(); win.end(); win.show(); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/browser.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const Window = zfltk.window.Window; const MultiBrowser = zfltk.browser.MultiBrowser; pub fn main() !void { try app.init(); var win = try Window.init(.{ .w = 900, .h = 300, .label = "Browser demo", }); // Available browsers are: normal, select, hold, multi and file var browser = try MultiBrowser.init(.{ .x = 10, .y = 10, .w = 900 - 20, .h = 300 - 20, }); browser.setColumnWidths( &[_:0]i32{ 50, 50, 50, 70, 70, 50, 50, 70, 70, 50 }, ); browser.setColumnChar('\t'); browser.add("USER\tPID\t%CPU\t%MEM\tVSZ\tRSS\tTTY\tSTAT\tSTART\tTIME\tCOMMAND"); browser.add("root\t2888\t0.0\t0.0\t1352\t0\ttty3\tSW\tAug15\t0:00\t@b@f/sbin/mingetty tty3"); browser.add("erco\t2889\t0.0\t13.0\t221352\t0\ttty3\tR\tAug15\t1:34\t@b@f/usr/local/bin/render a35 0004"); browser.add("uucp\t2892\t0.0\t0.0\t1352\t0\tttyS0\tSW\tAug15\t0:00\t@b@f/sbin/agetty -h 19200 ttyS0 vt100"); browser.add("root\t13115\t0.0\t0.0\t1352\t0\ttty2\tSW\tAug30\t0:00\t@b@f/sbin/mingetty tty2"); browser.add("root\t13464\t0.0\t0.0\t1352\t0\ttty1\tSW\tAug30\t0:00\t@b@f/sbin/mingetty tty1 --noclear"); win.end(); win.resizable(browser); win.show(); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/input.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const Box = zfltk.box.Box; const Event = zfltk.enums.Event; const Input = zfltk.input.Input; const Window = zfltk.window.Window; const Button = zfltk.button.Button; const std = @import("std"); const ButtonMessage = enum(usize) { pushed = 1, released, }; pub fn butCb(_: *Button, ev: Event) bool { switch (ev) { Event.push => { app.send(ButtonMessage, .pushed); return true; }, Event.release => { app.send(ButtonMessage, .released); return true; }, else => return false, } return false; } pub fn main() !void { try app.init(); app.setScheme(.plastic); var win = try Window.init(.{ .w = 400, .h = 250, .label = "Hello", }); var inp = try Input.init(.{ .x = 10, .y = 10, .w = 380, .h = 40, }); var mybox = try Box.init(.{ .x = 10, .y = 60, .w = 380, .h = 130, .boxtype = .up, }); var but = try Button.init(.{ .x = 160, .y = 200, .w = 80, .h = 40, .label = "Greet!", }); win.end(); win.show(); but.setEventHandler(butCb); mybox.setLabelSize(24); while (app.wait()) { if (app.recv(ButtonMessage)) |msg| switch (msg) { .pushed => { var buf: [100]u8 = undefined; const greeting = if (inp.value().len == 0) "I don't know your name!\nAdd it in the text box above" else try std.fmt.bufPrintZ(buf[0..], "Hello, {s}!", .{inp.value()}); mybox.setLabel(greeting); }, else => {}, }; } }
0
repos/zfltk
repos/zfltk/examples/editor.zig
// TODO: This example needs some extra work to properly port to the new API as // its a bit larger than other examples but it const zfltk = @import("zfltk"); const app = zfltk.app; const widget = zfltk.widget; const Window = zfltk.window.Window; const MenuBar = zfltk.menu.MenuBar; const enums = zfltk.enums; const Color = enums.Color; const TextEditor = zfltk.text.TextEditor; const dialog = zfltk.dialog; const FileDialog = zfltk.dialog.FileDialog; const std = @import("std"); // To avoid exiting when hitting escape. // Also logic can be added to prompt the user to save their work pub fn winCb(w: *Window) void { if (app.event() == .close) { w.hide(); } } fn newCb(_: *MenuBar, data: ?*anyopaque) void { var editor = TextEditor.fromRaw(data.?); editor.buffer().?.setText(""); } pub fn openCb(_: *MenuBar, data: ?*anyopaque) void { var editor = TextEditor.fromRaw(data.?); var dlg = try FileDialog(.file).init(.{}); dlg.setFilter("*.{txt,zig}"); dlg.show(); const fname = dlg.filename(); if (!std.mem.eql(u8, fname, "")) { editor.buffer().?.loadFile(fname) catch unreachable; } } pub fn saveCb(_: *MenuBar, data: ?*anyopaque) void { var editor = TextEditor.fromRaw(data.?); var dlg = try FileDialog(.save_file).init(.{ .save_as_confirm = true }); dlg.setFilter("*.{txt,zig}"); dlg.show(); const fname = dlg.filename(); if (!std.mem.eql(u8, fname, "")) { editor.buffer().?.saveFile(fname) catch unreachable; } } pub fn quitCb(_: *MenuBar, data: ?*anyopaque) void { var win = widget.Widget.fromRaw(data.?); win.hide(); } pub fn cutCb(_: *MenuBar, data: ?*anyopaque) void { const editor = TextEditor.fromRaw(data.?); editor.cut(); } pub fn copyCb(_: *MenuBar, data: ?*anyopaque) void { const editor = TextEditor.fromRaw(data.?); _ = editor.copy(); } pub fn pasteCb(_: *MenuBar, data: ?*anyopaque) void { const editor = TextEditor.fromRaw(data.?); editor.paste(); } pub fn helpCb(_: *MenuBar) void { dialog.message(300, 200, "This editor was built using fltk and zig!"); } pub fn main() !void { try app.init(); app.setScheme(.gtk); app.setBackground(Color.fromRgb(211, 211, 211)); var win = try Window.init(.{ .w = 800, .h = 600, .label = "Editor", }); win.freePosition(); var mymenu = try MenuBar.init(.{ .w = 800, .h = 35 }); var editor = try TextEditor.init(.{ .x = 2, .y = 37, .w = 800 - 2, .h = 600 - 37, }); editor.setLinenumberWidth(24); editor.showCursor(true); win.end(); win.add(.{editor}); win.resizable(editor); win.show(); win.setCallback(winCb); mymenu.addEx( "&File/New...\t", enums.Shortcut.Ctrl | 'n', .normal, newCb, editor, ); mymenu.addEx( "&File/Open...\t", enums.Shortcut.Ctrl | 'o', .normal, openCb, editor, ); mymenu.addEx( "&File/Save...\t", enums.Shortcut.Ctrl | 's', .menu_divider, saveCb, editor, ); mymenu.addEx( "&File/Quit...\t", enums.Shortcut.Ctrl | 'q', .normal, quitCb, win, ); mymenu.addEx( "&Edit/Cut...\t", enums.Shortcut.Ctrl | 'x', .normal, cutCb, editor, ); mymenu.addEx( "&Edit/Copy...\t", enums.Shortcut.Ctrl | 'c', .normal, copyCb, editor, ); mymenu.addEx( "&Edit/Paste...\t", enums.Shortcut.Ctrl | 'v', .normal, pasteCb, editor, ); mymenu.add( "&Help/About...\t", enums.Shortcut.Ctrl | 'q', .normal, helpCb, ); var item = mymenu.findItem("&File/Quit...\t"); item.setLabelColor(Color.fromName(.red)); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/threadawake.zig
const zfltk = @import("zfltk"); const std = @import("std"); const app = zfltk.app; const Window = zfltk.window.Window; const Button = zfltk.button.Button; const Box = zfltk.box.Box; const Color = zfltk.enums.Color; var count: u32 = 0; pub fn thread_func(data: ?*anyopaque) !void { var lighten = true; const d = data orelse unreachable; var mybox = Box.fromRaw(d); var buf: [256]u8 = undefined; while (true) { std.time.sleep(10_000_000); const val = try std.fmt.bufPrintZ(buf[0..], "Hello!\n{d}", .{count}); mybox.setLabel(val); const col = mybox.labelColor(); if (col.toHex() == 0xffffff) { lighten = false; } else if (col.toHex() == 0x000000) { lighten = true; } if (lighten) { mybox.setLabelColor(col.lighten(4)); } else { mybox.setLabelColor(col.darken(4)); } app.awake(); count += 1; } } pub fn butCb(_: *Button, data: ?*anyopaque) void { var thread = std.Thread.spawn(.{}, thread_func, .{data}) catch { return; }; thread.detach(); } pub fn main() !void { try app.init(); app.setScheme(.oxy); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Thread awake", }); var but = try Button.init(.{ .x = 120, .y = 220, .w = 160, .h = 40, .label = "Start threading!", }); but.clearVisibleFocus(); var mybox = try Box.init(.{ .x = 10, .y = 10, .w = 380, .h = 180, .label = "Hello!\n ", }); but.setCallbackEx(butCb, mybox.raw()); mybox.setLabelSize(48); win.end(); win.show(); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/mixed.zig
//! Example demonstrating how to combine the wrapped and raw C APIs const zfltk = @import("zfltk"); const app = zfltk.app; const Widget = zfltk.widget.Widget; const Window = zfltk.window.Window; const Button = zfltk.button.Button; const Color = zfltk.enums.Color; const std = @import("std"); const fmt = std.fmt; const c = zfltk.c; fn butCb(but: *Button) void { var buf: [32]u8 = undefined; const label = fmt.bufPrintZ( &buf, "X: {d}, Y: {d}", .{ c.Fl_event_x(), c.Fl_event_y() }, ) catch unreachable; but.setLabel(label); } fn colorButCb(color_but: *Button, _: ?*anyopaque) void { color_but.setColor(Color.fromRgbi( c.Fl_show_colormap(color_but.color().toRgbi()), )); } fn timeoutButCb(_: *Button, data: ?*anyopaque) void { const container: *[2]usize = @ptrCast(@alignCast(data.?)); const wait_time: f32 = @as(*f32, @ptrFromInt(container[1])).*; app.addTimeoutEx(wait_time, timeoutCb, data); } fn timeoutCb(data: ?*anyopaque) void { const container: *[2]usize = @ptrCast(@alignCast(data.?)); // Re-interpret our ints as pointers to get our objects back var but = Button.fromRaw(@ptrFromInt(container[0])); const wait_time: f32 = @as(*f32, @ptrFromInt(container[1])).*; var buf: [32]u8 = undefined; const label = fmt.bufPrintZ( &buf, "{d} seconds passed!\n", .{wait_time}, ) catch unreachable; // The same as `but.setLabel(label);`. // This is just for demonstration purposes c.Fl_Button_set_label( but.raw(), label.ptr, ); } pub fn main() !void { try app.init(); _ = c.Fl_set_scheme("gtk+"); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Mixed API", }); var but = try Button.init(.{ .x = 10, .y = 100, .w = 380, .h = 190, .label = "Click to get mouse coords", }); but.setLabelSize(24); but.setCallback(butCb); var color_but = try Button.init(.{ .x = 10, .y = 10, .w = 185, .h = 80, .label = "Set my color!", }); color_but.setCallbackEx(colorButCb, null); // Change this to whatever you want var wait_time: f32 = @floatCast(1); var buf: [32]u8 = undefined; const label = try fmt.bufPrintZ( &buf, "Add a {d} second\ntimeout!\n", .{wait_time}, ); var timeout_but = try Button.init(.{ .x = 205, .y = 10, .w = 185, .h = 80, .label = label, }); // Create a container to store multiple pointers as usizes var container: [2]usize = undefined; container[0] = @intFromPtr(timeout_but); container[1] = @intFromPtr(&wait_time); timeout_but.setCallbackEx( timeoutButCb, @ptrCast(&container), ); win.end(); win.show(); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/handle.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const Window = zfltk.window.Window; const Button = zfltk.button.Button; const Box = zfltk.box.Box; const Color = zfltk.enums.Color; const Event = zfltk.enums.Event; const std = @import("std"); const draw = zfltk.draw; fn butCb(but: *Button, data: ?*anyopaque) void { var box = Box.fromRaw(data.?); box.setLabel("Hello World!"); but.setColor(Color.fromName(.cyan)); } fn boxEventHandler(_: *Box, ev: Event, data: ?*anyopaque) bool { const btn = Button.fromRaw(data.?); switch (ev) { .push => { std.debug.print("Click the button: {s}\n", .{btn.label()}); return true; }, else => return false, } } fn boxDrawHandler(box: *Box) void { draw.setLineStyle(.DashDot, 2); draw.rectWithColor(box.x() + 10, box.y() + 10, box.w() - 20, box.h() - 20, Color.fromName(.cyan)); } pub fn main() !void { try app.init(); app.setScheme(.gtk); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Hello", }); var but = try Button.init(.{ .x = 160, .y = 220, .w = 80, .h = 40, .label = "Click me!", }); but.setDownBox(.flat); var box = try Box.init(.{ .x = 10, .y = 10, .w = 380, .h = 180, .label = "Hello", .boxtype = .up, }); box.setEventHandlerEx(boxEventHandler, but); box.setDrawHandler(boxDrawHandler); box.setLabelFont(.courier); box.setLabelSize(18); win.end(); win.show(); but.setCallbackEx(butCb, box); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/glwin.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const GlutWindow = zfltk.window.GlutWindow; const Mode = zfltk.enums.Mode; extern fn glClearColor(r: f32, g: f32, b: f32, a: f32) void; extern fn glClear(v: i32) void; const GL_COLOR_BUFFER_BIT = 16384; fn winDraw(win: *GlutWindow) void { win.makeCurrent(); glClearColor(1.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); } pub fn main() !void { try app.init(); var win = try GlutWindow.init(.{ .w = 400, .h = 300, .label = "Hello OpenGL", }); win.setMode(Mode.opengl3 | Mode.multi_sample); win.end(); win.resizable(win); win.show(); win.setDrawHandler(winDraw); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/channels.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const Window = zfltk.window.Window; const Button = zfltk.button.Button; const Box = zfltk.box.Box; const enums = zfltk.enums; pub const Message = enum(usize) { // Can't begin with Zero! first = 1, second, }; pub fn main() !void { try app.init(); app.setScheme(.gtk); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Hello", }); var but1 = try Button.init(.{ .x = 100, .y = 220, .w = 80, .h = 40, .label = "Button 1", }); var but2 = try Button.init(.{ .x = 200, .y = 220, .w = 80, .h = 40, .label = "Button 2", }); var mybox = try Box.init(.{ .x = 10, .y = 10, .w = 380, .h = 180, .boxtype = .up, }); mybox.setLabelFont(.courier); mybox.setLabelSize(18); win.end(); win.show(); but1.emit(Message, .first); but2.emit(Message, .second); while (app.wait()) { if (app.recv(Message)) |msg| switch (msg) { .first => mybox.setLabel("Button 1 Clicked!"), .second => mybox.setLabel("Button 2 Clicked!"), }; } }
0
repos/zfltk
repos/zfltk/examples/flutterlike.zig
const std = @import("std"); const zfltk = @import("zfltk"); const app = zfltk.app; const box = zfltk.box; const draw = zfltk.draw; const button = zfltk.button; const window = zfltk.window; const Align = zfltk.enums.Align; const Color = zfltk.enums.Color; const GRAY: Color = Color.fromHex(0x757575); const BLUE: Color = Color.fromHex(0x42A5F5); const SEL_BLUE: Color = Color.fromHex(0x2196F3); const WIDTH: i32 = 600; const HEIGHT: i32 = 400; var COUNT: i32 = 0; fn btnCb(_: *button.Button, data: ?*anyopaque) void { var count = box.Box.fromRaw(data.?); COUNT += 1; var buf: [250]u8 = undefined; const label = std.fmt.bufPrintZ(buf[0..], "{d}", .{COUNT}) catch "0"; count.setLabel(label); } fn barDrawHandler(b: *box.Box) void { draw.setColor(Color.fromRgb(211, 211, 211)); draw.rectFill(0, b.h(), b.w(), 3); } pub fn main() !void { try app.init(); var win = try window.Window.init(.{ .w = WIDTH, .h = HEIGHT, .label = "Flutter-like!" }); win.freePosition(); var bar = try box.Box.init(.{ .w = WIDTH, .h = 60, .label = " FLTK App!" }); bar.setLabelAlign(Align.left | Align.inside); var text = try box.Box.init(.{ .x = 250, .y = 180, .w = 100, .h = 40, .label = "You have pushed the button this many times:" }); var count = try box.Box.init(.{ .x = 250, .y = 220, .w = 100, .h = 40, .label = "0" }); var but = try button.Button.init(.{ .x = WIDTH - 100, .y = HEIGHT - 100, .w = 60, .h = 60, .label = "@+6plus" }); win.end(); win.resizable(win); win.show(); // Theming app.setBackground(Color.fromRgb(255, 255, 255)); app.setVisibleFocus(false); bar.setBox(.flat); bar.setLabelSize(22); bar.setLabelColor(Color.fromName(.white)); bar.setColor(BLUE); bar.setDrawHandler(barDrawHandler); text.setLabelSize(18); text.setLabelFont(.times); count.setLabelSize(36); count.setLabelColor(GRAY); but.setColor(BLUE); but.setSelectionColor(SEL_BLUE); but.setLabelColor(Color.fromName(.white)); but.setBox(.oflat); // End theming but.setCallbackEx(btnCb, count); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/image.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const SharedImage = zfltk.image.SharedImage; const Image = zfltk.image.Image; const Window = zfltk.window.Window; const Box = zfltk.box.Box; const Scroll = zfltk.group.Scroll; const Align = zfltk.enums.Align; const std = @import("std"); pub fn main() !void { try app.init(); var win = try Window.init(.{ .w = 415, .h = 140, .label = "Image demo", }); var scroll = try Scroll.init(.{ .w = 415, .h = 140, }); scroll.setScrollbar(.vertical); var mybox = try Box.init(.{ .w = 400, .h = 280, .boxtype = .up, }); scroll.add(.{mybox}); win.add(.{scroll}); const img = try Image.load(.png, "screenshots/logo.png"); mybox.setImage(img); win.end(); win.show(); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/layout.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const Window = zfltk.window.Window; const Box = zfltk.box.Box; const Button = zfltk.button.Button; const Pack = zfltk.group.Pack; const Color = zfltk.enums.Color; pub fn main() !void { try app.init(); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Hello", }); var pack = try Pack.init(.{ .w = 400, .h = 300, // The orientation is vertical by default so this isn't necessary to // set; this is just for reference .orientation = .vertical, .spacing = 6, }); win.resizable(pack); const btn = try Button.init(.{ .h = 48, .label = "Button", }); // In pack groups, the size must be provided as they don't automatically // adjust like flex groups. See `flex.zig` pack.add(.{ try Box.init(.{ .h = 48, .boxtype = .down }), btn, try Box.init(.{ .h = 48, .boxtype = .down }), }); // Flex has its own `end` method which recalculates layouts but the API // remains consistent by utilizing Zig's comptime pack.end(); win.end(); win.show(); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/simple.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const Window = zfltk.window.Window; const Button = zfltk.button.Button; const Box = zfltk.box.Box; const Color = zfltk.enums.Color; fn butCb(but: *Button, data: ?*anyopaque) void { var box = Box.fromRaw(data.?); box.setLabel("Hello World!"); but.setColor(Color.fromName(.cyan)); } pub fn main() !void { try app.init(); app.setScheme(.gtk); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Hello", }); win.freePosition(); var but = try Button.init(.{ .x = 160, .y = 220, .w = 80, .h = 40, .label = "Click me!", }); but.setDownBox(.flat); var box = try Box.init(.{ .x = 10, .y = 10, .w = 380, .h = 180, .boxtype = .up, }); box.setLabelFont(.courier); box.setLabelSize(18); win.end(); win.show(); but.setCallbackEx(butCb, box); try app.run(); }
0
repos/zfltk
repos/zfltk/examples/editormsgs.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const widget = zfltk.widget; const window = zfltk.window; const menu = zfltk.menu; const enums = zfltk.enums; const Color = enums.Color; const text = zfltk.text; const dialog = zfltk.dialog; const FileDialog = zfltk.dialog.FileDialog; const std = @import("std"); pub const Message = enum(usize) { // Can't begin with 0 New = 1, Open, Save, Quit, Cut, Copy, Paste, About, }; // To avoid exiting when hitting escape. // Also logic can be added to prompt the user to save their work pub fn winCb(w: *window.Window) void { if (app.event() == .close) { w.hide(); } } pub fn main() !void { try app.init(); app.setScheme(.gtk); app.setBackground(Color.fromRgb(211, 211, 211)); var win = try window.Window.init(.{ .w = 800, .h = 600, .label = "Editor" }); win.freePosition(); var mymenu = try menu.MenuBar.init(.{ .w = 800, .h = 35 }); var buf = try text.TextBuffer.init(); defer buf.deinit(); var editor = try text.TextEditor.init(.{ .x = 2, .y = 37, .w = 800 - 2, .h = 600 - 37, }); editor.setBuffer(buf); editor.setLinenumberWidth(24); win.end(); win.show(); win.setCallback(winCb); mymenu.addEmit( "&File/New...\t", enums.Shortcut.Ctrl | 'n', .normal, Message, .New, ); mymenu.addEmit( "&File/Open...\t", enums.Shortcut.Ctrl | 'o', .normal, Message, .Open, ); mymenu.addEmit( "&File/Save...\t", enums.Shortcut.Ctrl | 's', .menu_divider, Message, .Save, ); mymenu.addEmit( "&File/Quit...\t", enums.Shortcut.Ctrl | 'q', .normal, Message, .Quit, ); mymenu.addEmit( "&Edit/Cut...\t", enums.Shortcut.Ctrl | 'x', .normal, Message, .Cut, ); mymenu.addEmit( "&Edit/Copy...\t", enums.Shortcut.Ctrl | 'c', .normal, Message, .Copy, ); mymenu.addEmit( "&Edit/Paste...\t", enums.Shortcut.Ctrl | 'v', .normal, Message, .Paste, ); mymenu.addEmit( "&Help/About...\t", enums.Shortcut.Ctrl | 'q', .normal, Message, .About, ); var item = mymenu.findItem("&File/Quit...\t"); item.setLabelColor(Color.fromName(.red)); while (app.wait()) { if (app.recv(Message)) |msg| switch (msg) { .New => buf.setText(""), .Open => { var dlg = try FileDialog(.file).init(.{}); dlg.setFilter("*.{txt,zig}"); dlg.show(); const fname = dlg.filename(); if (!std.mem.eql(u8, fname, "")) { editor.buffer().?.loadFile(fname) catch unreachable; } }, .Save => { var dlg = try FileDialog(.save_file).init(.{}); dlg.setFilter("*.{txt,zig}"); dlg.show(); const fname = dlg.filename(); if (!std.mem.eql(u8, fname, "")) { editor.buffer().?.saveFile(fname) catch unreachable; } }, .Quit => win.hide(), .Cut => editor.cut(), .Copy => editor.copy(), .Paste => editor.paste(), .About => dialog.message(300, 200, "This editor was built using fltk and zig!"), }; } }
0
repos/zfltk
repos/zfltk/examples/valuators.zig
const zfltk = @import("zfltk"); const app = zfltk.app; const Window = zfltk.window.Window; const valuator = zfltk.valuator; const Pack = zfltk.group.Pack; const enums = zfltk.enums; pub fn main() !void { try app.init(); app.setScheme(.gtk); var win = try Window.init(.{ .w = 400, .h = 300, .label = "Valuators", }); var pack = try Pack.init(.{ .w = 400, .h = 300, .spacing = 40, }); pack.add(.{ try valuator.Slider.init(.{ .h = 40, .style = .nice, .orientation = .horizontal, .label = "Slider", }), try valuator.Scrollbar.init(.{ .h = 40, .style = .nice, .orientation = .horizontal, .label = "Scrollbar", }), try valuator.Counter.init(.{ .h = 40, .w = win.w(), .label = "Counter", }), try valuator.Adjuster.init(.{ .h = 40, .label = "Adjuster", }), }); pack.end(); win.end(); win.show(); try app.run(); }
0
repos
repos/bf-interpreter/README.md
# bf-interpreter To run the interpreter write your BF code in a separate file and provide the path to the file as an argument to the executable ```sh > bf-interpreter .\examples\hello_world.b ```
0
repos
repos/bf-interpreter/build.zig
const std = @import("std"); // Although this function looks imperative, note that its job is to // declaratively construct a build graph that will be executed by an external // runner. pub fn build(b: *std.Build) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard optimization options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not // set a preferred release mode, allowing the user to decide how to optimize. const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "bf-interpreter", // In this case the main source file is merely a path, however, in more // complicated build scripts, this could be a generated file. .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); // This declares intent for the executable to be installed into the // standard location when the user invokes the "install" step (the default // step when running `zig build`). b.installArtifact(exe); // This *creates* a Run step in the build graph, to be executed when another // step is evaluated that depends on it. The next line below will establish // such a dependency. const run_cmd = b.addRunArtifact(exe); // By making the run step depend on the install step, it will be run from the // installation directory rather than directly from within the cache directory. // This is not necessary, however, if the application depends on other installed // files, this ensures they will be present and in the expected location. run_cmd.step.dependOn(b.getInstallStep()); // This allows the user to pass arguments to the application in the build // command itself, like this: `zig build run -- arg1 arg2 etc` if (b.args) |args| { run_cmd.addArgs(args); } // This creates a build step. It will be visible in the `zig build --help` menu, // and can be selected like this: `zig build run` // This will evaluate the `run` step rather than the default, which is "install". const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); // Creates a step for unit testing. This only builds the test executable // but does not run it. const unit_tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); const run_unit_tests = b.addRunArtifact(unit_tests); // Similar to creating the run step earlier, this exposes a `test` step to // the `zig build --help` menu, providing a way for the user to request // running the unit tests. const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_unit_tests.step); }
0
repos/bf-interpreter
repos/bf-interpreter/src/main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const HashMap = std.HashMap; const Type = std.builtin.Type; const RAM = 30_000; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const stderr = std.io.getStdErr().writer(); var args = try std.process.argsWithAllocator(allocator); defer args.deinit(); _ = args.skip(); const file_path = args.next() orelse return error.NoFile; try stderr.print("File: {s}\n", .{file_path}); const file = try std.fs.cwd().openFile(file_path, .{}); defer file.close(); const code = try readToEndAlloc(allocator, file.reader()); try stderr.print("Code:\n\"{s}\"\n", .{code.items}); const program = try parseCode(allocator, std.mem.trim(u8, code.items, " \r\n\t")); code.deinit(); const stdin = std.io.getStdIn().reader(); const stdout = std.io.getStdOut().writer(); var result = ArrayList(u8).init(allocator); try runProgram(program.items, stdin, result.writer()); try stderr.print("Result:\n\"", .{}); try stdout.print("{s}", .{result.items}); try stderr.print("\"\n", .{}); } fn readToEndAlloc(allocator: Allocator, reader: anytype) !ArrayList(u8) { var contents = ArrayList(u8).init(allocator); errdefer contents.deinit(); reader.streamUntilDelimiter(contents.writer(), '\x00', null) catch |err| switch (err) { error.EndOfStream => {}, else => return err, }; return contents; } fn runProgram(program: []const Instruction, reader: anytype, writer: anytype) !void { var memory = [_]u8{0} ** RAM; var ptr: usize = 0; var cursor: usize = 0; errdefer std.debug.print("ptr: {d};\ncursor: {d};\nmemory: {any}\n", .{ ptr, cursor, memory }); while (cursor < program.len) : (cursor += 1) { const instruction = program[cursor]; switch (instruction) { Instruction.next => if (ptr == RAM - 1) { ptr = 0; } else { ptr += 1; }, Instruction.previous => if (ptr == 0) { ptr = RAM - 1; } else { ptr -= 1; }, Instruction.plus_one => memory[ptr] = @addWithOverflow(memory[ptr], 1)[0], Instruction.minus_one => memory[ptr] = @subWithOverflow(memory[ptr], 1)[0], Instruction.output => if (@TypeOf(writer) != @TypeOf(null)) { try writer.writeByte(memory[ptr]); } else { return error.NoWriter; }, Instruction.input => if (@TypeOf(reader) != @TypeOf(null)) { memory[ptr] = try reader.readByte(); } else { return error.NoReader; }, Instruction.loop_forwards => |end| if (memory[ptr] == 0) { cursor = end; }, Instruction.loop_backwards => |start| if (memory[ptr] != 0) { cursor = start; }, } } } fn parseCode(allocator: Allocator, code: []const u8) !ArrayList(Instruction) { var program = ArrayList(Instruction).init(allocator); errdefer program.deinit(); var loop_start_stack = ArrayList(usize).init(allocator); defer loop_start_stack.deinit(); for (code, 0..) |c, i| { switch (c) { '>' => try program.append(Instruction.next), '<' => try program.append(Instruction.previous), '+' => try program.append(Instruction.plus_one), '-' => try program.append(Instruction.minus_one), '.' => try program.append(Instruction.output), ',' => try program.append(Instruction.input), '[' => try program.append(.{ .loop_forwards = blk: { for (i + 1..code.len) |j| { if (code[j] == ']') { try loop_start_stack.append(i); break :blk j; } } return error.InvalidLoop; } }), ']' => try program.append(.{ .loop_backwards = loop_start_stack.popOrNull() orelse return error.InvalidLoop }), else => {}, } } return program; } const Instruction = union(enum) { next, previous, plus_one, minus_one, output, input, loop_forwards: usize, loop_backwards: usize, }; test "hello world" { var code = blk: { const path = "./examples/hello_world.b"; const file = try std.fs.cwd().openFile(path, .{}); defer file.close(); var data = ArrayList(u8).init(std.testing.allocator); errdefer data.deinit(); file.reader().streamUntilDelimiter(data.writer(), '\n', null) catch |err| switch (err) { error.EndOfStream => {}, else => return err, }; break :blk data; }; defer code.deinit(); const program = try parseCode(std.testing.allocator, std.mem.trim(u8, code.items, " \r\n\t")); defer program.deinit(); var output = ArrayList(u8).init(std.testing.allocator); defer output.deinit(); try runProgram(program.items, null, output.writer()); try std.testing.expectEqualSlices(u8, "Hello World!", output.items); }
0
repos
repos/libebur128/README.md
This is a fork of [libebur128](https://github.com/jiixyj/libebur128), packaged for Zig. Unnecessary files have been deleted, and the build system has been replaced with `build.zig`. Original README follows: ============================================================================ libebur128 ========== libebur128 is a library that implements the EBU R 128 standard for loudness normalisation. All source code is licensed under the MIT license. See COPYING file for details. See also [loudness-scanner tool](https://github.com/jiixyj/loudness-scanner). News ---- v1.2.6 released: * Fix dynamic linking on Windows. v1.2.5 released: * Remove `BUILD_STATIC_LIBS` build option. Instead the CMake-supported `BUILD_SHARED_LIBS` option is now honored as expected. * Various code cleanups, warning fixes and documentation improvements * Fix issue related to filter state indexing with high channel enums (#77) * Introduce limits for number of channels and maximum supported samplerate to avoid integer overflows * Fix error return code of `ebur128_set_channel`. The actual behavior is now aligned to the documentation (#90). v1.2.4 released: * Fix broken `ebur128_loudness_global_multiple()` function. Since v1.1.0 it calculated the relative threshold just from the last state given to it, resulting in wrong values. * More tests * Fix some minor build issues * Fix uninitialized memory in `ebur128_init()`, possibly resulting in wrong values v1.2.3 released: * Fix uninitialized memory access during true peak scanning (bug #72) v1.2.2 released (v1.2.1 was mistagged): * Fix a null pointer dereference when doing true peak scanning of 192kHz data v1.2.0 released: * New functions for real time loudness/peak monitoring: * `ebur128_loudness_window()` * `ebur128_set_max_window()` * `ebur128_set_max_history()` * `ebur128_prev_sample_peak()` * `ebur128_prev_true_peak()` * New FIR resampler for true peak calculation, removing Speex dependency * Add true peak conformance tests * Bug fixes v1.1.0 released: * Add `ebur128_relative_threshold()` * Add channel definitions from ITU R-REC-BS 1770-4 to channel enum * Fix some minor build issues v1.0.3 released: * Fix build with recent speexdsp * Correct license file name * CMake option to disable static library * minimal-example.c: do not hard code program name in usage Features -------- * Portable ANSI C code * Implements M, S and I modes * Implements loudness range measurement (EBU - TECH 3342) * True peak scanning * Supports all samplerates by recalculation of the filter coefficients Installation ------------ In the root folder, type: mkdir build cd build cmake .. make If you want the git version, run simply: git clone git://github.com/jiixyj/libebur128.git Usage ----- Library usage should be pretty straightforward. All exported symbols are documented in the ebur128.h header file. For a usage example, see minimal-example.c in the tests folder. On some operating systems, static libraries should be compiled as position independent code. You can enable that by turning on `WITH_STATIC_PIC`.
0
repos
repos/libebur128/build.zig.zon
.{ .name = "ebur128", .version = "1.2.7-1", .paths = .{ "COPYING", "README.md", "build.zig", "build.zig.zon", "ebur128", }, }
0
repos
repos/libebur128/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const lib = b.addStaticLibrary(.{ .name = "ebur128", .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}), }); lib.linkLibC(); lib.addCSourceFiles(.{ .files = &.{"ebur128/ebur128.c"}, }); lib.addIncludePath(.{ .path = "ebur128" }); lib.addIncludePath(.{ .path = "ebur128/queue" }); lib.installHeader("ebur128/ebur128.h", "ebur128.h"); b.installArtifact(lib); }
0
repos/libebur128
repos/libebur128/ebur128/ebur128.h
/* See COPYING file for copyright and license details. */ #ifndef EBUR128_H_ #define EBUR128_H_ /** \file ebur128.h * \brief libebur128 - a library for loudness measurement according to * the EBU R128 standard. */ #ifdef __cplusplus extern "C" { #endif #define EBUR128_VERSION_MAJOR 1 #define EBUR128_VERSION_MINOR 2 #define EBUR128_VERSION_PATCH 6 #include <stddef.h> /* for size_t */ /** \enum channel * Use these values when setting the channel map with ebur128_set_channel(). * See definitions in ITU R-REC-BS 1770-4 */ enum channel { EBUR128_UNUSED = 0, /**< unused channel (for example LFE channel) */ EBUR128_LEFT = 1, /**< */ EBUR128_Mp030 = 1, /**< itu M+030 */ EBUR128_RIGHT = 2, /**< */ EBUR128_Mm030 = 2, /**< itu M-030 */ EBUR128_CENTER = 3, /**< */ EBUR128_Mp000 = 3, /**< itu M+000 */ EBUR128_LEFT_SURROUND = 4, /**< */ EBUR128_Mp110 = 4, /**< itu M+110 */ EBUR128_RIGHT_SURROUND = 5, /**< */ EBUR128_Mm110 = 5, /**< itu M-110 */ EBUR128_DUAL_MONO, /**< a channel that is counted twice */ EBUR128_MpSC, /**< itu M+SC */ EBUR128_MmSC, /**< itu M-SC */ EBUR128_Mp060, /**< itu M+060 */ EBUR128_Mm060, /**< itu M-060 */ EBUR128_Mp090, /**< itu M+090 */ EBUR128_Mm090, /**< itu M-090 */ EBUR128_Mp135, /**< itu M+135 */ EBUR128_Mm135, /**< itu M-135 */ EBUR128_Mp180, /**< itu M+180 */ EBUR128_Up000, /**< itu U+000 */ EBUR128_Up030, /**< itu U+030 */ EBUR128_Um030, /**< itu U-030 */ EBUR128_Up045, /**< itu U+045 */ EBUR128_Um045, /**< itu U-030 */ EBUR128_Up090, /**< itu U+090 */ EBUR128_Um090, /**< itu U-090 */ EBUR128_Up110, /**< itu U+110 */ EBUR128_Um110, /**< itu U-110 */ EBUR128_Up135, /**< itu U+135 */ EBUR128_Um135, /**< itu U-135 */ EBUR128_Up180, /**< itu U+180 */ EBUR128_Tp000, /**< itu T+000 */ EBUR128_Bp000, /**< itu B+000 */ EBUR128_Bp045, /**< itu B+045 */ EBUR128_Bm045 /**< itu B-045 */ }; /** \enum error * Error return values. */ enum error { EBUR128_SUCCESS = 0, EBUR128_ERROR_NOMEM, EBUR128_ERROR_INVALID_MODE, EBUR128_ERROR_INVALID_CHANNEL_INDEX, EBUR128_ERROR_NO_CHANGE }; /** \enum mode * Use these values in ebur128_init (or'ed). Try to use the lowest possible * modes that suit your needs, as performance will be better. */ enum mode { /** can call ebur128_loudness_momentary */ EBUR128_MODE_M = (1 << 0), /** can call ebur128_loudness_shortterm */ EBUR128_MODE_S = (1 << 1) | EBUR128_MODE_M, /** can call ebur128_loudness_global_* and ebur128_relative_threshold */ EBUR128_MODE_I = (1 << 2) | EBUR128_MODE_M, /** can call ebur128_loudness_range */ EBUR128_MODE_LRA = (1 << 3) | EBUR128_MODE_S, /** can call ebur128_sample_peak */ EBUR128_MODE_SAMPLE_PEAK = (1 << 4) | EBUR128_MODE_M, /** can call ebur128_true_peak */ EBUR128_MODE_TRUE_PEAK = (1 << 5) | EBUR128_MODE_M | EBUR128_MODE_SAMPLE_PEAK, /** uses histogram algorithm to calculate loudness */ EBUR128_MODE_HISTOGRAM = (1 << 6) }; /** forward declaration of ebur128_state_internal */ struct ebur128_state_internal; /** \brief Contains information about the state of a loudness measurement. * * You should not need to modify this struct directly. */ typedef struct { int mode; /**< The current mode. */ unsigned int channels; /**< The number of channels. */ unsigned long samplerate; /**< The sample rate. */ struct ebur128_state_internal* d; /**< Internal state. */ } ebur128_state; /** \brief Get library version number. Do not pass null pointers here. * * @param major major version number of library * @param minor minor version number of library * @param patch patch version number of library */ void ebur128_get_version(int* major, int* minor, int* patch); /** \brief Initialize library state. * * @param channels the number of channels. * @param samplerate the sample rate. * @param mode see the mode enum for possible values. * @return an initialized library state, or NULL on error. */ ebur128_state* ebur128_init(unsigned int channels, unsigned long samplerate, int mode); /** \brief Destroy library state. * * @param st pointer to a library state. */ void ebur128_destroy(ebur128_state** st); /** \brief Set channel type. * * The default is: * - 0 -> EBUR128_LEFT * - 1 -> EBUR128_RIGHT * - 2 -> EBUR128_CENTER * - 3 -> EBUR128_UNUSED * - 4 -> EBUR128_LEFT_SURROUND * - 5 -> EBUR128_RIGHT_SURROUND * * @param st library state. * @param channel_number zero based channel index. * @param value channel type from the "channel" enum. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_INVALID_CHANNEL_INDEX if invalid channel index. */ int ebur128_set_channel(ebur128_state* st, unsigned int channel_number, int value); /** \brief Change library parameters. * * Note that the channel map will be reset when setting a different number of * channels. The current unfinished block will be lost. * * @param st library state. * @param channels new number of channels. * @param samplerate new sample rate. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_NOMEM on memory allocation error. The state will be * invalid and must be destroyed. * - EBUR128_ERROR_NO_CHANGE if channels and sample rate were not changed. */ int ebur128_change_parameters(ebur128_state* st, unsigned int channels, unsigned long samplerate); /** \brief Set the maximum window duration. * * Set the maximum duration that will be used for ebur128_loudness_window(). * Note that this destroys the current content of the audio buffer. * * @param st library state. * @param window duration of the window in ms. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_NOMEM on memory allocation error. The state will be * invalid and must be destroyed. * - EBUR128_ERROR_NO_CHANGE if window duration not changed. */ int ebur128_set_max_window(ebur128_state* st, unsigned long window); /** \brief Set the maximum history. * * Set the maximum history that will be stored for loudness integration. * More history provides more accurate results, but requires more resources. * * Applies to ebur128_loudness_range() and ebur128_loudness_global() when * EBUR128_MODE_HISTOGRAM is not set. * * Default is ULONG_MAX (at least ~50 days). * Minimum is 3000ms for EBUR128_MODE_LRA and 400ms for EBUR128_MODE_M. * * @param st library state. * @param history duration of history in ms. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_NO_CHANGE if history not changed. */ int ebur128_set_max_history(ebur128_state* st, unsigned long history); /** \brief Add frames to be processed. * * @param st library state. * @param src array of source frames. Channels must be interleaved. * @param frames number of frames. Not number of samples! * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_NOMEM on memory allocation error. */ int ebur128_add_frames_short(ebur128_state* st, const short* src, size_t frames); /** \brief See \ref ebur128_add_frames_short */ int ebur128_add_frames_int(ebur128_state* st, const int* src, size_t frames); /** \brief See \ref ebur128_add_frames_short */ int ebur128_add_frames_float(ebur128_state* st, const float* src, size_t frames); /** \brief See \ref ebur128_add_frames_short */ int ebur128_add_frames_double(ebur128_state* st, const double* src, size_t frames); /** \brief Get global integrated loudness in LUFS. * * @param st library state. * @param out integrated loudness in LUFS. -HUGE_VAL if result is negative * infinity. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_INVALID_MODE if mode "EBUR128_MODE_I" has not been set. */ int ebur128_loudness_global(ebur128_state* st, double* out); /** \brief Get global integrated loudness in LUFS across multiple instances. * * @param sts array of library states. * @param size length of sts * @param out integrated loudness in LUFS. -HUGE_VAL if result is negative * infinity. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_INVALID_MODE if mode "EBUR128_MODE_I" has not been set. */ int ebur128_loudness_global_multiple(ebur128_state** sts, size_t size, double* out); /** \brief Get momentary loudness (last 400ms) in LUFS. * * @param st library state. * @param out momentary loudness in LUFS. -HUGE_VAL if result is negative * infinity. * @return * - EBUR128_SUCCESS on success. */ int ebur128_loudness_momentary(ebur128_state* st, double* out); /** \brief Get short-term loudness (last 3s) in LUFS. * * @param st library state. * @param out short-term loudness in LUFS. -HUGE_VAL if result is negative * infinity. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_INVALID_MODE if mode "EBUR128_MODE_S" has not been set. */ int ebur128_loudness_shortterm(ebur128_state* st, double* out); /** \brief Get loudness of the specified window in LUFS. * * window must not be larger than the current window set in st. * The current window can be changed by calling ebur128_set_max_window(). * * @param st library state. * @param window window in ms to calculate loudness. * @param out loudness in LUFS. -HUGE_VAL if result is negative infinity. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_INVALID_MODE if window larger than current window in st. */ int ebur128_loudness_window(ebur128_state* st, unsigned long window, double* out); /** \brief Get loudness range (LRA) of programme in LU. * * Calculates loudness range according to EBU 3342. * * @param st library state. * @param out loudness range (LRA) in LU. Will not be changed in case of * error. EBUR128_ERROR_NOMEM or EBUR128_ERROR_INVALID_MODE will be * returned in this case. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_NOMEM in case of memory allocation error. * - EBUR128_ERROR_INVALID_MODE if mode "EBUR128_MODE_LRA" has not been set. */ int ebur128_loudness_range(ebur128_state* st, double* out); /** \brief Get loudness range (LRA) in LU across multiple instances. * * Calculates loudness range according to EBU 3342. * * @param sts array of library states. * @param size length of sts * @param out loudness range (LRA) in LU. Will not be changed in case of * error. EBUR128_ERROR_NOMEM or EBUR128_ERROR_INVALID_MODE will be * returned in this case. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_NOMEM in case of memory allocation error. * - EBUR128_ERROR_INVALID_MODE if mode "EBUR128_MODE_LRA" has not been set. */ int ebur128_loudness_range_multiple(ebur128_state** sts, size_t size, double* out); /** \brief Get maximum sample peak from all frames that have been processed. * * The equation to convert to dBFS is: 20 * log10(out) * * @param st library state * @param channel_number channel to analyse * @param out maximum sample peak in float format (1.0 is 0 dBFS) * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_INVALID_MODE if mode "EBUR128_MODE_SAMPLE_PEAK" has not * been set. * - EBUR128_ERROR_INVALID_CHANNEL_INDEX if invalid channel index. */ int ebur128_sample_peak(ebur128_state* st, unsigned int channel_number, double* out); /** \brief Get maximum sample peak from the last call to add_frames(). * * The equation to convert to dBFS is: 20 * log10(out) * * @param st library state * @param channel_number channel to analyse * @param out maximum sample peak in float format (1.0 is 0 dBFS) * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_INVALID_MODE if mode "EBUR128_MODE_SAMPLE_PEAK" has not * been set. * - EBUR128_ERROR_INVALID_CHANNEL_INDEX if invalid channel index. */ int ebur128_prev_sample_peak(ebur128_state* st, unsigned int channel_number, double* out); /** \brief Get maximum true peak from all frames that have been processed. * * Uses an implementation defined algorithm to calculate the true peak. Do not * try to compare resulting values across different versions of the library, * as the algorithm may change. * * The current implementation uses a custom polyphase FIR interpolator to * calculate true peak. Will oversample 4x for sample rates < 96000 Hz, 2x for * sample rates < 192000 Hz and leave the signal unchanged for 192000 Hz. * * The equation to convert to dBTP is: 20 * log10(out) * * @param st library state * @param channel_number channel to analyse * @param out maximum true peak in float format (1.0 is 0 dBTP) * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_INVALID_MODE if mode "EBUR128_MODE_TRUE_PEAK" has not * been set. * - EBUR128_ERROR_INVALID_CHANNEL_INDEX if invalid channel index. */ int ebur128_true_peak(ebur128_state* st, unsigned int channel_number, double* out); /** \brief Get maximum true peak from the last call to add_frames(). * * Uses an implementation defined algorithm to calculate the true peak. Do not * try to compare resulting values across different versions of the library, * as the algorithm may change. * * The current implementation uses a custom polyphase FIR interpolator to * calculate true peak. Will oversample 4x for sample rates < 96000 Hz, 2x for * sample rates < 192000 Hz and leave the signal unchanged for 192000 Hz. * * The equation to convert to dBTP is: 20 * log10(out) * * @param st library state * @param channel_number channel to analyse * @param out maximum true peak in float format (1.0 is 0 dBTP) * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_INVALID_MODE if mode "EBUR128_MODE_TRUE_PEAK" has not * been set. * - EBUR128_ERROR_INVALID_CHANNEL_INDEX if invalid channel index. */ int ebur128_prev_true_peak(ebur128_state* st, unsigned int channel_number, double* out); /** \brief Get relative threshold in LUFS. * * @param st library state * @param out relative threshold in LUFS. * @return * - EBUR128_SUCCESS on success. * - EBUR128_ERROR_INVALID_MODE if mode "EBUR128_MODE_I" has not * been set. */ int ebur128_relative_threshold(ebur128_state* st, double* out); #ifdef __cplusplus } #endif #endif /* EBUR128_H_ */
0
repos/libebur128
repos/libebur128/ebur128/ebur128.c
/* See COPYING file for copyright and license details. */ #include "ebur128.h" #include <float.h> #include <limits.h> #include <math.h> /* You may have to define _USE_MATH_DEFINES if you use MSVC */ #include <stdio.h> #include <stdlib.h> /* This can be replaced by any BSD-like queue implementation. */ #include <sys/queue.h> #define CHECK_ERROR(condition, errorcode, goto_point) \ if ((condition)) { \ errcode = (errorcode); \ goto goto_point; \ } #define EBUR128_MAX(a, b) (((a) > (b)) ? (a) : (b)) static int safe_size_mul(size_t nmemb, size_t size, size_t* result) { /* Adapted from OpenBSD reallocarray. */ #define MUL_NO_OVERFLOW (((size_t) 1) << (sizeof(size_t) * 4)) if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && /**/ nmemb > 0 && ((size_t) (-1)) / nmemb < size) { return 1; } #undef MUL_NO_OVERFLOW *result = nmemb * size; return 0; } STAILQ_HEAD(ebur128_double_queue, ebur128_dq_entry); struct ebur128_dq_entry { double z; STAILQ_ENTRY(ebur128_dq_entry) entries; }; #define ALMOST_ZERO 0.000001 #define FILTER_STATE_SIZE 5 typedef struct { unsigned int count; /* Number of coefficients in this subfilter */ unsigned int* index; /* Delay index of corresponding filter coeff */ double* coeff; /* List of subfilter coefficients */ } interp_filter; typedef struct { /* Data structure for polyphase FIR interpolator */ unsigned int factor; /* Interpolation factor of the interpolator */ unsigned int taps; /* Taps (prefer odd to increase zero coeffs) */ unsigned int channels; /* Number of channels */ unsigned int delay; /* Size of delay buffer */ interp_filter* filter; /* List of subfilters (one for each factor) */ float** z; /* List of delay buffers (one for each channel) */ unsigned int zi; /* Current delay buffer index */ } interpolator; /** BS.1770 filter state. */ typedef double filter_state[FILTER_STATE_SIZE]; struct ebur128_state_internal { /** Filtered audio data (used as ring buffer). */ double* audio_data; /** Size of audio_data array. */ size_t audio_data_frames; /** Current index for audio_data. */ size_t audio_data_index; /** How many frames are needed for a gating block. Will correspond to 400ms * of audio at initialization, and 100ms after the first block (75% overlap * as specified in the 2011 revision of BS1770). */ unsigned long needed_frames; /** The channel map. Has as many elements as there are channels. */ int* channel_map; /** How many samples fit in 100ms (rounded). */ unsigned long samples_in_100ms; /** BS.1770 filter coefficients (nominator). */ double b[5]; /** BS.1770 filter coefficients (denominator). */ double a[5]; /** one filter_state per channel. */ filter_state* v; /** Linked list of block energies. */ struct ebur128_double_queue block_list; unsigned long block_list_max; unsigned long block_list_size; /** Linked list of 3s-block energies, used to calculate LRA. */ struct ebur128_double_queue short_term_block_list; unsigned long st_block_list_max; unsigned long st_block_list_size; int use_histogram; unsigned long* block_energy_histogram; unsigned long* short_term_block_energy_histogram; /** Keeps track of when a new short term block is needed. */ size_t short_term_frame_counter; /** Maximum sample peak, one per channel */ double* sample_peak; double* prev_sample_peak; /** Maximum true peak, one per channel */ double* true_peak; double* prev_true_peak; interpolator* interp; float* resampler_buffer_input; size_t resampler_buffer_input_frames; float* resampler_buffer_output; size_t resampler_buffer_output_frames; /** The maximum window duration in ms. */ unsigned long window; unsigned long history; }; static double relative_gate = -10.0; /* Those will be calculated when initializing the library */ static double relative_gate_factor; static double minus_twenty_decibels; static double histogram_energies[1000]; static double histogram_energy_boundaries[1001]; static interpolator* interp_create(unsigned int taps, unsigned int factor, unsigned int channels) { int errcode; /* unused */ interpolator* interp; unsigned int j; interp = (interpolator*) calloc(1, sizeof(interpolator)); CHECK_ERROR(!interp, 0, exit); interp->taps = taps; interp->factor = factor; interp->channels = channels; interp->delay = (interp->taps + interp->factor - 1) / interp->factor; /* Initialize the filter memory * One subfilter per interpolation factor. */ interp->filter = (interp_filter*) calloc(interp->factor, sizeof(*interp->filter)); CHECK_ERROR(!interp->filter, 0, free_interp); for (j = 0; j < interp->factor; j++) { interp->filter[j].index = (unsigned int*) calloc(interp->delay, sizeof(unsigned int)); interp->filter[j].coeff = (double*) calloc(interp->delay, sizeof(double)); CHECK_ERROR(!interp->filter[j].index || !interp->filter[j].coeff, 0, free_filter_index_coeff); } /* One delay buffer per channel. */ interp->z = (float**) calloc(interp->channels, sizeof(float*)); CHECK_ERROR(!interp->z, 0, free_filter_index_coeff); for (j = 0; j < interp->channels; j++) { interp->z[j] = (float*) calloc(interp->delay, sizeof(float)); CHECK_ERROR(!interp->z[j], 0, free_filter_z); } /* Calculate the filter coefficients */ for (j = 0; j < interp->taps; j++) { /* Calculate sinc */ double m = (double) j - (double) (interp->taps - 1) / 2.0; double c = 1.0; if (fabs(m) > ALMOST_ZERO) { c = sin(m * M_PI / interp->factor) / (m * M_PI / interp->factor); } /* Apply Hanning window */ c *= 0.5 * (1 - cos(2 * M_PI * j / (interp->taps - 1))); if (fabs(c) > ALMOST_ZERO) { /* Ignore any zero coeffs. */ /* Put the coefficient into the correct subfilter */ unsigned int f = j % interp->factor; unsigned int t = interp->filter[f].count++; interp->filter[f].coeff[t] = c; interp->filter[f].index[t] = j / interp->factor; } } return interp; free_filter_z: for (j = 0; j < interp->channels; j++) { free(interp->z[j]); } free(interp->z); free_filter_index_coeff: for (j = 0; j < interp->factor; j++) { free(interp->filter[j].index); free(interp->filter[j].coeff); } free(interp->filter); free_interp: free(interp); exit: return NULL; } static void interp_destroy(interpolator* interp) { unsigned int j = 0; if (!interp) { return; } for (j = 0; j < interp->factor; j++) { free(interp->filter[j].index); free(interp->filter[j].coeff); } free(interp->filter); for (j = 0; j < interp->channels; j++) { free(interp->z[j]); } free(interp->z); free(interp); } static size_t interp_process(interpolator* interp, size_t frames, float* in, float* out) { size_t frame = 0; unsigned int chan = 0; unsigned int f = 0; unsigned int t = 0; unsigned int out_stride = interp->channels * interp->factor; float* outp = 0; double acc = 0; double c = 0; for (frame = 0; frame < frames; frame++) { for (chan = 0; chan < interp->channels; chan++) { /* Add sample to delay buffer */ interp->z[chan][interp->zi] = *in++; /* Apply coefficients */ outp = out + chan; for (f = 0; f < interp->factor; f++) { acc = 0.0; for (t = 0; t < interp->filter[f].count; t++) { int i = (int) interp->zi - (int) interp->filter[f].index[t]; if (i < 0) { i += (int) interp->delay; } c = interp->filter[f].coeff[t]; acc += (double) interp->z[chan][i] * c; } *outp = (float) acc; outp += interp->channels; } } out += out_stride; interp->zi++; if (interp->zi == interp->delay) { interp->zi = 0; } } return frames * interp->factor; } static int ebur128_init_filter(ebur128_state* st) { int errcode = EBUR128_SUCCESS; int i, j; double f0 = 1681.974450955533; double G = 3.999843853973347; double Q = 0.7071752369554196; double K = tan(M_PI * f0 / (double) st->samplerate); double Vh = pow(10.0, G / 20.0); double Vb = pow(Vh, 0.4996667741545416); double pb[3] = { 0.0, 0.0, 0.0 }; double pa[3] = { 1.0, 0.0, 0.0 }; double rb[3] = { 1.0, -2.0, 1.0 }; double ra[3] = { 1.0, 0.0, 0.0 }; double a0 = 1.0 + K / Q + K * K; pb[0] = (Vh + Vb * K / Q + K * K) / a0; pb[1] = 2.0 * (K * K - Vh) / a0; pb[2] = (Vh - Vb * K / Q + K * K) / a0; pa[1] = 2.0 * (K * K - 1.0) / a0; pa[2] = (1.0 - K / Q + K * K) / a0; /* fprintf(stderr, "%.14f %.14f %.14f %.14f %.14f\n", b1[0], b1[1], b1[2], a1[1], a1[2]); */ f0 = 38.13547087602444; Q = 0.5003270373238773; K = tan(M_PI * f0 / (double) st->samplerate); ra[1] = 2.0 * (K * K - 1.0) / (1.0 + K / Q + K * K); ra[2] = (1.0 - K / Q + K * K) / (1.0 + K / Q + K * K); /* fprintf(stderr, "%.14f %.14f\n", a2[1], a2[2]); */ st->d->b[0] = pb[0] * rb[0]; st->d->b[1] = pb[0] * rb[1] + pb[1] * rb[0]; st->d->b[2] = pb[0] * rb[2] + pb[1] * rb[1] + pb[2] * rb[0]; st->d->b[3] = pb[1] * rb[2] + pb[2] * rb[1]; st->d->b[4] = pb[2] * rb[2]; st->d->a[0] = pa[0] * ra[0]; st->d->a[1] = pa[0] * ra[1] + pa[1] * ra[0]; st->d->a[2] = pa[0] * ra[2] + pa[1] * ra[1] + pa[2] * ra[0]; st->d->a[3] = pa[1] * ra[2] + pa[2] * ra[1]; st->d->a[4] = pa[2] * ra[2]; st->d->v = (filter_state*) malloc(st->channels * sizeof(filter_state)); CHECK_ERROR(!st->d->v, EBUR128_ERROR_NOMEM, exit); for (i = 0; i < (int) st->channels; ++i) { for (j = 0; j < FILTER_STATE_SIZE; ++j) { st->d->v[i][j] = 0.0; } } exit: return errcode; } static int ebur128_init_channel_map(ebur128_state* st) { size_t i; st->d->channel_map = (int*) malloc(st->channels * sizeof(int)); if (!st->d->channel_map) { return EBUR128_ERROR_NOMEM; } if (st->channels == 4) { st->d->channel_map[0] = EBUR128_LEFT; st->d->channel_map[1] = EBUR128_RIGHT; st->d->channel_map[2] = EBUR128_LEFT_SURROUND; st->d->channel_map[3] = EBUR128_RIGHT_SURROUND; } else if (st->channels == 5) { st->d->channel_map[0] = EBUR128_LEFT; st->d->channel_map[1] = EBUR128_RIGHT; st->d->channel_map[2] = EBUR128_CENTER; st->d->channel_map[3] = EBUR128_LEFT_SURROUND; st->d->channel_map[4] = EBUR128_RIGHT_SURROUND; } else { for (i = 0; i < st->channels; ++i) { switch (i) { case 0: st->d->channel_map[i] = EBUR128_LEFT; break; case 1: st->d->channel_map[i] = EBUR128_RIGHT; break; case 2: st->d->channel_map[i] = EBUR128_CENTER; break; case 3: st->d->channel_map[i] = EBUR128_UNUSED; break; case 4: st->d->channel_map[i] = EBUR128_LEFT_SURROUND; break; case 5: st->d->channel_map[i] = EBUR128_RIGHT_SURROUND; break; default: st->d->channel_map[i] = EBUR128_UNUSED; break; } } } return EBUR128_SUCCESS; } static int ebur128_init_resampler(ebur128_state* st) { int errcode = EBUR128_SUCCESS; if (st->samplerate < 96000) { st->d->interp = interp_create(49, 4, st->channels); CHECK_ERROR(!st->d->interp, EBUR128_ERROR_NOMEM, exit) } else if (st->samplerate < 192000) { st->d->interp = interp_create(49, 2, st->channels); CHECK_ERROR(!st->d->interp, EBUR128_ERROR_NOMEM, exit) } else { st->d->resampler_buffer_input = NULL; st->d->resampler_buffer_output = NULL; st->d->interp = NULL; goto exit; } st->d->resampler_buffer_input_frames = st->d->samples_in_100ms * 4; st->d->resampler_buffer_input = (float*) malloc( st->d->resampler_buffer_input_frames * st->channels * sizeof(float)); CHECK_ERROR(!st->d->resampler_buffer_input, EBUR128_ERROR_NOMEM, free_interp) st->d->resampler_buffer_output_frames = st->d->resampler_buffer_input_frames * st->d->interp->factor; st->d->resampler_buffer_output = (float*) malloc( st->d->resampler_buffer_output_frames * st->channels * sizeof(float)); CHECK_ERROR(!st->d->resampler_buffer_output, EBUR128_ERROR_NOMEM, free_input) return errcode; free_interp: interp_destroy(st->d->interp); st->d->interp = NULL; free_input: free(st->d->resampler_buffer_input); st->d->resampler_buffer_input = NULL; exit: return errcode; } static void ebur128_destroy_resampler(ebur128_state* st) { free(st->d->resampler_buffer_input); st->d->resampler_buffer_input = NULL; free(st->d->resampler_buffer_output); st->d->resampler_buffer_output = NULL; interp_destroy(st->d->interp); st->d->interp = NULL; } void ebur128_get_version(int* major, int* minor, int* patch) { *major = EBUR128_VERSION_MAJOR; *minor = EBUR128_VERSION_MINOR; *patch = EBUR128_VERSION_PATCH; } #define VALIDATE_MAX_CHANNELS (64) #define VALIDATE_MAX_SAMPLERATE (2822400) #define VALIDATE_CHANNELS_AND_SAMPLERATE(err) \ do { \ if (channels == 0 || channels > VALIDATE_MAX_CHANNELS) { \ return (err); \ } \ \ if (samplerate < 16 || samplerate > VALIDATE_MAX_SAMPLERATE) { \ return (err); \ } \ } while (0); ebur128_state* ebur128_init(unsigned int channels, unsigned long samplerate, int mode) { int result; int errcode; ebur128_state* st; unsigned int i; size_t j; VALIDATE_CHANNELS_AND_SAMPLERATE(NULL); st = (ebur128_state*) malloc(sizeof(ebur128_state)); CHECK_ERROR(!st, 0, exit) st->d = (struct ebur128_state_internal*) malloc( sizeof(struct ebur128_state_internal)); CHECK_ERROR(!st->d, 0, free_state) st->channels = channels; errcode = ebur128_init_channel_map(st); CHECK_ERROR(errcode, 0, free_internal) st->d->sample_peak = (double*) malloc(channels * sizeof(double)); CHECK_ERROR(!st->d->sample_peak, 0, free_channel_map) st->d->prev_sample_peak = (double*) malloc(channels * sizeof(double)); CHECK_ERROR(!st->d->prev_sample_peak, 0, free_sample_peak) st->d->true_peak = (double*) malloc(channels * sizeof(double)); CHECK_ERROR(!st->d->true_peak, 0, free_prev_sample_peak) st->d->prev_true_peak = (double*) malloc(channels * sizeof(double)); CHECK_ERROR(!st->d->prev_true_peak, 0, free_true_peak) for (i = 0; i < channels; ++i) { st->d->sample_peak[i] = 0.0; st->d->prev_sample_peak[i] = 0.0; st->d->true_peak[i] = 0.0; st->d->prev_true_peak[i] = 0.0; } st->d->use_histogram = mode & EBUR128_MODE_HISTOGRAM ? 1 : 0; st->d->history = ULONG_MAX; st->samplerate = samplerate; st->d->samples_in_100ms = (st->samplerate + 5) / 10; st->mode = mode; if ((mode & EBUR128_MODE_S) == EBUR128_MODE_S) { st->d->window = 3000; } else if ((mode & EBUR128_MODE_M) == EBUR128_MODE_M) { st->d->window = 400; } else { goto free_prev_true_peak; } st->d->audio_data_frames = st->samplerate * st->d->window / 1000; if (st->d->audio_data_frames % st->d->samples_in_100ms) { /* round up to multiple of samples_in_100ms */ st->d->audio_data_frames = (st->d->audio_data_frames + st->d->samples_in_100ms) - (st->d->audio_data_frames % st->d->samples_in_100ms); } st->d->audio_data = (double*) malloc(st->d->audio_data_frames * st->channels * sizeof(double)); CHECK_ERROR(!st->d->audio_data, 0, free_prev_true_peak) for (j = 0; j < st->d->audio_data_frames * st->channels; ++j) { st->d->audio_data[j] = 0.0; } errcode = ebur128_init_filter(st); CHECK_ERROR(errcode, 0, free_audio_data) if (st->d->use_histogram) { st->d->block_energy_histogram = (unsigned long*) malloc(1000 * sizeof(unsigned long)); CHECK_ERROR(!st->d->block_energy_histogram, 0, free_filter) for (i = 0; i < 1000; ++i) { st->d->block_energy_histogram[i] = 0; } } else { st->d->block_energy_histogram = NULL; } if (st->d->use_histogram) { st->d->short_term_block_energy_histogram = (unsigned long*) malloc(1000 * sizeof(unsigned long)); CHECK_ERROR(!st->d->short_term_block_energy_histogram, 0, free_block_energy_histogram) for (i = 0; i < 1000; ++i) { st->d->short_term_block_energy_histogram[i] = 0; } } else { st->d->short_term_block_energy_histogram = NULL; } STAILQ_INIT(&st->d->block_list); st->d->block_list_size = 0; st->d->block_list_max = st->d->history / 100; STAILQ_INIT(&st->d->short_term_block_list); st->d->st_block_list_size = 0; st->d->st_block_list_max = st->d->history / 3000; st->d->short_term_frame_counter = 0; result = ebur128_init_resampler(st); CHECK_ERROR(result, 0, free_short_term_block_energy_histogram) /* the first block needs 400ms of audio data */ st->d->needed_frames = st->d->samples_in_100ms * 4; /* start at the beginning of the buffer */ st->d->audio_data_index = 0; /* initialize static constants */ relative_gate_factor = pow(10.0, relative_gate / 10.0); minus_twenty_decibels = pow(10.0, -20.0 / 10.0); histogram_energy_boundaries[0] = pow(10.0, (-70.0 + 0.691) / 10.0); if (st->d->use_histogram) { for (i = 0; i < 1000; ++i) { histogram_energies[i] = pow(10.0, ((double) i / 10.0 - 69.95 + 0.691) / 10.0); } for (i = 1; i < 1001; ++i) { histogram_energy_boundaries[i] = pow(10.0, ((double) i / 10.0 - 70.0 + 0.691) / 10.0); } } return st; free_short_term_block_energy_histogram: free(st->d->short_term_block_energy_histogram); free_block_energy_histogram: free(st->d->block_energy_histogram); free_filter: free(st->d->v); free_audio_data: free(st->d->audio_data); free_prev_true_peak: free(st->d->prev_true_peak); free_true_peak: free(st->d->true_peak); free_prev_sample_peak: free(st->d->prev_sample_peak); free_sample_peak: free(st->d->sample_peak); free_channel_map: free(st->d->channel_map); free_internal: free(st->d); free_state: free(st); exit: return NULL; } void ebur128_destroy(ebur128_state** st) { struct ebur128_dq_entry* entry; free((*st)->d->short_term_block_energy_histogram); free((*st)->d->block_energy_histogram); free((*st)->d->v); free((*st)->d->audio_data); free((*st)->d->channel_map); free((*st)->d->sample_peak); free((*st)->d->prev_sample_peak); free((*st)->d->true_peak); free((*st)->d->prev_true_peak); while (!STAILQ_EMPTY(&(*st)->d->block_list)) { entry = STAILQ_FIRST(&(*st)->d->block_list); STAILQ_REMOVE_HEAD(&(*st)->d->block_list, entries); free(entry); } while (!STAILQ_EMPTY(&(*st)->d->short_term_block_list)) { entry = STAILQ_FIRST(&(*st)->d->short_term_block_list); STAILQ_REMOVE_HEAD(&(*st)->d->short_term_block_list, entries); free(entry); } ebur128_destroy_resampler(*st); free((*st)->d); free(*st); *st = NULL; } static void ebur128_check_true_peak(ebur128_state* st, size_t frames) { size_t c, i, frames_out; frames_out = interp_process(st->d->interp, frames, st->d->resampler_buffer_input, st->d->resampler_buffer_output); for (i = 0; i < frames_out; ++i) { for (c = 0; c < st->channels; ++c) { double val = (double) st->d->resampler_buffer_output[i * st->channels + c]; if (EBUR128_MAX(val, -val) > st->d->prev_true_peak[c]) { st->d->prev_true_peak[c] = EBUR128_MAX(val, -val); } } } } #if defined(__SSE2_MATH__) || defined(_M_X64) || _M_IX86_FP >= 2 #include <xmmintrin.h> #define TURN_ON_FTZ \ unsigned int mxcsr = _mm_getcsr(); \ _mm_setcsr(mxcsr | _MM_FLUSH_ZERO_ON); #define TURN_OFF_FTZ _mm_setcsr(mxcsr); #define FLUSH_MANUALLY #else #warning "manual FTZ is being used, please enable SSE2 (-msse2 -mfpmath=sse)" #define TURN_ON_FTZ #define TURN_OFF_FTZ #define FLUSH_MANUALLY \ st->d->v[c][4] = fabs(st->d->v[c][4]) < DBL_MIN ? 0.0 : st->d->v[c][4]; \ st->d->v[c][3] = fabs(st->d->v[c][3]) < DBL_MIN ? 0.0 : st->d->v[c][3]; \ st->d->v[c][2] = fabs(st->d->v[c][2]) < DBL_MIN ? 0.0 : st->d->v[c][2]; \ st->d->v[c][1] = fabs(st->d->v[c][1]) < DBL_MIN ? 0.0 : st->d->v[c][1]; #endif #define EBUR128_FILTER(type, min_scale, max_scale) \ static void ebur128_filter_##type(ebur128_state* st, const type* src, \ size_t frames) { \ static double scaling_factor = \ EBUR128_MAX(-((double) (min_scale)), (double) (max_scale)); \ \ double* audio_data = st->d->audio_data + st->d->audio_data_index; \ size_t i, c; \ \ TURN_ON_FTZ \ \ if ((st->mode & EBUR128_MODE_SAMPLE_PEAK) == EBUR128_MODE_SAMPLE_PEAK) { \ for (c = 0; c < st->channels; ++c) { \ double max = 0.0; \ for (i = 0; i < frames; ++i) { \ double cur = (double) src[i * st->channels + c]; \ if (EBUR128_MAX(cur, -cur) > max) { \ max = EBUR128_MAX(cur, -cur); \ } \ } \ max /= scaling_factor; \ if (max > st->d->prev_sample_peak[c]) { \ st->d->prev_sample_peak[c] = max; \ } \ } \ } \ if ((st->mode & EBUR128_MODE_TRUE_PEAK) == EBUR128_MODE_TRUE_PEAK && \ st->d->interp) { \ for (i = 0; i < frames; ++i) { \ for (c = 0; c < st->channels; ++c) { \ st->d->resampler_buffer_input[i * st->channels + c] = \ (float) ((double) src[i * st->channels + c] / scaling_factor); \ } \ } \ ebur128_check_true_peak(st, frames); \ } \ for (c = 0; c < st->channels; ++c) { \ if (st->d->channel_map[c] == EBUR128_UNUSED) { \ continue; \ } \ for (i = 0; i < frames; ++i) { \ st->d->v[c][0] = \ (double) ((double) src[i * st->channels + c] / scaling_factor) - \ st->d->a[1] * st->d->v[c][1] - /**/ \ st->d->a[2] * st->d->v[c][2] - /**/ \ st->d->a[3] * st->d->v[c][3] - /**/ \ st->d->a[4] * st->d->v[c][4]; \ audio_data[i * st->channels + c] = /**/ \ st->d->b[0] * st->d->v[c][0] + /**/ \ st->d->b[1] * st->d->v[c][1] + /**/ \ st->d->b[2] * st->d->v[c][2] + /**/ \ st->d->b[3] * st->d->v[c][3] + /**/ \ st->d->b[4] * st->d->v[c][4]; \ st->d->v[c][4] = st->d->v[c][3]; \ st->d->v[c][3] = st->d->v[c][2]; \ st->d->v[c][2] = st->d->v[c][1]; \ st->d->v[c][1] = st->d->v[c][0]; \ } \ FLUSH_MANUALLY \ } \ TURN_OFF_FTZ \ } EBUR128_FILTER(short, SHRT_MIN, SHRT_MAX) EBUR128_FILTER(int, INT_MIN, INT_MAX) EBUR128_FILTER(float, -1.0f, 1.0f) EBUR128_FILTER(double, -1.0, 1.0) static double ebur128_energy_to_loudness(double energy) { return 10 * (log(energy) / log(10.0)) - 0.691; } static size_t find_histogram_index(double energy) { size_t index_min = 0; size_t index_max = 1000; size_t index_mid; do { index_mid = (index_min + index_max) / 2; if (energy >= histogram_energy_boundaries[index_mid]) { index_min = index_mid; } else { index_max = index_mid; } } while (index_max - index_min != 1); return index_min; } static int ebur128_calc_gating_block(ebur128_state* st, size_t frames_per_block, double* optional_output) { size_t i, c; double sum = 0.0; double channel_sum; for (c = 0; c < st->channels; ++c) { if (st->d->channel_map[c] == EBUR128_UNUSED) { continue; } channel_sum = 0.0; if (st->d->audio_data_index < frames_per_block * st->channels) { for (i = 0; i < st->d->audio_data_index / st->channels; ++i) { channel_sum += st->d->audio_data[i * st->channels + c] * st->d->audio_data[i * st->channels + c]; } for (i = st->d->audio_data_frames - (frames_per_block - st->d->audio_data_index / st->channels); i < st->d->audio_data_frames; ++i) { channel_sum += st->d->audio_data[i * st->channels + c] * st->d->audio_data[i * st->channels + c]; } } else { for (i = st->d->audio_data_index / st->channels - frames_per_block; i < st->d->audio_data_index / st->channels; ++i) { channel_sum += st->d->audio_data[i * st->channels + c] * st->d->audio_data[i * st->channels + c]; } } if (st->d->channel_map[c] == EBUR128_Mp110 || st->d->channel_map[c] == EBUR128_Mm110 || st->d->channel_map[c] == EBUR128_Mp060 || st->d->channel_map[c] == EBUR128_Mm060 || st->d->channel_map[c] == EBUR128_Mp090 || st->d->channel_map[c] == EBUR128_Mm090) { channel_sum *= 1.41; } else if (st->d->channel_map[c] == EBUR128_DUAL_MONO) { channel_sum *= 2.0; } sum += channel_sum; } sum /= (double) frames_per_block; if (optional_output) { *optional_output = sum; return EBUR128_SUCCESS; } if (sum >= histogram_energy_boundaries[0]) { if (st->d->use_histogram) { ++st->d->block_energy_histogram[find_histogram_index(sum)]; } else { struct ebur128_dq_entry* block; if (st->d->block_list_size == st->d->block_list_max) { block = STAILQ_FIRST(&st->d->block_list); STAILQ_REMOVE_HEAD(&st->d->block_list, entries); } else { block = (struct ebur128_dq_entry*) malloc(sizeof(struct ebur128_dq_entry)); if (!block) { return EBUR128_ERROR_NOMEM; } st->d->block_list_size++; } block->z = sum; STAILQ_INSERT_TAIL(&st->d->block_list, block, entries); } } return EBUR128_SUCCESS; } int ebur128_set_channel(ebur128_state* st, unsigned int channel_number, int value) { if (channel_number >= st->channels) { return EBUR128_ERROR_INVALID_CHANNEL_INDEX; } if (value == EBUR128_DUAL_MONO && (st->channels != 1 || channel_number != 0)) { fprintf(stderr, "EBUR128_DUAL_MONO only works with mono files!\n"); return EBUR128_ERROR_INVALID_CHANNEL_INDEX; } st->d->channel_map[channel_number] = value; return EBUR128_SUCCESS; } int ebur128_change_parameters(ebur128_state* st, unsigned int channels, unsigned long samplerate) { int errcode = EBUR128_SUCCESS; size_t j; /* This is needed to suppress a clang-tidy warning. */ #ifndef __has_builtin #define __has_builtin(x) 0 #endif #if __has_builtin(__builtin_unreachable) if (st->channels == 0) { __builtin_unreachable(); } #endif VALIDATE_CHANNELS_AND_SAMPLERATE(EBUR128_ERROR_NOMEM); if (channels == st->channels && samplerate == st->samplerate) { return EBUR128_ERROR_NO_CHANGE; } free(st->d->audio_data); st->d->audio_data = NULL; if (channels != st->channels) { unsigned int i; free(st->d->channel_map); st->d->channel_map = NULL; free(st->d->sample_peak); st->d->sample_peak = NULL; free(st->d->prev_sample_peak); st->d->prev_sample_peak = NULL; free(st->d->true_peak); st->d->true_peak = NULL; free(st->d->prev_true_peak); st->d->prev_true_peak = NULL; st->channels = channels; errcode = ebur128_init_channel_map(st); CHECK_ERROR(errcode, EBUR128_ERROR_NOMEM, exit) st->d->sample_peak = (double*) malloc(channels * sizeof(double)); CHECK_ERROR(!st->d->sample_peak, EBUR128_ERROR_NOMEM, exit) st->d->prev_sample_peak = (double*) malloc(channels * sizeof(double)); CHECK_ERROR(!st->d->prev_sample_peak, EBUR128_ERROR_NOMEM, exit) st->d->true_peak = (double*) malloc(channels * sizeof(double)); CHECK_ERROR(!st->d->true_peak, EBUR128_ERROR_NOMEM, exit) st->d->prev_true_peak = (double*) malloc(channels * sizeof(double)); CHECK_ERROR(!st->d->prev_true_peak, EBUR128_ERROR_NOMEM, exit) for (i = 0; i < channels; ++i) { st->d->sample_peak[i] = 0.0; st->d->prev_sample_peak[i] = 0.0; st->d->true_peak[i] = 0.0; st->d->prev_true_peak[i] = 0.0; } } if (samplerate != st->samplerate) { st->samplerate = samplerate; st->d->samples_in_100ms = (st->samplerate + 5) / 10; } /* If we're here, either samplerate or channels * have changed. Re-init filter. */ free(st->d->v); st->d->v = NULL; errcode = ebur128_init_filter(st); CHECK_ERROR(errcode, EBUR128_ERROR_NOMEM, exit) st->d->audio_data_frames = st->samplerate * st->d->window / 1000; if (st->d->audio_data_frames % st->d->samples_in_100ms) { /* round up to multiple of samples_in_100ms */ st->d->audio_data_frames = (st->d->audio_data_frames + st->d->samples_in_100ms) - (st->d->audio_data_frames % st->d->samples_in_100ms); } st->d->audio_data = (double*) malloc(st->d->audio_data_frames * st->channels * sizeof(double)); CHECK_ERROR(!st->d->audio_data, EBUR128_ERROR_NOMEM, exit) for (j = 0; j < st->d->audio_data_frames * st->channels; ++j) { st->d->audio_data[j] = 0.0; } ebur128_destroy_resampler(st); errcode = ebur128_init_resampler(st); CHECK_ERROR(errcode, EBUR128_ERROR_NOMEM, exit) /* the first block needs 400ms of audio data */ st->d->needed_frames = st->d->samples_in_100ms * 4; /* start at the beginning of the buffer */ st->d->audio_data_index = 0; /* reset short term frame counter */ st->d->short_term_frame_counter = 0; exit: return errcode; } int ebur128_set_max_window(ebur128_state* st, unsigned long window) { int errcode = EBUR128_SUCCESS; size_t j; if ((st->mode & EBUR128_MODE_S) == EBUR128_MODE_S && window < 3000) { window = 3000; } else if ((st->mode & EBUR128_MODE_M) == EBUR128_MODE_M && window < 400) { window = 400; } if (window == st->d->window) { return EBUR128_ERROR_NO_CHANGE; } size_t new_audio_data_frames; if (safe_size_mul(st->samplerate, window, &new_audio_data_frames) != 0 || new_audio_data_frames > ((size_t) -1) - st->d->samples_in_100ms) { return EBUR128_ERROR_NOMEM; } if (new_audio_data_frames % st->d->samples_in_100ms) { /* round up to multiple of samples_in_100ms */ new_audio_data_frames = (new_audio_data_frames + st->d->samples_in_100ms) - (new_audio_data_frames % st->d->samples_in_100ms); } size_t new_audio_data_size; if (safe_size_mul(new_audio_data_frames, st->channels * sizeof(double), &new_audio_data_size) != 0) { return EBUR128_ERROR_NOMEM; } double* new_audio_data = (double*) malloc(new_audio_data_size); CHECK_ERROR(!new_audio_data, EBUR128_ERROR_NOMEM, exit) st->d->window = window; free(st->d->audio_data); st->d->audio_data = new_audio_data; st->d->audio_data_frames = new_audio_data_frames; for (j = 0; j < st->d->audio_data_frames * st->channels; ++j) { st->d->audio_data[j] = 0.0; } /* the first block needs 400ms of audio data */ st->d->needed_frames = st->d->samples_in_100ms * 4; /* start at the beginning of the buffer */ st->d->audio_data_index = 0; /* reset short term frame counter */ st->d->short_term_frame_counter = 0; exit: return errcode; } int ebur128_set_max_history(ebur128_state* st, unsigned long history) { if ((st->mode & EBUR128_MODE_LRA) == EBUR128_MODE_LRA && history < 3000) { history = 3000; } else if ((st->mode & EBUR128_MODE_M) == EBUR128_MODE_M && history < 400) { history = 400; } if (history == st->d->history) { return EBUR128_ERROR_NO_CHANGE; } st->d->history = history; st->d->block_list_max = st->d->history / 100; st->d->st_block_list_max = st->d->history / 3000; while (st->d->block_list_size > st->d->block_list_max) { struct ebur128_dq_entry* block = STAILQ_FIRST(&st->d->block_list); STAILQ_REMOVE_HEAD(&st->d->block_list, entries); free(block); st->d->block_list_size--; } while (st->d->st_block_list_size > st->d->st_block_list_max) { struct ebur128_dq_entry* block = STAILQ_FIRST(&st->d->short_term_block_list); STAILQ_REMOVE_HEAD(&st->d->short_term_block_list, entries); free(block); st->d->st_block_list_size--; } return EBUR128_SUCCESS; } static int ebur128_energy_shortterm(ebur128_state* st, double* out); #define EBUR128_ADD_FRAMES(type) \ int ebur128_add_frames_##type(ebur128_state* st, const type* src, \ size_t frames) { \ size_t src_index = 0; \ unsigned int c = 0; \ for (c = 0; c < st->channels; c++) { \ st->d->prev_sample_peak[c] = 0.0; \ st->d->prev_true_peak[c] = 0.0; \ } \ while (frames > 0) { \ if (frames >= st->d->needed_frames) { \ ebur128_filter_##type(st, src + src_index, st->d->needed_frames); \ src_index += st->d->needed_frames * st->channels; \ frames -= st->d->needed_frames; \ st->d->audio_data_index += st->d->needed_frames * st->channels; \ /* calculate the new gating block */ \ if ((st->mode & EBUR128_MODE_I) == EBUR128_MODE_I) { \ if (ebur128_calc_gating_block(st, st->d->samples_in_100ms * 4, \ NULL)) { \ return EBUR128_ERROR_NOMEM; \ } \ } \ if ((st->mode & EBUR128_MODE_LRA) == EBUR128_MODE_LRA) { \ st->d->short_term_frame_counter += st->d->needed_frames; \ if (st->d->short_term_frame_counter == \ st->d->samples_in_100ms * 30) { \ struct ebur128_dq_entry* block; \ double st_energy; \ if (ebur128_energy_shortterm(st, &st_energy) == EBUR128_SUCCESS && \ st_energy >= histogram_energy_boundaries[0]) { \ if (st->d->use_histogram) { \ ++st->d->short_term_block_energy_histogram \ [find_histogram_index(st_energy)]; \ } else { \ if (st->d->st_block_list_size == st->d->st_block_list_max) { \ block = STAILQ_FIRST(&st->d->short_term_block_list); \ STAILQ_REMOVE_HEAD(&st->d->short_term_block_list, entries); \ } else { \ block = (struct ebur128_dq_entry*) malloc( \ sizeof(struct ebur128_dq_entry)); \ if (!block) { \ return EBUR128_ERROR_NOMEM; \ } \ st->d->st_block_list_size++; \ } \ block->z = st_energy; \ STAILQ_INSERT_TAIL(&st->d->short_term_block_list, block, \ entries); \ } \ } \ st->d->short_term_frame_counter = st->d->samples_in_100ms * 20; \ } \ } \ /* 100ms are needed for all blocks besides the first one */ \ st->d->needed_frames = st->d->samples_in_100ms; \ /* reset audio_data_index when buffer full */ \ if (st->d->audio_data_index == \ st->d->audio_data_frames * st->channels) { \ st->d->audio_data_index = 0; \ } \ } else { \ ebur128_filter_##type(st, src + src_index, frames); \ st->d->audio_data_index += frames * st->channels; \ if ((st->mode & EBUR128_MODE_LRA) == EBUR128_MODE_LRA) { \ st->d->short_term_frame_counter += frames; \ } \ st->d->needed_frames -= (unsigned long) frames; \ frames = 0; \ } \ } \ for (c = 0; c < st->channels; c++) { \ if (st->d->prev_sample_peak[c] > st->d->sample_peak[c]) { \ st->d->sample_peak[c] = st->d->prev_sample_peak[c]; \ } \ if (st->d->prev_true_peak[c] > st->d->true_peak[c]) { \ st->d->true_peak[c] = st->d->prev_true_peak[c]; \ } \ } \ return EBUR128_SUCCESS; \ } EBUR128_ADD_FRAMES(short) EBUR128_ADD_FRAMES(int) EBUR128_ADD_FRAMES(float) EBUR128_ADD_FRAMES(double) static int ebur128_calc_relative_threshold(ebur128_state* st, size_t* above_thresh_counter, double* relative_threshold) { struct ebur128_dq_entry* it; size_t i; if (st->d->use_histogram) { for (i = 0; i < 1000; ++i) { *relative_threshold += st->d->block_energy_histogram[i] * histogram_energies[i]; *above_thresh_counter += st->d->block_energy_histogram[i]; } } else { STAILQ_FOREACH(it, &st->d->block_list, entries) { ++*above_thresh_counter; *relative_threshold += it->z; } } return EBUR128_SUCCESS; } static int ebur128_gated_loudness(ebur128_state** sts, size_t size, double* out) { struct ebur128_dq_entry* it; double gated_loudness = 0.0; double relative_threshold = 0.0; size_t above_thresh_counter = 0; size_t i, j, start_index; for (i = 0; i < size; i++) { if (sts[i] && (sts[i]->mode & EBUR128_MODE_I) != EBUR128_MODE_I) { return EBUR128_ERROR_INVALID_MODE; } } for (i = 0; i < size; i++) { if (!sts[i]) { continue; } ebur128_calc_relative_threshold(sts[i], &above_thresh_counter, &relative_threshold); } if (!above_thresh_counter) { *out = -HUGE_VAL; return EBUR128_SUCCESS; } relative_threshold /= (double) above_thresh_counter; relative_threshold *= relative_gate_factor; above_thresh_counter = 0; if (relative_threshold < histogram_energy_boundaries[0]) { start_index = 0; } else { start_index = find_histogram_index(relative_threshold); if (relative_threshold > histogram_energies[start_index]) { ++start_index; } } for (i = 0; i < size; i++) { if (!sts[i]) { continue; } if (sts[i]->d->use_histogram) { for (j = start_index; j < 1000; ++j) { gated_loudness += sts[i]->d->block_energy_histogram[j] * histogram_energies[j]; above_thresh_counter += sts[i]->d->block_energy_histogram[j]; } } else { STAILQ_FOREACH(it, &sts[i]->d->block_list, entries) { if (it->z >= relative_threshold) { ++above_thresh_counter; gated_loudness += it->z; } } } } if (!above_thresh_counter) { *out = -HUGE_VAL; return EBUR128_SUCCESS; } gated_loudness /= (double) above_thresh_counter; *out = ebur128_energy_to_loudness(gated_loudness); return EBUR128_SUCCESS; } int ebur128_relative_threshold(ebur128_state* st, double* out) { double relative_threshold = 0.0; size_t above_thresh_counter = 0; if ((st->mode & EBUR128_MODE_I) != EBUR128_MODE_I) { return EBUR128_ERROR_INVALID_MODE; } ebur128_calc_relative_threshold(st, &above_thresh_counter, &relative_threshold); if (!above_thresh_counter) { *out = -70.0; return EBUR128_SUCCESS; } relative_threshold /= (double) above_thresh_counter; relative_threshold *= relative_gate_factor; *out = ebur128_energy_to_loudness(relative_threshold); return EBUR128_SUCCESS; } int ebur128_loudness_global(ebur128_state* st, double* out) { return ebur128_gated_loudness(&st, 1, out); } int ebur128_loudness_global_multiple(ebur128_state** sts, size_t size, double* out) { return ebur128_gated_loudness(sts, size, out); } static int ebur128_energy_in_interval(ebur128_state* st, size_t interval_frames, double* out) { if (interval_frames > st->d->audio_data_frames) { return EBUR128_ERROR_INVALID_MODE; } ebur128_calc_gating_block(st, interval_frames, out); return EBUR128_SUCCESS; } static int ebur128_energy_shortterm(ebur128_state* st, double* out) { return ebur128_energy_in_interval(st, st->d->samples_in_100ms * 30, out); } int ebur128_loudness_momentary(ebur128_state* st, double* out) { double energy; int error; error = ebur128_energy_in_interval(st, st->d->samples_in_100ms * 4, &energy); if (error) { return error; } if (energy <= 0.0) { *out = -HUGE_VAL; return EBUR128_SUCCESS; } *out = ebur128_energy_to_loudness(energy); return EBUR128_SUCCESS; } int ebur128_loudness_shortterm(ebur128_state* st, double* out) { double energy; int error; error = ebur128_energy_shortterm(st, &energy); if (error) { return error; } if (energy <= 0.0) { *out = -HUGE_VAL; return EBUR128_SUCCESS; } *out = ebur128_energy_to_loudness(energy); return EBUR128_SUCCESS; } int ebur128_loudness_window(ebur128_state* st, unsigned long window, double* out) { double energy; size_t interval_frames; int error; if (window > st->d->window) { return EBUR128_ERROR_INVALID_MODE; } interval_frames = st->samplerate * window / 1000; error = ebur128_energy_in_interval(st, interval_frames, &energy); if (error) { return error; } if (energy <= 0.0) { *out = -HUGE_VAL; return EBUR128_SUCCESS; } *out = ebur128_energy_to_loudness(energy); return EBUR128_SUCCESS; } static int ebur128_double_cmp(const void* p1, const void* p2) { const double* d1 = (const double*) p1; const double* d2 = (const double*) p2; return (*d1 > *d2) - (*d1 < *d2); } /* EBU - TECH 3342 */ int ebur128_loudness_range_multiple(ebur128_state** sts, size_t size, double* out) { size_t i, j; struct ebur128_dq_entry* it; double* stl_vector; size_t stl_size; double* stl_relgated; size_t stl_relgated_size; double stl_power, stl_integrated; /* High and low percentile energy */ double h_en, l_en; int use_histogram = 0; for (i = 0; i < size; ++i) { if (sts[i]) { if ((sts[i]->mode & EBUR128_MODE_LRA) != EBUR128_MODE_LRA) { return EBUR128_ERROR_INVALID_MODE; } if (i == 0 && sts[i]->mode & EBUR128_MODE_HISTOGRAM) { use_histogram = 1; } else if (use_histogram != !!(sts[i]->mode & EBUR128_MODE_HISTOGRAM)) { return EBUR128_ERROR_INVALID_MODE; } } } if (use_histogram) { unsigned long hist[1000] = { 0 }; size_t percentile_low, percentile_high; size_t index; stl_size = 0; stl_power = 0.0; for (i = 0; i < size; ++i) { if (!sts[i]) { continue; } for (j = 0; j < 1000; ++j) { hist[j] += sts[i]->d->short_term_block_energy_histogram[j]; stl_size += sts[i]->d->short_term_block_energy_histogram[j]; stl_power += sts[i]->d->short_term_block_energy_histogram[j] * histogram_energies[j]; } } if (!stl_size) { *out = 0.0; return EBUR128_SUCCESS; } stl_power /= stl_size; stl_integrated = minus_twenty_decibels * stl_power; if (stl_integrated < histogram_energy_boundaries[0]) { index = 0; } else { index = find_histogram_index(stl_integrated); if (stl_integrated > histogram_energies[index]) { ++index; } } stl_size = 0; for (j = index; j < 1000; ++j) { stl_size += hist[j]; } if (!stl_size) { *out = 0.0; return EBUR128_SUCCESS; } percentile_low = (size_t) ((stl_size - 1) * 0.1 + 0.5); percentile_high = (size_t) ((stl_size - 1) * 0.95 + 0.5); stl_size = 0; j = index; while (stl_size <= percentile_low) { stl_size += hist[j++]; } l_en = histogram_energies[j - 1]; while (stl_size <= percentile_high) { stl_size += hist[j++]; } h_en = histogram_energies[j - 1]; *out = ebur128_energy_to_loudness(h_en) - ebur128_energy_to_loudness(l_en); return EBUR128_SUCCESS; } stl_size = 0; for (i = 0; i < size; ++i) { if (!sts[i]) { continue; } STAILQ_FOREACH(it, &sts[i]->d->short_term_block_list, entries) { ++stl_size; } } if (!stl_size) { *out = 0.0; return EBUR128_SUCCESS; } stl_vector = (double*) malloc(stl_size * sizeof(double)); if (!stl_vector) { return EBUR128_ERROR_NOMEM; } j = 0; for (i = 0; i < size; ++i) { if (!sts[i]) { continue; } STAILQ_FOREACH(it, &sts[i]->d->short_term_block_list, entries) { stl_vector[j] = it->z; ++j; } } qsort(stl_vector, stl_size, sizeof(double), ebur128_double_cmp); stl_power = 0.0; for (i = 0; i < stl_size; ++i) { stl_power += stl_vector[i]; } stl_power /= (double) stl_size; stl_integrated = minus_twenty_decibels * stl_power; stl_relgated = stl_vector; stl_relgated_size = stl_size; while (stl_relgated_size > 0 && *stl_relgated < stl_integrated) { ++stl_relgated; --stl_relgated_size; } if (stl_relgated_size) { h_en = stl_relgated[(size_t) ((stl_relgated_size - 1) * 0.95 + 0.5)]; l_en = stl_relgated[(size_t) ((stl_relgated_size - 1) * 0.1 + 0.5)]; free(stl_vector); *out = ebur128_energy_to_loudness(h_en) - ebur128_energy_to_loudness(l_en); } else { free(stl_vector); *out = 0.0; } return EBUR128_SUCCESS; } int ebur128_loudness_range(ebur128_state* st, double* out) { return ebur128_loudness_range_multiple(&st, 1, out); } int ebur128_sample_peak(ebur128_state* st, unsigned int channel_number, double* out) { if ((st->mode & EBUR128_MODE_SAMPLE_PEAK) != EBUR128_MODE_SAMPLE_PEAK) { return EBUR128_ERROR_INVALID_MODE; } if (channel_number >= st->channels) { return EBUR128_ERROR_INVALID_CHANNEL_INDEX; } *out = st->d->sample_peak[channel_number]; return EBUR128_SUCCESS; } int ebur128_prev_sample_peak(ebur128_state* st, unsigned int channel_number, double* out) { if ((st->mode & EBUR128_MODE_SAMPLE_PEAK) != EBUR128_MODE_SAMPLE_PEAK) { return EBUR128_ERROR_INVALID_MODE; } if (channel_number >= st->channels) { return EBUR128_ERROR_INVALID_CHANNEL_INDEX; } *out = st->d->prev_sample_peak[channel_number]; return EBUR128_SUCCESS; } int ebur128_true_peak(ebur128_state* st, unsigned int channel_number, double* out) { if ((st->mode & EBUR128_MODE_TRUE_PEAK) != EBUR128_MODE_TRUE_PEAK) { return EBUR128_ERROR_INVALID_MODE; } if (channel_number >= st->channels) { return EBUR128_ERROR_INVALID_CHANNEL_INDEX; } *out = EBUR128_MAX(st->d->true_peak[channel_number], st->d->sample_peak[channel_number]); return EBUR128_SUCCESS; } int ebur128_prev_true_peak(ebur128_state* st, unsigned int channel_number, double* out) { if ((st->mode & EBUR128_MODE_TRUE_PEAK) != EBUR128_MODE_TRUE_PEAK) { return EBUR128_ERROR_INVALID_MODE; } if (channel_number >= st->channels) { return EBUR128_ERROR_INVALID_CHANNEL_INDEX; } *out = EBUR128_MAX(st->d->prev_true_peak[channel_number], st->d->prev_sample_peak[channel_number]); return EBUR128_SUCCESS; }
0
repos/libebur128/ebur128/queue
repos/libebur128/ebur128/queue/sys/queue.h
/* * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)queue.h 8.5 (Berkeley) 8/20/94 */ #ifndef _SYS_QUEUE_H_ #define _SYS_QUEUE_H_ /* * This file defines five types of data structures: singly-linked lists, * lists, simple queues, tail queues, and circular queues. * * A singly-linked list is headed by a single forward pointer. The * elements are singly linked for minimum space and pointer manipulation * overhead at the expense of O(n) removal for arbitrary elements. New * elements can be added to the list after an existing element or at the * head of the list. Elements being removed from the head of the list * should use the explicit macro for this purpose for optimum * efficiency. A singly-linked list may only be traversed in the forward * direction. Singly-linked lists are ideal for applications with large * datasets and few or no removals or for implementing a LIFO queue. * * A list is headed by a single forward pointer (or an array of forward * pointers for a hash table header). The elements are doubly linked * so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before * or after an existing element or at the head of the list. A list * may only be traversed in the forward direction. * * A simple queue is headed by a pair of pointers, one the head of the * list and the other to the tail of the list. The elements are singly * linked to save space, so elements can only be removed from the * head of the list. New elements can be added to the list after * an existing element, at the head of the list, or at the end of the * list. A simple queue may only be traversed in the forward direction. * * A tail queue is headed by a pair of pointers, one to the head of the * list and the other to the tail of the list. The elements are doubly * linked so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before or * after an existing element, at the head of the list, or at the end of * the list. A tail queue may be traversed in either direction. * * A circle queue is headed by a pair of pointers, one to the head of the * list and the other to the tail of the list. The elements are doubly * linked so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before or after * an existing element, at the head of the list, or at the end of the list. * A circle queue may be traversed in either direction, but has a more * complex end of list detection. * * For details on the use of these macros, see the queue(3) manual page. */ /* * List definitions. */ #define LIST_HEAD(name, type) \ struct name { \ struct type *lh_first; /* first element */ \ } #define LIST_HEAD_INITIALIZER(head) \ { NULL } #define LIST_ENTRY(type) \ struct { \ struct type *le_next; /* next element */ \ struct type **le_prev; /* address of previous next element */ \ } /* * List functions. */ #define LIST_INIT(head) do { \ (head)->lh_first = NULL; \ } while (/*CONSTCOND*/0) #define LIST_INSERT_AFTER(listelm, elm, field) do { \ if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ (listelm)->field.le_next->field.le_prev = \ &(elm)->field.le_next; \ (listelm)->field.le_next = (elm); \ (elm)->field.le_prev = &(listelm)->field.le_next; \ } while (/*CONSTCOND*/0) #define LIST_INSERT_BEFORE(listelm, elm, field) do { \ (elm)->field.le_prev = (listelm)->field.le_prev; \ (elm)->field.le_next = (listelm); \ *(listelm)->field.le_prev = (elm); \ (listelm)->field.le_prev = &(elm)->field.le_next; \ } while (/*CONSTCOND*/0) #define LIST_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.le_next = (head)->lh_first) != NULL) \ (head)->lh_first->field.le_prev = &(elm)->field.le_next;\ (head)->lh_first = (elm); \ (elm)->field.le_prev = &(head)->lh_first; \ } while (/*CONSTCOND*/0) #define LIST_REMOVE(elm, field) do { \ if ((elm)->field.le_next != NULL) \ (elm)->field.le_next->field.le_prev = \ (elm)->field.le_prev; \ *(elm)->field.le_prev = (elm)->field.le_next; \ } while (/*CONSTCOND*/0) #define LIST_FOREACH(var, head, field) \ for ((var) = ((head)->lh_first); \ (var); \ (var) = ((var)->field.le_next)) /* * List access methods. */ #define LIST_EMPTY(head) ((head)->lh_first == NULL) #define LIST_FIRST(head) ((head)->lh_first) #define LIST_NEXT(elm, field) ((elm)->field.le_next) /* * Singly-linked List definitions. */ #define SLIST_HEAD(name, type) \ struct name { \ struct type *slh_first; /* first element */ \ } #define SLIST_HEAD_INITIALIZER(head) \ { NULL } #define SLIST_ENTRY(type) \ struct { \ struct type *sle_next; /* next element */ \ } /* * Singly-linked List functions. */ #define SLIST_INIT(head) do { \ (head)->slh_first = NULL; \ } while (/*CONSTCOND*/0) #define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ (elm)->field.sle_next = (slistelm)->field.sle_next; \ (slistelm)->field.sle_next = (elm); \ } while (/*CONSTCOND*/0) #define SLIST_INSERT_HEAD(head, elm, field) do { \ (elm)->field.sle_next = (head)->slh_first; \ (head)->slh_first = (elm); \ } while (/*CONSTCOND*/0) #define SLIST_REMOVE_HEAD(head, field) do { \ (head)->slh_first = (head)->slh_first->field.sle_next; \ } while (/*CONSTCOND*/0) #define SLIST_REMOVE(head, elm, type, field) do { \ if ((head)->slh_first == (elm)) { \ SLIST_REMOVE_HEAD((head), field); \ } \ else { \ struct type *curelm = (head)->slh_first; \ while(curelm->field.sle_next != (elm)) \ curelm = curelm->field.sle_next; \ curelm->field.sle_next = \ curelm->field.sle_next->field.sle_next; \ } \ } while (/*CONSTCOND*/0) #define SLIST_FOREACH(var, head, field) \ for((var) = (head)->slh_first; (var); (var) = (var)->field.sle_next) /* * Singly-linked List access methods. */ #define SLIST_EMPTY(head) ((head)->slh_first == NULL) #define SLIST_FIRST(head) ((head)->slh_first) #define SLIST_NEXT(elm, field) ((elm)->field.sle_next) /* * Singly-linked Tail queue declarations. */ #define STAILQ_HEAD(name, type) \ struct name { \ struct type *stqh_first; /* first element */ \ struct type **stqh_last; /* addr of last next element */ \ } #define STAILQ_HEAD_INITIALIZER(head) \ { NULL, &(head).stqh_first } #define STAILQ_ENTRY(type) \ struct { \ struct type *stqe_next; /* next element */ \ } /* * Singly-linked Tail queue functions. */ #define STAILQ_INIT(head) do { \ (head)->stqh_first = NULL; \ (head)->stqh_last = &(head)->stqh_first; \ } while (/*CONSTCOND*/0) #define STAILQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.stqe_next = (head)->stqh_first) == NULL) \ (head)->stqh_last = &(elm)->field.stqe_next; \ (head)->stqh_first = (elm); \ } while (/*CONSTCOND*/0) #define STAILQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.stqe_next = NULL; \ *(head)->stqh_last = (elm); \ (head)->stqh_last = &(elm)->field.stqe_next; \ } while (/*CONSTCOND*/0) #define STAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.stqe_next = (listelm)->field.stqe_next) == NULL)\ (head)->stqh_last = &(elm)->field.stqe_next; \ (listelm)->field.stqe_next = (elm); \ } while (/*CONSTCOND*/0) #define STAILQ_REMOVE_HEAD(head, field) do { \ if (((head)->stqh_first = (head)->stqh_first->field.stqe_next) == NULL) \ (head)->stqh_last = &(head)->stqh_first; \ } while (/*CONSTCOND*/0) #define STAILQ_REMOVE(head, elm, type, field) do { \ if ((head)->stqh_first == (elm)) { \ STAILQ_REMOVE_HEAD((head), field); \ } else { \ struct type *curelm = (head)->stqh_first; \ while (curelm->field.stqe_next != (elm)) \ curelm = curelm->field.stqe_next; \ if ((curelm->field.stqe_next = \ curelm->field.stqe_next->field.stqe_next) == NULL) \ (head)->stqh_last = &(curelm)->field.stqe_next; \ } \ } while (/*CONSTCOND*/0) #define STAILQ_FOREACH(var, head, field) \ for ((var) = ((head)->stqh_first); \ (var); \ (var) = ((var)->field.stqe_next)) #define STAILQ_CONCAT(head1, head2) do { \ if (!STAILQ_EMPTY((head2))) { \ *(head1)->stqh_last = (head2)->stqh_first; \ (head1)->stqh_last = (head2)->stqh_last; \ STAILQ_INIT((head2)); \ } \ } while (/*CONSTCOND*/0) /* * Singly-linked Tail queue access methods. */ #define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) #define STAILQ_FIRST(head) ((head)->stqh_first) #define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) /* * Simple queue definitions. */ #define SIMPLEQ_HEAD(name, type) \ struct name { \ struct type *sqh_first; /* first element */ \ struct type **sqh_last; /* addr of last next element */ \ } #define SIMPLEQ_HEAD_INITIALIZER(head) \ { NULL, &(head).sqh_first } #define SIMPLEQ_ENTRY(type) \ struct { \ struct type *sqe_next; /* next element */ \ } /* * Simple queue functions. */ #define SIMPLEQ_INIT(head) do { \ (head)->sqh_first = NULL; \ (head)->sqh_last = &(head)->sqh_first; \ } while (/*CONSTCOND*/0) #define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \ (head)->sqh_last = &(elm)->field.sqe_next; \ (head)->sqh_first = (elm); \ } while (/*CONSTCOND*/0) #define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.sqe_next = NULL; \ *(head)->sqh_last = (elm); \ (head)->sqh_last = &(elm)->field.sqe_next; \ } while (/*CONSTCOND*/0) #define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\ (head)->sqh_last = &(elm)->field.sqe_next; \ (listelm)->field.sqe_next = (elm); \ } while (/*CONSTCOND*/0) #define SIMPLEQ_REMOVE_HEAD(head, field) do { \ if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ (head)->sqh_last = &(head)->sqh_first; \ } while (/*CONSTCOND*/0) #define SIMPLEQ_REMOVE(head, elm, type, field) do { \ if ((head)->sqh_first == (elm)) { \ SIMPLEQ_REMOVE_HEAD((head), field); \ } else { \ struct type *curelm = (head)->sqh_first; \ while (curelm->field.sqe_next != (elm)) \ curelm = curelm->field.sqe_next; \ if ((curelm->field.sqe_next = \ curelm->field.sqe_next->field.sqe_next) == NULL) \ (head)->sqh_last = &(curelm)->field.sqe_next; \ } \ } while (/*CONSTCOND*/0) #define SIMPLEQ_FOREACH(var, head, field) \ for ((var) = ((head)->sqh_first); \ (var); \ (var) = ((var)->field.sqe_next)) /* * Simple queue access methods. */ #define SIMPLEQ_EMPTY(head) ((head)->sqh_first == NULL) #define SIMPLEQ_FIRST(head) ((head)->sqh_first) #define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) /* * Tail queue definitions. */ #define _TAILQ_HEAD(name, type, qual) \ struct name { \ qual type *tqh_first; /* first element */ \ qual type *qual *tqh_last; /* addr of last next element */ \ } #define TAILQ_HEAD(name, type) _TAILQ_HEAD(name, struct type,) #define TAILQ_HEAD_INITIALIZER(head) \ { NULL, &(head).tqh_first } #define _TAILQ_ENTRY(type, qual) \ struct { \ qual type *tqe_next; /* next element */ \ qual type *qual *tqe_prev; /* address of previous next element */\ } #define TAILQ_ENTRY(type) _TAILQ_ENTRY(struct type,) /* * Tail queue functions. */ #define TAILQ_INIT(head) do { \ (head)->tqh_first = NULL; \ (head)->tqh_last = &(head)->tqh_first; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ (head)->tqh_first->field.tqe_prev = \ &(elm)->field.tqe_next; \ else \ (head)->tqh_last = &(elm)->field.tqe_next; \ (head)->tqh_first = (elm); \ (elm)->field.tqe_prev = &(head)->tqh_first; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.tqe_next = NULL; \ (elm)->field.tqe_prev = (head)->tqh_last; \ *(head)->tqh_last = (elm); \ (head)->tqh_last = &(elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ (elm)->field.tqe_next->field.tqe_prev = \ &(elm)->field.tqe_next; \ else \ (head)->tqh_last = &(elm)->field.tqe_next; \ (listelm)->field.tqe_next = (elm); \ (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ (elm)->field.tqe_next = (listelm); \ *(listelm)->field.tqe_prev = (elm); \ (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_REMOVE(head, elm, field) do { \ if (((elm)->field.tqe_next) != NULL) \ (elm)->field.tqe_next->field.tqe_prev = \ (elm)->field.tqe_prev; \ else \ (head)->tqh_last = (elm)->field.tqe_prev; \ *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_FOREACH(var, head, field) \ for ((var) = ((head)->tqh_first); \ (var); \ (var) = ((var)->field.tqe_next)) #define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ for ((var) = (*(((struct headname *)((head)->tqh_last))->tqh_last)); \ (var); \ (var) = (*(((struct headname *)((var)->field.tqe_prev))->tqh_last))) #define TAILQ_CONCAT(head1, head2, field) do { \ if (!TAILQ_EMPTY(head2)) { \ *(head1)->tqh_last = (head2)->tqh_first; \ (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ (head1)->tqh_last = (head2)->tqh_last; \ TAILQ_INIT((head2)); \ } \ } while (/*CONSTCOND*/0) /* * Tail queue access methods. */ #define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) #define TAILQ_FIRST(head) ((head)->tqh_first) #define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) #define TAILQ_LAST(head, headname) \ (*(((struct headname *)((head)->tqh_last))->tqh_last)) #define TAILQ_PREV(elm, headname, field) \ (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) /* * Circular queue definitions. */ #define CIRCLEQ_HEAD(name, type) \ struct name { \ struct type *cqh_first; /* first element */ \ struct type *cqh_last; /* last element */ \ } #define CIRCLEQ_HEAD_INITIALIZER(head) \ { (void *)&head, (void *)&head } #define CIRCLEQ_ENTRY(type) \ struct { \ struct type *cqe_next; /* next element */ \ struct type *cqe_prev; /* previous element */ \ } /* * Circular queue functions. */ #define CIRCLEQ_INIT(head) do { \ (head)->cqh_first = (void *)(head); \ (head)->cqh_last = (void *)(head); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ (elm)->field.cqe_next = (listelm)->field.cqe_next; \ (elm)->field.cqe_prev = (listelm); \ if ((listelm)->field.cqe_next == (void *)(head)) \ (head)->cqh_last = (elm); \ else \ (listelm)->field.cqe_next->field.cqe_prev = (elm); \ (listelm)->field.cqe_next = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do { \ (elm)->field.cqe_next = (listelm); \ (elm)->field.cqe_prev = (listelm)->field.cqe_prev; \ if ((listelm)->field.cqe_prev == (void *)(head)) \ (head)->cqh_first = (elm); \ else \ (listelm)->field.cqe_prev->field.cqe_next = (elm); \ (listelm)->field.cqe_prev = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_HEAD(head, elm, field) do { \ (elm)->field.cqe_next = (head)->cqh_first; \ (elm)->field.cqe_prev = (void *)(head); \ if ((head)->cqh_last == (void *)(head)) \ (head)->cqh_last = (elm); \ else \ (head)->cqh_first->field.cqe_prev = (elm); \ (head)->cqh_first = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.cqe_next = (void *)(head); \ (elm)->field.cqe_prev = (head)->cqh_last; \ if ((head)->cqh_first == (void *)(head)) \ (head)->cqh_first = (elm); \ else \ (head)->cqh_last->field.cqe_next = (elm); \ (head)->cqh_last = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_REMOVE(head, elm, field) do { \ if ((elm)->field.cqe_next == (void *)(head)) \ (head)->cqh_last = (elm)->field.cqe_prev; \ else \ (elm)->field.cqe_next->field.cqe_prev = \ (elm)->field.cqe_prev; \ if ((elm)->field.cqe_prev == (void *)(head)) \ (head)->cqh_first = (elm)->field.cqe_next; \ else \ (elm)->field.cqe_prev->field.cqe_next = \ (elm)->field.cqe_next; \ } while (/*CONSTCOND*/0) #define CIRCLEQ_FOREACH(var, head, field) \ for ((var) = ((head)->cqh_first); \ (var) != (const void *)(head); \ (var) = ((var)->field.cqe_next)) #define CIRCLEQ_FOREACH_REVERSE(var, head, field) \ for ((var) = ((head)->cqh_last); \ (var) != (const void *)(head); \ (var) = ((var)->field.cqe_prev)) /* * Circular queue access methods. */ #define CIRCLEQ_EMPTY(head) ((head)->cqh_first == (void *)(head)) #define CIRCLEQ_FIRST(head) ((head)->cqh_first) #define CIRCLEQ_LAST(head) ((head)->cqh_last) #define CIRCLEQ_NEXT(elm, field) ((elm)->field.cqe_next) #define CIRCLEQ_PREV(elm, field) ((elm)->field.cqe_prev) #define CIRCLEQ_LOOP_NEXT(head, elm, field) \ (((elm)->field.cqe_next == (void *)(head)) \ ? ((head)->cqh_first) \ : (elm->field.cqe_next)) #define CIRCLEQ_LOOP_PREV(head, elm, field) \ (((elm)->field.cqe_prev == (void *)(head)) \ ? ((head)->cqh_last) \ : (elm->field.cqe_prev)) #endif /* sys/queue.h */
0
repos
repos/zigpkgs/default.nix
(import ( fetchTarball { url = "https://github.com/edolstra/flake-compat/archive/12c64ca55c1014cdc1b16ed5a804aa8576601ff2.tar.gz"; sha256 = "hY8g6H2KFL8ownSiFeMOjwPC8P0ueXpCVEbxgda3pko="; }) { src = ./.; }).defaultNix
0
repos
repos/zigpkgs/README.md
# zigpkgs A collection of Zig packages built with Nix For a list of all packages, see `flake.nix`. ## Usage ### Using flakes (recommended) Try out a package in a `nix shell` environment: ```shell nix shell github:joachimschmidt557/zigpkgs#zigmod ``` Install a package into your profile: ```shell nix profile install github:joachimschmidt557/zigpkgs#zls ``` ### No flake support Install a package into your profile: ```shell nix-env -f https://github.com/joachimschmidt557/zigpkgs/archive/trunk.tar.gz -iA packages.x86_64-linux.zls ``` ### Cachix support All packages in the collection are built on every push to the `trunk` branch and pushed to a Cachix cache via GitHub Actions. It is possible to add this cache to your Nix configuration so that Nix doesn't need to build every package from scratch. See the [Cachix docs](https://docs.cachix.org/) for more information. ```shell cachix add zigpkgs ```
0
repos
repos/zigpkgs/flake.nix
{ description = "A collection of Zig packages"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; flake-utils.url = "github:numtide/flake-utils"; zig-overlay.url = "github:mitchellh/zig-overlay"; }; outputs = { self, nixpkgs, flake-utils, zig-overlay }: let systems = [ "x86_64-linux" "aarch64-linux" "x86_64-darwin" "aarch64-darwin" ]; hydraSystems = [ "x86_64-linux" ]; in flake-utils.lib.eachSystem systems (system: { packages = let pkgs = nixpkgs.legacyPackages.${system}; buildZig_0_9_0_Project = pkgs.callPackage ./pkgs/development/build-zig-project.nix { zig = zig-overlay.packages.${system}."0.9.0"; }; buildZig_0_10_0_Project = pkgs.callPackage ./pkgs/development/build-zig-project.nix { zig = zig-overlay.packages.${system}."0.10.0"; }; buildZig_0_11_0_Project = pkgs.callPackage ./pkgs/development/build-zig-project.nix { zig = zig-overlay.packages.${system}."0.11.0"; }; buildZigNightlyProject = pkgs.callPackage ./pkgs/development/build-zig-project.nix { zig = zig-overlay.packages.${system}.master; }; in { aro = pkgs.callPackage ./pkgs/aro { buildZigProject = buildZigNightlyProject; }; bork = pkgs.callPackage ./pkgs/bork { buildZigProject = buildZig_0_9_0_Project; }; brightnessztl = pkgs.callPackage ./pkgs/brightnessztl { buildZigProject = buildZig_0_11_0_Project; }; gyro = pkgs.callPackage ./pkgs/gyro { buildZigProject = buildZigNightlyProject; }; vpkz = pkgs.callPackage ./pkgs/vpkz { buildZigProject = buildZigNightlyProject; }; zig-doctest = pkgs.callPackage ./pkgs/zig-doctest { buildZigProject = buildZigNightlyProject; }; zigfd = pkgs.callPackage ./pkgs/zigfd { buildZigProject = buildZigNightlyProject; }; zigmod = pkgs.callPackage ./pkgs/zigmod { buildZigProject = buildZigNightlyProject; }; zls = pkgs.callPackage ./pkgs/zls { buildZigProject = buildZigNightlyProject; }; }; } ) // { hydraJobs = builtins.foldl' nixpkgs.lib.recursiveUpdate { } (builtins.map # Turn system.pname into pname.system (system: builtins.mapAttrs (pname: pkg: { ${system} = pkg; }) self.packages.${system}) hydraSystems); }; }
0
repos
repos/zigpkgs/flake.lock
{ "nodes": { "flake-compat": { "flake": false, "locked": { "lastModified": 1673956053, "narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=", "owner": "edolstra", "repo": "flake-compat", "rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9", "type": "github" }, "original": { "owner": "edolstra", "repo": "flake-compat", "type": "github" } }, "flake-utils": { "inputs": { "systems": "systems" }, "locked": { "lastModified": 1694529238, "narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=", "owner": "numtide", "repo": "flake-utils", "rev": "ff7b65b44d01cf9ba6a71320833626af21126384", "type": "github" }, "original": { "owner": "numtide", "repo": "flake-utils", "type": "github" } }, "flake-utils_2": { "locked": { "lastModified": 1659877975, "narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=", "owner": "numtide", "repo": "flake-utils", "rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0", "type": "github" }, "original": { "owner": "numtide", "repo": "flake-utils", "type": "github" } }, "nixpkgs": { "locked": { "lastModified": 1700794826, "narHash": "sha256-RyJTnTNKhO0yqRpDISk03I/4A67/dp96YRxc86YOPgU=", "owner": "NixOS", "repo": "nixpkgs", "rev": "5a09cb4b393d58f9ed0d9ca1555016a8543c2ac8", "type": "github" }, "original": { "owner": "NixOS", "ref": "nixos-unstable", "repo": "nixpkgs", "type": "github" } }, "nixpkgs_2": { "locked": { "lastModified": 1689088367, "narHash": "sha256-Y2tl2TlKCWEHrOeM9ivjCLlRAKH3qoPUE/emhZECU14=", "owner": "NixOS", "repo": "nixpkgs", "rev": "5c9ddb86679c400d6b7360797b8a22167c2053f8", "type": "github" }, "original": { "owner": "NixOS", "ref": "release-23.05", "repo": "nixpkgs", "type": "github" } }, "root": { "inputs": { "flake-utils": "flake-utils", "nixpkgs": "nixpkgs", "zig-overlay": "zig-overlay" } }, "systems": { "locked": { "lastModified": 1681028828, "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", "owner": "nix-systems", "repo": "default", "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", "type": "github" }, "original": { "owner": "nix-systems", "repo": "default", "type": "github" } }, "zig-overlay": { "inputs": { "flake-compat": "flake-compat", "flake-utils": "flake-utils_2", "nixpkgs": "nixpkgs_2" }, "locked": { "lastModified": 1701000474, "narHash": "sha256-M/nfodghuNn9nhIYLiRWyddqIAVBHox32FimE1iUink=", "owner": "mitchellh", "repo": "zig-overlay", "rev": "a8b011878747485fed674ef7d0b34bd59f164aff", "type": "github" }, "original": { "owner": "mitchellh", "repo": "zig-overlay", "type": "github" } } }, "root": "root", "version": 7 }
0
repos/zigpkgs/pkgs
repos/zigpkgs/pkgs/brightnessztl/default.nix
{ lib , fetchFromGitHub , buildZigProject , pkg-config , systemd , logindSupport ? true }: buildZigProject rec { pname = "brightnessztl-unstable"; version = "2023-11-26"; src = fetchFromGitHub { owner = "hspak"; repo = "brightnessztl"; rev = "d20672ac818553df804996a3fd6122b4c4f88296"; hash = "sha256-gOfb3+74JfKUirhsScOMz59FkItU8sS3bM9b8xnvFok="; }; nativeBuildInputs = lib.optional logindSupport pkg-config; buildInputs = lib.optional logindSupport systemd; options = [ "-Dcpu=baseline" "-Dlogind=${lib.boolToString logindSupport}" "-Doptimize=ReleaseSafe" ]; meta = with lib; { homepage = "https://github.com/hspak/brightnessztl"; description = " A CLI to control device backlight"; license = licenses.mit; platforms = platforms.linux; maintainers = with maintainers; [ joachimschmidt557 ]; }; }
0
repos/zigpkgs/pkgs
repos/zigpkgs/pkgs/zls/default.nix
{ lib , stdenv , fetchFromGitHub , buildZigProject }: buildZigProject { pname = "zls-unstable"; version = "2023-01-20"; src = fetchFromGitHub { owner = "zigtools"; repo = "zls"; rev = "1ed8d49b305a4ed03578eb251b18e5bd193ec04c"; sha256 = "MxTgzQE1UI2Bc1mSQGP/mxErqp7e0QU3lerp3KlCNJ0="; fetchSubmodules = true; }; options = [ "-Drelease-safe" "-Dcpu=baseline" ]; meta = with lib; { homepage = "https://github.com/zigtools/zls"; description = "The officially unofficial Zig language server"; license = licenses.mit; platforms = platforms.linux; maintainers = with maintainers; [ joachimschmidt557 ]; broken = true; }; }