From 22b43de6dc1e45f0d454e4540de53392d83b0c12 Mon Sep 17 00:00:00 2001 From: Drew Galbraith Date: Sun, 18 May 2025 19:26:06 -0700 Subject: [PATCH] Rust XHCI Register Types. --- rust/Cargo.lock | 1 + rust/sys/voyageurs/Cargo.toml | 1 + rust/sys/voyageurs/src/main.rs | 2 + rust/sys/voyageurs/src/xhci/mod.rs | 1 + .../src/xhci/registers/capabilities.rs | 344 ++++++++++++ .../voyageurs/src/xhci/registers/doorbell.rs | 106 ++++ .../src/xhci/registers/host_controller.rs | 505 ++++++++++++++++++ .../xhci/registers/host_controller_port.rs | 415 ++++++++++++++ .../src/xhci/registers/interrupter.rs | 206 +++++++ rust/sys/voyageurs/src/xhci/registers/mod.rs | 15 + 10 files changed, 1596 insertions(+) create mode 100644 rust/sys/voyageurs/src/xhci/mod.rs create mode 100644 rust/sys/voyageurs/src/xhci/registers/capabilities.rs create mode 100644 rust/sys/voyageurs/src/xhci/registers/doorbell.rs create mode 100644 rust/sys/voyageurs/src/xhci/registers/host_controller.rs create mode 100644 rust/sys/voyageurs/src/xhci/registers/host_controller_port.rs create mode 100644 rust/sys/voyageurs/src/xhci/registers/interrupter.rs create mode 100644 rust/sys/voyageurs/src/xhci/registers/mod.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 432d9ba..35fccae 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -193,6 +193,7 @@ dependencies = [ name = "voyageurs" version = "0.1.0" dependencies = [ + "bitfield-struct", "mammoth", ] diff --git a/rust/sys/voyageurs/Cargo.toml b/rust/sys/voyageurs/Cargo.toml index e44085b..492a285 100644 --- a/rust/sys/voyageurs/Cargo.toml +++ b/rust/sys/voyageurs/Cargo.toml @@ -4,4 +4,5 @@ version = "0.1.0" edition = "2024" [dependencies] +bitfield-struct = "0.8.0" mammoth = { path = "../../lib/mammoth/" } diff --git a/rust/sys/voyageurs/src/main.rs b/rust/sys/voyageurs/src/main.rs index bcbd530..e9e5dd6 100644 --- a/rust/sys/voyageurs/src/main.rs +++ b/rust/sys/voyageurs/src/main.rs @@ -3,6 +3,8 @@ extern crate alloc; +mod xhci; + use mammoth::{debug, define_entry, zion::z_err_t}; define_entry!(); diff --git a/rust/sys/voyageurs/src/xhci/mod.rs b/rust/sys/voyageurs/src/xhci/mod.rs new file mode 100644 index 0000000..8993d24 --- /dev/null +++ b/rust/sys/voyageurs/src/xhci/mod.rs @@ -0,0 +1 @@ +pub mod registers; diff --git a/rust/sys/voyageurs/src/xhci/registers/capabilities.rs b/rust/sys/voyageurs/src/xhci/registers/capabilities.rs new file mode 100644 index 0000000..d9bfed2 --- /dev/null +++ b/rust/sys/voyageurs/src/xhci/registers/capabilities.rs @@ -0,0 +1,344 @@ +use bitfield_struct::bitfield; + +#[bitfield(u32)] +pub struct HostControllerCapabilitiesLengthAndVersion { + /// This register is used as an offset to add to register base to find the beginning of + /// the Operational Register Space. + #[bits(access=RO)] + pub cap_length: u8, + __: u8, + /// This is a two-byte register containing a BCD encoding of the xHCI specification + /// revision number supported by this host controller. The most significant byte of + /// this register represents a major revision and the least significant byte contains + /// the minor revision extensions. e.g. 0100h corresponds to xHCI version 1.0.0, or + /// 0110h corresponds to xHCI version 1.1.0, etc + #[bits(access=RO)] + pub hci_version: u16, +} + +#[bitfield(u32)] +pub struct HCSParams1 { + /// Number of Device Slots (MaxSlots). This field specifies the maximum number of Device + /// Context Structures and Doorbell Array entries this host controller can support. Valid values are + /// in the range of 1 to 255. The value of ‘0’ is reserved. + #[bits(access=RO)] + pub max_device_slots: u8, + + /// Number of Interrupters (MaxIntrs). This field specifies the number of Interrupters implemented + /// on this host controller. Each Interrupter may be allocated to a MSI or MSI-X vector and controls + /// its generation and moderation. + /// + /// The value of this field determines how many Interrupter Register Sets are addressable in the + /// Runtime Register Space (refer to section 5.5). Valid values are in the range of 1h to 400h. A ‘0’ in + /// this field is undefined. + #[bits(11, access=RO)] + pub max_interrupters: u16, + + #[bits(5)] + __: u8, + /// Number of Ports (MaxPorts). This field specifies the maximum Port Number value, i.e. the + /// highest numbered Port Register Set that are addressable in the Operational Register Space + /// (refer to Table 5-18). Valid values are in the range of 1h to FFh. + /// + /// The value in this field shall reflect the maximum Port Number value assigned by an xHCI + /// Supported Protocol Capability, described in section 7.2. Software shall refer to these capabilities + /// to identify whether a specific Port Number is valid, and the protocol supported by the + /// associated Port Register Set. + #[bits(access=RO)] + pub max_ports: u8, +} + +#[bitfield(u32)] +pub struct HCSParams2 { + /// Isochronous Scheduling Threshold (IST). Default = implementation dependent. The value in + /// this field indicates to system software the minimum distance (in time) that it is required to stay + /// ahead of the host controller while adding TRBs, in order to have the host controller process + /// them at the correct time. The value shall be specified in terms of number of + /// frames/microframes. + /// + /// If bit [3] of IST is cleared to '0', software can add a TRB no later than IST[2:0] Microframes + /// before that TRB is scheduled to be executed. + /// + /// If bit [3] of IST is set to '1', software can add a TRB no later than IST[2:0] Frames before that TRB + /// is scheduled to be executed. + /// + /// Refer to Section 4.14.2 for details on how software uses this information for scheduling + /// isochronous transfers. + #[bits(4, access=RO)] + pub isochronous_scheduling_threshold: u8, + /// Event Ring Segment Table Max (ERST Max). Default = implementation dependent. Valid values + /// are 0 – 15. This field determines the maximum value supported the Event Ring Segment Table + /// Base Size registers (5.5.2.3.1), where: + /// + /// The maximum number of Event Ring Segment Table entries = 2 ERST Max. + /// e.g. if the ERST Max = 7, then the xHC Event Ring Segment Table(s) supports up to 128 entries, + /// 15 then 32K entries, etc. + #[bits(4, access=RO)] + pub event_ring_segment_table_max: u8, + + #[bits(13)] + __: u16, + + /// Max Scratchpad Buffers (Max Scratchpad Bufs Hi). Default = implementation dependent. This + /// field indicates the high order 5 bits of the number of Scratchpad Buffers system software shall + /// reserve for the xHC. Refer to section 4.20 for more information. + #[bits(5, access=RO)] + max_scratchpad_buffers_hi: u16, + + /// Scratchpad Restore (SPR). Default = implementation dependent. If Max Scratchpad Buffers is > + /// ‘0’ then this flag indicates whether the xHC uses the Scratchpad Buffers for saving state when + /// executing Save and Restore State operations. If Max Scratchpad Buffers is = ‘0’ then this flag + /// shall be ‘0’. Refer to section 4.23.2 for more information. + /// + /// A value of ‘1’ indicates that the xHC requires the integrity of the Scratchpad Buffer space to be + /// maintained across power events. + /// + /// A value of ‘0’ indicates that the Scratchpad Buffer space may be freed and reallocated between + /// power events. + #[bits(access=RO)] + pub scratchpad_restore: bool, + + /// Max Scratchpad Buffers (Max Scratchpad Bufs Lo). Default = implementation dependent. Valid + /// values for Max Scratchpad Buffers (Hi and Lo) are 0-1023. This field indicates the low order 5 + /// bits of the number of Scratchpad Buffers system software shall reserve for the xHC. Refer to + /// section 4.20 for more information + #[bits(5, access=RO)] + max_scratchpad_buffers_lo: u16, +} + +impl HCSParams2 { + pub fn max_scratchpad_buffers(&self) -> u16 { + (self.max_scratchpad_buffers_hi()) << 5 | self.max_scratchpad_buffers_lo() + } +} + +#[bitfield(u32)] +pub struct HCSParams3 { + /// U1 Device Exit Latency. Worst case latency to transition a root hub Port Link State (PLS) from + /// U1 to U0. Applies to all root hub ports. + /// The following are permissible values: + /// + /// Value Description + /// 00h Zero + /// 01h Less than 1 μs + /// 02h Less than 2 μs. + /// … + /// 0Ah Less than 10 μs + #[bits(access=RO)] + pub u1_device_exit_latency: u8, + /// U2 Device Exit Latency. Worst case latency to transition from U2 to U0. Applies to all root hub + /// ports. + /// The following are permissible values: + /// Value Description + /// 0000h Zero + /// 0001h Less than 1 μs. + /// 0002h Less than 2 μs. + /// … + /// 07FFh Less than 2047 μs. + /// 0800-FFFFh Reserved + #[bits(access=RO)] + pub u2_device_exit_latency: u8, + __: u16, +} + +#[bitfield(u32)] +pub struct HCCParams1 { + /// 64-bit Addressing Capability (AC64). This flag documents the addressing range capability of + /// this implementation. The value of this flag determines whether the xHC has implemented the + /// high order 32 bits of 64 bit register and data structure pointer fields. Values for this flag have the + /// following interpretation: + /// + /// Value Description + /// 0 32-bit address memory pointers implemented + /// 1 64-bit address memory pointers implemented + /// + /// If 32-bit address memory pointers are implemented, the xHC shall ignore the high order 32 bits + /// of 64 bit data structure pointer fields, and system software shall ignore the high order 32 bits of + /// 64 bit xHC registers. + #[bits(access=RO)] + pub supports_64_bit: bool, + /// BW Negotiation Capability (BNC). This flag identifies whether the xHC has implemented the + /// Bandwidth Negotiation. Values for this flag have the following interpretation: + /// + /// Value Description + /// 0 BW Negotiation not implemented + /// 1 BW Negotiation implemented + /// + /// Refer to section 4.16 for more information on Bandwidth Negotiation. + #[bits(access=RO)] + pub bandwidth_negotiation: bool, + /// Context Size (CSZ). If this bit is set to ‘1’, then the xHC uses 64 byte Context data structures. If + /// this bit is cleared to ‘0’, then the xHC uses 32 byte Context data structures. + /// Note: This flag does not apply to Stream Contexts. + #[bits(access=RO)] + pub context_size: bool, + /// Port Power Control (PPC). This flag indicates whether the host controller implementation + /// includes port power control. A ‘1’ in this bit indicates the ports have port power switches. A ‘0’ in + /// this bit indicates the port do not have port power switches. The value of this flag affects the + /// functionality of the PP flag in each port status and control register (refer to Section 5.4.8) + #[bits(access=RO)] + pub port_power_control: bool, + /// Port Indicators (PIND). This bit indicates whether the xHC root hub ports support port indicator + /// control. When this bit is a ‘1’, the port status and control registers include a read/writeable field + /// for controlling the state of the port indicator. Refer to Section 5.4.8 for definition of the Port + /// Indicator Control field. + #[bits(access=RO)] + pub port_indicators: bool, + /// Light HC Reset Capability (LHRC). This flag indicates whether the host controller implementation + /// supports a Light Host Controller Reset. A ‘1’ in this bit indicates that Light Host Controller Reset is + /// supported. A ‘0’ in this bit indicates that Light Host Controller Reset is not supported. The value + /// of this flag affects the functionality of the Light Host Controller Reset (LHCRST) flag in the + /// USBCMD register (refer to Section 5.4.1). + #[bits(access=RO)] + pub light_hc_reset_capability: bool, + /// Latency Tolerance Messaging Capability (LTC). This flag indicates whether the host controller + /// implementation supports Latency Tolerance Messaging (LTM). A ‘1’ in this bit indicates that LTM + /// is supported. A ‘0’ in this bit indicates that LTM is not supported. Refer to section 4.13.1 for more + /// information on LTM + #[bits(access=RO)] + pub latency_tolerance_messaging_capability: bool, + /// No Secondary SID Support (NSS). This flag indicates whether the host controller + /// implementation supports Secondary Stream IDs. A ‘1’ in this bit indicates that Secondary Stream + /// ID decoding is not supported. A ‘0’ in this bit indicates that Secondary Stream ID decoding is + /// supported. (refer to Sections 4.12.2 and 6.2.3) + #[bits(access=RO)] + pub no_secondary_sid_support: bool, + /// Parse All Event Data (PAE). This flag indicates whether the host controller implementation + /// Parses all Event Data TRBs while advancing to the next TD after a Short Packet, or it skips all but + /// the first Event Data TRB. A ‘1’ in this bit indicates that all Event Data TRBs are parsed. A ‘0’ in this + /// bit indicates that only the first Event Data TRB is parsed (refer to section 4.10.1.1). + #[bits(access=RO)] + pub parse_all_event_data: bool, + /// Stopped - Short Packet Capability (SPC). This flag indicates that the host controller + /// implementation is capable of generating a Stopped - Short Packet Completion Code. Refer to + /// section 4.6.9 for more information + #[bits(access=RO)] + pub stopped_short_packet_capability: bool, + /// Stopped EDTLA Capability (SEC). This flag indicates that the host controller implementation + /// Stream Context support a Stopped EDTLA field. Refer to sections 4.6.9, 4.12, and 6.4.4.1 for more + /// information. + /// Stopped EDTLA Capability support (i.e. SEC = '1') shall be mandatory for all xHCI 1.1 and xHCI 1.2 + /// compliant xHCs. + #[bits(access=RO)] + pub stopped_edtla_capability: bool, + /// Contiguous Frame ID Capability (CFC). This flag indicates that the host controller + /// implementation is capable of matching the Frame ID of consecutive Isoch TDs. Refer to section + /// 4.11.2.5 for more information. + #[bits(access=RO)] + pub contiguous_frame_id_capability: bool, + /// Maximum Primary Stream Array Size (MaxPSASize). This fields identifies the maximum size + /// Primary Stream Array that the xHC supports. The Primary Stream Array size = 2MaxPSASize+1. Valid + /// MaxPSASize values are 0 to 15, where ‘0’ indicates that Streams are not supported + #[bits(4, access=RO)] + pub maximum_primary_stream_array_size: u8, + /// xHCI Extended Capabilities Pointer (xECP). This field indicates the existence of a capabilities list. + /// The value of this field indicates a relative offset, in 32-bit words, from Base to the beginning of + /// the first extended capability. + /// + /// For example, using the offset of Base is 1000h and the xECP value of 0068h, we can calculated + /// the following effective address of the first extended capability: + /// 1000h + (0068h << 2) -> 1000h + 01A0h -> 11A0h + #[bits(access=RO)] + pub xhci_extended_capabilities_pointer: u16, +} + +#[bitfield(u32)] +pub struct HCCParams2 { + /// U3 Entry Capability (U3C) - RO. This bit indicates whether the xHC Root Hub ports support port + /// Suspend Complete notification. When this bit is '1', PLC shall be asserted on any transition of + /// PLS to the U3 State. Refer to section 4.15.1 for more information. + #[bits(access=RO)] + pub u3_entry_capability: bool, + /// Configure Endpoint Command Max Exit Latency Too Large Capability (CMC) - RO. This bit + /// indicates whether a Configure Endpoint Command is capable of generating a Max Exit Latency + /// Too Large Capability Error. When this bit is '1', a Max Exit Latency Too Large Capability Error + /// may be returned by a Configure Endpoint Command. When this bit is '0', a Max Exit Latency Too + /// Large Capability Error shall not be returned by a Configure Endpoint Command. This capability + /// is enabled by the CME flag in the USBCMD register. Refer to sections 4.23.5.2 and 5.4.1 for more + /// information. + #[bits(access=RO)] + pub configure_endpoint_command_max_exit_latency_too_large_capability: bool, + /// Force Save Context Capability (FSC) - RO. This bit indicates whether the xHC supports the + /// Force Save Context Capability. When this bit is '1', the Save State operation shall save any + /// cached Slot, Endpoint, Stream or other Context information to memory. Refer to + /// Implementation Note “FSC and Context handling by Save and Restore”, and sections 4.23.2 and + /// 5.4.1 for more information. + #[bits(access=RO)] + pub force_save_context_capability: bool, + /// Compliance Transition Capability (CTC) - RO. This bit indicates whether the xHC USB3 Root + /// Hub ports support the Compliance Transition Enabled (CTE) flag. When this bit is ‘1’, USB3 Root + /// Hub port state machine transitions to the Compliance substate shall be explicitly enabled + /// software. When this bit is ‘0’, USB3 Root Hub port state machine transitions to the Compliance + /// substate are automatically enabled. Refer to section 4.19.1.2.4.1 for more information. + #[bits(access=RO)] + pub compliance_transition_capability: bool, + /// Large ESIT Payload Capability (LEC) - RO. This bit indicates whether the xHC supports ESIT + /// Payloads greater than 48K bytes. When this bit is ‘1’, ESIT Payloads greater than 48K bytes are + /// supported. When this bit is ‘0’, ESIT Payloads greater than 48K bytes are not supported. Refer to + /// section 6.2.3.8 for more information. + #[bits(access=RO)] + pub large_esit_payload_capability: bool, + /// Configuration Information Capability (CIC) - RO. This bit indicates if the xHC supports + /// extended Configuration Information. When this bit is 1, the Configuration Value, Interface + /// Number, and Alternate Setting fields in the Input Control Context are supported. When this bit is + /// 0, the extended Input Control Context fields are not supported. Refer to section 6.2.5.1 for more + /// information. + #[bits(access=RO)] + pub configuration_information_capability: bool, + /// Extended TBC Capability78 (ETC) - RO. This bit indicates if the TBC field in an Isoch TRB + /// supports the definition of Burst Counts greater than 65535 bytes. When this bit is ‘1’, the + /// Extended EBC capability is supported by the xHC. When this bit is ‘0’, it is not. Refer to section + /// 4.11.2.3 for more information. + #[bits(access=RO)] + pub extended_tbc_capability: bool, + /// Extended TBC TRB Status Capability (ETC_TSC) - RO. This bit indicates if the TBC/TRBSts field + /// in an Isoch TRB indicates additional information regarding TRB in the TD. When this bit is ‘1’, the + /// Isoch TRB TD Size/TBC field presents TBC value and TBC/TRBSts field presents the TRBSts + /// value. When this bit is ‘0’ then the ETC/ETE values defines the TD Size/TBC field and TBC/RsvdZ + /// field. This capability shall be enabled only if LEC = ‘1’ and ETC=’1’. Refer to section 4.11.2.3 for + /// more information. + #[bits(access=RO)] + pub extended_tbc_trb_status_capability: bool, + /// Get/Set Extended Property Capability (GSC) – RO. This bit indicates support for the Set + /// Extended Property and Get Extended Property commands. When this bit is ‘1’, the xHC supports + /// the Get Extended Property and Set Extended Property commands defined in section 4.6.17 and + /// section 4.6.18. When this bit is ‘0’, the xHC does not support the Get Extended Property and Set + /// Extended Property commands and the xHC does not support any of the associated Extended + /// Capabilities. + /// + /// This bit shall only be set to ‘1’ if the xHC supports one or more extended capabilities that + /// require the Get Extended Property and Set Extended Property commands. + #[bits(access=RO)] + pub get_set_extended_property_capability: bool, + /// Virtualization Based Trusted I/O Capability (VTC) – RO. This bit when set to 1, indicates that + /// the xHC supports the Virtualization based Trusted IO (VTIO) Capability. When this bit is 0, the + /// VTIO Capability is not supported. This capability is enabled by the VTIOE flag in the USBCMD + /// register. + #[bits(access=RO)] + pub virtualization_based_trusted_io_capability: bool, + + #[bits(22)] + __: u32, +} + +/// XHCI Spec Section 5.3 +/// Note that for 64 bit implementations, the controller requires qword (32bit) accesses. +/// Hence the grouping of parameters here. +/// +/// These registers are located at the addresses specified in BAR0 and BAR1 in the PCI Header. +#[repr(C)] +#[derive(Copy, Clone)] +pub struct HostControllerCapabilities { + pub cap_length_and_version: HostControllerCapabilitiesLengthAndVersion, + pub params_1: HCSParams1, + pub params_2: HCSParams2, + pub params_3: HCSParams3, + pub cap_params_1: HCCParams1, + /// This register defines the offset of the Doorbell Array base address from the Base. (RO) + pub doorbell_offset: u32, + /// This register defines the offset of the xHCI Runtime Registers from the Base. + pub runtime_register_space_offset: u32, + pub cap_params_2: HCCParams2, +} + +const _: () = assert!(size_of::() == 0x20); diff --git a/rust/sys/voyageurs/src/xhci/registers/doorbell.rs b/rust/sys/voyageurs/src/xhci/registers/doorbell.rs new file mode 100644 index 0000000..9427efe --- /dev/null +++ b/rust/sys/voyageurs/src/xhci/registers/doorbell.rs @@ -0,0 +1,106 @@ +use core::ptr::NonNull; + +use alloc::boxed::Box; +use bitfield_struct::bitfield; +use volatile::VolatileRef; + +/// The Doorbell Array is organized as an array of up to 256 Doorbell Registers. One +/// 32-bit Doorbell Register is defined in the array for each Device Slot. System +/// software utilizes the Doorbell Register to notify the xHC that it has Device Slot +/// related work for the xHC to perform. +/// +/// The number of Doorbell Registers implemented by a particular instantiation of a +/// host controller is documented in the Number of Device Slots (MaxSlots) field of +/// the HCSPARAMS1 register (section 5.3.3). +/// +/// These registers are pointed to by the Doorbell Offset Register (DBOFF) in the +/// xHC Capability register space. The Doorbell Array base address shall be Dword +/// 430 aligned and is calculated by adding the value in the DBOFF register (section +/// 5.3.7) to “Base” (the base address of the xHCI Capability register address space). +/// Refer to section 4.7 for more information on Doorbell registers. +#[bitfield(u32)] +pub struct Doorbell { + /// DB Target – RW. Doorbell Target. This field defines the target of the doorbell reference. The + /// table below defines the xHC notification that is generated by ringing the doorbell. Note that + /// Doorbell Register 0 is dedicated to Command Ring and decodes this field differently than the + /// other Doorbell Registers. + /// + /// Device Context Doorbells (1-255) + /// Value Definition + /// 0 Reserved + /// 1 Control EP 0 Enqueue Pointer Update + /// 2 EP 1 OUT Enqueue Pointer Update + /// 3 EP 1 IN Enqueue Pointer Update + /// 4 EP 2 OUT Enqueue Pointer Update + /// 5 EP 2 IN Enqueue Pointer Update + /// … ... + /// 30 EP 15 OUT Enqueue Pointer Update + /// 31 EP 15 IN Enqueue Pointer Update + /// 32:247 Reserved + /// 248:255 Vendor Defined + /// + /// Host Controller Doorbell (0) + /// Value Definition + /// 0 Command Doorbell + /// 1:247 Reserved + /// 248:255 Vendor Defined + /// + /// This field returns ‘0’ when read and should be treated as “undefined” by software. + /// When the Command Doorbell is written, the DB Stream ID field shall be cleared to ‘0’. + db_target: u8, + _reserved: u8, + + /// DB Stream ID - RW. Doorbell Stream ID. If the endpoint of a Device Context Doorbell defines + /// Streams, then this field shall be used to identify which Stream of the endpoint the doorbell + /// reference is targeting. System software is responsible for ensuring that the value written to this + /// field is valid. + /// + /// If the endpoint defines Streams (MaxPStreams > 0), then 0, 65535 (No Stream) and 65534 + /// (Prime) are reserved Stream ID values and shall not be written to this field. + /// + /// If the endpoint does not define Streams (MaxPStreams = 0) and a non-'0' value is written to this + /// field, the doorbell reference shall be ignored. + /// + /// This field only applies to Device Context Doorbells and shall be cleared to ‘0’ for Host Controller + /// Command Doorbells. + /// + /// This field returns ‘0’ when read + db_stream_id: u16, +} + +#[repr(transparent)] +pub struct DoorbellPointer(VolatileRef<'static, Doorbell>); + +impl DoorbellPointer { + // Construct a new doorbell pointer. + fn new(doorbell: NonNull) -> Self { + // SAFETY: + // - We allocate this memory in the create + Self(unsafe { VolatileRef::new(doorbell) }) + } + + pub fn create_command_and_slots( + doorbell_physical: usize, + max_slots: u8, + ) -> (Self, Box<[Self]>) { + // Add one for the command doorbell. + let doorbell_cnt = max_slots as usize + 1; + let doorbell_array_size = size_of::() * doorbell_cnt; + let doorbells: NonNull = + mammoth::mem::map_direct_physical_and_leak(doorbell_physical, doorbell_array_size); + let first = DoorbellPointer::new(doorbells); + let remainder = (1..=max_slots) + .map(|offset| { + // SAFETY: We just allocated the array of this size above. + DoorbellPointer::new(unsafe { doorbells.add(offset as usize) }) + }) + .collect(); + (first, remainder) + } + + pub fn ring(&mut self, target: u8) { + self.0 + .as_mut_ptr() + .write(Doorbell::new().with_db_target(target)) + } +} diff --git a/rust/sys/voyageurs/src/xhci/registers/host_controller.rs b/rust/sys/voyageurs/src/xhci/registers/host_controller.rs new file mode 100644 index 0000000..34037d6 --- /dev/null +++ b/rust/sys/voyageurs/src/xhci/registers/host_controller.rs @@ -0,0 +1,505 @@ +use core::ptr::NonNull; + +use alloc::vec::Vec; +use bitfield_struct::bitfield; +use mammoth::{mem::map_direct_physical_and_leak, sync::Mutex}; +use volatile::{VolatilePtr, VolatileRef, map_field}; + +use crate::xhci::registers::{ + HostControllerCapabilities, HostControllerUsbPort, PortStatusAndControl, +}; + +#[bitfield(u32)] +pub struct UsbCommand { + /// Run/Stop (R/S) – RW. Default = ‘0’. ‘1’ = Run. ‘0’ = Stop. When set to a ‘1’, the xHC proceeds with + /// execution of the schedule. The xHC continues execution as long as this bit is set to a ‘1’. When + /// this bit is cleared to ‘0’, the xHC completes any current or queued commands or TDs, and any + /// USB transactions associated with them, then halts. + /// + /// Refer to section 5.4.1.1 for more information on how R/S shall be managed. + /// + /// The xHC shall halt within 16 ms. after software clears the Run/Stop bit if the above conditions + /// have been met. + /// + /// The HCHalted (HCH) bit in the USBSTS register indicates when the xHC has finished its pending + /// pipelined transactions and has entered the stopped state. Software shall not write a ‘1’ to this + /// flag unless the xHC is in the Halted state (i.e. HCH in the USBSTS register is ‘1’). Doing so may + /// yield undefined results. Writing a ‘0’ to this flag when the xHC is in the Running state (i.e. HCH = + /// ‘0’) and any Event Rings are in the Event Ring Full state (refer to section 4.9.4) may result in lost + /// events. + /// + /// When this register is exposed by a Virtual Function (VF), this bit only controls the run state of + /// the xHC instance presented by the selected VF. Refer to section 8 for more information. + pub run_stop: bool, + /// Host Controller Reset (HCRST) – RW. Default = ‘0’. This control bit is used by software to reset + /// the host controller. The effects of this bit on the xHC and the Root Hub registers are similar to a + /// Chip Hardware Reset. + /// + /// When software writes a ‘1’ to this bit, the Host Controller resets its internal pipelines, timers, + /// counters, state machines, etc. to their initial value. Any transaction currently in progress on the + /// USB is immediately terminated. A USB reset shall not be driven on USB2 downstream ports, + /// however a Hot or Warm Reset79 shall be initiated on USB3 Root Hub downstream ports. + /// + /// PCI Configuration registers are not affected by this reset. All operational registers, including port + /// registers and port state machines are set to their initial values. Software shall reinitialize the + /// host controller as described in Section 4.2 in order to return the host controller to an + /// operational state. + /// + /// This bit is cleared to ‘0’ by the Host Controller when the reset process is complete. Software + /// cannot terminate the reset process early by writing a ‘0’ to this bit and shall not write any xHC + /// Operational or Runtime registers until while HCRST is ‘1’. Note, the completion of the xHC reset + /// process is not gated by the Root Hub port reset process. + /// + /// Software shall not set this bit to ‘1’ when the HCHalted (HCH) bit in the USBSTS register is a ‘0’. + /// Attempting to reset an actively running host controller may result in undefined behavior. + /// + /// When this register is exposed by a Virtual Function (VF), this bit only resets the xHC instance + /// presented by the selected VF. Refer to section 8 for more information + pub host_controller_reset: bool, + /// Interrupter Enable (INTE) – RW. Default = ‘0’. This bit provides system software with a means of + /// enabling or disabling the host system interrupts generated by Interrupters. When this bit is a ‘1’, + /// then Interrupter host system interrupt generation is allowed, e.g. the xHC shall issue an interrupt + /// at the next interrupt threshold if the host system interrupt mechanism (e.g. MSI, MSI-X, etc.) is + /// enabled. The interrupt is acknowledged by a host system interrupt specific mechanism. + /// + /// When this register is exposed by a Virtual Function (VF), this bit only enables the set of + /// Interrupters assigned to the selected VF. Refer to section 7.7.2 for more information. + pub interrupter_enable: bool, + /// Host System Error Enable (HSEE) – RW. Default = ‘0’. When this bit is a ‘1’, and the HSE bit in + /// the USBSTS register is a ‘1’, the xHC shall assert out-of-band error signaling to the host. The + /// signaling is acknowledged by software clearing the HSE bit. Refer to section 4.10.2.6 for more + /// information. + /// When this register is exposed by a Virtual Function (VF), the effect of the assertion of this bit on + /// the Physical Function (PF0) is determined by the VMM. Refer to section 8 for more information + pub host_system_error_enable: bool, + #[bits(3)] + __: u8, + /// Light Host Controller Reset (LHCRST) – RO or RW. Optional normative. Default = ‘0’. If the Light + /// HC Reset Capability (LHRC) bit in the HCCPARAMS1 register is ‘1’, then this flag allows the driver + /// to reset the xHC without affecting the state of the ports. + /// + /// A system software read of this bit as ‘0’ indicates the Light Host Controller Reset has completed + /// and it is safe for software to re-initialize the xHC. A software read of this bit as a ‘1’ indicates the + /// Light Host Controller Reset has not yet completed. + /// + /// If not implemented, a read of this flag shall always return a ‘0’. + /// + /// All registers in the Aux Power well shall maintain the values that had been asserted prior to the + /// Light Host Controller Reset. Refer to section 4.23.1 for more information. + /// + /// When this register is exposed by a Virtual Function (VF), this bit only generates a Light Reset to + /// the xHC instance presented by the selected VF, e.g. Disable the VFs’ device slots and set the + /// associated VF Run bit to Stopped. Refer to section 8 for more information. + pub light_host_controller_reset: bool, + /// Controller Save State (CSS) - RW. Default = ‘0’. When written by software with ‘1’ and HCHalted + /// (HCH) = ‘1’, then the xHC shall save any internal state (that may be restored by a subsequent + /// Restore State operation) and if FSC = '1' any cached Slot, Endpoint, Stream, or other Context + /// information (so that software may save it). When written by software with ‘1’ and HCHalted + /// (HCH) = ‘0’, or written with ‘0’, no Save State operation shall be performed. This flag always + /// returns ‘0’ when read. Refer to the Save State Status (SSS) flag in the USBSTS register for + /// information on Save State completion. Refer to section 4.23.2 for more information on xHC + /// + /// Save/Restore operation. Note that undefined behavior may occur if a Save State operation is + /// initiated while Restore State Status (RSS) = ‘1’. + /// + /// When this register is exposed by a Virtual Function (VF), this bit only controls saving the state of + /// the xHC instance presented by the selected VF. Refer to section 8 for more information. + pub controller_save_state: bool, + /// Controller Restore State (CRS) - RW. Default = ‘0’. When set to ‘1’, and HCHalted (HCH) = ‘1’, + /// then the xHC shall perform a Restore State operation and restore its internal state. When set to + /// ‘1’ and Run/Stop (R/S) = ‘1’ or HCHalted (HCH) = ‘0’, or when cleared to ‘0’, no Restore State + /// operation shall be performed. This flag always returns ‘0’ when read. Refer to the Restore State + /// Status (RSS) flag in the USBSTS register for information on Restore State completion. Refer to + /// section 4.23.2 for more information. Note that undefined behavior may occur if a Restore State + /// operation is initiated while Save State Status (SSS) = ‘1’. + /// When this register is exposed by a Virtual Function (VF), this bit only controls restoring the state + /// of the xHC instance presented by the selected VF. Refer to section 8 for more information. + pub controller_restore_state: bool, + /// Enable Wrap Event (EWE) - RW. Default = ‘0’. When set to ‘1’, the xHC shall generate a MFINDEX + /// Wrap Event every time the MFINDEX register transitions from 03FFFh to 0. When cleared to ‘0’ + /// no MFINDEX Wrap Events are generated. Refer to section 4.14.2 for more information. + /// + /// When this register is exposed by a Virtual Function (VF), the generation of MFINDEX Wrap + /// Events to VFs shall be emulated by the VMM. + pub enable_wrap_event: bool, + /// Enable U3 MFINDEX Stop (EU3S) - RW. Default = ‘0’. When set to ‘1’, the xHC may stop the + /// MFINDEX counting action if all Root Hub ports are in the U3, Disconnected, Disabled, or + /// Powered-off state. When cleared to ‘0’ the xHC may stop the MFINDEX counting action if all + /// Root Hub ports are in the Disconnected, Disabled, Training, or Powered-off state. Refer to + /// section 4.14.2 for more information + pub enable_u3_mfindex_stop: bool, + ___: bool, + /// CEM Enable (CME) - RW. Default = '0'. When set to '1', a Max Exit Latency Too Large Capability + /// Error may be returned by a Configure Endpoint Command. When cleared to '0', a Max Exit + /// Latency Too Large Capability Error shall not be returned by a Configure Endpoint Command. + /// This bit is Reserved if CMC = ‘0’. Refer to section 4.23.5.2.2 for more information. + pub cem_enable: bool, + /// Extended TBC Enable (ETE). This flag indicates that the host controller implementation is + /// enabled to support Transfer Burst Count (TBC) values greater that 4 in isoch TDs. When this bit + /// is ‘1’, the Isoch TRB TD Size/TBC field presents the TBC value, and the TBC/RsvdZ field is RsvdZ. + /// When this bit is ‘0’, the TDSize/TCB field presents the TD Size value, and the TBC/RsvdZ field + /// presents the TBC value. This bit may be set only if ETC = ‘1’. Refer to section 4.11.2.3 for more + /// information. + pub extended_tbc_enable: bool, + /// Extended TBC TRB Status Enable (TSC_EN). This flag indicates that the host controller + /// implementation is enabled to support ETC_TSC capability. When this is ‘1’, TRBSts field in the + /// TRB updated to indicate if it is last transfer TRB in the TD. This bit may be set only if + /// ETC_TSC=’1’. Refer to section 4.11.2.3 for more information. + pub extended_tbc_trb_status_enable: bool, + /// VTIO Enable (VTIOE) – RW. Default = ‘0’. When set to ‘1’, XHCI HW will enable its VTIO + /// capability and begin to use the information provided via that VTIO Registers to determine its + /// DMA-ID. When cleared to ‘0’, XHCI HW will use the Primary DMA-ID for all accesses. This bit + /// may be set only if VTC = ‘1’. + pub vtio_enable: bool, + #[bits(15)] + ____: u16, +} + +#[bitfield(u32)] +pub struct UsbStatus { + /// HCHalted (HCH) – RO. Default = ‘1’. This bit is a ‘0’ whenever the Run/Stop (R/S) bit is a ‘1’. The + /// xHC sets this bit to ‘1’ after it has stopped executing as a result of the Run/Stop (R/S) bit being + /// cleared to ‘0’, either by software or by the xHC hardware (e.g. internal error). + /// + /// If this bit is '1', then SOFs, microSOFs, or Isochronous Timestamp Packets (ITP) shall not be + /// generated by the xHC, and any received Transaction Packet shall be dropped. + /// + /// When this register is exposed by a Virtual Function (VF), this bit only reflects the Halted state of + /// the xHC instance presented by the selected VF. Refer to section 8 for more information + #[bits(access=RO)] + pub host_controller_halted: bool, + __: bool, + /// Host System Error (HSE) – RW1C. Default = ‘0’. The xHC sets this bit to ‘1’ when a serious error + /// is detected, either internal to the xHC or during a host system access involving the xHC module. + /// (In a PCI system, conditions that set this bit to ‘1’ include PCI Parity error, PCI Master Abort, and + /// PCI Target Abort.) When this error occurs, the xHC clears the Run/Stop (R/S) bit in the USBCMD + /// register to prevent further execution of the scheduled TDs. If the HSEE bit in the USBCMD + /// register is a ‘1’, the xHC shall also assert out-of-band error signaling to the host. Refer to section + /// 4.10.2.6 for more information. + /// When this register is exposed by a Virtual Function (VF), the assertion of this bit affects all VFs + /// and reflects the Host System Error state of the Physical Function (PF0). Refer to section 8 for + /// more information. + pub host_system_error: bool, + /// Event Interrupt (EINT) – RW1C. Default = ‘0’. The xHC sets this bit to ‘1’ when the Interrupt + /// Pending (IP) bit of any Interrupter transitions from ‘0’ to ‘1’. Refer to section 7.1.2 for use. + /// Software that uses EINT shall clear it prior to clearing any IP flags. A race condition may occur if + /// software clears the IP flags then clears the EINT flag, and between the operations another IP ‘0’ + /// to '1' transition occurs. In this case the new IP transition shall be lost. + /// When this register is exposed by a Virtual Function (VF), this bit is the logical 'OR' of the IP bits + /// for the Interrupters assigned to the selected VF. And it shall be cleared to ‘0’ when all associated + /// interrupter IP bits are cleared, i.e. all the VF’s Interrupter Event Ring(s) are empty. Refer to + /// section 8 for more information + pub event_interrupt: bool, + /// Port Change Detect (PCD) – RW1C. Default = ‘0’. The xHC sets this bit to a ‘1’ when any port has + /// a change bit transition from a ‘0’ to a ‘1’. + /// + /// This bit is allowed to be maintained in the Aux Power well. Alternatively, it is also acceptable + /// that on a D3 to D0 transition of the xHC, this bit is loaded with the OR of all of the PORTSC + /// change bits. Refer to section 4.19.3. + /// + /// This bit provides system software an efficient means of determining if there has been Root Hub + /// port activity. Refer to section 4.15.2.3 for more information. + /// + /// When this register is exposed by a Virtual Function (VF), the VMM determines the state of this + /// bit as a function of the Root Hub Ports associated with the Device Slots assigned to the selected + /// VF. Refer to section 8 for more information. + pub port_change_detect: bool, + #[bits(3)] + __: u8, + /// Save State Status (SSS) - RO. Default = ‘0’. When the Controller Save State (CSS) flag in the + /// USBCMD register is written with ‘1’ this bit shall be set to ‘1’ and remain 1 while the xHC saves + /// its internal state. When the Save State operation is complete, this bit shall be cleared to ‘0’. + /// Refer to section 4.23.2 for more information. + /// + /// When this register is exposed by a Virtual Function (VF), the VMM determines the state of this + /// bit as a function of the saving the state for the selected VF. Refer to section 8 for more + /// information. + #[bits(access=RO)] + pub save_state_status: bool, + /// Restore State Status (RSS) - RO. Default = ‘0’. When the Controller Restore State (CRS) flag in + /// the USBCMD register is written with ‘1’ this bit shall be set to ‘1’ and remain 1 while the xHC + /// restores its internal state. When the Restore State operation is complete, this bit shall be + /// cleared to ‘0’. Refer to section 4.23.2 for more information. + /// + /// When this register is exposed by a Virtual Function (VF), the VMM determines the state of this + /// bit as a function of the restoring the state for the selected VF. Refer to section 8 for more + /// information. + #[bits(access=RO)] + pub restore_state_status: bool, + /// Save/Restore Error (SRE) - RW1C. Default = ‘0’. If an error occurs during a Save or Restore + /// operation this bit shall be set to ‘1’. This bit shall be cleared to ‘0’ when a Save or Restore + /// operation is initiated or when written with ‘1’. Refer to section 4.23.2 for more information. + /// When this register is exposed by a Virtual Function (VF), the VMM determines the state of this + /// bit as a function of the Save/Restore completion status for the selected VF. Refer to section 8 + /// for more information. + pub save_restore_error: bool, + /// Controller Not Ready (CNR) – RO. Default = ‘1’. ‘0’ = Ready and ‘1’ = Not Ready. Software shall + /// not write any Doorbell or Operational register of the xHC, other than the USBSTS register, until + /// CNR = ‘0’. This flag is set by the xHC after a Chip Hardware Reset and cleared when the xHC is + /// ready to begin accepting register writes. This flag shall remain cleared (‘0’) until the next Chip + /// Hardware Reset. + #[bits(access=RO)] + pub controller_not_ready: bool, + /// Host Controller Error (HCE) – RO. Default = 0. 0’ = No internal xHC error conditions exist and ‘1’ + /// = Internal xHC error condition. This flag shall be set to indicate that an internal error condition + /// has been detected which requires software to reset and reinitialize the xHC. Refer to section + /// 4.24.1 for more information. + #[bits(access=RO)] + pub host_controller_error: bool, + #[bits(19)] + __: u32, +} + +impl UsbStatus { + // Returns a copy of this object that can be written without overwritting flags that are RW1C. + fn preserving_flags(&self) -> UsbStatus { + self.with_host_system_error(false) + .with_event_interrupt(false) + .with_port_change_detect(false) + .with_save_restore_error(false) + } +} + +/// Internal data structure to ensure 64 bit reads and writes. +#[bitfield(u64)] +struct CommandAndStatus { + #[bits(32)] + usb_command: UsbCommand, + #[bits(32)] + usb_status: UsbStatus, +} + +impl CommandAndStatus { + fn update_command(&self, f: impl Fn(UsbCommand) -> UsbCommand) -> CommandAndStatus { + CommandAndStatus::new() + .with_usb_command(f(self.usb_command())) + .with_usb_status(self.usb_status().preserving_flags()) + } + + fn update_status(&self, f: impl Fn(UsbStatus) -> UsbStatus) -> CommandAndStatus { + self.with_usb_status(f(self.usb_status()).preserving_flags()) + } +} + +#[bitfield(u64)] +struct PageSize { + ///Page Size – RO. Default = Implementation defined. This field defines the page size supported by + /// the xHC implementation. This xHC supports a page size of 2^(n+12) if bit n is Set. For example, if + /// bit 0 is Set, the xHC supports 4k byte page sizes. + /// + /// For a Virtual Function, this register reflects the page size selected in the System Page Size field + /// of the SR-IOV Extended Capability structure. For the Physical Function 0, this register reflects + /// the implementation dependent default xHC page size. + /// + /// Various xHC resources reference PAGESIZE to describe their minimum alignment requirements. + /// + /// The maximum possible page size is 128M. + #[bits(access=RO)] + page_size: u32, + __: u32, +} + +#[bitfield(u64)] +struct DeviceNotificationControl { + __: u32, + /// This register is used by software to enable or disable the reporting of the + /// reception of specific USB Device Notification Transaction Packets. A Notification + /// Enable (Nx, where x = 0 to 15) flag is defined for each of the 16 possible de vice + /// notification types. If a flag is set for a specific notification type, a Device + /// Notification Event shall be generated when the respective notification packet is + /// received. After reset all notifications are disabled. Refer to section 6.4.2.7 + device_notification_control: u32, +} + +#[bitfield(u64)] +pub struct UsbConfigure { + /// Max Device Slots Enabled (MaxSlotsEn) – RW. Default = ‘0’. This field specifies the maximum + /// number of enabled Device Slots. Valid values are in the range of 0 to MaxSlots. Enabled Devices + /// Slots are allocated contiguously. e.g. A value of 16 specifies that Device Slots 1 to 16 are active. + /// + /// A value of ‘0’ disables all Device Slots. A disabled Device Slot shall not respond to Doorbell + /// Register references. + /// + /// This field shall not be modified by software if the xHC is running (Run/Stop (R/S) = ‘1’) + pub max_device_slots_enabled: u8, + /// U3 Entry Enable (U3E) – RW. Default = '0'. When set to '1', the xHC shall assert the PLC flag ('1') + /// when a Root Hub port transitions to the U3 State. Refer to section 4.15.1 for more information. + pub u3_entry_enable: bool, + /// Configuration Information Enable (CIE) - RW. Default = '0'. When set to '1', the software shall + /// initialize the Configuration Value, Interface Number, and Alternate Setting fields in the Input + /// Control Context when it is associated with a Configure Endpoint Command. When this bit is '0', + /// the extended Input Control Context fields are not supported. Refer to section 6.2.5.1 for more + /// information. + pub configuration_information_enable: bool, + + #[bits(22)] + __: u32, + + // Pad to 64 bits for the purposes of reads and writes. + __: u32, +} + +/// XHCI Spec Section 5.4 +/// +/// The base address of this register space is referred to as Operational Base. The +/// Operational Base shall be Dword aligned and is calculated by adding the value +/// of the Capability Registers Length (CAPLENGTH) register (refer to Section 5.3.1) +/// to the Capability Base address. All registers are multiples of 32 bits in length +#[repr(C)] +#[derive(Copy, Clone)] +pub struct HostControllerOperational { + command_and_status: CommandAndStatus, + page_size: PageSize, + device_notification_control: DeviceNotificationControl, + /// Bit 0: Ring Cycle State (RW) + /// Bit 1: Command Stop (RW1S) + /// Bit 2: Command Abort (RW1S) + /// Bit 3: Command Ring Running (RO) + command_ring_control: u64, + __: u64, + ___: u64, + /// The Device Context Base Address Array Pointer Register identifies the base + /// address of the Device Context Base Address Array. + /// The memory structure referenced by this physical memory pointer is assumed to + /// be physically contiguous and 64-byte aligned. + device_context_base_address_array_pointer: u64, + configure: UsbConfigure, +} + +const _: () = assert!(size_of::() == 0x40); + +pub struct HostControllerOperationalWrapper { + operational: Mutex>, + // TODO: This should maybe be its own structure. + ports: Vec>>, +} + +#[allow(dead_code)] +impl HostControllerOperationalWrapper { + pub fn new(mmio_address: usize) -> (Self, HostControllerCapabilities) { + const MAP_SIZE: usize = 0x1000; + let caps_ptr: NonNull = + map_direct_physical_and_leak(mmio_address, MAP_SIZE); + + // SAFETY: + // - The pointer is valid. + // - No other thread has access in this block. + let capabilities = unsafe { VolatilePtr::new(caps_ptr).read() }; + + assert!( + capabilities.cap_params_1.supports_64_bit(), + "We only support 64 bit XHCI" + ); + + // TODO: I don't think we acutally handle this properly. + // SAFETY: XHCI Spec says that this resides in a single page of memory which we mapped + // above. + // + // BAR0 Size Allocation + // If virtualization is supported, the Capability and Operational Register sets, and + // the Extended Capabilities may reside in a single page of virtual memory, + let cap_length_and_version = capabilities.cap_length_and_version; + let operational_ptr = unsafe { + (caps_ptr.as_ptr() as *mut u8).add(cap_length_and_version.cap_length() as usize) + as *mut HostControllerOperational + }; + + const PORT_OFFSET: usize = 0x400; + + // FIXME: This calculation is cursed. + let ports_addr = unsafe { (operational_ptr as *mut u8).add(PORT_OFFSET) as usize }; + let ports_space = MAP_SIZE - cap_length_and_version.cap_length() as usize - PORT_OFFSET; + let max_ports_we_support = ports_space / size_of::(); + let max_ports = capabilities.params_1.max_ports(); + assert!( + max_ports as usize <= max_ports_we_support, + "TODO: Support more ports." + ); + + let mut ports = Vec::new(); + let ports_addr = ports_addr as *mut HostControllerUsbPort; + for port_index in 0..max_ports { + ports.push(unsafe { + Mutex::new(VolatileRef::new( + NonNull::new(ports_addr.add(port_index as usize)).unwrap(), + )) + }); + } + + let operational = Self { + operational: Mutex::new(unsafe { + VolatileRef::new(NonNull::new(operational_ptr).unwrap()) + }), + ports, + }; + + (operational, capabilities) + } + + pub fn read_command(&self) -> UsbCommand { + let locked = self.operational.lock(); + let op = locked.as_ptr(); + map_field!(op.command_and_status).read().usb_command() + } + + pub fn update_command(&self, f: impl Fn(UsbCommand) -> UsbCommand) { + let mut locked = self.operational.lock(); + let op = locked.as_mut_ptr(); + map_field!(op.command_and_status).update(|c_and_s| c_and_s.update_command(f)); + } + + pub fn read_status(&self) -> UsbStatus { + let locked = self.operational.lock(); + let op = locked.as_ptr(); + map_field!(op.command_and_status).read().usb_status() + } + + pub fn update_status(&self, f: impl Fn(UsbStatus) -> UsbStatus) { + let mut locked = self.operational.lock(); + let op = locked.as_mut_ptr(); + map_field!(op.command_and_status).update(|c_and_s| c_and_s.update_status(f)); + } + + pub fn set_device_context_base_address_array_pointer(&self, pointer: usize) { + let mut locked = self.operational.lock(); + let op = locked.as_mut_ptr(); + map_field!(op.device_context_base_address_array_pointer).write(pointer as u64); + } + + pub fn set_command_ring_dequeue_pointer(&self, pointer: usize, cycle_bit: bool) { + // TODO: Assert that the command ring is not running here. + let mut locked = self.operational.lock(); + let op = locked.as_mut_ptr(); + map_field!(op.command_ring_control).write(pointer as u64 | cycle_bit as u64); + } + + pub fn read_configure(&self) -> UsbConfigure { + let locked = self.operational.lock(); + let op = locked.as_ptr(); + map_field!(op.configure).read() + } + + pub fn update_configure(&self, f: impl Fn(UsbConfigure) -> UsbConfigure) { + let mut locked = self.operational.lock(); + let op = locked.as_mut_ptr(); + map_field!(op.configure).update(f); + } + + pub fn get_port(&self, index: usize) -> HostControllerUsbPort { + self.ports[index].lock().as_ptr().read() + } + + pub fn update_port_status( + &self, + index: usize, + f: impl Fn(PortStatusAndControl) -> PortStatusAndControl, + ) { + let mut port_ref = self.ports[index].lock(); + let ptr = port_ref.as_mut_ptr(); + map_field!(ptr.status_and_control).update(f); + } + + pub fn num_ports(&self) -> usize { + self.ports.len() + } +} diff --git a/rust/sys/voyageurs/src/xhci/registers/host_controller_port.rs b/rust/sys/voyageurs/src/xhci/registers/host_controller_port.rs new file mode 100644 index 0000000..27f1f45 --- /dev/null +++ b/rust/sys/voyageurs/src/xhci/registers/host_controller_port.rs @@ -0,0 +1,415 @@ +use bitfield_struct::bitfield; + +/// A host controller shall implement one or more port registers. The number of +/// port registers implemented by a particular instantiation of a host controller is +/// documented in the HCSPARAMS1 register (Section 5.3.3). Software uses this +/// information as an input parameter to determine how many ports need to be +/// serviced. +/// +/// XHCI Spec 5.4.8 +#[bitfield(u32)] +pub struct PortStatusAndControl { + /// Current Connect Status (CCS) – ROS. Default = ‘0’. ‘1’ = A device is connected81 to the port. ‘0’ = + /// A device is not connected. This value reflects the current state of the port, and may not + /// correspond directly to the event that caused the Connect Status Change (CSC) bit to be set to ‘1’. + /// + /// Refer to sections 4.19.3 and 4.19.4 for more details on the Connect Status Change (CSC) + /// assertion conditions. + /// This flag is ‘0’ if PP is ‘0’. + #[bits(access=RO)] + pub current_connect_status: bool, + + /// Port Enabled/Disabled (PED) – RW1CS. Default = ‘0’. ‘1’ = Enabled. ‘0’ = Disabled. + /// Ports may only be enabled by the xHC. Software cannot enable a port by writing a ‘1’ to this flag. + /// + /// A port may be disabled by software writing a ‘1’ to this flag. + /// + /// This flag shall automatically be cleared to ‘0’ by a disconnect event or other fault condition. + /// Note that the bit status does not change until the port state actually changes. There may be a + /// delay in disabling or enabling a port due to other host controller or bus events. + /// + /// When the port is disabled (PED = ‘0’) downstream propagation of data is blocked on this port, + /// except for reset. + /// + /// For USB2 protocol ports: + /// When the port is in the Disabled state, software shall reset the port (PR = ‘1’) to transition PED to + /// ‘1’ and the port to the Enabled state. + /// + /// For USB3 protocol ports: + /// When the port is in the Polling state (after detecting an attach), the port shall automatically + /// transition to the Enabled state and set PED to ‘1’ upon the completion of successful link training. + /// When the port is in the Disabled state, software shall write a ‘5’ (RxDetect) to the PLS field to + /// transition the port to the Disconnected state. Refer to section 4.19.1.2. + /// + /// PED shall automatically be cleared to ‘0’ when PR is set to ‘1’, and set to ‘1’ when PR transitions + /// from ‘1’ to ‘0’ after a successful reset. Refer to Port Reset (PR) bit for more information on how + /// the PED bit is managed. + /// + /// Note that when software writes this bit to a ‘1’, it shall also write a ‘0’ to the PR bit. + /// This flag is ‘0’ if PP is ‘0’. + pub port_enabled_disabled: bool, + + __: bool, + + /// Over-current Active (OCA) – RO. Default = ‘0’. ‘1’ = This port currently has an over-current + /// condition. ‘0’ = This port does not have an over-current condition. This bit shall automatically + /// transition from a ‘1’ to a ‘0’ when the over-current condition is removed. + #[bits(access=RO)] + pub over_current_active: bool, + + /// Port Reset (PR) – RW1S. Default = ‘0’. ‘1’ = Port Reset signaling is asserted. ‘0’ = Port is not in + /// Reset. When software writes a ‘1’ to this bit generating a ‘0’ to ‘1’ transition, the bus reset + /// sequence is initiated83; USB2 protocol ports shall execute the bus reset sequence as defined in + /// the USB2 Spec. USB3 protocol ports shall execute the Hot Reset sequence as defined in the + /// USB3 Spec. PR remains set until reset signaling is completed by the root hub. + /// + /// Note that software shall write a ‘1’ to this flag to transition a USB2 port from the Polling state to + /// the Enabled state. Refer to sections 4.15.2.3 and 4.19.1.1. + /// + /// This flag is ‘0’ if PP is ‘0’. + pub port_reset: bool, + + /// Port Link State (PLS) – RWS. Default = RxDetect (‘5’). This field is used to power manage the port + /// and reflects its current link state. + /// + /// When the port is in the Enabled state, system software may set the link U state by writing this + /// field. System software may also write this field to force a Disabled to Disconnected state + /// transition of the port. + /// + /// Write Value Description + /// 0 The link shall transition to a U0 state from any of the U states. + /// 285 USB2 protocol ports only. The link should transition to the U2 State. + /// 384 The link shall transition to a U3 state from the U0 state. This action + /// selectively suspends the device connected to this port. While the Port + /// Link State = U3, the hub does not propagate downstream-directed + /// traffic to this port, but the hub shall respond to resume signaling from + /// the port. + /// 5 USB3 protocol ports only. If the port is in the Disabled state (PLS = + /// Disabled, PP = 1), then the link shall transition to a RxDetect state and + /// the port shall transition to the Disconnected state, else ignored. + /// 10 USB3 protocol ports only. Shall enable a link transition to the + /// Compliance state, i.e. CTE = ‘1’. Refer to section 4.19.1.2.4.1 for more + /// information. + /// 185,4,6-9,11-14 Ignored. + /// 15 USB2 protocol ports only. If the port is in the U3 state (PLS = U3), then + /// the link shall remain in the U3 state and the port shall transition to the + /// Resume substate, else ignored. Refer to section 4.15.2 for more + /// information. + /// + /// Note: The Port Link State Write Strobe (LWS) shall also be set to ‘1’ to write this + /// field. + /// + /// For USB2 protocol ports: Writing a value of '2' to this field shall request LPM, asserting L1 + /// signaling on the USB2 bus. Software may read this field to determine if the transition to the U2 + /// state was successful. Writing a value of '0' shall deassert L1 signaling on the USB. Writing a value + /// of '1' shall have no effect. The U1 state shall never be reported by a USB2 protocol port. + /// + /// Read Value Meaning + /// 0 Link is in the U0 State + /// 1 Link is in the U1 State + /// 2 Link is in the U2 State + /// 3 Link is in the U3 State (Device Suspended) + /// 4 Link is in the Disabled State86 + /// 5 Link is in the RxDetect State87 + /// 6 Link is in the Inactive State88 + /// 7 Link is in the Polling State + /// 8 Link is in the Recovery State + /// 9 Link is in the Hot Reset State + /// 10 Link is in the Compliance Mode State + /// 11 Link is in the Test Mode89 State + /// 12-14 Reserved + /// 15 Link is in the Resume State90 + /// + /// This field is undefined if PP = ‘0’. + /// + /// Note: Transitions between different states are not reflected until the transition is complete. Refer + /// to section 4.19 for PLS transition conditions. + /// 409 + /// + /// Refer to sections 4.15.2 and 4.23.5 for more information on the use of this field. Refer to the + /// USB2 LPM ECR for more information on USB link power management operation. Refer to section + /// 7.2 for supported USB protocols + #[bits(4)] + pub port_link_status: u8, + /// Port Power (PP) – RWS. Default = ‘1’. This flag reflects a port's logical, power control state. + /// Because host controllers can implement different methods of port power switching, this flag may + /// or may not represent whether (VBus) power is actually applied to the port. When PP equals a '0' + /// the port is nonfunctional and shall not report attaches, detaches, or Port Link State (PLS) + /// changes. However, the port shall report over-current conditions when PP = ‘0’ if PPC = ‘0’. After + /// modifying PP, software shall read PP and confirm that it is reached its target state before + /// modifying it again91, undefined behavior may occur if this procedure is not followed. + /// + /// 0 = This port is in the Powered-off state. + /// 1 = This port is not in the Powered-off state. + /// + /// If the Port Power Control (PPC) flag in the HCCPARAMS1 register is '1', then xHC has port power + /// control switches and this bit represents the current setting of the switch ('0' = off, '1' = on). + /// + /// If the Port Power Control (PPC) flag in the HCCPARAMS1 register is '0', then xHC does not have + /// port power control switches and each port is hard wired to power, and not affected by this bit. + /// When an over-current condition is detected on a powered port, the xHC shall transition the PP + /// bit in each affected port from a ‘1’ to ‘0’ (removing power from the port). + /// + /// Note: If this is an SSIC Port, then the DSP Disconnect process is initiated by '1' to '0' transition of + /// PP. After an SSIC USP disconnect process, the port may be disabled by setting PED = 1. As noted, + /// the SSIC spec does not define a mechanism for the USP to request DSP to be re-enabled for a + /// subsequent re-connect. If PED is set to 1 without a prior negotiated disconnect with the USP, + /// subsequent re-enabling of the port requires DSP to issue a WPR to bring USP back to Rx.Detect. + /// + /// Refer to section 5.1.2 in the SSIC Spec for more information. + /// Refer to section 4.19.4 for more information. + pub port_power: bool, + /// Port Speed (Port Speed) – ROS. Default = ‘0’. This field identifies the speed of the connected + /// USB Device. This field is only relevant if a device is connected (CCS = ‘1’) in all other cases this + /// field shall indicate Undefined Speed. Refer to section 4.19.3. + /// + /// Value Meaning + /// 0 Undefined Speed + /// 1 -15 Protocol Speed ID (PSI), refer to section 7.2.1 for the definition of PSIV + /// field in the PSI Dword + /// + /// Note: This field is invalid on a USB2 protocol port until after the port is reset. + #[bits(4)] + pub port_speed: u8, + /// Port Indicator Control (PIC) – RWS. Default = 0. Writing to these bits has no effect if the Port + /// Indicators (PIND) bit in the HCCPARAMS1 register is a ‘0’. If PIND bit is a ‘1’, then the bit + /// encodings are: + /// + /// Value Meaning + /// 0 Port indicators are off + /// 1 Amber + /// 2 Green + /// 3 Undefined + /// + /// Refer to the USB2 Specification section 11.5.3 for a description on how these bits shall be used. + /// This field is ‘0’ if PP is ‘0’ + #[bits(2)] + pub port_indicator_control: u8, + /// Port Link State Write Strobe (LWS) – RW. Default = ‘0’. When this bit is set to ‘1’ on a write + /// reference to this register, this flag enables writes to the PLS field. When ‘0’, write data in PLS field + /// is ignored. Reads to this bit return ‘0’ + pub port_link_state_write_strobe: bool, + /// Connect Status Change (CSC) – RW1CS. Default = ‘0’. ‘1’ = Change in CCS. ‘0’ = No change. This + /// flag indicates a change has occurred in the port’s Current Connect Status (CCS) or Cold Attach + /// Status (CAS) bits. Note that this flag shall not be set if the CCS transition was due to software + /// setting PP to ‘0’, or the CAS transition was due to software setting WPR to ‘1’. The xHC sets this + /// bit to ‘1’ for all changes to the port device connect status92, even if system software has not + /// cleared an existing Connect Status Change. For example, the insertion status changes twice + /// before system software has cleared the changed condition, root hub hardware will be “setting” + /// an already-set bit (i.e., the bit will remain ‘1’). Software shall clear this bit by writing a ‘1’ to it. + /// Refer to section 4.19.2 for more information on change bit usage. + pub connect_status_change: bool, + /// Port Enabled/Disabled Change (PEC) – RW1CS. Default = ‘0’. ‘1’ = change in PED. ‘0’ = No + /// change. Note that this flag shall not be set if the PED transition was due to software setting PP to + /// ‘0’. Software shall clear this bit by writing a ‘1’ to it. Refer to section 4.19.2 for more information + /// on change bit usage. + /// + /// For a USB2 protocol port, this bit shall be set to ‘1’ only when the port is disabled due to the + /// appropriate conditions existing at the EOF2 point (refer to section 11.8.1 of the USB2 + /// + /// Specification for the definition of a Port Error). + /// For a USB3 protocol port, this bit shall never be set to ‘1’. + pub port_enabled_disabled_change: bool, + /// Warm Port Reset Change (WRC) – RW1CS/RsvdZ. Default = ‘0’. This bit is set when Warm Reset + /// processing on this port completes. ‘0’ = No change. ‘1’ = Warm Reset complete. Note that this + /// flag shall not be set to ‘1’ if the Warm Reset processing was forced to terminate due to software + /// clearing PP or PED to '0'. Software shall clear this bit by writing a '1' to it. Refer to section 4.19.5.1. + /// Refer to section 4.19.2 for more information on change bit usage. + /// + /// This bit only applies to USB3 protocol ports. For USB2 protocol ports it shall be RsvdZ. + pub warm_port_reset_change: bool, + /// Over-current Change (OCC) – RW1CS. Default = ‘0’. This bit shall be set to a ‘1’ when there is a ‘0’ + /// to ‘1’ or ‘1’ to ‘0’ transition of Over-current Active (OCA). Software shall clear this bit by writing a + /// ‘1’ to it. Refer to section 4.19.2 for more information on change bit usage. + pub over_current_change: bool, + /// Port Reset Change (PRC) – RW1CS. Default = ‘0’. This flag is set to ‘1’ due to a '1' to '0' transition + /// of Port Reset (PR). e.g. when any reset processing (Warm or Hot) on this port is complete. Note + /// that this flag shall not be set to ‘1’ if the reset processing was forced to terminate due to software + /// clearing PP or PED to '0'. ‘0’ = No change. ‘1’ = Reset complete. Software shall clear this bit by + /// writing a '1' to it. Refer to section 4.19.5. Refer to section 4.19.2 for more information on change + /// bit usage + pub port_reset_change: bool, + /// Port Link State Change (PLC) – RW1CS. Default = ‘0’. This flag is set to ‘1’ due to the following + /// PLS transitions: + /// + /// Transition Condition + /// U3 -> Resume: Wakeup signaling from a device + /// Resume -> Recovery -> U0: Device Resume complete (USB3 protocol ports + /// only) + /// Resume -> U0: Device Resume complete (USB2 protocol ports + /// only) + /// U3 -> Recovery -> U0: Software Resume complete (USB3 protocol ports + /// only) + /// U3 -> U0: Software Resume complete (USB2 protocol ports + /// only) + /// U2 -> U0: L1 Resume complete (USB2 protocol ports only)93 + /// U0 -> U0: L1 Entry Reject (USB2 protocol ports only)93 + /// Any state -> Inactive: Error (USB3 protocol ports only). + /// Note: PLC is asserted only on the first LTSSM + /// SS.Inactive.Disconnect.Detect to SS.Inactive.Quiet + /// substate transition after entering the SS.Inactive + /// state. + /// Any State -> U3: U3 Entry complete. Note: PLC is asserted only if + /// U3E = ‘1’. + /// + /// Note that this flag shall not be set if the PLS transition was due to software + /// setting PP to ‘0’. Refer to section 4.23.5 for more information. '0' = No + /// change. '1' = Link Status Changed. Software shall clear this bit by + /// writing a '1' to it. Refer to “PLC Condition:” references in section 4.19.1 + /// for the specific port state transitions that set this flag. Refer to section + /// 4.19.2 for more information on change bit usage. + pub port_link_state_change: bool, + /// Port Config Error Change (CEC) – RW1CS/RsvdZ. Default = ‘0’. This flag indicates that the port + /// failed to configure its link partner. 0 = No change. 1 = Port Config Error detected. Software shall + /// clear this bit by writing a '1' to it. Refer to section 4.19.2 for more information on change bit + /// usage. + /// + /// Note: This flag is valid only for USB3 protocol ports. For USB2 protocol ports this bit shall be + /// RsvdZ. + pub port_config_error_change: bool, + /// Cold Attach Status (CAS) – RO. Default = ‘0’. ‘1’ = Far-end Receiver Terminations were detected + /// in the Disconnected state and the Root Hub Port State Machine was unable to advance to the + /// Enabled state. Refer to sections 4.19.8 for more details on the Cold Attach Status (CAS) assertion + /// conditions. Software shall clear this bit by writing a '1' to WPR or the xHC shall clear this bit if CCS + /// transitions to ‘1’. + /// This flag is ‘0’ if PP is ‘0’ or for USB2 protocol ports + #[bits(access=RO)] + pub cold_attach_status: bool, + /// Wake on Connect Enable (WCE) – RWS. Default = ‘0’. Writing this bit to a ‘1’ enables the port to + /// be sensitive to device connects as system wake-up events96. Refer to section 4.15 for operational + /// model. + pub wake_on_connect_enable: bool, + /// Wake on Disconnect Enable (WDE) – RWS. Default = ‘0’. Writing this bit to a ‘1’ enables the port + /// to be sensitive to device disconnects as system wake-up events. Refer to section 4.15 for + /// operational model. + pub wake_on_disconnect_enable: bool, + /// Wake on Over-current Enable (WOE) – RWS. Default = ‘0’. Writing this bit to a ‘1’ enables the + /// port to be sensitive to over-current conditions as system wake-up events96. Refer to section 4.15 + /// for operational model. + pub wake_on_overcurrent_enable: bool, + __: bool, + __: bool, + /// Device Removable97 (DR) - RO. This flag indicates if this port has a removable device attached. + /// ‘1’ = Device is non-removable. ‘0’ = Device is removable. + #[bits(access=RO)] + pub device_removable: bool, + /// Warm Port Reset (WPR) – RW1S/RsvdZ. Default = ‘0’. When software writes a ‘1’ to this bit, the + /// Warm Reset sequence as defined in the USB3 Specification is initiated and the PR flag is set to ‘1’. + /// Once initiated, the PR, PRC, and WRC flags shall reflect the progress of the Warm Reset + /// sequence. This flag shall always return ‘0’ when read. Refer to section 4.19.5.1. + /// This flag only applies to USB3 protocol ports. For USB2 protocol ports it shall be RsvdZ. + pub warm_port_reset: bool, +} + +impl PortStatusAndControl { + pub fn clear_change_bits(&self) -> Self { + PortStatusAndControl::new() + .with_connect_status_change(true) + .with_port_enabled_disabled_change(true) + .with_warm_port_reset_change(true) + .with_over_current_change(true) + .with_port_reset_change(true) + .with_port_link_state_change(true) + .with_port_config_error_change(true) + .with_port_power(self.port_power()) + .with_wake_on_connect_enable(self.wake_on_connect_enable()) + .with_wake_on_disconnect_enable(self.wake_on_disconnect_enable()) + .with_wake_on_overcurrent_enable(self.wake_on_overcurrent_enable()) + } +} + +/// XHCI Spec 5.4.9 +/// NOTE: This definition is USB3 only. +#[bitfield(u32)] +pub struct PortPowerManagementStatusAndControl { + /// U1 Timeout – RWS. Default = ‘0’. Timeout value for U1 inactivity timer. If equal to FFh, the port + /// is disabled from initiating U1 entry. This field shall be set to ‘0’ by the assertion of PR to ‘1’. Refer + /// to section 4.19.4.1 for more information on U1 Timeout operation. The following are + /// permissible values: + /// + /// Value Description + /// 00h Zero (default) + /// 01h 1 μs. + /// 02h 2 μs. + /// … + /// 7Fh 127 μs. + /// 80h–FEh Reserved + /// FFh Infinite + u1_timeout: u8, + /// U2 Timeout – RWS. Default = ‘0’. Timeout value for U2 inactivity timer. If equal to FFh, the port + /// is disabled from initiating U2 entry. This field shall be set to ‘0’ by the assertion of PR to ‘1’. Refer + /// to section 4.19.4.1 for more information on U2 Timeout operation. The following are + /// permissible values: + /// + /// Value Description + /// 00h Zero (default) + /// 01h 256 μs + /// 02h 512 μs + /// … + /// FEh 65,024 ms + /// FFh Infinite + /// + /// A U2 Inactivity Timeout LMP shall be sent by the xHC to the device connected on this port when + /// this field is written. Refer to Sections 8.4.3 and 10.4.2.10 of the USB3 specification for more + /// details + u2_timeout: u8, + /// Force Link PM Accept (FLA) - RW. Default = ‘0’. When this bit is set to ‘1’, the port shall generate + /// a Set Link Function LMP with the Force_LinkPM_Accept bit asserted (‘1’). When this bit is cleared + /// to ‘0’, the port shall generate a Set Link Function LMP with the Force_LinkPM_Accept bit de- + /// asserted (‘0’). + /// This flag shall be set to ‘0’ by the assertion of PR to ‘1’ or when CCS = transitions from ‘0’ to ‘1’. + /// Writes to this flag have no effect if PP = ‘0’. + /// The Set Link Function LMP is sent by the xHC to the device connected on this port when this bit + /// transitions from ‘0’ to ‘1’ or ‘1’ to ‘0’. Refer to Sections 8.4.2 and 10.14.2.2 of the USB3 + /// specification for more details. + /// Improper use of the SS Force_LinkPM_Accept functionality can impact the performance of the + /// link significantly. This bit shall only be used for compliance and testing purposes. Software shall + /// ensure that there are no pending packets at the link level before setting this bit. + /// This flag is ‘0’ if PP is ‘0’ + force_link_pm_accept: bool, + #[bits(15)] + __: u16, +} + +/// XHCI Spec 5.4.10 +/// +/// NOTE: This definition is USB3 only. +#[bitfield(u32)] +pub struct PortLinkInfo { + /// Link Error Count – RW. Default = ‘0’. This field returns the number of link errors detected by the + /// port. This value shall be reset to ‘0’ by the assertion of a Chip Hardware Reset, HCRST, when PR + /// transitions from ‘1’ to ‘0’, or when reset by software by writing 0 to it. This register will increment + /// by one each time a port transitions from U0 to Recovery to recover an error event and will + /// saturate at max + link_error_count: u16, + /// Rx Lane Count (RLC) - RO. Default = '0'. This field that identifies the number of Receive Lanes + /// negotiated by the port. This is a "zero-based" value, where 0 to 15 represents Lane Counts of 1 + /// to 16, respectively. This value is valid only when CCS = '1'. RLC shall equal '0' for a simplex + /// Sublink. Refer to section 7.2.1 for more information. + #[bits(4)] + rx_lane_count: u8, + /// Tx Lane Count (TLC) - RO. Default = '0'. This field that identifies the number of Transmit Lanes + /// negotiated by the port. This is a "zero-based" value, where 0 to 15 represents Lane Counts of 1 + /// to 16, respectively. This value is valid only when CCS = '1'. TLC shall equal '0' for a simplex + /// Sublink. Refer to section 7.2.1 for more information. + #[bits(4)] + tx_lane_count: u8, + __: u8, +} + +/// XHCI Spec 5.4.8 - 5.4.11 +/// +/// These registers are an array of size MAX_PORTS located at offset 0x400 +/// from the HostControllerOperation address. +/// +/// Where MAX_PORTS is HostControllerCapabilities.params_1.max_ports +#[repr(C)] +#[derive(Copy, Clone)] +pub struct HostControllerUsbPort { + pub status_and_control: PortStatusAndControl, + pub power_management_status_and_control: PortPowerManagementStatusAndControl, + pub link_info: PortLinkInfo, + pub hardware_lpm_control: u32, +} + +const _: () = assert!(size_of::() == 0x10); diff --git a/rust/sys/voyageurs/src/xhci/registers/interrupter.rs b/rust/sys/voyageurs/src/xhci/registers/interrupter.rs new file mode 100644 index 0000000..3b75f98 --- /dev/null +++ b/rust/sys/voyageurs/src/xhci/registers/interrupter.rs @@ -0,0 +1,206 @@ +use core::ptr::NonNull; + +use bitfield_struct::bitfield; +use volatile::{VolatileRef, map_field}; + +use crate::xhci::data_structures::EventRingSegmentTable; + +/// The Interrupter Management register allows system software to enable, disable, +/// and detect xHC interrupts. +/// +/// XHCI 5.5.2.1 +#[bitfield(u32)] +struct InterrupterManagement { + /// Interrupt Pending (IP) - RW1C. Default = ‘0’. This flag represents the current state of the + /// Interrupter. If IP = ‘1’, an interrupt is pending for this Interrupter. A ‘0’ value indicates that no + /// interrupt is pending for the Interrupter. Refer to section 4.17.3 for the conditions that modify + /// the state of this flag. + interrupt_pending: bool, + + /// Interrupt Enable (IE) – RW. Default = ‘0’. This flag specifies whether the Interrupter is capable of + /// generating an interrupt. When this bit and the IP bit are set (‘1’), the Interrupter shall generate + /// an interrupt when the Interrupter Moderation Counter reaches ‘0’. If this bit is ‘0’, then the + /// Interrupter is prohibited from generating interrupts + interrupt_enabled: bool, + + #[bits(30)] + _reserved: u32, +} + +/// The Interrupter Moderation Register controls the “interrupt moderation” feature +/// of an Interrupter, allowing system software to throttle the interrupt rate +/// generated by the xHC +/// +/// XHCI 5.5.2.2 +#[bitfield(u32)] +pub struct InterrupterModeration { + /// Interrupt Moderation Interval (IMODI) – RW. Default = ‘4000’ (~1ms). Minimum inter-interrupt + /// interval. The interval is specified in 250ns increments. A value of ‘0’ disables interrupt throttling + /// logic and interrupts shall be generated immediately if IP = ‘0’, EHB = ‘0’, and the Event Ring is + /// not empty + pub interrupt_moderation_interval: u16, + + /// Interrupt Moderation Counter (IMODC) – RW. Default = undefined. Down counter. Loaded with + /// the IMODI value whenever IP is cleared to ‘0’, counts down to ‘0’, and stops. The associated + /// interrupt shall be signaled whenever this counter is ‘0’, the Event Ring is not empty, the IE and IP + /// flags = ‘1’, and EHB = ‘0’. + /// This counter may be directly written by software at any time to alter the interrupt rate + pub interrupt_moderation_counter: u16, +} + +#[bitfield(u64)] +struct ManagementAndModeration { + #[bits(32)] + management: InterrupterManagement, + + #[bits(32)] + moderation: InterrupterModeration, +} + +impl ManagementAndModeration { + fn update_moderation(self, moderation: InterrupterModeration) -> Self { + // Update preserving intterupt pending. + self.with_management(self.management().with_interrupt_pending(false)) + .with_moderation(moderation) + } +} + +/// The Event Ring Dequeue Pointer Register is written by software to define the +/// Event Ring Dequeue Pointer location to the xHC. Software updates this pointer +/// when it is finished the evaluation of an Event(s) on the Event Ring. +/// +/// XHCI 5.5.2.3.3 +#[bitfield(u64)] +struct EventRingDequePointer { + /// Dequeue ERST Segment Index (DESI) – RW. Default = ‘0’. This field may be used by the xHC to + /// accelerate checking the Event Ring full condition. This field is written with the low order 3 bits of + /// the offset of the ERST entry which defines the Event Ring segment that the Event Ring Dequeue + /// Pointer resides in. Refer to section 6.5 for the definition of an ERST entry. + #[bits(3)] + dequeue_erst_segment_index: u8, + + /// Event Handler Busy (EHB) - RW1C. Default = ‘0’. This flag shall be set to ‘1’ when the IP bit is set + /// to ‘1’ and cleared to ‘0’ by software when the Dequeue Pointer register is written. Refer to + /// section 4.17.2 for more information + event_handler_busy: bool, + + /// Event Ring Dequeue Pointer - RW. Default = ‘0’. This field defines the high order bits of the 64- + /// bit address of the current Event Ring Dequeue Pointer + #[bits(60)] + event_ring_dequeue_pointer: u64, +} + +impl EventRingDequePointer { + fn with_dequeue_pointer_adjusted(self, event_ring_dequeue_pointer: usize) -> Self { + assert!( + event_ring_dequeue_pointer & 0b1111 == 0, + "Bottom four bits of event ring dequeue pointer must be 0" + ); + self.with_event_ring_dequeue_pointer((event_ring_dequeue_pointer >> 4) as u64) + } + + fn clear_event_hanlder_busy(self) -> Self { + // RW1C + self.with_event_handler_busy(true) + } +} + +/// The Event Ring Segment Table Size Register defines the number of segments +/// supported by the Event Ring Segment Table. +/// +/// XHCI 5.5.2.3.1 +#[bitfield(u64)] +struct EventRingSegmentTableSize { + /// Event Ring Segment Table Size – RW. Default = ‘0’. This field identifies the number of valid + /// Event Ring Segment Table entries in the Event Ring Segment Table pointed to by the Event Ring + /// Segment Table Base Address register. The maximum value supported by an xHC + /// implementation for this register is defined by the ERST Max field in the HCSPARAMS2 register + /// (5.3.4). + /// For Secondary Interrupters: Writing a value of ‘0’ to this field disables the Event Ring. Any events + /// targeted at this Event Ring when it is disabled shall result in undefined behavior of the Event + /// Ring. + /// For the Primary Interrupter: Writing a value of ‘0’ to this field shall result in undefined behavior + /// of the Event Ring. The Primary Event Ring cannot be disabled. + event_ring_segment_table_size: u16, + __: u16, + __: u32, +} + +/// This is an array of registers starting at offset 0x20 of the Runtime Base. +/// The Runtime Base shall be 32-byte aligned and is calculated by adding the +/// value Runtime Register Space Offset register (refer to Section 5.3.8) to +/// the Capability Base address. All Runtime registers are multiples of 32 bits in length. +/// +/// XHCI Spec 5.5.2 +#[repr(C)] +pub struct InterrupterRegisterSet { + management_and_moderation: ManagementAndModeration, + event_ring_segment_table_size: EventRingSegmentTableSize, + /// Event Ring Segment Table Base Address Register – RW. Default = ‘0’. This field defines the + /// high order bits of the start address of the Event Ring Segment Table. + /// Writing this register sets the Event Ring State Machine:EREP Advancement to the Start state. + /// Refer to Figure 4-12 for more information. + /// For Secondary Interrupters: This field may be modified at any time. + /// For the Primary Interrupter: This field shall not be modified if HCHalted (HCH) = ‘0’. + /// + /// NOTE: This must be aligned such that bits 0:5 are 0. + /// + /// XHCI 5.5.2.3.2 + event_ring_segment_table_base_address: u64, + event_ring_deque_pointer: EventRingDequePointer, +} + +const _: () = assert!(size_of::() == 0x20); + +pub struct InterrupterRegisters(VolatileRef<'static, InterrupterRegisterSet>); + +impl InterrupterRegisters { + pub fn new(interrupter_register_set: NonNull) -> Self { + // TODO: Validate safety. + unsafe { Self(VolatileRef::new(interrupter_register_set)) } + } + + /// SAFETY: + /// - For the primary interrupter HC must be halted. + /// - The event rings size must be at most ERST_MAX from HCSPARAMS2 + pub unsafe fn set_event_ring( + &mut self, + event_ring_segment_table: &EventRingSegmentTable, + event_ring_dequeue_pointer: usize, + ) { + // NOTE: We must write the size before the base address otherwise qemu is unhappy. + // Not sure if this is required by the spec. + + let internal = self.0.as_mut_ptr(); + map_field!(internal.event_ring_segment_table_size).write( + EventRingSegmentTableSize::new() + .with_event_ring_segment_table_size(event_ring_segment_table.len() as u16), + ); + map_field!(internal.event_ring_segment_table_base_address) + .write(event_ring_segment_table.physical_address() as u64); + map_field!(internal.event_ring_deque_pointer).write( + EventRingDequePointer::new().with_dequeue_pointer_adjusted(event_ring_dequeue_pointer), + ); + } + + pub fn update_dequeue_pointer_clearing_busy(&mut self, event_ring_dequeue_pointer: usize) { + let internal = self.0.as_mut_ptr(); + map_field!(internal.event_ring_deque_pointer).update(|ptr| { + ptr.with_dequeue_pointer_adjusted(event_ring_dequeue_pointer) + .clear_event_hanlder_busy() + }); + } + + pub fn set_moderation(&mut self, moderation: InterrupterModeration) { + let internal = self.0.as_mut_ptr(); + map_field!(internal.management_and_moderation) + .update(|reg| reg.update_moderation(moderation)); + } + + pub fn enable_interrupts(&mut self) { + let internal = self.0.as_mut_ptr(); + map_field!(internal.management_and_moderation).update(|reg| { + reg.with_management(InterrupterManagement::new().with_interrupt_enabled(true)) + }); + } +} diff --git a/rust/sys/voyageurs/src/xhci/registers/mod.rs b/rust/sys/voyageurs/src/xhci/registers/mod.rs new file mode 100644 index 0000000..37acf46 --- /dev/null +++ b/rust/sys/voyageurs/src/xhci/registers/mod.rs @@ -0,0 +1,15 @@ +/// This mod contains XHCI Register Definitions +/// +/// These are generally hardware backed registers +/// defined at fixed addresses. +mod capabilities; +mod doorbell; +mod host_controller; +mod host_controller_port; +mod interrupter; + +pub use capabilities::*; +pub use doorbell::*; +pub use host_controller::*; +pub use host_controller_port::*; +pub use interrupter::*;