Skip to main content

oxicuda_memory/
device_buffer.rs

1//! Type-safe device (GPU VRAM) memory buffer.
2//!
3//! [`DeviceBuffer<T>`] owns a contiguous allocation of `T` elements in device
4//! memory.  It supports synchronous and asynchronous copies to/from host
5//! memory, device-to-device copies, and zero-initialisation via `cuMemsetD8`.
6//!
7//! The buffer is parameterised over `T: Copy` so that only plain-old-data
8//! types can be stored — no heap pointers that would be meaningless on the
9//! GPU.
10//!
11//! # Ownership
12//!
13//! The allocation is freed automatically when the buffer is dropped.  If
14//! `cuMemFree_v2` fails during [`Drop`], the error is logged via
15//! [`tracing::warn`] rather than panicking.
16//!
17//! # Example
18//!
19//! ```rust,no_run
20//! # use oxicuda_memory::DeviceBuffer;
21//! let mut buf = DeviceBuffer::<f32>::alloc(1024)?;
22//! let host_data = vec![1.0_f32; 1024];
23//! buf.copy_from_host(&host_data)?;
24//!
25//! let mut result = vec![0.0_f32; 1024];
26//! buf.copy_to_host(&mut result)?;
27//! assert_eq!(result, host_data);
28//! # Ok::<(), oxicuda_driver::error::CudaError>(())
29//! ```
30
31use std::ffi::c_void;
32use std::marker::PhantomData;
33
34use oxicuda_driver::error::{CudaError, CudaResult};
35use oxicuda_driver::ffi::CUdeviceptr;
36use oxicuda_driver::loader::try_driver;
37use oxicuda_driver::stream::Stream;
38
39// ---------------------------------------------------------------------------
40// DeviceBuffer<T>
41// ---------------------------------------------------------------------------
42
43/// A contiguous buffer of `T` elements allocated in GPU device memory.
44///
45/// The buffer owns the underlying `CUdeviceptr` allocation and frees it on
46/// drop.  All copy operations validate that source and destination lengths
47/// match, returning [`CudaError::InvalidValue`] on mismatch.
48pub struct DeviceBuffer<T: Copy> {
49    /// Raw CUDA device pointer to the start of the allocation.
50    ptr: CUdeviceptr,
51    /// Number of `T` elements (not bytes).
52    len: usize,
53    /// Whether this buffer owns its allocation and must free it on drop.
54    ///
55    /// `true` for buffers created via [`DeviceBuffer::alloc`],
56    /// [`DeviceBuffer::zeroed`], or [`DeviceBuffer::from_host`]; `false` for
57    /// non-owning views created via [`DeviceBuffer::from_raw`], which borrow an
58    /// externally-owned device pointer and must NOT free it on drop.
59    owned: bool,
60    /// Marker to tie the generic parameter `T` to this struct.
61    _phantom: PhantomData<T>,
62}
63
64// SAFETY: Device memory is not bound to a specific host thread.  The raw
65// pointer is a `u64` handle managed by the CUDA driver, which is thread-safe
66// for memory operations when properly synchronised.
67unsafe impl<T: Copy + Send> Send for DeviceBuffer<T> {}
68unsafe impl<T: Copy + Sync> Sync for DeviceBuffer<T> {}
69
70impl<T: Copy> DeviceBuffer<T> {
71    /// Allocates a device buffer capable of holding `n` elements of type `T`.
72    ///
73    /// # Errors
74    ///
75    /// * [`CudaError::InvalidValue`] if `n` is zero.
76    /// * [`CudaError::OutOfMemory`] if the GPU cannot satisfy the request.
77    /// * Other driver errors propagated from `cuMemAlloc_v2`.
78    pub fn alloc(n: usize) -> CudaResult<Self> {
79        if n == 0 {
80            return Err(CudaError::InvalidValue);
81        }
82        let byte_size = n
83            .checked_mul(std::mem::size_of::<T>())
84            .ok_or(CudaError::InvalidValue)?;
85        let api = try_driver()?;
86        let mut ptr: CUdeviceptr = 0;
87        // SAFETY: `cu_mem_alloc_v2` writes a valid device pointer on success.
88        let rc = unsafe { (api.cu_mem_alloc_v2)(&mut ptr, byte_size) };
89        oxicuda_driver::check(rc)?;
90        Ok(Self {
91            ptr,
92            len: n,
93            owned: true,
94            _phantom: PhantomData,
95        })
96    }
97
98    /// Allocates a device buffer of `n` elements and zero-initialises every byte.
99    ///
100    /// This is equivalent to [`alloc`](Self::alloc) followed by a
101    /// `cuMemsetD8_v2` call that writes `0` to every byte.
102    ///
103    /// # Errors
104    ///
105    /// Same as [`alloc`](Self::alloc), plus any error from `cuMemsetD8_v2`.
106    pub fn zeroed(n: usize) -> CudaResult<Self> {
107        let buf = Self::alloc(n)?;
108        let api = try_driver()?;
109        // SAFETY: the buffer was just allocated with the correct byte size.
110        let rc = unsafe { (api.cu_memset_d8_v2)(buf.ptr, 0, buf.byte_size()) };
111        oxicuda_driver::check(rc)?;
112        Ok(buf)
113    }
114
115    /// Allocates a device buffer and copies the contents of `data` into it.
116    ///
117    /// The resulting buffer has the same length as the input slice.
118    ///
119    /// # Errors
120    ///
121    /// * [`CudaError::InvalidValue`] if `data` is empty.
122    /// * Other driver errors from allocation or the host-to-device copy.
123    pub fn from_host(data: &[T]) -> CudaResult<Self> {
124        let mut buf = Self::alloc(data.len())?;
125        buf.copy_from_host(data)?;
126        Ok(buf)
127    }
128
129    /// Wraps an externally-owned device pointer in a non-owning
130    /// [`DeviceBuffer`] view **without allocating**.
131    ///
132    /// The returned buffer points at the *existing* allocation described by
133    /// `ptr` and `len`, and exposes the full [`DeviceBuffer`] API (copies,
134    /// slicing, [`as_device_ptr`](Self::as_device_ptr), and use as a matrix
135    /// operand in `oxicuda-blas`) over that memory.  Because the view does not
136    /// own the allocation, its [`Drop`] is a no-op: it will **not** call
137    /// `cuMemFree_v2`.  Ownership and the lifetime of the underlying memory
138    /// remain entirely with the original owner (e.g. another CUDA library,
139    /// `cudarc`, or a foreign allocator).
140    ///
141    /// This enables zero-copy interop: a consumer that already holds a
142    /// resident device allocation can wrap it here and run OxiCUDA operations
143    /// in place, with no host round-trip and no extra device allocation.
144    ///
145    /// # Safety
146    ///
147    /// The caller must guarantee all of the following:
148    ///
149    /// * `ptr` is a valid CUDA device pointer into an allocation of at least
150    ///   `len * size_of::<T>()` bytes, correctly aligned for `T`, and
151    ///   associated with the CUDA context that subsequent OxiCUDA operations
152    ///   run under.
153    /// * The pointed-to memory contains a valid, initialised `[T; len]` (or is
154    ///   only used as a write target before being read).
155    /// * The underlying allocation **outlives** this `DeviceBuffer` view: the
156    ///   original owner must not free, reallocate, or invalidate `ptr` while
157    ///   this view (or any [`DeviceSlice`] borrowed from it) is alive.
158    /// * No other live `DeviceBuffer` owns the same `ptr` (to avoid a
159    ///   double-free) and aliasing rules are respected when the view is used
160    ///   mutably (e.g. as a [`MatrixDescMut`](../oxicuda_blas/struct.MatrixDescMut.html)
161    ///   output operand).
162    ///
163    /// A zero `len` is permitted (unlike [`alloc`](Self::alloc)) since no
164    /// allocation is performed; a `ptr` of `0` is also permitted for a
165    /// zero-length view, but pointer/length validity is the caller's
166    /// responsibility.
167    ///
168    /// # Example
169    ///
170    /// ```rust,no_run
171    /// # use oxicuda_memory::DeviceBuffer;
172    /// # use oxicuda_driver::ffi::CUdeviceptr;
173    /// // `raw` is a device pointer owned elsewhere (e.g. obtained from another
174    /// // CUDA library) pointing at `n` resident `f32` elements.
175    /// # let raw: CUdeviceptr = 0;
176    /// # let n: usize = 1024;
177    /// // SAFETY: `raw` is valid for `n` f32s and outlives `view`.
178    /// let view = unsafe { DeviceBuffer::<f32>::from_raw(raw, n) };
179    /// // `view` can now be used with oxicuda-blas / copies; dropping it does
180    /// // NOT free `raw`.
181    /// assert_eq!(view.len(), n);
182    /// ```
183    #[must_use]
184    pub unsafe fn from_raw(ptr: CUdeviceptr, len: usize) -> Self {
185        Self {
186            ptr,
187            len,
188            owned: false,
189            _phantom: PhantomData,
190        }
191    }
192
193    /// Copies data from a host slice into this device buffer (synchronous).
194    ///
195    /// The slice length must exactly match the buffer length.
196    ///
197    /// # Errors
198    ///
199    /// * [`CudaError::InvalidValue`] if `src.len() != self.len()`.
200    /// * Other driver errors from `cuMemcpyHtoD_v2`.
201    pub fn copy_from_host(&mut self, src: &[T]) -> CudaResult<()> {
202        if src.len() != self.len {
203            return Err(CudaError::InvalidValue);
204        }
205        let api = try_driver()?;
206        // SAFETY: `src` is a valid host slice with the correct byte count.
207        let rc = unsafe {
208            (api.cu_memcpy_htod_v2)(self.ptr, src.as_ptr().cast::<c_void>(), self.byte_size())
209        };
210        oxicuda_driver::check(rc)
211    }
212
213    /// Copies this device buffer's contents into a host slice (synchronous).
214    ///
215    /// The slice length must exactly match the buffer length.
216    ///
217    /// # Errors
218    ///
219    /// * [`CudaError::InvalidValue`] if `dst.len() != self.len()`.
220    /// * Other driver errors from `cuMemcpyDtoH_v2`.
221    pub fn copy_to_host(&self, dst: &mut [T]) -> CudaResult<()> {
222        if dst.len() != self.len {
223            return Err(CudaError::InvalidValue);
224        }
225        let api = try_driver()?;
226        // SAFETY: `dst` is a valid host slice with the correct byte count.
227        let rc = unsafe {
228            (api.cu_memcpy_dtoh_v2)(
229                dst.as_mut_ptr().cast::<c_void>(),
230                self.ptr,
231                self.byte_size(),
232            )
233        };
234        oxicuda_driver::check(rc)
235    }
236
237    /// Copies the entire contents of another device buffer into this one.
238    ///
239    /// Both buffers must have the same length.
240    ///
241    /// # Errors
242    ///
243    /// * [`CudaError::InvalidValue`] if `src.len() != self.len()`.
244    /// * Other driver errors from `cuMemcpyDtoD_v2`.
245    pub fn copy_from_device(&mut self, src: &DeviceBuffer<T>) -> CudaResult<()> {
246        if src.len != self.len {
247            return Err(CudaError::InvalidValue);
248        }
249        let api = try_driver()?;
250        // SAFETY: both pointers are valid device allocations of the same size.
251        let rc = unsafe { (api.cu_memcpy_dtod_v2)(self.ptr, src.ptr, self.byte_size()) };
252        oxicuda_driver::check(rc)
253    }
254
255    /// Asynchronously copies data from a host slice into this device buffer.
256    ///
257    /// The copy is enqueued on `stream` and may not be complete when this
258    /// function returns.  The caller must ensure that `src` remains valid
259    /// (i.e., is not moved or dropped) until the stream has been
260    /// synchronised.  For guaranteed correctness, prefer using a
261    /// [`PinnedBuffer`](crate::PinnedBuffer) as the source.
262    ///
263    /// # Errors
264    ///
265    /// * [`CudaError::InvalidValue`] if `src.len() != self.len()`.
266    /// * Other driver errors from `cuMemcpyHtoDAsync_v2`.
267    pub fn copy_from_host_async(&mut self, src: &[T], stream: &Stream) -> CudaResult<()> {
268        if src.len() != self.len {
269            return Err(CudaError::InvalidValue);
270        }
271        let api = try_driver()?;
272        // SAFETY: the caller is responsible for keeping `src` alive until
273        // the stream completes.
274        let rc = unsafe {
275            (api.cu_memcpy_htod_async_v2)(
276                self.ptr,
277                src.as_ptr().cast::<c_void>(),
278                self.byte_size(),
279                stream.raw(),
280            )
281        };
282        oxicuda_driver::check(rc)
283    }
284
285    /// Asynchronously copies this device buffer's contents into a host slice.
286    ///
287    /// The copy is enqueued on `stream` and may not be complete when this
288    /// function returns.  The caller must ensure that `dst` remains valid
289    /// and is not read until the stream has been synchronised.  For
290    /// guaranteed correctness, prefer using a
291    /// [`PinnedBuffer`](crate::PinnedBuffer) as the destination.
292    ///
293    /// # Errors
294    ///
295    /// * [`CudaError::InvalidValue`] if `dst.len() != self.len()`.
296    /// * Other driver errors from `cuMemcpyDtoHAsync_v2`.
297    pub fn copy_to_host_async(&self, dst: &mut [T], stream: &Stream) -> CudaResult<()> {
298        if dst.len() != self.len {
299            return Err(CudaError::InvalidValue);
300        }
301        let api = try_driver()?;
302        // SAFETY: the caller is responsible for keeping `dst` alive until
303        // the stream completes.
304        let rc = unsafe {
305            (api.cu_memcpy_dtoh_async_v2)(
306                dst.as_mut_ptr().cast::<c_void>(),
307                self.ptr,
308                self.byte_size(),
309                stream.raw(),
310            )
311        };
312        oxicuda_driver::check(rc)
313    }
314
315    /// Returns the number of `T` elements in this buffer.
316    #[inline]
317    pub fn len(&self) -> usize {
318        self.len
319    }
320
321    /// Returns `true` if the buffer contains zero elements.
322    ///
323    /// In practice this is always `false` because [`alloc`](Self::alloc)
324    /// rejects zero-length allocations.
325    #[inline]
326    pub fn is_empty(&self) -> bool {
327        self.len == 0
328    }
329
330    /// Returns the total size of the allocation in bytes.
331    #[inline]
332    pub fn byte_size(&self) -> usize {
333        self.len * std::mem::size_of::<T>()
334    }
335
336    /// Returns the raw [`CUdeviceptr`] handle for this buffer.
337    ///
338    /// This is useful when passing the pointer to kernel launch parameters
339    /// or other low-level driver calls.
340    #[inline]
341    pub fn as_device_ptr(&self) -> CUdeviceptr {
342        self.ptr
343    }
344
345    /// Returns a borrowed [`DeviceSlice`] referencing a sub-range of this
346    /// buffer starting at element `offset` and spanning `len` elements.
347    ///
348    /// # Errors
349    ///
350    /// Returns [`CudaError::InvalidValue`] if the requested range exceeds
351    /// the buffer bounds (i.e., `offset + len > self.len()`).
352    pub fn slice(&self, offset: usize, len: usize) -> CudaResult<DeviceSlice<'_, T>> {
353        let end = offset.checked_add(len).ok_or(CudaError::InvalidValue)?;
354        if end > self.len {
355            return Err(CudaError::InvalidValue);
356        }
357        let byte_offset = offset
358            .checked_mul(std::mem::size_of::<T>())
359            .ok_or(CudaError::InvalidValue)?;
360        Ok(DeviceSlice {
361            ptr: self.ptr + byte_offset as u64,
362            len,
363            _phantom: PhantomData,
364        })
365    }
366}
367
368impl<T: Copy> Drop for DeviceBuffer<T> {
369    fn drop(&mut self) {
370        // Non-owning views (created via `from_raw`) borrow an externally-owned
371        // allocation and must never free it.
372        if !self.owned {
373            return;
374        }
375        if let Ok(api) = try_driver() {
376            // SAFETY: `self.ptr` was allocated by `cu_mem_alloc_v2` and has
377            // not yet been freed.
378            let rc = unsafe { (api.cu_mem_free_v2)(self.ptr) };
379            if rc != 0 {
380                tracing::warn!(
381                    cuda_error = rc,
382                    ptr = self.ptr,
383                    len = self.len,
384                    "cuMemFree_v2 failed during DeviceBuffer drop"
385                );
386            }
387        }
388    }
389}
390
391// ---------------------------------------------------------------------------
392// DeviceSlice<'a, T>
393// ---------------------------------------------------------------------------
394
395/// A borrowed, non-owning view into a sub-range of a [`DeviceBuffer`].
396///
397/// A `DeviceSlice` does not own the memory it points to — it borrows from
398/// the parent [`DeviceBuffer`] and is lifetime-bound to it.  This is useful
399/// for passing sub-regions of a buffer to kernels or copy operations without
400/// extra allocations.
401///
402/// `DeviceSlice` does **not** implement [`Drop`]; the parent buffer is
403/// responsible for freeing the allocation.
404pub struct DeviceSlice<'a, T: Copy> {
405    /// Raw device pointer to the start of this slice within the parent buffer.
406    ptr: CUdeviceptr,
407    /// Number of `T` elements in this slice.
408    len: usize,
409    /// Ties the lifetime to the parent buffer and the element type.
410    _phantom: PhantomData<&'a T>,
411}
412
413impl<T: Copy> DeviceSlice<'_, T> {
414    /// Returns the number of `T` elements in this slice.
415    #[inline]
416    pub fn len(&self) -> usize {
417        self.len
418    }
419
420    /// Returns `true` if the slice contains zero elements.
421    #[inline]
422    pub fn is_empty(&self) -> bool {
423        self.len == 0
424    }
425
426    /// Returns the total size of this slice in bytes.
427    #[inline]
428    pub fn byte_size(&self) -> usize {
429        self.len * std::mem::size_of::<T>()
430    }
431
432    /// Returns the raw [`CUdeviceptr`] handle for the start of this slice.
433    #[inline]
434    pub fn as_device_ptr(&self) -> CUdeviceptr {
435        self.ptr
436    }
437}
438
439// ---------------------------------------------------------------------------
440// Tests
441// ---------------------------------------------------------------------------
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446
447    /// A `from_raw` view must be marked non-owning so that `Drop` skips the
448    /// `cuMemFree_v2` call. We construct over a dummy sentinel pointer; because
449    /// the view is non-owning, dropping it performs no driver call and is safe
450    /// even without a CUDA device present.
451    #[test]
452    fn from_raw_is_non_owning() {
453        let sentinel: CUdeviceptr = 0xDEAD_BEEF;
454        // SAFETY: this view is never dereferenced; we only inspect metadata and
455        // rely on the non-owning Drop being a no-op.
456        let view = unsafe { DeviceBuffer::<f32>::from_raw(sentinel, 16) };
457        assert!(!view.owned, "from_raw must produce a non-owning buffer");
458        assert_eq!(view.len(), 16);
459        assert_eq!(view.as_device_ptr(), sentinel);
460        assert_eq!(view.byte_size(), 16 * std::mem::size_of::<f32>());
461        // Dropping a non-owning view must NOT touch the driver / free memory.
462        // Reaching the end of scope here exercises that path without a GPU.
463        drop(view);
464    }
465
466    /// A zero-length `from_raw` view is permitted (no allocation occurs) and is
467    /// reported as empty.
468    #[test]
469    fn from_raw_zero_len_is_empty() {
470        // SAFETY: zero-length, pointer never dereferenced; Drop is a no-op.
471        let view = unsafe { DeviceBuffer::<u8>::from_raw(0, 0) };
472        assert!(!view.owned);
473        assert!(view.is_empty());
474        assert_eq!(view.len(), 0);
475        assert_eq!(view.byte_size(), 0);
476    }
477
478    /// Two non-owning views may share the same pointer without risking a
479    /// double-free, because neither frees on drop. This models a consumer
480    /// re-wrapping the same resident allocation.
481    #[test]
482    fn from_raw_aliasing_views_do_not_double_free() {
483        let ptr: CUdeviceptr = 0x1000;
484        // SAFETY: non-owning aliases, never dereferenced; both Drops are no-ops.
485        let a = unsafe { DeviceBuffer::<f64>::from_raw(ptr, 8) };
486        let b = unsafe { DeviceBuffer::<f64>::from_raw(ptr, 8) };
487        assert!(!a.owned);
488        assert!(!b.owned);
489        assert_eq!(a.as_device_ptr(), b.as_device_ptr());
490        drop(a);
491        drop(b);
492    }
493
494    /// A real owning allocation created via `alloc` is marked `owned` so that
495    /// its memory is freed on drop. This requires a CUDA device, so it is gated
496    /// behind a runtime driver check and skipped (passing) when no GPU/driver
497    /// is available — keeping the test green on macOS while still proving the
498    /// owned-flag wiring on real hardware.
499    #[test]
500    fn alloc_is_owning_when_driver_available() {
501        match DeviceBuffer::<f32>::alloc(32) {
502            Ok(buf) => {
503                assert!(buf.owned, "alloc must produce an owning buffer");
504                assert_eq!(buf.len(), 32);
505                // `buf` is dropped here and frees its allocation via the driver.
506            }
507            Err(_) => {
508                // No CUDA driver/device on this host (e.g. macOS CI): the
509                // owned-flag logic is covered by the non-GPU tests above.
510            }
511        }
512    }
513}