1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Craton Software Company
//! Process-wide CUDA primary-context management for the `wasi-cuda` launch
//! path (roadmap fix #6).
//!
//! ## The thread-bound-context bug this closes
//!
//! `cust` 0.3 uses CUDA's *primary context* model: [`cust::quick_init`] runs
//! `cuInit` + `cuDevicePrimaryCtxRetain` and makes the retained context
//! current via `cuCtxSetCurrent` — but `cuCtxSetCurrent` binds the context to
//! the **calling thread only**. The CUDA driver keeps the "current context" in
//! thread-local state.
//!
//! The launch path is multi-threaded:
//!
//! * `load_ptx` / `launch` run on whatever thread the wasmtime async fiber is
//! polled on (a tokio worker), which may never have touched CUDA;
//! * `launch` then moves `stream.synchronize()` into
//! [`tokio::task::spawn_blocking`], which runs on a *different* thread from
//! the blocking pool;
//! * libtest runs each `#[test]` / `#[tokio::test]` on its own thread.
//!
//! Before this module, only the first thread that happened to call
//! `quick_init` (typically a `tensor-wasm-mem` allocation, or the e2e test's
//! one-shot init) had a current context. Every other thread that reached a
//! `cuLaunchKernel` / `cuStreamSynchronize` saw `CUDA_ERROR_INVALID_CONTEXT`.
//! That surfaced as spurious `InvalidContext` launch failures under libtest
//! and — more importantly — in the production `spawn_blocking` synchronize
//! path.
//!
//! ## The fix
//!
//! Retain the device's primary context **once** per process (cached in a
//! `OnceLock`) and re-bind it to the **calling thread** on every entry into a
//! CUDA operation via [`ensure_current_context`]. Because primary contexts are
//! reference-counted and unique per device, retaining the same device's
//! primary context from several call sites (here, plus
//! `tensor-wasm-mem`'s `unified::ensure_cuda_init`) all resolve to the *same*
//! underlying `CUcontext`; `cuCtxSetCurrent` on any handle binds that one
//! context. So binding is always consistent regardless of which subsystem
//! initialised CUDA first.
//!
//! `cuCtxSetCurrent` is idempotent and cheap on a thread already bound to the
//! same context (the driver compares pointer identity — a single TLS write),
//! so callers invoke [`ensure_current_context`] unconditionally at the top of
//! every CUDA entry point, including inside the `spawn_blocking` closure.
//!
//! This mirrors the `mem M4` `ensure_context_bound` discipline the cudarc
//! backend already applies (`crates/tensor-wasm-mem/src/cudarc_backend.rs`);
//! the cust launch path needed the same treatment.
use OnceLock;
use sys as cuda_sys;
/// The process-wide device-0 primary-context handle, retained once.
///
/// We deliberately do NOT use `cust::quick_init` here. `quick_init` (and
/// `cust::context::Context::new`) is a *one-per-process* initialiser: calling it
/// after another subsystem has already initialised CUDA fails. In particular
/// `tensor-wasm-mem`'s `unified-memory` (cust) path runs its own init when the
/// `TensorWasmMemoryCreator` allocates a guest linear memory, so a `quick_init`
/// here would race it and one of the two would cache an `Err` forever — which
/// surfaced as spurious `CUDA_ERROR_INVALID_CONTEXT` at `Module::from_ptx` /
/// `cuLaunchKernel` once both code paths ran in the same process.
///
/// Instead we retain the device's PRIMARY context directly via
/// `cuDevicePrimaryCtxRetain`. The primary context is reference-counted and
/// unique per device, so every retainer in the process (here, plus
/// tensor-wasm-mem, plus cust's own `quick_init` if anything calls it) resolves
/// to the SAME `CUcontext`. Binding it current on a thread is then just a
/// thread-local `cuCtxSetCurrent`. We keep the handle for the process lifetime
/// (never `cuDevicePrimaryCtxRelease`) so the refcount never hits zero and
/// invalidates outstanding allocations.
///
/// Stored as `usize` (the raw `CUcontext` pointer value) so the `OnceLock` is
/// `Send + Sync`; the driver handle is just an opaque pointer.
static PRIMARY_CTX: = new;
/// Ensure device 0's primary CUDA context exists **and** is current on the
/// calling thread.
///
/// Idempotent and safe to call from any thread — the tokio fiber thread, a
/// `spawn_blocking` pool thread, or a libtest harness thread. The first call in
/// the process retains the device-0 primary context; every call (including the
/// first) then `cuCtxSetCurrent`s it onto the current thread.
///
/// Returns the underlying CUDA error as a `String` on failure so callers can
/// fold it into their own `record_error` + `AbiError` mapping.