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#75 (code only)
Apply it
git checkout -b patch-c2efd4148af6010e 3a8e3bac6250e273c78d462bdf4b0fea04c1b58b curl -fsSL https://interplane.io/drakestapleton/aienux/patches/c2efd4148af6010e.patch | git am
Provenance
github-import 1
aien-dev/aienux
75
6cbfd7c7c6ead2e2ac18d06c1943d8ce9d28443e
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":75,"url":"https://github.com/aien-dev/aienux/pull/75","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:43Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aienos-kernel/src/acpi.rs b/crates/aienos-kernel/src/acpi.rs index 3a0ed54a..89e43761 100644 --- a/crates/aienos-kernel/src/acpi.rs +++ b/crates/aienos-kernel/src/acpi.rs @@ -259,6 +259,50 @@ pub fn madt_cpu_topology_for( Ok(topo) } +/// MCFG allocations start after the header and 8 reserved bytes. +const MCFG_ENTRIES_OFFSET: usize = 44; +const MCFG_ENTRY_LEN: usize = 16; + +/// One PCI Express enhanced configuration (ECAM) window from the MCFG table. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EcamWindow { + pub base: u64, + pub segment: u16, + pub start_bus: u8, + pub end_bus: u8, +} + +impl EcamWindow { + /// Address of config register `offset` of `bus:device.function`, or + /// `None` outside this window or the 4 KiB function space. + pub fn config_address(&self, bus: u8, device: u8, function: u8, offset: u16) -> Option<u64> { + let in_window = (self.start_bus..=self.end_bus).contains(&bus); + if !in_window || device > 31 || function > 7 || offset > 0xfff { + return None; + } + let bus = u64::from(bus - self.start_bus); + let function_offset = u64::from(device) << 15 | u64::from(function) << 12; + Some(self.base + (bus << 20 | function_offset | u64::from(offset))) + } +} + +/// The ECAM window of a validated MCFG table covering `segment` and `bus`. +pub fn mcfg_window(mcfg: &[u8], segment: u16, bus: u8) -> Result<Option<EcamWindow>, AcpiError> { + let mcfg = checked_table(mcfg, b"MCFG")?; + let entries = mcfg.get(MCFG_ENTRIES_OFFSET..).ok_or(AcpiError::Truncated)?; + Ok(entries + .as_chunks::<MCFG_ENTRY_LEN>() + .0 + .iter() + .map(|e| EcamWindow { + base: u64_at(e, 0).unwrap_or(0), + segment: u16::from_le_bytes([e[8], e[9]]), + start_bus: e[10], + end_bus: e[11], + }) + .find(|w| w.segment == segment && (w.start_bus..=w.end_bus).contains(&bus))) +} + #[cfg(test)] mod tests { use super::*; @@ -422,6 +466,42 @@ mod tests { assert_eq!(spcr_console(&bad), Err(AcpiError::BadChecksum)); } + fn mcfg(windows: &[(u64, u16, u8, u8)]) -> Vec<u8> { + let mut t = std::vec![0u8; MCFG_ENTRIES_OFFSET]; + t[..4].copy_from_slice(b"MCFG"); + for (base, segment, start, end) in windows { + t.extend_from_slice(&base.to_le_bytes()); + t.extend_from_slice(&segment.to_le_bytes()); + t.extend_from_slice(&[*start, *end, 0, 0, 0, 0]); + } + let len = t.len() as u32; + t[4..8].copy_from_slice(&len.to_le_bytes()); + let sum = t.iter().fold(0u8, |s, b| s.wrapping_add(*b)); + t[9] = 0u8.wrapping_sub(sum); + t + } + + #[test] + fn mcfg_finds_the_ecam_window_for_a_segment_and_bus() { + // QEMU virt high ECAM, plus a second segment starting at bus 0x80. + let table = mcfg(&[(0x40_1000_0000, 0, 0, 0xff), (0x6000_0000, 1, 0x80, 0x8f)]); + let qemu = mcfg_window(&table, 0, 0).unwrap().unwrap(); + assert_eq!(qemu.base, 0x40_1000_0000); + assert_eq!(qemu.config_address(0, 2, 0, 0x04), Some(0x40_1001_0004)); + let second = mcfg_window(&table, 1, 0x81).unwrap().unwrap(); + // Bus numbers count from the window's start bus. + assert_eq!(second.config_address(0x81, 1, 3, 0x10), Some(0x6010_b010)); + assert_eq!(second.config_address(0x90, 0, 0, 0), None, "past end bus"); + assert_eq!(second.config_address(0x80, 32, 0, 0), None); + assert_eq!(second.config_address(0x80, 0, 8, 0), None); + assert_eq!(second.config_address(0x80, 0, 0, 0x1000), None); + assert_eq!(mcfg_window(&table, 1, 0x7f).unwrap(), None); + assert_eq!(mcfg_window(&table, 2, 0).unwrap(), None); + let mut bad = table.clone(); + bad[50] ^= 1; + assert_eq!(mcfg_window(&bad, 0, 0), Err(AcpiError::BadChecksum)); + } + #[test] fn reads_xsdt_entry_addresses() { let mut xsdt = std::vec![0u8; SDT_HEADER_LEN]; diff --git a/crates/aienos-kernel/src/arch/aarch64.rs b/crates/aienos-kernel/src/arch/aarch64.rs index bef08b2d..a294f891 100644 --- a/crates/aienos-kernel/src/arch/aarch64.rs +++ b/crates/aienos-kernel/src/arch/aarch64.rs @@ -172,6 +172,59 @@ pub fn isb() { } } +/// Smallest data cache line in bytes, from CTR_EL0.DminLine (log2 of the +/// line size in 4-byte words). Maintenance loops must step by this, never by +/// a guess: `dc` acts on the one line holding the address it is given. +pub fn dcache_line_bytes() -> usize { + #[cfg(target_arch = "aarch64")] + { + let ctr: u64; + unsafe { + core::arch::asm!("mrs {0}, ctr_el0", out(reg) ctr, options(nomem, nostack, preserves_flags)); + } + 4 << ((ctr >> 16) & 0xf) + } + #[cfg(not(target_arch = "aarch64"))] + { + 64 + } +} + +/// Clean `[addr, addr + size)` to the point of coherency so a DMA master +/// sees what the CPU wrote. No-op on hosts. +pub fn clean_dcache_range(addr: usize, size: usize) { + #[cfg(target_arch = "aarch64")] + dcache_range(addr, size, |line| unsafe { + core::arch::asm!("dc cvac, {0}", in(reg) line, options(nostack, preserves_flags)); + }); + #[cfg(not(target_arch = "aarch64"))] + let _ = (addr, size); +} + +/// Clean and invalidate `[addr, addr + size)` so the next CPU read sees what +/// a DMA master wrote. Cleaning first means no CPU write in a shared line is +/// lost. No-op on hosts. +pub fn clean_invalidate_dcache_range(addr: usize, size: usize) { + #[cfg(target_arch = "aarch64")] + dcache_range(addr, size, |line| unsafe { + core::arch::asm!("dc civac, {0}", in(reg) line, options(nostack, preserves_flags)); + }); + #[cfg(not(target_arch = "aarch64"))] + let _ = (addr, size); +} + +#[cfg(target_arch = "aarch64")] +fn dcache_range(addr: usize, size: usize, op: impl Fn(usize)) { + let line = dcache_line_bytes(); + let end = addr.saturating_add(size); + let mut cursor = addr & !(line - 1); + while cursor < end { + op(cursor); + cursor += line; + } + dsb(); +} + /// Disable interrupts (set DAIF flags). #[inline(always)] pub fn disable_interrupts() { diff --git a/crates/aienos-kernel/src/usb/descriptor.rs b/crates/aienos-kernel/src/usb/descriptor.rs new file mode 100644 index 00000000..8b22cf2f --- /dev/null +++ b/crates/aienos-kernel/src/usb/descriptor.rs @@ -0,0 +1,164 @@ +//! USB descriptor parsing for keyboard bring-up (USB 2.0 section 9.6, HID +//! 1.11 appendix B): the device descriptor's control packet size and the +//! boot keyboard interface inside a configuration descriptor. + +const DESCRIPTOR_DEVICE: u8 = 1; +const DESCRIPTOR_CONFIGURATION: u8 = 2; +const DESCRIPTOR_INTERFACE: u8 = 4; +const DESCRIPTOR_ENDPOINT: u8 = 5; +const CLASS_HID: u8 = 3; +const SUBCLASS_BOOT: u8 = 1; +const PROTOCOL_KEYBOARD: u8 = 1; +const TRANSFER_INTERRUPT: u8 = 3; + +/// bMaxPacketSize0 from the first 8 bytes of a device descriptor. +pub fn control_max_packet(device_descriptor: &[u8]) -> Option<u8> { + match device_descriptor { + [len, DESCRIPTOR_DEVICE, _, _, _, _, _, size, ..] if *len >= 8 && *size > 0 => Some(*size), + _ => None, + } +} + +/// Where a boot-protocol keyboard's reports come from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BootKeyboard { + /// bConfigurationValue to pass to SET_CONFIGURATION. + pub configuration: u8, + pub interface: u8, + /// Interrupt-IN endpoint address, for example 0x81. + pub endpoint_address: u8, + pub max_packet: u16, + /// bInterval as the device states it. + pub interval: u8, +} + +/// First boot keyboard interface (class 3, subclass 1, protocol 1) with an +/// interrupt-IN endpoint in a configuration descriptor and what follows it. +/// Parsing stops at wTotalLength or the end of `bytes`, whichever is first, +/// and at any descriptor whose length is impossible. +pub fn find_boot_keyboard(bytes: &[u8]) -> Option<BootKeyboard> { + if bytes.len() < 9 || bytes[0] < 9 || bytes[1] != DESCRIPTOR_CONFIGURATION { + return None; + } + let total = usize::from(u16::from_le_bytes([bytes[2], bytes[3]])).min(bytes.len()); + let configuration = bytes[5]; + let mut interface = None; + let mut at = 0; + while at + 2 <= total { + let len = usize::from(bytes[at]); + if len < 2 || at + len > total { + return None; + } + let d = &bytes[at..at + len]; + match d[1] { + DESCRIPTOR_INTERFACE if len >= 9 => { + let keyboard = + d[5] == CLASS_HID && d[6] == SUBCLASS_BOOT && d[7] == PROTOCOL_KEYBOARD; + interface = keyboard.then_some(d[2]); + } + DESCRIPTOR_ENDPOINT if len >= 7 => { + let is_in = d[2] & 0x80 != 0; + if let (Some(interface), true, TRANSFER_INTERRUPT) = (interface, is_in, d[3] & 0x3) + { + return Some(BootKeyboard { + configuration, + interface, + endpoint_address: d[2], + max_packet: u16::from_le_bytes([d[4], d[5]]) & 0x7ff, + interval: d[6], + }); + } + } + _ => {} + } + at += len; + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Configuration descriptor QEMU 8.2.2 usb-kbd returned to the driver in + /// the QEMU keyboard test: config, interface, HID, endpoint 0x81. + const KEYBOARD: [u8; 34] = [ + 9, 2, 34, 0, 1, 1, 8, 0xa0, 50, // + 9, 4, 0, 0, 1, 3, 1, 1, 0, // + 9, 0x21, 0x11, 0x01, 0, 1, 0x22, 63, 0, // + 7, 5, 0x81, 3, 8, 0, 7, + ]; + + #[test] + fn finds_the_keyboard_interrupt_in_endpoint() { + assert_eq!( + find_boot_keyboard(&KEYBOARD), + Some(BootKeyboard { + configuration: 1, + interface: 0, + endpoint_address: 0x81, + max_packet: 8, + interval: 7, + }) + ); + } + + #[test] + fn skips_a_mouse_interface_and_out_endpoints_in_a_composite_device() { + let composite: [u8; 50] = [ + 9, 2, 50, 0, 2, 2, 0, 0xa0, 50, // + 9, 4, 0, 0, 1, 3, 1, 2, 0, // boot mouse + 7, 5, 0x81, 3, 4, 0, 10, // + 9, 4, 1, 0, 2, 3, 1, 1, 0, // boot keyboard + 7, 5, 0x02, 3, 8, 0, 10, // interrupt OUT (LEDs): not this + 9, 0x21, 0x11, 0x01, 0, 1, 0x22, 63, 0, + ]; + let mut with_endpoint = [0u8; 57]; + with_endpoint[..50].copy_from_slice(&composite); + with_endpoint[50..].copy_from_slice(&[7, 5, 0x83, 3, 8, 0, 4]); + with_endpoint[2] = 57; + let found = find_boot_keyboard(&with_endpoint).unwrap(); + assert_eq!((found.configuration, found.interface), (2, 1)); + assert_eq!(found.endpoint_address, 0x83); + assert_eq!(found.interval, 4); + assert_eq!( + find_boot_keyboard(&composite), + None, + "mouse only, no keyboard IN" + ); + } + + #[test] + fn stops_at_total_length_and_malformed_descriptors() { + let mut short_total = KEYBOARD; + short_total[2] = 27; // total length excludes the endpoint + assert_eq!(find_boot_keyboard(&short_total), None); + let mut zero_len = KEYBOARD; + zero_len[9] = 0; + assert_eq!(find_boot_keyboard(&zero_len), None, "no endless loop"); + let mut overrun = KEYBOARD; + overrun[27] = 200; + assert_eq!(find_boot_keyboard(&overrun), None); + assert_eq!(find_boot_keyboard(&KEYBOARD[..20]), None, "truncated read"); + assert_eq!( + find_boot_keyboard(&[9, 1, 0, 0]), + None, + "not a configuration" + ); + } + + #[test] + fn reads_the_control_packet_size_from_a_device_descriptor() { + assert_eq!( + control_max_packet(&[18, 1, 0x00, 0x02, 0, 0, 0, 64]), + Some(64) + ); + assert_eq!( + control_max_packet(&[18, 1, 0x10, 0x01, 0, 0, 0, 8, 0x27, 0x06]), + Some(8) + ); + assert_eq!(control_max_packet(&[18, 2, 0, 0, 0, 0, 0, 8]), None); + assert_eq!(control_max_packet(&[18, 1, 0, 0, 0, 0, 0, 0]), None); + assert_eq!(control_max_packet(&[18, 1, 0]), None); + } +} diff --git a/crates/aienos-kernel/src/usb/mod.rs b/crates/aienos-kernel/src/usb/mod.rs index 7e5e9071..aa4c67b6 100644 --- a/crates/aienos-kernel/src/usb/mod.rs +++ b/crates/aienos-kernel/src/usb/mod.rs @@ -3,8 +3,10 @@ //! After `ExitBootServices` the firmware's USB keyboard support is gone, so //! AIENOS must drive the keyboard itself. This module holds the parts that //! need no hardware: decoding HID boot-protocol keyboard reports into key -//! events and text, and the xHCI data structures a polled controller driver -//! builds on (ADR 0012, SEED-0A experiment #1 `input.keyboard.usb`). +//! events and text, parsing the descriptors that locate a boot keyboard, and +//! the xHCI data structures (TRBs, rings, contexts) a polled controller +//! driver builds on (ADR 0012, SEED-0A experiment #1 `input.keyboard.usb`). +pub mod descriptor; pub mod hid; pub mod xhci; diff --git a/crates/aienos-kernel/src/usb/xhci/mod.rs b/crates/aienos-kernel/src/usb/xhci/mod.rs index 280f51be..00e82aa2 100644 --- a/crates/aienos-kernel/src/usb/xhci/mod.rs +++ b/crates/aienos-kernel/src/usb/xhci/mod.rs @@ -1,7 +1,271 @@ -//! xHCI (USB 3 host controller) data structures for the polled keyboard -//! driver, host-tested against the xHCI 1.2 specification. Register access -//! and controller bring-up come later in the series and build on these. +//! xHCI (USB 3 host controller) building blocks for the polled keyboard +//! driver: PCI recognition, capability decoding, register layout, port +//! status helpers, TRBs, rings and input contexts. All pure data layout and +//! bookkeeping, host-tested against the xHCI 1.2 specification; register +//! access and controller bring-up follow in the next part of the series. pub mod context; pub mod ring; pub mod trb; + +/// PCI class code of an xHCI controller: serial bus (0x0c), USB (0x03), +/// programming interface xHCI (0x30). +pub const XHCI_CLASS_CODE: u32 = 0x0c_03_30; +/// PCI command register bits the driver needs: memory decode and DMA. +pub const PCI_COMMAND_MEMORY: u16 = 1 << 1; +pub const PCI_COMMAND_BUS_MASTER: u16 = 1 << 2; + +/// Base of an xHCI controller's register block from its PCI header: the +/// class/revision dword (offset 0x08) and BAR0/BAR1 (offsets 0x10, 0x14). +/// `None` for another device class, an I/O or unprogrammed BAR, or a failed +/// (all-ones) read. +pub fn xhci_mmio_base(class_revision: u32, bar0_low: u32, bar0_high: u32) -> Option<u64> { + if class_revision == u32::MAX || class_revision >> 8 != XHCI_CLASS_CODE { + return None; + } + let base = match bar0_low & 0x7 { + // 32-bit memory BAR. + 0b000 => u64::from(bar0_low & !0xf), + // 64-bit memory BAR (what the xHCI specification requires). + 0b100 => u64::from(bar0_high) << 32 | u64::from(bar0_low & !0xf), + _ => return None, + }; + (base != 0 && bar0_low != u32::MAX).then_some(base) +} + +/// Operational register offsets from the operational base (CAPLENGTH). +pub mod op { + pub const USBCMD: usize = 0x00; + pub const USBSTS: usize = 0x04; + pub const CRCR: usize = 0x18; + pub const DCBAAP: usize = 0x30; + pub const CONFIG: usize = 0x38; + /// PORTSC of root hub port `port` (1-based). + pub const fn portsc(port: u8) -> usize { + 0x400 + 0x10 * (port as usize - 1) + } + pub const USBCMD_RUN: u32 = 1 << 0; + pub const USBCMD_RESET: u32 = 1 << 1; + pub const USBSTS_HALTED: u32 = 1 << 0; + pub const USBSTS_HOST_ERROR: u32 = 1 << 2; + pub const USBSTS_NOT_READY: u32 = 1 << 11; +} + +/// Interrupter 0 register offsets from the runtime base (RTSOFF). Each +/// interrupter set is 32 bytes and set 0 starts at 0x20. +pub mod rt { + pub const IMAN: usize = 0x20; + pub const ERSTSZ: usize = 0x28; + pub const ERSTBA: usize = 0x30; + pub const ERDP: usize = 0x38; + /// ERDP Event Handler Busy, cleared by writing 1. + pub const ERDP_BUSY: u64 = 1 << 3; +} + +/// What the capability registers say about a controller. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Capabilities { + /// Offset of the operational registers (CAPLENGTH). + pub operational_offset: usize, + pub runtime_offset: usize, + pub doorbell_offset: usize, + pub max_slots: u8, + pub max_ports: u8, + /// Scratchpad pages the controller asks software to provide. + pub scratchpad_pages: u16, + /// HCCPARAMS1.AC64: the controller can reach 64-bit addresses. + pub addresses_64: bool, + /// Context entry size, 32 or 64 bytes (HCCPARAMS1.CSZ). + pub context_bytes: usize, +} + +impl Capabilities { + /// Decode CAPLENGTH/HCIVERSION (offset 0x00), HCSPARAMS1 (0x04), + /// HCSPARAMS2 (0x08), HCCPARAMS1 (0x10), DBOFF (0x14) and RTSOFF (0x18). + /// `None` when the block reads as absent or inconsistent. + pub fn decode( + version_length: u32, + hcsparams1: u32, + hcsparams2: u32, + hccparams1: u32, + dboff: u32, + rtsoff: u32, + ) -> Option<Self> { + let cap_length = (version_length & 0xff) as usize; + let version = version_length >> 16; + if version_length == u32::MAX || cap_length < 0x20 || version < 0x0090 { + return None; + } + let max_slots = (hcsparams1 & 0xff) as u8; + let max_ports = (hcsparams1 >> 24) as u8; + if max_slots == 0 || max_ports == 0 { + return None; + } + let scratchpad_hi = (hcsparams2 >> 21) & 0x1f; + let scratchpad_lo = (hcsparams2 >> 27) & 0x1f; + Some(Self { + operational_offset: cap_length, + runtime_offset: (rtsoff & !0x1f) as usize, + doorbell_offset: (dboff & !0x3) as usize, + max_slots, + max_ports, + scratchpad_pages: (scratchpad_hi << 5 | scratchpad_lo) as u16, + addresses_64: hccparams1 & 1 != 0, + context_bytes: if hccparams1 & (1 << 2) != 0 { 64 } else { 32 }, + }) + } +} + +/// PORTSC bits (xHCI 1.2 section 5.4.8). +pub mod portsc { + pub const CONNECTED: u32 = 1 << 0; + pub const ENABLED: u32 = 1 << 1; + pub const RESET: u32 = 1 << 4; + pub const POWER: u32 = 1 << 9; + pub const RESET_CHANGE: u32 = 1 << 21; + /// Change bits, all write-1-to-clear: CSC, PEC, WRC, OCC, PRC, PLC, CEC. + pub const CHANGES: u32 = 0x7f << 17; + /// Bits that keep their value when written back: read-only fields and + /// the preserved read/write ones (Linux calls this state "neutral"). + const READ_ONLY: u32 = 1 << 0 | 1 << 3 | 0xf << 10 | 1 << 30; + const PRESERVED: u32 = 0xf << 5 | 1 << 9 | 0x3 << 14 | 0x7 << 25; + + /// A write value that changes nothing: it keeps the preserved fields + /// and writes 0 to Port Enabled (writing 1 disables the port) and to + /// every write-1-to-clear change bit. + pub fn neutral(value: u32) -> u32 { + value & (READ_ONLY | PRESERVED) + } + + /// Port speed ID (bits 13:10). + pub fn speed(value: u32) -> u8 { + ((value >> 10) & 0xf) as u8 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recognizes_xhci_class_and_memory_bars() { + // qemu-xhci as read in the QEMU keyboard test: class 0x0c0330 rev 1, + // 64-bit BAR at 0x80_0000_4000. + assert_eq!( + xhci_mmio_base(0x0c03_3001, 0x0000_4004, 0x80), + Some(0x80_0000_4000) + ); + assert_eq!( + xhci_mmio_base(0x0c03_3000, 0x0000_000c, 0x6), + Some(0x6_0000_0000) + ); + // A 32-bit BAR ignores the next dword (it belongs to BAR1). + assert_eq!( + xhci_mmio_base(0x0c03_3000, 0xfe00_0000, 0x1234), + Some(0xfe00_0000) + ); + } + + #[test] + fn rejects_other_classes_io_and_unprogrammed_bars() { + assert!( + xhci_mmio_base(0x0c03_2000, 0x1000_0004, 0).is_none(), + "EHCI" + ); + assert!( + xhci_mmio_base(0x0c03_0000, 0x1000_0004, 0).is_none(), + "UHCI" + ); + assert!( + xhci_mmio_base(0x0600_0000, 0x1000_0004, 0).is_none(), + "bridge" + ); + assert!( + xhci_mmio_base(u32::MAX, 0x1000_0004, 0).is_none(), + "failed read" + ); + assert!( + xhci_mmio_base(0x0c03_3000, 0x0000_1001, 0).is_none(), + "I/O BAR" + ); + assert!( + xhci_mmio_base(0x0c03_3000, 0x1000_0002, 0).is_none(), + "below 1 MiB type" + ); + assert!( + xhci_mmio_base(0x0c03_3000, 0x0000_0004, 0).is_none(), + "unprogrammed" + ); + assert!(xhci_mmio_base(0x0c03_3000, u32::MAX, u32::MAX).is_none()); + } + + #[test] + fn capabilities_decode_qemu_xhci_registers() { + // Read from qemu-xhci in QEMU 8.2.2: CAPLENGTH 0x40, version 1.00, 64 + // slots, 16 interrupters, 8 ports, no scratchpad, AC64, 32-byte contexts. + let caps = Capabilities::decode( + 0x0100_0040, + 0x0800_1040, + 0x0000_000f, + 0x0008_7001, + 0x2000, + 0x1000, + ) + .unwrap(); + assert_eq!(caps.operational_offset, 0x40); + assert_eq!(caps.max_slots, 64); + assert_eq!(caps.max_ports, 8); + assert_eq!(caps.scratchpad_pages, 0); + assert!(caps.addresses_64); + assert_eq!(caps.context_bytes, 32); + assert_eq!( + (caps.doorbell_offset, caps.runtime_offset), + (0x2000, 0x1000) + ); + } + + #[test] + fn capabilities_decode_scratchpads_large_contexts_and_reject_absent_blocks() { + // Scratchpad count hi = 1 (bit 21), lo = 2 (bit 28): 34 pages. + let caps = Capabilities::decode( + 0x0110_0020, + 0x0400_0020, + 1 << 21 | 2 << 27, + 1 << 2, + 0x3003, + 0x201f, + ) + .unwrap(); + assert_eq!(caps.scratchpad_pages, 34); + assert_eq!(caps.context_bytes, 64); + assert!(!caps.addresses_64); + assert_eq!( + (caps.doorbell_offset, caps.runtime_offset), + (0x3000, 0x2000) + ); + assert!(Capabilities::decode(u32::MAX, u32::MAX, 0, 0, 0, 0).is_none()); + assert!(Capabilities::decode(0x0100_0010, 0x0800_1040, 0, 0, 0, 0).is_none()); + assert!( + Capabilities::decode(0x0100_0040, 0x0800_1000, 0, 0, 0, 0).is_none(), + "0 slots" + ); + } + + #[test] + fn portsc_neutral_never_disables_the_port_or_acks_changes() { + // Connected, enabled, powered, high speed, reset-change pending. + let value = portsc::CONNECTED + | portsc::ENABLED + | portsc::POWER + | 3 << 10 + | portsc::RESET_CHANGE + | 1 << 17; + let neutral = portsc::neutral(value); + assert_eq!(neutral & portsc::ENABLED, 0, "writing PED=1 would disable"); + assert_eq!(neutral & portsc::CHANGES, 0, "no change bit acknowledged"); + assert_ne!(neutral & portsc::POWER, 0, "power stays on"); + assert_eq!(portsc::speed(value), 3); + assert_eq!(op::portsc(1), 0x400); + assert_eq!(op::portsc(3), 0x420); + } +}