Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions cuda_core/cuda/core/_context.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ cdef class Context:
cpdef close(self)


cdef int Context_get_primary_handle(int device_id, ContextHandle* h_context) except -1
cdef Context Context_primary(int device_id)


cdef inline int Context_check_open(Context self) except -1:
if not self._h_context:
raise RuntimeError("Context has been closed")
Expand Down
21 changes: 21 additions & 0 deletions cuda_core/cuda/core/_context.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ from cuda.core._rt cimport (
create_context_handle_from_green_ctx,
get_context_green_ctx,
get_last_error,
get_primary_context,
as_intptr,
as_py,
)
Expand Down Expand Up @@ -150,6 +151,26 @@ cdef class Context:
return f"<Context handle={as_intptr(self._h_context):#x} device={self._device_id}>"


cdef int Context_get_primary_handle(int device_id, ContextHandle* h_context) except -1:
"""Store the primary context of ``device_id`` in ``h_context``.

cuda.core retains it on first use and never releases it. Raises if it
cannot be retained.
"""
h_context[0] = get_primary_context(device_id)
if not h_context[0]:
HANDLE_RETURN(get_last_error())
raise RuntimeError(f"Failed to retain the primary context for device {device_id}")
return 0


cdef Context Context_primary(int device_id):
"""Return a :class:`Context` for the primary context of ``device_id``."""
cdef ContextHandle h_context
Context_get_primary_handle(device_id, &h_context)
return Context._from_handle(Context, h_context, device_id)


@dataclass
cdef class ContextOptions:
"""Options for context creation.
Expand Down
59 changes: 57 additions & 2 deletions cuda_core/cuda/core/_cpp/rt/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,8 @@ Two rules follow:
1. Do not make a `DRIVER_CALL` while the caller holds a C++ lock, because the
fill acquires the GIL. Resolve the table before the lock
(`ensure_fn_table(FnTable::driver)`) and use the raw pointer inside it,
marked `// raw:` (see `deviceptr_import_ipc`).
marked `// raw:` (see `deviceptr_import_ipc`, and `pin_primary_context`
under the primary-context table's mutex).
2. If the Cython layer gates a driver function, gate it at the version
cuda-bindings requests it at (the number in the table), not at the version
the driver first shipped it.
Expand Down Expand Up @@ -317,7 +318,61 @@ that must update shared state before user code can run does so in
`cleanup_in_context`'s `after_cleanup` hook, which runs once the cleanup is done
and before anything that may run user code; the IPC pointer deleter releases its
registry entry there. The registries store `weak_ptr`s,
so erasing an entry under a registry lock never runs a deleter.
so erasing an entry under a registry lock never runs a deleter. Releasing a
handle can, though: `HandleRegistry::insert_or_get` therefore destroys a
displaced handle only after it has unlocked, and a caller drops a losing
candidate outside the lock (REGISTRY_DESIGN.md).

Resolving a context handle can call the driver and report a failure, so
`create_context_handle_ref()`, `create_current_context_handle_ref()`,
`get_current_context()` and everything that calls them, such as
`make_deallocation_stream()` for a default-stream token, must not run while a
C++ lock is held (see "Primary contexts"). `deviceptr_import_ipc`
resolves its deallocation stream before it takes the IPC pointer cache's mutex
for this reason.

### Primary contexts

`cuda.core` retains each device's primary context at most once per process and
never releases it, as the CUDA runtime does. The driver destroys a primary
context when its last retain is released, so code outside `cuda.core`
(`cuDevicePrimaryCtxReset`, `cudaDeviceReset`) is the only way a primary context
that `cuda.core` has handed out can go away. Before #1368 `cuda.core` already
behaved this way; #1368 released the retain when the last handle dropped, which
#3533 showed to be wrong.

- `get_primary_context()` pins one retaining `ContextBox` per device in a
process-wide table (`pin_primary_context()` in `context.cpp`). The table is
leaked on purpose and holds a strong reference, so the box's deleter never
runs and its retain is never given back. The table is read without a lock:
pinning publishes a new immutable snapshot under the table's mutex, and old
snapshots are leaked, so a reader never sees freed memory. There is no
per-thread cache, so a thread's exit has no effect on primary contexts. The
mutex and the snapshot pointer are constant-initialized globals, not
function-local statics, so no static-initialization guard is involved (see
"Static Initialization and Deadlock Hazards").
- `create_context_handle_ref()`, `create_current_context_handle_ref()` and
`get_current_context()` pin a primary context that another library made
current: when `ctx` is the calling thread's current context and its device's
active primary context, it is retained and pinned. All three go through
`resolve_context_handle()`; the last two are for callers that already know
what is current, so it is not queried again. Only the current context is
examined, because its device is the only one that can be queried without
switching contexts. An inactive primary context is never retained, because
that would create it. When the active primary context turns out to be
another one, the retain taken to find out is given back. That release cannot
destroy a context, because it was active without that retain.
- A context that is not current at the time of the lookup, such as another
context's stream or a graph node's update context, gets a plain handle that
does not keep it alive.
- The retain runs with the GIL released, under the table's mutex, through the
raw `p_` pointers after `ensure_fn_table()` (see "The GIL is the outermost
lock"). Giving back a probe retain can report a failure through Python, so it
runs after the mutex is released.
- Cython code gets a primary context through `Context_get_primary_handle()`
(a `ContextHandle`) or `Context_primary()` (a `Context`) in `_context.pyx`,
not by calling `get_primary_context()` directly. Both drain
`get_last_error()` and raise on failure, so every caller fails the same way.

### Static Initialization and Deadlock Hazards

Expand Down
24 changes: 23 additions & 1 deletion cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ together to map a raw driver handle all the way back to the original
Python object. Both use weak references so they
do not prevent cleanup. Entries are removed either explicitly (via
`destroy()` or a Box destructor) or implicitly when the weak reference
expires.
expires. The one exception is a primary context's Box, which a separate table
pins for the life of the process (see "Removing and replacing entries").

## Level 1: Driver Handle -> Resource Handle (C++)

Expand All @@ -33,6 +34,27 @@ Instances: `context_registry`, `stream_registry`, `event_registry`,
`kernel_registry`, and, per `GraphBox`, one registry for its direct child
graphs and one for its nodes.

### Removing and replacing entries

More than one Box can exist for one raw handle, for example a plain `_ref`
Box and an owning one. An entry therefore records the address of the
element its handle points to, and `unregister_handle(key, resource)` erases
the entry only if `resource` matches. A Box destructor thus never erases the
entry of another, still-live Box registered under the same key.

`insert_or_get(key, candidate, replace)` registers a new Box without blindly
overwriting a live entry; `replace(existing)` decides. Build the candidate
before the call and drop a losing candidate after it, never under the
registry's lock, because its deleter takes that lock. For the same reason,
`insert_or_get` releases a displaced live handle only after the unlock: another
thread may have dropped its own copy, leaving the last reference to that Box
inside the call. `context_registry` uses
this to keep one owning Box per live context (#3533): a Box that holds a
primary-context retain or the owning green-context handle replaces a plain
one, and nothing replaces an owning one. A primary context's retaining Box is
pinned for the life of the process (`pin_primary_context()` in `context.cpp`),
so all threads share it and its retain is never released.

### Imports that wait for an in-flight release

IPC imports use `ReleasingHandleRegistry`, a variant whose entry outlives its
Expand Down
22 changes: 17 additions & 5 deletions cuda_core/cuda/core/_cpp/rt/api.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,19 @@ namespace cuda_core::rt {
// Context handle functions
// ============================================================================

// Function to create a non-owning context handle (references existing context).
// Return a handle for an existing context: the registered handle if there is
// one. A primary context that is the calling thread's current context is
// retained and pinned for the life of the process (see get_primary_context).
// Any other context gets a handle that does not keep it alive. May call the
// driver and report a failure, which acquires the GIL: do not call it while
// holding a C++ lock.
ContextHandle create_context_handle_ref(CUcontext ctx);

// As create_context_handle_ref, for a caller that knows that ctx is the calling
// thread's current context and that its device is `device`, so that neither is
// queried again.
ContextHandle create_current_context_handle_ref(CUcontext ctx, CUdevice device);

// Create a context handle for the CUcontext view of the provided green context.
// The returned ContextHandle keeps the green context alive, but the CUcontext
// view is non-owning and is not destroyed independently.
Expand All @@ -35,12 +45,14 @@ GreenCtxHandle create_green_ctx_handle(
// Create a non-owning green context handle.
GreenCtxHandle create_green_ctx_handle_ref(CUgreenCtx ctx);

// Get handle to the primary context for a device (with thread-local caching)
// Returns empty handle on error (caller must check)
// Get handle to the primary context for a device.
// cuda.core retains each primary context at most once per process and never
// releases it. Returns empty handle on error (caller must check)
ContextHandle get_primary_context(int device_id);

// Get handle to the current CUDA context
// Returns empty handle if no context is current (caller must check)
// Get handle to the current CUDA context, as create_context_handle_ref does;
// the same rules apply. Returns empty handle if no context is current (caller
// must check)
ContextHandle get_current_context();

// Synchronize the provided context. Releases the GIL around the driver call.
Expand Down
Loading
Loading