Skip to main content

singe_cuda/device/
mod.rs

1//! Device enumeration, properties, attributes, and peer capabilities.
2
3#![expect(
4    deprecated,
5    reason = "wraps deprecated upstream API values that remain part of the supported surface"
6)]
7
8mod attribute;
9mod clique;
10mod properties;
11
12use std::{
13    ffi::{CString, c_char},
14    mem,
15};
16
17use num_enum::{IntoPrimitive, TryFromPrimitive};
18use singe_core::{impl_enum_display, string_from_c_chars};
19use singe_cuda_sys::runtime;
20
21use crate::{
22    context::ContextFlags,
23    error::{Error, Result},
24    try_ffi,
25    types::FunctionCache,
26    utility::to_usize,
27};
28
29pub use self::{
30    attribute::DeviceAttribute,
31    clique::{CliqueInfo, CliqueType},
32    properties::{DeviceProperties, Uuid},
33};
34
35singe_core::native_enum! {
36    /// CUDA Limits.
37    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
38    #[repr(u32)]
39    #[non_exhaustive]
40    pub enum Limit: runtime::cudaLimit {
41        /// Per-block memory size.
42        PerBlockMemorySize = cudaLimitPerBlockMemorySize,
43        /// GPU thread stack size.
44        StackSize = cudaLimitStackSize,
45        /// GPU printf FIFO size.
46        PrintfFifoSize = cudaLimitPrintfFifoSize,
47        /// GPU malloc heap size.
48        MallocHeapSize = cudaLimitMallocHeapSize,
49        /// GPU device runtime synchronize depth.
50        DevRuntimeSyncDepth = cudaLimitDevRuntimeSyncDepth,
51        /// GPU device runtime pending launch count.
52        DevRuntimePendingLaunchCount = cudaLimitDevRuntimePendingLaunchCount,
53        /// A value between 0 and 128 that indicates the maximum fetch granularity of L2, in bytes.
54        /// The value is a hint.
55        MaxL2FetchGranularity = cudaLimitMaxL2FetchGranularity,
56        /// A size in bytes for L2 persisting lines cache size.
57        PersistingL2CacheSize = cudaLimitPersistingL2CacheSize,
58    }
59}
60
61impl_enum_display!(Limit, {
62    Self::PerBlockMemorySize => "cudaLimitPerBlockMemorySize",
63    Self::StackSize => "cudaLimitStackSize",
64    Self::PrintfFifoSize => "cudaLimitPrintfFifoSize",
65    Self::MallocHeapSize => "cudaLimitMallocHeapSize",
66    Self::DevRuntimeSyncDepth => "cudaLimitDevRuntimeSyncDepth",
67    Self::DevRuntimePendingLaunchCount => "cudaLimitDevRuntimePendingLaunchCount",
68    Self::MaxL2FetchGranularity => "cudaLimitMaxL2FetchGranularity",
69    Self::PersistingL2CacheSize => "cudaLimitPersistingL2CacheSize",
70});
71
72singe_core::native_enum! {
73    /// CUDA device compute modes.
74    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
75    #[repr(u32)]
76    #[non_exhaustive]
77    pub enum ComputeMode: runtime::cudaComputeMode {
78        /// Default compute mode; multiple threads can use [`Device::set_current`] with this device.
79        Default = cudaComputeModeDefault,
80        /// Compute-exclusive-thread mode; only one thread in one process can use [`Device::set_current`] with this device.
81        Exclusive = cudaComputeModeExclusive,
82        /// Compute-prohibited mode; no threads can use [`Device::set_current`] with this device.
83        Prohibited = cudaComputeModeProhibited,
84        /// Compute-exclusive-process mode; many threads in one process can use [`Device::set_current`] with this device.
85        ExclusiveProcess = cudaComputeModeExclusiveProcess,
86    }
87}
88
89singe_core::native_enum! {
90    /// Attributes queryable between two devices using [`Device::p2p_attribute`].
91    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
92    #[repr(u32)]
93    #[non_exhaustive]
94    pub enum PeerToPeerAttribute: runtime::cudaDeviceP2PAttr {
95        /// Relative performance rank of the link between two devices.
96        PerformanceRank = CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK,
97        /// Whether peer access is supported between the devices.
98        AccessSupported = CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED,
99        /// Whether all CUDA-valid native atomic operations are supported over the peer link.
100        NativeAtomicSupported = CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED,
101        /// Deprecated selector for CUDA array peer-access support.
102        #[deprecated]
103        CudaArrayAccessSupported = CU_DEVICE_P2P_ATTRIBUTE_ACCESS_ACCESS_SUPPORTED,
104    }
105}
106
107impl_enum_display!(PeerToPeerAttribute, {
108    Self::PerformanceRank => "cudaDevP2PAttrPerformanceRank",
109    Self::AccessSupported => "cudaDevP2PAttrAccessSupported",
110    Self::NativeAtomicSupported => "cudaDevP2PAttrNativeAtomicSupported",
111    Self::CudaArrayAccessSupported => "cudaDevP2PAttrCudaArrayAccessSupported",
112});
113
114/// Inclusive stream priority limits supported by the current device.
115///
116/// Lower numeric values represent higher priorities.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118pub struct StreamPriorityRange {
119    /// Least supported priority, with the highest numeric value.
120    pub least: i32,
121    /// Greatest supported priority, with the lowest numeric value.
122    pub greatest: i32,
123}
124
125/// A CUDA device ordinal.
126///
127/// The value does not own a CUDA context or validate device availability until an operation queries CUDA.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
129pub struct Device(DeviceId);
130
131/// Signed CUDA device ordinal used by runtime and driver APIs.
132pub type DeviceId = i32;
133
134impl Device {
135    /// Wraps a device ordinal without querying CUDA, validating it, or making the device current.
136    #[must_use]
137    pub const fn new(id: DeviceId) -> Self {
138        Self(id)
139    }
140
141    /// Returns the number of devices with compute capability greater or equal to 2.0 that are available for execution.
142    ///
143    /// # Errors
144    ///
145    /// Returns an error if CUDA cannot query the device count, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics such as [`crate::error::Status::NotInitialized`], [`crate::error::Status::CallRequiresNewerDriver`], or [`crate::error::Status::NoDevice`].
146    pub fn count() -> Result<i32> {
147        let mut count: i32 = 0;
148        // SAFETY: `count` is a local that `cudaGetDeviceCount` writes through an exclusive pointer.
149        unsafe {
150            try_ffi!(runtime::cudaGetDeviceCount(&raw mut count))?;
151        }
152        Ok(count)
153    }
154
155    /// Returns the current device for the calling host thread.
156    ///
157    /// # Errors
158    ///
159    /// Returns an error if CUDA cannot query the current device, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
160    pub fn current() -> Result<Self> {
161        let mut device_id: i32 = 0;
162        // SAFETY: `device_id` is a local that `cudaGetDevice` writes through an exclusive pointer.
163        unsafe {
164            try_ffi!(runtime::cudaGetDevice(&raw mut device_id))?;
165        }
166        Ok(Self(device_id))
167    }
168
169    /// Blocks until the device has completed all preceding requested tasks.
170    /// [`Device::synchronize`] returns an error if one of the preceding tasks has failed.
171    /// If [`ContextFlags::SCHEDULE_BLOCKING_SYNC`] was set for this device, the host thread blocks until the device has finished its work.
172    ///
173    /// * Use of [`Device::synchronize`] in device code was deprecated in CUDA 11.6 and removed for `compute_90`+ compilation.
174    ///   For compute capability &lt; 9.0, compile-time opt-in with `-D CUDA_FORCE_CDP1_IF_SUPPORTED` is required to continue using [`Device::synchronize`] in device code for now.
175    ///   This is different from host-side [`Device::synchronize`], which is still supported.
176    ///
177    /// # Errors
178    ///
179    /// Returns an error if synchronization fails, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
180    pub fn synchronize() -> Result<()> {
181        // SAFETY: `cudaDeviceSynchronize` takes no arguments and only waits for work on the current device.
182        unsafe {
183            try_ffi!(runtime::cudaDeviceSynchronize())?;
184        }
185        Ok(())
186    }
187
188    /// Explicitly destroys and cleans up all resources associated with the current device in the current process.
189    /// Accessing these resources or passing them to subsequent API calls after reset results in undefined behavior.
190    /// These resources include streams, events, arrays, mipmapped arrays, pitched allocations, texture and surface objects, external memory and semaphore objects, and graphics resources owned by the current device state.
191    /// These resources also include memory allocations by [`DeviceMemory::alloc`](crate::memory::DeviceMemory::alloc), [`PinnedHost`](crate::memory::PinnedHost), [`DeviceMemory::alloc_managed`](crate::memory::DeviceMemory::alloc_managed), and [`PitchedDeviceMemory`](crate::memory::PitchedDeviceMemory).
192    /// Any subsequent call to this device reinitializes it.
193    ///
194    /// This call resets the device immediately.
195    /// Ensure that no other host threads in the process are accessing the device when this is called.
196    ///
197    /// * [`Device::reset`] does not destroy memory allocated by [`DeviceMemory::alloc_async`](crate::memory::DeviceMemory::alloc_async) or [`sys::cudaMallocFromPoolAsync`](singe_cuda_sys::runtime::cudaMallocFromPoolAsync).
198    ///   These memory allocations must be destroyed explicitly.
199    /// * If a non-primary CUDA context is current to the thread, [`Device::reset`] will destroy only the internal CUDA runtime state for that context.
200    ///
201    /// # Safety
202    ///
203    /// All affected resources must have been released and all work completed.
204    /// Exclude other host threads and any later use of pre-reset owners or handles.
205    ///
206    /// # Errors
207    ///
208    /// Returns an error if device reset fails, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
209    pub unsafe fn reset() -> Result<()> {
210        // SAFETY: the caller guarantees every resource of the device is released, its work is complete, and no other thread uses it.
211        unsafe {
212            try_ffi!(runtime::cudaDeviceReset())?;
213        }
214        Ok(())
215    }
216
217    /// Returns the current size of limit.
218    /// The following [`Limit`] values are supported.
219    ///
220    /// * [`Limit::StackSize`] is the stack size in bytes of each GPU thread.
221    /// * [`Limit::PrintfFifoSize`] is the size in bytes of the shared FIFO used by the `printf()` device system call.
222    /// * [`Limit::MallocHeapSize`] is the size in bytes of the heap used by the `malloc()` and `free()` device system calls.
223    /// * [`Limit::DevRuntimeSyncDepth`] is the maximum grid depth at which a thread can issue the device runtime call [`Device::synchronize`] to wait on child grid launches to complete.
224    ///   This feature is removed for devices of compute capability &gt;= 9.0, so such devices return [`crate::error::Status::UnsupportedLimit`].
225    /// * [`Limit::DevRuntimePendingLaunchCount`] is the maximum number of outstanding device runtime launches.
226    /// * [`Limit::MaxL2FetchGranularity`] is the L2 cache fetch granularity.
227    /// * [`Limit::PersistingL2CacheSize`] is the persisting L2 cache size in bytes.
228    ///
229    /// # Errors
230    ///
231    /// Returns an error if `limit` is unsupported, CUDA cannot query the limit, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
232    pub fn limit(limit: Limit) -> Result<usize> {
233        let mut value = 0;
234        // SAFETY: `value` is a local that `cudaDeviceGetLimit` writes through an exclusive pointer.
235        unsafe {
236            try_ffi!(runtime::cudaDeviceGetLimit(&raw mut value, limit.into(),))?;
237        }
238        to_usize(value, "device limit")
239    }
240
241    /// Setting limit to value is a request by the application to update the current limit maintained by the device.
242    /// The driver may modify the requested value to meet hardware requirements, such as clamping to minimum or maximum values or rounding up to the nearest element size.
243    /// Use [`Device::limit`] to query the effective value.
244    ///
245    /// Setting each [`Limit`] has its own specific restrictions, so each is discussed here.
246    ///
247    /// * [`Limit::StackSize`] controls the stack size in bytes of each GPU thread.
248    ///
249    /// * [`Limit::PrintfFifoSize`] controls the size in bytes of the shared FIFO used by the `printf()` device system call.
250    ///   Setting [`Limit::PrintfFifoSize`] must not be performed after launching any kernel that uses the `printf()` device system call; otherwise [`crate::error::Status::InvalidValue`] is returned.
251    ///
252    /// * [`Limit::MallocHeapSize`] controls the size in bytes of the heap used by the `malloc()` and `free()` device system calls.
253    ///   Setting [`Limit::MallocHeapSize`] must not be performed after launching any kernel that uses the `malloc()` or `free()` device system calls; otherwise [`crate::error::Status::InvalidValue`] is returned.
254    ///
255    /// * [`Limit::DevRuntimeSyncDepth`] controls the maximum nesting depth of a grid at which a thread can safely call [`Device::synchronize`].
256    ///   Setting this limit must be performed before any launch of a kernel that uses the device runtime and calls [`Device::synchronize`] above the default sync depth, two levels of grids.
257    ///   Calls to [`Device::synchronize`] fail if this limit is violated.
258    ///   This limit can be set smaller than the default or up to the maximum launch depth of 24.
259    ///   Additional sync-depth levels require the runtime to reserve large amounts of device memory that can no longer be used for application allocations.
260    ///   If these device-memory reservations fail, [`Device::set_limit`] returns an error, and the limit can be reset to a lower value.
261    ///   This limit is only applicable to devices of compute capability &lt; 9.0.
262    ///   Setting this limit on devices with other compute capabilities returns [`crate::error::Status::UnsupportedLimit`].
263    ///
264    /// * [`Limit::DevRuntimePendingLaunchCount`] controls the maximum number of outstanding device runtime launches that can be made from the current device.
265    ///   A grid is outstanding from launch until it is known to have completed.
266    ///   Device runtime launches that violate this limit fail.
267    ///   If a module using the device runtime needs more pending launches than the default 2048 launches, this limit can be increased.
268    ///   Sustaining additional pending launches requires the runtime to reserve larger amounts of device memory up front, which can no longer be used for allocations.
269    ///   If these reservations fail, [`Device::set_limit`] returns an error, and the limit can be reset to a lower value.
270    ///   This limit is only applicable to devices of compute capability 3.5 and higher.
271    ///   Setting this limit on devices with compute capability less than 3.5 returns [`crate::error::Status::UnsupportedLimit`].
272    ///
273    /// * [`Limit::MaxL2FetchGranularity`] controls the L2 cache fetch granularity.
274    ///   Values can range from 0B to 128B.
275    ///   Performance hint that can be ignored or clamped depending on the platform.
276    ///
277    /// * [`Limit::PersistingL2CacheSize`] controls size in bytes available for persisting L2 cache.
278    ///   Performance hint that can be ignored or clamped depending on the platform.
279    ///
280    /// # Errors
281    ///
282    /// Returns an error if `limit` is unsupported, `value` is invalid for that limit, CUDA cannot set the limit, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
283    pub fn set_limit(limit: Limit, value: usize) -> Result<()> {
284        let value = value
285            .try_into()
286            .map_err(|_| Error::out_of_range("device limit value"))?;
287        // SAFETY: `cudaDeviceSetLimit` receives only values.
288        unsafe {
289            try_ffi!(runtime::cudaDeviceSetLimit(limit.into(), value))?;
290        }
291        Ok(())
292    }
293
294    /// Records flags as the flags for the current device.
295    /// If the current device has been set and that device has already been initialized, the previous flags are overwritten.
296    /// If the current device has not been initialized, it is initialized with the provided flags.
297    /// If no device has been made current to the calling thread, a default device is selected and initialized with the provided flags.
298    ///
299    /// The three least significant bits of `flags` control how the CPU thread interacts with the OS scheduler while waiting for device results.
300    ///
301    /// * [`ContextFlags::SCHEDULE_AUTO`]: The default value if `flags` is zero.
302    ///   Uses a heuristic based on the number of active CUDA contexts in the process (`C`) and the number of logical processors in the system (`P`).
303    ///   If `C > P`, CUDA yields to other OS threads when waiting for the device; otherwise, CUDA actively spins while waiting for results.
304    ///   Additionally, on Tegra devices, [`ContextFlags::SCHEDULE_AUTO`] uses a heuristic based on the power profile of the platform and may choose [`ContextFlags::SCHEDULE_BLOCKING_SYNC`] for low-powered devices.
305    /// * [`ContextFlags::SCHEDULE_SPIN`]: Instruct CUDA to actively spin when waiting for results from the device.
306    ///   This can decrease latency when waiting for the device, but may lower the performance of CPU threads if they are performing work in parallel with the CUDA thread.
307    /// * [`ContextFlags::SCHEDULE_YIELD`]: Instruct CUDA to yield its thread when waiting for results from the device.
308    ///   This can increase latency when waiting for the device, but can increase the performance of CPU threads performing work in parallel with the device.
309    /// * [`ContextFlags::SCHEDULE_BLOCKING_SYNC`]: Instruct CUDA to block the CPU thread on a synchronization primitive when waiting for the device to finish work.
310    ///
311    /// This matches the deprecated CUDA runtime blocking-sync behavior now represented by [`ContextFlags::SCHEDULE_BLOCKING_SYNC`].
312    /// * [`ContextFlags::MAP_HOST`]: This flag enables allocating pinned host memory that is accessible to the device.
313    ///   It is implicit for the runtime but may be absent if a context is created using the driver API.
314    ///   If this flag is not set, [`sys::cudaHostGetDevicePointer`](singe_cuda_sys::runtime::cudaHostGetDevicePointer) always returns a failure code.
315    /// * [`ContextFlags::LOCAL_MEMORY_RESIZE_TO_MAX`]: Instruct CUDA to not reduce local memory after resizing local memory for a kernel.
316    ///   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.
317    ///
318    /// Deprecated: this behavior is now the default and cannot be disabled.
319    /// * [`ContextFlags::SYNC_MEMORY_OPERATIONS`]: Ensures that synchronous memory operations initiated on this context always synchronize.
320    ///   See further documentation in the section titled "API Synchronization behavior" to learn more about cases when synchronous memory operations can exhibit asynchronous behavior.
321    ///
322    /// # Errors
323    ///
324    /// Returns an error if CUDA cannot set the device flags, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
325    pub fn set_flags(flags: ContextFlags) -> Result<()> {
326        // SAFETY: `cudaSetDeviceFlags` receives only a flag value, which CUDA validates.
327        unsafe { try_ffi!(runtime::cudaSetDeviceFlags(flags.bits())) }
328    }
329
330    /// Returns the flags for the current device.
331    /// If there is a current device for the calling thread, the flags for the device are returned.
332    /// If there is no current device, the flags for the first device are returned, which may be the default flags.
333    /// Compare to the behavior of [`Device::set_flags`].
334    ///
335    /// Typically, the returned flags match the behavior seen if the calling thread uses a device after this call, assuming this thread or another thread does not change the flags or current device in between.
336    /// If the device is not initialized, another thread can change the flags for the current device before it is initialized.
337    /// Additionally, when using exclusive mode, if this thread has not requested a specific device, it may use a device other than the first device, contrary to the assumption made by this query.
338    ///
339    /// If a context has been created via the driver API and is current to the calling thread, the flags for that context are always returned.
340    ///
341    /// Returned flags may specifically include [`ContextFlags::MAP_HOST`] even though it is not accepted by [`Device::set_flags`] because it is implicit in runtime API flags.
342    /// The reason for this is that the current context may have been created via the driver API in which case the flag is not implicit and may be unset.
343    ///
344    /// # Errors
345    ///
346    /// Returns an error if CUDA cannot query the device flags, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
347    pub fn flags() -> Result<ContextFlags> {
348        let mut flags_raw: u32 = 0;
349        // SAFETY: `flags_raw` is a local that `cudaGetDeviceFlags` writes through an exclusive pointer.
350        unsafe {
351            try_ffi!(runtime::cudaGetDeviceFlags(&raw mut flags_raw))?;
352        }
353        Ok(ContextFlags::from_bits_retain(flags_raw))
354    }
355
356    /// Returns the device which has properties that best match the given prop.
357    ///
358    /// # Errors
359    ///
360    /// Returns an error if CUDA cannot choose a matching device, the selected device cannot be represented by this wrapper, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
361    pub fn choose(prop: &DeviceProperties) -> Result<Self> {
362        // CUDA matches against a template, so only the compute capability and managed-memory support of `prop` take part.
363        // SAFETY: this plain C struct is valid when all bytes are zero.
364        let mut ffi_prop: runtime::cudaDeviceProp = unsafe { mem::zeroed() };
365        ffi_prop.major = prop.major;
366        ffi_prop.minor = prop.minor;
367        ffi_prop.managedMemory = i32::from(prop.managed_memory);
368
369        let mut device: i32 = -1;
370        // SAFETY: `device` is a writable local, and `ffi_prop` is a local template live for the call.
371        unsafe {
372            try_ffi!(runtime::cudaChooseDevice(
373                (&raw mut device).cast(),
374                &raw const ffi_prop
375            ))?;
376        }
377        if device == -1 {
378            Err(Error::DeviceNotFound)
379        } else {
380            Ok(Self(device))
381        }
382    }
383
384    /// Returns a device ordinal given a PCI bus ID string.
385    ///
386    /// # Errors
387    ///
388    /// Returns an error if `pci_bus_id` contains an interior NUL byte, CUDA cannot resolve the bus ID, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
389    pub fn by_pci_bus_id(pci_bus_id: &str) -> Result<Self> {
390        let c_pci_bus_id = CString::new(pci_bus_id)?;
391        let mut device: i32 = -1;
392        // SAFETY: `device` is a writable local, and `c_pci_bus_id` is a NUL-terminated string live for the call.
393        unsafe {
394            try_ffi!(runtime::cudaDeviceGetByPCIBusId(
395                (&raw mut device).cast(),
396                c_pci_bus_id.as_ptr(),
397            ))?;
398        }
399        if device == -1 {
400            Err(Error::DeviceNotFound)
401        } else {
402            Ok(Self(device))
403        }
404    }
405
406    /// Sets device as the current device for the calling host thread.
407    /// Valid device IDs are 0 to [`Device::count`] minus one.
408    ///
409    /// Device memory subsequently allocated from this host thread is physically resident on `device`.
410    /// Host memory allocated or registered from this host thread has its lifetime associated with `device`.
411    /// Streams and events created from this host thread are associated with `device`.
412    /// Kernels launched from this host thread execute on `device`.
413    ///
414    /// This may be called from any host thread, for any device, at any time.
415    /// This performs no synchronization with the previous or new device, and usually only takes significant time when it initializes the runtime's context state.
416    /// This binds the primary context of the specified device to the calling thread; subsequent memory allocations, stream and event creations, and kernel launches are associated with that primary context.
417    /// This also immediately initializes the runtime state on the primary context, and the context is current on the device immediately.
418    /// It returns an error if the device is in [`ComputeMode::ExclusiveProcess`] and is occupied by another process, or if it is in [`ComputeMode::Prohibited`].
419    ///
420    /// It is not required to call [`sys::cudaInitDevice`](singe_cuda_sys::runtime::cudaInitDevice) before using this method.
421    ///
422    /// # Errors
423    ///
424    /// Returns an error if CUDA cannot set the current device, the device is unavailable due to compute mode restrictions, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
425    pub fn set_current(self) -> Result<()> {
426        // SAFETY: `cudaSetDevice` receives only the ordinal, which CUDA validates.
427        unsafe {
428            try_ffi!(runtime::cudaSetDevice(self.0))?;
429        }
430        Ok(())
431    }
432
433    /// Returns this device's properties.
434    ///
435    /// # Errors
436    ///
437    /// Returns an error if CUDA cannot query the device properties, the returned properties cannot be converted into the safe wrapper type, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
438    pub fn properties(self) -> Result<DeviceProperties> {
439        let mut prop = runtime::cudaDeviceProp::default();
440        // SAFETY: `cudaGetDeviceProperties` writes only into the local `prop`.
441        unsafe {
442            try_ffi!(runtime::cudaGetDeviceProperties(&raw mut prop, self.0))?;
443        }
444        prop.try_into()
445    }
446
447    /// Returns the PCI bus ID string identifying the device.
448    ///
449    /// # Errors
450    ///
451    /// Returns an error if CUDA cannot query the PCI bus ID, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
452    pub fn pci_bus_id(self) -> Result<String> {
453        const LEN: usize = 16; // Sufficient for typical PCI IDs like 0000:01:00.0
454        let mut pci_bus_id_buf: [c_char; LEN] = [0; LEN];
455        // SAFETY: `pci_bus_id_buf` is a local buffer of `LEN` = 16 bytes, the length passed to CUDA.
456        unsafe {
457            try_ffi!(runtime::cudaDeviceGetPCIBusId(
458                pci_bus_id_buf.as_mut_ptr().cast(),
459                16,
460                self.0,
461            ))?;
462            Ok(string_from_c_chars(&pci_bus_id_buf))
463        }
464    }
465
466    /// Returns true if this device can directly access memory from `other`.
467    /// If direct access from this device to `other` is possible, access may be enabled by calling [`Context::enable_peer_access`](crate::context::Context::enable_peer_access).
468    ///
469    /// # Errors
470    ///
471    /// Returns an error if CUDA cannot query peer accessibility, either device is invalid, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
472    pub fn can_access_peer(self, other: Self) -> Result<bool> {
473        let mut can_access_peer: i32 = 0;
474        // SAFETY: `can_access_peer` is a local that `cudaDeviceCanAccessPeer` writes through an exclusive pointer.
475        unsafe {
476            try_ffi!(runtime::cudaDeviceCanAccessPeer(
477                (&raw mut can_access_peer).cast(),
478                self.0,
479                other.0,
480            ))?;
481        }
482        Ok(can_access_peer != 0)
483    }
484
485    /// Returns the value of the requested attribute of the link between devices.
486    /// Supported attributes are represented by [`PeerToPeerAttribute`]:
487    ///
488    /// * [`PeerToPeerAttribute::PerformanceRank`]: relative performance of the link between the two devices.
489    ///   Lower values are better.
490    /// * [`PeerToPeerAttribute::AccessSupported`]: whether direct peer access is supported.
491    /// * [`PeerToPeerAttribute::NativeAtomicSupported`]: whether native atomic operations over the link are supported.
492    /// * [`PeerToPeerAttribute::CudaArrayAccessSupported`]: whether CUDA arrays are accessible over the link.
493    ///
494    /// Returns [`crate::error::Status::InvalidDevice`] if either device is invalid or if they represent the same device.
495    ///
496    /// Returns [`crate::error::Status::InvalidValue`] if `attrib` is not valid.
497    ///
498    /// # Errors
499    ///
500    /// Returns an error if either device is invalid, `attr` is not accepted by CUDA, CUDA cannot query the attribute, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
501    pub fn p2p_attribute(self, attr: PeerToPeerAttribute, other: Self) -> Result<i32> {
502        let mut value: i32 = 0;
503        // SAFETY: `value` is a local that `cudaDeviceGetP2PAttribute` writes through an exclusive pointer.
504        unsafe {
505            try_ffi!(runtime::cudaDeviceGetP2PAttribute(
506                (&raw mut value).cast(),
507                attr.into(),
508                self.0,
509                other.0,
510            ))?;
511        }
512        Ok(value)
513    }
514
515    /// On devices where the L1 cache and shared memory use the same hardware resources, this returns the preferred cache configuration for the current device.
516    /// This setting is only a preference.
517    /// The runtime uses the requested configuration if possible, but it may choose a different configuration if required to execute functions.
518    ///
519    /// This returns [`FunctionCache::PreferNone`] on devices where the size of the L1 cache and shared memory are fixed.
520    ///
521    /// The supported cache configurations are:
522    ///
523    /// * [`FunctionCache::PreferNone`]: no preference for shared memory or L1 (default)
524    /// * [`FunctionCache::PreferShared`]: prefer larger shared memory and smaller L1 cache
525    /// * [`FunctionCache::PreferL1`]: prefer larger L1 cache and smaller shared memory
526    /// * [`FunctionCache::PreferEqual`]: prefer equal size L1 cache and shared memory
527    ///
528    /// # Errors
529    ///
530    /// Returns an error if CUDA cannot query the cache configuration, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
531    pub fn cache_config() -> Result<FunctionCache> {
532        let mut config = runtime::cudaFuncCache::CU_FUNC_CACHE_PREFER_NONE;
533        // SAFETY: `config` is a local that `cudaDeviceGetCacheConfig` writes through an exclusive pointer.
534        unsafe {
535            try_ffi!(runtime::cudaDeviceGetCacheConfig(&raw mut config))?;
536        }
537        Ok(config.try_into()?)
538    }
539
540    /// On devices where the L1 cache and shared memory use the same hardware resources, this sets through cacheConfig the preferred cache configuration for the current device.
541    /// This setting is only a preference.
542    /// The runtime uses the requested configuration if possible, but it is free to choose a different configuration if required to execute the kernel.
543    /// Any per-kernel cache preference set through the CUDA API takes precedence over this device-wide setting.
544    /// Setting the device-wide cache configuration to [`FunctionCache::PreferNone`] causes subsequent kernel launches to prefer not changing the cache configuration unless required to launch the kernel.
545    ///
546    /// This setting does nothing on devices where the size of the L1 cache and shared memory are fixed.
547    ///
548    /// Launching a kernel with a different preference than the most recent preference setting may insert a device-side synchronization point.
549    ///
550    /// The supported cache configurations are:
551    ///
552    /// * [`FunctionCache::PreferNone`]: no preference for shared memory or L1 (default)
553    /// * [`FunctionCache::PreferShared`]: prefer larger shared memory and smaller L1 cache
554    /// * [`FunctionCache::PreferL1`]: prefer larger L1 cache and smaller shared memory
555    /// * [`FunctionCache::PreferEqual`]: prefer equal size L1 cache and shared memory
556    ///
557    /// # Errors
558    ///
559    /// Returns an error if CUDA cannot set the cache configuration, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
560    pub fn set_cache_config(config: FunctionCache) -> Result<()> {
561        // SAFETY: `cudaDeviceSetCacheConfig` receives only an enum value.
562        unsafe {
563            try_ffi!(runtime::cudaDeviceSetCacheConfig(config.into()))?;
564        }
565        Ok(())
566    }
567
568    /// Returns the least and greatest stream priority numerical values.
569    /// Stream priorities follow a convention where lower numbers represent greater priorities.
570    /// The range of meaningful stream priorities is given by \[greatest, least\].
571    /// If a stream is created with a priority value outside this range, the priority is automatically clamped.
572    /// See [`StreamOptions::priority`](crate::stream::StreamOptions::priority) for creating a priority stream.
573    ///
574    /// Returns 0 for both values if the current context's device does not support stream priorities.
575    ///
576    /// # Errors
577    ///
578    /// Returns an error if CUDA cannot query the stream-priority range, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
579    pub fn stream_priority_range() -> Result<StreamPriorityRange> {
580        let mut least = 0;
581        let mut greatest = 0;
582        // SAFETY: `least` and `greatest` are locals that CUDA writes through exclusive pointers.
583        unsafe {
584            try_ffi!(runtime::cudaDeviceGetStreamPriorityRange(
585                &raw mut least,
586                &raw mut greatest,
587            ))?;
588        }
589        Ok(StreamPriorityRange { least, greatest })
590    }
591
592    /// Returns this device's ordinal.
593    #[must_use]
594    pub const fn id(self) -> DeviceId {
595        self.0
596    }
597}
598
599impl_enum_display!(ComputeMode, {
600    ComputeMode::Default => "cudaComputeModeDefault",
601    ComputeMode::Exclusive => "cudaComputeModeExclusive",
602    ComputeMode::Prohibited => "cudaComputeModeProhibited",
603    ComputeMode::ExclusiveProcess => "cudaComputeModeExclusiveProcess",
604});
605
606#[cfg(all(test, feature = "testing"))]
607mod tests {
608    use super::*;
609    use crate::testing;
610
611    #[test]
612    fn test_it_works() -> Result<()> {
613        let _lock = testing::device_lock(Device::new(0))?;
614        assert!(Device::count()? > 0);
615        assert!(!Device::new(0).properties()?.name.is_empty());
616        Ok(())
617    }
618}