Skip to main content

virtio_accel_xdna/
native.rs

1//! Native XDNA backend over the HRX runtime (`libhrx`).
2//!
3//! This module owns every call across the `ffi` boundary. `SAFETY.md` is the audit of record; each
4//! `unsafe` block below carries a local `SAFETY:` note. It implements the execution-model spec
5//! (issue #85): one audited process-wide device owner, a per-instance stream driven by one
6//! serialized dispatch worker, a bounded preallocated submission ring and event-slot pool, and the
7//! `hrx_buffer` primitives (persistent host mapping, range flush/invalidate, release).
8//!
9//! `load_program` accepts the crate-local precompiled artifact format directly, and a TOSA
10//! artifact by admitting it (`lower`) and compiling it with the bounded helper subprocess
11//! (`compiler`); it builds an `hrx_amdxdna_executable` and dispatches it through the worker.
12//! Finite timeouts are rejected before admission (no cancellation exists); a synchronize error
13//! latches the event `Failed` and poisons the instance (device-loss tier 1). A 120-second watchdog
14//! detects a synchronize call that outlives the kernel's 60-second TDR (tier 2), poisons the
15//! instance, and quarantines the still-pending job until the backend is discarded.
16
17use core::ffi::c_void;
18use core::marker::PhantomData;
19use core::mem::size_of;
20use core::ptr::{self, NonNull};
21use core::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
22use std::collections::VecDeque;
23use std::ffi::CString;
24use std::sync::{Arc, Condvar, Mutex};
25use std::thread::JoinHandle;
26use std::time::{Duration, Instant};
27
28use virtio_accel_core::{
29    Accelerator, AcceleratorClass, AccessMode, AllocatedBuffer, ArtifactRef, BackendError,
30    BindingRef, BufferDesc, BufferInfo, BufferProperties, BufferUsage, ByteSink, ByteSource,
31    Capabilities, ContextDesc, DeviceIdentity, DeviceInfo, DeviceLimits, EventState, MemoryDomain,
32    QueueDesc, ReleaseFailure, SubmitFailure, Timeout,
33};
34
35use crate::artifact::{self, PrecompiledArtifact};
36use crate::compiler::Compiler;
37use crate::ffi;
38use crate::lower;
39use crate::{InitError, XDNA_ERROR_DOMAIN};
40
41/// Upper bound advertised for a loaded artifact (mirrors the OpenVINO backend).
42const MAX_TOSA_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024;
43
44/// Default submission-ring depth: up to four requests outstanding per instance. Issue #85 started
45/// at one (matching the Hexagon backend); pipelined dispatch (#151/#149) raised it so consecutive
46/// submissions overlap on the stream and the per-submission host cost amortizes.
47const DEFAULT_RING_DEPTH: usize = 4;
48
49/// Completion waits poll the stream timeline in bounded slices so the worker observes a watchdog
50/// wedge verdict promptly and no HRX call blocks unboundedly.
51const WAIT_SLICE_NS: u64 = 100_000_000;
52
53/// AIE DMA descriptors transfer whole four-byte words, so a bound range must begin on a word
54/// boundary as well as cover its slot's exact byte length. The base mapping is page-aligned, so the
55/// caller's offset alone decides alignment (the reference backend rejects the same way, against its
56/// per-slot scalar size).
57const DMA_WORD_BYTES: u64 = 4;
58
59/// The kernel's NPU TDR is 60 seconds. A longer userspace watchdog distinguishes a returned
60/// device-loss error (tier 1) from an HRX synchronize call that never returns (tier 2).
61const DEFAULT_WATCHDOG_TIMEOUT: Duration = Duration::from_secs(120);
62
63/// Internal state-machine failure: a live event handle observed a free/unknown slot state.
64const INVALID_EVENT_STATE_CODE: i64 = 200;
65
66/// Consume an HRX status and map it to a `BackendError`.
67///
68/// A non-NULL `hrx_status_t` is owned by the caller and must be consumed exactly once. This reads
69/// its code, then ignores it (freeing it); on error it also renders and frees the message so the
70/// message allocation is released (it is not logged — no logging facility exists at this layer).
71/// `NULL` is success.
72fn check(status: ffi::hrx_status_t) -> Result<(), BackendError> {
73    if status.is_null() {
74        return Ok(());
75    }
76    // SAFETY: `status` is a non-NULL status just returned by an HRX call; reading its code and
77    // ignoring it are the documented consume operations and are valid exactly once.
78    let code = unsafe { (ffi::api().hrx_status_code)(status) };
79    // SAFETY: out-pointers are valid locals; `hrx_status_to_string` returns its own status which we
80    // ignore, and any produced message is freed with `hrx_status_free_message`.
81    unsafe {
82        let mut message: *mut core::ffi::c_char = ptr::null_mut();
83        let mut length: usize = 0;
84        let string_status = (ffi::api().hrx_status_to_string)(status, &mut message, &mut length);
85        if !message.is_null() {
86            (ffi::api().hrx_status_free_message)(message);
87        }
88        (ffi::api().hrx_status_ignore)(string_status);
89        (ffi::api().hrx_status_ignore)(status);
90    }
91    Err(backend_error_from_code(code))
92}
93
94/// The two `hrx_status_code_t` values the retire loop branches on by value.
95mod code {
96    pub(super) const OK: super::ffi::hrx_status_code_t = 0;
97    pub(super) const DEADLINE_EXCEEDED: super::ffi::hrx_status_code_t = 4;
98}
99
100/// Map an HRX status code (`hrx_status_code_t`, mirroring IREE) to a `BackendError`.
101fn backend_error_from_code(code: ffi::hrx_status_code_t) -> BackendError {
102    match code {
103        3 => BackendError::InvalidArgument,  // INVALID_ARGUMENT
104        4 => BackendError::DeadlineExpired,  // DEADLINE_EXCEEDED
105        7 => BackendError::PermissionDenied, // PERMISSION_DENIED
106        8 => BackendError::OutOfMemory,      // OUT_OF_MEMORY (RESOURCE_EXHAUSTED)
107        11 => BackendError::OutOfBounds,     // OUT_OF_RANGE
108        12 => BackendError::Unsupported,     // UNIMPLEMENTED
109        14 => BackendError::DeviceLost,      // UNAVAILABLE
110        other => BackendError::External {
111            domain: XDNA_ERROR_DOMAIN,
112            code: other as i64,
113        },
114    }
115}
116
117/// The process-wide HRX device, initialized once and never shut down (the fork's model: one
118/// device per process, `hrx_gpu_shutdown` is never called).
119struct SharedDevice(NonNull<ffi::hrx_device_s>);
120
121// SAFETY: the device handle is refcounted and, in HRX's amdxdna HAL, is a process-wide singleton
122// reachable from any thread. This module uses it only to create per-instance streams and
123// executables (read-only factory use), never mutating it; sharing the pointer across threads for
124// that use is sound. Concurrency hazards live on the stream, which is serialized (see `Lane`).
125unsafe impl Send for SharedDevice {}
126unsafe impl Sync for SharedDevice {}
127
128fn shared_device() -> Result<&'static SharedDevice, InitError> {
129    ffi::ensure_loaded()?;
130    use std::sync::OnceLock;
131    static DEVICE: OnceLock<Result<SharedDevice, InitError>> = OnceLock::new();
132    DEVICE
133        .get_or_init(|| {
134            // SAFETY: HRX GPU initialization is process-wide and idempotent under the OnceLock;
135            // the out-pointers are valid locals and every returned status is consumed by `check`.
136            unsafe {
137                check((ffi::api().hrx_gpu_initialize)(0)).map_err(|_| InitError::Initialization)?;
138                let mut count: core::ffi::c_int = 0;
139                check((ffi::api().hrx_gpu_device_count)(&mut count))
140                    .map_err(|_| InitError::Initialization)?;
141                if count < 1 {
142                    return Err(InitError::DeviceUnavailable);
143                }
144                let mut device: ffi::hrx_device_t = ptr::null_mut();
145                check((ffi::api().hrx_gpu_device_get)(0, &mut device))
146                    .map_err(|_| InitError::Initialization)?;
147                NonNull::new(device)
148                    .map(SharedDevice)
149                    .ok_or(InitError::Initialization)
150            }
151        })
152        .as_ref()
153        .map_err(|error| *error)
154}
155
156/// An owned HRX stream. Access is serialized by the `Lane` mutex.
157struct Stream(NonNull<ffi::hrx_stream_s>);
158
159// SAFETY: the stream pointer is only ever dereferenced while the `Lane` stream mutex is held, so it
160// is never used concurrently; moving it between the constructing thread and the worker is sound.
161unsafe impl Send for Stream {}
162
163impl Drop for Stream {
164    fn drop(&mut self) {
165        // SAFETY: the lane owns exactly one stream reference. A normal teardown joins the worker;
166        // a detached tier-2 worker itself holds the last lane Arc, so this Drop still cannot run
167        // until its HRX call has returned and no dispatch is in progress.
168        unsafe { (ffi::api().hrx_stream_release)(self.0.as_ptr()) };
169    }
170}
171
172/// Terminal-state codes latched into an [`EventSlot`].
173mod slot_state {
174    pub const FREE: u8 = 0;
175    pub const PENDING: u8 = 1;
176    pub const COMPLETE: u8 = 2;
177    pub const FAILED: u8 = 3;
178}
179
180/// One preallocated event slot: a latched terminal state plus the failure detail.
181#[derive(Debug)]
182struct EventSlot {
183    state: AtomicU8,
184    error: Mutex<Option<BackendError>>,
185}
186
187/// Provider-owned resources that are currently live for one backend instance.
188///
189/// This is intentionally backend-local rather than part of the `Accelerator` ABI. The shared
190/// conformance hook translates it to its own `ResourceCounts` type.
191#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
192pub struct XdnaResourceCounts {
193    pub contexts: u64,
194    pub buffers: u64,
195    pub programs: u64,
196    pub queues: u64,
197    pub events: u64,
198}
199
200#[derive(Debug, Default)]
201struct ResourceTracker {
202    contexts: AtomicU64,
203    buffers: AtomicU64,
204    programs: AtomicU64,
205    queues: AtomicU64,
206    events: AtomicU64,
207}
208
209impl ResourceTracker {
210    fn snapshot(&self) -> XdnaResourceCounts {
211        XdnaResourceCounts {
212            contexts: self.contexts.load(Ordering::Acquire),
213            buffers: self.buffers.load(Ordering::Acquire),
214            programs: self.programs.load(Ordering::Acquire),
215            queues: self.queues.load(Ordering::Acquire),
216            events: self.events.load(Ordering::Acquire),
217        }
218    }
219
220    fn decrement(counter: &AtomicU64) {
221        let previous = counter.fetch_sub(1, Ordering::AcqRel);
222        debug_assert!(previous > 0, "XDNA resource counter underflow");
223    }
224}
225
226impl EventSlot {
227    fn new() -> Arc<Self> {
228        Arc::new(Self {
229            state: AtomicU8::new(slot_state::FREE),
230            error: Mutex::new(None),
231        })
232    }
233
234    fn latch(&self, result: Result<(), BackendError>) {
235        match result {
236            Ok(()) => self.state.store(slot_state::COMPLETE, Ordering::Release),
237            Err(error) => {
238                *self.error.lock().expect("event error mutex") = Some(error);
239                self.state.store(slot_state::FAILED, Ordering::Release);
240            }
241        }
242    }
243}
244
245/// One queued dispatch handed to the worker. The raw pointers are HRX handles — heap objects HRX
246/// owns, whose addresses are independent of where the caller's `XdnaBuffer`/`XdnaProgram` values
247/// live. The accompanying Arcs keep those handles referenced for the full worker operation, even
248/// when a poisoned backend is discarded, and the worker touches them only under the stream mutex.
249/// The in-flight gates live in the same Arcs, not in caller-movable structs.
250struct Job {
251    program: Arc<ProgramInner>,
252    bindings: Vec<ffi::hrx_buffer_ref_t>,
253    outputs: Vec<(ffi::hrx_buffer_t, usize, usize)>,
254    /// Retains each distinct HRX allocation and supplies its address-stable in-flight gate.
255    buffers: Vec<Arc<BufferInner>>,
256    slot: Arc<EventSlot>,
257}
258
259// SAFETY: the raw pointers in a `Job` are HRX buffer/executable handles: heap objects owned by the
260// HRX runtime whose addresses do not change when the caller moves its Rust-side handle values.
261// Their accompanying Arcs keep them referenced until the worker has stopped touching them, and
262// they are dereferenced only on the worker thread while the stream mutex is held. Moving the job to
263// the worker transfers that exclusive access. Everything else in the job (`Arc`s) is `Send`.
264unsafe impl Send for Job {}
265
266/// The bounded submission ring. `queue` holds accepted jobs the worker has not yet dispatched;
267/// `dispatched` counts jobs the worker has moved onto the device but not yet retired. Their sum is
268/// bounded by the lane depth, so `submit` rejects with `Busy` exactly when `depth` submissions are
269/// outstanding in any mix of queued and in-flight.
270struct Ring {
271    queue: VecDeque<Job>,
272    dispatched: usize,
273    stopping: bool,
274}
275
276#[derive(Debug)]
277struct WatchdogState {
278    generation: u64,
279    active: Option<(u64, Instant)>,
280    stopping: bool,
281}
282
283#[cfg(feature = "test-control")]
284#[derive(Clone, Copy, Debug)]
285enum InjectedFault {
286    Tier1,
287    Tier2 { stall: Duration },
288    HoldDispatch { hold: Duration },
289}
290
291/// One-shot fault used by the on-metal fault-path tests.
292#[cfg(feature = "test-control")]
293#[derive(Clone, Copy, Debug)]
294#[doc(hidden)]
295pub enum XdnaTestFault {
296    /// Return a definite device-loss error from the worker before dispatching to HRX.
297    Tier1,
298    /// Hold the worker beyond the watchdog deadline without touching HRX.
299    Tier2 { stall: Duration },
300    /// Delay the worker before one normal dispatch (no fault): a deterministic pending window for
301    /// tests that assert in-flight semantics, which are otherwise a race against real completion.
302    HoldDispatch { hold: Duration },
303}
304
305/// Test-only construction parameters. This API is absent unless `test-control` is enabled.
306#[cfg(feature = "test-control")]
307#[derive(Clone, Copy, Debug)]
308#[doc(hidden)]
309pub struct XdnaTestConfig {
310    pub watchdog_timeout: Duration,
311    pub fault: XdnaTestFault,
312}
313
314/// One instance's serialized dispatch lane: the stream, the ring, and the poison flag.
315struct Lane {
316    stream: Mutex<Stream>,
317    ring: Mutex<Ring>,
318    signal: Condvar,
319    poisoned: AtomicBool,
320    wedged: AtomicBool,
321    watchdog: Mutex<WatchdogState>,
322    watchdog_signal: Condvar,
323    watchdog_timeout: Duration,
324    #[cfg(feature = "test-control")]
325    injected_fault: Mutex<Option<InjectedFault>>,
326    depth: usize,
327}
328
329impl Lane {
330    fn is_poisoned(&self) -> bool {
331        self.poisoned.load(Ordering::Acquire)
332    }
333
334    fn arm_watchdog(&self) -> u64 {
335        let mut watchdog = self.watchdog.lock().expect("watchdog mutex");
336        watchdog.generation = watchdog.generation.wrapping_add(1);
337        let generation = watchdog.generation;
338        watchdog.active = Some((generation, Instant::now() + self.watchdog_timeout));
339        self.watchdog_signal.notify_one();
340        generation
341    }
342
343    /// Disarm one dispatch. `false` means the watchdog already declared this lane wedged.
344    fn disarm_watchdog(&self, generation: u64) -> bool {
345        let mut watchdog = self.watchdog.lock().expect("watchdog mutex");
346        if matches!(watchdog.active, Some((active, _)) if active == generation) {
347            watchdog.active = None;
348        }
349        self.watchdog_signal.notify_one();
350        !self.wedged.load(Ordering::Acquire)
351    }
352
353    fn run_watchdog(self: &Arc<Self>) {
354        let mut watchdog = self.watchdog.lock().expect("watchdog mutex");
355        loop {
356            if watchdog.stopping {
357                return;
358            }
359            let Some((generation, deadline)) = watchdog.active else {
360                watchdog = self
361                    .watchdog_signal
362                    .wait(watchdog)
363                    .expect("watchdog condvar");
364                continue;
365            };
366            let now = Instant::now();
367            if now < deadline {
368                let (next, _) = self
369                    .watchdog_signal
370                    .wait_timeout(watchdog, deadline - now)
371                    .expect("watchdog condvar");
372                watchdog = next;
373                continue;
374            }
375            if matches!(watchdog.active, Some((active, _)) if active == generation) {
376                watchdog.active = None;
377                self.wedged.store(true, Ordering::Release);
378                self.poisoned.store(true, Ordering::Release);
379                return;
380            }
381        }
382    }
383
384    /// Run the worker loop: keep up to `depth` jobs in flight on the stream, retiring the oldest
385    /// while later submissions are already recorded and executing. Dispatch (record + flush +
386    /// timeline position) holds the stream mutex briefly; the completion wait blocks on the
387    /// stream's timeline semaphore with no lock held, so `allocate_buffer` never queues behind a
388    /// running dispatch. In-flight jobs are worker-owned: on a tier-2 wedge the worker parks
389    /// forever holding them (and the `Arc<Lane>` stream), forming the quarantine.
390    fn run_worker(self: &Arc<Self>) {
391        let mut in_flight: VecDeque<(Job, ffi::hrx_timeline_point_t)> = VecDeque::new();
392        // The timeline target of the most recently dispatched job. The stream is instance-private
393        // and dispatches are serialized under the stream mutex, so each job's target is exactly
394        // the first timeline value observed past its predecessor's (see `dispatch_job`).
395        let mut last_target: u64 = 0;
396        loop {
397            // Fill: move queued jobs onto the device up to the lane depth.
398            loop {
399                let job = {
400                    let mut ring = self.ring.lock().expect("ring mutex");
401                    if in_flight.len() >= self.depth {
402                        None
403                    } else if let Some(job) = ring.queue.pop_front() {
404                        ring.dispatched += 1;
405                        Some(job)
406                    } else {
407                        None
408                    }
409                };
410                let Some(job) = job else { break };
411                match self.dispatch_job(job, &mut last_target) {
412                    DispatchOutcome::InFlight(entry) => in_flight.push_back(entry),
413                    // Terminal at dispatch (error, poisoned short-circuit, or an injected
414                    // fault). `finish` released the ring capacity where a terminal state was
415                    // latched; the deliberately-pending outcomes (untrusted boundary, injected
416                    // tier 2) keep their slot and capacity, as quarantined work must.
417                    DispatchOutcome::Retired => {}
418                }
419            }
420            // Retire the oldest in-flight job, or sleep until there is work.
421            if let Some((job, position)) = in_flight.pop_front() {
422                if !self.retire(job, position) {
423                    // Tier-2 wedge: no trustworthy completion boundary exists for this job or
424                    // anything recorded behind it. Park forever holding every in-flight job's
425                    // retained resources and the stream; `Drop` detaches this thread.
426                    loop {
427                        std::thread::sleep(Duration::from_secs(3600));
428                    }
429                }
430                continue;
431            }
432            let mut ring = self.ring.lock().expect("ring mutex");
433            loop {
434                if !ring.queue.is_empty() {
435                    break;
436                }
437                if ring.stopping {
438                    return;
439                }
440                ring = self.signal.wait(ring).expect("ring condvar");
441            }
442        }
443    }
444
445    /// Dispatch one job: record it on the stream, flush, and capture its timeline position. On a
446    /// definite error the job is latched `Failed` here and the instance poisons (device-loss
447    /// tier 1); on a poisoned lane the job short-circuits to `Failed(DeviceLost)` without touching
448    /// the stream. Injected test faults are consumed here, before any HRX call.
449    fn dispatch_job(&self, job: Job, last_target: &mut u64) -> DispatchOutcome {
450        #[cfg(feature = "test-control")]
451        {
452            let injected = self
453                .injected_fault
454                .lock()
455                .expect("fault-injector mutex")
456                .take();
457            match injected {
458                Some(InjectedFault::Tier2 { stall }) => {
459                    let watchdog_generation = self.arm_watchdog();
460                    std::thread::sleep(stall);
461                    let _ = self.disarm_watchdog(watchdog_generation);
462                    // Tier 2 has no trustworthy completion boundary: leave the event pending and
463                    // every gate armed. Discarding the backend quarantines this job's native
464                    // resources. (No HRX call was made, so dropping the job itself is safe.)
465                    return DispatchOutcome::Retired;
466                }
467                Some(InjectedFault::Tier1) => {
468                    let generation = self.arm_watchdog();
469                    let trusted = self.disarm_watchdog(generation);
470                    if trusted {
471                        self.finish(job, Err(BackendError::DeviceLost));
472                    }
473                    return DispatchOutcome::Retired;
474                }
475                Some(InjectedFault::HoldDispatch { hold }) => {
476                    // A deterministic pending window: the event and every in-flight gate stay
477                    // armed for at least `hold`, then the job proceeds normally.
478                    std::thread::sleep(hold);
479                }
480                None => {}
481            }
482        }
483        // A poisoned lane refuses the stream: jobs accepted before the poison latch terminally.
484        if self.is_poisoned() {
485            self.finish(job, Err(BackendError::DeviceLost));
486            return DispatchOutcome::Retired;
487        }
488
489        let config = ffi::hrx_dispatch_config_t {
490            workgroup_count: [1, 1, 1],
491            workgroup_size: [1, 1, 1],
492            subgroup_size: 0,
493        };
494        let program = job.program.as_ref();
495        let stream = self.stream.lock().expect("stream mutex");
496        // The watchdog covers the record/flush ioctls too: a driver hang here is the same
497        // ownership-boundary loss as one during the completion wait.
498        let watchdog_generation = self.arm_watchdog();
499        // SAFETY: the stream, executable, and every bound buffer are retained by the lane/job for
500        // this call; the bindings slice is valid for `binding_count`; the config is a valid local;
501        // constants are unused on this path.
502        let dispatch = unsafe {
503            (ffi::api().hrx_stream_dispatch)(
504                stream.0.as_ptr(),
505                program.executable.as_ptr(),
506                program.ordinal,
507                &config,
508                ptr::null(),
509                0,
510                job.bindings.as_ptr(),
511                job.bindings.len(),
512                0,
513            )
514        };
515        let result = check(dispatch).and_then(|()| {
516            // SAFETY: the stream is live; flush submits the recorded work without waiting.
517            check(unsafe { (ffi::api().hrx_stream_flush)(stream.0.as_ptr()) })?;
518            // The flushed batch's timeline value is assigned asynchronously: a position read
519            // before the dispatch (or immediately after the flush, on an unlucky schedule) still
520            // reports the previous batch's target, and waiting on that retires this job early --
521            // observed on metal as stale outputs. The stream is instance-private and dispatches
522            // are serialized under this mutex, so only this flush can advance the timeline past
523            // the previous job's target: spin until it does, and that value is exactly this
524            // job's completion tick. The watchdog is armed, so a driver that never assigns is
525            // declared wedged rather than spun on forever.
526            loop {
527                let mut position = ffi::hrx_timeline_point_t {
528                    semaphore: ptr::null_mut(),
529                    value: 0,
530                };
531                // SAFETY: the stream is live; the out-pointer is a valid local.
532                check(unsafe {
533                    (ffi::api().hrx_stream_get_timeline_position)(stream.0.as_ptr(), &mut position)
534                })?;
535                if position.value > *last_target {
536                    *last_target = position.value;
537                    break Ok(position);
538                }
539                if self.wedged.load(Ordering::Acquire) {
540                    break Err(BackendError::DeviceLost);
541                }
542                std::thread::yield_now();
543            }
544        });
545        drop(stream);
546        let trusted = self.disarm_watchdog(watchdog_generation);
547        if !trusted {
548            // The ioctl returned only after the watchdog declared the boundary lost: keep the
549            // event pending, keep the gates armed; the caller's teardown quarantines.
550            return DispatchOutcome::Retired;
551        }
552        match result {
553            Ok(position) => DispatchOutcome::InFlight((job, position)),
554            Err(error) => {
555                self.finish(job, Err(error));
556                DispatchOutcome::Retired
557            }
558        }
559    }
560
561    /// Wait for one in-flight job's timeline position and latch its terminal state. Returns
562    /// `false` when the watchdog declared the lane wedged while waiting (tier 2): the caller must
563    /// quarantine, because the device may still write through this and every later in-flight
564    /// job's bindings.
565    fn retire(&self, job: Job, position: ffi::hrx_timeline_point_t) -> bool {
566        let watchdog_generation = self.arm_watchdog();
567        let result = loop {
568            // Bounded slices keep this wait off the stream mutex and let the watchdog's verdict
569            // surface promptly; the semaphore is the stream's own timeline object, valid while
570            // the lane retains the stream, and safe to wait on while another thread holds the
571            // stream mutex (it is a standalone synchronization object).
572            // SAFETY: `position.semaphore` is the live stream timeline semaphore (see above); the
573            // status is consumed.
574            let status = unsafe {
575                (ffi::api().hrx_semaphore_wait)(position.semaphore, position.value, WAIT_SLICE_NS)
576            };
577            let code = unsafe { (ffi::api().hrx_status_code)(status) };
578            unsafe { (ffi::api().hrx_status_ignore)(status) };
579            match code {
580                code::OK => break Ok(()),
581                code::DEADLINE_EXCEEDED => {
582                    if self.wedged.load(Ordering::Acquire) {
583                        // Watchdog verdict while we sliced: same as disarm returning untrusted.
584                        return false;
585                    }
586                }
587                other => break Err(backend_error_from_code(other)),
588            }
589        };
590        let trusted = self.disarm_watchdog(watchdog_generation);
591        if !trusted {
592            return false;
593        }
594        let result = result.and_then(|()| {
595            for &(buffer, offset, len) in &job.outputs {
596                // SAFETY: each output buffer is live and persistently mapped; the range was
597                // validated at submit; invalidate makes device writes host-visible.
598                check(unsafe { (ffi::api().hrx_buffer_invalidate_range)(buffer, offset, len) })?;
599            }
600            Ok(())
601        });
602        self.finish(job, result);
603        true
604    }
605
606    /// Publish a job's terminal state: clear the in-flight gates, latch the event, and poison the
607    /// instance on failure (device-loss tier 1).
608    fn finish(&self, job: Job, result: Result<(), BackendError>) {
609        let failed = result.is_err();
610        // Release this job's ring capacity before the terminal state becomes observable: a caller
611        // that polls `Complete`, destroys the event, and immediately resubmits must never bounce
612        // off a stale `dispatched` count.
613        {
614            let mut ring = self.ring.lock().expect("ring mutex");
615            ring.dispatched -= 1;
616        }
617        // Clear the in-flight gates before publishing the terminal state, so a caller that observes
618        // completion may immediately read or free the buffers. The retained `Arc`s remain valid
619        // regardless of where (or whether) the caller's buffer values still live.
620        for buffer in &job.buffers {
621            buffer.in_flight.store(0, Ordering::Release);
622        }
623        // Latch the terminal state before poisoning, so this event reports its real error rather
624        // than the instance-level `DeviceLost`.
625        job.slot.latch(result);
626        if failed {
627            // Device-loss tier 1: the kernel TDR (or a definite HRX error) has returned; the
628            // instance refuses further work (libhrx is not validated to remain healthy after an
629            // under-the-hood context recreate).
630            self.poisoned.store(true, Ordering::Release);
631        }
632    }
633}
634
635/// What became of one job handed to `dispatch_job`.
636enum DispatchOutcome {
637    /// Recorded and flushed; retire it at this timeline position.
638    InFlight((Job, ffi::hrx_timeline_point_t)),
639    /// Terminal at dispatch: latched (error paths) or deliberately left pending (untrusted
640    /// boundary and the injected tier-2 fault).
641    Retired,
642}
643
644/// One HRX backend instance: a serialized dispatch lane over the shared device.
645pub struct XdnaAccelerator {
646    lane: Arc<Lane>,
647    worker: Option<JoinHandle<()>>,
648    watchdog: Option<JoinHandle<()>>,
649    slots: Vec<Arc<EventSlot>>,
650    compiler: CompilerState,
651    info: DeviceInfo,
652    next_id: AtomicU64,
653    resources: Arc<ResourceTracker>,
654    /// Cumulative count of buffers admitted as direct bindings (no submission-time staging copy).
655    direct_binding_admissions: AtomicU64,
656    /// Cumulative bytes moved by explicit `write_buffer`/`read_buffer` transfers.
657    explicit_transfer_bytes: AtomicU64,
658    _not_send_sync: PhantomData<*mut u8>,
659}
660
661enum CompilerState {
662    Ready(Compiler),
663    Unconfigured,
664    Failed(BackendError),
665}
666
667impl XdnaAccelerator {
668    /// Initialize the shared device (once per process), create this instance's stream, and start
669    /// its dispatch worker.
670    pub fn new() -> Result<Self, InitError> {
671        #[cfg(feature = "test-control")]
672        return Self::initialize(DEFAULT_WATCHDOG_TIMEOUT, None);
673        #[cfg(not(feature = "test-control"))]
674        Self::initialize(DEFAULT_WATCHDOG_TIMEOUT)
675    }
676
677    /// Construct a backend with one deterministic fault and a shortened watchdog.
678    #[cfg(feature = "test-control")]
679    #[doc(hidden)]
680    pub fn new_for_testing(config: XdnaTestConfig) -> Result<Self, InitError> {
681        if config.watchdog_timeout.is_zero() {
682            return Err(InitError::Initialization);
683        }
684        let fault = match config.fault {
685            XdnaTestFault::Tier1 => InjectedFault::Tier1,
686            XdnaTestFault::Tier2 { stall } if stall > config.watchdog_timeout => {
687                InjectedFault::Tier2 { stall }
688            }
689            XdnaTestFault::Tier2 { .. } => return Err(InitError::Initialization),
690            // The hold must stay well inside the watchdog deadline: it delays a healthy
691            // dispatch, it does not simulate a hang.
692            XdnaTestFault::HoldDispatch { hold }
693                if !hold.is_zero() && hold * 2 <= config.watchdog_timeout =>
694            {
695                InjectedFault::HoldDispatch { hold }
696            }
697            XdnaTestFault::HoldDispatch { .. } => return Err(InitError::Initialization),
698        };
699        Self::initialize(config.watchdog_timeout, Some(fault))
700    }
701
702    fn initialize(
703        watchdog_timeout: Duration,
704        #[cfg(feature = "test-control")] fault: Option<InjectedFault>,
705    ) -> Result<Self, InitError> {
706        let device = shared_device()?;
707        let mut stream: ffi::hrx_stream_t = ptr::null_mut();
708        // SAFETY: `device.0` is the live process-wide device; the out-pointer is a valid local and
709        // the returned status is consumed by `check`.
710        let status = unsafe { (ffi::api().hrx_stream_create)(device.0.as_ptr(), 0, &mut stream) };
711        check(status).map_err(|_| InitError::Initialization)?;
712        let stream = NonNull::new(stream).ok_or(InitError::Initialization)?;
713
714        let depth = DEFAULT_RING_DEPTH;
715        let lane = Arc::new(Lane {
716            stream: Mutex::new(Stream(stream)),
717            ring: Mutex::new(Ring {
718                queue: VecDeque::with_capacity(depth),
719                dispatched: 0,
720                stopping: false,
721            }),
722            signal: Condvar::new(),
723            poisoned: AtomicBool::new(false),
724            wedged: AtomicBool::new(false),
725            watchdog: Mutex::new(WatchdogState {
726                generation: 0,
727                active: None,
728                stopping: false,
729            }),
730            watchdog_signal: Condvar::new(),
731            watchdog_timeout,
732            #[cfg(feature = "test-control")]
733            injected_fault: Mutex::new(fault),
734            depth,
735        });
736        let slots = (0..depth).map(|_| EventSlot::new()).collect();
737
738        let watchdog_lane = Arc::clone(&lane);
739        let watchdog = std::thread::Builder::new()
740            .name("xdna-watchdog".into())
741            .spawn(move || watchdog_lane.run_watchdog())
742            .map_err(|_| InitError::Initialization)?;
743
744        let worker_lane = Arc::clone(&lane);
745        let worker = match std::thread::Builder::new()
746            .name("xdna-dispatch".into())
747            .spawn(move || worker_lane.run_worker())
748        {
749            Ok(worker) => worker,
750            Err(_) => {
751                {
752                    let mut state = lane.watchdog.lock().expect("watchdog mutex");
753                    state.stopping = true;
754                }
755                lane.watchdog_signal.notify_all();
756                let _ = watchdog.join();
757                return Err(InitError::Initialization);
758            }
759        };
760
761        let compiler = match Compiler::from_env() {
762            Ok(compiler) => CompilerState::Ready(compiler),
763            Err(_error) if std::env::var_os("VIRTIO_ACCEL_AMDXDNA_TOOLCHAIN").is_none() => {
764                CompilerState::Unconfigured
765            }
766            Err(error) => CompilerState::Failed(error),
767        };
768
769        Ok(Self {
770            lane,
771            worker: Some(worker),
772            watchdog: Some(watchdog),
773            slots,
774            compiler,
775            info: device_info(),
776            next_id: AtomicU64::new(1),
777            resources: Arc::new(ResourceTracker::default()),
778            direct_binding_admissions: AtomicU64::new(0),
779            explicit_transfer_bytes: AtomicU64::new(0),
780            _not_send_sync: PhantomData,
781        })
782    }
783
784    fn next_id(&self) -> u64 {
785        self.next_id.fetch_add(1, Ordering::Relaxed)
786    }
787
788    /// Cumulative count of buffers admitted as direct bindings (no submission-time staging copy).
789    ///
790    /// Every XDNA buffer is a persistently mapped, device-visible allocation bound straight into
791    /// the dispatch with no bounce buffer, so a submission admits `bindings.len()` direct bindings
792    /// and stages none. Surfaced to the conformance transfer/staging diagnostics hook (issue #90).
793    pub fn direct_binding_admissions(&self) -> u64 {
794        self.direct_binding_admissions.load(Ordering::Relaxed)
795    }
796
797    /// Cumulative bytes moved by explicit `write_buffer`/`read_buffer` transfers.
798    pub fn explicit_transfer_bytes(&self) -> u64 {
799        self.explicit_transfer_bytes.load(Ordering::Relaxed)
800    }
801
802    /// Snapshot provider-owned resources that have been admitted but not successfully released.
803    pub fn resource_counts(&self) -> XdnaResourceCounts {
804        self.resources.snapshot()
805    }
806
807    /// Claim a free event slot, transitioning it to `PENDING`.
808    fn claim_slot(&self) -> Option<Arc<EventSlot>> {
809        self.slots.iter().find_map(|slot| {
810            slot.state
811                .compare_exchange(
812                    slot_state::FREE,
813                    slot_state::PENDING,
814                    Ordering::AcqRel,
815                    Ordering::Acquire,
816                )
817                .is_ok()
818                .then(|| Arc::clone(slot))
819        })
820    }
821}
822
823impl Drop for XdnaAccelerator {
824    fn drop(&mut self) {
825        // Signal both threads to stop. A normally quiescent worker is joined before the stream is
826        // released. If an accepted event is still pending (including a tier-2 wedge), detach the
827        // worker instead: its `Arc<Lane>` and the job's retained native resources form the
828        // quarantine and make discarding the poisoned instance nonblocking and memory-safe.
829        {
830            let mut ring = self.lane.ring.lock().expect("ring mutex");
831            ring.stopping = true;
832        }
833        self.lane.signal.notify_all();
834        {
835            let mut watchdog = self.lane.watchdog.lock().expect("watchdog mutex");
836            watchdog.stopping = true;
837        }
838        self.lane.watchdog_signal.notify_all();
839        if let Some(watchdog) = self.watchdog.take() {
840            let _ = watchdog.join();
841        }
842        let has_pending = self
843            .slots
844            .iter()
845            .any(|slot| slot.state.load(Ordering::Acquire) == slot_state::PENDING);
846        if let Some(worker) = self.worker.take() {
847            if !has_pending && !self.lane.wedged.load(Ordering::Acquire) {
848                let _ = worker.join();
849            }
850        }
851    }
852}
853
854/// A device-neutral description of the XDNA NPU.
855fn device_info() -> DeviceInfo {
856    DeviceInfo {
857        identity: DeviceIdentity {
858            uuid: *b"amd.xdna.npu\0\0\0\0",
859            class: AcceleratorClass::NPU,
860            vendor_id: 0x1022,
861            device_id: 0x17f0,
862        },
863        capabilities: Capabilities::HOST_VISIBLE_MEMORY | Capabilities::SHARED_MEMORY,
864        // Finite aggregate bounds: the device-state layer checked-multiplies `max_contexts` by each
865        // per-context limit, so `u32::MAX` would overflow and reject the backend. These mirror the
866        // OpenVINO backend's advertised limits.
867        limits: DeviceLimits {
868            max_contexts: 64,
869            max_buffers_per_context: 1_024,
870            max_programs_per_context: 64,
871            max_queues_per_context: 64,
872            max_events_per_context: 4_096,
873            max_bindings_per_submission: 256,
874            max_buffer_bytes: 16 * 1024 * 1024 * 1024,
875            max_artifact_bytes: MAX_TOSA_ARTIFACT_BYTES,
876        },
877    }
878}
879
880/// Create and load an amdxdna executable from a parsed precompiled artifact.
881fn build_executable(
882    device: &SharedDevice,
883    parsed: PrecompiledArtifact<'_>,
884    context_id: u64,
885    resources: &Arc<ResourceTracker>,
886) -> Result<XdnaProgram, BackendError> {
887    // Build the borrowed create-params (valid only for the duration of the create call).
888    let xclbin_span = ffi::hrx_const_byte_span_t {
889        data: parsed.xclbin.as_ptr().cast(),
890        data_length: parsed.xclbin.len(),
891    };
892    let run = ffi::hrx_amdxdna_executable_run_t {
893        record_length: size_of::<ffi::hrx_amdxdna_executable_run_t>() as u32,
894        abi_version: ffi::HRX_AMDXDNA_EXECUTABLE_RUN_ABI_VERSION_0,
895        transaction: ffi::hrx_const_byte_span_t {
896            data: parsed.insts.as_ptr().cast(),
897            data_length: parsed.insts.len(),
898        },
899        data_payload: ffi::hrx_const_byte_span_t {
900            data: ptr::null(),
901            data_length: 0,
902        },
903    };
904    let entry = ffi::hrx_amdxdna_executable_entry_point_t {
905        record_length: size_of::<ffi::hrx_amdxdna_executable_entry_point_t>() as u32,
906        abi_version: ffi::HRX_AMDXDNA_EXECUTABLE_ENTRY_POINT_ABI_VERSION_0,
907        name: ffi::hrx_string_view_t {
908            data: parsed.entry.as_ptr().cast(),
909            size: parsed.entry.len(),
910        },
911        context_mode: ffi::HRX_AMDXDNA_CONTEXT_MODE_CREATE,
912        xclbin_ordinal: 0,
913        pdi_ordinal: 0,
914        source_line: 0,
915        source_file: ffi::hrx_string_view_t {
916            data: ptr::null(),
917            size: 0,
918        },
919        runs: &run,
920        run_count: 1,
921    };
922    let params = ffi::hrx_amdxdna_executable_create_params_t {
923        record_length: size_of::<ffi::hrx_amdxdna_executable_create_params_t>() as u32,
924        abi_version: ffi::HRX_AMDXDNA_EXECUTABLE_CREATE_PARAMS_ABI_VERSION_0,
925        flags: 0,
926        reserved: 0,
927        xclbins: &xclbin_span,
928        xclbin_count: 1,
929        entry_points: &entry,
930        entry_point_count: 1,
931    };
932
933    let mut executable: ffi::hrx_executable_t = ptr::null_mut();
934    // SAFETY: the device is live; every span/record referenced by `params` is borrowed from
935    // `parsed`, which outlives this call; the out-pointer is a valid local; status consumed. HRX
936    // copies what it needs and the borrows may be released after return.
937    let status = unsafe {
938        (ffi::api().hrx_amdxdna_executable_create)(device.0.as_ptr(), &params, &mut executable)
939    };
940    check(status)?;
941    let executable = NonNull::new(executable).ok_or(BackendError::External {
942        domain: XDNA_ERROR_DOMAIN,
943        code: 0,
944    })?;
945
946    // Resolve the export ordinal by entry-point name.
947    let ordinal = CString::new(parsed.entry)
948        .map_err(|_| BackendError::InvalidArgument)
949        .and_then(|entry_c| {
950            let mut ordinal: u32 = 0;
951            // SAFETY: the executable is live; `entry_c` is a valid NUL-terminated string; the
952            // out-pointer is a valid local; status consumed.
953            let status = unsafe {
954                (ffi::api().hrx_executable_lookup_export_by_name)(
955                    executable.as_ptr(),
956                    entry_c.as_ptr(),
957                    &mut ordinal,
958                )
959            };
960            check(status).map(|()| ordinal)
961        });
962    let ordinal = match ordinal {
963        Ok(ordinal) => ordinal,
964        Err(error) => {
965            // SAFETY: the executable is live and owned here; release it before returning.
966            unsafe { (ffi::api().hrx_executable_release)(executable.as_ptr()) };
967            return Err(error);
968        }
969    };
970
971    resources.programs.fetch_add(1, Ordering::AcqRel);
972    Ok(XdnaProgram {
973        inner: Arc::new(ProgramInner {
974            executable,
975            ordinal,
976            inputs: parsed.inputs,
977            outputs: parsed.outputs,
978            slot_bytes: parsed.slot_bytes,
979            resources: Arc::clone(resources),
980        }),
981        context_id,
982    })
983}
984
985/// A logical execution context. HRX holds no per-context state; the id gives resources a home so
986/// cross-context admission can be rejected (queues, programs, and buffers carry their context id).
987#[derive(Debug)]
988pub struct XdnaContext {
989    id: u64,
990    resources: Arc<ResourceTracker>,
991}
992
993/// A logical execution queue funnelling into the instance's single stream lane.
994#[derive(Debug)]
995pub struct XdnaQueue {
996    context_id: u64,
997    resources: Arc<ResourceTracker>,
998}
999
1000/// A loaded, refcounted amdxdna executable and its dispatch plan.
1001#[derive(Debug)]
1002struct ProgramInner {
1003    executable: NonNull<ffi::hrx_executable_s>,
1004    ordinal: u32,
1005    inputs: usize,
1006    outputs: usize,
1007    /// Exact per-slot byte sizes (inputs `0..inputs`, then outputs). The compiled TXN stream DMAs
1008    /// these extents regardless of the bound range length, so submit must enforce an exact match.
1009    slot_bytes: Vec<u64>,
1010    resources: Arc<ResourceTracker>,
1011}
1012
1013// SAFETY: the executable is refcounted and used only by the worker under the stream mutex, plus
1014// released once on drop. Sharing the handle across threads (submit clones the `Arc` into a job) is
1015// sound because access is serialized on the worker.
1016unsafe impl Send for ProgramInner {}
1017unsafe impl Sync for ProgramInner {}
1018
1019impl Drop for ProgramInner {
1020    fn drop(&mut self) {
1021        // SAFETY: this is the last owner of the executable reference (the caller unloaded it and no
1022        // in-flight job still holds a clone); release drops exactly one reference.
1023        unsafe { (ffi::api().hrx_executable_release)(self.executable.as_ptr()) };
1024        ResourceTracker::decrement(&self.resources.programs);
1025    }
1026}
1027
1028/// A loaded program: a cheap handle over the shared program storage, tagged with its context.
1029#[derive(Debug)]
1030pub struct XdnaProgram {
1031    inner: Arc<ProgramInner>,
1032    context_id: u64,
1033}
1034
1035/// A submission event: a handle over one preallocated event slot.
1036#[derive(Debug)]
1037pub struct XdnaEvent {
1038    slot: Arc<EventSlot>,
1039    resources: Arc<ResourceTracker>,
1040}
1041
1042/// One owned HRX allocation and its persistent mapping.
1043#[derive(Debug)]
1044struct BufferInner {
1045    buffer: NonNull<ffi::hrx_buffer_s>,
1046    mapped: NonNull<u8>,
1047    len: usize,
1048    /// Set while the device may be reading or writing this buffer; guards host access and release.
1049    in_flight: AtomicU64,
1050    resources: Arc<ResourceTracker>,
1051}
1052
1053// SAFETY: the HRX allocation and persistent mapping are only accessed through XDNA's host-access
1054// API or by the serialized worker. The in-flight gate excludes those paths from overlapping, and
1055// the `Arc` keeps the allocation live until the worker has stopped touching it.
1056unsafe impl Send for BufferInner {}
1057unsafe impl Sync for BufferInner {}
1058
1059impl Drop for BufferInner {
1060    fn drop(&mut self) {
1061        // SAFETY: this is the last `Arc` owning one buffer reference. The persistent mapping is
1062        // released together with the buffer (the fork never unmaps first).
1063        unsafe { (ffi::api().hrx_buffer_release)(self.buffer.as_ptr()) };
1064        ResourceTracker::decrement(&self.resources.buffers);
1065    }
1066}
1067
1068/// An HRX buffer handle over a refcounted native allocation.
1069#[derive(Debug)]
1070pub struct XdnaBuffer {
1071    inner: Arc<BufferInner>,
1072    desc: BufferDesc,
1073    /// The context that allocated this buffer; a submission may only bind buffers from its own.
1074    context_id: u64,
1075    _not_send_sync: PhantomData<*mut u8>,
1076}
1077
1078impl XdnaBuffer {
1079    /// Byte range `[offset, offset+len)` checked against the mapping, returning `(start, end)`.
1080    fn checked_range(&self, offset: u64, len: usize) -> Result<(usize, usize), BackendError> {
1081        let start = usize::try_from(offset).map_err(|_| BackendError::OutOfBounds)?;
1082        let end = start
1083            .checked_add(len)
1084            .filter(|end| *end <= self.inner.len)
1085            .ok_or(BackendError::OutOfBounds)?;
1086        Ok((start, end))
1087    }
1088}
1089
1090impl Accelerator for XdnaAccelerator {
1091    type Context = XdnaContext;
1092    type Buffer = XdnaBuffer;
1093    type Program = XdnaProgram;
1094    type Queue = XdnaQueue;
1095    type Event = XdnaEvent;
1096
1097    fn device_info(&self) -> Result<DeviceInfo, BackendError> {
1098        Ok(self.info)
1099    }
1100
1101    fn create_context(&self, desc: ContextDesc) -> Result<Self::Context, BackendError> {
1102        self.info.validate_context_desc(desc)?;
1103        self.resources.contexts.fetch_add(1, Ordering::AcqRel);
1104        Ok(XdnaContext {
1105            id: self.next_id(),
1106            resources: Arc::clone(&self.resources),
1107        })
1108    }
1109
1110    fn destroy_context(&self, context: Self::Context) -> Result<(), ReleaseFailure<Self::Context>> {
1111        ResourceTracker::decrement(&context.resources.contexts);
1112        Ok(())
1113    }
1114
1115    fn allocate_buffer(
1116        &self,
1117        context: &Self::Context,
1118        desc: BufferDesc,
1119    ) -> Result<AllocatedBuffer<Self::Buffer>, BackendError> {
1120        self.info.validate_buffer_desc(desc)?;
1121        if self.lane.is_poisoned() {
1122            return Err(BackendError::DeviceLost);
1123        }
1124        if desc.domain == MemoryDomain::Device {
1125            return Err(BackendError::Unsupported);
1126        }
1127        let size = usize::try_from(desc.bytes()).map_err(|_| BackendError::OutOfMemory)?;
1128
1129        let mut buffer: ffi::hrx_buffer_t = ptr::null_mut();
1130        // SAFETY: the stream is live (held under the lane mutex); the out-pointer is a valid local;
1131        // the status is consumed. The lock serializes allocation against the worker's dispatch.
1132        let status = {
1133            let stream = self.lane.stream.lock().expect("stream mutex");
1134            unsafe {
1135                (ffi::api().hrx_buffer_allocate)(
1136                    stream.0.as_ptr(),
1137                    size,
1138                    ffi::HRX_MEMORY_TYPE_HOST_LOCAL | ffi::HRX_MEMORY_TYPE_DEVICE_VISIBLE,
1139                    ffi::HRX_BUFFER_USAGE_DEFAULT | ffi::HRX_BUFFER_USAGE_MAPPING_PERSISTENT,
1140                    &mut buffer,
1141                )
1142            }
1143        };
1144        check(status)?;
1145        let buffer = NonNull::new(buffer).ok_or(BackendError::External {
1146            domain: XDNA_ERROR_DOMAIN,
1147            code: 0,
1148        })?;
1149
1150        let mut mapped: *mut c_void = ptr::null_mut();
1151        // SAFETY: `buffer` is the just-allocated live buffer; the out-pointer is a valid local; the
1152        // status is consumed. Mapping does not touch the stream.
1153        let status = unsafe {
1154            (ffi::api().hrx_buffer_map_with_mode)(
1155                buffer.as_ptr(),
1156                ffi::HRX_MAPPING_MODE_PERSISTENT,
1157                ffi::HRX_MAP_READ | ffi::HRX_MAP_WRITE,
1158                0,
1159                size,
1160                &mut mapped,
1161            )
1162        };
1163        let mapped = match check(status).and_then(|()| {
1164            NonNull::new(mapped.cast::<u8>()).ok_or(BackendError::External {
1165                domain: XDNA_ERROR_DOMAIN,
1166                code: 0,
1167            })
1168        }) {
1169            Ok(mapped) => mapped,
1170            Err(error) => {
1171                // SAFETY: `buffer` is live and owned here; release its only reference on the error
1172                // path before the handle is discarded.
1173                unsafe { (ffi::api().hrx_buffer_release)(buffer.as_ptr()) };
1174                return Err(error);
1175            }
1176        };
1177
1178        let alignment = 1u64 << (mapped.as_ptr() as usize).trailing_zeros().min(63);
1179        let info = BufferInfo::new(
1180            desc,
1181            size as u64,
1182            alignment,
1183            BufferProperties::HOST_VISIBLE | BufferProperties::DIRECT_BINDING,
1184        )
1185        .inspect_err(|_| {
1186            // SAFETY: the buffer is live and owned; release its only reference before returning.
1187            unsafe { (ffi::api().hrx_buffer_release)(buffer.as_ptr()) };
1188        })?;
1189
1190        self.resources.buffers.fetch_add(1, Ordering::AcqRel);
1191        Ok(AllocatedBuffer::new(
1192            XdnaBuffer {
1193                inner: Arc::new(BufferInner {
1194                    buffer,
1195                    mapped,
1196                    len: size,
1197                    in_flight: AtomicU64::new(0),
1198                    resources: Arc::clone(&self.resources),
1199                }),
1200                desc,
1201                context_id: context.id,
1202                _not_send_sync: PhantomData,
1203            },
1204            info,
1205        ))
1206    }
1207
1208    fn write_buffer(
1209        &self,
1210        buffer: &mut Self::Buffer,
1211        offset: u64,
1212        data: &dyn ByteSource,
1213    ) -> Result<(), BackendError> {
1214        if !buffer
1215            .desc
1216            .usage
1217            .contains(BufferUsage::TRANSFER_DESTINATION)
1218        {
1219            return Err(BackendError::PermissionDenied);
1220        }
1221        if buffer.inner.in_flight.load(Ordering::Acquire) != 0 {
1222            return Err(BackendError::Busy);
1223        }
1224        let len = usize::try_from(data.len()).map_err(|_| BackendError::OutOfBounds)?;
1225        let (start, end) = buffer.checked_range(offset, len)?;
1226        // SAFETY: the mapping is valid for `buffer.len` bytes and `[start,end)` is within it; the
1227        // exclusive borrow and the in-flight gate rule out concurrent device or host access.
1228        let dst = unsafe {
1229            core::slice::from_raw_parts_mut(buffer.inner.mapped.as_ptr().add(start), len)
1230        };
1231        data.read_at(0, dst)?;
1232        // SAFETY: the buffer is live and currently mapped; the range is validated; status consumed.
1233        check(unsafe {
1234            (ffi::api().hrx_buffer_flush_range)(buffer.inner.buffer.as_ptr(), start, end - start)
1235        })?;
1236        // Count only completed transfers, so the diagnostics never include a failed write.
1237        self.explicit_transfer_bytes
1238            .fetch_add(len as u64, Ordering::Relaxed);
1239        Ok(())
1240    }
1241
1242    fn read_buffer(
1243        &self,
1244        buffer: &Self::Buffer,
1245        offset: u64,
1246        data: &mut dyn ByteSink,
1247    ) -> Result<(), BackendError> {
1248        if !buffer.desc.usage.contains(BufferUsage::TRANSFER_SOURCE) {
1249            return Err(BackendError::PermissionDenied);
1250        }
1251        if buffer.inner.in_flight.load(Ordering::Acquire) != 0 {
1252            return Err(BackendError::Busy);
1253        }
1254        let len = usize::try_from(data.len()).map_err(|_| BackendError::OutOfBounds)?;
1255        let (start, end) = buffer.checked_range(offset, len)?;
1256        // SAFETY: the buffer is live and currently mapped; the range is validated; status consumed.
1257        check(unsafe {
1258            (ffi::api().hrx_buffer_invalidate_range)(
1259                buffer.inner.buffer.as_ptr(),
1260                start,
1261                end - start,
1262            )
1263        })?;
1264        // SAFETY: the mapping is valid for `buffer.len` bytes and `[start,end)` is within it; the
1265        // shared borrow with the in-flight gate rules out concurrent device writes.
1266        let src =
1267            unsafe { core::slice::from_raw_parts(buffer.inner.mapped.as_ptr().add(start), len) };
1268        data.write_at(0, src)?;
1269        self.explicit_transfer_bytes
1270            .fetch_add(len as u64, Ordering::Relaxed);
1271        Ok(())
1272    }
1273
1274    fn free_buffer(&self, buffer: Self::Buffer) -> Result<(), ReleaseFailure<Self::Buffer>> {
1275        if buffer.inner.in_flight.load(Ordering::Acquire) != 0 {
1276            return Err(ReleaseFailure::Rejected {
1277                error: BackendError::Busy,
1278                resource: buffer,
1279            });
1280        }
1281        // The buffer's `Drop` releases the HRX handle (and its persistent mapping).
1282        drop(buffer);
1283        Ok(())
1284    }
1285
1286    fn load_program(
1287        &self,
1288        context: &Self::Context,
1289        artifact: ArtifactRef<'_>,
1290    ) -> Result<Self::Program, BackendError> {
1291        if self.lane.is_poisoned() {
1292            return Err(BackendError::DeviceLost);
1293        }
1294        if artifact.payload.len() > self.info.limits.max_artifact_bytes {
1295            return Err(BackendError::ResourceLimit);
1296        }
1297        // HRX publishes no finite residency bound for a loaded executable, so only the maximal
1298        // charge keeps the caller's program-residency accounting truthful (mirrors OpenVINO).
1299        if artifact.resident_bytes != crate::REQUIRED_RESIDENT_BYTES {
1300            return Err(BackendError::ResourceLimit);
1301        }
1302        let mut owned = Vec::new();
1303        let bytes = match artifact.payload.as_contiguous() {
1304            Some(bytes) => bytes,
1305            None => {
1306                let len = usize::try_from(artifact.payload.len())
1307                    .map_err(|_| BackendError::ResourceLimit)?;
1308                owned
1309                    .try_reserve_exact(len)
1310                    .map_err(|_| BackendError::OutOfMemory)?;
1311                owned.resize(len, 0);
1312                artifact.payload.read_at(0, &mut owned)?;
1313                &owned
1314            }
1315        };
1316
1317        // The precompiled format loads directly; a TOSA artifact is admitted and compiled to
1318        // one; an XBFP experiment container is envelope-validated and translated to one. Every
1319        // path funnels through the single audited executable-construction step below.
1320        let container = if artifact.format == artifact::XDNA_PRECOMPILED_FORMAT {
1321            std::borrow::Cow::Borrowed(bytes)
1322        } else if artifact.format == crate::bfp_experiment::XDNA_BFP_EXPERIMENT_FORMAT {
1323            // The experiment's numerical label is its own immutable identity; a load under any
1324            // other identity (including a TOSA target) is a relabeling attempt and is rejected.
1325            if artifact.target != crate::bfp_experiment::XDNA_BFP_EXPERIMENT_TARGET_IDENTITY {
1326                return Err(BackendError::Incompatible);
1327            }
1328            let parsed = crate::bfp_experiment::BfpExperimentArtifact::parse(bytes)?;
1329            std::borrow::Cow::Owned(parsed.to_precompiled_container())
1330        } else if artifact.format == virtio_accel_tosa::ARTIFACT_FORMAT {
1331            let target = virtio_accel_tosa::Target::from_identity(artifact.target)
1332                .map_err(|_| BackendError::Incompatible)?;
1333            let spec = lower::admit(bytes, target)?;
1334            let compiler = match &self.compiler {
1335                CompilerState::Ready(compiler) => compiler,
1336                CompilerState::Unconfigured => return Err(BackendError::Unsupported),
1337                CompilerState::Failed(error) => return Err(*error),
1338            };
1339            std::borrow::Cow::Owned(compiler.compile(spec)?)
1340        } else {
1341            return Err(BackendError::Unsupported);
1342        };
1343
1344        let parsed = PrecompiledArtifact::parse(container.as_ref())?;
1345        let device = shared_device().map_err(|_| BackendError::DeviceLost)?;
1346        build_executable(device, parsed, context.id, &self.resources)
1347    }
1348
1349    fn unload_program(&self, program: Self::Program) -> Result<(), ReleaseFailure<Self::Program>> {
1350        // Dropping the caller's `Arc` releases the executable once no in-flight job holds a clone.
1351        drop(program);
1352        Ok(())
1353    }
1354
1355    fn create_queue(
1356        &self,
1357        context: &Self::Context,
1358        desc: QueueDesc,
1359    ) -> Result<Self::Queue, BackendError> {
1360        self.info.validate_queue_desc(desc)?;
1361        self.resources.queues.fetch_add(1, Ordering::AcqRel);
1362        Ok(XdnaQueue {
1363            context_id: context.id,
1364            resources: Arc::clone(&self.resources),
1365        })
1366    }
1367
1368    fn destroy_queue(&self, queue: Self::Queue) -> Result<(), ReleaseFailure<Self::Queue>> {
1369        ResourceTracker::decrement(&queue.resources.queues);
1370        Ok(())
1371    }
1372
1373    fn submit(
1374        &self,
1375        queue: &Self::Queue,
1376        program: &Self::Program,
1377        bindings: &[BindingRef<'_, Self::Buffer>],
1378        timeout: Timeout,
1379    ) -> Result<Self::Event, SubmitFailure<Self::Event>> {
1380        let reject = |error| Err(SubmitFailure::Rejected(error));
1381
1382        if self.lane.is_poisoned() {
1383            return reject(BackendError::DeviceLost);
1384        }
1385        // No cancellation exists on this hardware, so a finite deadline cannot be honored once work
1386        // reaches the device; reject it before admission (issue #85).
1387        if matches!(timeout, Timeout::AfterNs(_)) {
1388            return reject(BackendError::DeadlineExpired);
1389        }
1390        // An empty or over-limit binding list is a resource-limit violation (mirrors OpenVINO).
1391        if bindings.is_empty()
1392            || bindings.len() > self.info.limits.max_bindings_per_submission as usize
1393        {
1394            return reject(BackendError::ResourceLimit);
1395        }
1396        // Cross-context admission is rejected: the queue, the program, and every bound buffer must
1397        // belong to one context.
1398        if queue.context_id != program.context_id {
1399            return reject(BackendError::InvalidArgument);
1400        }
1401
1402        let inputs = program.inner.inputs;
1403        let outputs = program.inner.outputs;
1404        let total = inputs + outputs;
1405        if bindings.len() != total {
1406            return reject(BackendError::InvalidArgument);
1407        }
1408
1409        // One pass over the caller's bindings, writing each into its slot-indexed position:
1410        // inputs occupy slots `0..inputs`, outputs `inputs..total`. A 256-bit occupancy mask
1411        // rejects duplicate slots; with `bindings.len() == total` that also proves full coverage.
1412        let mut refs: Vec<ffi::hrx_buffer_ref_t> = (0..total)
1413            .map(|_| ffi::hrx_buffer_ref_t {
1414                buffer: ptr::null_mut(),
1415                offset: 0,
1416                length: 0,
1417            })
1418            .collect();
1419        let mut output_ranges: Vec<(ffi::hrx_buffer_t, usize, usize)> = Vec::with_capacity(outputs);
1420        let mut retained: Vec<Arc<BufferInner>> = Vec::with_capacity(total);
1421        // (buffer handle, bound-for-write) pairs for the aliasing rule below.
1422        let mut bound: Vec<(ffi::hrx_buffer_t, bool)> = Vec::with_capacity(total);
1423        let mut occupied = [0u64; 4]; // total <= max_bindings_per_submission = 256
1424        for binding in bindings {
1425            let slot = binding.slot as usize;
1426            if slot >= total {
1427                return reject(BackendError::InvalidArgument);
1428            }
1429            let bit = 1u64 << (slot % 64);
1430            if occupied[slot / 64] & bit != 0 {
1431                return reject(BackendError::InvalidArgument);
1432            }
1433            occupied[slot / 64] |= bit;
1434            let is_output = slot >= inputs;
1435            let expected = if is_output {
1436                AccessMode::Write
1437            } else {
1438                AccessMode::Read
1439            };
1440            if binding.access != expected {
1441                // The access is incompatible with the program's slot plan (mirrors OpenVINO).
1442                return reject(BackendError::Incompatible);
1443            }
1444            let buffer = binding.buffer;
1445            if buffer.context_id != queue.context_id {
1446                return reject(BackendError::InvalidArgument);
1447            }
1448            // The host is required to enforce usage-vs-access before submit (Wire ABI 4.4); repeat
1449            // it as defense in depth for in-process consumers, exactly as OpenVINO does.
1450            if !buffer.desc.allows_access(binding.access) {
1451                return reject(BackendError::PermissionDenied);
1452            }
1453            let offset = usize::try_from(binding.range.offset).unwrap_or(usize::MAX);
1454            let length = usize::try_from(binding.range.bytes()).unwrap_or(usize::MAX);
1455            if buffer.checked_range(binding.range.offset, length).is_err() {
1456                return reject(BackendError::OutOfBounds);
1457            }
1458            // The compiled TXN stream DMAs the slot's exact tensor extent regardless of the bound
1459            // length, so anything but an exact match would read or write past the caller's declared
1460            // range (mirrors OpenVINO's per-slot byte_len check).
1461            if binding.range.bytes() != program.inner.slot_bytes[slot] {
1462                return reject(BackendError::Incompatible);
1463            }
1464            // The descriptor starts at `offset`, so an unaligned start would ask the DMA for a
1465            // sub-word transfer it cannot express.
1466            if binding.range.offset % DMA_WORD_BYTES != 0 {
1467                return reject(BackendError::Incompatible);
1468            }
1469            // Aliasing rule: binding one buffer to several read slots is sound (the kernel only
1470            // loads from it; OpenVINO admits the same). Any alias involving a write slot has
1471            // kernel-order-dependent results and is rejected.
1472            let handle = buffer.inner.buffer.as_ptr();
1473            let mut already_retained = false;
1474            for &(other, other_writes) in &bound {
1475                if core::ptr::eq(other, handle) {
1476                    if is_output || other_writes {
1477                        return reject(BackendError::InvalidArgument);
1478                    }
1479                    already_retained = true;
1480                }
1481            }
1482            bound.push((handle, is_output));
1483            refs[slot] = ffi::hrx_buffer_ref_t {
1484                buffer: handle,
1485                offset,
1486                length,
1487            };
1488            if !already_retained {
1489                retained.push(Arc::clone(&buffer.inner));
1490            }
1491            if is_output {
1492                output_ranges.push((handle, offset, length));
1493            }
1494        }
1495
1496        // Acceptance boundary: claim a ring entry and an event slot, then arm the in-flight gates.
1497        let slot = {
1498            let mut ring = self.lane.ring.lock().expect("ring mutex");
1499            if ring.queue.len() + ring.dispatched >= self.lane.depth {
1500                return reject(BackendError::Busy);
1501            }
1502            let Some(slot) = self.claim_slot() else {
1503                return reject(BackendError::Busy);
1504            };
1505            for (armed, buffer) in retained.iter().enumerate() {
1506                if buffer
1507                    .in_flight
1508                    .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire)
1509                    .is_err()
1510                {
1511                    for prior in &retained[..armed] {
1512                        prior.in_flight.store(0, Ordering::Release);
1513                    }
1514                    slot.state.store(slot_state::FREE, Ordering::Release);
1515                    return reject(BackendError::Busy);
1516                }
1517            }
1518            self.resources.events.fetch_add(1, Ordering::AcqRel);
1519            ring.queue.push_back(Job {
1520                program: Arc::clone(&program.inner),
1521                bindings: refs,
1522                outputs: output_ranges,
1523                buffers: retained,
1524                slot: Arc::clone(&slot),
1525            });
1526            slot
1527        };
1528        self.lane.signal.notify_one();
1529        // Every binding was bound directly (persistent device-visible mapping, no bounce buffer).
1530        self.direct_binding_admissions
1531            .fetch_add(total as u64, Ordering::Relaxed);
1532        Ok(XdnaEvent {
1533            slot,
1534            resources: Arc::clone(&self.resources),
1535        })
1536    }
1537
1538    fn poll_event(&self, event: &Self::Event) -> Result<EventState, BackendError> {
1539        match event.slot.state.load(Ordering::Acquire) {
1540            slot_state::PENDING => {
1541                if self.lane.is_poisoned() {
1542                    // A tier-2 wedge has no trustworthy terminal boundary. Keep the event pending
1543                    // internally while reporting device loss at the polling API.
1544                    Err(BackendError::DeviceLost)
1545                } else {
1546                    Ok(EventState::Pending)
1547                }
1548            }
1549            slot_state::COMPLETE => Ok(EventState::Complete),
1550            slot_state::FAILED => {
1551                let error = event
1552                    .slot
1553                    .error
1554                    .lock()
1555                    .expect("event error mutex")
1556                    .unwrap_or(BackendError::External {
1557                        domain: XDNA_ERROR_DOMAIN,
1558                        code: 0,
1559                    });
1560                Ok(EventState::Failed(error))
1561            }
1562            _ => Err(BackendError::External {
1563                domain: XDNA_ERROR_DOMAIN,
1564                code: INVALID_EVENT_STATE_CODE,
1565            }),
1566        }
1567    }
1568
1569    fn destroy_event(&self, event: Self::Event) -> Result<(), ReleaseFailure<Self::Event>> {
1570        // A pending event cannot be destroyed (the worker still writes its slot and gates).
1571        if event.slot.state.load(Ordering::Acquire) == slot_state::PENDING {
1572            return Err(ReleaseFailure::Rejected {
1573                error: BackendError::Busy,
1574                resource: event,
1575            });
1576        }
1577        // Dropping reclaims the slot, so this is the single reclaim path: an event that is merely
1578        // dropped instead of destroyed cannot strand its ring entry.
1579        drop(event);
1580        Ok(())
1581    }
1582}
1583
1584impl Drop for XdnaEvent {
1585    /// Reclaim the ring slot. `destroy_event` is the intended release path, but a
1586    /// dropped-instead-of-destroyed event would strand its slot; enough of them exhaust the ring
1587    /// and fail every later submission with `Busy` for the life of the instance.
1588    ///
1589    /// Only a terminal slot is reclaimed. A `PENDING` slot still belongs to the dispatch worker,
1590    /// which will latch it; freeing it here would hand a live slot to the next submission. Such a
1591    /// slot stays charged to `resource_counts`, which is exactly where a wedged lane's event
1592    /// belongs. The error detail is cleared before `FREE` is published, so a later claimer of this
1593    /// slot can never observe the previous submission's failure.
1594    fn drop(&mut self) {
1595        let state = self.slot.state.load(Ordering::Acquire);
1596        if state != slot_state::COMPLETE && state != slot_state::FAILED {
1597            return;
1598        }
1599        *self.slot.error.lock().expect("event error mutex") = None;
1600        self.slot.state.store(slot_state::FREE, Ordering::Release);
1601        ResourceTracker::decrement(&self.resources.events);
1602    }
1603}