Skip to content
Open
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
1 change: 1 addition & 0 deletions cuda_core/cuda/core/_cpp/rt/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,7 @@ exactly one of these; none is ever dropped.
| Cython, inside an `except` block whose rollback failed | `attach_rollback_failure(op, status, detail)` | Adds a note to the exception being handled. Reports instead if nothing is being handled. |
| C++, a deleter or deferred cleanup | A `pw_*` wrapper, or `report_cuda_error()` / `report_message()` | Emits `CUDAWarning`. Never raises. |
| Cython or Python, a `__dealloc__` or destructor-path callback | `warnings.warn(msg, CUDAWarning, stacklevel=2)` | Same. |
| C++, a deleter that can run during native thread exit (a `thread_local` destructor) | Call the driver with `DRIVER_CALL`, and on failure hand a preallocated `DeferredCleanupItem` that reports to the deferred-cleanup queue | Warning hooks must not run during thread teardown: on Windows the loader lock is held, and a hook that starts a thread deadlocks. The report is delivered from the main thread. The primary context's deleter does this when `primary_context_cache_closed` is set. |
| A CUDA user-object destructor callback | Nothing that needs the GIL. Hand the work to the deferred-cleanup queue with `Py_AddPendingCall` | CUDA forbids driver calls there, and acquiring the GIL there can deadlock with a GIL holder blocked in a driver call. GIL-free C API that only schedules work is fine. |

### `p_` versus `pw_`
Expand Down
20 changes: 20 additions & 0 deletions cuda_core/cuda/core/_cpp/rt/REGISTRY_DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,26 @@ 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. `get_primary_context()` therefore
shares one retaining Box per primary context across all threads.

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

IPC imports use `ReleasingHandleRegistry`, a variant whose entry outlives its
Expand Down
146 changes: 125 additions & 21 deletions cuda_core/cuda/core/_cpp/rt/context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,29 @@ context_get_device(const ContextHandle &h_context, CUdevice *device) noexcept
// ============================================================================

namespace {
// A release failure that could not be reported where it happened. The
// deferred-cleanup queue destroys it on Python's main thread, and its
// destructor reports the failure there.
struct DeferredCudaReport final : DeferredCleanupItem {
char operation[kOperationNameSize] = {};
CUresult status = CUDA_SUCCESS;

~DeferredCudaReport() noexcept override
{
if (status != CUDA_SUCCESS) {
report_cuda_error(operation, status);
}
}
};

struct ContextBox {
CUcontext resource;
GreenCtxHandle h_green_ctx;
bool retains_primary = false; // Owns one cuDevicePrimaryCtxRetain.
// Allocated with a retaining box, so that its deleter never allocates. The
// deleter hands it to the deferred-cleanup queue when it must not report
// a failed release itself. Mutable: the deleter sees a const box.
mutable std::unique_ptr<DeferredCudaReport> deferred_release;
};

struct GreenCtxBox {
Expand All @@ -135,6 +155,27 @@ get_box(const ContextHandle &h) noexcept
// See REGISTRY_DESIGN.md (Level 1: Driver Handle -> Resource Handle)
HandleRegistry<CUcontext, ContextHandle> context_registry;

// A box keeps its context alive if it holds a primary-context retain or the
// owning green-context handle. Reads only immutable box fields, so it is safe
// under the registry's mutex.
bool
owns_context(const ContextHandle &h) noexcept
{
const ContextBox *b = get_box(h);
return b->retains_primary || b->h_green_ctx;
}

// Registry replacement policy for contexts: an owning candidate replaces a
// non-owning entry, and nothing replaces an owning entry. This keeps one
// owning box per live context, and a lookup never trades it for a plain one.
auto
replace_if_upgrade(const ContextHandle &candidate) noexcept
{
return [owning = owns_context(candidate)](const ContextHandle &existing) noexcept {
return owning && !owns_context(existing);
};
}

// Create a context handle reference, with optional green context as source.
ContextHandle
create_context_handle_ref(CUcontext ctx, GreenCtxHandle h_green_ctx)
Expand All @@ -143,20 +184,26 @@ create_context_handle_ref(CUcontext ctx, GreenCtxHandle h_green_ctx)
return {};
}
if (auto h = context_registry.lookup(ctx)) {
return h;
// An owning entry for ctx is either this green context's own box or a
// live primary context. A green context cannot share a live primary
// context's CUcontext, so returning it never drops a needed green owner.
if (!h_green_ctx || owns_context(h)) {
return h;
}
}
// clang-format off
auto box = std::shared_ptr<const ContextBox>(
new ContextBox{ctx, std::move(h_green_ctx)},
[](const ContextBox *b) {
context_registry.unregister_handle(b->resource);
context_registry.unregister_handle(b->resource, &b->resource);
delete b;
}
);
// clang-format on
ContextHandle h(box, &box->resource);
context_registry.register_handle(ctx, h);
return h;
ContextHandle candidate(box, &box->resource);
// A losing candidate is dropped by the caller, outside the registry's lock;
// its deleter's ownership-checked erase is then a no-op.
return context_registry.insert_or_get(ctx, candidate, replace_if_upgrade(candidate));
}
} // namespace

Expand Down Expand Up @@ -227,15 +274,44 @@ create_green_ctx_handle_ref(CUgreenCtx green_ctx)
return GreenCtxHandle(box, &box->resource);
}

// Thread-local cache of primary contexts indexed by device ID
static thread_local std::vector<ContextHandle> primary_context_cache;
namespace {
// Set when the calling thread's primary-context cache is torn down. A plain
// bool needs no destructor, so it stays readable for the whole thread exit.
thread_local bool primary_context_cache_closed = false;

// Thread-local cache of primary contexts indexed by device ID. A fast path in
// front of the registry: every thread caches the same process-wide box.
struct PrimaryContextCache {
std::vector<ContextHandle> entries;

PrimaryContextCache() = default;
PrimaryContextCache(const PrimaryContextCache &) = delete;
PrimaryContextCache &operator=(const PrimaryContextCache &) = delete;

// Releasing the last entry can run a CUDAWarning hook on this thread, and
// the hook may call get_primary_context(). Close the cache first and drop
// the entries from a local, so such a call bypasses the cache instead of
// reading one that is being destroyed.
~PrimaryContextCache()
{
primary_context_cache_closed = true;
std::vector<ContextHandle> doomed;
doomed.swap(entries);
}
};

thread_local PrimaryContextCache primary_context_cache;
} // namespace

ContextHandle
get_primary_context(int device_id)
{
const bool use_cache = !primary_context_cache_closed;
auto idx = static_cast<size_t>(device_id);

// Check thread-local cache
if (static_cast<size_t>(device_id) < primary_context_cache.size()) {
if (auto cached = primary_context_cache[device_id]) {
if (use_cache && idx < primary_context_cache.entries.size()) {
if (auto cached = primary_context_cache.entries[idx]) {
return cached;
}
}
Expand All @@ -249,28 +325,56 @@ get_primary_context(int device_id)

// clang-format off
auto box = std::shared_ptr<const ContextBox>(
new ContextBox{ctx, {}},
new ContextBox{ctx, {}, true, std::make_unique<DeferredCudaReport>()},
[device_id](const ContextBox *b) {
context_registry.unregister_handle(b->resource);
context_registry.unregister_handle(b->resource, &b->resource);
// During interpreter shutdown, leave primary-context cleanup to
// process teardown. An unavailable table entry would need Python
// to report itself.
// process teardown. Reporting a failure needs Python too.
if (Py_IsInitialized() && !py_is_finalizing()) {
GILReleaseGuard gil;
DRIVER_CALL(cuDevicePrimaryCtxRelease, device_id);
if (!primary_context_cache_closed) {
pw_cuDevicePrimaryCtxRelease(device_id);
}
else {
// This thread's cache is being destroyed, so the thread is
// exiting. Native thread teardown must not run Python: a
// warning hook that starts a thread would wait for a
// thread that needs the loader lock this one holds on
// Windows. Report the failure from the main thread.
const CUresult status = DRIVER_CALL(cuDevicePrimaryCtxRelease, device_id);
if (status != CUDA_SUCCESS && status != CUDA_ERROR_DEINITIALIZED) {
DeferredCudaReport *report = b->deferred_release.release();
report->status = status;
format_operation(report->operation, sizeof(report->operation), "cuDevicePrimaryCtxRelease", device_id);
enqueue_cleanup(static_cast<DeferredCleanupItem *>(report));
}
}
}
delete b;
}
);
// clang-format on
auto h = ContextHandle(box, &box->resource);
context_registry.register_handle(ctx, h);

// Update cache
if (static_cast<size_t>(device_id) >= primary_context_cache.size()) {
primary_context_cache.resize(device_id + 1);
ContextHandle candidate(box, &box->resource);
// Keep one retaining box per primary context per process. If another
// thread's box is live, use it, and dropping our candidate releases the
// extra retain taken above; the live box still holds its own retain, so the
// driver's count never reaches zero. This runs with the GIL released and
// after insert_or_get has released the registry's lock, so the deleter may
// report through a pw_ wrapper.
ContextHandle h = context_registry.insert_or_get(ctx, candidate, replace_if_upgrade(candidate));

// Update the cache before dropping a losing candidate. Dropping it releases
// its extra retain, and a failure report can run a hook that calls
// get_primary_context() again; that call must find the cache entry instead
// of retaining and releasing once more.
if (use_cache) {
if (idx >= primary_context_cache.entries.size()) {
primary_context_cache.entries.resize(idx + 1);
}
primary_context_cache.entries[idx] = h;
}
primary_context_cache[device_id] = h;
candidate.reset();
box.reset();
return h;
}

Expand Down
4 changes: 2 additions & 2 deletions cuda_core/cuda/core/_cpp/rt/event.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ create_event_handle(
auto box = std::shared_ptr<const EventBox>(
new EventBox{event, timing_enabled, is_blocking_sync, ipc_enabled, device_id, h_ctx},
[](const EventBox *b) {
event_registry.unregister_handle(b->resource);
event_registry.unregister_handle(b->resource, &b->resource);
GILReleaseGuard gil;
pw_cuEventDestroy(b->resource);
delete b;
Expand Down Expand Up @@ -154,7 +154,7 @@ create_event_handle_ipc(const CUipcEventHandle &ipc_handle, bool is_blocking_syn
auto box = std::shared_ptr<const EventBox>(
new EventBox{event, false, is_blocking_sync, true, -1, {}},
[](const EventBox *b) {
event_registry.unregister_handle(b->resource);
event_registry.unregister_handle(b->resource, &b->resource);
GILReleaseGuard gil;
pw_cuEventDestroy(b->resource);
delete b;
Expand Down
7 changes: 4 additions & 3 deletions cuda_core/cuda/core/_cpp/rt/graph.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -686,13 +686,14 @@ static void
retire_graph(GraphHierarchy &hierarchy, std::list<GraphBox>::iterator graph) noexcept
{
for (auto &entry : graph->node_handles.drain()) {
if (GraphNodeHandle h_node = entry.second.lock()) {
if (GraphNodeHandle h_node = entry.second.handle.lock()) {
get_box(h_node)->resource = nullptr;
}
}
if (graph->resource) {
if (graph->parent) {
graph->parent->children.unregister_handle({graph->resource, graph->owner_node});
// Child graph handles alias &child.resource (create_child_graph_handle).
graph->parent->children.unregister_handle({graph->resource, graph->owner_node}, &graph->resource);
}
graph->resource = nullptr;
}
Expand Down Expand Up @@ -779,7 +780,7 @@ invalidate_graph_node(const GraphNodeHandle &h) noexcept
return;
}
GraphBox *graph = get_box(node_box->h_graph);
graph->node_handles.unregister_handle(node);
graph->node_handles.unregister_handle(node, &node_box->resource);
node_box->resource = nullptr;
}

Expand Down
59 changes: 52 additions & 7 deletions cuda_core/cuda/core/_cpp/rt/internal.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ const WarnOnFailure<p_cuMipmappedArrayDestroy> pw_cuMipmappedArrayDestroy{"cuMip
const WarnOnFailure<p_cuTexObjectDestroy> pw_cuTexObjectDestroy{"cuTexObjectDestroy"};
const WarnOnFailure<p_cuSurfObjectDestroy> pw_cuSurfObjectDestroy{"cuSurfObjectDestroy"};
const WarnOnFailure<p_cuGreenCtxDestroy> pw_cuGreenCtxDestroy{"cuGreenCtxDestroy"};
const WarnOnFailure<p_cuDevicePrimaryCtxRelease> pw_cuDevicePrimaryCtxRelease{"cuDevicePrimaryCtxRelease"};
const WarnOnFailure<p_cuMemPoolDestroy> pw_cuMemPoolDestroy{"cuMemPoolDestroy"};
const WarnOnFailure<p_cuMemFreeHost> pw_cuMemFreeHost{"cuMemFreeHost"};
const WarnOnFailure<p_cuMemRelease> pw_cuMemRelease{"cuMemRelease"};
Expand Down Expand Up @@ -179,28 +180,72 @@ void enqueue_cleanup(void *item) noexcept;
template <typename Key, typename Handle, typename Hash = std::hash<Key>>
class HandleRegistry {
public:
using MapType = std::unordered_map<Key, std::weak_ptr<typename Handle::element_type>, Hash>;
using Element = typename Handle::element_type;

// An entry keeps the element pointer next to the weak_ptr: a deleter's own
// weak_ptr has already expired, so ownership is checked by address.
struct Entry {
std::weak_ptr<Element> handle;
const Element *resource = nullptr;
};
using MapType = std::unordered_map<Key, Entry, Hash>;

void
register_handle(const Key &key, const Handle &h)
{
std::scoped_lock lock(mutex_);
map_[key] = h;
map_[key] = Entry{h, h.get()};
}

// Erase key's entry only if it was registered by the handle that pointed
// to resource, so a dying handle cannot erase the entry of a live handle
// registered under the same key. A deleter erases before freeing its box,
// so no other handle can share the address while the entry is compared.
void
unregister_handle(const Key &key) noexcept
unregister_handle(const Key &key, const Element *resource) noexcept
{
std::scoped_lock lock(mutex_);
auto it = map_.find(key);
if (it != map_.end() && it->second.resource == resource) {
map_.erase(it);
}
}

// Register candidate under key unless a live entry should be kept, and
// return the handle to use: the live entry, or candidate. replace(existing)
// decides whether candidate displaces a live entry; an expired entry is
// always displaced. replace runs under the registry's mutex, so it must
// not call the driver or acquire the GIL. Build candidate before calling
// and drop a losing candidate afterwards, never under the mutex: a deleter
// that takes this mutex would deadlock.
template <typename Replace>
Handle
insert_or_get(const Key &key, const Handle &candidate, Replace &&replace)
{
// Declared before the lock so that it is destroyed after the unlock.
// A displaced handle may hold the last reference to its box: another
// thread can drop its own copy while we hold this one. Its deleter
// takes this mutex, so releasing it under the lock would deadlock.
Handle existing;
std::scoped_lock lock(mutex_);
map_.erase(key);
auto [it, inserted] = map_.try_emplace(key);
if (!inserted) {
existing = it->second.handle.lock();
if (existing && !replace(existing)) {
return existing;
}
}
it->second = Entry{candidate, candidate.get()};
return candidate;
}

Handle
lookup(const Key &key)
{
std::scoped_lock lock(mutex_);
auto it = map_.find(key);
if (it != map_.end()) {
if (auto h = it->second.lock()) {
if (auto h = it->second.handle.lock()) {
return h;
}
map_.erase(it);
Expand All @@ -215,15 +260,15 @@ class HandleRegistry {
std::scoped_lock lock(mutex_);
auto it = map_.find(key);
if (it != map_.end()) {
if (Handle h = it->second.lock()) {
if (Handle h = it->second.handle.lock()) {
return h;
}
map_.erase(it);
}

Handle h = create();
if (h) {
map_[key] = h;
map_[key] = Entry{h, h.get()};
}
return h;
}
Expand Down
Loading
Loading