Coverage for cuda/core/_memory/_ipc.pyx: 87.65%
340 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 01:06 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-03 01:06 +0000
1# SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
5from __future__ import annotations
7cimport cpython
9from libc.stddef cimport size_t
10from libc.stdint cimport uintptr_t
11from libc.string cimport memcpy
12from cuda.bindings cimport cydriver
13from cuda.core._memory._buffer cimport Buffer, Buffer_check_open, Buffer_from_deviceptr_handle
14from cuda.core._memory._memory_pool cimport (
15 _MemPool,
16 MP_check_open,
17 MP_get_location, # no-cython-lint
18 MP_location_query_available, # no-cython-lint
19)
20from cuda.core._stream cimport Stream, Stream_accept
21from cuda.core._rt cimport (
22 DevicePtrHandle,
23 create_fd_handle,
24 create_mempool_handle_ipc,
25 deviceptr_import_ipc,
26 get_last_error,
27 as_cu,
28 as_py,
29)
31from cuda.core._utils.cuda_utils cimport HANDLE_RETURN
32from cuda.core._utils.cuda_utils import check_multiprocessing_start_method
34import multiprocessing
35import operator
36import os
37import platform
38import threading
39import uuid
40import weakref
41from typing import TYPE_CHECKING, Iterable
43if TYPE_CHECKING:
44 from cuda.core.typing import VirtualMemoryHandleType
46__all__ = []
49# Maps uuid.UUID.bytes to a weakref.KeyedRef of the registered resource. The key
50# is bytes so that the dict hashes and compares it in C, without running Python.
51cdef dict registry = {}
52# Guards every access to the registry, reads included. Without the GIL a read
53# needs it for two reasons. Cython reads a typed dict through a borrowed
54# reference, which a concurrent removal can free before the read takes its own
55# reference. And a registration inserts the entry and then sets the handle's
56# UUID, so a reader must not run between the two.
57#
58# No Python code may run while it is held: a collection can start in Python
59# code, and its callbacks and finalizers can register or drop resources on this
60# thread. That includes hashing or comparing a uuid.UUID, calling a
61# WeakValueDictionary method, raising, and dropping the last reference to a
62# resource. Anything that can run Python goes before the lock, and errors are
63# raised after it is released. One exception remains: if the insertion fails
64# (for example with MemoryError), building the traceback allocates objects,
65# which on Python 3.11 can start a collection under the lock.
66cdef object _registry_lock = threading.RLock()
69def _registry_remove(ref):
70 # Runs wherever the last reference to a registered resource is dropped. The
71 # registry lock is a leaf lock, so taking it here cannot deadlock.
72 key = ref.key 29d!db #d$d%da
73 with _registry_lock: 29d!db #d$d%da
74 # A newer entry may have replaced this one.
75 if registry.get(key) is ref: 2d 9d!db #d$d%da
76 del registry[key] 29d!db #d$d%da
79cdef bytes _registry_key(key):
80 if not isinstance(key, uuid.UUID): 2i j b f x y E pdqdrda
81 raise TypeError(f"the key of a memory resource must be a uuid.UUID, got {type(key).__name__}") 2d pdqdrd
82 return key.bytes 1ijbfxyEa
85cdef inline _MemPool _registry_lookup_locked(bytes key):
86 """Return the live resource, or None. The caller must hold _registry_lock."""
87 ref = registry.get(key) 1ijbfxyEa
88 return None if ref is None else ref() 1ijbfxyEa
91cdef inline _MemPool _registry_lookup(bytes key):
92 with _registry_lock: 1bfEa
93 return _registry_lookup_locked(key) 1bfEa
96cdef cydriver.CUmemAllocationHandleType IPC_HANDLE_TYPE = \
97 cydriver.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR \
98 if platform.system() == "Linux" else \
99 cydriver.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_NONE
101cdef is_supported():
102 return IPC_HANDLE_TYPE != cydriver.CUmemAllocationHandleType.CU_MEM_HANDLE_TYPE_NONE 21b2bl 3bm 4b5b6b7b8bp 9bq !bdb#b$bc %b'bb f (b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8c9c!c#c$c%c'c(c)c*c+cgbhb,c-cr s .c/c:c;c=c?ct u v w n o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
105cdef class IPCDataForBuffer:
106 """Data members related to sharing memory buffers via IPC."""
107 def __cinit__(self, IPCBufferDescriptor ipc_descriptor, bint is_mapped) -> None:
108 self._ipc_descriptor = ipc_descriptor 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G a g } ObPb~ e h abebbbt u v w n o B C D
109 self._is_mapped = is_mapped 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G a g } ObPb~ e h abebbbt u v w n o B C D
111 @property
112 def ipc_descriptor(self) -> IPCBufferDescriptor:
113 return self._ipc_descriptor 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G t u v w n o B C D
115 @property
116 def is_mapped(self) -> bool:
117 return self._is_mapped 2ObPbabbb
120cdef class IPCDataForMR:
121 """Data members related to sharing memory resources via IPC."""
122 def __cinit__(self, IPCAllocationHandle alloc_handle, bint is_mapped) -> None:
123 self._alloc_handle = alloc_handle 21b2bl 3bm 4b5b6b7b8bp 9bq !bdb#b$bc %b'bb f (b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8c9c!c#c$c%c'c(c)c*c+cgbhb,c-cr s .c/c:c;c=c?ca t u v w n o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
124 self._is_mapped = is_mapped 21b2bl 3bm 4b5b6b7b8bp 9bq !bdb#b$bc %b'bb f (b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8c9c!c#c$c%c'c(c)c*c+cgbhb,c-cr s .c/c:c;c=c?ca t u v w n o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
126 @property
127 def alloc_handle(self) -> IPCAllocationHandle:
128 return self._alloc_handle
130 @property
131 def is_mapped(self) -> bool:
132 return self._is_mapped
134 @property
135 def uuid(self) -> uuid.UUID | None:
136 return getattr(self._alloc_handle, 'uuid', None) 1lmijcbfxyFGno
139cdef class IPCBufferDescriptor:
140 """Serializable object describing a buffer that can be shared between processes.
142 Note
143 ----
144 The payload and ``size`` fields are controlled by the exporting peer.
145 Receivers must treat them as untrusted and import only through
146 :meth:`Buffer.from_ipc_descriptor`.
147 """
149 def __init__(self, *arg, **kwargs) -> None:
150 raise RuntimeError("IPCBufferDescriptor objects cannot be instantiated directly. Please use MemoryResource APIs.") 2(dk
152 @staticmethod
153 def _init(reserved: bytes, size: int) -> IPCBufferDescriptor:
154 cdef IPCBufferDescriptor self = IPCBufferDescriptor.__new__(IPCBufferDescriptor) 2l m H I J K p q c YbZbodL M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G a z t u v w n o ldB md7dC 8dD
155 self._payload = reserved 2l m H I J K p q c YbZbodL M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G a z t u v w n o ldB md7dC 8dD
156 self._size = size 2l m H I J K p q c YbZbodL M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G a z t u v w n o ldB md7dC 8dD
157 return self 2l m H I J K p q c YbZbodL M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G a z t u v w n o ldB md7dC 8dD
159 def __reduce__(self) -> tuple[object, ...]:
160 return IPCBufferDescriptor._init, (self._payload, self._size) 2l m H I J K p q L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G t u v w n o 7d8d
162 @property
163 def size(self) -> int:
164 return self._size 2fbc a k g } ObPbcbe Wbh B
166 cdef const void* payload_ptr(self) noexcept:
167 """Return the payload as a const void* for C API calls."""
168 return <const void*><const char*>(self._payload) 1ca
171cdef inline int IPCAllocationHandle_check_open(IPCAllocationHandle self) except -1:
172 if self._h_fd.get() == NULL: 2sdtdl m H I jbJ K fbp q kbdbi j b L M lbN O mbP Q nbR S obT U V W udvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdX Y Z 0 1 2 3 4 OdPd5 6 7 8 Qd9 ! # $ RdSdTdUdVdWdXdYdZd0d% 1d' 2d( 3d) 4d* 5d+ 6dpbqbrbsbtbub, - vb. / wb: ; xb= ? yb@ [ zbgbhb] ^ r s AbBb_ ` Cb{ | DbF G Eba FbGbHbIbJbcbe t u KbLbv w MbNbn o ib
173 raise RuntimeError("IPCAllocationHandle has been closed") 1ije
174 return 0 2sdtdl m H I jbJ K fbp q kbdbb L M lbN O mbP Q nbR S obT U V W udvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdX Y Z 0 1 2 3 4 OdPd5 6 7 8 Qd9 ! # $ RdSdTdUdVdWdXdYdZd0d% 1d' 2d( 3d) 4d* 5d+ 6dpbqbrbsbtbub, - vb. / wb: ; xb= ? yb@ [ zbgbhb] ^ r s AbBb_ ` Cb{ | DbF G Eba FbGbHbIbJbcbe t u KbLbv w MbNbn o ib
177cdef class IPCAllocationHandle:
178 """Shareable OS handle to an IPC-enabled memory pool or to a physical allocation
179 of a :class:`VirtualMemoryResource` buffer."""
181 def __init__(self, *arg, **kwargs) -> None:
182 raise RuntimeError("IPCAllocationHandle objects cannot be instantiated directly. Please use MemoryResource APIs.") 2(d
184 @classmethod
185 def _init(cls, handle: int, uuid: uuid.UUID | None) -> IPCAllocationHandle: # no-cython-lint
186 cdef IPCAllocationHandle self = IPCAllocationHandle.__new__(cls) 21b2bl 3bm 4b5b6bjb7b8bfbp 9bq !bkbdbi #bj $bc %b'b'dndb f (b)b*b+blb,b-bmb.b/bnb:b;bob=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8cpbqbrbsbtbub9c!cvb#c$cwb%c'cxb(c)cyb*c+czbgbhb,c-cr s AbBb.c/cCb:c;cDb=c?cEba Fbg } 0bGbHb~ IbJbcbe Wbh abebXbz bbt u KbLbv w MbNbn o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
187 if handle < 0: 21b2bl 3bm 4b5b6bjb7b8bfbp 9bq !bkbdbi #bj $bc %b'b'dndb f (b)b*b+blb,b-bmb.b/bnb:b;bob=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8cpbqbrbsbtbub9c!cvb#c$cwb%c'cxb(c)cyb*c+czbgbhb,c-cr s AbBb.c/cCb:c;cDb=c?cEba Fbg } 0bGbHb~ IbJbcbe Wbh abebXbz bbt u KbLbv w MbNbn o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
188 raise ValueError(f"Invalid allocation handle (fd) {handle}: must be non-negative") 2'd
189 self._h_fd = create_fd_handle(handle) 21b2bl 3bm 4b5b6bjb7b8bfbp 9bq !bkbdbi #bj $bc %b'bndb f (b)b*b+blb,b-bmb.b/bnb:b;bob=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8cpbqbrbsbtbub9c!cvb#c$cwb%c'cxb(c)cyb*c+czbgbhb,c-cr s AbBb.c/cCb:c;cDb=c?cEba Fbg } 0bGbHb~ IbJbcbe Wbh abebXbz bbt u KbLbv w MbNbn o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
190 self._uuid = uuid 21b2bl 3bm 4b5b6bjb7b8bfbp 9bq !bkbdbi #bj $bc %b'bndb f (b)b*b+blb,b-bmb.b/bnb:b;bob=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8cpbqbrbsbtbub9c!cvb#c$cwb%c'cxb(c)cyb*c+czbgbhb,c-cr s AbBb.c/cCb:c;cDb=c?cEba Fbg } 0bGbHb~ IbJbcbe Wbh abebXbz bbt u KbLbv w MbNbn o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
191 return self 21b2bl 3bm 4b5b6bjb7b8bfbp 9bq !bkbdbi #bj $bc %b'bndb f (b)b*b+blb,b-bmb.b/bnb:b;bob=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8cpbqbrbsbtbub9c!cvb#c$cwb%c'cxb(c)cyb*c+czbgbhb,c-cr s AbBb.c/cCb:c;cDb=c?cEba Fbg } 0bGbHb~ IbJbcbe Wbh abebXbz bbt u KbLbv w MbNbn o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
193 cpdef close(self):
194 """Close the handle."""
195 self._h_fd.reset() 2dbi j ndg e
197 @property
198 def is_closed(self) -> bool:
199 """Whether this allocation handle has been closed."""
200 return self._h_fd.get() == NULL 2nd
202 def __int__(self) -> int:
203 if self._h_fd.get() == NULL: 2i j c ndb a g } 0b~ cbe Wbh abebXbbb
204 raise ValueError( 2ndg
205 f"Cannot convert IPCAllocationHandle to int: the handle (id={id(self)}) is closed." 2ndg
206 )
207 return as_py(self._h_fd) 2i j c b a g } 0b~ cbe Wbh abebXbbb
209 @property
210 def handle(self) -> int:
211 return as_py(self._h_fd) 2sdtdl m H I jbJ K fbp q kbdbc L M lbN O mbP Q nbR S obT U V W udvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdX Y Z 0 1 2 3 4 OdPd5 6 7 8 Qd9 ! # $ RdSdTdUdVdWdXdYdZd0d% 1d' 2d( 3d) 4d* 5d+ 6dpbqbrbsbtbub, - vb. / wb: ; xb= ? yb@ [ zbgbhb] ^ r s AbBb_ ` Cb{ | DbF G EbFbGbHbIbJbcbt u KbLbv w MbNbn o ib
213 @property
214 def uuid(self) -> uuid.UUID:
215 return self._uuid 2sdtdl m H I jbJ K fbp q kbdbi j c b f x y L M lbN O mbP Q nbR S obT U V W udvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdX Y Z 0 1 2 3 4 OdPd5 6 7 8 Qd9 ! # $ RdSdTdUdVdWdXdYdZd0d% 1d' 2d( 3d) 4d* 5d+ 6dpbqbrbsbtbub, - vb. / wb: ; xb= ? yb@ [ zbgbhb] ^ r s AbBb_ ` Cb{ | DbF G Eba FbGbHbIbJbcbt u KbLbv w MbNbn o ib
218def _reduce_allocation_handle(IPCAllocationHandle alloc_handle not None: IPCAllocationHandle) -> tuple[object, ...]:
219 IPCAllocationHandle_check_open(alloc_handle) 2sdtdl m H I jbJ K fbp q kbdbL M lbN O mbP Q nbR S obT U V W udvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdX Y Z 0 1 2 3 4 OdPd5 6 7 8 Qd9 ! # $ RdSdTdUdVdWdXdYdZd0d% 1d' 2d( 3d) 4d* 5d+ 6dpbqbrbsbtbub, - vb. / wb: ; xb= ? yb@ [ zbgbhb] ^ r s AbBb_ ` Cb{ | DbF G EbFbGbHbIbJbcbt u KbLbv w MbNbn o ib
220 check_multiprocessing_start_method() 2sdtdl m H I jbJ K fbp q kbdbL M lbN O mbP Q nbR S obT U V W udvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdX Y Z 0 1 2 3 4 OdPd5 6 7 8 Qd9 ! # $ RdSdTdUdVdWdXdYdZd0d% 1d' 2d( 3d) 4d* 5d+ 6dpbqbrbsbtbub, - vb. / wb: ; xb= ? yb@ [ zbgbhb] ^ r s AbBb_ ` Cb{ | DbF G EbFbGbHbIbJbcbt u KbLbv w MbNbn o ib
221 df = multiprocessing.reduction.DupFd(alloc_handle.handle) 2sdtdl m H I jbJ K fbp q kbdbL M lbN O mbP Q nbR S obT U V W udvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdX Y Z 0 1 2 3 4 OdPd5 6 7 8 Qd9 ! # $ RdSdTdUdVdWdXdYdZd0d% 1d' 2d( 3d) 4d* 5d+ 6dpbqbrbsbtbub, - vb. / wb: ; xb= ? yb@ [ zbgbhb] ^ r s AbBb_ ` Cb{ | DbF G EbFbGbHbIbJbcbt u KbLbv w MbNbn o ib
222 return _reconstruct_allocation_handle, (type(alloc_handle), df, alloc_handle.uuid) 2sdtdl m H I jbJ K fbp q kbdbL M lbN O mbP Q nbR S obT U V W udvdwdxdydzdAdBdCdDdEdFdGdHdIdJdKdLdMdNdX Y Z 0 1 2 3 4 OdPd5 6 7 8 Qd9 ! # $ RdSdTdUdVdWdXdYdZd0d% 1d' 2d( 3d) 4d* 5d+ 6dpbqbrbsbtbub, - vb. / wb: ; xb= ? yb@ [ zbgbhb] ^ r s AbBb_ ` Cb{ | DbF G EbFbGbHbIbJbcbt u KbLbv w MbNbn o ib
225def _reconstruct_allocation_handle(cls: type, df: object, uuid: uuid.UUID | None) -> IPCAllocationHandle: # no-cython-lint
226 return cls._init(df.detach(), uuid) 2dba
229multiprocessing.reduction.register(IPCAllocationHandle, _reduce_allocation_handle)
232cdef class _VirtualMemoryDescriptor(IPCBufferDescriptor):
233 """Common allocation layout and driver-handle interface for VMM descriptors."""
235 @property
236 def handle_type(self) -> VirtualMemoryHandleType:
237 """The export handle type; the importing resource must use the same type."""
238 from cuda.core._memory._virtual_memory_resource import VirtualMemoryResourceOptions 1eh
240 handle_type = self.driver_handle_type() 1eh
241 for spec, value in VirtualMemoryResourceOptions._handle_types.items(): 1eh
242 if spec is not None and int(value) == handle_type: 1eh
243 return spec 1eh
244 raise ValueError(f"the descriptor carries an unknown handle type ({handle_type})")
246 @property
247 def sizes(self) -> tuple[int, ...]:
248 """Size of each physical allocation, in address order; the sum is at least ``size``."""
249 return self._chunk_sizes 2k ObPb0be Wbh
251 cdef int driver_handle_type(self) except -1:
252 raise NotImplementedError("a concrete VMM descriptor is required")
254 cdef void* handle_ptr(self, Py_ssize_t i, cydriver.CUmemFabricHandle* scratch) except? NULL:
255 raise NotImplementedError("a concrete VMM descriptor is required")
258cdef class VirtualMemoryFdBufferDescriptor(_VirtualMemoryDescriptor):
259 """Serializable object describing a :class:`VirtualMemoryBuffer` that can be shared between processes.
261 The descriptor holds one exported POSIX file descriptor per physical
262 allocation that backs the buffer, in address order (``handles``, each an
263 :class:`IPCAllocationHandle` that the descriptor owns and closes when it
264 is released), with each allocation's size (``sizes``) and the buffer's
265 size (``size``, which may be smaller than their sum). ``handle_type`` is
266 ``"posix_fd"``; the rules below describe file descriptors.
268 A descriptor pins the physical memory while it exists, in every process
269 that holds one, and nothing else does: the exporting buffer keeps no
270 descriptor, and an imported buffer does not keep the one it came from. A
271 descriptor parked in a ``multiprocessing`` ``Queue`` or sent to a ``Pool``
272 pins the memory in the sender until the receiver has unpickled it; a
273 buffer passed as a ``Process`` argument pins it until the ``Process``
274 object is released, because the child receives the file descriptors when
275 it is spawned.
277 Two transports exist. ``multiprocessing`` (a ``Queue``, a ``Pipe``,
278 ``Process`` arguments, or a ``Pool``) pickles the descriptor, or a buffer,
279 and duplicates the file descriptors into the receiving process; plain
280 ``pickle`` cannot carry them and raises. A process with its own file
281 descriptor passing sends ``fds``, ``sizes``, and ``size`` itself, and the
282 receiver rebuilds the descriptor with :meth:`from_fds`.
284 Note
285 ----
286 The sizes are controlled by the exporting peer. Receivers must treat them
287 as untrusted and import only through :meth:`Buffer.from_ipc_descriptor`,
288 which checks what it can and fails instead of mapping a size the driver
289 rejects.
290 """
292 @staticmethod
293 def _from_exports(
294 chunk_sizes: tuple[int, ...], handles: tuple, size: int
295 ) -> VirtualMemoryFdBufferDescriptor:
296 cdef VirtualMemoryFdBufferDescriptor self = VirtualMemoryFdBufferDescriptor.__new__( 2jbfbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbA Fbg } ObPb0bGbHb~ IbJbcbe Wbh abebXbz bbKbLbMbNb
297 VirtualMemoryFdBufferDescriptor)
298 self._payload = b"" 2jbfbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbA Fbg } ObPb0bGbHb~ IbJbcbe Wbh abebXbz bbKbLbMbNb
299 self._size = size 2jbfbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbA Fbg } ObPb0bGbHb~ IbJbcbe Wbh abebXbz bbKbLbMbNb
300 self._chunk_sizes = tuple(chunk_sizes) 2jbfbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbA Fbg } ObPb0bGbHb~ IbJbcbe Wbh abebXbz bbKbLbMbNb
301 self._handles = tuple(handles) 2jbfbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbA Fbg } ObPb0bGbHb~ IbJbcbe Wbh abebXbz bbKbLbMbNb
302 return self 2jbfbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbA Fbg } ObPb0bGbHb~ IbJbcbe Wbh abebXbz bbKbLbMbNb
304 @classmethod
305 def from_fds(
306 cls,
307 fds: Iterable[int | IPCAllocationHandle],
308 sizes: Iterable[int],
309 *,
310 size: int | None = None,
311 ) -> VirtualMemoryFdBufferDescriptor:
312 """Build a descriptor from POSIX file descriptors received outside ``multiprocessing``.
314 The exporter sends ``fds``, ``sizes``, and ``size`` of its descriptor
315 through a transport of its own (a Unix socket with ``SCM_RIGHTS``, for
316 example); the receiver rebuilds the descriptor here and imports it
317 with :meth:`Buffer.from_ipc_descriptor`. The result's ``handle_type``
318 is ``"posix_fd"``, the only handle type a file descriptor can carry.
320 Parameters
321 ----------
322 fds : Iterable[int | IPCAllocationHandle]
323 One handle per physical allocation, in address order, as the
324 exporter's ``fds`` listed them. An ``int`` is duplicated: the
325 caller keeps ownership of the original and closes it. An
326 :class:`IPCAllocationHandle` is shared and closes with its last
327 holder.
328 sizes : Iterable[int]
329 The exporter's ``sizes``, one per handle.
330 size : int, optional
331 The exporter's ``size``, at most the sum of ``sizes``; the sum by
332 default.
334 Raises
335 ------
336 ValueError
337 If the counts differ, a size is not positive, or ``size`` exceeds
338 the sum of ``sizes``.
339 RuntimeError
340 If an :class:`IPCAllocationHandle` is closed.
341 OSError
342 If an ``int`` is not an open file descriptor.
343 """
344 cdef tuple sizes_t = tuple(operator.index(n) for n in sizes) 1eh
345 cdef list given = list(fds) 1eh
346 if len(given) != len(sizes_t): 1eh
347 raise ValueError(f"{len(given)} handles for {len(sizes_t)} sizes; one size per handle is required") 1e
348 for n in sizes_t: 1eh
349 if n <= 0: 1eh
350 raise ValueError(f"allocation sizes must be positive, got {n}") 1e
351 total = sum(sizes_t) 1eh
352 size = total if size is None else operator.index(size) 1eh
353 if size < 0 or size > total: 1eh
354 raise ValueError(f"size {size} is outside 0..{total}, the sum of the allocation sizes") 1e
355 cdef list handles = [] 1eh
356 cdef int dup
357 for item in given: 1eh
358 if isinstance(item, IPCAllocationHandle): 1eh
359 IPCAllocationHandle_check_open(<IPCAllocationHandle>item) 1e
360 handles.append(item) 1e
361 continue 1e
362 dup = os.dup(operator.index(item)) 1eh
363 try: 1h
364 handle = IPCAllocationHandle._init(dup, None) 1h
365 except: # noqa: E722 rollback-then-raise: the duplicate is not owned yet
366 os.close(dup)
367 raise
368 # The handle owns the duplicate now; if append fails, the handle closes it once.
369 handles.append(handle) 1h
370 return VirtualMemoryFdBufferDescriptor._from_exports(sizes_t, tuple(handles), size) 1eh
372 cdef int driver_handle_type(self) except -1:
373 return <int>cydriver.CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR 2A g } ObPb~ e h abebbb
375 cdef void* handle_ptr(self, Py_ssize_t i, cydriver.CUmemFabricHandle* scratch) except? NULL:
376 # fd zero is valid, so NULL is a valid result unless an exception is set.
377 cdef int fd = int(self._handles[i]) 2g } ~ e h abebbb
378 return <void*><uintptr_t>fd 2g } ~ e h abebbb
380 @property
381 def handles(self) -> tuple[IPCAllocationHandle, ...]:
382 """The exported handles, one :class:`IPCAllocationHandle` per allocation, in address order.
384 The descriptor owns them and closes them when it is released.
385 """
386 return self._handles 2g } ObPb~ e h abebbb
388 @property
389 def fds(self) -> tuple[int, ...]:
390 """The exported file descriptors as integers, for a transport of your own.
392 They belong to this descriptor: send or duplicate them while it is
393 alive, because each one is closed when the descriptor is released.
394 Keep the descriptor in a variable while you use them; the numbers
395 from ``buf.ipc_descriptor.fds`` alone may already be closed.
396 """
397 return tuple(int(handle) for handle in self._handles) 2ObPb0b~ e Wbh Xb
399 def __reduce__(self) -> tuple[object, ...]:
400 # multiprocessing duplicates the IPCAllocationHandle fds into the receiver; plain pickle raises.
401 return VirtualMemoryFdBufferDescriptor._from_exports, ( 2jbfbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbObPbGbHbIbJbcbXbKbLbMbNb
402 self._chunk_sizes, self._handles, self._size) 2jbfbkblbmbnbobpbqbrbsbtbubvbwbxbybzbAbBbCbDbEbFbObPbGbHbIbJbcbXbKbLbMbNb
405cdef class VirtualMemoryFabricBufferDescriptor(_VirtualMemoryDescriptor):
406 """Plain-data descriptor of a :class:`VirtualMemoryBuffer` exported with fabric handles.
408 Each physical allocation contributes one opaque 64-byte handle, in address
409 order. Plain ``pickle``, ``multiprocessing``, or a transport of your own
410 can carry these bytes. Use :meth:`from_handles` to rebuild a descriptor
411 received outside cuda.core, then :meth:`Buffer.from_ipc_descriptor` to
412 import it. ``handle_type`` is always ``"fabric"``.
414 Nothing is pinned: unlike a file descriptor, a fabric descriptor parked
415 in a queue does not retain the memory. The exporter must keep the buffer
416 alive until every importer has imported it. After import, the imported
417 allocation holds its own driver references and is independent of the
418 exporter. Importing a stale or forged handle fails with a driver error.
420 Sharing is supported on one node; multi-node sharing is untested. Fabric
421 handles require an NVLink fabric and an accessible IMEX channel. Treat
422 handles and sizes received from another process as untrusted and import
423 only through :meth:`Buffer.from_ipc_descriptor`.
424 """
426 @staticmethod
427 def _from_exports(
428 sizes: tuple[int, ...], handles: tuple[bytes, ...], size: int, owner_uuid: str | None
429 ) -> VirtualMemoryFabricBufferDescriptor:
430 return VirtualMemoryFabricBufferDescriptor.from_handles( 1kA
431 handles, sizes, size=size, owner_uuid=owner_uuid) 1kA
433 @classmethod
434 def from_handles(
435 cls, handles: Iterable[bytes], sizes: Iterable[int], *,
436 size: int | None = None, owner_uuid: str | None = None,
437 ) -> VirtualMemoryFabricBufferDescriptor:
438 """Build a descriptor from fabric handles received through a transport of your own.
440 Parameters
441 ----------
442 handles : Iterable[bytes]
443 One opaque 64-byte handle per physical allocation, in address order.
444 sizes : Iterable[int]
445 One positive allocation size per handle, in the same order.
446 size : int, optional
447 Buffer size, between zero and the sum of ``sizes``; the sum by default.
448 owner_uuid : str, optional
449 Exporting device's UUID, used to identify the owner in error messages.
451 Raises
452 ------
453 ValueError
454 If counts differ, a handle is not 64 bytes, an allocation size is
455 not a positive integer, or the buffer size is outside the allocation sizes.
456 """
457 cdef tuple handles_t = tuple(handles) 1kAg
458 try: 1kAg
459 sizes_t = tuple(operator.index(n) for n in sizes) 1kAg
460 size = None if size is None else operator.index(size) 1kAg
461 except TypeError as exc: 1k
462 raise ValueError("allocation sizes and size must be integers") from exc 1k
463 if len(handles_t) != len(sizes_t): 1kAg
464 raise ValueError(f"{len(handles_t)} handles for {len(sizes_t)} sizes; one size per handle is required") 1k
465 for handle in handles_t: 1kAg
466 if not isinstance(handle, bytes) or len(handle) != 64: 1kg
467 raise ValueError("each fabric handle must be 64 bytes") 1k
468 for n in sizes_t: 1kAg
469 if n <= 0: 1kg
470 raise ValueError(f"allocation sizes must be positive, got {n}") 1k
471 total = sum(sizes_t) 1kAg
472 size = total if size is None else size 1kAg
473 if size < 0 or size > total: 1kAg
474 raise ValueError(f"size {size} is outside 0..{total}, the sum of the allocation sizes") 1k
475 cdef VirtualMemoryFabricBufferDescriptor self = VirtualMemoryFabricBufferDescriptor.__new__(cls) 1kAg
476 self._payload = b"" 1kAg
477 self._chunk_sizes = sizes_t 1kAg
478 self._handles = handles_t 1kAg
479 self._size = size 1kAg
480 self._owner_uuid = owner_uuid 1kAg
481 return self 1kAg
483 @property
484 def handles(self) -> tuple[bytes, ...]:
485 """One opaque 64-byte fabric handle per allocation, in address order."""
486 return self._handles 1k
488 @property
489 def owner_uuid(self) -> str | None:
490 """The exporting device's UUID, if supplied by the exporter."""
491 return self._owner_uuid 1k
493 cdef int driver_handle_type(self) except -1:
494 return <int>cydriver.CU_MEM_HANDLE_TYPE_FABRIC 1Ag
496 cdef void* handle_ptr(self, Py_ssize_t i, cydriver.CUmemFabricHandle* scratch) except? NULL:
497 cdef bytes handle = self._handles[i]
498 memcpy(scratch.data, <const char*>handle, 64)
499 return <void*>scratch
501 def __reduce__(self) -> tuple[object, ...]:
502 return VirtualMemoryFabricBufferDescriptor._from_exports, ( 1k
503 self._chunk_sizes, self._handles, self._size, self._owner_uuid) 1k
505 def __eq__(self, other) -> bool:
506 if not isinstance(other, VirtualMemoryFabricBufferDescriptor): 1k
507 return NotImplemented 1k
508 cdef VirtualMemoryFabricBufferDescriptor rhs = other 1k
509 return (self._chunk_sizes, self._handles, self._size) == (rhs._chunk_sizes, rhs._handles, rhs._size) 1k
511 def __hash__(self) -> int:
512 return hash((self._chunk_sizes, self._handles, self._size)) 1k
515# Buffer IPC Implementation
516# -------------------------
517cdef IPCBufferDescriptor Buffer_get_ipc_descriptor(Buffer self):
518 Buffer_check_open(self) 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G z t u v w n o ldB mdC D
519 if not self.memory_resource.is_ipc_enabled: 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G z t u v w n o ldB mdC D
520 raise RuntimeError("Memory resource is not IPC-enabled") 2ldmd
521 if not isinstance(self.memory_resource, _MemPool): 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G z t u v w n o B C D
522 # VirtualMemoryBuffer overrides ipc_descriptor; a plain Buffer wrapped
523 # with Buffer.from_handle(mr=<VirtualMemoryResource>) lands here.
524 raise TypeError( 1z
525 f"a Buffer that {type(self.memory_resource).__name__} did not allocate cannot be shared") 1z
526 cdef cydriver.CUmemPoolPtrExportData data
527 with nogil: 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G t u v w n o B C D
528 HANDLE_RETURN( 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G t u v w n o B C D
529 cydriver.cuMemPoolExportPointer(&data, as_cu(self._h_ptr)) 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G t u v w n o B C D
530 )
531 cdef bytes data_b = cpython.PyBytes_FromStringAndSize( 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G t u v w n o B C D
532 <char*>(data.reserved), sizeof(data.reserved)
533 )
534 return IPCBufferDescriptor._init(data_b, self.size) 2l m H I J K p q c L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ! # $ % Qb' Rb( Sb) Tb* Ub+ Vb, - . / : ; = ? @ [ ] ^ r s _ ` { | F G t u v w n o B C D
536cdef Buffer Buffer_from_ipc_descriptor(
537 cls, object mr, IPCBufferDescriptor ipc_descriptor, stream
538):
539 """Import a buffer that was exported from another process."""
540 if isinstance(ipc_descriptor, _VirtualMemoryDescriptor): 2c YbZboda A g } ObPb~ e h abebz bbldmd
541 # Imported here rather than cimported: _virtual_memory_resource
542 # cimports this module.
543 from cuda.core._memory._virtual_memory_resource import VirtualMemoryResource 2A g } ObPb~ e h abebz bb
544 if not isinstance(mr, VirtualMemoryResource): 2A g } ObPb~ e h abebz bb
545 raise TypeError( 1z
546 "this descriptor was exported from a VirtualMemoryResource buffer and must be " 1z
547 f"imported with a VirtualMemoryResource, not {type(mr).__name__}") 1z
548 return mr._import_ipc_buffer(ipc_descriptor, stream) 2A g } ObPb~ e h abebz bb
549 if not isinstance(mr, _MemPool): 2c YbZboda z ldmd
550 raise TypeError( 2odz
551 "this descriptor was exported from a memory pool buffer and must be imported with a " 2odz
552 f"DeviceMemoryResource or PinnedMemoryResource, not {type(mr).__name__}") 2odz
553 cdef _MemPool pool = <_MemPool>mr 2c YbZba ldmd
554 MP_check_open(pool) 2c YbZba ldmd
555 if not mr.is_ipc_enabled: 2c YbZba ldmd
556 raise RuntimeError("Memory resource is not IPC-enabled") 2ldmd
557 cdef size_t payload_size = len(ipc_descriptor._payload) 2c YbZba
558 cdef size_t expected_size = sizeof(cydriver.CUmemPoolPtrExportData) 2c YbZba
559 if payload_size < expected_size: 2c YbZba
560 raise ValueError( 2YbZb
561 f"IPC buffer descriptor payload is {payload_size} bytes; " 2YbZb
562 f"expected at least {expected_size}" 2YbZb
563 )
564 cdef Stream s = Stream_accept(stream) 1ca
565 cdef DevicePtrHandle h_ptr = deviceptr_import_ipc( 1ca
566 pool._h_pool,
567 ipc_descriptor.payload_ptr(),
568 s._h_stream
569 )
570 if not h_ptr: 1ca
571 HANDLE_RETURN(get_last_error())
572 cdef size_t mapped_size = 0 1ca
573 cdef size_t claimed_size = ipc_descriptor.size 1ca
574 with nogil: 1ca
575 HANDLE_RETURN(cydriver.cuPointerGetAttribute( 1ca
576 &mapped_size,
577 cydriver.CU_POINTER_ATTRIBUTE_RANGE_SIZE,
578 as_cu(h_ptr)))
579 if claimed_size > mapped_size: 1ca
580 h_ptr.reset()
581 raise ValueError(
582 f"IPC buffer descriptor size ({claimed_size}) exceeds "
583 f"mapped allocation extent ({mapped_size} bytes)"
584 )
585 return Buffer_from_deviceptr_handle(h_ptr, claimed_size, pool, ipc_descriptor) 1ca
588# _MemPool IPC Implementation
589# ---------------------------
591cdef inline _check_registered_type(mr, cls, uuid):
592 if not isinstance(mr, cls): 1b
593 raise TypeError(
594 f"Registry contains a {type(mr).__name__} for uuid "
595 f"{uuid}, but {cls.__name__} was requested")
598cdef int MP_check_import_location(
599 _MemPool self, bint host, cydriver.CUmemLocation* loc) except? -1:
600 IF CUDA_CORE_BUILD_MAJOR >= 13:
601 cdef cydriver.CUmemLocationType loc_type
602 cdef bint on_host
603 cdef bint on_device
604 cdef int loc_type_value
605 if not MP_location_query_available(): 1cba
606 return 0
607 MP_get_location(self, loc) 1cba
608 loc_type = loc.type 1cba
609 loc_type_value = <int>loc_type 1cba
610 on_host = (
611 loc_type == cydriver.CUmemLocationType.CU_MEM_LOCATION_TYPE_HOST
612 or loc_type == cydriver.CUmemLocationType.CU_MEM_LOCATION_TYPE_HOST_NUMA 1cba
613 )
614 # An imported device pool is INVISIBLE when its device is not visible to
615 # this process (for example under a restricted CUDA_VISIBLE_DEVICES). A
616 # DEVICE_LOCALITY_DOMAIN pool lives in part of a device's memory.
617 on_device = (
618 loc_type == cydriver.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE 1cba
619 or loc_type == cydriver.CUmemLocationType.CU_MEM_LOCATION_TYPE_INVISIBLE 1cba
620 or loc_type == cydriver.CUmemLocationType.CU_MEM_LOCATION_TYPE_DEVICE_LOCALITY_DOMAIN 1cba
621 )
622 if (host and on_host) or (not host and on_device): 1cba
623 return 1 1cba
624 if on_host:
625 problem = "a host memory pool; import it with PinnedMemoryResource.from_allocation_handle"
626 elif on_device:
627 problem = "a device memory pool; import it with DeviceMemoryResource.from_allocation_handle"
628 else:
629 problem = f"a memory pool at location type {loc_type_value}, which neither class can import"
630 raise TypeError(
631 f"The allocation handle refers to {problem}, but {type(self).__name__} was requested")
632 ELSE:
633 return 0
636cdef _MemPool MP_from_allocation_handle(
637 cls, alloc_handle, MP_import_init_t init=NULL, object init_arg=None):
638 if isinstance(alloc_handle, IPCAllocationHandle): 1ijcba
639 IPCAllocationHandle_check_open(<IPCAllocationHandle>alloc_handle) 1ijba
641 # Quick exit for registry hits.
642 uuid = getattr(alloc_handle, 'uuid', None) # no-cython-lint 1cba
643 cdef _MemPool mr = None 1cba
644 if uuid is not None: 1cba
645 mr = _registry_lookup(_registry_key(uuid)) 1ba
646 if mr is not None: 1cba
647 _check_registered_type(mr, cls, uuid) 1b
648 MP_check_open(<_MemPool>mr) 1b
649 return mr 1b
651 # Ensure we have an allocation handle. Duplicate the file descriptor, if
652 # necessary.
653 if isinstance(alloc_handle, int): 1cba
654 fd = os.dup(alloc_handle) 1c
655 try: 1c
656 alloc_handle = IPCAllocationHandle._init(fd, None) 1c
657 except:
658 os.close(fd)
659 raise
661 # Construct a new mempool.
662 cdef _MemPool self = <_MemPool>(cls.__new__(cls)) 1cba
663 self._mempool_owned = True 1cba
664 cdef int ipc_fd = int(alloc_handle) 1cba
665 self._h_pool = create_mempool_handle_ipc(ipc_fd, IPC_HANDLE_TYPE) 1cba
666 if not self._h_pool: 1cba
667 HANDLE_RETURN(get_last_error())
668 raise RuntimeError(
669 f"Failed to import {cls.__name__} from an allocation handle: "
670 "cuda-core returned an empty memory pool handle without recording a CUDA error. "
671 "This is an internal cuda-core error; please report it with your CUDA driver, "
672 "CUDA Toolkit, and cuda-python versions."
673 )
674 self._ipc_data = IPCDataForMR(alloc_handle, True) 1cba
676 # Initialize before registering: a registry hit in another thread must not
677 # return a pool whose initialization is in progress or has failed. A
678 # resource returned from the registry is never initialized again.
679 if init != NULL: 1cba
680 init(self, init_arg) 1cba
682 # Register it.
683 if uuid is not None: 1cba
684 registered = self.register(uuid) 1ba
685 if registered is not self: 1ba
686 # A concurrent import of the same UUID registered first. Both
687 # imports share one pool handle, so dropping this one only drops a
688 # reference.
689 _check_registered_type(registered, cls, uuid)
690 return registered
692 return self 1cba
695cdef _MemPool MP_from_registry(uuid):
696 cdef _MemPool mr = _registry_lookup(_registry_key(uuid)) 2b f E pdqdrda
697 if mr is None: 1bfEa
698 raise RuntimeError(f"Memory resource {uuid} was not found") 1fE
699 MP_check_open(mr) 1bfa
700 return mr 1bfa
703cdef _MemPool MP_register(_MemPool self, uuid):
704 MP_check_open(self) 2i j b f x y E pdqdrda
705 cdef IPCAllocationHandle handle = None 2i j b f x y E pdqdrda
706 cdef _MemPool existing
707 cdef object current = None 2i j b f x y E pdqdrda
708 cdef bint changed
709 cdef bint conflict = False 2i j b f x y E pdqdrda
710 # Everything that can run Python code happens before the lock.
711 cdef bytes key = _registry_key(uuid) 2i j b f x y E pdqdrda
712 ref = weakref.KeyedRef(self, _registry_remove, key) 1ijbfxyEa
713 if self.is_ipc_enabled: 1ijbfxyEa
714 handle = self._ipc_data._alloc_handle 1ijbfxya
715 while True: 1ijbfxyEa
716 changed = False 1ijbfxyEa
717 if handle is not None: 1ijbfxyEa
718 current = handle._uuid 1ijbfxya
719 conflict = current is not None and current != uuid 1ijbfxya
720 # The lookup and the insertion are one step: without the GIL, two threads
721 # could otherwise both miss and register different resources for one
722 # UUID, and a nested registration cannot run between them because no
723 # Python code runs here. See the comment at _registry_lock.
724 with _registry_lock: 1ijbfxyEa
725 # Reuse the held lock. On CPython 3.11, binding the context manager
726 # methods for another lock scope can allocate GC-tracked objects
727 # and start a collection here.
728 existing = _registry_lookup_locked(key) 1ijbfxyEa
729 if existing is None and handle is not None: 1ijbfxyEa
730 # Imports can share one handle. If another registration gave it
731 # its UUID since it was read, validate again.
732 changed = handle._uuid is not current 1ijbfxya
733 if not changed and not conflict: 1ijbfxya
734 registry[key] = ref 1ijbfxya
735 # Write the UUID once. The handle's UUID is read without
736 # this lock (above and in IPCAllocationHandle.uuid), so
737 # replacing an equal UUID would release an object that
738 # another thread may be taking a reference to. Releasing it
739 # here could also run a uuid.UUID subclass's __del__ under
740 # the lock.
741 if current is None: 1ijbfxya
742 handle._uuid = uuid
743 return self 1ijbfxya
744 if existing is not None: 1bxyE
745 MP_check_open(existing) 1b
746 return existing 1b
747 if handle is None: 1xyE
748 raise RuntimeError("Memory resource is not IPC-enabled") 1E
749 if changed: 1xy
750 continue
751 raise ValueError( 1xy
752 f"Cannot register memory resource with UUID {uuid}: " 1xy
753 f"the resource already has UUID {current}" 1xy
754 )
757cdef IPCAllocationHandle MP_export_mempool(_MemPool self):
758 # Note: This is Linux only (int for file descriptor)
759 MP_check_open(self) 21b2bl 3bm 4b5b6b7b8bp 9bq !bdb#b$bc %b'bb f (b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8c9c!c#c$c%c'c(c)c*c+cgbhb,c-cr s .c/c:c;c=c?ct u v w n o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
760 cdef int fd
761 with nogil: 21b2bl 3bm 4b5b6b7b8bp 9bq !bdb#b$bc %b'bb f (b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8c9c!c#c$c%c'c(c)c*c+cgbhb,c-cr s .c/c:c;c=c?ct u v w n o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
762 HANDLE_RETURN(cydriver.cuMemPoolExportToShareableHandle( 21b2bl 3bm 4b5b6b7b8bp 9bq !bdb#b$bc %b'bb f (b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8c9c!c#c$c%c'c(c)c*c+cgbhb,c-cr s .c/c:c;c=c?ct u v w n o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
763 &fd, as_cu(self._h_pool), IPC_HANDLE_TYPE, 0)
764 )
765 try: 21b2bl 3bm 4b5b6b7b8bp 9bq !bdb#b$bc %b'bb f (b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8c9c!c#c$c%c'c(c)c*c+cgbhb,c-cr s .c/c:c;c=c?ct u v w n o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
766 return IPCAllocationHandle._init(fd, uuid.uuid4()) 21b2bl 3bm 4b5b6b7b8bp 9bq !bdb#b$bc %b'bb f (b)b*b+b,b-b.b/b:b;b=b?b@b[b]b^b_b`b{b|b}b~bacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczcAcBcCcDcEcFcGcHcIcJcKcLcMcNcOcPcQcRcScTcUcVcWcXcYcZc0c1c2c3c4c5c6c7c8c9c!c#c$c%c'c(c)c*c+cgbhb,c-cr s .c/c:c;c=c?ct u v w n o @c[c]c^c_c`c{c|c}c~cadbdcdddedfdB gdhdidibjdkdC D
767 except:
768 os.close(fd)
769 raise