singe_cuda/memory/device/raw.rs
1use std::ptr;
2
3use singe_cuda_sys::runtime;
4
5use super::DeviceMemory;
6use crate::{
7 context::Context,
8 error::{Error, Result},
9 memory::{MemoryAttachFlags, MemoryCopyKind, MemoryLocation, PointerAttributes},
10 stream::{AsStream, Stream},
11 try_ffi,
12 types::{DevicePtr, MemoryAdvise},
13 utility::{checked_bytes, checked_element_count, to_usize},
14};
15
16/// Associated utility functions.
17impl<T> DeviceMemory<T> {
18 /// Allocates uninitialized linear device memory for `count` elements and returns its pointer.
19 ///
20 /// The memory is aligned for any element type and is not cleared.
21 /// An allocation failure returns [`crate::error::Status::OutOfMemory`].
22 /// A zero-byte request returns a null pointer without calling CUDA.
23 ///
24 /// # Safety
25 ///
26 /// The returned pointer is uninitialized device memory.
27 /// The caller must use it only for `count` elements of `T` and eventually free it with a compatible CUDA free function.
28 ///
29 /// # Errors
30 ///
31 /// Returns an error if `context` cannot be bound, the requested byte size overflows, CUDA cannot allocate device memory, 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`].
32 pub unsafe fn alloc(context: &Context, count: usize) -> Result<*mut T> {
33 context.bind()?;
34 let bytes = checked_bytes::<T>(count, "byte count")?;
35 if bytes == 0 {
36 return Ok(ptr::null_mut());
37 }
38
39 let mut p = ptr::null_mut();
40 // SAFETY: `p` is a local output, and `bytes` is a checked nonzero size.
41 unsafe {
42 try_ffi!(runtime::cudaMalloc(&raw mut p, bytes as _))?;
43 }
44 Ok(p.cast())
45 }
46
47 /// Allocates CUDA managed memory for `count` elements.
48 ///
49 /// `flags` controls the initial stream attachment behavior for the managed allocation.
50 ///
51 /// # Safety
52 ///
53 /// The returned pointer is managed CUDA memory.
54 /// The caller must eventually free it with a CUDA-compatible device free and must synchronize host and device access according to CUDA managed-memory rules.
55 ///
56 /// # Errors
57 ///
58 /// Returns an error if `context` cannot be bound, the requested byte size overflows, CUDA cannot allocate managed memory, or `count` is non-zero for a zero-sized `T`.
59 pub unsafe fn alloc_managed(
60 context: &Context,
61 count: usize,
62 flags: MemoryAttachFlags,
63 ) -> Result<*mut T> {
64 context.bind()?;
65 let bytes = checked_bytes::<T>(count, "byte count")?;
66 if bytes == 0 {
67 return Ok(ptr::null_mut());
68 }
69
70 let mut p = ptr::null_mut();
71 // SAFETY: `p` is a local output, and `bytes` is a checked nonzero size.
72 unsafe {
73 try_ffi!(runtime::cudaMallocManaged(
74 &raw mut p,
75 bytes as _,
76 flags.bits(),
77 ))?;
78 }
79 Ok(p.cast::<T>())
80 }
81
82 /// Frees the device allocation at `ptr`.
83 ///
84 /// This does not synchronize when the pointer came from the stream-ordered allocator, such as [`DeviceMemory::alloc_async`].
85 /// For best performance and memory reuse, free such memory with [`DeviceMemory::free_async`] instead.
86 /// For all other pointers, this call may synchronize implicitly.
87 ///
88 /// If `ptr` is null, no operation is performed.
89 ///
90 /// # Safety
91 ///
92 /// `ptr` must be null or a live allocation of `context` returned by a CUDA device allocation function, and not freed before.
93 /// All work that accesses it must have completed, no work may access it afterwards, and no allocation owner may free it again.
94 ///
95 /// # Errors
96 ///
97 /// Returns an error if `context` cannot be bound, CUDA cannot free `ptr`, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
98 pub unsafe fn free(context: &Context, ptr: *mut T) -> Result<()> {
99 context.bind()?;
100 // SAFETY: the caller passes null or a live CUDA allocation that no work uses any more.
101 unsafe {
102 try_ffi!(runtime::cudaFree(ptr.cast()))?;
103 }
104 Ok(())
105 }
106
107 /// Allocates 2D pitched device memory and returns the base pointer and row pitch in bytes.
108 ///
109 /// `width` is measured in elements of `T`, while the returned pitch is measured in bytes.
110 /// CUDA may pad each row so that row-to-row addressing satisfies device alignment requirements.
111 ///
112 /// # Safety
113 ///
114 /// The returned pointer is uninitialized device memory.
115 /// The caller must use it only as a `width` by `height` pitched allocation with the returned pitch and eventually free it with a CUDA-compatible device free.
116 ///
117 /// # Errors
118 ///
119 /// Returns an error if `context` cannot be bound, the requested byte size overflows, `T` is a non-empty zero-sized allocation, CUDA cannot allocate pitched memory, or CUDA returns a null allocation for a non-empty request.
120 pub unsafe fn alloc_pitched(
121 context: &Context,
122 width: usize,
123 height: usize,
124 ) -> Result<(*mut T, usize)> {
125 context.bind()?;
126 let row_bytes = checked_bytes::<T>(width, "row bytes")?;
127 checked_element_count(&[row_bytes, height], "rectangle bytes")?;
128 if row_bytes == 0 || height == 0 {
129 return Ok((ptr::null_mut(), row_bytes));
130 }
131
132 let mut ptr = ptr::null_mut();
133 let mut pitch = 0;
134 // SAFETY: `ptr` and `pitch` are local outputs, and the rectangle size was checked for overflow.
135 unsafe {
136 try_ffi!(runtime::cudaMallocPitch(
137 &raw mut ptr,
138 &raw mut pitch,
139 row_bytes as _,
140 height as _,
141 ))?;
142 }
143
144 if ptr.is_null() {
145 return Err(Error::NullHandle);
146 }
147 Ok((ptr.cast(), to_usize(pitch, "allocation pitch")?))
148 }
149
150 /// Allocates 3D pitched device memory and returns CUDA's pitched pointer descriptor.
151 ///
152 /// `width` is measured in elements of `T`.
153 /// CUDA's `cudaPitchedPtr::pitch` and `xsize` fields are measured in bytes for linear memory, and `ysize` records the logical height.
154 ///
155 /// # Safety
156 ///
157 /// The returned allocation is uninitialized device memory.
158 /// The caller must treat it as a `width` by `height` by `depth` pitched allocation and free the base pointer with a CUDA-compatible device free.
159 ///
160 /// # Errors
161 ///
162 /// Returns an error if `context` cannot be bound, the requested byte volume overflows, `T` is a non-empty zero-sized allocation, CUDA cannot allocate pitched memory, or CUDA returns a null allocation for a non-empty request.
163 pub unsafe fn alloc_pitched_3d(
164 context: &Context,
165 width: usize,
166 height: usize,
167 depth: usize,
168 ) -> Result<runtime::cudaPitchedPtr> {
169 context.bind()?;
170 let row_bytes = checked_bytes::<T>(width, "row bytes")?;
171 checked_element_count(&[row_bytes, height, depth], "volume bytes")?;
172 if row_bytes == 0 || height == 0 || depth == 0 {
173 return Ok(runtime::cudaPitchedPtr {
174 ptr: ptr::null_mut(),
175 pitch: row_bytes as _,
176 xsize: row_bytes as _,
177 ysize: height as _,
178 });
179 }
180
181 let mut pitched = runtime::cudaPitchedPtr::default();
182 // SAFETY: `pitched` is a local output, and the volume size was checked for overflow.
183 unsafe {
184 try_ffi!(runtime::cudaMalloc3D(
185 &raw mut pitched,
186 runtime::cudaExtent {
187 width: row_bytes as _,
188 height: height as _,
189 depth: depth as _,
190 },
191 ))?;
192 }
193
194 if pitched.ptr.is_null() {
195 return Err(Error::NullHandle);
196 }
197 Ok(pitched)
198 }
199
200 /// Copies `count` elements from `src` to `dst`.
201 /// The transfer direction is specified by [`MemoryCopyKind`].
202 /// [`MemoryCopyKind::Default`] is recommended when unified virtual addressing is available, in which case the transfer direction is inferred from the pointer values.
203 /// Calling [`DeviceMemory::copy`] with `dst` and `src` pointers that do not match the direction of the copy results in undefined behavior.
204 ///
205 /// The copy is synchronous with respect to the host for most pointer combinations.
206 /// Each range must be entirely registered with CUDA or, for pageable host transfers, not registered at all.
207 /// A range spanning registered and unregistered allocations returns [`crate::error::Status::InvalidValue`].
208 ///
209 /// # Safety
210 ///
211 /// Device operands must belong to `context` or be accessible from it.
212 /// `src` and `dst` must be valid for `count` elements of `T` according to `kind`, and the source and destination regions must not overlap unless CUDA permits that transfer.
213 ///
214 /// # Errors
215 ///
216 /// Returns an error if `context` cannot be bound, the requested byte count overflows, CUDA rejects the pointer combination or copy kind, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
217 pub unsafe fn copy(
218 context: &Context,
219 dst: *mut T,
220 src: *const T,
221 count: usize,
222 kind: MemoryCopyKind,
223 ) -> Result<()> {
224 context.bind()?;
225 let bytes = checked_bytes::<T>(count, "byte count")?;
226 if bytes == 0 {
227 return Ok(());
228 }
229
230 // SAFETY: the caller guarantees `count` valid elements at both pointers for `kind`, and `bytes` was checked.
231 unsafe {
232 try_ffi!(runtime::cudaMemcpy(
233 dst.cast(),
234 src.cast(),
235 bytes as _,
236 kind.into(),
237 ))?;
238 }
239 Ok(())
240 }
241
242 /// Copies a typed 2D rectangle between pitched host or device memory regions.
243 ///
244 /// `width` and `height` are measured in elements and rows.
245 /// `dst_pitch` and `src_pitch` are byte strides between adjacent rows.
246 ///
247 /// # Safety
248 ///
249 /// Device operands must belong to `context` or be accessible from it.
250 /// `dst` and `src` must be valid for the described rectangle according to `kind`.
251 /// The source and destination regions must not overlap unless CUDA permits that transfer.
252 ///
253 /// # Errors
254 ///
255 /// Returns an error if `context` cannot be bound, the requested byte rectangle overflows, either pitch is smaller than the copied row width, CUDA rejects the pointer combination or copy kind, or a previous asynchronous launch reports an error.
256 pub unsafe fn copy_2d(
257 context: &Context,
258 dst: *mut T,
259 dst_pitch: usize,
260 src: *const T,
261 src_pitch: usize,
262 width: usize,
263 height: usize,
264 kind: MemoryCopyKind,
265 ) -> Result<()> {
266 context.bind()?;
267 let row_bytes = checked_bytes::<T>(width, "row bytes")?;
268 checked_element_count(&[row_bytes, height], "rectangle bytes")?;
269 if row_bytes == 0 || height == 0 {
270 return Ok(());
271 }
272
273 if row_bytes > dst_pitch {
274 return Err(Error::buffer_too_small(
275 "destination pitch",
276 row_bytes,
277 dst_pitch,
278 ));
279 }
280
281 if row_bytes > src_pitch {
282 return Err(Error::buffer_too_small(
283 "source pitch",
284 row_bytes,
285 src_pitch,
286 ));
287 }
288
289 // SAFETY: the caller guarantees both rectangles for `kind`, and both pitches were checked against the row width.
290 unsafe {
291 try_ffi!(runtime::cudaMemcpy2D(
292 dst.cast(),
293 dst_pitch as _,
294 src.cast(),
295 src_pitch as _,
296 row_bytes as _,
297 height as _,
298 kind.into(),
299 ))?;
300 }
301 Ok(())
302 }
303
304 /// Enqueues a typed 2D rectangle copy on `stream`.
305 ///
306 /// `width` and `height` are measured in elements and rows.
307 /// Pitches are byte strides between adjacent rows.
308 ///
309 /// # Safety
310 ///
311 /// `dst` and `src` must remain valid for the described rectangle until `stream` reaches the enqueued copy.
312 /// The pointer combination must match `kind`.
313 ///
314 /// # Errors
315 ///
316 /// Returns an error if the stream context cannot be bound, the requested byte rectangle overflows, either pitch is smaller than the copied row width, CUDA cannot enqueue the copy, or a previous asynchronous launch reports an error.
317 pub unsafe fn copy_2d_async(
318 dst: *mut T,
319 dst_pitch: usize,
320 src: *const T,
321 src_pitch: usize,
322 width: usize,
323 height: usize,
324 kind: MemoryCopyKind,
325 stream: &Stream,
326 ) -> Result<()> {
327 stream.context().bind()?;
328 let row_bytes = checked_bytes::<T>(width, "row bytes")?;
329 checked_element_count(&[row_bytes, height], "rectangle bytes")?;
330 if row_bytes == 0 || height == 0 {
331 return Ok(());
332 }
333
334 if row_bytes > dst_pitch {
335 return Err(Error::buffer_too_small(
336 "destination pitch",
337 row_bytes,
338 dst_pitch,
339 ));
340 }
341
342 if row_bytes > src_pitch {
343 return Err(Error::buffer_too_small(
344 "source pitch",
345 row_bytes,
346 src_pitch,
347 ));
348 }
349
350 // SAFETY: the caller keeps both rectangles valid until `stream` reaches the copy, and both pitches were checked.
351 unsafe {
352 try_ffi!(runtime::cudaMemcpy2DAsync(
353 dst.cast(),
354 dst_pitch as _,
355 src.cast(),
356 src_pitch as _,
357 row_bytes as _,
358 height as _,
359 kind.into(),
360 stream.as_raw(),
361 ))?;
362 }
363 Ok(())
364 }
365
366 /// Copies a typed 3D extent between CUDA pitched pointer operands.
367 ///
368 /// `width`, `height`, and `depth` are measured in elements, rows, and slices.
369 /// CUDA receives an extent whose width is converted to bytes.
370 ///
371 /// # Safety
372 ///
373 /// Device operands must belong to `context` or be accessible from it.
374 /// `dst` and `src` must describe live host or device memory large enough for the requested extent according to `kind`.
375 /// The source and destination regions must not overlap unless CUDA permits that transfer.
376 ///
377 /// # Errors
378 ///
379 /// Returns an error if `context` cannot be bound, the requested byte volume overflows, either pitch is smaller than the copied row width, CUDA rejects the copy parameters, or a previous asynchronous launch reports an error.
380 pub unsafe fn copy_3d(
381 context: &Context,
382 dst: runtime::cudaPitchedPtr,
383 src: runtime::cudaPitchedPtr,
384 width: usize,
385 height: usize,
386 depth: usize,
387 kind: MemoryCopyKind,
388 ) -> Result<()> {
389 context.bind()?;
390 let row_bytes = checked_bytes::<T>(width, "row bytes")?;
391 checked_element_count(&[row_bytes, height, depth], "volume bytes")?;
392 if row_bytes == 0 || height == 0 || depth == 0 {
393 return Ok(());
394 }
395
396 let dst_pitch = to_usize(dst.pitch, "destination pitch")?;
397 if row_bytes > dst_pitch {
398 return Err(Error::buffer_too_small(
399 "destination pitch",
400 row_bytes,
401 dst_pitch,
402 ));
403 }
404
405 let src_pitch = to_usize(src.pitch, "source pitch")?;
406 if row_bytes > src_pitch {
407 return Err(Error::buffer_too_small(
408 "source pitch",
409 row_bytes,
410 src_pitch,
411 ));
412 }
413
414 let params = runtime::cudaMemcpy3DParms {
415 srcArray: ptr::null_mut(),
416 srcPos: runtime::cudaPos::default(),
417 srcPtr: src,
418 dstArray: ptr::null_mut(),
419 dstPos: runtime::cudaPos::default(),
420 dstPtr: dst,
421 extent: runtime::cudaExtent {
422 width: row_bytes as _,
423 height: height as _,
424 depth: depth as _,
425 },
426 kind: kind.into(),
427 };
428 // SAFETY: `params` is a local, the caller guarantees both extents for `kind`, and both pitches were checked.
429 unsafe {
430 try_ffi!(runtime::cudaMemcpy3D(&raw const params))?;
431 }
432 Ok(())
433 }
434
435 /// Enqueues a typed 3D extent copy on `stream`.
436 ///
437 /// `width`, `height`, and `depth` are measured in elements, rows, and slices.
438 /// CUDA receives an extent whose width is converted to bytes.
439 ///
440 /// # Safety
441 ///
442 /// `dst` and `src` must remain valid for the described extent until `stream` reaches the enqueued copy.
443 /// The pointer combination must match `kind`.
444 ///
445 /// # Errors
446 ///
447 /// Returns an error if the stream context cannot be bound, the requested byte volume overflows, either pitch is smaller than the copied row width, CUDA cannot enqueue the copy, or a previous asynchronous launch reports an error.
448 pub unsafe fn copy_3d_async(
449 dst: runtime::cudaPitchedPtr,
450 src: runtime::cudaPitchedPtr,
451 width: usize,
452 height: usize,
453 depth: usize,
454 kind: MemoryCopyKind,
455 stream: &Stream,
456 ) -> Result<()> {
457 stream.context().bind()?;
458 let row_bytes = checked_bytes::<T>(width, "row bytes")?;
459 checked_element_count(&[row_bytes, height, depth], "volume bytes")?;
460 if row_bytes == 0 || height == 0 || depth == 0 {
461 return Ok(());
462 }
463
464 let dst_pitch = to_usize(dst.pitch, "destination pitch")?;
465 if row_bytes > dst_pitch {
466 return Err(Error::buffer_too_small(
467 "destination pitch",
468 row_bytes,
469 dst_pitch,
470 ));
471 }
472
473 let src_pitch = to_usize(src.pitch, "source pitch")?;
474 if row_bytes > src_pitch {
475 return Err(Error::buffer_too_small(
476 "source pitch",
477 row_bytes,
478 src_pitch,
479 ));
480 }
481
482 let params = runtime::cudaMemcpy3DParms {
483 srcArray: ptr::null_mut(),
484 srcPos: runtime::cudaPos::default(),
485 srcPtr: src,
486 dstArray: ptr::null_mut(),
487 dstPos: runtime::cudaPos::default(),
488 dstPtr: dst,
489 extent: runtime::cudaExtent {
490 width: row_bytes as _,
491 height: height as _,
492 depth: depth as _,
493 },
494 kind: kind.into(),
495 };
496 // SAFETY: `params` is a local read during the call, the caller keeps both extents valid until `stream` reaches the copy, and both pitches were checked.
497 unsafe {
498 try_ffi!(runtime::cudaMemcpy3DAsync(
499 &raw const params,
500 stream.as_raw(),
501 ))?;
502 }
503 Ok(())
504 }
505
506 /// Fills `count` elements at `dst` with the constant byte pattern `value`.
507 ///
508 /// This call is asynchronous with respect to the host unless `ptr` refers to pinned host memory.
509 ///
510 /// See the CUDA memset synchronization rules for when this operation blocks the host.
511 ///
512 /// # Safety
513 ///
514 /// Device operands must belong to `context` or be accessible from it.
515 /// `dst` must be valid for writes of `count * size_of::<T>()` bytes and must refer to memory that CUDA can memset.
516 ///
517 /// # Errors
518 ///
519 /// Returns an error if `context` cannot be bound, the requested byte count overflows, CUDA rejects the pointer or size, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
520 pub unsafe fn set(context: &Context, dst: *mut T, value: u8, count: usize) -> Result<()> {
521 context.bind()?;
522 let bytes = checked_bytes::<T>(count, "byte count")?;
523 if bytes == 0 {
524 return Ok(());
525 }
526
527 // SAFETY: the caller guarantees `bytes` writable bytes at `dst`.
528 unsafe {
529 try_ffi!(runtime::cudaMemset(dst.cast(), value.into(), bytes as _))?;
530 }
531 Ok(())
532 }
533
534 /// Fills a typed 2D pitched memory region with a byte value.
535 ///
536 /// `width` and `height` are measured in elements and rows.
537 /// `pitch` is the byte stride between adjacent rows.
538 ///
539 /// # Safety
540 ///
541 /// Device operands must belong to `context` or be accessible from it.
542 /// `dst` must be valid for writes over the described pitched rectangle and must refer to memory CUDA can memset.
543 ///
544 /// # Errors
545 ///
546 /// Returns an error if `context` cannot be bound, the requested byte rectangle overflows, `pitch` is smaller than the row width, CUDA rejects the memory region, or a previous asynchronous launch reports an error.
547 pub unsafe fn set_2d(
548 context: &Context,
549 dst: *mut T,
550 pitch: usize,
551 value: u8,
552 width: usize,
553 height: usize,
554 ) -> Result<()> {
555 context.bind()?;
556 let row_bytes = checked_bytes::<T>(width, "row bytes")?;
557 checked_element_count(&[row_bytes, height], "rectangle bytes")?;
558 if row_bytes == 0 || height == 0 {
559 return Ok(());
560 }
561
562 if row_bytes > pitch {
563 return Err(Error::buffer_too_small("pitch", row_bytes, pitch));
564 }
565
566 // SAFETY: the caller guarantees the writable rectangle, and `pitch` was checked against the row width.
567 unsafe {
568 try_ffi!(runtime::cudaMemset2D(
569 dst.cast(),
570 pitch as _,
571 value.into(),
572 row_bytes as _,
573 height as _,
574 ))?;
575 }
576 Ok(())
577 }
578
579 /// Fills a typed 3D pitched memory region with a byte value.
580 ///
581 /// `width`, `height`, and `depth` are measured in elements, rows, and slices.
582 /// CUDA receives an extent whose width is converted to bytes.
583 ///
584 /// # Safety
585 ///
586 /// Device operands must belong to `context` or be accessible from it.
587 /// `dst` must describe live memory large enough for the requested extent and must refer to memory CUDA can memset.
588 ///
589 /// # Errors
590 ///
591 /// Returns an error if `context` cannot be bound, the requested byte volume overflows, `dst.pitch` is smaller than the row width, CUDA rejects the memory region, or a previous asynchronous launch reports an error.
592 pub unsafe fn set_3d(
593 context: &Context,
594 dst: runtime::cudaPitchedPtr,
595 value: u8,
596 width: usize,
597 height: usize,
598 depth: usize,
599 ) -> Result<()> {
600 context.bind()?;
601 let row_bytes = checked_bytes::<T>(width, "row bytes")?;
602 checked_element_count(&[row_bytes, height, depth], "volume bytes")?;
603 if row_bytes == 0 || height == 0 || depth == 0 {
604 return Ok(());
605 }
606
607 let dst_pitch = to_usize(dst.pitch, "destination pitch")?;
608 if row_bytes > dst_pitch {
609 return Err(Error::buffer_too_small(
610 "destination pitch",
611 row_bytes,
612 dst_pitch,
613 ));
614 }
615
616 // SAFETY: the caller guarantees the writable extent, and `dst.pitch` was checked against the row width.
617 unsafe {
618 try_ffi!(runtime::cudaMemset3D(
619 dst,
620 value.into(),
621 runtime::cudaExtent {
622 width: row_bytes as _,
623 height: height as _,
624 depth: depth as _,
625 },
626 ))?;
627 }
628 Ok(())
629 }
630
631 /// Returns the free and total device memory, in bytes, seen from `context`.
632 /// CUDA is not guaranteed to be able to allocate all of the memory that the OS reports as free.
633 /// In a multi-tenant situation, the free-memory estimate is prone to a race condition: an allocation or free by another process or thread between estimation and reporting can make the reported free value differ from actual free memory.
634 ///
635 /// The integrated GPU on Tegra shares memory with CPU and other component of the `SoC`.
636 /// The free and total values returned by this call exclude the SWAP memory space maintained by the OS on some platforms.
637 /// The OS may move some of the memory pages into swap area as the GPU or CPU allocate or access memory.
638 /// See Tegra app note on how to calculate total and free memory on Tegra.
639 ///
640 /// # Errors
641 ///
642 /// Returns an error if `context` cannot be bound, CUDA cannot query memory information, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
643 pub fn memory_info(context: &Context) -> Result<(usize, usize)> {
644 context.bind()?;
645 let mut free: runtime::size_t = 0;
646 let mut total: runtime::size_t = 0;
647 // SAFETY: `free` and `total` are local outputs.
648 unsafe {
649 try_ffi!(runtime::cudaMemGetInfo(&raw mut free, &raw mut total))?;
650 }
651 Ok((
652 to_usize(free, "free device memory")?,
653 to_usize(total, "total device memory")?,
654 ))
655 }
656
657 /// Returns the attributes of `ptr`.
658 /// If `ptr` was not allocated in, mapped by, or registered with a context that supports unified addressing, [`crate::error::Status::InvalidValue`] is returned.
659 ///
660 /// In CUDA 11.0 and later, passing a host pointer reports [`MemoryType::Unregistered`](crate::memory::MemoryType::Unregistered) in [`PointerAttributes::memory_type`].
661 ///
662 /// * [`PointerAttributes::memory_type`] identifies the type of memory.
663 /// It can be [`MemoryType::Unregistered`](crate::memory::MemoryType::Unregistered) for unregistered host memory, [`MemoryType::Host`](crate::memory::MemoryType::Host) for registered host memory, [`MemoryType::Device`](crate::memory::MemoryType::Device) for device memory, or [`MemoryType::Managed`](crate::memory::MemoryType::Managed) for managed memory.
664 ///
665 /// * [`PointerAttributes::device`] is the device against which `ptr` was allocated.
666 /// If `ptr` has memory type [`MemoryType::Device`](crate::memory::MemoryType::Device), this identifies the device on which the memory physically resides.
667 /// If `ptr` has memory type [`MemoryType::Host`](crate::memory::MemoryType::Host), this identifies the device that was current when the allocation was made, and if that device is deinitialized then this allocation will vanish with that device's state.
668 ///
669 /// * [`PointerAttributes::device_pointer`] is the device pointer alias through which the memory referred to by `ptr` may be accessed on the current device.
670 /// If the memory referred to by `ptr` cannot be accessed directly by the current device then this is null.
671 ///
672 /// * [`PointerAttributes::host_pointer`] is the host pointer alias through which the memory referred to by `ptr` may be accessed on the host.
673 /// If the memory referred to by `ptr` cannot be accessed directly by the host then this is null.
674 ///
675 /// # Errors
676 ///
677 /// Returns an error if CUDA cannot query attributes for `ptr`, `ptr` is not known to a unified-addressing context, or CUDA reports runtime initialization diagnostics.
678 pub fn pointer_attributes(ptr: *const T) -> Result<PointerAttributes> {
679 PointerAttributes::query(ptr)
680 }
681
682 /// Enqueues a stream-ordered device allocation on `stream`.
683 ///
684 /// # Safety
685 ///
686 /// The returned pointer is uninitialized device memory whose lifetime is ordered by `stream`.
687 /// The caller must ensure all accesses are stream ordered correctly and free it with [`DeviceMemory::free_async`] or a compatible CUDA free after all accesses complete.
688 ///
689 /// # Errors
690 ///
691 /// Returns an error if the stream context cannot be bound, the requested byte size overflows, CUDA cannot enqueue the allocation, or `count` is non-zero for a zero-sized `T`.
692 pub unsafe fn alloc_async(count: usize, stream: &Stream) -> Result<*mut T> {
693 stream.context().bind()?;
694 let bytes = checked_bytes::<T>(count, "byte count")?;
695 if bytes == 0 {
696 return Ok(ptr::null_mut());
697 }
698
699 let mut p = ptr::null_mut();
700 // SAFETY: `p` is a local output, `bytes` is a checked nonzero size, and `stream` is borrowed live.
701 unsafe {
702 try_ffi!(runtime::cudaMallocAsync(
703 &raw mut p,
704 bytes as _,
705 stream.as_raw()
706 ))?;
707 }
708 Ok(p.cast::<T>())
709 }
710
711 /// Inserts a free operation into `stream`.
712 /// The allocation must not be accessed after stream execution reaches the free.
713 /// After this call returns, accessing the memory from any subsequent work launched on the GPU or querying its pointer attributes results in undefined behavior.
714 ///
715 /// During stream capture, this creates a free node and must therefore be passed the address of a graph allocation.
716 ///
717 /// # Safety
718 ///
719 /// `ptr` must be null or a live stream-ordered CUDA allocation.
720 /// No work may access it after `stream` reaches the enqueued free.
721 ///
722 /// # Errors
723 ///
724 /// Returns an error if the stream context cannot be bound, CUDA cannot enqueue the free on `stream`, `ptr` is invalid for asynchronous freeing, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
725 pub unsafe fn free_async(ptr: *mut T, stream: &Stream) -> Result<()> {
726 stream.context().bind()?;
727 if ptr.is_null() {
728 return Ok(());
729 }
730 // SAFETY: the caller passes a live stream-ordered allocation that no work uses after `stream` reaches this free.
731 unsafe { try_ffi!(runtime::cudaFreeAsync(ptr.cast(), stream.as_raw())) }
732 }
733
734 /// Enqueues a typed one-dimensional memory copy on `stream`.
735 ///
736 /// # Safety
737 ///
738 /// `dst` and `src` must remain valid for `count` elements until `stream` reaches the enqueued copy, and during every replay of a captured copy.
739 /// The pointer combination must match `kind` and the stream's context.
740 ///
741 /// # Errors
742 ///
743 /// Returns an error if the requested byte count overflows, the context cannot be bound, CUDA cannot enqueue the copy, the pointer combination is invalid for `kind`, or a previous asynchronous launch reports an error.
744 pub unsafe fn copy_async(
745 dst: *mut T,
746 src: *const T,
747 count: usize,
748 kind: MemoryCopyKind,
749 stream: &(impl AsStream + ?Sized),
750 ) -> Result<()> {
751 if count == 0 {
752 return Ok(());
753 }
754
755 let bytes = checked_bytes::<T>(count, "byte count")?;
756 if bytes == 0 {
757 return Ok(());
758 }
759
760 stream.context().bind()?;
761 // SAFETY: the caller keeps `count` elements at both pointers valid until the stream reaches the copy, and the stream's context is bound.
762 unsafe {
763 try_ffi!(runtime::cudaMemcpyAsync(
764 dst.cast(),
765 src.cast(),
766 bytes as _,
767 kind.into(),
768 stream.as_raw(),
769 ))?;
770 }
771 Ok(())
772 }
773
774 /// Enqueues a fill of `count` elements at `dst` with the byte `value` on `stream`.
775 ///
776 /// The call may return before the fill completes, and the fill may overlap work on other streams.
777 /// See the CUDA memset synchronization rules for when this operation blocks the host.
778 ///
779 /// # Safety
780 ///
781 /// `dst` must remain valid and exclusive for writes of `count * size_of::<T>()` bytes until `stream` reaches the enqueued memset, and during every replay of a captured fill.
782 ///
783 /// # Errors
784 ///
785 /// Returns an error if the requested byte count overflows, the context cannot be bound, CUDA cannot enqueue the memset on `stream`, or a previous asynchronous launch reports an error.
786 pub unsafe fn set_async(
787 dst: *mut T,
788 value: u8,
789 count: usize,
790 stream: &(impl AsStream + ?Sized),
791 ) -> Result<()> {
792 if count == 0 {
793 return Ok(());
794 }
795
796 let bytes = checked_bytes::<T>(count, "byte count")?;
797 if bytes == 0 {
798 return Ok(());
799 }
800
801 stream.context().bind()?;
802 // SAFETY: the caller keeps `bytes` bytes at `dst` writable until the stream reaches the fill, and the stream's context is bound.
803 unsafe {
804 try_ffi!(runtime::cudaMemsetAsync(
805 dst.cast(),
806 value.into(),
807 bytes as _,
808 stream.as_raw(),
809 ))?;
810 }
811 Ok(())
812 }
813
814 /// Enqueues a 2D pitched memset on `stream`.
815 ///
816 /// `width` and `height` are measured in elements and rows.
817 /// `pitch` is the byte stride between adjacent rows.
818 ///
819 /// # Safety
820 ///
821 /// `dst` must remain valid for writes over the described pitched rectangle until `stream` reaches the enqueued memset.
822 ///
823 /// # Errors
824 ///
825 /// Returns an error if the stream context cannot be bound, the requested byte rectangle overflows, `pitch` is smaller than the row width, CUDA cannot enqueue the memset, or a previous asynchronous launch reports an error.
826 pub unsafe fn set_2d_async(
827 dst: *mut T,
828 pitch: usize,
829 value: u8,
830 width: usize,
831 height: usize,
832 stream: &Stream,
833 ) -> Result<()> {
834 stream.context().bind()?;
835 let row_bytes = checked_bytes::<T>(width, "row bytes")?;
836 checked_element_count(&[row_bytes, height], "rectangle bytes")?;
837 if row_bytes == 0 || height == 0 {
838 return Ok(());
839 }
840
841 if row_bytes > pitch {
842 return Err(Error::buffer_too_small("pitch", row_bytes, pitch));
843 }
844
845 // SAFETY: the caller keeps the rectangle writable until `stream` reaches the fill, and `pitch` was checked against the row width.
846 unsafe {
847 try_ffi!(runtime::cudaMemset2DAsync(
848 dst.cast(),
849 pitch as _,
850 value.into(),
851 row_bytes as _,
852 height as _,
853 stream.as_raw(),
854 ))?;
855 }
856 Ok(())
857 }
858
859 /// Enqueues a 3D pitched memset on `stream`.
860 ///
861 /// `width`, `height`, and `depth` are measured in elements, rows, and slices.
862 /// CUDA receives an extent whose width is converted to bytes.
863 ///
864 /// # Safety
865 ///
866 /// `dst` must remain valid for the described extent until `stream` reaches the enqueued memset.
867 ///
868 /// # Errors
869 ///
870 /// Returns an error if the stream context cannot be bound, the requested byte volume overflows, `dst.pitch` is smaller than the row width, CUDA cannot enqueue the memset, or a previous asynchronous launch reports an error.
871 pub unsafe fn set_3d_async(
872 dst: runtime::cudaPitchedPtr,
873 value: u8,
874 width: usize,
875 height: usize,
876 depth: usize,
877 stream: &Stream,
878 ) -> Result<()> {
879 stream.context().bind()?;
880 let row_bytes = checked_bytes::<T>(width, "row bytes")?;
881 checked_element_count(&[row_bytes, height, depth], "volume bytes")?;
882 if row_bytes == 0 || height == 0 || depth == 0 {
883 return Ok(());
884 }
885
886 let dst_pitch = to_usize(dst.pitch, "destination pitch")?;
887 if row_bytes > dst_pitch {
888 return Err(Error::buffer_too_small(
889 "destination pitch",
890 row_bytes,
891 dst_pitch,
892 ));
893 }
894
895 // SAFETY: the caller keeps the extent writable until `stream` reaches the fill, and `dst.pitch` was checked against the row width.
896 unsafe {
897 try_ffi!(runtime::cudaMemset3DAsync(
898 dst,
899 value.into(),
900 runtime::cudaExtent {
901 width: row_bytes as _,
902 height: height as _,
903 depth: depth as _,
904 },
905 stream.as_raw(),
906 ))?;
907 }
908 Ok(())
909 }
910
911 /// Enqueues a prefetch of `count` bytes at `ptr` to `location` on `stream`.
912 ///
913 /// The memory range must refer to managed memory allocated via [`DeviceMemory::alloc_managed`] or declared via `__managed__` variables.
914 /// It may also refer to memory allocated from a managed memory pool, or to system-allocated memory on systems where [`DeviceProperties::pageable_memory_access`](crate::device::DeviceProperties::pageable_memory_access) is enabled.
915 ///
916 /// Using [`MemoryLocation::Device`] prefetches memory to the GPU identified by its device ID.
917 /// That device, and the device associated with `stream`, must support concurrent managed access.
918 /// Using [`MemoryLocation::Host`] prefetches data to host memory.
919 /// Applications can request prefetching memory to a specific host NUMA node by using [`MemoryLocation::Numa`] with a valid NUMA node identifier, or to the NUMA node closest to the current thread's CPU by using [`MemoryLocation::NumaCurrent`].
920 ///
921 /// The start and end addresses of the memory range are rounded down and up, respectively, to CPU page-size alignment before the prefetch operation is enqueued in the stream.
922 ///
923 /// If no physical memory has been allocated for this region, CUDA populates and maps it on the destination device.
924 /// If there is insufficient memory to prefetch the desired region, the Unified Memory driver may evict pages from other [`DeviceMemory::alloc_managed`] allocations to host memory to make room.
925 /// Device memory allocated using [`DeviceMemory::alloc`] or [`sys::cudaMallocArray`](singe_cuda_sys::runtime::cudaMallocArray) is not evicted.
926 ///
927 /// By default, mappings to the previous location of the migrated pages are removed and mappings for the new location are only set up at the destination.
928 /// The exact behavior also depends on the advice applied to this memory range with [`DeviceMemory::advise`]:
929 ///
930 /// If read-mostly advice was set on any subset of this memory range, then that subset will create a read-only copy of the pages at the destination location.
931 /// If the destination location is a host NUMA node, any pages of that subset that are already in another host NUMA node are transferred to the destination.
932 ///
933 /// If preferred-location advice was set on any subset of this memory range, then the pages will migrate to `location` even if it is not the preferred location of every page in the range.
934 ///
935 /// If accessed-by advice was set on any subset of this memory range, then mappings to those pages from all appropriate processors are updated to refer to the new location if establishing such a mapping is possible.
936 /// Otherwise, those mappings are cleared.
937 ///
938 /// This is not required for correctness; it improves performance by allowing the application to migrate data to a suitable location before access.
939 /// Memory accesses to this range are always coherent and are allowed even when the data is actively being migrated.
940 ///
941 /// This call is asynchronous with respect to the host and all work on other devices.
942 ///
943 /// # Errors
944 ///
945 /// Returns an error if the stream context cannot be bound, CUDA cannot enqueue the prefetch on `stream`, the memory range or destination location is invalid, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
946 pub fn prefetch(
947 ptr: DevicePtr,
948 count: usize,
949 location: MemoryLocation,
950 stream: &Stream,
951 ) -> Result<()> {
952 stream.context().bind()?;
953 if count == 0 {
954 return Ok(());
955 }
956
957 // SAFETY: prefetching migrates pages without changing their contents, CUDA rejects ranges it does not manage, and `stream` is borrowed live.
958 unsafe {
959 try_ffi!(runtime::cudaMemPrefetchAsync(
960 ptr.as_const_ptr().cast(),
961 count as _,
962 location.into(),
963 0, // flags
964 stream.as_raw()
965 ))?;
966 }
967 Ok(())
968 }
969
970 /// Applies a managed-memory advice policy to a byte range.
971 ///
972 /// The memory range must refer to managed memory, a managed memory-pool allocation, or pageable memory on systems that support pageable memory access.
973 ///
974 /// # Errors
975 ///
976 /// Returns an error if CUDA rejects the advice, memory range, or location, or if a previous asynchronous launch reports an error.
977 pub fn advise(
978 ptr: DevicePtr,
979 count: usize,
980 advice: MemoryAdvise,
981 location: MemoryLocation,
982 ) -> Result<()> {
983 if count == 0 {
984 return Ok(());
985 }
986
987 // SAFETY: advice changes only migration policy, not contents, and CUDA rejects ranges it does not manage.
988 unsafe {
989 try_ffi!(runtime::cudaMemAdvise(
990 ptr.as_ptr().cast_const().cast(),
991 count as _,
992 advice.into(),
993 location.into(),
994 ))?;
995 }
996 Ok(())
997 }
998}