aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
GitHub aien-dev/aienux#102 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/7298661fe09a9e08.bundle -o 7298661fe09a9e08.bundle git fetch 7298661fe09a9e08.bundle refs/pull/102/head
Provenance
github-import 1
aien-dev/aienux
102
d2bfd0a17fa7e55c5a3c42d142ad396c98707891
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":102,"url":"https://github.com/aien-dev/aienux/pull/102","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:43Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aienos-kernel/src/usb/audio.rs b/crates/aienos-kernel/src/usb/audio.rs index 64cbe2c1..afc9bc0c 100644 --- a/crates/aienos-kernel/src/usb/audio.rs +++ b/crates/aienos-kernel/src/usb/audio.rs @@ -1,7 +1,9 @@ //! Host-testable USB Audio Class output descriptor and PCM helpers. //! //! This parses the common single-configuration UAC1/UAC2 layout. It does not -//! submit transfers; an xHCI audio engine can use the selected stream later. +//! touch controller registers; packet scheduling is host-testable. + +use crate::usb::xhci::trb::Trb; const CONFIG: u8 = 2; const INTERFACE: u8 = 4; @@ -222,6 +224,13 @@ impl PcmFramer { self.remainder = numerator % 1_000_000; frames as usize * usize::from(self.channels) * usize::from(self.sample_bytes) } + /// Bytes the next packet will need, without advancing the framer. + pub fn peek_packet_bytes(&self) -> usize { + let numerator = u64::from(self.rate) * u64::from(self.interval_us) + self.remainder; + (numerator / 1_000_000) as usize + * usize::from(self.channels) + * usize::from(self.sample_bytes) + } /// Fill one packet from interleaved PCM, wrapping the caller's ring cursor. pub fn fill_i16(&mut self, ring: &[i16], cursor: &mut usize, out: &mut [i16]) -> usize { let bytes = self.next_packet_bytes(); @@ -238,6 +247,74 @@ impl PcmFramer { } } +/// Prepare `packets.len()` service intervals ahead of `controller_frame`. +/// Each PCM output chunk has `packet_stride_samples` samples; its DMA address +/// is supplied in the matching entry. Frame IDs wrap at the xHCI 11-bit field. +pub struct AudioBatch<'a> { + pub controller_frame: u16, + pub lead_frames: u16, + pub packets: &'a [(u64, u16)], + pub pcm_ring: &'a [i16], + pub cursor: &'a mut usize, + pub pcm: &'a mut [i16], + pub packet_stride_samples: usize, + pub trbs: &'a mut [Trb], +} + +pub fn schedule_isoch_ahead(framer: &mut PcmFramer, batch: &mut AudioBatch<'_>) -> usize { + let AudioBatch { + controller_frame, + lead_frames, + packets, + pcm_ring, + cursor, + pcm, + packet_stride_samples, + trbs, + } = batch; + let stride = *packet_stride_samples; + if stride == 0 { + return 0; + } + let slots = packets.len().min(trbs.len()).min(pcm.len() / stride); + let mut count = 0; + while count < slots { + // Check before consuming PCM: a packet that doesn't fit its buffer or + // its PCM chunk stops scheduling here, rather than being truncated + // while the cursor skips the samples that were cut. + let needed = framer.peek_packet_bytes(); + if needed > usize::from(packets[count].1) || needed > stride * 2 { + break; + } + let start = count * stride; + let out = &mut pcm[start..start + stride]; + let samples = framer.fill_i16(pcm_ring, cursor, out); + trbs[count] = Trb::isoch( + packets[count].0, + (samples * 2) as u32, + controller_frame + .wrapping_add(*lead_frames) + .wrapping_add(count as u16) + & 0x7ff, + false, + false, + ); + count += 1; + } + if count > 0 { + // Interrupt on completion of the last packet actually scheduled. + let last = &trbs[count - 1]; + trbs[count - 1] = Trb::isoch( + last.0[0] as u64 | (last.0[1] as u64) << 32, + last.0[2] & 0x1_ffff, + ((last.0[3] >> 20) & 0x7ff) as u16, + false, + true, + ); + } + count +} + /// Deterministic 16-bit sine approximation using a parabolic fixed-point wave. #[derive(Clone, Copy, Debug, Default)] pub struct TestTone { @@ -308,6 +385,45 @@ mod tests { assert_eq!(frames, 44100); assert!(saw44 && saw45); } + + #[test] + fn stereo_44100_scheduler_emits_one_second_of_pcm_bytes() { + let mut framer = PcmFramer::new(44_100, 2, 2, 1000).unwrap(); + let mut cursor = 0; + let source = [7i16; 256]; + let mut output = [0i16; 90]; + let mut total = 0; + for _ in 0..1000 { + let n = framer.fill_i16(&source, &mut cursor, &mut output); + total += n * 2; + } + assert_eq!(total, 176_400); + } + + #[test] + fn isoch_schedule_stays_ahead_and_wraps_frame_id() { + let mut framer = PcmFramer::new(48_000, 2, 2, 1000).unwrap(); + let packets = [(0x1000, 192), (0x2000, 192)]; + let mut pcm = [0i16; 192]; + let mut trbs = [Trb::default(); 2]; + let mut cursor = 0; + let mut batch = AudioBatch { + controller_frame: 2046, + lead_frames: 2, + packets: &packets, + pcm_ring: &[], + cursor: &mut cursor, + pcm: &mut pcm, + packet_stride_samples: 96, + trbs: &mut trbs, + }; + let n = schedule_isoch_ahead(&mut framer, &mut batch); + assert_eq!(n, 2); + assert_eq!((trbs[0].0[3] >> 20) & 0x7ff, 0); + assert_eq!((trbs[1].0[3] >> 20) & 0x7ff, 1); + assert_eq!(trbs[0].0[2], 192); + assert_eq!(trbs[1].0[2], 192); + } #[test] fn ring_wraps_and_tone_is_bounded() { let mut f = PcmFramer::new(48000, 2, 2, 1000).unwrap(); @@ -347,4 +463,38 @@ mod tests { v[at] = 7; let _ = select_output(&v); } + #[test] + fn oversized_packet_is_not_truncated_and_zero_stride_schedules_nothing() { + // Review regression: 96 kHz stereo 16-bit needs 384 B per 1 ms packet. + let mut framer = PcmFramer::new(96_000, 2, 2, 1000).unwrap(); + let packets = [(0x1000, 192)]; + let ring = [7i16; 512]; + let mut pcm = [0i16; 256]; + let mut trbs = [Trb::default(); 1]; + let mut cursor = 0; + let mut batch = AudioBatch { + controller_frame: 0, + lead_frames: 1, + packets: &packets, + pcm_ring: &ring, + cursor: &mut cursor, + pcm: &mut pcm, + packet_stride_samples: 256, + trbs: &mut trbs, + }; + assert_eq!(schedule_isoch_ahead(&mut framer, &mut batch), 0); + assert_eq!(cursor, 0, "no samples consumed"); + let mut cursor = 0; + let mut batch = AudioBatch { + controller_frame: 0, + lead_frames: 1, + packets: &[(0x1000, 1024)], + pcm_ring: &ring, + cursor: &mut cursor, + pcm: &mut pcm, + packet_stride_samples: 0, + trbs: &mut trbs, + }; + assert_eq!(schedule_isoch_ahead(&mut framer, &mut batch), 0); + } } diff --git a/crates/aienos-kernel/src/usb/xhci/context.rs b/crates/aienos-kernel/src/usb/xhci/context.rs index 68a96e20..9afc3db7 100644 --- a/crates/aienos-kernel/src/usb/xhci/context.rs +++ b/crates/aienos-kernel/src/usb/xhci/context.rs @@ -17,6 +17,7 @@ pub mod speed { /// Endpoint Context EP Type values. pub const EP_TYPE_CONTROL: u8 = 4; pub const EP_TYPE_INTERRUPT_IN: u8 = 7; +pub const EP_TYPE_ISOCH_OUT: u8 = 1; /// Error count: retry a failing transaction three times before halting. const CERR: u32 = 3; /// Device context index of the default control endpoint. @@ -46,6 +47,45 @@ pub fn interrupt_interval(port_speed: u8, b_interval: u8) -> u8 { } } +/// xHCI Interval for an isochronous endpoint (xHCI 1.2 section 6.2.3.6): +/// full speed counts 1 ms frames as 2^(bInterval-1), i.e. bInterval + 2 in +/// 125 us exponent units; high/super speed use bInterval - 1 directly. +/// (Interrupt endpoints follow a different full-speed rule.) +pub fn isoch_interval(port_speed: u8, b_interval: u8) -> u8 { + let b = b_interval.clamp(1, 16); + match port_speed { + speed::FULL | speed::LOW => b + 2, + _ => b - 1, + } +} + +/// Configure an isochronous OUT endpoint from the raw `wMaxPacketSize`. +/// Bits 10:0 are the packet size; for high speed, bits 12:11 are the extra +/// transactions per microframe, which go in Max Burst Size (Mult is +/// SuperSpeed-only). `max_esit_payload` is the bytes per service interval. +pub fn isoch_out_endpoint( + port_speed: u8, + b_interval: u8, + w_max_packet_size: u16, + max_esit_payload: u16, + dequeue: u64, +) -> EndpointConfig { + let high_bandwidth = if port_speed == speed::HIGH { + ((w_max_packet_size >> 11) & 0x3) as u8 + } else { + 0 + }; + EndpointConfig { + ep_type: EP_TYPE_ISOCH_OUT, + max_packet: w_max_packet_size & 0x7ff, + max_burst: high_bandwidth, + interval: isoch_interval(port_speed, b_interval), + dequeue, + average_trb_length: max_esit_payload, + max_esit_payload, + } +} + /// Device context index for a non-control endpoint address such as 0x81. pub fn endpoint_dci(endpoint_address: u8) -> Option<u8> { let number = endpoint_address & 0x0f; @@ -60,6 +100,8 @@ pub fn endpoint_dci(endpoint_address: u8) -> Option<u8> { pub struct EndpointConfig { pub ep_type: u8, pub max_packet: u16, + /// Max Burst Size (Endpoint Context dword 1 bits 15:8). + pub max_burst: u8, pub interval: u8, /// TR Dequeue Pointer with the Dequeue Cycle State in bit 0. pub dequeue: u64, @@ -115,8 +157,10 @@ impl<'a> InputContext<'a> { } let ep = self.entry(usize::from(dci) + 1); ep[0] = u32::from(config.interval) << 16; - ep[1] = - CERR << 1 | u32::from(config.ep_type & 0x7) << 3 | u32::from(config.max_packet) << 16; + ep[1] = CERR << 1 + | u32::from(config.ep_type & 0x7) << 3 + | u32::from(config.max_burst) << 8 + | u32::from(config.max_packet) << 16; ep[2] = config.dequeue as u32; ep[3] = (config.dequeue >> 32) as u32; ep[4] = u32::from(config.average_trb_length) | u32::from(config.max_esit_payload) << 16; @@ -162,6 +206,7 @@ mod tests { CONTROL_DCI, &EndpointConfig { ep_type: EP_TYPE_CONTROL, + max_burst: 0, max_packet: 8, interval: 0, dequeue: 0x4000_1000 | 1, @@ -190,6 +235,7 @@ mod tests { 3, &EndpointConfig { ep_type: EP_TYPE_INTERRUPT_IN, + max_burst: 0, max_packet: 8, interval: 6, dequeue: 0x2_0000_0001, @@ -201,6 +247,7 @@ mod tests { 0, &EndpointConfig { ep_type: 0, + max_burst: 0, max_packet: 0, interval: 0, dequeue: u64::MAX, @@ -223,4 +270,35 @@ mod tests { assert!(InputContext::new(&mut words, 48).is_none()); assert!(InputContext::new(&mut words[..100], 32).is_none()); } + + #[test] + fn isochronous_out_endpoint_fields_encode_in_context() { + let mut words = [0u32; 8 * 33]; + let mut input = InputContext::new(&mut words, 32).unwrap(); + input.endpoint( + 2, + &isoch_out_endpoint(speed::HIGH, 4, 192, 192, 0x1234_5001), + ); + let ep = 8 * 3; + assert_eq!(words[ep], 3 << 16); + assert_eq!( + words[ep + 1], + CERR << 1 | (EP_TYPE_ISOCH_OUT as u32) << 3 | 192 << 16 + ); + assert_eq!([words[ep + 2], words[ep + 3]], [0x1234_5001, 0]); + assert_eq!(words[ep + 4], 192 | 192 << 16); + } + #[test] + fn isoch_interval_and_high_bandwidth_burst() { + // Review regressions: FS isochronous bInterval 2 = 2 ms = 2^4 x 125 us. + assert_eq!(isoch_interval(speed::FULL, 1), 3); + assert_eq!(isoch_interval(speed::FULL, 2), 4); + assert_eq!(isoch_interval(speed::HIGH, 4), 3); + // HS wMaxPacketSize 0x1400: 1024 bytes, 2 extra transactions. + let ep = isoch_out_endpoint(speed::HIGH, 1, 0x1400, 3072, 0x1000); + assert_eq!((ep.max_packet, ep.max_burst), (1024, 2)); + // Full speed: bits 12:11 are reserved, never a burst. + let ep = isoch_out_endpoint(speed::FULL, 1, 0x1400, 1023, 0x1000); + assert_eq!((ep.max_packet, ep.max_burst), (1024 & 0x7ff, 0)); + } } diff --git a/crates/aienos-kernel/src/usb/xhci/controller.rs b/crates/aienos-kernel/src/usb/xhci/controller.rs index 140930a7..6b8f865b 100644 --- a/crates/aienos-kernel/src/usb/xhci/controller.rs +++ b/crates/aienos-kernel/src/usb/xhci/controller.rs @@ -374,6 +374,7 @@ impl Keyboard { dci, &EndpointConfig { ep_type: EP_TYPE_INTERRUPT_IN, + max_burst: 0, max_packet: keyboard.max_packet, interval: interrupt_interval(speed, keyboard.interval), dequeue, @@ -404,6 +405,7 @@ impl Keyboard { CONTROL_DCI, &EndpointConfig { ep_type: EP_TYPE_CONTROL, + max_burst: 0, max_packet, interval: 0, dequeue, diff --git a/crates/aienos-kernel/src/usb/xhci/ring.rs b/crates/aienos-kernel/src/usb/xhci/ring.rs index 03088afb..9b676bd7 100644 --- a/crates/aienos-kernel/src/usb/xhci/ring.rs +++ b/crates/aienos-kernel/src/usb/xhci/ring.rs @@ -86,6 +86,23 @@ impl ProducerRing { addr } + /// Enqueue a batch of isochronous packets, chaining all but the last and + /// requesting one completion event for the batch. Returns TRB addresses. + pub fn push_isoch_batch(&mut self, packets: &[Trb], addresses: &mut [u64]) -> usize { + let count = packets.len().min(addresses.len()); + for (i, packet) in packets[..count].iter().enumerate() { + let mut trb = *packet; + trb.0[3] &= !(super::trb::IOC | super::trb::CHAIN); + trb.0[3] |= if i + 1 == count { + super::trb::IOC + } else { + super::trb::CHAIN + }; + addresses[i] = self.push(trb); + } + count + } + fn write_owned(&mut self, index: usize, trb: Trb) { let trb = trb.with_cycle(self.cycle); // SAFETY: `index < len` at every call site. diff --git a/crates/aienos-kernel/src/usb/xhci/trb.rs b/crates/aienos-kernel/src/usb/xhci/trb.rs index eb46be34..22534930 100644 --- a/crates/aienos-kernel/src/usb/xhci/trb.rs +++ b/crates/aienos-kernel/src/usb/xhci/trb.rs @@ -11,6 +11,7 @@ pub mod kind { pub const SETUP_STAGE: u8 = 2; pub const DATA_STAGE: u8 = 3; pub const STATUS_STAGE: u8 = 4; + pub const ISOCH: u8 = 5; pub const LINK: u8 = 6; pub const ENABLE_SLOT: u8 = 9; pub const DISABLE_SLOT: u8 = 10; @@ -36,6 +37,8 @@ pub const TOGGLE_CYCLE: u32 = 1 << 1; pub const ISP: u32 = 1 << 2; /// Interrupt on completion: post an event when this TRB completes. pub const IOC: u32 = 1 << 5; +/// Continue a transfer descriptor on the next TRB. +pub const CHAIN: u32 = 1 << 4; /// Immediate data: the parameter dwords hold the data (Setup Stage only). pub const IDT: u32 = 1 << 6; /// Data and Status Stage direction bit: set for device-to-host. @@ -45,6 +48,8 @@ const SLOT_SHIFT: u32 = 24; /// Setup Stage transfer type (TRT) values, bits 17:16. const TRT_OUT: u32 = 2 << 16; const TRT_IN: u32 = 3 << 16; +/// Isoch TRB Schedule Immediately, used when Frame ID is not selected. +pub const SIA: u32 = 1 << 31; /// One 16-byte TRB as four little-endian dwords. #[repr(C, align(16))] @@ -131,6 +136,22 @@ impl Trb { Self::new(buffer, length & 0x1_ffff, kind::NORMAL, IOC | ISP) } + /// One isochronous OUT packet. SuperSpeed TBC/TLBPC are zero for an + /// endpoint without a companion descriptor; `last` terminates the batch. + pub fn isoch(buffer: u64, length: u32, frame_id: u16, sia: bool, last: bool) -> Self { + let mut flags = + (u32::from(frame_id & 0x7ff) << 20) | (u32::from(kind::ISOCH) << TYPE_SHIFT); + if sia { + flags |= SIA; + } + // One packet per TD: CHAIN would merge packets with different Frame + // IDs into a single TD. `last` only requests an interrupt on completion. + if last { + flags |= IOC; + } + Self::new(buffer, length & 0x1_ffff, kind::ISOCH, flags & !(0x7 << 7)) + } + pub fn kind(&self) -> u8 { ((self.0[3] >> TYPE_SHIFT) & 0x3f) as u8 } @@ -350,4 +371,24 @@ mod tests { assert_eq!(link.kind(), kind::LINK); assert_ne!(link.0[3] & TOGGLE_CYCLE, 0); } + + #[test] + fn isoch_trb_encodes_frame_id_and_batch_flags() { + let first = Trb::isoch(0x1234_5678_9abc_def0, 176, 0x456, false, false); + assert_eq!(first.kind(), kind::ISOCH); + assert_eq!(first.pointer(), 0x1234_5678_9abc_def0); + assert_eq!(first.0[2], 176); + assert_eq!((first.0[3] >> 20) & 0x7ff, 0x456); + assert_eq!( + first.0[3] & CHAIN, + 0, + "each isochronous packet is its own TD" + ); + assert_eq!(first.0[3] & IOC, 0); + assert_eq!(first.0[3] & (7 << 7), 0, "SuperSpeed companion fields zero"); + let last = Trb::isoch(0x2000, 180, 7, true, true); + assert_ne!(last.0[3] & SIA, 0); + assert_ne!(last.0[3] & IOC, 0); + assert_eq!(last.0[3] & CHAIN, 0); + } }