Skip to main content

virtio_accel_core/
lib.rs

1//! Transport-independent accelerator semantics.
2//!
3//! This crate does not name virtqueues, guest memory, host operating systems, or vendor APIs.
4//! Transport adapters validate untrusted input and translate it into these typed contracts.
5
6#![no_std]
7#![forbid(unsafe_code)]
8
9use bitflags::bitflags;
10use core::fmt;
11use core::num::{NonZeroU32, NonZeroU64};
12use virtio_accel_transport::{ByteAccessError, ReadableBytes, WritableBytes};
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum BackendError {
16    Unsupported,
17    Incompatible,
18    InvalidArgument,
19    OutOfBounds,
20    Busy,
21    OutOfMemory,
22    ResourceLimit,
23    DeadlineExpired,
24    DeviceLost,
25    PermissionDenied,
26    /// Stable provider-owned error namespace. Transport adapters must not reinterpret it.
27    External {
28        domain: u32,
29        code: i64,
30    },
31}
32
33impl fmt::Display for BackendError {
34    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
35        write!(formatter, "{self:?}")
36    }
37}
38
39/// Extensible accelerator class. Unknown values remain representable across newer implementations.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41#[repr(transparent)]
42pub struct AcceleratorClass(u16);
43
44impl AcceleratorClass {
45    pub const OTHER: Self = Self(0);
46    pub const NPU: Self = Self(1);
47    pub const GPU: Self = Self(2);
48    pub const DSP: Self = Self(3);
49
50    pub const fn new(value: u16) -> Self {
51        Self(value)
52    }
53
54    pub const fn get(self) -> u16 {
55        self.0
56    }
57}
58
59bitflags! {
60    /// Semantic capabilities exposed by a backend, independent of virtio feature negotiation.
61    ///
62    /// Capabilities describe which accelerator operations the backend can perform. They do not
63    /// change the wire layout. A transport feature bit is required separately whenever enabling a
64    /// capability would change descriptor framing or any other device/driver protocol behavior.
65    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
66    pub struct Capabilities: u64 {
67        /// Supports [`MemoryDomain::Host`] allocations.
68        const HOST_VISIBLE_MEMORY = 1 << 0;
69        /// Supports [`MemoryDomain::Device`] allocations.
70        const DEVICE_LOCAL_MEMORY = 1 << 1;
71        /// [`Accelerator::cancel_event`] is implemented for pending events.
72        const EVENT_CANCELLATION = 1 << 2;
73        /// Reserved for post-v1 external-allocation import/export semantics.
74        const EXTERNAL_MEMORY = 1 << 3;
75        /// Reserved until secure-context isolation requirements are specified.
76        const SECURE_CONTEXTS = 1 << 4;
77        /// Supports provider-owned [`MemoryDomain::Shared`] allocations.
78        const SHARED_MEMORY = 1 << 5;
79
80        /// Capabilities that make at least one provider-owned memory domain usable.
81        const MEMORY_DOMAINS = Self::HOST_VISIBLE_MEMORY.bits()
82            | Self::DEVICE_LOCAL_MEMORY.bits()
83            | Self::SHARED_MEMORY.bits();
84        /// Assigned bits whose semantics remain reserved by this version of the contract.
85        const RESERVED = Self::EXTERNAL_MEMORY.bits() | Self::SECURE_CONTEXTS.bits();
86    }
87}
88
89impl Capabilities {
90    /// Whether the backend can allocate the requested provider-owned memory domain.
91    pub const fn supports_memory_domain(self, domain: MemoryDomain) -> bool {
92        match domain {
93            MemoryDomain::Host => self.contains(Self::HOST_VISIBLE_MEMORY),
94            MemoryDomain::Device => self.contains(Self::DEVICE_LOCAL_MEMORY),
95            MemoryDomain::Shared => self.contains(Self::SHARED_MEMORY),
96        }
97    }
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub struct DeviceIdentity {
102    pub uuid: [u8; 16],
103    pub class: AcceleratorClass,
104    pub vendor_id: u32,
105    pub device_id: u32,
106}
107
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub struct DeviceLimits {
110    pub max_contexts: u32,
111    pub max_buffers_per_context: u32,
112    pub max_programs_per_context: u32,
113    pub max_queues_per_context: u32,
114    pub max_events_per_context: u32,
115    pub max_bindings_per_submission: u32,
116    pub max_buffer_bytes: u64,
117    pub max_artifact_bytes: u64,
118}
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub struct DeviceInfo {
122    pub identity: DeviceIdentity,
123    pub capabilities: Capabilities,
124    pub limits: DeviceLimits,
125}
126
127/// Invalid provider metadata discovered before any resource operation is invoked.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum DeviceInfoError {
130    /// A capability whose semantics are still reserved was advertised.
131    ReservedCapabilities,
132    /// No provider-owned memory domain can be allocated.
133    MissingMemoryDomain,
134    /// A mandatory resource or byte limit is zero.
135    ZeroLimit,
136}
137
138bitflags! {
139    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
140    pub struct ContextFlags: u32 {
141        /// Reserved until secure-context isolation and transport semantics are specified.
142        const SECURE = 1 << 0;
143    }
144}
145
146#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
147pub struct ContextDesc {
148    pub flags: ContextFlags,
149}
150
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152#[repr(u8)]
153pub enum MemoryDomain {
154    /// Provider memory optimized for host transfers.
155    ///
156    /// If the usage includes program access, the returned allocation is still directly bindable;
157    /// this value never permits per-submission staging.
158    Host = 1,
159    /// Provider memory optimized for accelerator access.
160    ///
161    /// Explicit read/write transfers may stage through provider-owned temporary memory.
162    Device = 2,
163    /// One provider-owned allocation that is host visible and directly accelerator bindable.
164    ///
165    /// This does not imply cross-process export, guest-memory import, cache coherence, or any
166    /// platform external-memory handle.
167    Shared = 3,
168}
169
170impl TryFrom<u8> for MemoryDomain {
171    type Error = BackendError;
172
173    fn try_from(value: u8) -> Result<Self, Self::Error> {
174        match value {
175            1 => Ok(Self::Host),
176            2 => Ok(Self::Device),
177            3 => Ok(Self::Shared),
178            _ => Err(BackendError::InvalidArgument),
179        }
180    }
181}
182
183bitflags! {
184    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
185    pub struct BufferUsage: u32 {
186        /// The buffer may be the source of an explicit [`Accelerator::read_buffer`] transfer.
187        const TRANSFER_SOURCE = 1 << 0;
188        /// The buffer may be the destination of an explicit [`Accelerator::write_buffer`] transfer.
189        const TRANSFER_DESTINATION = 1 << 1;
190        const PROGRAM_INPUT = 1 << 2;
191        const PROGRAM_OUTPUT = 1 << 3;
192        const MUTABLE_STATE = 1 << 4;
193    }
194}
195
196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
197pub struct BufferDesc {
198    bytes: NonZeroU64,
199    alignment: NonZeroU64,
200    pub domain: MemoryDomain,
201    pub usage: BufferUsage,
202}
203
204impl BufferDesc {
205    pub fn new(
206        bytes: u64,
207        alignment: u64,
208        domain: MemoryDomain,
209        usage: BufferUsage,
210    ) -> Result<Self, BackendError> {
211        let bytes = NonZeroU64::new(bytes).ok_or(BackendError::InvalidArgument)?;
212        let alignment = NonZeroU64::new(alignment).ok_or(BackendError::InvalidArgument)?;
213        if !alignment.is_power_of_two() || usage.is_empty() || !BufferUsage::all().contains(usage) {
214            return Err(BackendError::InvalidArgument);
215        }
216        Ok(Self {
217            bytes,
218            alignment,
219            domain,
220            usage,
221        })
222    }
223
224    pub const fn bytes(self) -> u64 {
225        self.bytes.get()
226    }
227
228    pub const fn alignment(self) -> u64 {
229        self.alignment.get()
230    }
231
232    /// Whether this declaration permits one program binding access mode.
233    pub const fn allows_access(self, access: AccessMode) -> bool {
234        match access {
235            AccessMode::Read => self
236                .usage
237                .intersects(BufferUsage::PROGRAM_INPUT.union(BufferUsage::MUTABLE_STATE)),
238            AccessMode::Write => self
239                .usage
240                .intersects(BufferUsage::PROGRAM_OUTPUT.union(BufferUsage::MUTABLE_STATE)),
241            AccessMode::ReadWrite => self.usage.contains(BufferUsage::MUTABLE_STATE),
242        }
243    }
244
245    /// Whether this allocation can appear in a program binding.
246    pub const fn is_program_visible(self) -> bool {
247        self.usage.intersects(
248            BufferUsage::PROGRAM_INPUT
249                .union(BufferUsage::PROGRAM_OUTPUT)
250                .union(BufferUsage::MUTABLE_STATE),
251        )
252    }
253}
254
255bitflags! {
256    /// Properties of the actual provider allocation returned for a [`BufferDesc`].
257    ///
258    /// These properties describe the backing allocation, not an aspirational fast path. A backend
259    /// must reject allocation rather than advertise a property that it can satisfy only by
260    /// allocating and copying a full-size bounce buffer during submission.
261    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
262    pub struct BufferProperties: u32 {
263        /// The provider can access the allocation through a host mapping.
264        const HOST_VISIBLE = 1 << 0;
265        /// The allocation uses the provider's accelerator-local placement class.
266        const DEVICE_LOCAL = 1 << 1;
267        /// Compatible program submissions bind this exact allocation without copying the bound
268        /// byte range into or out of a different allocation.
269        const DIRECT_BINDING = 1 << 2;
270    }
271}
272
273/// Verified properties of one provider allocation.
274#[derive(Clone, Copy, Debug, PartialEq, Eq)]
275pub struct BufferInfo {
276    desc: BufferDesc,
277    allocation_bytes: NonZeroU64,
278    alignment: NonZeroU64,
279    properties: BufferProperties,
280}
281
282impl BufferInfo {
283    /// Validate that actual allocation properties honestly satisfy the requested descriptor.
284    pub fn new(
285        desc: BufferDesc,
286        allocation_bytes: u64,
287        alignment: u64,
288        properties: BufferProperties,
289    ) -> Result<Self, BackendError> {
290        let allocation_bytes =
291            NonZeroU64::new(allocation_bytes).ok_or(BackendError::InvalidArgument)?;
292        let alignment = NonZeroU64::new(alignment).ok_or(BackendError::InvalidArgument)?;
293        if !BufferProperties::all().contains(properties) {
294            return Err(BackendError::InvalidArgument);
295        }
296        if allocation_bytes.get() < desc.bytes()
297            || !alignment.is_power_of_two()
298            || alignment.get() < desc.alignment()
299        {
300            return Err(BackendError::Incompatible);
301        }
302
303        let required = match desc.domain {
304            MemoryDomain::Host => BufferProperties::HOST_VISIBLE,
305            MemoryDomain::Device => BufferProperties::DEVICE_LOCAL,
306            MemoryDomain::Shared => {
307                BufferProperties::HOST_VISIBLE.union(BufferProperties::DIRECT_BINDING)
308            }
309        };
310        if !properties.contains(required)
311            || (desc.is_program_visible() && !properties.contains(BufferProperties::DIRECT_BINDING))
312        {
313            return Err(BackendError::Incompatible);
314        }
315
316        Ok(Self {
317            desc,
318            allocation_bytes,
319            alignment,
320            properties,
321        })
322    }
323
324    pub const fn desc(self) -> BufferDesc {
325        self.desc
326    }
327
328    /// Physical/provider backing bytes retained for this logical buffer.
329    pub const fn allocation_bytes(self) -> u64 {
330        self.allocation_bytes.get()
331    }
332
333    /// Alignment guaranteed by the actual provider allocation.
334    pub const fn alignment(self) -> u64 {
335        self.alignment.get()
336    }
337
338    pub const fn properties(self) -> BufferProperties {
339        self.properties
340    }
341}
342
343impl DeviceInfo {
344    /// Validate immutable provider metadata once, before constructing live object state.
345    ///
346    /// Unknown capability bits remain representable for forward-compatible diagnostics. Assigned
347    /// reserved bits are rejected because this version cannot enforce their ownership and
348    /// synchronization rules.
349    pub const fn validate(self) -> Result<(), DeviceInfoError> {
350        if self.capabilities.intersects(Capabilities::RESERVED) {
351            return Err(DeviceInfoError::ReservedCapabilities);
352        }
353        if !self.capabilities.intersects(Capabilities::MEMORY_DOMAINS) {
354            return Err(DeviceInfoError::MissingMemoryDomain);
355        }
356        if self.limits.max_contexts == 0
357            || self.limits.max_buffers_per_context == 0
358            || self.limits.max_programs_per_context == 0
359            || self.limits.max_queues_per_context == 0
360            || self.limits.max_events_per_context == 0
361            || self.limits.max_bindings_per_submission == 0
362            || self.limits.max_buffer_bytes == 0
363            || self.limits.max_artifact_bytes == 0
364        {
365            return Err(DeviceInfoError::ZeroLimit);
366        }
367        Ok(())
368    }
369
370    /// Validate context intent before backend invocation.
371    ///
372    /// This contract currently reserves every nonempty context flag set.
373    pub fn validate_context_desc(self, desc: ContextDesc) -> Result<(), BackendError> {
374        if desc.flags.is_empty() {
375            Ok(())
376        } else {
377            Err(BackendError::Unsupported)
378        }
379    }
380
381    /// Validate allocation size and memory-domain support before backend invocation.
382    pub fn validate_buffer_desc(self, desc: BufferDesc) -> Result<(), BackendError> {
383        if desc.bytes() > self.limits.max_buffer_bytes {
384            return Err(BackendError::ResourceLimit);
385        }
386        if !self.capabilities.supports_memory_domain(desc.domain) {
387            return Err(BackendError::Unsupported);
388        }
389        Ok(())
390    }
391
392    /// Validate that a backend allocation describes the request it was asked to satisfy.
393    pub fn validate_buffer_info(
394        self,
395        requested: BufferDesc,
396        actual: BufferInfo,
397    ) -> Result<(), BackendError> {
398        self.validate_buffer_desc(requested)?;
399        if actual.desc() != requested {
400            return Err(BackendError::Incompatible);
401        }
402        Ok(())
403    }
404
405    /// Validate execution-queue intent before backend invocation.
406    ///
407    /// This contract currently reserves every nonempty execution-queue flag set.
408    pub fn validate_queue_desc(self, desc: QueueDesc) -> Result<(), BackendError> {
409        if desc.flags.is_empty() {
410            Ok(())
411        } else {
412            Err(BackendError::Unsupported)
413        }
414    }
415
416    /// Validate event-cancellation support before backend invocation.
417    pub fn validate_event_cancellation(self) -> Result<(), BackendError> {
418        if self.capabilities.contains(Capabilities::EVENT_CANCELLATION) {
419            Ok(())
420        } else {
421            Err(BackendError::Unsupported)
422        }
423    }
424}
425
426/// A newly allocated native buffer handle and its verified backing properties.
427///
428/// Device implementations should retain `info` in their object record and pass only `buffer` to
429/// backend hot paths.
430#[derive(Debug)]
431pub struct AllocatedBuffer<B> {
432    buffer: B,
433    info: BufferInfo,
434}
435
436impl<B> AllocatedBuffer<B> {
437    pub const fn new(buffer: B, info: BufferInfo) -> Self {
438        Self { buffer, info }
439    }
440
441    pub const fn buffer(&self) -> &B {
442        &self.buffer
443    }
444
445    pub fn buffer_mut(&mut self) -> &mut B {
446        &mut self.buffer
447    }
448
449    pub const fn info(&self) -> BufferInfo {
450        self.info
451    }
452
453    pub fn into_parts(self) -> (B, BufferInfo) {
454        (self.buffer, self.info)
455    }
456}
457
458#[derive(Clone, Copy, Debug, PartialEq, Eq)]
459pub struct BufferRange {
460    pub offset: u64,
461    bytes: NonZeroU64,
462}
463
464impl BufferRange {
465    pub fn new(offset: u64, bytes: u64) -> Result<Self, BackendError> {
466        let bytes = NonZeroU64::new(bytes).ok_or(BackendError::InvalidArgument)?;
467        offset
468            .checked_add(bytes.get())
469            .ok_or(BackendError::OutOfBounds)?;
470        Ok(Self { offset, bytes })
471    }
472
473    pub const fn bytes(self) -> u64 {
474        self.bytes.get()
475    }
476
477    pub const fn end(self) -> u64 {
478        self.offset + self.bytes.get()
479    }
480}
481
482#[derive(Clone, Copy, Debug, PartialEq, Eq)]
483#[repr(u8)]
484pub enum AccessMode {
485    Read = 1,
486    Write = 2,
487    ReadWrite = 3,
488}
489
490impl TryFrom<u8> for AccessMode {
491    type Error = BackendError;
492
493    fn try_from(value: u8) -> Result<Self, Self::Error> {
494        match value {
495            1 => Ok(Self::Read),
496            2 => Ok(Self::Write),
497            3 => Ok(Self::ReadWrite),
498            _ => Err(BackendError::InvalidArgument),
499        }
500    }
501}
502
503/// A bounded byte source that may be physically segmented.
504///
505/// Transport adapters can implement this trait over validated descriptor-backed regions so
506/// providers can read directly into final program or buffer storage without first coalescing the
507/// complete payload. Every range fully contained in `0..len()` must be readable for the duration of
508/// the backend call. The optional contiguous view preserves the single-slice fast path.
509pub trait ByteSource: fmt::Debug {
510    /// Stable logical length of this source.
511    fn len(&self) -> u64;
512
513    fn is_empty(&self) -> bool {
514        self.len() == 0
515    }
516
517    /// Fill `target` from the exact logical range beginning at `offset`.
518    fn read_at(&self, offset: u64, target: &mut [u8]) -> Result<(), BackendError>;
519
520    /// Borrow the complete logical source when it is one contiguous region.
521    ///
522    /// A returned slice has length [`Self::len`] and contains the same bytes as `read_at`.
523    fn as_contiguous(&self) -> Option<&[u8]> {
524        None
525    }
526}
527
528/// Zero-copy core byte-source adapter over a transport-owned readable port.
529#[derive(Debug)]
530pub struct TransportByteSource<'a, T: ?Sized>(&'a T);
531
532impl<'a, T: ?Sized> TransportByteSource<'a, T> {
533    /// Borrow a transport-readable port without copying or coalescing its bytes.
534    pub const fn new(source: &'a T) -> Self {
535        Self(source)
536    }
537
538    /// Recover the wrapped transport port.
539    pub const fn into_inner(self) -> &'a T {
540        self.0
541    }
542}
543
544impl<T: ReadableBytes + ?Sized> ByteSource for TransportByteSource<'_, T> {
545    fn len(&self) -> u64 {
546        ReadableBytes::len(self.0)
547    }
548
549    fn read_at(&self, offset: u64, target: &mut [u8]) -> Result<(), BackendError> {
550        ReadableBytes::read_at(self.0, offset, target).map_err(backend_error_from_byte_access)
551    }
552
553    fn as_contiguous(&self) -> Option<&[u8]> {
554        ReadableBytes::as_contiguous(self.0)
555    }
556}
557
558impl ByteSource for [u8] {
559    fn len(&self) -> u64 {
560        self.len() as u64
561    }
562
563    fn read_at(&self, offset: u64, target: &mut [u8]) -> Result<(), BackendError> {
564        let start = usize::try_from(offset).map_err(|_| BackendError::OutOfBounds)?;
565        let end = start
566            .checked_add(target.len())
567            .filter(|end| *end <= self.len())
568            .ok_or(BackendError::OutOfBounds)?;
569        target.copy_from_slice(&self[start..end]);
570        Ok(())
571    }
572
573    fn as_contiguous(&self) -> Option<&[u8]> {
574        Some(self)
575    }
576}
577
578impl<const N: usize> ByteSource for [u8; N] {
579    fn len(&self) -> u64 {
580        N as u64
581    }
582
583    fn read_at(&self, offset: u64, target: &mut [u8]) -> Result<(), BackendError> {
584        ByteSource::read_at(self.as_slice(), offset, target)
585    }
586
587    fn as_contiguous(&self) -> Option<&[u8]> {
588        Some(self)
589    }
590}
591
592/// A bounded byte destination that may be physically segmented.
593///
594/// Providers can write buffer contents directly into validated response regions. The optional
595/// contiguous view avoids callback overhead when the destination is already one slice. Every range
596/// fully contained in `0..len()` must be writable for the duration of the backend call.
597pub trait ByteSink: fmt::Debug {
598    /// Stable logical length of this destination.
599    fn len(&self) -> u64;
600
601    fn is_empty(&self) -> bool {
602        self.len() == 0
603    }
604
605    /// Write `source` to the exact logical range beginning at `offset`.
606    fn write_at(&mut self, offset: u64, source: &[u8]) -> Result<(), BackendError>;
607
608    /// Mutably borrow the complete logical destination when it is one contiguous region.
609    ///
610    /// A returned slice has length [`Self::len`] and represents the same bytes as `write_at`.
611    fn as_contiguous_mut(&mut self) -> Option<&mut [u8]> {
612        None
613    }
614}
615
616/// Zero-copy core byte-sink adapter over a transport-owned writable port.
617#[derive(Debug)]
618pub struct TransportByteSink<'a, T: ?Sized>(&'a mut T);
619
620impl<'a, T: ?Sized> TransportByteSink<'a, T> {
621    /// Borrow a transport-writable port without copying or coalescing its bytes.
622    pub const fn new(sink: &'a mut T) -> Self {
623        Self(sink)
624    }
625
626    /// Recover the wrapped transport port.
627    pub fn into_inner(self) -> &'a mut T {
628        self.0
629    }
630}
631
632impl<T: WritableBytes + ?Sized> ByteSink for TransportByteSink<'_, T> {
633    fn len(&self) -> u64 {
634        WritableBytes::len(self.0)
635    }
636
637    fn write_at(&mut self, offset: u64, source: &[u8]) -> Result<(), BackendError> {
638        WritableBytes::write_at(self.0, offset, source).map_err(backend_error_from_byte_access)
639    }
640
641    fn as_contiguous_mut(&mut self) -> Option<&mut [u8]> {
642        WritableBytes::as_contiguous_mut(self.0)
643    }
644}
645
646const fn backend_error_from_byte_access(error: ByteAccessError) -> BackendError {
647    match error {
648        ByteAccessError::OutOfBounds => BackendError::OutOfBounds,
649        ByteAccessError::Busy | ByteAccessError::Reset => BackendError::Busy,
650        ByteAccessError::Access => BackendError::DeviceLost,
651    }
652}
653
654impl ByteSink for [u8] {
655    fn len(&self) -> u64 {
656        self.len() as u64
657    }
658
659    fn write_at(&mut self, offset: u64, source: &[u8]) -> Result<(), BackendError> {
660        let start = usize::try_from(offset).map_err(|_| BackendError::OutOfBounds)?;
661        let end = start
662            .checked_add(source.len())
663            .filter(|end| *end <= self.len())
664            .ok_or(BackendError::OutOfBounds)?;
665        self[start..end].copy_from_slice(source);
666        Ok(())
667    }
668
669    fn as_contiguous_mut(&mut self) -> Option<&mut [u8]> {
670        Some(self)
671    }
672}
673
674impl<const N: usize> ByteSink for [u8; N] {
675    fn len(&self) -> u64 {
676        N as u64
677    }
678
679    fn write_at(&mut self, offset: u64, source: &[u8]) -> Result<(), BackendError> {
680        ByteSink::write_at(self.as_mut_slice(), offset, source)
681    }
682
683    fn as_contiguous_mut(&mut self) -> Option<&mut [u8]> {
684        Some(self)
685    }
686}
687
688/// Opaque, provider-owned executable format identifier.
689#[derive(Clone, Copy, Debug, PartialEq, Eq)]
690#[repr(transparent)]
691pub struct ArtifactFormat(NonZeroU32);
692
693impl ArtifactFormat {
694    pub const fn new(value: u32) -> Option<Self> {
695        match NonZeroU32::new(value) {
696            Some(value) => Some(Self(value)),
697            None => None,
698        }
699    }
700
701    pub const fn get(self) -> u32 {
702        self.0.get()
703    }
704}
705
706/// Opaque target words. Their schema belongs to the artifact format, not this crate.
707#[derive(Clone, Copy, Debug, PartialEq, Eq)]
708#[repr(transparent)]
709pub struct TargetIdentity(pub [u32; 12]);
710
711/// Borrowed program artifact envelope.
712///
713/// Payload bytes may be segmented; providers should stream them into final resident storage or use
714/// [`ByteSource::as_contiguous`] when a borrowed slice is available. `resident_bytes` is the
715/// caller-authorized upper bound for all provider storage retained by the returned program; a
716/// provider must reject the artifact if it cannot stay within that charge.
717#[derive(Clone, Copy, Debug)]
718pub struct ArtifactRef<'a> {
719    pub format: ArtifactFormat,
720    pub target: TargetIdentity,
721    pub payload: &'a dyn ByteSource,
722    pub resident_bytes: u64,
723}
724
725bitflags! {
726    /// Flags for an accelerator execution queue.
727    ///
728    /// This queue is a backend object used to submit programs. It is not a virtqueue; the v1
729    /// protocol uses the term *command virtqueue* for the transport queue carrying requests.
730    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
731    pub struct QueueFlags: u32 {
732        /// Reserved until ordering behavior and capability negotiation are specified.
733        const IN_ORDER = 1 << 0;
734    }
735}
736
737#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
738pub struct QueueDesc {
739    pub flags: QueueFlags,
740}
741
742/// A relative timeout measured from backend admission. Zero on the wire means infinite.
743#[derive(Clone, Copy, Debug, PartialEq, Eq)]
744pub enum Timeout {
745    Infinite,
746    AfterNs(NonZeroU64),
747}
748
749impl Timeout {
750    pub const fn from_wire_ns(value: u64) -> Self {
751        match NonZeroU64::new(value) {
752            Some(value) => Self::AfterNs(value),
753            None => Self::Infinite,
754        }
755    }
756
757    pub const fn to_wire_ns(self) -> u64 {
758        match self {
759            Self::Infinite => 0,
760            Self::AfterNs(value) => value.get(),
761        }
762    }
763}
764
765/// One borrowed program binding. The referenced buffer must remain alive until its event is
766/// reclaimed.
767///
768/// Program-visible buffers carry [`BufferProperties::DIRECT_BINDING`]. A backend must reject an
769/// incompatible buffer/program combination instead of copying the range into a hidden bounce
770/// allocation. Binding order is not semantic; command engines may present the slice in slot order.
771///
772/// Before [`Accelerator::submit`], hosts must reject an [`AccessMode`] incompatible with the
773/// buffer's declared [`BufferUsage`] (see [`Self::validate_for_submit`]).
774#[derive(Debug)]
775pub struct BindingRef<'a, B> {
776    pub slot: u32,
777    pub buffer: &'a B,
778    pub range: BufferRange,
779    pub access: AccessMode,
780}
781
782impl<'a, B> BindingRef<'a, B> {
783    /// Slot/count checks plus [`BufferDesc::allows_access`] for each binding.
784    ///
785    /// Hosts must enforce both checks before [`Accelerator::submit`]. This combined
786    /// helper is suitable when descriptors are already available as a slice. A host
787    /// resolving descriptors individually may call [`validate_bindings`] once and
788    /// [`BufferDesc::allows_access`] as each buffer is resolved, avoiding a descriptor
789    /// mirror allocation. `descs[i]` must be the descriptor for the buffer behind
790    /// `bindings[i].buffer` (equal length alone is not enough). A usage mismatch
791    /// returns [`BackendError::PermissionDenied`].
792    pub fn validate_for_submit(
793        bindings: &[Self],
794        descs: &[BufferDesc],
795        max_bindings: u32,
796    ) -> Result<(), BackendError> {
797        validate_bindings(bindings, max_bindings)?;
798        if bindings.len() != descs.len() {
799            return Err(BackendError::InvalidArgument);
800        }
801        for (binding, desc) in bindings.iter().zip(descs.iter()) {
802            if !desc.allows_access(binding.access) {
803                return Err(BackendError::PermissionDenied);
804            }
805        }
806        Ok(())
807    }
808}
809
810/// Slot/count uniqueness helper for program bindings.
811///
812/// Structural only: nonempty, bounded by `max_bindings`, and unique slots. This is
813/// **incomplete** for pre-admission checks -- it does not enforce access/usage
814/// compatibility required before backend admission. Prefer
815/// [`BindingRef::validate_for_submit`] before [`Accelerator::submit`]. Strictly
816/// slot-ordered input takes a linear, allocation-free path; arbitrary order remains
817/// supported by the allocation-free fallback.
818pub fn validate_bindings<B>(
819    bindings: &[BindingRef<'_, B>],
820    max_bindings: u32,
821) -> Result<(), BackendError> {
822    if bindings.is_empty() || bindings.len() > max_bindings as usize {
823        return Err(BackendError::ResourceLimit);
824    }
825
826    // The wire decoder canonicalizes bindings into slot order. Recognizing that
827    // invariant here avoids a second quadratic uniqueness pass on every host
828    // submission while preserving the public API's order-independent semantics.
829    if bindings.windows(2).all(|pair| pair[0].slot < pair[1].slot) {
830        return Ok(());
831    }
832
833    for (index, binding) in bindings.iter().enumerate() {
834        if bindings[..index]
835            .iter()
836            .any(|prior| prior.slot == binding.slot)
837        {
838            return Err(BackendError::InvalidArgument);
839        }
840    }
841    Ok(())
842}
843
844#[derive(Clone, Copy, Debug, PartialEq, Eq)]
845pub enum EventState {
846    Pending,
847    Complete,
848    Failed(BackendError),
849    Cancelled,
850}
851
852/// Submission failure that makes the provider acceptance boundary explicit.
853#[derive(Debug)]
854pub enum SubmitFailure<E> {
855    /// The backend guarantees execution was not accepted and no resources were retained.
856    Rejected(BackendError),
857    /// Acceptance is uncertain; the event owns the resources until it reaches a terminal state.
858    Indeterminate { error: BackendError, event: E },
859}
860
861/// Failure to release a provider handle.
862#[derive(Debug)]
863pub enum ReleaseFailure<R> {
864    /// The backend rejected the release and returns the still-live resource for retry.
865    Rejected { error: BackendError, resource: R },
866    /// The resource state is unknown. The adapter must invalidate its ID and request device reset.
867    Indeterminate { error: BackendError },
868}
869
870impl<R> ReleaseFailure<R> {
871    pub const fn error(&self) -> BackendError {
872        match self {
873            Self::Rejected { error, .. } | Self::Indeterminate { error } => *error,
874        }
875    }
876}
877
878/// Native accelerator lifecycle over provider-owned handle types.
879///
880/// The reference command engine is generic over this trait, so its calls are statically dispatched
881/// and native handles need no boxing. The trait imposes no `Send` or `Sync` bounds: a provider may
882/// preserve thread-affine handles, while a provider that opts into those auto traits must make the
883/// corresponding shared calls safe. Callers must not overlap a mutable borrow, a consumed handle,
884/// or destruction with another use of the same resource.
885///
886/// Borrowed arguments are valid only for the duration of a call and must not be retained as Rust
887/// references. Destructive methods consume handles. A caller must reject parent destruction while
888/// child objects or in-flight events still exist; it must not use `Drop` timing as lifecycle state.
889///
890/// The only operations that explicitly transfer buffer contents are [`Self::write_buffer`] and
891/// [`Self::read_buffer`]. Allocation, submission, polling, and release must not hide full-range
892/// staging copies. In particular, `submit` binds the exact provider allocation directly or rejects
893/// it as [`BackendError::Incompatible`].
894///
895/// Dynamic loading, a stable binary interface, and erased cross-boundary handle ownership are not
896/// defined here. An integration that needs dynamic dispatch must fix one concrete handle family in
897/// an adapter without weakening this trait's borrowing, acceptance, or release contracts.
898pub trait Accelerator {
899    /// Owned context handle. It may be a native value and need not be boxed, cloneable, or thread
900    /// safe.
901    type Context;
902    /// Owned handle for the exact allocation described by its accompanying [`BufferInfo`].
903    type Buffer;
904    /// Owned resident-program handle with no borrow of its source artifact.
905    type Program;
906    /// Owned accelerator execution-queue handle.
907    type Queue;
908    /// Owned submission and completion token with no borrow of the submitted binding slice.
909    type Event;
910
911    /// Return immutable identity, capability, and limit metadata.
912    ///
913    /// - **Ownership/lifetime:** no ownership changes; a successful value must remain stable for
914    ///   the lifetime of this backend instance.
915    /// - **Progress/concurrency:** discovery may perform bounded synchronous provider work but must
916    ///   not wait for resource progress. Concurrent calls are permitted only when the concrete
917    ///   backend is `Sync`.
918    /// - **Failure/retry:** an error creates no resource and may be retried; callers validate and
919    ///   cache the first successful result before invoking resource methods.
920    /// - **Allocation/copies:** the call must not allocate resource backing or copy bulk content.
921    fn device_info(&self) -> Result<DeviceInfo, BackendError>;
922
923    /// Create one context from prevalidated intent.
924    ///
925    /// - **Ownership/lifetime:** `desc` is consumed by value and not retained by reference; success
926    ///   returns one owned context. All current nonempty context flags are unsupported.
927    /// - **Progress/concurrency:** provider setup may synchronously block, but must not wait for
928    ///   unrelated resource progress. Independent creation may overlap only when concrete types
929    ///   permit it.
930    /// - **Failure/retry:** `Err` guarantees that no context resource was retained and the request
931    ///   may be retried.
932    /// - **Allocation/copies:** context bookkeeping may be allocated; no buffer content is copied.
933    fn create_context(&self, desc: ContextDesc) -> Result<Self::Context, BackendError>;
934
935    /// Destroy an empty context.
936    ///
937    /// - **Ownership/lifetime:** the handle is consumed and must have no live child resources.
938    /// - **Progress/concurrency:** release may synchronously block, but must not wait for children
939    ///   or in-flight work; no use of this context may overlap the call.
940    /// - **Failure/retry:** [`ReleaseFailure::Rejected`] returns the live handle for retry;
941    ///   [`ReleaseFailure::Indeterminate`] invalidates it and forbids retry.
942    /// - **Allocation/copies:** the call releases provider bookkeeping and copies no content.
943    fn destroy_context(&self, context: Self::Context) -> Result<(), ReleaseFailure<Self::Context>>;
944
945    /// Allocate one exact provider-owned buffer backing.
946    ///
947    /// - **Ownership/lifetime:** `context` is borrowed only for this call. Success returns an owned
948    ///   handle plus metadata for the actual backing; neither may borrow `context`.
949    /// - **Progress/concurrency:** allocation may synchronously block. Independent contexts may be
950    ///   used concurrently only when the concrete backend and handles permit it.
951    /// - **Failure/retry:** `Err` guarantees that no buffer backing was retained and may be retried.
952    /// - **Allocation/copies:** this is the buffer-allocation boundary. Program-visible requests
953    ///   allocate directly bindable backing here or fail; they must not reserve a submission-time
954    ///   bounce allocation or copy buffer content.
955    fn allocate_buffer(
956        &self,
957        context: &Self::Context,
958        desc: BufferDesc,
959    ) -> Result<AllocatedBuffer<Self::Buffer>, BackendError>;
960
961    /// Perform one explicit host-to-buffer transfer.
962    ///
963    /// - **Ownership/lifetime:** `buffer` is exclusively borrowed and `data` is borrowed only for
964    ///   this call. The provider must not retain either reference.
965    /// - **Progress/concurrency:** the call may synchronously block until the explicit transfer is
966    ///   complete. The exclusive buffer borrow prevents overlapping access without forcing
967    ///   interior synchronization; unrelated buffers may progress when concrete types permit it.
968    /// - **Failure/retry:** on `Err`, the requested range may be partially modified but the handle
969    ///   remains live. A later successful full-range write replaces it; device loss is not
970    ///   retryable on the same backend instance.
971    /// - **Allocation/copies:** this is an explicit content-copy boundary. Segmented input should
972    ///   flow into final backing without frame-sized coalescing. Device-local backing may use
973    ///   bounded temporary staging during this call.
974    fn write_buffer(
975        &self,
976        buffer: &mut Self::Buffer,
977        offset: u64,
978        data: &dyn ByteSource,
979    ) -> Result<(), BackendError>;
980    /// Perform one explicit buffer-to-host transfer.
981    ///
982    /// - **Ownership/lifetime:** `buffer` is shared-borrowed and `data` is exclusively borrowed only
983    ///   for this call. The provider must not retain either reference.
984    /// - **Progress/concurrency:** the call may synchronously block until the explicit transfer is
985    ///   complete. Shared reads may overlap only when the concrete buffer is `Sync` and the
986    ///   provider supports that access.
987    /// - **Failure/retry:** `Err` leaves the destination potentially partially initialized; the
988    ///   caller must not publish it. The buffer is unchanged and a complete read may be retried
989    ///   unless the backend is lost. `Ok(())` guarantees every destination byte was initialized.
990    /// - **Allocation/copies:** this is an explicit content-copy boundary. The provider should
991    ///   write directly across segmented destinations; device-local backing may use bounded
992    ///   temporary staging during this call.
993    fn read_buffer(
994        &self,
995        buffer: &Self::Buffer,
996        offset: u64,
997        data: &mut dyn ByteSink,
998    ) -> Result<(), BackendError>;
999
1000    /// Release an unreferenced buffer and its exact backing allocation.
1001    ///
1002    /// - **Ownership/lifetime:** the handle is consumed and must not be bound to an in-flight event.
1003    /// - **Progress/concurrency:** release may synchronously block but must not wait for references
1004    ///   to disappear; no access to this buffer may overlap the call.
1005    /// - **Failure/retry:** rejected release returns the live handle for retry; indeterminate
1006    ///   release invalidates it and requires recovery.
1007    /// - **Allocation/copies:** backing is deallocated without copying its contents or allocating a
1008    ///   replacement.
1009    fn free_buffer(&self, buffer: Self::Buffer) -> Result<(), ReleaseFailure<Self::Buffer>>;
1010
1011    /// Create a resident program from an opaque, possibly segmented artifact.
1012    ///
1013    /// - **Ownership/lifetime:** `context`, `artifact.payload`, and the envelope are borrowed only
1014    ///   for this call. Success returns an owned program with no source borrow.
1015    /// - **Progress/concurrency:** program creation may synchronously block. Independent lifecycle
1016    ///   work may overlap only when the concrete backend and context permit it.
1017    /// - **Failure/retry:** `Err` guarantees that no program resource was retained and may be
1018    ///   retried with a still-live context and artifact.
1019    /// - **Allocation/copies:** resident program storage may be allocated but all storage retained
1020    ///   by the returned handle must fit `artifact.resident_bytes`. Segmented bytes should stream
1021    ///   into final resident storage rather than require one artifact-sized coalescing copy.
1022    fn load_program(
1023        &self,
1024        context: &Self::Context,
1025        artifact: ArtifactRef<'_>,
1026    ) -> Result<Self::Program, BackendError>;
1027
1028    /// Release an unreferenced resident program.
1029    ///
1030    /// - **Ownership/lifetime:** the program is consumed and must not be referenced by an event.
1031    /// - **Progress/concurrency:** release may synchronously block but must not wait for in-flight
1032    ///   references; no use of this program may overlap the call.
1033    /// - **Failure/retry:** rejected release returns the live handle for retry; indeterminate
1034    ///   release invalidates it and requires recovery.
1035    /// - **Allocation/copies:** resident storage is released without copying buffer contents or
1036    ///   allocating replacement state.
1037    fn unload_program(&self, program: Self::Program) -> Result<(), ReleaseFailure<Self::Program>>;
1038
1039    /// Create one accelerator execution queue.
1040    ///
1041    /// - **Ownership/lifetime:** `context` is borrowed only for this call and success returns an
1042    ///   owned queue. All current nonempty queue flags are unsupported.
1043    /// - **Progress/concurrency:** queue setup may synchronously block. Independent creation may
1044    ///   overlap only when concrete types permit it.
1045    /// - **Failure/retry:** `Err` guarantees that no queue resource was retained and may be retried.
1046    /// - **Allocation/copies:** queue bookkeeping may be allocated; no program or buffer content is
1047    ///   copied.
1048    fn create_queue(
1049        &self,
1050        context: &Self::Context,
1051        desc: QueueDesc,
1052    ) -> Result<Self::Queue, BackendError>;
1053
1054    /// Release an unreferenced execution queue.
1055    ///
1056    /// - **Ownership/lifetime:** the queue is consumed and must not be referenced by an event.
1057    /// - **Progress/concurrency:** release may synchronously block but must not wait for submitted
1058    ///   work; no use of this queue may overlap the call.
1059    /// - **Failure/retry:** rejected release returns the live handle for retry; indeterminate
1060    ///   release invalidates it and requires recovery.
1061    /// - **Allocation/copies:** queue state is released without copying buffer content or allocating
1062    ///   replacement state.
1063    fn destroy_queue(&self, queue: Self::Queue) -> Result<(), ReleaseFailure<Self::Queue>>;
1064
1065    /// Attempt to admit one program execution and return its event.
1066    ///
1067    /// Hosts must reject an [`AccessMode`] incompatible with each buffer's [`BufferUsage`] before
1068    /// calling this method (see [`BufferDesc::allows_access`] and
1069    /// [`BindingRef::validate_for_submit`]). Providers may repeat the check as defense in depth, but
1070    /// host-side rejection is required by Wire ABI section 4.4.
1071    ///
1072    /// - **Ownership/lifetime:** queue, program, buffers, and the binding slice are borrowed only
1073    ///   during admission and must not be retained as Rust references. The caller keeps every
1074    ///   referenced handle alive until the returned event is terminal and destroyed.
1075    /// - **Progress/concurrency:** synchronous work is limited to validation and admission; the call
1076    ///   must not wait for execution to finish. Concurrent submission requires concrete `Sync`
1077    ///   handles and provider support; the trait requires no lock or atomic operation by itself.
1078    /// - **Failure/retry:** [`SubmitFailure::Rejected`] guarantees no acceptance and permits retry.
1079    ///   Success or [`SubmitFailure::Indeterminate`] transfers invocation ownership to the event and
1080    ///   must not be retried as though rejected.
1081    /// - **Allocation/copies:** the borrowed slice requires no per-binding box or owned mirror.
1082    ///   Providers may use amortized event storage, but must directly bind each exact allocation and
1083    ///   reject incompatibility instead of allocating or copying through hidden bounce buffers.
1084    fn submit(
1085        &self,
1086        queue: &Self::Queue,
1087        program: &Self::Program,
1088        bindings: &[BindingRef<'_, Self::Buffer>],
1089        timeout: Timeout,
1090    ) -> Result<Self::Event, SubmitFailure<Self::Event>>;
1091
1092    /// Observe event state without blocking or driving an executor.
1093    ///
1094    /// - **Ownership/lifetime:** the event is borrowed only for this call and remains live.
1095    /// - **Progress/concurrency:** polling is bounded, nonblocking, and safe to race with provider
1096    ///   completion when the concrete event is `Sync`.
1097    /// - **Failure/retry:** errors do not make an event terminal; polling may be retried unless the
1098    ///   backend is lost. Once observed, a terminal state is stable across every later success.
1099    /// - **Allocation/copies:** polling allocates no per-call state and copies no bulk content.
1100    fn poll_event(&self, event: &Self::Event) -> Result<EventState, BackendError>;
1101
1102    /// Attempt to make a pending event terminal as [`EventState::Cancelled`].
1103    ///
1104    /// - **Ownership/lifetime:** the event is borrowed only for this call and remains live.
1105    /// - **Progress/concurrency:** cancellation is bounded and nonblocking. It may race with
1106    ///   completion; the provider chooses exactly one terminal result without requiring a lock in
1107    ///   the handle contract.
1108    /// - **Failure/retry:** `Ok(())` means cancellation won. [`BackendError::Busy`] means completion
1109    ///   won and the caller should poll. The default `Unsupported` implementation is conformant only
1110    ///   when [`Capabilities::EVENT_CANCELLATION`] is absent.
1111    /// - **Allocation/copies:** cancellation allocates no per-call state and copies no bulk content.
1112    fn cancel_event(&self, _event: &Self::Event) -> Result<(), BackendError> {
1113        Err(BackendError::Unsupported)
1114    }
1115
1116    /// Release one terminal event and its provider invocation state.
1117    ///
1118    /// - **Ownership/lifetime:** the event is consumed. Every referenced queue, program, and buffer
1119    ///   must remain live until this release succeeds or becomes indeterminate.
1120    /// - **Progress/concurrency:** release may synchronously block but must not wait for a pending
1121    ///   event to finish; no poll or cancellation may overlap this call.
1122    /// - **Failure/retry:** rejected release returns the live event for retry; indeterminate release
1123    ///   invalidates it and requires recovery.
1124    /// - **Allocation/copies:** invocation state is released without copying buffer content or
1125    ///   allocating replacement state.
1126    fn destroy_event(&self, event: Self::Event) -> Result<(), ReleaseFailure<Self::Event>>;
1127}
1128
1129#[cfg(test)]
1130mod tests {
1131    use super::*;
1132
1133    #[derive(Debug)]
1134    struct TransportBytes([u8; 4]);
1135
1136    impl ReadableBytes for TransportBytes {
1137        fn len(&self) -> u64 {
1138            self.0.as_slice().len() as u64
1139        }
1140
1141        fn read_at(&self, offset: u64, target: &mut [u8]) -> Result<(), ByteAccessError> {
1142            let start = usize::try_from(offset).map_err(|_| ByteAccessError::OutOfBounds)?;
1143            let end = start
1144                .checked_add(target.len())
1145                .filter(|end| *end <= self.0.as_slice().len())
1146                .ok_or(ByteAccessError::OutOfBounds)?;
1147            target.copy_from_slice(&self.0[start..end]);
1148            Ok(())
1149        }
1150    }
1151
1152    impl WritableBytes for TransportBytes {
1153        fn len(&self) -> u64 {
1154            self.0.as_slice().len() as u64
1155        }
1156
1157        fn write_at(&mut self, offset: u64, source: &[u8]) -> Result<(), ByteAccessError> {
1158            let start = usize::try_from(offset).map_err(|_| ByteAccessError::OutOfBounds)?;
1159            let end = start
1160                .checked_add(source.len())
1161                .filter(|end| *end <= self.0.as_slice().len())
1162                .ok_or(ByteAccessError::OutOfBounds)?;
1163            self.0[start..end].copy_from_slice(source);
1164            Ok(())
1165        }
1166    }
1167
1168    fn valid_device_info() -> DeviceInfo {
1169        DeviceInfo {
1170            identity: DeviceIdentity {
1171                uuid: [0; 16],
1172                class: AcceleratorClass::OTHER,
1173                vendor_id: 0,
1174                device_id: 0,
1175            },
1176            capabilities: Capabilities::HOST_VISIBLE_MEMORY,
1177            limits: DeviceLimits {
1178                max_contexts: 1,
1179                max_buffers_per_context: 1,
1180                max_programs_per_context: 1,
1181                max_queues_per_context: 1,
1182                max_events_per_context: 1,
1183                max_bindings_per_submission: 1,
1184                max_buffer_bytes: 1,
1185                max_artifact_bytes: 1,
1186            },
1187        }
1188    }
1189
1190    #[test]
1191    fn transport_byte_adapters_preserve_segment_ports_without_copying() {
1192        let mut bytes = TransportBytes(*b"abcd");
1193        let source = TransportByteSource::new(&bytes);
1194        let mut read = [0; 2];
1195        ByteSource::read_at(&source, 1, &mut read).unwrap();
1196        assert_eq!(&read, b"bc");
1197
1198        let mut sink = TransportByteSink::new(&mut bytes);
1199        ByteSink::write_at(&mut sink, 2, b"xy").unwrap();
1200        assert_eq!(&bytes.0, b"abxy");
1201    }
1202
1203    #[test]
1204    fn buffer_descriptors_reject_invalid_alignment() {
1205        assert!(BufferDesc::new(1, 0, MemoryDomain::Host, BufferUsage::empty()).is_err());
1206        assert!(BufferDesc::new(1, 3, MemoryDomain::Host, BufferUsage::TRANSFER_SOURCE).is_err());
1207        assert!(BufferDesc::new(1, 1, MemoryDomain::Host, BufferUsage::empty()).is_err());
1208        assert_eq!(
1209            BufferDesc::new(64, 16, MemoryDomain::Shared, BufferUsage::PROGRAM_INPUT)
1210                .unwrap()
1211                .alignment(),
1212            16
1213        );
1214    }
1215
1216    #[test]
1217    fn buffer_usage_defines_submission_access_compatibility() {
1218        let input =
1219            BufferDesc::new(64, 16, MemoryDomain::Host, BufferUsage::PROGRAM_INPUT).unwrap();
1220        assert!(input.allows_access(AccessMode::Read));
1221        assert!(!input.allows_access(AccessMode::Write));
1222        assert!(!input.allows_access(AccessMode::ReadWrite));
1223
1224        let output =
1225            BufferDesc::new(64, 16, MemoryDomain::Host, BufferUsage::PROGRAM_OUTPUT).unwrap();
1226        assert!(!output.allows_access(AccessMode::Read));
1227        assert!(output.allows_access(AccessMode::Write));
1228        assert!(!output.allows_access(AccessMode::ReadWrite));
1229
1230        let mutable =
1231            BufferDesc::new(64, 16, MemoryDomain::Host, BufferUsage::MUTABLE_STATE).unwrap();
1232        assert!(mutable.allows_access(AccessMode::Read));
1233        assert!(mutable.allows_access(AccessMode::Write));
1234        assert!(mutable.allows_access(AccessMode::ReadWrite));
1235    }
1236
1237    #[test]
1238    fn allocation_properties_reject_hidden_submission_staging() {
1239        let host_input =
1240            BufferDesc::new(64, 16, MemoryDomain::Host, BufferUsage::PROGRAM_INPUT).unwrap();
1241        assert_eq!(
1242            BufferInfo::new(host_input, 64, 16, BufferProperties::HOST_VISIBLE),
1243            Err(BackendError::Incompatible)
1244        );
1245        assert!(
1246            BufferInfo::new(
1247                host_input,
1248                64,
1249                16,
1250                BufferProperties::HOST_VISIBLE | BufferProperties::DIRECT_BINDING
1251            )
1252            .is_ok()
1253        );
1254
1255        let shared =
1256            BufferDesc::new(64, 16, MemoryDomain::Shared, BufferUsage::TRANSFER_SOURCE).unwrap();
1257        assert_eq!(
1258            BufferInfo::new(shared, 64, 16, BufferProperties::HOST_VISIBLE),
1259            Err(BackendError::Incompatible)
1260        );
1261        assert_eq!(
1262            BufferInfo::new(
1263                shared,
1264                63,
1265                16,
1266                BufferProperties::HOST_VISIBLE | BufferProperties::DIRECT_BINDING
1267            ),
1268            Err(BackendError::Incompatible)
1269        );
1270        assert_eq!(
1271            BufferInfo::new(
1272                shared,
1273                64,
1274                8,
1275                BufferProperties::HOST_VISIBLE | BufferProperties::DIRECT_BINDING
1276            ),
1277            Err(BackendError::Incompatible)
1278        );
1279    }
1280
1281    #[test]
1282    fn capabilities_report_memory_domains_independently() {
1283        let capabilities = Capabilities::HOST_VISIBLE_MEMORY | Capabilities::SHARED_MEMORY;
1284        assert!(capabilities.supports_memory_domain(MemoryDomain::Host));
1285        assert!(capabilities.supports_memory_domain(MemoryDomain::Shared));
1286        assert!(!capabilities.supports_memory_domain(MemoryDomain::Device));
1287    }
1288
1289    #[test]
1290    fn device_information_rejects_unusable_provider_contracts() {
1291        let valid = valid_device_info();
1292        assert_eq!(valid.validate(), Ok(()));
1293
1294        let mut reserved = valid;
1295        reserved.capabilities |= Capabilities::EXTERNAL_MEMORY;
1296        assert_eq!(
1297            reserved.validate(),
1298            Err(DeviceInfoError::ReservedCapabilities)
1299        );
1300
1301        let mut no_memory = valid;
1302        no_memory.capabilities = Capabilities::EVENT_CANCELLATION;
1303        assert_eq!(
1304            no_memory.validate(),
1305            Err(DeviceInfoError::MissingMemoryDomain)
1306        );
1307
1308        let mut zero_limit = valid;
1309        zero_limit.limits.max_bindings_per_submission = 0;
1310        assert_eq!(zero_limit.validate(), Err(DeviceInfoError::ZeroLimit));
1311
1312        let mut unknown = valid;
1313        unknown.capabilities |= Capabilities::from_bits_retain(1 << 63);
1314        assert_eq!(unknown.validate(), Ok(()));
1315    }
1316
1317    #[test]
1318    fn reserved_operations_are_rejected_before_provider_invocation() {
1319        let mut info = valid_device_info();
1320        assert_eq!(info.validate_context_desc(ContextDesc::default()), Ok(()));
1321        assert_eq!(info.validate_queue_desc(QueueDesc::default()), Ok(()));
1322        assert_eq!(
1323            info.validate_context_desc(ContextDesc {
1324                flags: ContextFlags::SECURE,
1325            }),
1326            Err(BackendError::Unsupported)
1327        );
1328        assert_eq!(
1329            info.validate_queue_desc(QueueDesc {
1330                flags: QueueFlags::IN_ORDER,
1331            }),
1332            Err(BackendError::Unsupported)
1333        );
1334        assert_eq!(
1335            info.validate_event_cancellation(),
1336            Err(BackendError::Unsupported)
1337        );
1338
1339        info.capabilities |= Capabilities::EVENT_CANCELLATION;
1340        assert_eq!(info.validate_event_cancellation(), Ok(()));
1341    }
1342
1343    #[test]
1344    fn bindings_are_nonempty_bounded_and_unique() {
1345        let buffer = ();
1346        let range = BufferRange::new(0, 16).unwrap();
1347        let binding = BindingRef {
1348            slot: 3,
1349            buffer: &buffer,
1350            range,
1351            access: AccessMode::Read,
1352        };
1353        assert!(validate_bindings(&[binding], 1).is_ok());
1354
1355        let duplicate = [
1356            BindingRef {
1357                slot: 3,
1358                buffer: &buffer,
1359                range,
1360                access: AccessMode::Read,
1361            },
1362            BindingRef {
1363                slot: 3,
1364                buffer: &buffer,
1365                range,
1366                access: AccessMode::Write,
1367            },
1368        ];
1369        assert_eq!(
1370            validate_bindings(&duplicate, 2),
1371            Err(BackendError::InvalidArgument)
1372        );
1373        assert_eq!(
1374            validate_bindings::<()>(&[], 1),
1375            Err(BackendError::ResourceLimit)
1376        );
1377
1378        let arbitrary_order = [
1379            BindingRef {
1380                slot: 7,
1381                buffer: &buffer,
1382                range,
1383                access: AccessMode::Read,
1384            },
1385            BindingRef {
1386                slot: 2,
1387                buffer: &buffer,
1388                range,
1389                access: AccessMode::Write,
1390            },
1391        ];
1392        assert!(validate_bindings(&arbitrary_order, 2).is_ok());
1393
1394        let canonical_order = [
1395            BindingRef {
1396                slot: 2,
1397                buffer: &buffer,
1398                range,
1399                access: AccessMode::Read,
1400            },
1401            BindingRef {
1402                slot: 7,
1403                buffer: &buffer,
1404                range,
1405                access: AccessMode::Write,
1406            },
1407        ];
1408        assert!(validate_bindings(&canonical_order, 2).is_ok());
1409    }
1410
1411    #[test]
1412    fn binding_access_rejects_usage_mismatch_with_unique_slots() {
1413        let buffer = ();
1414        let range = BufferRange::new(0, 16).unwrap();
1415        let bindings = [BindingRef {
1416            slot: 0,
1417            buffer: &buffer,
1418            range,
1419            access: AccessMode::Write,
1420        }];
1421        let input =
1422            BufferDesc::new(64, 16, MemoryDomain::Host, BufferUsage::PROGRAM_INPUT).unwrap();
1423        assert!(!input.allows_access(AccessMode::Write));
1424        // Slot-only checks still pass; the usage gate lives on validate_for_submit.
1425        assert!(validate_bindings(&bindings, 1).is_ok());
1426        assert_eq!(
1427            BindingRef::validate_for_submit(&bindings, &[input], 1),
1428            Err(BackendError::PermissionDenied)
1429        );
1430
1431        let read_bindings = [BindingRef {
1432            slot: 0,
1433            buffer: &buffer,
1434            range,
1435            access: AccessMode::Read,
1436        }];
1437        assert!(BindingRef::validate_for_submit(&read_bindings, &[input], 1).is_ok());
1438        assert_eq!(
1439            BindingRef::validate_for_submit(&read_bindings, &[], 1),
1440            Err(BackendError::InvalidArgument)
1441        );
1442    }
1443
1444    #[test]
1445    fn wire_timeouts_are_relative_and_zero_is_infinite() {
1446        assert_eq!(Timeout::from_wire_ns(0), Timeout::Infinite);
1447        assert_eq!(Timeout::from_wire_ns(42).to_wire_ns(), 42);
1448    }
1449}