Skip to main content

singe_cuda/memory/
pool.rs

1use std::{ptr, result::Result as StdResult, sync::Arc};
2
3use num_enum::{IntoPrimitive, TryFromPrimitive};
4use singe_core::{impl_enum_display, report_cleanup_failure};
5
6use singe_cuda_sys::driver;
7
8use crate::{
9    context::Context,
10    error::{Error, Result},
11    memory::MemoryLocation,
12    try_ffi,
13    utility::{to_u32, to_u64, usage_bits},
14    virtual_memory::AllocationHandleTypes,
15};
16
17impl MemoryPool {
18    /// Creates a CUDA memory pool.
19    /// `props` determines the properties of the pool such as the backing device and IPC capabilities.
20    ///
21    /// To create a memory pool for host memory not targeting a specific NUMA node, applications must set [`MemoryPoolProps::location`] to [`MemoryLocation::Host`].
22    /// [`MemoryLocation`] is ignored for such pools.
23    /// Pools created with [`MemoryLocation::Host`] are not IPC-capable and [`MemoryPoolProps::handle_types`] must be empty; any other value returns [`crate::error::Status::InvalidValue`].
24    /// To create a memory pool targeting a specific host NUMA node, applications must set [`MemoryLocation`] to [`MemoryLocation::Numa`] and [`MemoryLocation`] must specify the NUMA ID of the host memory node.
25    /// Specifying [`MemoryLocation::NumaCurrent`] as [`MemoryLocation`] returns [`crate::error::Status::InvalidValue`].
26    /// By default, the pool's memory is accessible from the device where it is allocated.
27    /// Pools created with [`MemoryLocation::Numa`] or [`MemoryLocation::Host`] are accessible from the host CPU by default.
28    /// Applications can control the maximum size of the pool by specifying a non-zero value for [`MemoryPoolProps::max_size`].
29    /// A value of 0 uses a system-dependent maximum pool size.
30    ///
31    /// Callers that intend to use [`AllocationHandleTypes::FABRIC`] based memory sharing must ensure: (1) the `nvidia-caps-imex-channels` character device is created by the driver and is listed under `/proc/devices`; (2) at least one IMEX channel file is accessible to the process.
32    ///
33    /// When exporter and importer CUDA processes have been granted access to the same IMEX channel, they can securely share memory.
34    ///
35    /// The IMEX channel security model works per operating-system account.
36    /// All processes for an account can share memory if that account has access to a valid IMEX channel.
37    /// When isolation between accounts is desired, each account needs a separate IMEX channel.
38    ///
39    /// These channel files exist in `/dev/nvidia-caps-imex-channels/channel*` and can be created using standard OS native calls like `mknod` on Linux.
40    ///
41    /// To create a managed memory pool, applications must set [`MemoryPoolProps::alloc_type`] to [`MemoryAllocationType::Managed`].
42    /// [`MemoryPoolProps::handle_types`] must also be empty because IPC is not supported.
43    /// For managed memory pools, [`MemoryPoolProps::location`] is treated as the preferred location for all allocations created from the pool.
44    /// An application can also set [`MemoryLocation::Unspecified`] to indicate no preferred location.
45    /// [`MemoryPoolProps::max_size`] must be set to zero for managed memory pools.
46    /// [`MemoryPoolProps::usage`] must be zero because decompression for managed memory is not supported.
47    /// For managed memory pools, every device on the system must report [`DeviceAttribute::ConcurrentManagedAccess`](crate::device::DeviceAttribute::ConcurrentManagedAccess).
48    /// If not, this call returns [`crate::error::Status::NotSupported`].
49    ///
50    /// Empty [`MemoryPoolProps::handle_types`] create a memory pool that does not support IPC.
51    ///
52    /// # Errors
53    ///
54    /// Returns an error if `props` describes an unsupported pool, CUDA cannot create the pool, or CUDA returns a null memory-pool handle.
55    pub fn create(context: &Arc<Context>, props: MemoryPoolProps) -> Result<Self> {
56        context.bind()?;
57        let mut handle = ptr::null_mut();
58        let props = driver::CUmemPoolProps::from(props);
59        // SAFETY: `handle` is a writable local, `props` is a converted local that outlives the call, and `context` is bound.
60        unsafe {
61            try_ffi!(driver::cuMemPoolCreate(&raw mut handle, &raw const props))?;
62        }
63
64        if handle.is_null() {
65            return Err(Error::NullHandle);
66        }
67        Ok(Self {
68            owner: Arc::new(MemoryPoolOwner {
69                context: Arc::clone(context),
70                handle,
71                owned: true,
72            }),
73        })
74    }
75
76    /// Sets a pool attribute.
77    ///
78    /// Settable attributes are:
79    ///
80    /// * [`MemoryPoolAttribute::ReleaseThreshold`]: the reserved bytes the pool keeps before it tries to release memory back to the OS.
81    ///   When the pool holds more, it tries to release memory at the next stream, event, or context synchronization.
82    ///   The default is 0.
83    /// * [`MemoryPoolAttribute::ReuseFollowEventDependencies`]: lets a stream-ordered allocation reuse memory freed in another stream when the allocating stream depends on the free.
84    ///   Events and the null stream can create that dependency.
85    ///   The default is enabled.
86    /// * [`MemoryPoolAttribute::ReuseAllowOpportunistic`]: lets an allocation reuse a completed free that it has no dependency on.
87    ///   The default is enabled.
88    /// * [`MemoryPoolAttribute::ReuseAllowInternalDependencies`]: lets a stream-ordered allocation insert stream dependencies so it can reuse memory freed in another stream.
89    ///   The default is enabled.
90    /// * [`MemoryPoolAttribute::ReservedMemoryHigh`]: resets the high watermark of the pool's backing memory, and only accepts zero.
91    /// * [`MemoryPoolAttribute::UsedMemoryHigh`]: resets the high watermark of the pool's memory in use, and only accepts zero.
92    ///
93    /// # Errors
94    ///
95    /// Returns an error if the value variant does not match the attribute, the context cannot be bound, or CUDA rejects the attribute or value.
96    /// Current-usage statistics are read-only, and high watermarks only reset to zero.
97    pub fn set_attribute(
98        &mut self,
99        attribute: MemoryPoolAttribute,
100        value: MemoryPoolAttributeValue,
101    ) -> Result<()> {
102        self.context().bind()?;
103        // SAFETY: the pool handle is live and its context is bound, and each `value` is a local of the width CUDA reads for its attribute: `u32` for the reuse flags, `u64` for byte counts.
104        unsafe {
105            match (attribute, value) {
106                (
107                    MemoryPoolAttribute::ReuseFollowEventDependencies
108                    | MemoryPoolAttribute::ReuseAllowOpportunistic
109                    | MemoryPoolAttribute::ReuseAllowInternalDependencies,
110                    MemoryPoolAttributeValue::Bool(value),
111                ) => {
112                    let mut value = u32::from(value);
113                    try_ffi!(driver::cuMemPoolSetAttribute(
114                        self.owner.handle,
115                        attribute.into(),
116                        ptr::from_mut(&mut value).cast(),
117                    ))?;
118                }
119                (
120                    MemoryPoolAttribute::ReleaseThreshold
121                    | MemoryPoolAttribute::ReservedMemoryCurrent
122                    | MemoryPoolAttribute::ReservedMemoryHigh
123                    | MemoryPoolAttribute::UsedMemoryCurrent
124                    | MemoryPoolAttribute::UsedMemoryHigh,
125                    MemoryPoolAttributeValue::Bytes(value),
126                ) => {
127                    let mut value = value;
128                    try_ffi!(driver::cuMemPoolSetAttribute(
129                        self.owner.handle,
130                        attribute.into(),
131                        ptr::from_mut(&mut value).cast(),
132                    ))?;
133                }
134                _ => return Err(Error::out_of_range("memory pool attribute value")),
135            }
136        }
137        Ok(())
138    }
139
140    /// Returns a pool attribute.
141    ///
142    /// Besides the settable attributes described at [`MemoryPool::set_attribute`], it reports:
143    ///
144    /// * [`MemoryPoolAttribute::ReservedMemoryCurrent`]: the backing memory the pool holds.
145    /// * [`MemoryPoolAttribute::ReservedMemoryHigh`]: the high watermark of backing memory since the last reset.
146    /// * [`MemoryPoolAttribute::UsedMemoryCurrent`]: the pool's memory in use by the application.
147    /// * [`MemoryPoolAttribute::UsedMemoryHigh`]: the high watermark of memory in use since the last reset.
148    ///
149    /// # Errors
150    ///
151    /// Returns an error if the context cannot be bound or CUDA cannot report the attribute.
152    pub fn attribute(&self, attribute: MemoryPoolAttribute) -> Result<MemoryPoolAttributeValue> {
153        self.context().bind()?;
154        // SAFETY: the pool handle is live and its context is bound, and each `value` is a writable local of the width CUDA writes for its attribute: `u32` for the reuse flags, `u64` for byte counts.
155        unsafe {
156            match attribute {
157                MemoryPoolAttribute::ReuseFollowEventDependencies
158                | MemoryPoolAttribute::ReuseAllowOpportunistic
159                | MemoryPoolAttribute::ReuseAllowInternalDependencies => {
160                    let mut value = 0u32;
161                    try_ffi!(driver::cuMemPoolGetAttribute(
162                        self.owner.handle,
163                        attribute.into(),
164                        ptr::from_mut(&mut value).cast(),
165                    ))?;
166                    Ok(MemoryPoolAttributeValue::Bool(value != 0))
167                }
168                MemoryPoolAttribute::ReleaseThreshold
169                | MemoryPoolAttribute::ReservedMemoryCurrent
170                | MemoryPoolAttribute::ReservedMemoryHigh
171                | MemoryPoolAttribute::UsedMemoryCurrent
172                | MemoryPoolAttribute::UsedMemoryHigh => {
173                    let mut value = 0u64;
174                    try_ffi!(driver::cuMemPoolGetAttribute(
175                        self.owner.handle,
176                        attribute.into(),
177                        ptr::from_mut(&mut value).cast(),
178                    ))?;
179                    Ok(MemoryPoolAttributeValue::Bytes(value))
180                }
181            }
182        }
183    }
184
185    /// Sets which locations can access the pool's memory, and how.
186    ///
187    /// # Errors
188    ///
189    /// Returns an error if the context cannot be bound or CUDA rejects the access descriptors.
190    pub fn set_access(&mut self, access_descs: &[MemoryAccessDescriptor]) -> Result<()> {
191        self.context().bind()?;
192        let access_descs: Vec<_> = access_descs.iter().copied().map(Into::into).collect();
193        let count = to_u64(access_descs.len(), "memory pool access descriptor count")?;
194        // SAFETY: the pool handle is live and its context is bound, and `access_descs` is a local vector of `count` converted descriptors.
195        unsafe {
196            try_ffi!(driver::cuMemPoolSetAccess(
197                self.owner.handle,
198                access_descs.as_ptr(),
199                count,
200            ))?;
201        }
202        Ok(())
203    }
204
205    /// Returns the accessibility of the pool's memory from the specified location.
206    ///
207    /// # Errors
208    ///
209    /// Returns an error if the context cannot be bound or CUDA cannot report access from `location`.
210    pub fn access(&self, location: MemoryLocation) -> Result<MemoryAccessFlag> {
211        self.context().bind()?;
212        let mut flags = driver::CUmemAccess_flags::CU_MEM_ACCESS_FLAGS_PROT_NONE;
213        let mut location = driver::CUmemLocation_st::from(location);
214        // SAFETY: `flags` and `location` are writable locals, the pool handle is live, and its context is bound.
215        unsafe {
216            try_ffi!(driver::cuMemPoolGetAccess(
217                &raw mut flags,
218                self.owner.handle,
219                &raw mut location,
220            ))?;
221        }
222        Ok(flags.try_into()?)
223    }
224
225    /// Releases memory back to the OS until the pool holds fewer than `min_bytes_to_keep` reserved bytes or has no more memory it can release.
226    /// The allocator cannot release OS allocations that back outstanding asynchronous allocations.
227    /// The OS allocations may happen at different granularity from the caller's allocations.
228    ///
229    /// * Allocations that have not been freed count as outstanding.
230    /// * Allocations that have been asynchronously freed but whose completion has not been observed on the host, for example by synchronization, can count as outstanding.
231    ///
232    /// # Errors
233    ///
234    /// Returns an error if the context cannot be bound or CUDA cannot trim the pool.
235    pub fn trim_to(&mut self, min_bytes_to_keep: usize) -> Result<()> {
236        let min_bytes_to_keep = to_u64(min_bytes_to_keep, "minimum bytes to keep")?;
237        self.context().bind()?;
238        // SAFETY: the pool handle is live, its context is bound, and the byte count is a plain integer.
239        unsafe {
240            try_ffi!(driver::cuMemPoolTrimTo(
241                self.owner.handle,
242                min_bytes_to_keep
243            ))?;
244        }
245        Ok(())
246    }
247
248    /// Returns the raw CUDA memory pool handle.
249    #[must_use]
250    pub fn as_raw(&self) -> driver::CUmemoryPool {
251        self.owner.handle
252    }
253}
254
255impl MemoryPool {
256    /// Returns the CUDA context retained by this allocation or pool.
257    #[must_use]
258    pub fn context(&self) -> &Arc<Context> {
259        &self.owner.context
260    }
261
262    /// Takes ownership of a CUDA pool created for this context.
263    ///
264    /// # Safety
265    ///
266    /// The handle must identify a live pool that the caller may destroy.
267    /// It must not be a driver-owned default pool or have another destroying owner.
268    ///
269    /// # Errors
270    ///
271    /// Returns an error if the pool handle is null.
272    pub unsafe fn from_raw(raw: RawMemoryPool) -> Result<Self> {
273        if raw.handle.is_null() {
274            return Err(Error::NullHandle);
275        }
276        Ok(Self {
277            owner: Arc::new(MemoryPoolOwner {
278                context: raw.context,
279                handle: raw.handle,
280                owned: true,
281            }),
282        })
283    }
284
285    /// Transfers an owned handle only when no allocations or other owners retain it.
286    /// Driver-owned pools cannot transfer destruction responsibility.
287    ///
288    /// # Errors
289    ///
290    /// Returns the wrapper unchanged as the error if the pool is driver-owned or another wrapper or allocation retains it.
291    pub fn into_raw(self) -> StdResult<RawMemoryPool, Self> {
292        if !self.owner.owned {
293            return Err(self);
294        }
295        match Arc::try_unwrap(self.owner) {
296            Ok(mut owner) => {
297                owner.owned = false;
298                Ok(RawMemoryPool {
299                    handle: owner.handle,
300                    context: Arc::clone(&owner.context),
301                })
302            }
303            Err(owner) => Err(Self { owner }),
304        }
305    }
306}
307
308impl MemoryPool {
309    /// Borrows a driver-owned default pool for a location and allocation kind.
310    ///
311    /// # Errors
312    ///
313    /// Returns an error if the context cannot be bound, CUDA has no default pool for the location and allocation type, or CUDA returns a null handle.
314    pub fn default_for(
315        context: &Arc<Context>,
316        location: MemoryLocation,
317        allocation_type: MemoryAllocationType,
318    ) -> Result<Self> {
319        context.bind()?;
320        let mut handle = ptr::null_mut();
321        let mut location = driver::CUmemLocation::from(location);
322        // SAFETY: `handle` and `location` are writable locals, and `context` is bound.
323        unsafe {
324            try_ffi!(driver::cuMemGetDefaultMemPool(
325                &raw mut handle,
326                &raw mut location,
327                allocation_type.into()
328            ))?;
329        }
330
331        if handle.is_null() {
332            return Err(Error::NullHandle);
333        }
334        Ok(Self {
335            owner: Arc::new(MemoryPoolOwner {
336                context: Arc::clone(context),
337                handle,
338                owned: false,
339            }),
340        })
341    }
342
343    /// Selects this pool for future implicit allocations of its location and kind.
344    ///
345    /// This changes CUDA's shared pool selection.
346    /// Destroying the selected owned pool restores the driver's default pool.
347    /// Existing allocations retain their original backing memory regardless of later selection changes.
348    ///
349    /// # Errors
350    ///
351    /// Returns an error if the context cannot be bound, the pool's location or allocation type cannot be read, or CUDA rejects the selection.
352    pub fn set_current(&self) -> Result<()> {
353        self.context().bind()?;
354        let mut location = driver::CUmemLocation::from(self.location()?);
355        let allocation_type = self.allocation_type()?;
356        // SAFETY: `location` is a writable local, the pool handle is live for `&self`, and its context is bound.
357        unsafe {
358            try_ffi!(driver::cuMemSetMemPool(
359                &raw mut location,
360                allocation_type.into(),
361                self.as_raw(),
362            ))
363        }
364    }
365}
366
367impl Context {
368    /// Borrows the device's default pool while retaining its CUDA context.
369    ///
370    /// # Errors
371    ///
372    /// Returns an error if the context cannot be bound, CUDA cannot look up the default pool, or CUDA returns a null handle.
373    pub fn default_memory_pool(self: &Arc<Self>) -> Result<MemoryPool> {
374        MemoryPool::default_for(
375            self,
376            MemoryLocation::Device(self.device().id()),
377            MemoryAllocationType::Pinned,
378        )
379    }
380}
381
382impl PoolAttributeValue for i32 {}
383
384impl PoolAttributeValue for u32 {}
385
386impl PoolAttributeValue for u64 {}
387
388impl MemoryPool {
389    /// Returns the locality domain ID of a localized pool, or `None` for a full-device pool.
390    ///
391    /// # Errors
392    ///
393    /// Returns an error if the context cannot be bound, CUDA cannot report the attribute, or the identifier is negative other than the full-device value of -1.
394    pub fn locality_domain_id(&self) -> Result<Option<u32>> {
395        let location_type = self.location_type()?;
396        if location_type != driver::CUmemLocationType::CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN {
397            return Ok(None);
398        }
399
400        let value: i32 =
401            self.read_attribute(driver::CUmemPool_attribute::CU_MEMPOOL_ATTR_LOCALITY_DOMAIN_ID)?;
402        // CUDA normalizes a localized pool to a full-device pool on single-domain devices.
403        if value == -1 {
404            return Ok(None);
405        }
406
407        Ok(Some(to_u32(value, "locality domain id")?))
408    }
409
410    /// Returns the allocation type of the memory pool.
411    ///
412    /// # Errors
413    ///
414    /// Returns an error if the context cannot be bound, CUDA cannot report the attribute, or the value is not a known allocation type.
415    pub fn allocation_type(&self) -> Result<MemoryAllocationType> {
416        let value: u32 =
417            self.read_attribute(driver::CUmemPool_attribute::CU_MEMPOOL_ATTR_ALLOCATION_TYPE)?;
418        MemoryAllocationType::try_from(value).map_err(|_| Error::UnknownEnumValue {
419            name: "MemoryAllocationType".into(),
420            value: i64::from(value),
421        })
422    }
423
424    /// Returns the location of the memory pool.
425    ///
426    /// # Errors
427    ///
428    /// Returns an error if the context cannot be bound, CUDA cannot report the attributes, the location type is unknown, or an identifier does not fit the localized device representation.
429    pub fn location(&self) -> Result<MemoryLocation> {
430        let kind = self.location_type()?;
431        let id: i32 =
432            self.read_attribute(driver::CUmemPool_attribute::CU_MEMPOOL_ATTR_LOCATION_ID)?;
433        if let Some(locality_domain_id) = self.locality_domain_id()? {
434            return Ok(MemoryLocation::DeviceLocalityDomain {
435                device_id: id
436                    .try_into()
437                    .map_err(|_| Error::out_of_range("pool device id"))?,
438                locality_domain_id: locality_domain_id
439                    .try_into()
440                    .map_err(|_| Error::out_of_range("pool locality domain id"))?,
441            });
442        }
443        Ok(driver::CUmemLocation {
444            type_: kind,
445            __bindgen_anon_1: driver::CUmemLocation_st__bindgen_ty_1 { id },
446        }
447        .into())
448    }
449
450    /// Returns the maximum size of the pool in bytes, including alignment requirements.
451    ///
452    /// # Errors
453    ///
454    /// Returns an error if the context cannot be bound or CUDA cannot report the attribute.
455    pub fn maximum_size(&self) -> Result<u64> {
456        self.read_attribute(driver::CUmemPool_attribute::CU_MEMPOOL_ATTR_MAX_POOL_SIZE)
457    }
458
459    /// Returns whether hardware decompression is enabled for allocations from this pool.
460    ///
461    /// # Errors
462    ///
463    /// Returns an error if the context cannot be bound or CUDA cannot report the attribute.
464    pub fn hardware_decompression_enabled(&self) -> Result<bool> {
465        let value: i32 = self
466            .read_attribute(driver::CUmemPool_attribute::CU_MEMPOOL_ATTR_HW_DECOMPRESS_ENABLED)?;
467        Ok(value != 0)
468    }
469
470    /// Returns the handle types the pool can export.
471    ///
472    /// # Errors
473    ///
474    /// Returns an error if the context cannot be bound or CUDA cannot report the attribute.
475    pub fn export_handle_types(&self) -> Result<AllocationHandleTypes> {
476        let value: u32 =
477            self.read_attribute(driver::CUmemPool_attribute::CU_MEMPOOL_ATTR_EXPORT_HANDLE_TYPES)?;
478        Ok(AllocationHandleTypes::from_bits_retain(value))
479    }
480
481    fn location_type(&self) -> Result<driver::CUmemLocationType> {
482        let value: u32 =
483            self.read_attribute(driver::CUmemPool_attribute::CU_MEMPOOL_ATTR_LOCATION_TYPE)?;
484        Ok(driver::CUmemLocationType(value))
485    }
486
487    // Reads an integer-valued pool attribute; enum attributes are read as `u32`.
488    fn read_attribute<T: PoolAttributeValue>(
489        &self,
490        attribute: driver::CUmemPool_attribute,
491    ) -> Result<T> {
492        self.context().bind()?;
493        let mut value = T::default();
494        // SAFETY: `T` is an integer type whose size matches the attribute's documented representation, `value` is a writable local, the pool handle is live, and its context is bound.
495        unsafe {
496            try_ffi!(driver::cuMemPoolGetAttribute(
497                self.as_raw(),
498                attribute,
499                (&raw mut value).cast()
500            ))?;
501        }
502        Ok(value)
503    }
504}
505
506bitflags::bitflags! {
507    /// Usage restrictions for allocations from a memory pool.
508    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
509    pub struct MemoryPoolUsage: u16 {
510        /// Allocations from this pool will be used for hardware decompression.
511        const HARDWARE_DECOMPRESSION = usage_bits(driver::CU_MEM_POOL_CREATE_USAGE_HW_DECOMPRESS);
512    }
513}
514
515singe_core::native_enum! {
516    /// Kind of physical memory backing an allocation.
517    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
518    #[repr(u32)]
519    #[non_exhaustive]
520    pub enum MemoryAllocationType: driver::CUmemAllocationType {
521        /// Memory that cannot migrate from its current location while the application uses it.
522        Pinned = CU_MEM_ALLOCATION_TYPE_PINNED,
523        /// This allocation type is managed memory.
524        Managed = CU_MEM_ALLOCATION_TYPE_MANAGED,
525    }
526}
527
528singe_core::native_enum! {
529    /// Specifies the memory protection flags for mapping.
530    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
531    #[repr(u32)]
532    #[non_exhaustive]
533    pub enum MemoryAccessFlag: driver::CUmemAccess_flags {
534        /// Default, make the address range not accessible.
535        None = CU_MEM_ACCESS_FLAGS_PROT_NONE,
536        /// Make the address range read accessible.
537        Read = CU_MEM_ACCESS_FLAGS_PROT_READ,
538        /// Make the address range read-write accessible.
539        ReadWrite = CU_MEM_ACCESS_FLAGS_PROT_READWRITE,
540    }
541}
542
543singe_core::native_enum! {
544    /// Attribute of a CUDA memory pool, read and written as a [`MemoryPoolAttributeValue`].
545    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
546    #[repr(u32)]
547    #[non_exhaustive]
548    pub enum MemoryPoolAttribute: driver::CUmemPool_attribute {
549        /// Allows stream-ordered allocations to reuse memory freed on another stream when the allocating stream depends on that free.
550        /// Events and default-stream interactions can create the dependency.
551        /// A [`MemoryPoolAttributeValue::Bool`], enabled by default.
552        ReuseFollowEventDependencies = CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES,
553        /// Allows reuse of completed frees that the allocation does not depend on.
554        /// A [`MemoryPoolAttributeValue::Bool`], enabled by default.
555        ReuseAllowOpportunistic = CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC,
556        /// Allows stream-ordered allocations to insert stream dependencies so they can reuse memory from stream-ordered frees.
557        /// A [`MemoryPoolAttributeValue::Bool`], enabled by default.
558        ReuseAllowInternalDependencies = CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES,
559        /// Reserved bytes the pool holds before releasing memory back to the operating system.
560        /// Above the threshold, the allocator releases memory at the next stream, event, or context synchronization.
561        /// A [`MemoryPoolAttributeValue::Bytes`], zero by default.
562        ReleaseThreshold = CU_MEMPOOL_ATTR_RELEASE_THRESHOLD,
563        /// Backing memory currently allocated for the pool, as [`MemoryPoolAttributeValue::Bytes`].
564        ReservedMemoryCurrent = CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT,
565        /// High watermark of backing memory since the last reset, as [`MemoryPoolAttributeValue::Bytes`].
566        /// It can only be reset to zero.
567        ReservedMemoryHigh = CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH,
568        /// Pool memory currently in use by the application, as [`MemoryPoolAttributeValue::Bytes`].
569        UsedMemoryCurrent = CU_MEMPOOL_ATTR_USED_MEM_CURRENT,
570        /// High watermark of pool memory in use since the last reset, as [`MemoryPoolAttributeValue::Bytes`].
571        /// It can only be reset to zero.
572        UsedMemoryHigh = CU_MEMPOOL_ATTR_USED_MEM_HIGH,
573    }
574}
575
576/// Typed value supplied to or returned from a CUDA memory-pool attribute.
577#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
578#[non_exhaustive]
579pub enum MemoryPoolAttributeValue {
580    /// Boolean value for a pool reuse policy.
581    Bool(
582        /// Whether the policy is enabled.
583        bool,
584    ),
585    /// Unsigned byte count for a pool threshold or memory-usage statistic.
586    Bytes(
587        /// Number of bytes.
588        u64,
589    ),
590}
591
592/// Access permissions granted to a CUDA memory location.
593#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
594pub struct MemoryAccessDescriptor {
595    /// Memory location whose access permissions are being specified.
596    pub location: MemoryLocation,
597    /// Read and write permissions granted at the location.
598    pub flags: MemoryAccessFlag,
599}
600
601/// Allocation, sharing, and placement properties for creating a CUDA memory pool.
602#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
603pub struct MemoryPoolProps {
604    /// Type of memory allocated from the pool.
605    pub alloc_type: MemoryAllocationType,
606    /// Handle types pool memory can be exported as; empty disables IPC export.
607    pub handle_types: AllocationHandleTypes,
608    /// Backing location, or preferred location for managed allocations.
609    pub location: MemoryLocation,
610    /// Maximum pool size in bytes; zero uses the system-dependent limit.
611    pub max_size: usize,
612    /// Additional usage requirements for allocations from the pool.
613    pub usage: MemoryPoolUsage,
614    /// Enables `GPUDirect` RDMA access for allocations from this pool.
615    pub gpu_direct_rdma_capable: bool,
616}
617
618/// Raw ownership of a CUDA memory pool and its context.
619///
620/// Destroy `handle` while `context` is alive, or re-adopt the value with [`MemoryPool::from_raw`].
621#[derive(Debug)]
622pub struct RawMemoryPool {
623    /// Native pool handle.
624    pub handle: driver::CUmemoryPool,
625    /// Context the pool was created for.
626    pub context: Arc<Context>,
627}
628
629/// Shares ownership of a CUDA memory pool and retains its context.
630///
631/// Clones and pool-backed allocations keep an owned pool alive.
632/// Default pools are driver-owned and are not destroyed when the last wrapper is dropped.
633#[derive(Debug, Clone)]
634pub struct MemoryPool {
635    owner: Arc<MemoryPoolOwner>,
636}
637
638#[derive(Debug)]
639pub(crate) struct MemoryPoolOwner {
640    context: Arc<Context>,
641    handle: driver::CUmemoryPool,
642    owned: bool,
643}
644
645// SAFETY: CUDA driver calls on a `CUmemoryPool` are thread-safe, and each call binds the retained context on the calling thread first.
646unsafe impl Send for MemoryPoolOwner {}
647
648// SAFETY: the owner exposes only the immutable handle, and concurrent driver calls on one pool are thread-safe.
649unsafe impl Sync for MemoryPoolOwner {}
650
651impl From<MemoryAccessDescriptor> for driver::CUmemAccessDesc {
652    fn from(value: MemoryAccessDescriptor) -> Self {
653        Self {
654            location: value.location.into(),
655            flags: value.flags.into(),
656        }
657    }
658}
659
660impl From<MemoryPoolProps> for driver::CUmemPoolProps {
661    fn from(value: MemoryPoolProps) -> Self {
662        Self {
663            allocType: value.alloc_type.into(),
664            handleTypes: driver::CUmemAllocationHandleType(value.handle_types.bits()),
665            location: value.location.into(),
666            win32SecurityAttributes: ptr::null_mut(),
667            maxSize: value.max_size as _,
668            usage: value.usage.bits(),
669            gpuDirectRDMACapable: value.gpu_direct_rdma_capable.into(),
670            reserved: [0; 53],
671        }
672    }
673}
674
675impl Drop for MemoryPoolOwner {
676    fn drop(&mut self) {
677        if !self.owned {
678            return;
679        }
680
681        if let Err(error) = self.context.bind() {
682            report_cleanup_failure(
683                "bind the cuda context to destroy",
684                "cuda memory pool",
685                &error,
686            );
687            return;
688        }
689
690        // SAFETY: this owned pool was created by this wrapper, and the last `MemoryPool` clone and pool-backed allocation are gone.
691        if let Err(error) = unsafe { try_ffi!(driver::cuMemPoolDestroy(self.handle)) } {
692            report_cleanup_failure("destroy", "cuda memory pool", &error);
693        }
694    }
695}
696
697/// Integer types that memory pool attributes are read into; every bit pattern is valid.
698pub(crate) trait PoolAttributeValue: Copy + Default {}
699
700impl_enum_display!(MemoryAllocationType, {
701    MemoryAllocationType::Pinned => "CU_MEM_ALLOCATION_TYPE_PINNED",
702    MemoryAllocationType::Managed => "CU_MEM_ALLOCATION_TYPE_MANAGED",
703});
704
705impl_enum_display!(MemoryAccessFlag, {
706    MemoryAccessFlag::None => "CU_MEM_ACCESS_FLAGS_PROT_NONE",
707    MemoryAccessFlag::Read => "CU_MEM_ACCESS_FLAGS_PROT_READ",
708    MemoryAccessFlag::ReadWrite => "CU_MEM_ACCESS_FLAGS_PROT_READWRITE",
709});
710
711impl_enum_display!(MemoryPoolAttribute, {
712    MemoryPoolAttribute::ReuseFollowEventDependencies => "CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES",
713    MemoryPoolAttribute::ReuseAllowOpportunistic => "CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC",
714    MemoryPoolAttribute::ReuseAllowInternalDependencies => "CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES",
715    MemoryPoolAttribute::ReleaseThreshold => "CU_MEMPOOL_ATTR_RELEASE_THRESHOLD",
716    MemoryPoolAttribute::ReservedMemoryCurrent => "CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT",
717    MemoryPoolAttribute::ReservedMemoryHigh => "CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH",
718    MemoryPoolAttribute::UsedMemoryCurrent => "CU_MEMPOOL_ATTR_USED_MEM_CURRENT",
719    MemoryPoolAttribute::UsedMemoryHigh => "CU_MEMPOOL_ATTR_USED_MEM_HIGH",
720});