From 890b41c6ec95395c6a7ce8ee97002771ab85847f Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:24:28 +0000 Subject: [PATCH 01/18] feat(bluetooth): log every packet of the guest's Bluetooth controller with --bluetooth-trace, 1024 a configuration in both directions, whole up to 300 bytes, in a line format that reads back, where the boot log named only the first 48 commands with four parameter bytes each --- crates/stela-boot-core/src/options.rs | 7 + crates/stela-boot-core/src/options/parse.rs | 1 + crates/stela-boot-core/src/options/tests.rs | 13 + crates/stela-boot/src/engine/bluetooth.rs | 40 ++- crates/stela-boot/src/engine/start.rs | 13 +- crates/stela-soc/src/machine.rs | 5 +- crates/stela-soc/src/machine/usb.rs | 15 ++ crates/stela-soc/src/usb/hci.rs | 138 ++++++++++ crates/stela-soc/src/usb/hci/capture.rs | 270 ++++++++++++++++++++ 9 files changed, 490 insertions(+), 12 deletions(-) create mode 100644 crates/stela-soc/src/usb/hci/capture.rs diff --git a/crates/stela-boot-core/src/options.rs b/crates/stela-boot-core/src/options.rs index 6c4dc272d6..24e4eba69d 100644 --- a/crates/stela-boot-core/src/options.rs +++ b/crates/stela-boot-core/src/options.rs @@ -47,6 +47,7 @@ pub const WIFI: &str = "--wifi"; pub const WIFI_KEY: &str = "--wifi-key"; pub const WIFI_COUNTRY: &str = "--wifi-country"; pub const USB4_APPROVE: &str = "--usb4-approve"; +pub const BLUETOOTH_TRACE: &str = "--bluetooth-trace"; /// The ESP file `--wifi` reads its key from without `--wifi-key`. pub const DEFAULT_WIFI_KEY: &str = "\\EFI\\stela\\wifi.key"; /// IEEE 802.11 SSIDs are 1 to 32 octets. @@ -274,6 +275,10 @@ pub struct System { /// Cable the native USB keyboard and pointer to the last USB-C /// controller and feed it the host's virtio-input devices (`--input`). pub input: bool, + /// Log every packet of the guest's Bluetooth controller, 1024 per + /// configuration (`--bluetooth-trace`). The packets name nearby devices' + /// addresses and names. + pub bluetooth_trace: bool, /// Explicit native executors and guest PEs (`--native-cores N`), one per /// logical processor; SMT siblings count after every physical core. pub native_cores: Option, @@ -394,6 +399,7 @@ impl Default for System { survey: false, idle_skip: false, input: false, + bluetooth_trace: false, native_cores: None, guest_pes: None, display_size: None, @@ -841,6 +847,7 @@ impl fmt::Display for System { line.value(IPV4_GATEWAY, self.ipv4_gateway)?; line.value(DNS, (!self.dns.is_empty()).then(|| Servers(&self.dns)))?; line.flag("--input", self.input)?; + line.flag(BLUETOOTH_TRACE, self.bluetooth_trace)?; line.flag("--idle-skip", self.idle_skip)?; line.flag("--survey", self.survey)?; line.flag("--sep-observe", self.sep_observe)?; diff --git a/crates/stela-boot-core/src/options/parse.rs b/crates/stela-boot-core/src/options/parse.rs index b555856f5e..82277c59f3 100644 --- a/crates/stela-boot-core/src/options/parse.rs +++ b/crates/stela-boot-core/src/options/parse.rs @@ -142,6 +142,7 @@ impl ParseState<'_> { "--development-restore" => options.development_restore = true, "--idle-skip" => options.idle_skip = true, "--input" => options.input = true, + BLUETOOTH_TRACE => options.bluetooth_trace = true, "--usb-storage" => { let serial = value().ok_or(Error::MissingUsbStorage)?; if options.usb_storage.iter().any(|other| other == serial) { diff --git a/crates/stela-boot-core/src/options/tests.rs b/crates/stela-boot-core/src/options/tests.rs index b8f77aa583..126734eee3 100644 --- a/crates/stela-boot-core/src/options/tests.rs +++ b/crates/stela-boot-core/src/options/tests.rs @@ -200,6 +200,19 @@ fn every_option_survives_a_round_trip() { assert_eq!(restore.restore_manifest_path.as_deref(), Some("m.plist")); } +/// The guest Bluetooth capture is off unless asked for, and survives the +/// line a setup writes. +#[test] +fn the_bluetooth_capture_round_trips_and_is_off_by_default() { + assert!(!System::default().bluetooth_trace); + assert!(!round_trip("--system --input").bluetooth_trace); + let line = format!("--system --storage {DISK} --input {BLUETOOTH_TRACE}"); + let options = round_trip(&line); + assert!(options.input && options.bluetooth_trace); + assert_eq!(options.to_string(), line); + assert!(!System::default().to_string().contains("bluetooth")); +} + #[test] fn usb4_approvals_repeat_and_keep_their_canonical_spelling() { let first = "446ab8f0-5aff-47c9-8962-5870641e4d61"; diff --git a/crates/stela-boot/src/engine/bluetooth.rs b/crates/stela-boot/src/engine/bluetooth.rs index a29733c322..ab7d24d733 100644 --- a/crates/stela-boot/src/engine/bluetooth.rs +++ b/crates/stela-boot/src/engine/bluetooth.rs @@ -10,7 +10,9 @@ //! reports the model's unknown commands, each once, how many commands the //! guest sent, at each doubling, and the function's trace: each //! configuration and reset, and the first commands after each -//! configuration with their answers. +//! configuration with their answers. With `--bluetooth-trace` it also logs +//! every packet the function captures (`GUEST BLUETOOTH RAW`, at most +//! `stela_soc::usb::hci::capture::CAPTURED_PACKETS` per configuration). //! //! One controller serves the guest; others are reported and left idle. A //! controller that fails is reported once, and the guest's commands then get @@ -24,13 +26,15 @@ //! controller, for the next service turn. use super::{output, storage::RestoreRoot}; use alloc::{boxed::Box, collections::VecDeque, string::String, vec::Vec}; +use stela_boot_core::options::System; use stela_drivers::{ bluetooth::{bcm4377, intel_pcie}, probe::native::{Bcm4377, IntelBluetooth, PcieController, PcieHci}, usb::bluetooth::{Packet, UsbHci}, }; use stela_soc::machine::{ - AppleDevices, Outbound, UsbBluetooth, UsbBluetoothCounters, UsbBluetoothTrace, + AppleDevices, Outbound, UsbBluetooth, UsbBluetoothCaptured, UsbBluetoothCounters, + UsbBluetoothTrace, }; enum Controller { @@ -61,6 +65,10 @@ pub struct HostBluetooth { reported_commands: u64, /// The guest function's trace, to report. trace: Vec, + /// Whether the function is still to be asked for its capture. + capture: bool, + /// The packets it captured, to report. + captured: Vec, } /// The controller is dropped in the loader's root. An install runs without @@ -109,6 +117,8 @@ impl HostBluetooth { unknown: Vec::new(), reported_commands: 0, trace: Vec::new(), + capture: false, + captured: Vec::new(), }) } @@ -125,9 +135,26 @@ impl HostBluetooth { unknown: Vec::new(), reported_commands: 0, trace: Vec::new(), + capture: false, + captured: Vec::new(), } } + /// The guest's controller for a boot with `options`, said once in the + /// log: the model of Apple's internal USB module for every boot with + /// host input. The host's `controller` is not lent: the guest's + /// function would carry the host's vendor commands and replies, which + /// BlueTool's chip boot and bluetoothd's bring-up do not take. One not + /// kept is released in the loader's root by its drop. + pub fn guest(controller: Option, options: &System, root: u64) -> Option { + let line = + stela_boot_core::guest_bluetooth::model_line(controller.is_some(), options.input)?; + output::arguments(format_args!("{line}")); + let mut guest = Self::modeled(root); + guest.capture = options.bluetooth_trace; + Some(guest) + } + /// The guest's USB function for this controller. pub fn kind(&self) -> UsbBluetooth { match self.controller { @@ -145,7 +172,13 @@ impl HostBluetooth { if matches!(self.controller, Controller::Modeled) { self.unknown.extend(devices.bluetooth_unknown()); } + // Asked at the first service turn, before the guest's USB stack + // can configure the function. + if core::mem::take(&mut self.capture) { + devices.bluetooth_capture(); + } self.trace.extend(devices.bluetooth_trace()); + self.captured.extend(devices.bluetooth_captured()); let packets = core::iter::from_fn(|| devices.bluetooth_take()).collect(); ( packets, @@ -170,6 +203,9 @@ impl HostBluetooth { for entry in self.trace.drain(..) { output::arguments(format_args!("GUEST BLUETOOTH {entry}\n")); } + for packet in self.captured.drain(..) { + output::arguments(format_args!("GUEST BLUETOOTH RAW {packet}\n")); + } for opcode in self.unknown.drain(..) { output::arguments(format_args!( "BLUETOOTH model: unknown command {opcode:#06x} (OGF {:#04x} OCF {:#05x}) \ diff --git a/crates/stela-boot/src/engine/start.rs b/crates/stela-boot/src/engine/start.rs index 11ac64aee6..821f215635 100644 --- a/crates/stela-boot/src/engine/start.rs +++ b/crates/stela-boot/src/engine/start.rs @@ -3367,15 +3367,10 @@ fn start_devices( // is not lent: the guest's function would carry the host's // vendor commands and replies, which BlueTool's chip boot and // bluetoothd's bring-up do not take. It is released in the - // loader's root by its drop. The log says so once. - if let Some(line) = stela_boot_core::guest_bluetooth::model_line( - host_controller.is_some(), - options.input, - ) { - output::arguments(format_args!("{line}")); - host_bluetooth = Some(bluetooth::HostBluetooth::modeled(handoff.root)); - } - drop(host_controller); + // loader's root by its drop (`bluetooth::HostBluetooth::guest`). + // The log says so once. + host_bluetooth = + bluetooth::HostBluetooth::guest(host_controller, options, handoff.root); // With no adapter started, the screen names each one found and // why it stayed off, before the steps that need one say so. if links.devices.is_empty() && (wants_network || options.guest_network) { diff --git a/crates/stela-soc/src/machine.rs b/crates/stela-soc/src/machine.rs index c71669aa61..ecc7d42b15 100644 --- a/crates/stela-soc/src/machine.rs +++ b/crates/stela-soc/src/machine.rs @@ -30,7 +30,10 @@ use crate::usb::{ }; pub use crate::usb::{ ecm::Counters as UsbNetworkCounters, - hci::{Counters as UsbBluetoothCounters, Outbound, Traced as UsbBluetoothTrace}, + hci::{ + Counters as UsbBluetoothCounters, Outbound, Traced as UsbBluetoothTrace, + capture::Captured as UsbBluetoothCaptured, + }, host::{Descriptor as UsbDescriptor, MuxEndpoints}, mux::{ Backpressure as MuxBackpressure, State as MuxState, StreamId as MuxStream, diff --git a/crates/stela-soc/src/machine/usb.rs b/crates/stela-soc/src/machine/usb.rs index 764c3b4d0f..89fadf30c8 100644 --- a/crates/stela-soc/src/machine/usb.rs +++ b/crates/stela-soc/src/machine/usb.rs @@ -263,6 +263,21 @@ impl AppleDevices { .unwrap_or_default() } + /// Capture every packet of the guest's Bluetooth controller from now on + /// (`--bluetooth-trace`). + pub fn bluetooth_capture(&mut self) { + if let Some(hci) = self.usb_bluetooth() { + hci.capture(); + } + } + + /// The Bluetooth packets captured since they were last taken. + pub fn bluetooth_captured(&mut self) -> Vec { + self.usb_bluetooth() + .map(|hci| hci.take_captured()) + .unwrap_or_default() + } + /// Whether the guest configured its Bluetooth controller, and the /// controller's counters; `None` without one. pub fn bluetooth_status(&mut self) -> Option<(bool, UsbBluetoothCounters)> { diff --git a/crates/stela-soc/src/usb/hci.rs b/crates/stela-soc/src/usb/hci.rs index 564aa97aa4..265d92f7ea 100644 --- a/crates/stela-soc/src/usb/hci.rs +++ b/crates/stela-soc/src/usb/hci.rs @@ -73,6 +73,7 @@ use alloc::{boxed::Box, collections::VecDeque, string::String, vec, vec::Vec}; use stela_contracts::refuse; use stela_drivers::usb::bluetooth::MAX_ACL_PAYLOAD; +pub mod capture; pub mod model; const EVENTS: u8 = 0x81; @@ -135,6 +136,8 @@ pub enum Traced { /// [`TRACED_COMMANDS`] commands were traced; an HCI Reset or the next /// configuration starts again. Ended, + /// The capture (`capture`) took its packets for this configuration. + CaptureEnded, } /// The event that answered a traced command. @@ -187,6 +190,11 @@ impl core::fmt::Display for Traced { f, "trace ends after {TRACED_COMMANDS} commands until the next HCI Reset or configuration" ), + Self::CaptureEnded => write!( + f, + "capture ends after {} packets until the next configuration", + capture::CAPTURED_PACKETS + ), } } } @@ -278,6 +286,8 @@ struct State { configured: u8, /// HCI Resets that may still start the trace again. bring_ups: u8, + /// Every packet, once the owner asks (`--bluetooth-trace`). + capture: capture::Capture, } /// The function: its pipes and queues. @@ -425,6 +435,7 @@ impl Hci { tracing: 0, configured: 0, bring_ups: 0, + capture: capture::Capture::default(), }, } } @@ -465,6 +476,18 @@ impl Hci { core::mem::take(&mut self.state.trace) } + /// Capture every packet from now on, [`capture::CAPTURED_PACKETS`] per + /// configuration (`--bluetooth-trace`). + pub fn capture(&mut self) { + let configured = self.up(); + self.state.capture.enable(configured); + } + + /// The packets captured since they were last taken. + pub fn take_captured(&mut self) -> Vec { + self.state.capture.take() + } + /// The next packet the guest sent for the host's controller. pub fn take(&mut self) -> Option { self.state.outbound.pop_front() @@ -491,6 +514,7 @@ impl Hci { return; } state.counters.acl_to_guest += 1; + state.captured(capture::Direction::ToGuest, capture::Kind::Acl, packet); state.acl.queue.push_back(packet.to_vec()); } } @@ -514,9 +538,16 @@ impl State { return; } self.counters.events_to_guest += 1; + self.captured(capture::Direction::ToGuest, capture::Kind::Event, &packet); self.events.queue.push_back(packet); } + fn captured(&mut self, direction: capture::Direction, kind: capture::Kind, packet: &[u8]) { + if self.capture.record(direction, kind, packet) { + self.trace(Traced::CaptureEnded); + } + } + fn modeled_command(&mut self, packet: &[u8]) { let Some(model) = self.model.as_mut() else { return; @@ -594,6 +625,11 @@ impl State { self.counters.malformed += 1; return Err(Stall); } + self.captured( + capture::Direction::FromGuest, + capture::Kind::Command, + packet, + ); let opcode = u16::from_le_bytes([low, high]); let vendor = opcode >> 10 == VENDOR_GROUP; if self.model.is_some() { @@ -630,6 +666,7 @@ impl State { self.assembling.clear(); } else if self.assembling.len() == ACL_HEADER + data { let packet = core::mem::take(&mut self.assembling); + self.captured(capture::Direction::FromGuest, capture::Kind::Acl, &packet); if self.model.is_some() { self.modeled_acl(&packet); } else { @@ -655,6 +692,7 @@ impl Requests for State { } else { (TRACED_COMMANDS, TRACED_BRING_UPS) }; + self.capture.configured(value); self.halted = [false; 3]; self.sco_setting = 0; self.outbound.clear(); @@ -1187,6 +1225,106 @@ mod tests { assert_eq!(Traced::Reset.to_string(), "bus reset"); } + /// `--bluetooth-trace`: once the owner asks, every packet after each + /// configuration, both ways, then one end line until the next + /// configuration; nothing before it asks. + #[test] + fn the_capture_holds_every_packet_after_each_configuration() { + use capture::{CAPTURED_PACKETS, Captured, Direction, Kind}; + let mut hci = modeled(); + command(&mut hci, &[0x03, 0x0c, 0]).unwrap(); + read(&mut hci, EVENTS, EVENT_PACKET); + assert!(hci.take_captured().is_empty(), "nothing until asked"); + hci.capture(); + command(&mut hci, &[0x09, 0x10, 0]).unwrap(); + let answer = read(&mut hci, EVENTS, EVENT_PACKET).concat(); + assert_eq!( + hci.take_captured(), + [ + Captured::new(Direction::FromGuest, Kind::Command, &[0x09, 0x10, 0]), + Captured::new(Direction::ToGuest, Kind::Event, &answer), + ] + ); + // ACL data from the guest, and the model's return of its buffer. + hci.packet(ACL_OUT, Token::Out, &mut [1, 0, 1, 0, 7]) + .unwrap(); + let completed = read(&mut hci, EVENTS, EVENT_PACKET).concat(); + assert_eq!( + hci.take_captured(), + [ + Captured::new(Direction::FromGuest, Kind::Acl, &[1, 0, 1, 0, 7]), + Captured::new(Direction::ToGuest, Kind::Event, &completed), + ] + ); + hci.take_trace(); + // The bound counts every packet of the configuration. + let left = usize::from(CAPTURED_PACKETS) - 4; + for _ in 0..left / 2 { + command(&mut hci, &[0x09, 0x10, 0]).unwrap(); + read(&mut hci, EVENTS, EVENT_PACKET); + } + assert_eq!(hci.take_captured().len(), left); + assert_eq!(hci.take_trace().last(), Some(&Traced::CaptureEnded)); + command(&mut hci, &[0x09, 0x10, 0]).unwrap(); + read(&mut hci, EVENTS, EVENT_PACKET); + assert!(hci.take_captured().is_empty()); + assert_eq!( + Traced::CaptureEnded.to_string(), + "capture ends after 1024 packets until the next configuration" + ); + // A new configuration starts it again; a bus reset stops it. + transfer(&mut hci, setup(0, SET_CONFIGURATION, 1, 0, 0), &[]).unwrap(); + command(&mut hci, &[0x09, 0x10, 0]).unwrap(); + read(&mut hci, EVENTS, EVENT_PACKET); + assert_eq!(hci.take_captured().len(), 2); + hci.reset().unwrap(); + let mut hci = configured(hci); + command(&mut hci, &[0x09, 0x10, 0]).unwrap(); + assert_eq!(hci.take_captured().len(), 2, "still asked for"); + } + + /// A packet longer than the capture shows keeps its first bytes and + /// counts the rest; a host controller's packets are captured as they + /// reach the guest. + #[test] + fn a_captured_packet_keeps_its_first_bytes_and_counts_the_rest() { + use capture::{CAPTURED_BYTES, Captured, Direction, Kind}; + let mut hci = controller(); + hci.capture(); + let mut long = vec![1, 0, 0, 2]; + long.resize(ACL_HEADER + 512, 7); + let (first, rest) = long.split_at(512); + hci.packet(ACL_OUT, Token::Out, &mut first.to_vec()) + .unwrap(); + hci.packet(ACL_OUT, Token::Out, &mut rest.to_vec()).unwrap(); + hci.deliver_acl(&long); + hci.deliver_event(&[0x0e, 4, 1, 0x03, 0x0c, 0]); + let shown = long[..CAPTURED_BYTES].to_vec(); + let cut = long.len() - CAPTURED_BYTES; + assert_eq!( + hci.take_captured(), + [ + Captured { + direction: Direction::FromGuest, + kind: Kind::Acl, + bytes: shown.clone(), + cut, + }, + Captured { + direction: Direction::ToGuest, + kind: Kind::Acl, + bytes: shown, + cut, + }, + Captured::new( + Direction::ToGuest, + Kind::Event, + &[0x0e, 4, 1, 0x03, 0x0c, 0] + ), + ] + ); + } + #[test] fn a_procedure_ends_when_the_system_count_reaches_it() { let mut hci = modeled(); diff --git a/crates/stela-soc/src/usb/hci/capture.rs b/crates/stela-soc/src/usb/hci/capture.rs new file mode 100644 index 0000000000..5e713658be --- /dev/null +++ b/crates/stela-soc/src/usb/hci/capture.rs @@ -0,0 +1,270 @@ +//! The function's full capture (`--bluetooth-trace`): every HCI packet that +//! crosses it after each configuration, both ways, and for a lent controller +//! (`super::bridge`) each one to and from the host's, for the owner's log. +//! +//! A line holds one packet: where it went (`>` from the guest, `<` to it, +//! `chip>` to the host's controller, `chip<` from it), its kind (`cmd`, +//! `evt`, `acl`), its first [`CAPTURED_BYTES`] in hex, then `+N` for the N +//! bytes cut, which [`Captured::parse`] reads back. Packets carry no H4 +//! indicator: the USB transport has none (Bluetooth Core v5.4 Vol 4 Part +//! B 2), so the kind names it. The capture holds at most +//! [`CAPTURED_PACKETS`] packets per configuration, and none unless the owner +//! asks for it. +use alloc::vec::Vec; +use core::fmt; + +/// Packets captured after each configuration. +pub const CAPTURED_PACKETS: u16 = 1024; +/// Bytes a captured packet shows: every command and event whole (at most +/// 258 and 257 bytes), and an ACL packet's first ones. +pub const CAPTURED_BYTES: usize = 300; + +/// Where a captured packet went. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Direction { + /// From the guest to the function. + FromGuest, + /// From the function to the guest. + ToGuest, + /// From the function to the host's controller. + ToChip, + /// From the host's controller to the function. + FromChip, +} + +impl Direction { + pub const ALL: [Self; 4] = [Self::FromGuest, Self::ToGuest, Self::ToChip, Self::FromChip]; + + fn token(self) -> &'static str { + match self { + Self::FromGuest => ">", + Self::ToGuest => "<", + Self::ToChip => "chip>", + Self::FromChip => "chip<", + } + } +} + +/// What a captured packet is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Command, + Event, + Acl, +} + +impl Kind { + pub const ALL: [Self; 3] = [Self::Command, Self::Event, Self::Acl]; + + fn token(self) -> &'static str { + match self { + Self::Command => "cmd", + Self::Event => "evt", + Self::Acl => "acl", + } + } +} + +/// One captured packet. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Captured { + pub direction: Direction, + pub kind: Kind, + /// Its first [`CAPTURED_BYTES`]. + pub bytes: Vec, + /// How many bytes followed those. + pub cut: usize, +} + +impl Captured { + pub fn new(direction: Direction, kind: Kind, packet: &[u8]) -> Self { + let shown = packet.len().min(CAPTURED_BYTES); + Self { + direction, + kind, + bytes: packet[..shown].to_vec(), + cut: packet.len() - shown, + } + } + + /// The packet a line as [`fmt::Display`] writes it shows; `None` for any + /// other text. + pub fn parse(line: &str) -> Option { + let mut words = line.split_ascii_whitespace(); + let direction = words.next()?; + let direction = *Direction::ALL.iter().find(|d| d.token() == direction)?; + let kind = words.next()?; + let kind = *Kind::ALL.iter().find(|k| k.token() == kind)?; + let mut bytes = Vec::new(); + let mut cut = 0; + for word in words { + if cut != 0 { + return None; + } + if let Some(count) = word.strip_prefix('+') { + cut = count.parse().ok().filter(|&n| n != 0)?; + continue; + } + if word.len() != 2 { + return None; + } + bytes.push(u8::from_str_radix(word, 16).ok()?); + } + (!bytes.is_empty() && (cut == 0 || bytes.len() == CAPTURED_BYTES)).then_some(Self { + direction, + kind, + bytes, + cut, + }) + } +} + +impl fmt::Display for Captured { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} {}", self.direction.token(), self.kind.token())?; + for byte in &self.bytes { + write!(f, " {byte:02x}")?; + } + if self.cut != 0 { + write!(f, " +{}", self.cut)?; + } + Ok(()) + } +} + +/// What the function captures, and what it holds until the owner takes it. +#[derive(Debug, Clone, Default)] +pub(super) struct Capture { + /// Whether the owner asked for the capture. + enabled: bool, + /// Packets still captured in this configuration. + left: u16, + held: Vec, +} + +impl Capture { + /// The owner asks for the capture; it starts at once on a configured + /// function. + pub(super) fn enable(&mut self, configured: bool) { + if !self.enabled { + self.enabled = true; + if configured { + self.left = CAPTURED_PACKETS; + } + } + } + + /// The guest set the configuration to `value` (0: unconfigured). + pub(super) fn configured(&mut self, value: u8) { + self.left = if self.enabled && value != 0 { + CAPTURED_PACKETS + } else { + 0 + }; + } + + /// Captures `packet`; true when it was this configuration's last. + pub(super) fn record(&mut self, direction: Direction, kind: Kind, packet: &[u8]) -> bool { + if self.left == 0 { + return false; + } + self.left -= 1; + if self.held.len() < usize::from(CAPTURED_PACKETS) { + self.held.push(Captured::new(direction, kind, packet)); + } + self.left == 0 + } + + pub(super) fn take(&mut self) -> Vec { + core::mem::take(&mut self.held) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::{string::ToString, vec}; + + /// The `--bluetooth-trace` line format round-trips every packet. + #[test] + fn a_captured_line_reads_back_as_the_packet_it_shows() { + for direction in Direction::ALL { + for kind in Kind::ALL { + let packet = Captured::new(direction, kind, &[0x03, 0x0c, 0]); + assert_eq!(Captured::parse(&packet.to_string()), Some(packet)); + } + } + assert_eq!( + Captured::new(Direction::FromGuest, Kind::Command, &[0x03, 0x0c, 0]).to_string(), + "> cmd 03 0c 00" + ); + assert_eq!( + Captured::new(Direction::ToGuest, Kind::Event, &[0x0e, 4, 1, 3, 0x0c, 0]).to_string(), + "< evt 0e 04 01 03 0c 00" + ); + let long: Vec = (0..=255).cycle().take(1025).collect(); + let cut = Captured::new(Direction::FromChip, Kind::Acl, &long); + assert_eq!((cut.bytes.len(), cut.cut), (CAPTURED_BYTES, 725)); + let line = cut.to_string(); + assert!(line.starts_with("chip< acl 00 01 02 ") && line.ends_with(" 2b +725")); + assert_eq!(Captured::parse(&line), Some(cut)); + // Extra spaces between words read the same. + assert_eq!( + Captured::parse(" chip> cmd 01 04 05 33 8b 9e 08 00 "), + Some(Captured::new( + Direction::ToChip, + Kind::Command, + &[1, 4, 5, 0x33, 0x8b, 0x9e, 8, 0] + )) + ); + } + + #[test] + fn other_text_is_no_captured_packet() { + for bad in [ + "", + ">", + "> cmd", + "> sco 01", + "? cmd 01", + "> cmd 1", + "> cmd 001", + "> cmd 0g", + "> cmd 01 +", + "> cmd 01 +x", + "> cmd 01 +0", + "> cmd +3", + "> cmd 01 +3", + "> cmd 01 +3 02", + ] { + assert_eq!(Captured::parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn the_capture_holds_its_bound_per_configuration_and_only_once_asked() { + let mut capture = Capture::default(); + capture.configured(1); + assert!(!capture.record(Direction::FromGuest, Kind::Command, &[3, 0x0c, 0])); + assert!(capture.take().is_empty()); + capture.enable(true); + for _ in 1..CAPTURED_PACKETS { + assert!(!capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0])); + } + assert!(capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0])); + assert!(!capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0])); + assert_eq!(capture.take().len(), usize::from(CAPTURED_PACKETS)); + capture.configured(0); + assert!(!capture.record(Direction::FromGuest, Kind::Command, &[3, 0x0c, 0])); + capture.configured(1); + capture.record(Direction::FromGuest, Kind::Command, &[3, 0x0c, 0]); + assert_eq!( + capture.take(), + vec![Captured::new( + Direction::FromGuest, + Kind::Command, + &[3, 0x0c, 0] + )] + ); + } +} From 45c2920c443bec7c24a1e0caf094c78c9649c2e0 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:32:56 +0000 Subject: [PATCH 02/18] feat(bluetooth): add the core of a bridge to a lent host Bluetooth controller behind Apple's module, which answers every vendor command and every standard one off milestone 1's list from a shadow of the controller model, sends only listed standard commands to the host's controller, one in flight with one credit for the guest, and falls back to the model for good when the controller gives no answer in 1 s, fails, or answers with an error or a length the model would not give, where lending handed the host's controller every command of the guest --- crates/stela-soc/src/usb/hci.rs | 1 + crates/stela-soc/src/usb/hci/bridge.rs | 350 ++++++++++++++++++ crates/stela-soc/src/usb/hci/bridge/policy.rs | 159 ++++++++ crates/stela-soc/src/usb/hci/bridge/tests.rs | 267 +++++++++++++ 4 files changed, 777 insertions(+) create mode 100644 crates/stela-soc/src/usb/hci/bridge.rs create mode 100644 crates/stela-soc/src/usb/hci/bridge/policy.rs create mode 100644 crates/stela-soc/src/usb/hci/bridge/tests.rs diff --git a/crates/stela-soc/src/usb/hci.rs b/crates/stela-soc/src/usb/hci.rs index 265d92f7ea..28394cbbab 100644 --- a/crates/stela-soc/src/usb/hci.rs +++ b/crates/stela-soc/src/usb/hci.rs @@ -73,6 +73,7 @@ use alloc::{boxed::Box, collections::VecDeque, string::String, vec, vec::Vec}; use stela_contracts::refuse; use stela_drivers::usb::bluetooth::MAX_ACL_PAYLOAD; +pub mod bridge; pub mod capture; pub mod model; diff --git a/crates/stela-soc/src/usb/hci/bridge.rs b/crates/stela-soc/src/usb/hci/bridge.rs new file mode 100644 index 0000000000..03748c537d --- /dev/null +++ b/crates/stela-soc/src/usb/hci/bridge.rs @@ -0,0 +1,350 @@ +//! A host controller lent to the guest behind Apple's module +//! (`--bluetooth-lend`): the function keeps the module's identity, a shadow +//! of the controller model ([`Model`]) answers every vendor command and +//! every command the milestone keeps local, and only the standard commands +//! on [`policy`]'s list go to the host's controller, whose answers the guest +//! gets. +//! +//! The bridge decides, packet by packet, and does no I/O: [`Bridge::command`] +//! and [`Bridge::chip_event`] return [`Step`]s, an event for the guest or a +//! command for the host's controller, which the function queues for its +//! owner to carry. +//! +//! - The shadow executes every command, so it always holds the state the +//! guest set. Its own later events (an inquiry or page that ends) are +//! discarded while the bridge forwards. +//! - One forwarded command is in flight. The guest always sees one command +//! credit, as from the model; later commands wait their turn. +//! - Every forwarded command is answered by [`DEADLINE`]. If the host's +//! controller has not answered by then, fails, or answers with an error the +//! model would not give or of another kind or length than the model's, the +//! bridge falls back: the guest gets the shadow's answer to that command +//! and the shadow answers everything after it, for the rest of the boot. +//! Nothing goes to the host's controller again. So bluetoothd's bring-up, +//! and Setup's first screen, which waits for it, never wait on a stalled +//! controller. +use super::model::Model; +use crate::counter::FREQUENCY_HZ; +use alloc::{collections::VecDeque, vec, vec::Vec}; +use core::fmt; + +pub mod policy; + +pub use policy::ChipCommand; + +/// System counts the host's controller has to answer a forwarded command: +/// one second. +pub const DEADLINE: u64 = FREQUENCY_HZ; + +/// Commands that wait behind the one in flight; more stall the guest's +/// control transfer until one is answered. +pub const BACKLOG: usize = 64; + +// Events (Bluetooth Core v5.4 Vol 4 Part E 7.7). +const COMMAND_COMPLETE: u8 = 0x0e; +const COMMAND_STATUS: u8 = 0x0f; + +/// What the bridge does with a packet: an event for the guest, or a command +/// for the host's controller. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Step { + Guest(Vec), + Chip(ChipCommand), +} + +/// Why the bridge fell back to the model. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Cause { + /// No answer by [`DEADLINE`]. + Timeout, + /// This error status where the model answers success. + Refused(u8), + /// An answer of another kind or length than the model's. + Malformed, + /// The host's controller failed. + HostFailed, +} + +impl fmt::Display for Cause { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Timeout => f.write_str("no answer in 1 s"), + Self::Refused(status) => write!(f, "status {status:#04x} where the model succeeds"), + Self::Malformed => f.write_str("an answer of another kind or length than the model's"), + Self::HostFailed => f.write_str("the host controller failed"), + } + } +} + +/// The command the bridge fell back at, if one was in flight, and why. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Fallback { + pub opcode: Option, + pub cause: Cause, +} + +impl fmt::Display for Fallback { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.opcode { + Some(opcode) => write!(f, "{opcode:#06x} {}", self.cause), + None => write!(f, "between commands: {}", self.cause), + } + } +} + +/// Counters for the owner's log. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Counters { + /// Commands sent to the host's controller. + pub forwarded: u64, + /// Commands the shadow answered while the bridge forwarded. + pub local: u64, + /// Events of the host's controller the guest got. + pub passed: u64, + /// Events of the host's controller dropped: vendor events, credits + /// alone, stale answers, and every event after the fallback. + pub dropped: u64, +} + +/// The forwarded command in flight. +#[derive(Debug, Clone)] +struct Pending { + opcode: u16, + kind: policy::Forward, + /// The shadow's answer, the first of its events, given on a fallback. + shadow: Vec>, + deadline: u64, +} + +/// The bridge. +#[derive(Debug, Clone)] +pub struct Bridge { + shadow: Model, + fallen: Option, + pending: Option, + backlog: VecDeque>, + counters: Counters, +} + +/// The parts of a Command Complete or Command Status event that answers a +/// command, with its status. +pub(super) struct Completion<'a> { + pub code: u8, + pub opcode: u16, + pub status: u8, + pub returns: &'a [u8], +} + +/// Whether `event` is a Command Complete or Command Status, which answers a +/// command or only gives credits. +fn completes(event: &[u8]) -> bool { + matches!(event.first(), Some(&(COMMAND_COMPLETE | COMMAND_STATUS))) +} + +impl<'a> Completion<'a> { + pub(super) fn of(event: &'a [u8]) -> Option { + if event.len() < 2 || usize::from(event[1]) + 2 != event.len() { + return None; + } + match *event { + [COMMAND_COMPLETE, _, _, low, high, status, ref returns @ ..] => Some(Self { + code: COMMAND_COMPLETE, + opcode: u16::from_le_bytes([low, high]), + status, + returns, + }), + [COMMAND_STATUS, 4, status, _, low, high] => Some(Self { + code: COMMAND_STATUS, + opcode: u16::from_le_bytes([low, high]), + status, + returns: &[], + }), + _ => None, + } + } + + /// The event, with the one command credit the guest always sees. + fn event(&self, returns: &[u8]) -> Vec { + let [low, high] = self.opcode.to_le_bytes(); + if self.code == COMMAND_STATUS { + return vec![COMMAND_STATUS, 4, self.status, 1, low, high]; + } + let mut event = vec![COMMAND_COMPLETE, (4 + returns.len()) as u8, 1, low, high]; + event.push(self.status); + event.extend_from_slice(returns); + event + } +} + +/// The opcode of a command or of the completion event that answers one. +fn opcode(packet: &[u8]) -> u16 { + u16::from_le_bytes([packet[0], packet[1]]) +} + +fn guest(events: Vec>) -> Vec { + events.into_iter().map(Step::Guest).collect() +} + +impl Bridge { + /// A bridge whose shadow's power-on BD_ADDR is `address`. + pub fn new(address: [u8; 6]) -> Self { + Self { + shadow: Model::new(address), + fallen: None, + pending: None, + backlog: VecDeque::new(), + counters: Counters::default(), + } + } + + /// Why the bridge fell back to the model, once it has. + pub fn fallen(&self) -> Option { + self.fallen + } + + pub fn counters(&self) -> Counters { + self.counters + } + + /// The shadow's BD_ADDR now. + pub fn address(&self) -> [u8; 6] { + self.shadow.address() + } + + /// Opcodes the shadow answered Unknown HCI Command that were not taken + /// before, each once. + pub fn take_unknown(&mut self) -> Vec { + self.shadow.take_unknown() + } + + /// Whether another command can wait for its turn. + pub fn has_room(&self) -> bool { + self.backlog.len() < BACKLOG + } + + /// One command of the guest, header included, whose length its header + /// already matches. + pub fn command(&mut self, packet: &[u8], now: u64) -> Vec { + if self.pending.is_some() { + self.backlog.push_back(packet.to_vec()); + return Vec::new(); + } + self.start(packet, now) + } + + fn start(&mut self, packet: &[u8], now: u64) -> Vec { + let shadow = self.shadow.command(packet, now); + if self.fallen.is_some() { + return guest(shadow); + } + let Some((command, kind)) = policy::forward(packet) else { + self.counters.local += 1; + return guest(shadow); + }; + self.counters.forwarded += 1; + self.pending = Some(Pending { + opcode: opcode(packet), + kind, + shadow, + deadline: now.saturating_add(DEADLINE), + }); + vec![Step::Chip(command)] + } + + /// The commands that waited, until one is in flight again. + fn next(&mut self, now: u64) -> Vec { + let mut steps = Vec::new(); + while self.pending.is_none() + && let Some(packet) = self.backlog.pop_front() + { + steps.extend(self.start(&packet, now)); + } + steps + } + + /// Falls back for good; the guest gets the shadow's answer to the + /// command in flight, and the commands that waited are the shadow's. + fn fall(&mut self, cause: Cause, now: u64) -> Vec { + let pending = self.pending.take(); + self.fallen.get_or_insert(Fallback { + opcode: pending.as_ref().map(|p| p.opcode), + cause, + }); + let mut steps = pending.map(|p| guest(p.shadow)).unwrap_or_default(); + steps.extend(self.next(now)); + steps + } + + /// One event from the host's controller. + pub fn chip_event(&mut self, event: &[u8], now: u64) -> Vec { + if self.fallen.is_some() { + self.counters.dropped += 1; + return Vec::new(); + } + if completes(event) { + let completion = Completion::of(event); + let pending = completion + .as_ref() + .and_then(|completion| self.pending.take_if(|p| p.opcode == completion.opcode)); + let (Some(completion), Some(pending)) = (completion, pending) else { + // Credits alone (opcode 0, no status), or the answer to a + // command no longer in flight. + self.counters.dropped += 1; + return Vec::new(); + }; + return self.answer(pending, &completion, now); + } + self.counters.passed += 1; + vec![Step::Guest(event.to_vec())] + } + + fn answer(&mut self, pending: Pending, chip: &Completion<'_>, now: u64) -> Vec { + let shadow = pending.shadow.first().and_then(|e| Completion::of(e)); + match policy::answer(pending.kind, shadow.as_ref(), chip) { + Ok(returns) => { + self.counters.passed += 1; + let mut steps = vec![Step::Guest(chip.event(&returns))]; + steps.extend(self.next(now)); + steps + } + Err(cause) => { + self.pending = Some(pending); + self.fall(cause, now) + } + } + } + + /// The system count is `now`: a forwarded command past its deadline + /// falls back, and the shadow's procedures that ended give their events + /// once it has. + pub fn advance(&mut self, now: u64) -> Vec { + let mut steps = Vec::new(); + if self.pending.as_ref().is_some_and(|p| p.deadline <= now) { + steps = self.fall(Cause::Timeout, now); + } + let later = self.shadow.advance(now); + if self.fallen.is_some() { + steps.extend(guest(later)); + } + steps + } + + /// The earliest system count at which [`Self::advance`] has something + /// to do. + pub fn deadline(&self) -> Option { + let pending = self.pending.as_ref().map(|p| p.deadline); + let shadow = self.fallen.and(self.shadow.deadline()); + pending.into_iter().chain(shadow).min() + } + + /// The host's controller failed: the bridge falls back. + pub fn chip_failed(&mut self, now: u64) -> Vec { + if self.fallen.is_some() { + return Vec::new(); + } + self.fall(Cause::HostFailed, now) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-soc/src/usb/hci/bridge/policy.rs b/crates/stela-soc/src/usb/hci/bridge/policy.rs new file mode 100644 index 0000000000..ddf5c2c089 --- /dev/null +++ b/crates/stela-soc/src/usb/hci/bridge/policy.rs @@ -0,0 +1,159 @@ +//! Which of the guest's commands go to the host's controller: only the +//! standard commands on [`FORWARDED`]. Everything else, every vendor command +//! (OGF 0x3F) above all, is the shadow model's. Vendor opcodes mean other +//! things to other vendors' firmware: on a Realtek controller 0xFC20 +//! downloads firmware, 0xFC61 reads a register and 0xFC66 drops the +//! patch (Linux `drivers/bluetooth/btrtl.c`), so an Apple or Broadcom opcode +//! sent there could undo the host driver's setup. [`forward`] is the only +//! maker of a [`ChipCommand`], and it refuses any vendor opcode whatever the +//! list says, which a compile-time check also holds the list to. +//! +//! The list is milestone 1's, which lists nearby classic devices: the +//! controller resets and takes the guest's configuration (event masks, +//! inquiry mode, page timeout, names, class), and runs inquiries and remote +//! name requests. It keeps local: +//! +//! - the identity the module gives (Read Local Version Information and the +//! Broadcom vendor commands), so bluetoothd stays on its BCM20702B0 path; +//! - scan enable: with no command to accept a connection or answer pairing +//! in the model's Supported Commands, a connectable host controller would +//! hand bluetoothd requests it cannot answer; +//! - host flow control: controller-to-host flow control stays off in the +//! host's controller, as Linux leaves it, and the USB queues push back; +//! - connections and everything LE, the model's alone until later +//! milestones list them. +use super::{Cause, Completion}; +use alloc::vec::Vec; + +const VENDOR_GROUP: u16 = 0x3f; +const SUCCESS: u8 = 0x00; + +/// How the host controller's answer to a forwarded command becomes the +/// guest's. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Forward { + /// Configuration, reset and resources: the controller's answer, unless + /// it fails where the model succeeds. + Strict, + /// A radio procedure, whose error is the radio's outcome: the + /// controller's answer whatever its status. + Procedure, +} + +/// The standard commands milestone 1 forwards (opcode, Supported Commands +/// octet and bit of Bluetooth Core v5.4 Vol 4 Part E 6.27, kind). Each is +/// one the model implements and lists. +pub const FORWARDED: &[(u16, u8, u8, Forward)] = &[ + // Link control: inquiry and remote names. + (0x0401, 0, 0, Forward::Procedure), // Inquiry + (0x0402, 0, 1, Forward::Procedure), // Inquiry Cancel + (0x0419, 2, 3, Forward::Procedure), // Remote Name Request + (0x041a, 2, 4, Forward::Procedure), // Remote Name Request Cancel + // Link policy. + (0x080e, 5, 3, Forward::Strict), // Read Default Link Policy Settings + (0x080f, 5, 4, Forward::Strict), // Write Default Link Policy Settings + // Controller and baseband. + (0x0c01, 5, 6, Forward::Strict), // Set Event Mask + (0x0c03, 5, 7, Forward::Strict), // Reset + (0x0c13, 7, 0, Forward::Strict), // Write Local Name + (0x0c14, 7, 1, Forward::Strict), // Read Local Name + (0x0c15, 7, 2, Forward::Strict), // Read Connection Accept Timeout + (0x0c16, 7, 3, Forward::Strict), // Write Connection Accept Timeout + (0x0c17, 7, 4, Forward::Strict), // Read Page Timeout + (0x0c18, 7, 5, Forward::Strict), // Write Page Timeout + (0x0c1b, 8, 0, Forward::Strict), // Read Page Scan Activity + (0x0c1c, 8, 1, Forward::Strict), // Write Page Scan Activity + (0x0c1d, 8, 2, Forward::Strict), // Read Inquiry Scan Activity + (0x0c1e, 8, 3, Forward::Strict), // Write Inquiry Scan Activity + (0x0c1f, 8, 4, Forward::Strict), // Read Authentication Enable + (0x0c20, 8, 5, Forward::Strict), // Write Authentication Enable + (0x0c23, 9, 0, Forward::Strict), // Read Class Of Device + (0x0c24, 9, 1, Forward::Strict), // Write Class Of Device + (0x0c25, 9, 2, Forward::Strict), // Read Voice Setting + (0x0c26, 9, 3, Forward::Strict), // Write Voice Setting + (0x0c42, 12, 4, Forward::Strict), // Read Inquiry Scan Type + (0x0c43, 12, 5, Forward::Strict), // Write Inquiry Scan Type + (0x0c44, 12, 6, Forward::Strict), // Read Inquiry Mode + (0x0c45, 12, 7, Forward::Strict), // Write Inquiry Mode + (0x0c46, 13, 0, Forward::Strict), // Read Page Scan Type + (0x0c47, 13, 1, Forward::Strict), // Write Page Scan Type + (0x0c51, 17, 0, Forward::Strict), // Read Extended Inquiry Response + (0x0c52, 17, 1, Forward::Strict), // Write Extended Inquiry Response + (0x0c55, 17, 5, Forward::Strict), // Read Simple Pairing Mode + (0x0c56, 17, 6, Forward::Strict), // Write Simple Pairing Mode + (0x0c58, 18, 0, Forward::Strict), // Read Inquiry Response Transmit Power Level + (0x0c5a, 18, 2, Forward::Strict), // Read Default Erroneous Data Reporting + (0x0c5b, 18, 3, Forward::Strict), // Write Default Erroneous Data Reporting + (0x0c63, 22, 2, Forward::Strict), // Set Event Mask Page 2 + (0x0c6c, 24, 5, Forward::Strict), // Read LE Host Support + (0x0c6d, 24, 6, Forward::Strict), // Write LE Host Support + // Informational: the controller's own address. + (0x1009, 15, 1, Forward::Strict), // Read BD_ADDR + // LE: the event mask only. + (0x2001, 25, 0, Forward::Strict), // LE Set Event Mask +]; + +// No vendor opcode is ever on the list. +const _: () = { + let mut i = 0; + while i < FORWARDED.len() { + assert!(FORWARDED[i].0 >> 10 != VENDOR_GROUP); + i += 1; + } +}; + +/// A command the host's controller may be sent: a standard command on +/// [`FORWARDED`], never a vendor one. [`forward`] is its only maker. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChipCommand(Vec); + +impl ChipCommand { + pub fn opcode(&self) -> u16 { + u16::from_le_bytes([self.0[0], self.0[1]]) + } + + pub fn bytes(&self) -> &[u8] { + &self.0 + } + + pub fn into_bytes(self) -> Vec { + self.0 + } +} + +/// Whether `opcode` is a vendor command's. +pub fn vendor(opcode: u16) -> bool { + opcode >> 10 == VENDOR_GROUP +} + +/// `packet`, a whole command, as one for the host's controller, and how its +/// answer becomes the guest's; `None` for a command the shadow answers. +pub fn forward(packet: &[u8]) -> Option<(ChipCommand, Forward)> { + let opcode = u16::from_le_bytes([*packet.first()?, *packet.get(1)?]); + if vendor(opcode) { + return None; + } + let &(_, _, _, kind) = FORWARDED.iter().find(|entry| entry.0 == opcode)?; + Some((ChipCommand(packet.to_vec()), kind)) +} + +/// The return parameters of the guest's answer to a forwarded command, +/// from the host controller's answer `chip` and the shadow's, or why the +/// bridge falls back instead. +pub(super) fn answer( + kind: Forward, + shadow: Option<&Completion<'_>>, + chip: &Completion<'_>, +) -> Result, Cause> { + let Some(shadow) = shadow else { + return Ok(chip.returns.to_vec()); + }; + if chip.code != shadow.code || chip.returns.len() != shadow.returns.len() { + return Err(Cause::Malformed); + } + let refused = chip.status != SUCCESS && shadow.status == SUCCESS; + if refused && kind != Forward::Procedure { + return Err(Cause::Refused(chip.status)); + } + Ok(chip.returns.to_vec()) +} diff --git a/crates/stela-soc/src/usb/hci/bridge/tests.rs b/crates/stela-soc/src/usb/hci/bridge/tests.rs new file mode 100644 index 0000000000..6f2311e198 --- /dev/null +++ b/crates/stela-soc/src/usb/hci/bridge/tests.rs @@ -0,0 +1,267 @@ +use super::*; + +const ADDRESS: [u8; 6] = [0x11, 0x22, 0x33, 0x44, 0x55, 0x02]; +/// The host controller's own address, as a test gives it. +const CHIP_ADDRESS: [u8; 6] = [0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0x02]; + +fn packet(opcode: u16, parameters: &[u8]) -> Vec { + let mut packet = opcode.to_le_bytes().to_vec(); + packet.push(parameters.len() as u8); + packet.extend_from_slice(parameters); + packet +} + +/// A Command Complete with `credits`, `status` and `returns`. +fn complete(opcode: u16, credits: u8, status: u8, returns: &[u8]) -> Vec { + let [low, high] = opcode.to_le_bytes(); + let mut event = vec![ + COMMAND_COMPLETE, + 4 + returns.len() as u8, + credits, + low, + high, + status, + ]; + event.extend_from_slice(returns); + event +} + +fn status(opcode: u16, credits: u8, status: u8) -> Vec { + let [low, high] = opcode.to_le_bytes(); + vec![COMMAND_STATUS, 4, status, credits, low, high] +} + +/// The events of `steps`, which must send nothing to the host's controller. +fn events(steps: Vec) -> Vec> { + steps + .into_iter() + .map(|step| match step { + Step::Guest(event) => event, + Step::Chip(command) => panic!("{:#06x} went to the chip", command.opcode()), + }) + .collect() +} + +/// The command of `steps`, which must be exactly one for the host's +/// controller. +fn chip(steps: Vec) -> Vec { + match &steps[..] { + [Step::Chip(command)] => command.bytes().to_vec(), + _ => panic!("one command for the chip: {steps:02x?}"), + } +} + +#[test] +fn a_forwarded_answer_wins_over_the_shadows_and_has_one_credit() { + let mut bridge = Bridge::new(ADDRESS); + let read_address = packet(0x1009, &[]); + assert_eq!(chip(bridge.command(&read_address, 0)), read_address); + // The host controller's credits are its own. + let answer = events(bridge.chip_event(&complete(0x1009, 5, 0, &CHIP_ADDRESS), 10)); + assert_eq!(answer, [complete(0x1009, 1, 0, &CHIP_ADDRESS)]); + // A procedure answers with Command Status, also with one credit. + let inquiry = packet(0x0401, &[0x33, 0x8b, 0x9e, 8, 0]); + assert_eq!(chip(bridge.command(&inquiry, 20)), inquiry); + assert_eq!( + events(bridge.chip_event(&status(0x0401, 2, 0), 30)), + [status(0x0401, 1, 0)] + ); + assert_eq!(bridge.fallen(), None); + assert_eq!(bridge.counters().forwarded, 2); +} + +#[test] +fn vendor_and_unlisted_commands_are_the_shadows() { + let mut bridge = Bridge::new(ADDRESS); + // Read Local Version Information is the module's: Broadcom, Core 4.0. + let version = events(bridge.command(&packet(0x1001, &[]), 0)); + assert_eq!(version[0][5..], [0, 6, 0, 0, 6, 15, 0, 0x0e, 0x41]); + // Write BD_ADDR is the module's vendor command. + let written = events(bridge.command(&packet(0xfc01, &[9, 8, 7, 6, 5, 0x42]), 0)); + assert_eq!(written, [complete(0xfc01, 1, 0, &[])]); + assert_eq!(bridge.address(), [9, 8, 7, 6, 5, 0x42]); + // Every vendor opcode, of every parameter length the guest might send. + for ocf in 0..0x400u16 { + let opcode = 0x3f << 10 | ocf; + for length in [0, 1, 9] { + assert!(policy::forward(&packet(opcode, &vec![0; length])).is_none()); + for step in bridge.command(&packet(opcode, &vec![0; length]), 0) { + assert!( + matches!(step, Step::Guest(_)), + "{opcode:#06x} reached the chip" + ); + } + } + } + // A standard command not on the list. + let scan = events(bridge.command(&packet(0x0c1a, &[3]), 0)); + assert_eq!(scan, [complete(0x0c1a, 1, 0, &[])]); + assert_eq!(bridge.counters().forwarded, 0); + assert_eq!(bridge.fallen(), None); +} + +/// The list holds standard commands the model implements and lists, each +/// with the bit bluetoothd reads for it, once. +#[test] +fn the_forwarded_commands_are_standard_ones_the_model_lists() { + let bitmap = super::super::model::supported_commands(); + for (index, &(opcode, octet, bit, _)) in policy::FORWARDED.iter().enumerate() { + assert!(!policy::vendor(opcode)); + assert!(super::super::model::implements(opcode), "{opcode:#06x}"); + assert_ne!(bitmap[usize::from(octet)] & 1 << bit, 0, "{opcode:#06x}"); + for &(other, other_octet, other_bit, _) in &policy::FORWARDED[index + 1..] { + assert_ne!(other, opcode); + assert_ne!((other_octet, other_bit), (octet, bit), "{opcode:#06x}"); + } + } +} + +#[test] +fn one_command_is_in_flight_and_the_next_waits_its_turn() { + let mut bridge = Bridge::new(ADDRESS); + let reset = packet(0x0c03, &[]); + assert_eq!(chip(bridge.command(&reset, 0)), reset); + // A local command and a forwarded one wait behind it. + assert!(bridge.command(&packet(0x1001, &[]), 1).is_empty()); + let mask = packet(0x0c01, &[0xff; 8]); + assert!(bridge.command(&mask, 2).is_empty()); + let steps = bridge.chip_event(&complete(0x0c03, 1, 0, &[]), 3); + assert_eq!(steps.len(), 3); + assert_eq!(steps[0], Step::Guest(complete(0x0c03, 1, 0, &[]))); + assert!(matches!(&steps[1], Step::Guest(e) if e[3..5] == [0x01, 0x10])); + assert!(matches!(&steps[2], Step::Chip(c) if c.bytes() == mask)); + assert!(bridge.has_room()); +} + +#[test] +fn credits_alone_and_stale_answers_are_dropped() { + let mut bridge = Bridge::new(ADDRESS); + // Credits alone (opcode 0, no status), before and during a command. + assert!( + bridge + .chip_event(&[COMMAND_COMPLETE, 3, 1, 0, 0], 0) + .is_empty() + ); + let local_name = packet(0x0c14, &[]); + chip(bridge.command(&local_name, 0)); + assert!( + bridge + .chip_event(&[COMMAND_COMPLETE, 3, 1, 0, 0], 0) + .is_empty() + ); + assert!(bridge.chip_event(&status(0x0000, 1, 0), 0).is_empty()); + // An answer to another command than the one in flight. + assert!( + bridge + .chip_event(&complete(0x0c03, 1, 0, &[]), 0) + .is_empty() + ); + let answer = events(bridge.chip_event(&complete(0x0c14, 1, 0, &[0; 248]), 0)); + assert_eq!(answer.len(), 1); + assert_eq!(bridge.counters().dropped, 4); + assert_eq!(bridge.fallen(), None); +} + +#[test] +fn a_deadline_gives_the_shadows_answer_and_falls_back_for_good() { + let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(&packet(0x0c03, &[]), 100)); + assert_eq!(bridge.deadline(), Some(100 + DEADLINE)); + assert!(bridge.advance(100 + DEADLINE - 1).is_empty()); + let answer = events(bridge.advance(100 + DEADLINE)); + assert_eq!(answer, [complete(0x0c03, 1, 0, &[])]); + assert_eq!( + bridge.fallen(), + Some(Fallback { + opcode: Some(0x0c03), + cause: Cause::Timeout, + }) + ); + assert_eq!( + bridge.fallen().unwrap().to_string(), + "0x0c03 no answer in 1 s" + ); + // The late answer, and every event after, is dropped. + assert!( + bridge + .chip_event(&complete(0x0c03, 1, 0, &[]), 0) + .is_empty() + ); + assert!(bridge.chip_event(&[0x01, 1, 0], 0).is_empty()); + // Nothing reaches the host's controller again; the shadow answers. + let address = events(bridge.command(&packet(0x1009, &[]), 0)); + assert_eq!(address, [complete(0x1009, 1, 0, &ADDRESS)]); + // The shadow's procedures end with their events now. + let inquiry = events(bridge.command(&packet(0x0401, &[0x33, 0x8b, 0x9e, 1, 0]), 0)); + assert_eq!(inquiry, [status(0x0401, 1, 0)]); + let end = bridge.deadline().expect("the inquiry ends"); + assert_eq!(events(bridge.advance(end)), [vec![0x01, 1, 0]]); +} + +#[test] +fn an_error_the_model_would_not_give_falls_back_and_a_procedures_does_not() { + let mut bridge = Bridge::new(ADDRESS); + // Inquiry Cancel with no inquiry: the radio's outcome, passed on. + chip(bridge.command(&packet(0x0402, &[]), 0)); + let answer = events(bridge.chip_event(&complete(0x0402, 1, 0x0c, &[]), 0)); + assert_eq!(answer, [complete(0x0402, 1, 0x0c, &[])]); + // An error both give is the controller's. + let bad_mode = packet(0x0c45, &[7]); + chip(bridge.command(&bad_mode, 0)); + let answer = events(bridge.chip_event(&complete(0x0c45, 1, 0x12, &[]), 0)); + assert_eq!(answer, [complete(0x0c45, 1, 0x12, &[])]); + assert_eq!(bridge.fallen(), None); + // Set Event Mask refused where the model takes it. + let mask = packet(0x0c01, &[0xff; 8]); + chip(bridge.command(&mask, 0)); + let answer = events(bridge.chip_event(&complete(0x0c01, 1, 0x1f, &[]), 0)); + assert_eq!(answer, [complete(0x0c01, 1, 0, &[])]); + assert_eq!( + bridge.fallen(), + Some(Fallback { + opcode: Some(0x0c01), + cause: Cause::Refused(0x1f), + }) + ); +} + +#[test] +fn an_answer_of_another_kind_or_length_falls_back() { + for wrong in [ + // Read BD_ADDR with five bytes. + complete(0x1009, 1, 0, &[1, 2, 3, 4, 5]), + // Command Status for a command that completes. + status(0x1009, 1, 0), + ] { + let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(&packet(0x1009, &[]), 0)); + let answer = events(bridge.chip_event(&wrong, 0)); + assert_eq!(answer, [complete(0x1009, 1, 0, &ADDRESS)]); + assert_eq!(bridge.fallen().unwrap().cause, Cause::Malformed); + } +} + +#[test] +fn a_failed_host_controller_falls_back_with_the_answer_in_flight() { + let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(&packet(0x0c14, &[]), 0)); + assert!(bridge.command(&packet(0x0c03, &[]), 0).is_empty()); + let answers = events(bridge.chip_failed(0)); + assert_eq!( + answers.len(), + 2, + "the command in flight and the one waiting" + ); + assert_eq!(answers[0][2..6], [1, 0x14, 0x0c, 0]); + assert_eq!(answers[1], complete(0x0c03, 1, 0, &[])); + assert_eq!(bridge.fallen().unwrap().cause, Cause::HostFailed); + assert!(bridge.chip_failed(0).is_empty()); + // Between commands it falls back all the same. + let mut bridge = Bridge::new(ADDRESS); + assert!(bridge.chip_failed(0).is_empty()); + assert_eq!( + bridge.fallen().unwrap().to_string(), + "between commands: the host controller failed" + ); + events(bridge.command(&packet(0x0c03, &[]), 0)); +} From 14cba4a9c3acc6c5ba58bef5d0a8a389039242c2 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:45:17 +0000 Subject: [PATCH 03/18] feat(bluetooth): give the guest a lent controller's capabilities only merged with the model's, its supported commands and features less what the controller lacks of the forwarded ones, extended feature pages past 1 and LE features empty as the module's, and its ACL buffers with no synchronous ones, and check bluetoothd 26B123's whole start-up through the bridge and a scripted Realtek controller against the model step by step, where the controller's own Core 5.3 bitmap and features would have taken bluetoothd off the path it was traced on --- crates/stela-soc/src/usb/hci/bridge.rs | 2 + crates/stela-soc/src/usb/hci/bridge/chip.rs | 181 ++++++++++++++++++ .../hci/bridge/fixtures/26B123-bring-up.hci | 66 +++++++ crates/stela-soc/src/usb/hci/bridge/policy.rs | 104 +++++++++- crates/stela-soc/src/usb/hci/bridge/tests.rs | 153 +++++++++++++++ crates/stela-soc/src/usb/hci/capture.rs | 36 ++++ 6 files changed, 536 insertions(+), 6 deletions(-) create mode 100644 crates/stela-soc/src/usb/hci/bridge/chip.rs create mode 100644 crates/stela-soc/src/usb/hci/bridge/fixtures/26B123-bring-up.hci diff --git a/crates/stela-soc/src/usb/hci/bridge.rs b/crates/stela-soc/src/usb/hci/bridge.rs index 03748c537d..eb9ac802fe 100644 --- a/crates/stela-soc/src/usb/hci/bridge.rs +++ b/crates/stela-soc/src/usb/hci/bridge.rs @@ -346,5 +346,7 @@ impl Bridge { } } +#[cfg(test)] +mod chip; #[cfg(test)] mod tests; diff --git a/crates/stela-soc/src/usb/hci/bridge/chip.rs b/crates/stela-soc/src/usb/hci/bridge/chip.rs new file mode 100644 index 0000000000..409e02ba10 --- /dev/null +++ b/crates/stela-soc/src/usb/hci/bridge/chip.rs @@ -0,0 +1,181 @@ +//! A scripted stand-in for the host's controller: a standard Bluetooth +//! controller with an RTL8852C's identity after its patch, as Linux +//! `drivers/bluetooth/btrtl.c` and the Core specification describe one. The +//! bitmap, feature pages and buffer sizes are typical values, not ones read +//! from Garvit's chip (UNVERIFIED until a host check prints them). It +//! answers every standard command it lists with its specified return +//! lengths, records every command it is sent, and answers a vendor command, +//! which the bridge must never send, Unknown HCI Command. +use alloc::{vec, vec::Vec}; + +const COMMAND_COMPLETE: u8 = 0x0e; +const COMMAND_STATUS: u8 = 0x0f; +const SUCCESS: u8 = 0x00; +const UNKNOWN_COMMAND: u8 = 0x01; + +/// The controller's address in the tests. +pub const ADDRESS: [u8; 6] = [0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0x02]; +/// Read Local Version Information: Core 5.3 (12), Realtek (93). +pub const VERSION: [u8; 8] = [0x0c, 0x0c, 0x00, 0x0c, 0x5d, 0x00, 0x52, 0x88]; +/// LMP features page 0 of a Realtek combo controller: everything the model +/// lists and more (encryption, EDR, eSCO, sniff, role switch). +pub const FEATURES: [u8; 8] = [0xff, 0xff, 0xff, 0xfe, 0xdb, 0xfd, 0x7b, 0x87]; +/// Page 2: Secure Connections and more, which the bridge hides. +pub const FEATURES_2: [u8; 8] = [0x0f, 0x03, 0, 0, 0, 0, 0, 0]; +/// LE features: encryption, extended advertising and more. +pub const LE_FEATURES: [u8; 8] = [0xff, 0x59, 0x01, 0, 0, 0, 0, 0]; +/// Read Buffer Size: ACL 1021 x 6, SCO 255 x 12. +pub const BUFFERS: [u8; 7] = [0xfd, 0x03, 0xff, 0x06, 0x00, 0x0c, 0x00]; + +/// Commands that read what a write stored: (read, write, power-on value). +const SETTINGS: &[(u16, u16, &[u8])] = &[ + (0x080e, 0x080f, &[0, 0]), + (0x0c15, 0x0c16, &[0x40, 0x1f]), + (0x0c17, 0x0c18, &[0x00, 0x20]), + (0x0c19, 0x0c1a, &[0]), + (0x0c1b, 0x0c1c, &[0x00, 0x08, 0x12, 0x00]), + (0x0c1d, 0x0c1e, &[0x00, 0x10, 0x12, 0x00]), + (0x0c1f, 0x0c20, &[0]), + (0x0c23, 0x0c24, &[0, 0, 0]), + (0x0c25, 0x0c26, &[0x60, 0x00]), + (0x0c42, 0x0c43, &[0]), + (0x0c44, 0x0c45, &[0]), + (0x0c46, 0x0c47, &[0]), + (0x0c55, 0x0c56, &[0]), + (0x0c5a, 0x0c5b, &[0]), + (0x0c6c, 0x0c6d, &[0, 0]), +]; + +/// The stand-in controller. +#[derive(Debug, Clone)] +pub struct Chip { + /// Every command it was sent, in order. + pub received: Vec>, + /// Supported Commands. + pub commands: [u8; 64], + /// The credits each answer gives. + pub credits: u8, + /// LMP features page 0, and Read Buffer Size's return parameters. + pub features: [u8; 8], + pub buffers: [u8; 7], + /// Its settings since Reset: (write opcode, parameters). + written: Vec<(u16, Vec)>, + local_name: Vec, + eir: Vec, +} + +impl Chip { + pub fn new() -> Self { + // Every command of Core 5.3's first 42 octets. + let mut commands = [0; 64]; + commands[..42].fill(0xff); + Self { + received: Vec::new(), + commands, + credits: 2, + features: FEATURES, + buffers: BUFFERS, + written: Vec::new(), + local_name: vec![0; 248], + eir: vec![0; 241], + } + } + + /// Opcodes of the commands it was sent. + pub fn opcodes(&self) -> Vec { + self.received + .iter() + .map(|c| u16::from_le_bytes([c[0], c[1]])) + .collect() + } + + fn complete(&self, opcode: u16, status: u8, returns: &[u8]) -> Vec { + let [low, high] = opcode.to_le_bytes(); + let mut event = vec![ + COMMAND_COMPLETE, + 4 + returns.len() as u8, + self.credits, + low, + high, + ]; + event.push(status); + event.extend_from_slice(returns); + event + } + + fn status(&self, opcode: u16, status: u8) -> Vec { + let [low, high] = opcode.to_le_bytes(); + vec![COMMAND_STATUS, 4, status, self.credits, low, high] + } + + fn stored(&self, write: u16, default: &[u8]) -> Vec { + self.written + .iter() + .rev() + .find(|(opcode, _)| *opcode == write) + .map_or_else(|| default.to_vec(), |(_, p)| p.clone()) + } + + fn ok(&self, opcode: u16, returns: &[u8]) -> Vec> { + vec![self.complete(opcode, SUCCESS, returns)] + } + + /// One command; its events, in order. + pub fn command(&mut self, packet: &[u8]) -> Vec> { + self.received.push(packet.to_vec()); + let opcode = u16::from_le_bytes([packet[0], packet[1]]); + let p = packet[3..].to_vec(); + if let Some(&(_, write, default)) = SETTINGS.iter().find(|s| s.0 == opcode) { + return self.ok(opcode, &self.stored(write, default)); + } + if SETTINGS.iter().any(|s| s.1 == opcode) { + self.written.push((opcode, p)); + return self.ok(opcode, &[]); + } + match opcode { + 0x0401 | 0x0419 => vec![self.status(opcode, SUCCESS)], + 0x041a => self.ok(opcode, &p[..6]), + 0x0402 | 0x0c01 | 0x0c63 | 0x2001 => self.ok(opcode, &[]), + 0x0c03 => { + self.written.clear(); + self.local_name = vec![0; 248]; + self.eir = vec![0; 241]; + self.ok(opcode, &[]) + } + 0x0c13 => { + self.local_name = p; + self.ok(opcode, &[]) + } + 0x0c14 => self.ok(opcode, &self.local_name), + 0x0c51 => self.ok(opcode, &self.eir), + 0x0c52 => { + self.eir = p; + self.ok(opcode, &[]) + } + 0x0c58 => self.ok(opcode, &[0x04]), + 0x1001 => self.ok(opcode, &VERSION), + 0x1002 => self.ok(opcode, &self.commands), + 0x1003 => self.ok(opcode, &self.features), + 0x1004 => { + let features = match p[0] { + 0 => self.features, + 1 => { + let ssp = self.stored(0x0c56, &[0])[0]; + let le = self.stored(0x0c6d, &[0, 0])[0]; + [ssp | le << 1, 0, 0, 0, 0, 0, 0, 0] + } + 2 => FEATURES_2, + _ => [0; 8], + }; + let mut r = vec![p[0], 2]; + r.extend_from_slice(&features); + self.ok(opcode, &r) + } + 0x1005 => self.ok(opcode, &self.buffers), + 0x1009 => self.ok(opcode, &ADDRESS), + 0x2002 => self.ok(opcode, &[0xfb, 0x00, 0x08]), + 0x2003 => self.ok(opcode, &LE_FEATURES), + _ => vec![self.complete(opcode, UNKNOWN_COMMAND, &[])], + } + } +} diff --git a/crates/stela-soc/src/usb/hci/bridge/fixtures/26B123-bring-up.hci b/crates/stela-soc/src/usb/hci/bridge/fixtures/26B123-bring-up.hci new file mode 100644 index 0000000000..45cc4606a3 --- /dev/null +++ b/crates/stela-soc/src/usb/hci/bridge/fixtures/26B123-bring-up.hci @@ -0,0 +1,66 @@ +# bluetoothd 26B123's start-up on the USB transport, the guest's side only, +# in the `--bluetooth-trace` capture format (`hci/capture.rs`). Taken from +# the model's replay (`hci/model/tests.rs`, +# `bluetoothd_bring_up_completes_in_order`): its HCI bring-up (step table +# 0x100b38f70), the device configuration after it, the vendor commands of the +# stack's later start and the first multi-core LE scan, with the parameters +# bluetoothd sends. Addresses and names are synthetic. +# +# [1] Write BD_ADDR (sent when the platform stored an address), [4] Reset +> cmd 01 fc 06 06 05 04 03 02 42 +> cmd 03 0c 00 +# [5] Read Verbose Config Version Info, [6] version, [7] commands, +# [8] BD_ADDR, [9] features, [10] extended features page 2, [11] LE features +> cmd 79 fc 00 +> cmd 01 10 00 +> cmd 02 10 00 +> cmd 09 10 00 +> cmd 03 10 00 +> cmd 04 10 01 02 +> cmd 03 20 00 +# [12] Set Event Mask, [14] LE Set Event Mask, [15] SSP mode, [16] LE host +> cmd 01 0c 08 ff ff fb ff 07 f8 bf 3d +> cmd 01 20 08 1f 00 00 00 00 00 00 00 +> cmd 56 0c 01 01 +> cmd 6d 0c 02 01 00 +# [17] LE buffers, [19] LE states, [20] accept list, [21] buffers, +# [25] Host Buffer Size, [26] flow control, [27] erroneous data reporting +> cmd 02 20 00 +> cmd 1c 20 00 +> cmd 0f 20 00 +> cmd 05 10 00 +> cmd 33 0c 07 fd 03 00 08 00 00 00 +> cmd 31 0c 01 01 +> cmd 5b 0c 01 01 +# Device configuration: advertising power, class, name, page timeout, +# page and inquiry scan, Extended Inquiry Result mode, EIR +> cmd 07 20 00 +> cmd 24 0c 03 0c 01 1c +> cmd 23 0c 00 +> cmd 13 0c f8 4d 69 6e 69 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 +> cmd 14 0c 00 +> cmd 18 0c 02 00 20 +> cmd 1a 0c 01 03 +> cmd 45 0c 01 02 +> cmd 52 0c f1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 +# Vendor commands of the stack's later start, each answered Unknown HCI +# Command and tolerated +> cmd 27 fc 04 00 00 00 00 +> cmd 03 fd 04 00 00 00 00 +> cmd 3b fc 04 00 00 00 00 +> cmd 83 fe 04 00 00 00 00 +> cmd 23 fd 04 00 00 00 00 +> cmd f7 fc 04 00 00 00 00 +> cmd 5c fd 04 00 00 00 00 +> cmd e9 fc 05 00 00 00 00 00 +> cmd e2 fc 08 00 00 00 00 00 00 00 00 +> cmd 47 fd 03 00 00 00 +> cmd e9 fc 0e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 +# The first LE scan: multi-core parameters for the main core and the scan +# core, enable, duplicate list wipe, low-power core statistics, stop +> cmd 37 fe 0c 00 00 01 02 01 00 e0 01 30 00 1e 00 +> cmd 37 fe 0c 00 00 01 02 02 00 50 00 10 00 1e 00 +> cmd 29 fe 09 03 02 00 00 01 00 00 00 00 +> cmd 2a fe 01 01 +> cmd 3b fe 01 01 +> cmd 29 fe 09 00 02 00 00 03 00 00 00 00 diff --git a/crates/stela-soc/src/usb/hci/bridge/policy.rs b/crates/stela-soc/src/usb/hci/bridge/policy.rs index ddf5c2c089..e16f17e421 100644 --- a/crates/stela-soc/src/usb/hci/bridge/policy.rs +++ b/crates/stela-soc/src/usb/hci/bridge/policy.rs @@ -10,8 +10,9 @@ //! //! The list is milestone 1's, which lists nearby classic devices: the //! controller resets and takes the guest's configuration (event masks, -//! inquiry mode, page timeout, names, class), and runs inquiries and remote -//! name requests. It keeps local: +//! inquiry mode, page timeout, names, class), runs inquiries and remote +//! name requests, and gives its address, and its buffers and capabilities +//! merged with the model's ([`Merge`]). It keeps local: //! //! - the identity the module gives (Read Local Version Information and the //! Broadcom vendor commands), so bluetoothd stays on its BCM20702B0 path; @@ -24,6 +25,7 @@ //! milestones list them. use super::{Cause, Completion}; use alloc::vec::Vec; +use stela_drivers::usb::bluetooth::MAX_ACL_PAYLOAD; const VENDOR_GROUP: u16 = 0x3f; const SUCCESS: u8 = 0x00; @@ -38,6 +40,67 @@ pub enum Forward { /// A radio procedure, whose error is the radio's outcome: the /// controller's answer whatever its status. Procedure, + /// A capability: as [`Self::Strict`], its returns merged with the + /// model's. + Merge(Merge), +} + +/// How a capability the guest reads merges the controller's answer with +/// the model's, so bluetoothd stays on the path it was traced on with the +/// module (Core 4.0, BCM20702B0): it is never shown more than the model +/// claims, and never a forwarded command or a feature the controller +/// lacks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Merge { + /// Read Local Supported Commands: the model's bitmap, less each + /// forwarded command the controller lacks. A command the shadow answers + /// keeps its bit whatever the controller has. + Commands, + /// Read Local Supported Features: the model's features the controller + /// has too. + Features, + /// Read Local Extended Features, pages 0 and 1: likewise, under the + /// model's page number and maximum page, 1. Later pages are the + /// model's, empty, never asked of the controller: the module is a Core + /// 4.0 part, so BR/EDR Secure Connections stays hidden. + ExtendedFeatures, + /// Read Buffer Size: the controller's ACL buffers, no longer than the + /// transport carries, and no synchronous ones, as the function carries + /// no SCO data. + Buffers, + /// LE Read Local Supported Features: the controller's that + /// [`LE_FEATURES`] admits. + LeFeatures, +} + +/// The LE features milestone 1 shows: none, as the module has none. Any +/// feature bit bluetoothd reads as selecting LE Read Buffer Size v2 (0x2060) +/// or Read Local Supported Features v2 (0x2087) would send it a command the +/// model does not list. +pub const LE_FEATURES: [u8; 8] = [0; 8]; + +impl Merge { + /// The merged return parameters, of the model's length, which the + /// controller's has. + fn returns(self, shadow: &[u8], chip: &[u8]) -> Vec { + let both = |from: usize| shadow[from..].iter().zip(&chip[from..]).map(|(s, c)| s & c); + match self { + Self::Commands => shadow + .iter() + .zip(chip) + .zip(FORWARD_MASK) + .map(|((s, c), forwarded)| s & (!forwarded | c)) + .collect(), + Self::Features => both(0).collect(), + Self::ExtendedFeatures => shadow[..2].iter().copied().chain(both(2)).collect(), + Self::Buffers => { + let acl = u16::from_le_bytes([chip[0], chip[1]]).min(MAX_ACL_PAYLOAD as u16); + let [low, high] = acl.to_le_bytes(); + alloc::vec![low, high, 0, chip[3], chip[4], 0, 0] + } + Self::LeFeatures => chip.iter().zip(LE_FEATURES).map(|(c, a)| c & a).collect(), + } + } } /// The standard commands milestone 1 forwards (opcode, Supported Commands @@ -87,12 +150,33 @@ pub const FORWARDED: &[(u16, u8, u8, Forward)] = &[ (0x0c63, 22, 2, Forward::Strict), // Set Event Mask Page 2 (0x0c6c, 24, 5, Forward::Strict), // Read LE Host Support (0x0c6d, 24, 6, Forward::Strict), // Write LE Host Support - // Informational: the controller's own address. - (0x1009, 15, 1, Forward::Strict), // Read BD_ADDR - // LE: the event mask only. + // Informational: the capabilities, merged, and the controller's own + // address. + (0x1002, 14, 4, Forward::Merge(Merge::Commands)), // Read Local Supported Commands + (0x1003, 14, 5, Forward::Merge(Merge::Features)), // Read Local Supported Features + (0x1004, 14, 6, Forward::Merge(Merge::ExtendedFeatures)), // Read Local Extended Features + (0x1005, 14, 7, Forward::Merge(Merge::Buffers)), // Read Buffer Size + (0x1009, 15, 1, Forward::Strict), // Read BD_ADDR + // LE: the event mask and the features, merged. (0x2001, 25, 0, Forward::Strict), // LE Set Event Mask + (0x2003, 25, 2, Forward::Merge(Merge::LeFeatures)), // LE Read Local Supported Features ]; +/// The Supported Commands bits of [`FORWARDED`]. +const FORWARD_MASK: [u8; 64] = { + let mut mask = [0; 64]; + let mut i = 0; + while i < FORWARDED.len() { + let (_, octet, bit, _) = FORWARDED[i]; + mask[octet as usize] |= 1 << bit; + i += 1; + } + mask +}; + +/// Read Local Extended Features, whose pages past 1 are the model's. +const READ_EXTENDED_FEATURES: u16 = 0x1004; + // No vendor opcode is ever on the list. const _: () = { let mut i = 0; @@ -134,6 +218,9 @@ pub fn forward(packet: &[u8]) -> Option<(ChipCommand, Forward)> { return None; } let &(_, _, _, kind) = FORWARDED.iter().find(|entry| entry.0 == opcode)?; + if opcode == READ_EXTENDED_FEATURES && packet.get(3).is_none_or(|&page| page > 1) { + return None; + } Some((ChipCommand(packet.to_vec()), kind)) } @@ -155,5 +242,10 @@ pub(super) fn answer( if refused && kind != Forward::Procedure { return Err(Cause::Refused(chip.status)); } - Ok(chip.returns.to_vec()) + Ok(match kind { + Forward::Merge(merge) if chip.status == SUCCESS => { + merge.returns(shadow.returns, chip.returns) + } + _ => chip.returns.to_vec(), + }) } diff --git a/crates/stela-soc/src/usb/hci/bridge/tests.rs b/crates/stela-soc/src/usb/hci/bridge/tests.rs index 6f2311e198..76bb242ea1 100644 --- a/crates/stela-soc/src/usb/hci/bridge/tests.rs +++ b/crates/stela-soc/src/usb/hci/bridge/tests.rs @@ -1,3 +1,5 @@ +use super::super::model::{self, Model}; +use super::chip::{self, Chip}; use super::*; const ADDRESS: [u8; 6] = [0x11, 0x22, 0x33, 0x44, 0x55, 0x02]; @@ -265,3 +267,154 @@ fn a_failed_host_controller_falls_back_with_the_answer_in_flight() { ); events(bridge.command(&packet(0x0c03, &[]), 0)); } + +/// bluetoothd 26B123's start-up, the guest's side. +const BRING_UP: &str = include_str!("fixtures/26B123-bring-up.hci"); + +/// The commands the guest sent in a capture. +fn commands(capture: &str) -> Vec> { + use super::super::capture::{Direction, Kind, read}; + read(capture) + .expect("a capture") + .into_iter() + .filter(|p| p.direction == Direction::FromGuest && p.kind == Kind::Command) + .map(|p| p.bytes) + .collect() +} + +/// One guest command through `bridge`, `chip` answering at once what +/// reaches it, until nothing is left to carry: the guest's events. +fn exchange(bridge: &mut Bridge, chip: &mut Chip, command: &[u8]) -> Vec> { + let mut steps: VecDeque = bridge.command(command, 0).into(); + let mut events = Vec::new(); + while let Some(step) = steps.pop_front() { + match step { + Step::Guest(event) => events.push(event), + Step::Chip(command) => { + for event in chip.command(command.bytes()) { + steps.extend(bridge.chip_event(&event, 0)); + } + } + } + } + events +} + +/// The return parameters of the one successful Command Complete of `events`. +fn returns(events: &[Vec]) -> Vec { + assert_eq!(events.len(), 1, "{events:02x?}"); + let completion = Completion::of(&events[0]).expect("a completion"); + assert_eq!((completion.code, completion.status), (COMMAND_COMPLETE, 0)); + completion.returns.to_vec() +} + +/// The differential replay: bluetoothd's whole start-up through the bridge +/// and a controller that has everything the model lists gets, at every +/// step, the pure model's event, status and return length, and the same +/// returns but for the controller's own address and ACL buffers. Only the +/// listed standard commands reach the controller, in order. +#[test] +fn bluetoothds_start_up_through_the_bridge_answers_as_the_model_does() { + let mut model = Model::new(ADDRESS); + let mut bridge = Bridge::new(ADDRESS); + let mut chip = Chip::new(); + let start_up = commands(BRING_UP); + assert_eq!(start_up.len(), 46); + for command in &start_up { + let op = opcode(command); + let expected = model.command(command, 0); + let got = exchange(&mut bridge, &mut chip, command); + assert_eq!(got.len(), expected.len(), "{op:#06x}"); + for (got, expected) in got.iter().zip(&expected) { + let (g, e) = ( + Completion::of(got).unwrap(), + Completion::of(expected).unwrap(), + ); + assert_eq!( + (g.code, g.opcode, g.status, g.returns.len()), + (e.code, e.opcode, e.status, e.returns.len()), + "{op:#06x}" + ); + assert_eq!(got[2 + usize::from(g.code == COMMAND_STATUS)], 1); + match op { + 0x1009 => assert_eq!(g.returns, chip::ADDRESS), + 0x1005 => assert_eq!(g.returns, [0xfd, 0x03, 0, 6, 0, 0, 0]), + _ => assert_eq!(got, expected, "{op:#06x}"), + } + } + } + assert_eq!(bridge.fallen(), None); + assert_eq!( + chip.opcodes(), + [ + 0x0c03, 0x1002, 0x1009, 0x1003, 0x2003, 0x0c01, 0x2001, 0x0c56, 0x0c6d, 0x1005, 0x0c5b, + 0x0c24, 0x0c23, 0x0c13, 0x0c14, 0x0c18, 0x0c45, 0x0c52, + ] + ); + // The module's identity stays: Core 4.0 Broadcom, chip id 73, its IDs. + let version = returns(&exchange(&mut bridge, &mut chip, &packet(0x1001, &[]))); + assert_eq!(version, [6, 0, 0, 6, 15, 0, 0x0e, 0x41]); + let verbose = returns(&exchange(&mut bridge, &mut chip, &packet(0xfc79, &[]))); + assert_eq!(verbose[0], 73); + let product = returns(&exchange(&mut bridge, &mut chip, &packet(0xfc5a, &[]))); + assert_eq!(product, [0xac, 0x05, 0x8f, 0x82]); + assert_eq!(chip.opcodes().len(), 18); +} + +/// The capabilities the guest reads are the model's, less what the +/// controller lacks of the commands it is sent, and never more. +#[test] +fn the_merge_keeps_the_modules_capabilities_less_what_the_controller_lacks() { + let mut chip = Chip::new(); + // No Write Default Erroneous Data Reporting (octet 18 bit 3) or Write + // Inquiry Mode (12, 7), both forwarded; no Write Scan Enable (7, 7) or + // Host Number Of Completed Packets (10, 7), both the shadow's. + for (octet, bit) in [(18, 3), (12, 7), (7, 7), (10, 7)] { + chip.commands[octet] &= !(1 << bit); + } + // No extended inquiry response (feature bit 48). + chip.features[6] &= !1; + // ACL longer than the transport carries. + chip.buffers[..2].copy_from_slice(&0x2000u16.to_le_bytes()); + let mut bridge = Bridge::new(ADDRESS); + let model = model::supported_commands(); + let bitmap = returns(&exchange(&mut bridge, &mut chip, &packet(0x1002, &[]))); + for octet in 0..64 { + let lacking = match octet { + 18 => 1 << 3, + 12 => 1 << 7, + _ => 0, + }; + assert_eq!(bitmap[octet], model[octet] & !lacking, "octet {octet}"); + } + // Features: the model's, less what the controller lacks. + let features = returns(&exchange(&mut bridge, &mut chip, &packet(0x1003, &[]))); + let expected = returns(&Model::new(ADDRESS).command(&packet(0x1003, &[]), 0)); + assert_ne!(expected[6] & 1, 0, "the model has it"); + assert_eq!(features[6], expected[6] & !1); + for ((feature, model), chip) in features.iter().zip(&expected).zip(chip.features) { + assert_eq!(*feature, model & chip); + } + // Extended features: the model's page numbers, maximum 1; page 1 as + // both have it; page 2 the module's, empty, whatever the controller has. + for page in [0, 1] { + let extended = returns(&exchange(&mut bridge, &mut chip, &packet(0x1004, &[page]))); + assert_eq!(extended[..2], [page, 1]); + } + let page_2 = returns(&exchange(&mut bridge, &mut chip, &packet(0x1004, &[2]))); + assert_eq!(page_2, [2, 1, 0, 0, 0, 0, 0, 0, 0, 0]); + assert!( + chip.received + .iter() + .all(|c| opcode(c) != 0x1004 || c[3] < 2), + "later pages stay the module's" + ); + // Buffers: the controller's ACL buffers, as long as the transport + // carries at most; no synchronous ones. + let buffers = returns(&exchange(&mut bridge, &mut chip, &packet(0x1005, &[]))); + assert_eq!(buffers, [0x00, 0x10, 0, 6, 0, 0, 0]); + // LE features: none in milestone 1, whatever the controller has. + let le = returns(&exchange(&mut bridge, &mut chip, &packet(0x2003, &[]))); + assert_eq!(le, [0; 8]); + assert_eq!(bridge.fallen(), None); +} diff --git a/crates/stela-soc/src/usb/hci/capture.rs b/crates/stela-soc/src/usb/hci/capture.rs index 5e713658be..df40b972cc 100644 --- a/crates/stela-soc/src/usb/hci/capture.rs +++ b/crates/stela-soc/src/usb/hci/capture.rs @@ -132,6 +132,26 @@ impl fmt::Display for Captured { } } +/// What starts each captured packet's line in the boot log. +pub const LOG_PREFIX: &str = "GUEST BLUETOOTH RAW "; + +/// The packets of a capture: each line [`Captured::parse`] reads, on its own +/// or after [`LOG_PREFIX`] as the boot log writes it, blank lines and `#` +/// comments skipped. `Err` names the first other line, counted from 1. +pub fn read(text: &str) -> Result, usize> { + text.lines() + .enumerate() + .filter_map(|(index, line)| { + let line = line + .find(LOG_PREFIX) + .map_or(line, |at| &line[at + LOG_PREFIX.len()..]) + .trim(); + (!line.is_empty() && !line.starts_with('#')) + .then(|| Captured::parse(line).ok_or(index + 1)) + }) + .collect() +} + /// What the function captures, and what it holds until the owner takes it. #[derive(Debug, Clone, Default)] pub(super) struct Capture { @@ -241,6 +261,22 @@ mod tests { } } + /// A fixture's lines, or the boot log's raw lines as grep gives them. + #[test] + fn a_capture_reads_from_its_own_lines_or_the_boot_logs() { + let text = "# a comment\n\n> cmd 03 0c 00\n\ + [ 12.5] GUEST BLUETOOTH RAW < evt 0e 04 01 03 0c 00\n"; + assert_eq!( + read(text), + Ok(vec![ + Captured::new(Direction::FromGuest, Kind::Command, &[3, 0x0c, 0]), + Captured::new(Direction::ToGuest, Kind::Event, &[0x0e, 4, 1, 3, 0x0c, 0]), + ]) + ); + assert_eq!(read("> cmd 03 0c 00\nGUEST BLUETOOTH up\n"), Err(2)); + assert_eq!(read(""), Ok(vec![])); + } + #[test] fn the_capture_holds_its_bound_per_configuration_and_only_once_asked() { let mut capture = Capture::default(); From ae2efdfcd9e4b3c31d042c5618393fa70e106534 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:02:44 +0000 Subject: [PATCH 04/18] feat(bluetooth): carry a lent controller's packets through the bridge in the guest's Bluetooth function, which drops the controller's vendor events, credits alone and stale answers, keeps it out after a guest bus reset or new configuration until the guest's next HCI Reset is answered, never USB-resets it, gives the guest's ACL data to the shadow that owns every connection in milestone 1, and ends in the shadow each procedure the controller ended or refused; the engine reaches the controller through a HostController trait and a link that hands the guest at most its room left and tells the function when the controller fails, where one poll could overrun the guest's queues and a failed controller left its commands unanswered --- crates/stela-boot/src/engine/bluetooth.rs | 221 ++++----- crates/stela-boot/src/engine/service.rs | 12 +- crates/stela-soc/src/machine/usb.rs | 14 + crates/stela-soc/src/usb/hci.rs | 450 +++++++++++++++++-- crates/stela-soc/src/usb/hci/bridge.rs | 152 ++++++- crates/stela-soc/src/usb/hci/bridge/link.rs | 182 ++++++++ crates/stela-soc/src/usb/hci/bridge/tests.rs | 139 ++++++ 7 files changed, 1027 insertions(+), 143 deletions(-) create mode 100644 crates/stela-soc/src/usb/hci/bridge/link.rs diff --git a/crates/stela-boot/src/engine/bluetooth.rs b/crates/stela-boot/src/engine/bluetooth.rs index ab7d24d733..edffc33114 100644 --- a/crates/stela-boot/src/engine/bluetooth.rs +++ b/crates/stela-boot/src/engine/bluetooth.rs @@ -1,8 +1,9 @@ //! The host's Bluetooth controller behind the guest's USB one //! (`stela_soc::usb::hci`): HCI commands and ACL data the guest queued go to //! the first controller probe left healthy, and its events and ACL data come -//! back while the guest's queues have room. The rest wait in the host -//! controller, as they would for a host that reads slowly. +//! back as far as the guest's queues have room. The rest wait in the host +//! controller, or in the link (`stela_soc::usb::hci::bridge::Link`) when one +//! poll gave more, as they would for a host that reads slowly. //! //! The guest is given the controller model (`stela_soc::usb::hci::model`), //! presented as Apple's internal USB module, which answers inside the @@ -15,8 +16,9 @@ //! `stela_soc::usb::hci::capture::CAPTURED_PACKETS` per configuration). //! //! One controller serves the guest; others are reported and left idle. A -//! controller that fails is reported once, and the guest's commands then get -//! no answer, as from a controller that stopped responding. +//! controller that fails is reported once, and told to the guest's function: +//! a raw function's commands then get no answer, as from a controller that +//! stopped responding. //! //! The controllers' registers and DMA pages are reached through the loader's //! identity root, so each exchange runs in it (`storage::RestoreRoot`). An @@ -25,16 +27,19 @@ //! busy the guest's packets wait here and the controller's in the //! controller, for the next service turn. use super::{output, storage::RestoreRoot}; -use alloc::{boxed::Box, collections::VecDeque, string::String, vec::Vec}; +use alloc::{boxed::Box, format, string::String, vec::Vec}; use stela_boot_core::options::System; use stela_drivers::{ bluetooth::{bcm4377, intel_pcie}, probe::native::{Bcm4377, IntelBluetooth, PcieController, PcieHci}, usb::bluetooth::{Packet, UsbHci}, }; -use stela_soc::machine::{ - AppleDevices, Outbound, UsbBluetooth, UsbBluetoothCaptured, UsbBluetoothCounters, - UsbBluetoothTrace, +use stela_soc::{ + machine::{ + AppleDevices, Outbound, UsbBluetooth, UsbBluetoothCaptured, UsbBluetoothCounters, + UsbBluetoothTrace, + }, + usb::hci::bridge::{HostController, Link}, }; enum Controller { @@ -45,20 +50,91 @@ enum Controller { Modeled, } -/// Whether a controller took a packet, or holds it back for now. -enum Sent { - Taken, - Busy, +/// The host drivers' transports, as a service turn reaches them. +impl HostController for Controller { + fn send(&mut self, packet: &Outbound) -> Result { + match (self, packet) { + (Controller::Usb(hci), Outbound::Command(bytes)) => hci + .submit_command(bytes) + .map(|()| true) + .map_err(|error| format!("{error}")), + (Controller::Usb(hci), Outbound::Acl(bytes)) => hci + .submit_acl(bytes) + .map(|()| true) + .map_err(|error| format!("{error}")), + (Controller::Intel(transport), packet) => { + let (kind, bytes) = match packet { + Outbound::Command(bytes) => (intel_pcie::Kind::Command, bytes), + Outbound::Acl(bytes) => (intel_pcie::Kind::Acl, bytes), + }; + if !transport.ready() { + return Ok(false); + } + transport + .send(kind, bytes) + .map(|_| true) + .map_err(|error| format!("{error:?}")) + } + (Controller::Modeled, _) => Ok(true), + (Controller::Broadcom(transport), packet) => { + let (kind, bytes) = match packet { + Outbound::Command(bytes) => (bcm4377::Kind::Command, bytes), + Outbound::Acl(bytes) => (bcm4377::Kind::Acl, bytes), + }; + match transport.send(kind, bytes) { + Ok(_) => Ok(true), + Err(bcm4377::Error::QueueFull(_)) => Ok(false), + Err(error) => Err(format!("{error:?}")), + } + } + } + } + + fn poll(&mut self) -> Result, String> { + match self { + Controller::Modeled => Ok(Vec::new()), + Controller::Usb(hci) => hci.poll().map_err(|error| format!("{error}")), + Controller::Intel(transport) => transport + .poll() + .map(|packets| { + let useful = packets.into_iter().filter(|packet| !packet.diagnostic); + useful + .filter_map(|packet| match packet.kind { + intel_pcie::Kind::Event => Some(Packet::Event(packet.bytes)), + intel_pcie::Kind::Acl => Some(Packet::Acl(packet.bytes)), + _ => None, + }) + .collect() + }) + .map_err(|error| format!("{error:?}")), + Controller::Broadcom(transport) => transport + .poll() + .map(|observations| { + let packets = observations.packets.into_iter(); + packets + .filter_map(|packet| match packet.kind { + bcm4377::Kind::Event => Some(Packet::Event(packet.bytes)), + bcm4377::Kind::Acl => Some(Packet::Acl(packet.bytes)), + _ => None, + }) + .collect() + }) + .map_err(|error| format!("{error:?}")), + } + } } pub struct HostBluetooth { controller: Controller, location: String, root: u64, - /// What the guest sent that the controller has no room for yet. - waiting: VecDeque, + /// What the guest sent that the controller has no room for yet, and + /// what it gave that the guest has none for. + link: Link, up: Option, failed: bool, + /// Whether the failure is still to be told to the guest's function. + failure_due: bool, /// Commands the model answered Unknown HCI Command, to report. unknown: Vec, /// The command count reported last. @@ -111,9 +187,10 @@ impl HostBluetooth { controller, location, root, - waiting: VecDeque::new(), + link: Link::default(), up: None, failed: false, + failure_due: false, unknown: Vec::new(), reported_commands: 0, trace: Vec::new(), @@ -129,9 +206,10 @@ impl HostBluetooth { controller: Controller::Modeled, location: String::from("model"), root, - waiting: VecDeque::new(), + link: Link::default(), up: None, failed: false, + failure_due: false, unknown: Vec::new(), reported_commands: 0, trace: Vec::new(), @@ -163,12 +241,12 @@ impl HostBluetooth { } } - /// What the guest queued, whether it can take more, and its status, + /// What the guest queued, how many packets it takes, and its status, /// taken from its devices for the exchange to run without them. pub fn queued( &mut self, devices: &mut AppleDevices, - ) -> (Vec, bool, Option<(bool, UsbBluetoothCounters)>) { + ) -> (Vec, usize, Option<(bool, UsbBluetoothCounters)>) { if matches!(self.controller, Controller::Modeled) { self.unknown.extend(devices.bluetooth_unknown()); } @@ -182,7 +260,7 @@ impl HostBluetooth { let packets = core::iter::from_fn(|| devices.bluetooth_take()).collect(); ( packets, - devices.bluetooth_room(), + devices.bluetooth_room_left(), devices.bluetooth_status(), ) } @@ -193,7 +271,8 @@ impl HostBluetooth { self.location )); self.failed = true; - self.waiting.clear(); + self.failure_due = true; + self.link.clear(); } /// Reports the guest's controller going up or down. @@ -239,107 +318,44 @@ impl HostBluetooth { if self.failed || matches!(self.controller, Controller::Modeled) { return; } - self.waiting.extend(packets); + self.link.queue(packets); // SAFETY: the loader root `storage::open` captured, which maps the // controllers' registers and DMA pages for the whole run. let Some(_root) = (unsafe { RestoreRoot::try_enter(self.root) }) else { return; }; - while let Some(packet) = self.waiting.front() { - let sent = match (&mut self.controller, packet) { - (Controller::Usb(hci), Outbound::Command(bytes)) => hci - .submit_command(bytes) - .map(|()| Sent::Taken) - .map_err(|error| alloc::format!("{error}")), - (Controller::Usb(hci), Outbound::Acl(bytes)) => hci - .submit_acl(bytes) - .map(|()| Sent::Taken) - .map_err(|error| alloc::format!("{error}")), - (Controller::Intel(transport), packet) => { - let (kind, bytes) = match packet { - Outbound::Command(bytes) => (intel_pcie::Kind::Command, bytes), - Outbound::Acl(bytes) => (intel_pcie::Kind::Acl, bytes), - }; - if transport.ready() { - transport - .send(kind, bytes) - .map(|_| Sent::Taken) - .map_err(|error| alloc::format!("{error:?}")) - } else { - Ok(Sent::Busy) - } - } - (Controller::Modeled, _) => Ok(Sent::Taken), - (Controller::Broadcom(transport), packet) => { - let (kind, bytes) = match packet { - Outbound::Command(bytes) => (bcm4377::Kind::Command, bytes), - Outbound::Acl(bytes) => (bcm4377::Kind::Acl, bytes), - }; - match transport.send(kind, bytes) { - Ok(_) => Ok(Sent::Taken), - Err(bcm4377::Error::QueueFull(_)) => Ok(Sent::Busy), - Err(error) => Err(alloc::format!("{error:?}")), - } - } - }; - match sent { - Ok(Sent::Taken) => { - self.waiting.pop_front(); - } - Ok(Sent::Busy) => return, - Err(error) => return self.refuse("sending", error), - } + if let Err(error) = self.link.send(&mut self.controller) { + self.refuse("sending", error); } } - /// What the controller has for the guest. - pub fn receive(&mut self) -> Vec { - if self.failed || matches!(self.controller, Controller::Modeled) { + /// What the controller has for the guest, at most `room` packets; the + /// rest waits in the link for a later turn. + pub fn receive(&mut self, room: usize) -> Vec { + if self.failed || room == 0 || matches!(self.controller, Controller::Modeled) { return Vec::new(); } // SAFETY: as in `transmit`. let Some(_root) = (unsafe { RestoreRoot::try_enter(self.root) }) else { return Vec::new(); }; - let received = match &mut self.controller { - Controller::Modeled => Ok(Vec::new()), - Controller::Usb(hci) => hci.poll().map_err(|error| alloc::format!("{error}")), - Controller::Intel(transport) => transport - .poll() - .map(|packets| { - let useful = packets.into_iter().filter(|packet| !packet.diagnostic); - useful - .filter_map(|packet| match packet.kind { - intel_pcie::Kind::Event => Some(Packet::Event(packet.bytes)), - intel_pcie::Kind::Acl => Some(Packet::Acl(packet.bytes)), - _ => None, - }) - .collect() - }) - .map_err(|error| alloc::format!("{error:?}")), - Controller::Broadcom(transport) => transport - .poll() - .map(|observations| { - let packets = observations.packets.into_iter(); - packets - .filter_map(|packet| match packet.kind { - bcm4377::Kind::Event => Some(Packet::Event(packet.bytes)), - bcm4377::Kind::Acl => Some(Packet::Acl(packet.bytes)), - _ => None, - }) - .collect() - }) - .map_err(|error| alloc::format!("{error:?}")), - }; + let received = self.link.receive(&mut self.controller, room); received.unwrap_or_else(|error| { self.refuse("receiving", error); Vec::new() }) } - /// Hands `packets` to the guest's controller. A vendor diagnostic frame - /// is not ACL data and stays here. - pub fn deliver(devices: &mut AppleDevices, packets: Vec) { + /// Whether the controller's failure is still to be told to the guest's + /// function. + pub fn failure_due(&self) -> bool { + self.failure_due + } + + /// Hands `packets` to the guest's controller, then the host + /// controller's failure, once. A vendor diagnostic frame is not ACL data + /// and stays here. + pub fn deliver(&mut self, devices: &mut AppleDevices, packets: Vec) { for packet in packets { match packet { Packet::Event(bytes) => devices.bluetooth_event(&bytes), @@ -347,5 +363,8 @@ impl HostBluetooth { Packet::Diagnostic(_) => {} } } + if core::mem::take(&mut self.failure_due) { + devices.bluetooth_host_failed(); + } } } diff --git a/crates/stela-boot/src/engine/service.rs b/crates/stela-boot/src/engine/service.rs index 99bbf98caf..1cab4a53c8 100644 --- a/crates/stela-boot/src/engine/service.rs +++ b/crates/stela-boot/src/engine/service.rs @@ -33,7 +33,7 @@ use super::{ bluetooth, host, input, install_progress, network, nor, output, parallel, power, restore, usb, }; -use alloc::{format, string::String, vec::Vec}; +use alloc::{format, string::String}; use core::{ cell::UnsafeCell, sync::atomic::{AtomicBool, AtomicU64, Ordering}, @@ -398,13 +398,9 @@ impl Service { let (packets, room, status) = devices.with(|devices| bluetooth.queued(devices)); bluetooth.status(status); bluetooth.transmit(packets); - let received = if room { - bluetooth.receive() - } else { - Vec::new() - }; - if !received.is_empty() { - devices.serve(|devices| bluetooth::HostBluetooth::deliver(devices, received)); + let received = bluetooth.receive(room); + if !received.is_empty() || bluetooth.failure_due() { + devices.serve(|devices| bluetooth.deliver(devices, received)); } lap.part(Part::Bluetooth); } diff --git a/crates/stela-soc/src/machine/usb.rs b/crates/stela-soc/src/machine/usb.rs index 89fadf30c8..c384280fe1 100644 --- a/crates/stela-soc/src/machine/usb.rs +++ b/crates/stela-soc/src/machine/usb.rs @@ -241,6 +241,20 @@ impl AppleDevices { self.usb_bluetooth().is_some_and(|hci| hci.has_room()) } + /// How many packets from the host's Bluetooth controller the guest's + /// takes now; 0 without one. + pub fn bluetooth_room_left(&mut self) -> usize { + self.usb_bluetooth().map_or(0, |hci| hci.room_left()) + } + + /// The host's Bluetooth controller failed: a guest's controller it is + /// lent behind falls back to the model. + pub fn bluetooth_host_failed(&mut self) { + if let Some(hci) = self.usb_bluetooth() { + hci.host_failed(); + } + } + /// The next packet the guest sent for the host's Bluetooth controller. pub fn bluetooth_take(&mut self) -> Option { self.usb_bluetooth()?.take() diff --git a/crates/stela-soc/src/usb/hci.rs b/crates/stela-soc/src/usb/hci.rs index 28394cbbab..9987996c06 100644 --- a/crates/stela-soc/src/usb/hci.rs +++ b/crates/stela-soc/src/usb/hci.rs @@ -42,6 +42,11 @@ //! interface at number 2 for these modules (`data->diag`); bluetoothd //! uses only interfaces 0 and 1 of this product (0x1000fef70) and Linux //! runs without it, so the function has none. +//! - [`Hci::bridged`], for a host controller lent behind that module +//! (`--bluetooth-lend`): the same identity, with the [`bridge`] deciding +//! for each command whether a shadow of the model answers it or the host's +//! controller does, and falling back to the model when the controller +//! fails or stalls. No vendor command reaches the host's controller. //! //! The configuration also carries the standard synchronous interface (Vol 4 //! Part B 2.1.1): interface 1, alternate settings 0-5, each with an @@ -150,6 +155,45 @@ pub struct Answered { pub returns: u8, } +/// What `event` says of the command it answers, when it is a Command +/// Complete or Command Status. +fn answered(event: &[u8]) -> Option { + match *event { + [COMMAND_COMPLETE, length, _, _, _, status, ..] => Some(Answered { + event: COMMAND_COMPLETE, + status, + returns: length.saturating_sub(4), + }), + [COMMAND_STATUS, _, status, ..] => Some(Answered { + event: COMMAND_STATUS, + status, + returns: 0, + }), + _ => None, + } +} + +/// The opcode a Command Complete or Command Status answers. +fn answered_opcode(event: &[u8]) -> Option { + match *event { + [COMMAND_COMPLETE, _, _, low, high, ..] | [COMMAND_STATUS, _, _, _, low, high, ..] => { + Some(u16::from_le_bytes([low, high])) + } + _ => None, + } +} + +/// A command's first parameter bytes, zero past its parameters. +fn first_bytes(packet: &[u8]) -> [u8; TRACED_BYTES] { + let mut first = [0; TRACED_BYTES]; + let shown = packet[COMMAND_HEADER..].iter().take(TRACED_BYTES); + first + .iter_mut() + .zip(shown) + .for_each(|(to, from)| *to = *from); + first +} + impl core::fmt::Display for Traced { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match *self { @@ -289,6 +333,11 @@ struct State { bring_ups: u8, /// Every packet, once the owner asks (`--bluetooth-trace`). capture: capture::Capture, + /// The bridge, when a host controller is lent behind the module. + bridge: Option>, + /// Traced commands of the bridge whose answers have not reached the + /// guest yet: opcode, parameter length, first parameter bytes. + awaiting: VecDeque<(u16, u8, [u8; TRACED_BYTES])>, } /// The function: its pipes and queues. @@ -419,6 +468,18 @@ impl Hci { Self::with(&APPLE_MODULE, Some(Box::new(model::Model::new(address)))) } + /// Apple's internal USB Bluetooth module with a host controller lent + /// behind it (`bridge`), whose shadow model's power-on BD_ADDR is + /// `address`. The owner carries the commands the bridge sends the + /// controller ([`Self::take`]) and its packets back + /// ([`Self::deliver_event`], [`Self::deliver_acl`]), and says when it + /// fails ([`Self::host_failed`]). + pub fn bridged(address: [u8; 6]) -> Self { + let mut hci = Self::with(&APPLE_MODULE, None); + hci.state.bridge = Some(Box::new(bridge::Bridge::new(address))); + hci + } + fn with(identity: &Identity, model: Option>) -> Self { Self { control: Control::new(descriptors(identity)), @@ -437,6 +498,8 @@ impl Hci { configured: 0, bring_ups: 0, capture: capture::Capture::default(), + bridge: None, + awaiting: VecDeque::new(), }, } } @@ -457,21 +520,66 @@ impl Hci { state.events.queue.len() < QUEUE_PACKETS && state.acl.queue.len() < QUEUE_PACKETS } - /// The model's BD_ADDR now; `None` for a host controller's function. - pub fn model_address(&self) -> Option<[u8; 6]> { - self.state.model.as_ref().map(|model| model.address()) + /// How many packets from the host's controller both IN queues still + /// take. + pub fn room_left(&self) -> usize { + let state = &self.state; + let fuller = state.events.queue.len().max(state.acl.queue.len()); + QUEUE_PACKETS.saturating_sub(fuller) } - /// Opcodes the model answered Unknown HCI Command that were not taken - /// before, each once. + /// The model's BD_ADDR now, the bridge's shadow's when bridged; `None` + /// for a host controller's function. + pub fn model_address(&self) -> Option<[u8; 6]> { + let state = &self.state; + let bridged = state.bridge.as_ref().map(|bridge| bridge.address()); + bridged.or_else(|| state.model.as_ref().map(|model| model.address())) + } + + /// Opcodes the model (or the bridge's shadow) answered Unknown HCI + /// Command that were not taken before, each once. pub fn take_unknown(&mut self) -> Vec { - self.state + let state = &mut self.state; + if let Some(bridge) = state.bridge.as_mut() { + return bridge.take_unknown(); + } + state .model .as_mut() .map(|model| model.take_unknown()) .unwrap_or_default() } + /// Why the bridge fell back to the model, once it has. + pub fn fallback(&self) -> Option { + self.state.bridge.as_ref()?.fallen() + } + + /// The bridge's counters; `None` unless bridged. + pub fn bridge_counters(&self) -> Option { + Some(self.state.bridge.as_ref()?.counters()) + } + + /// Whether the guest wrote a BD_ADDR the lent controller does not have + /// (it keeps its own). + pub fn bridged_address_differs(&self) -> bool { + self.state + .bridge + .as_ref() + .is_some_and(|bridge| bridge.address_differs()) + } + + /// The lent host controller failed: the bridge falls back to the model, + /// which answers the command in flight. + pub fn host_failed(&mut self) { + let state = &mut self.state; + let Some(bridge) = state.bridge.as_mut() else { + return; + }; + let steps = bridge.chip_failed(state.now); + state.steps(steps); + } + /// The function's trace since it was last taken. pub fn take_trace(&mut self) -> Vec { core::mem::take(&mut self.state.trace) @@ -496,20 +604,39 @@ impl Hci { /// An event from the host's controller for the guest. Dropped (and /// counted) while the function is unconfigured or the queue is full. + /// The bridge, when there is one, decides what the guest gets of it. pub fn deliver_event(&mut self, packet: &[u8]) { if !self.up() { return; } - self.state.event(packet.to_vec()); + let state = &mut self.state; + if state.bridge.is_some() { + state.captured(capture::Direction::FromChip, capture::Kind::Event, packet); + } + let now = state.now; + match state.bridge.as_mut() { + Some(bridge) => { + let steps = bridge.chip_event(packet, now); + state.steps(steps); + } + None => state.event(packet.to_vec()), + } } /// ACL data from the host's controller for the guest, dropped as an - /// event is. + /// event is, and while a bridge keeps the controller out. pub fn deliver_acl(&mut self, packet: &[u8]) { if !self.up() { return; } let state = &mut self.state; + if let Some(bridge) = state.bridge.as_mut() { + let passes = bridge.chip_acl(); + state.captured(capture::Direction::FromChip, capture::Kind::Acl, packet); + if !passes { + return; + } + } if state.acl.queue.len() >= QUEUE_PACKETS { state.counters.overflowed += 1; return; @@ -567,29 +694,11 @@ impl State { self.tracing -= 1; // The first event answers the command; a procedure's later // ones follow it. - let answer = events.first().and_then(|e| match e[..] { - [COMMAND_COMPLETE, length, _, _, _, status, ..] => Some(Answered { - event: COMMAND_COMPLETE, - status, - returns: length.saturating_sub(4), - }), - [COMMAND_STATUS, _, status, ..] => Some(Answered { - event: COMMAND_STATUS, - status, - returns: 0, - }), - _ => None, - }); - let mut first = [0; TRACED_BYTES]; - let shown = packet[COMMAND_HEADER..].iter().take(TRACED_BYTES); - first - .iter_mut() - .zip(shown) - .for_each(|(to, from)| *to = *from); + let answer = events.first().and_then(|e| answered(e)); self.trace(Traced::Command { opcode, parameters: packet[2], - first, + first: first_bytes(packet), answer, }); if self.tracing == 0 { @@ -599,6 +708,86 @@ impl State { events.into_iter().for_each(|e| self.event(e)); } + /// A command for the bridge, traced once its answer reaches the guest. + fn bridged_command(&mut self, packet: &[u8]) { + let Some(lent) = self.bridge.as_mut() else { + return; + }; + let opcode = u16::from_le_bytes([packet[0], packet[1]]); + self.counters.commands += 1; + self.counters.unknown += u64::from(!model::implements(opcode)); + if opcode == HCI_RESET && self.bring_ups > 0 { + self.bring_ups -= 1; + self.tracing = TRACED_COMMANDS; + } + let traced = self.tracing > 0; + if traced { + self.tracing -= 1; + self.awaiting + .push_back((opcode, packet[2], first_bytes(packet))); + } + let waits = lent.busy(); + let steps = lent.command(packet, self.now); + let answers = steps.iter().any(|step| match step { + bridge::Step::Guest(event) => answered_opcode(event) == Some(opcode), + bridge::Step::Chip(_) => true, + }); + self.steps(steps); + // Host Number Of Completed Packets, answered by no event. + if traced && !waits && !answers { + self.awaiting.pop_back(); + self.trace(Traced::Command { + opcode, + parameters: packet[2], + first: first_bytes(packet), + answer: None, + }); + self.trace_ended(); + } + } + + /// What the bridge decided: events for the guest, commands for the + /// owner to carry to the host's controller. + fn steps(&mut self, steps: Vec) { + for step in steps { + match step { + bridge::Step::Guest(event) => { + self.trace_answer(&event); + self.event(event); + } + bridge::Step::Chip(command) => { + let command = command.into_bytes(); + self.captured(capture::Direction::ToChip, capture::Kind::Command, &command); + self.outbound.push_back(Outbound::Command(command)); + } + } + } + } + + /// Traces the bridged command `event` answers. + fn trace_answer(&mut self, event: &[u8]) { + let (Some(opcode), Some(answer)) = (answered_opcode(event), answered(event)) else { + return; + }; + let Some(&(_, parameters, first)) = self.awaiting.front().filter(|a| a.0 == opcode) else { + return; + }; + self.awaiting.pop_front(); + self.trace(Traced::Command { + opcode, + parameters, + first, + answer: Some(answer), + }); + self.trace_ended(); + } + + fn trace_ended(&mut self) { + if self.tracing == 0 && self.awaiting.is_empty() { + self.trace(Traced::Ended); + } + } + fn modeled_acl(&mut self, packet: &[u8]) { let Some(model) = self.model.as_mut() else { return; @@ -626,6 +815,13 @@ impl State { self.counters.malformed += 1; return Err(Stall); } + if self + .bridge + .as_ref() + .is_some_and(|bridge| !bridge.has_room()) + { + return Err(Stall); + } self.captured( capture::Direction::FromGuest, capture::Kind::Command, @@ -639,6 +835,12 @@ impl State { self.modeled_command(packet); return Ok(()); } + if self.bridge.is_some() { + // The shadow answers the vendor commands it models. + self.counters.vendor_refused += u64::from(vendor && !model::implements(opcode)); + self.bridged_command(packet); + return Ok(()); + } if vendor { self.counters.vendor_refused += 1; self.event(vec![COMMAND_COMPLETE, 4, 1, low, high, UNKNOWN_COMMAND]); @@ -670,6 +872,12 @@ impl State { self.captured(capture::Direction::FromGuest, capture::Kind::Acl, &packet); if self.model.is_some() { self.modeled_acl(&packet); + } else if let Some(bridge) = self.bridge.as_mut() { + // Milestone 1 lends no connection: the shadow owns every + // one, so it returns the buffer as the model does. + self.counters.acl_discarded += 1; + let steps = bridge.acl(&packet); + self.steps(steps); } else { self.counters.acl_to_host += 1; self.outbound.push_back(Outbound::Acl(packet)); @@ -700,6 +908,11 @@ impl Requests for State { self.events.clear(); self.acl.clear(); self.assembling.clear(); + // A command the queues dropped is no longer in flight. + if let Some(bridge) = self.bridge.as_mut() { + bridge.resync(); + } + self.awaiting.clear(); Ok(()) } @@ -759,6 +972,11 @@ impl BusPeer for Hci { if let Some(model) = self.state.model.as_mut() { model.power_on(); } + // The shadow's, not the host's: a USB reset of the real controller + // would lose its patched firmware. + if let Some(bridge) = self.state.bridge.as_mut() { + bridge.reset(); + } self.control.reset(&mut self.state)?; self.state .configure(0) @@ -797,6 +1015,10 @@ impl Function for Hci { let events = model.advance(now); events.into_iter().for_each(|e| state.event(e)); } + if let Some(bridge) = state.bridge.as_mut() { + let steps = bridge.advance(now); + state.steps(steps); + } } fn ready_at(&self, endpoint: u8) -> Option { @@ -806,8 +1028,12 @@ impl Function for Hci { let state = &self.state; match endpoint { EVENTS if !state.events.queue.is_empty() => Some(0), - // A procedure's end is an event then. - EVENTS => state.model.as_ref().and_then(|model| model.deadline()), + // A procedure's end is an event then, and a forwarded command's + // deadline the model's answer. + EVENTS => match state.bridge.as_ref() { + Some(bridge) => bridge.deadline(), + None => state.model.as_ref().and_then(|model| model.deadline()), + }, ACL_IN => (!state.acl.queue.is_empty()).then_some(0), _ => None, } @@ -1326,6 +1552,170 @@ mod tests { ); } + fn bridged() -> Hci { + configured(Hci::bridged(ADDRESS)) + } + + /// A host controller lent behind the module: the guest sees Apple's + /// module; its listed standard commands go to the owner for the host's + /// controller and their answers come back with one credit; vendor + /// commands and ACL data stay with the shadow. + #[test] + fn the_bridged_function_is_apples_module_with_the_hosts_controller_behind_it() { + use capture::Direction::{FromChip, FromGuest, ToChip, ToGuest}; + let hci = Hci::bridged(ADDRESS); + let device = hci.control.descriptors.device; + assert_eq!( + device[4..14], + [0xff, 1, 1, 64, 0xac, 0x05, 0x8f, 0x82, 0x50, 0x01] + ); + assert_eq!(hci.model_address(), Some(ADDRESS)); + let mut hci = configured(hci); + hci.capture(); + command(&mut hci, &[0x03, 0x0c, 0]).unwrap(); + assert_eq!(hci.take(), Some(Outbound::Command(vec![0x03, 0x0c, 0]))); + let mut buffer = [0; EVENT_PACKET]; + assert_eq!( + hci.packet(EVENTS, Token::In, &mut buffer).unwrap(), + Reply::Nak, + "no answer before the controller's" + ); + hci.deliver_event(&[COMMAND_COMPLETE, 3, 1, 0, 0]); + hci.deliver_event(&[COMMAND_COMPLETE, 4, 5, 0x03, 0x0c, 0]); + assert_eq!( + read(&mut hci, EVENTS, EVENT_PACKET), + [vec![COMMAND_COMPLETE, 4, 1, 0x03, 0x0c, 0]] + ); + // A vendor command stays here. + command(&mut hci, &[0x4c, 0xfc, 1, 9]).unwrap(); + assert_eq!(hci.take(), None); + assert_eq!(read(&mut hci, EVENTS, EVENT_PACKET)[0][5], UNKNOWN_COMMAND); + assert_eq!(hci.take_unknown(), [0xfc4c]); + assert_eq!(hci.counters().commands, 2); + assert_eq!(hci.counters().vendor_refused, 1); + let directions: Vec<_> = hci.take_captured().iter().map(|c| c.direction).collect(); + assert_eq!( + directions, + [ + FromGuest, ToChip, FromChip, FromChip, ToGuest, FromGuest, ToGuest + ] + ); + // ACL data from the guest names none of the controller's + // connections: the shadow returns its buffer. + hci.packet(ACL_OUT, Token::Out, &mut [1, 0, 1, 0, 7]) + .unwrap(); + assert_eq!(hci.take(), None); + assert_eq!( + read(&mut hci, EVENTS, EVENT_PACKET), + [vec![0x13, 5, 1, 1, 0, 1, 0]] + ); + // The controller's ACL data reaches the guest. + hci.deliver_acl(&[2, 0, 1, 0, 8]); + assert_eq!(read(&mut hci, ACL_IN, 512), [vec![2, 0, 1, 0, 8]]); + assert_eq!(hci.fallback(), None); + // The trace names each command with its answer, whoever gave it. + let traced = hci.take_trace(); + assert_eq!(traced[0], Traced::Configured(1)); + assert_eq!( + traced[1].to_string(), + "command 0x0c03 parameters=0 answered complete status=0x00 returns=0" + ); + assert_eq!( + traced[2].to_string(), + "command 0xfc4c parameters=1 [09] answered complete status=0x01 returns=0" + ); + } + + /// The fallback: a forwarded command not answered by its deadline, or a + /// failed host controller, gets the model's answer, and the model + /// answers from then on. + #[test] + fn a_bridged_command_left_unanswered_gets_the_models_answer() { + let mut hci = bridged(); + hci.set_time(100); + command(&mut hci, &[0x09, 0x10, 0]).unwrap(); + assert!(hci.take().is_some()); + assert_eq!(hci.ready_at(EVENTS), Some(100 + bridge::DEADLINE)); + hci.set_time(100 + bridge::DEADLINE); + assert_eq!(hci.ready_at(EVENTS), Some(0)); + assert_eq!( + read(&mut hci, EVENTS, EVENT_PACKET).concat(), + [COMMAND_COMPLETE, 10, 1, 0x09, 0x10, 0, 1, 2, 3, 4, 5, 0x02] + ); + let fallback = hci.fallback().expect("fell back"); + assert_eq!(fallback.to_string(), "0x1009 no answer in 1 s"); + command(&mut hci, &[0x03, 0x0c, 0]).unwrap(); + assert_eq!(hci.take(), None, "nothing goes out again"); + assert_eq!( + read(&mut hci, EVENTS, EVENT_PACKET)[0][3..6], + [0x03, 0x0c, 0] + ); + // A host controller that fails. + let mut hci = bridged(); + command(&mut hci, &[0x03, 0x0c, 0]).unwrap(); + hci.take(); + hci.host_failed(); + assert_eq!( + read(&mut hci, EVENTS, EVENT_PACKET)[0][3..6], + [0x03, 0x0c, 0] + ); + assert_eq!( + hci.fallback().map(|f| f.cause), + Some(bridge::Cause::HostFailed) + ); + } + + /// A bus reset drops the command in flight; the controller's events stay + /// out until the guest's next HCI Reset is answered. + #[test] + fn a_bus_reset_of_a_bridged_function_keeps_the_controller_out_until_its_reset() { + let result = [&[0x2f, 255, 1][..], &[7; 254]].concat(); + let mut hci = bridged(); + command(&mut hci, &[0x14, 0x0c, 0]).unwrap(); + hci.take(); + hci.reset().unwrap(); + let mut hci = configured(hci); + hci.deliver_event(&[&[COMMAND_COMPLETE, 252, 1, 0x14, 0x0c, 0][..], &[0; 248]].concat()); + hci.deliver_event(&result); + assert_eq!(hci.ready_at(EVENTS), None); + command(&mut hci, &[0x03, 0x0c, 0]).unwrap(); + hci.take(); + hci.deliver_event(&[COMMAND_COMPLETE, 4, 1, 0x03, 0x0c, 0]); + read(&mut hci, EVENTS, EVENT_PACKET); + hci.deliver_event(&result); + assert_eq!(read(&mut hci, EVENTS, EVENT_PACKET).concat(), result); + // The shadow powers on again with a bus reset, as the model does. + command(&mut hci, &[0x01, 0xfc, 6, 9, 8, 7, 6, 5, 0x42]).unwrap(); + read(&mut hci, EVENTS, EVENT_PACKET); + assert_eq!(hci.model_address(), Some([9, 8, 7, 6, 5, 0x42])); + hci.reset().unwrap(); + assert_eq!(hci.model_address(), Some(ADDRESS)); + // A new configuration alone drops the command in flight too. + let mut hci = configured(hci); + command(&mut hci, &[0x14, 0x0c, 0]).unwrap(); + hci.take(); + transfer(&mut hci, setup(0, SET_CONFIGURATION, 1, 0, 0), &[]).unwrap(); + assert_eq!(hci.ready_at(EVENTS), None, "no deadline left"); + hci.deliver_event(&[&[COMMAND_COMPLETE, 252, 1, 0x14, 0x0c, 0][..], &[0; 248]].concat()); + assert_eq!(hci.ready_at(EVENTS), None, "the stale answer is dropped"); + assert_eq!(hci.fallback(), None); + } + + #[test] + fn the_room_left_is_the_fuller_queues() { + let mut hci = controller(); + assert_eq!(hci.room_left(), QUEUE_PACKETS); + for _ in 0..60 { + hci.deliver_event(&[0x13, 0]); + } + hci.deliver_acl(&[1, 0, 0, 0]); + assert_eq!(hci.room_left(), QUEUE_PACKETS - 60); + for _ in 0..10 { + hci.deliver_event(&[0x13, 0]); + } + assert_eq!(hci.room_left(), 0); + } + #[test] fn a_procedure_ends_when_the_system_count_reaches_it() { let mut hci = modeled(); diff --git a/crates/stela-soc/src/usb/hci/bridge.rs b/crates/stela-soc/src/usb/hci/bridge.rs index eb9ac802fe..74388082a0 100644 --- a/crates/stela-soc/src/usb/hci/bridge.rs +++ b/crates/stela-soc/src/usb/hci/bridge.rs @@ -23,13 +23,23 @@ //! Nothing goes to the host's controller again. So bluetoothd's bring-up, //! and Setup's first screen, which waits for it, never wait on a stalled //! controller. +//! - The controller's events reach the guest as they are, but for its +//! vendor events, credits alone and answers to commands no longer in +//! flight, which are dropped. After a guest bus reset or a new +//! configuration, which reach the shadow but never the controller (a USB +//! reset would lose its patched firmware), its events stay out until the +//! guest's next HCI Reset is answered. +//! - The owner carries packets to and from the controller through a +//! [`Link`] and the [`HostController`] trait. use super::model::Model; use crate::counter::FREQUENCY_HZ; use alloc::{collections::VecDeque, vec, vec::Vec}; use core::fmt; +pub mod link; pub mod policy; +pub use link::{HostController, Link}; pub use policy::ChipCommand; /// System counts the host's controller has to answer a forwarded command: @@ -101,8 +111,9 @@ pub struct Counters { pub local: u64, /// Events of the host's controller the guest got. pub passed: u64, - /// Events of the host's controller dropped: vendor events, credits - /// alone, stale answers, and every event after the fallback. + /// Packets of the host's controller dropped: vendor events, credits + /// alone, stale answers, what comes while it is kept out after a guest + /// reset, and everything after the fallback. pub dropped: u64, } @@ -110,6 +121,7 @@ pub struct Counters { #[derive(Debug, Clone)] struct Pending { opcode: u16, + parameters: Vec, kind: policy::Forward, /// The shadow's answer, the first of its events, given on a fallback. shadow: Vec>, @@ -123,9 +135,33 @@ pub struct Bridge { fallen: Option, pending: Option, backlog: VecDeque>, + /// Whether the controller is kept out until the guest's next HCI Reset + /// is answered: the guest reset or configured the function again, and + /// the controller, which no USB reset reaches, may still send what the + /// old session asked for. + resync: bool, + /// The BD_ADDR the guest wrote with the module's vendor command. + written: Option<[u8; 6]>, + /// Whether the controller reported another address than that. + address_differs: bool, counters: Counters, } +// Commands and events the shadow follows (Bluetooth Core v5.4 Vol 4 Part E +// 7.1.1-7.1.2, 7.1.19-7.1.20, 7.3.2, 7.4.6, 7.7.1, 7.7.7). +const INQUIRY: u16 = 0x0401; +const INQUIRY_CANCEL: u16 = 0x0402; +const REMOTE_NAME_REQUEST: u16 = 0x0419; +const REMOTE_NAME_REQUEST_CANCEL: u16 = 0x041a; +const RESET: u16 = 0x0c03; +const READ_BD_ADDR: u16 = 0x1009; +/// The module's Write BD_ADDR (Linux `btbcm_set_bdaddr`). +const WRITE_BD_ADDR: u16 = 0xfc01; +const INQUIRY_COMPLETE: u8 = 0x01; +const REMOTE_NAME_REQUEST_COMPLETE: u8 = 0x07; +/// A vendor's own event (7.7.65 leaves code 0xFF to vendors). +const VENDOR_EVENT: u8 = 0xff; + /// The parts of a Command Complete or Command Status event that answers a /// command, with its status. pub(super) struct Completion<'a> { @@ -193,10 +229,58 @@ impl Bridge { fallen: None, pending: None, backlog: VecDeque::new(), + resync: false, + written: None, + address_differs: false, counters: Counters::default(), } } + /// Whether a forwarded command is in flight, so another waits. + pub fn busy(&self) -> bool { + self.pending.is_some() + } + + /// Whether the guest wrote a BD_ADDR the controller does not have: the + /// controller keeps its own, which Read BD_ADDR gives. + pub fn address_differs(&self) -> bool { + self.address_differs + } + + /// A guest USB bus reset: the shadow powers on again, as the model + /// does, and the controller is kept out until the next HCI Reset. + pub fn reset(&mut self) { + self.shadow.power_on(); + self.written = None; + self.resync(); + } + + /// The guest configured the function again, which drops its queues: the + /// command in flight and those waiting are gone, and the controller is + /// kept out until the next HCI Reset. + pub fn resync(&mut self) { + self.pending = None; + self.backlog.clear(); + self.resync = true; + } + + /// ACL data from the guest. Milestone 1 forwards no connection, so the + /// shadow owns every one: it returns the buffer, as the model does. + pub fn acl(&mut self, packet: &[u8]) -> Vec { + guest(self.shadow.acl(packet)) + } + + /// Whether ACL data from the controller reaches the guest. + pub fn chip_acl(&mut self) -> bool { + let passes = self.fallen.is_none() && !self.resync; + if passes { + self.counters.passed += 1; + } else { + self.counters.dropped += 1; + } + passes + } + /// Why the bridge fell back to the model, once it has. pub fn fallen(&self) -> Option { self.fallen @@ -233,6 +317,9 @@ impl Bridge { } fn start(&mut self, packet: &[u8], now: u64) -> Vec { + if opcode(packet) == WRITE_BD_ADDR && packet.len() == 3 + 6 { + self.written = packet[3..].try_into().ok(); + } let shadow = self.shadow.command(packet, now); if self.fallen.is_some() { return guest(shadow); @@ -244,6 +331,7 @@ impl Bridge { self.counters.forwarded += 1; self.pending = Some(Pending { opcode: opcode(packet), + parameters: packet[3..].to_vec(), kind, shadow, deadline: now.saturating_add(DEADLINE), @@ -275,9 +363,12 @@ impl Bridge { steps } - /// One event from the host's controller. + /// One event from the host's controller. The answer to the command in + /// flight becomes the guest's; a vendor event, credits alone or a stale + /// answer is dropped, as is everything while the controller is kept out + /// or after the fallback; every other event reaches the guest as it is. pub fn chip_event(&mut self, event: &[u8], now: u64) -> Vec { - if self.fallen.is_some() { + if self.fallen.is_some() || event.first() == Some(&VENDOR_EVENT) { self.counters.dropped += 1; return Vec::new(); } @@ -294,14 +385,67 @@ impl Bridge { }; return self.answer(pending, &completion, now); } + if self.resync { + self.counters.dropped += 1; + return Vec::new(); + } + self.follow(event, now); self.counters.passed += 1; vec![Step::Guest(event.to_vec())] } + /// The shadow ends what the controller's event ends, so that after a + /// fallback it gives the guest no second end of it. + fn follow(&mut self, event: &[u8], now: u64) { + match *event { + [INQUIRY_COMPLETE, ..] => self.shadow_only(INQUIRY_CANCEL, &[], now), + [REMOTE_NAME_REQUEST_COMPLETE, _, _, ref peer @ ..] if peer.len() >= 6 => { + let peer = peer[..6].to_vec(); + self.shadow_only(REMOTE_NAME_REQUEST_CANCEL, &peer, now); + } + _ => {} + } + } + + /// Runs a command in the shadow alone, its events discarded. + fn shadow_only(&mut self, opcode: u16, parameters: &[u8], now: u64) { + let mut packet = opcode.to_le_bytes().to_vec(); + packet.push(parameters.len() as u8); + packet.extend_from_slice(parameters); + self.shadow.command(&packet, now); + } + + /// The shadow follows what the controller's answer to `pending` says: + /// the address it has, and a procedure it refused. + fn follow_answer(&mut self, pending: &Pending, chip: &Completion<'_>, now: u64) { + let shadow = pending.shadow.first().and_then(|e| Completion::of(e)); + let shadow_succeeded = shadow.is_some_and(|s| s.status == 0); + match pending.opcode { + RESET if chip.status == 0 => self.resync = false, + READ_BD_ADDR if chip.status == 0 && chip.returns.len() == 6 => { + let address = &chip.returns[..6]; + if self.written.is_some_and(|written| written != address) { + self.address_differs = true; + } + self.shadow_only(WRITE_BD_ADDR, address, now); + } + INQUIRY if chip.status != 0 && shadow_succeeded => { + self.shadow_only(INQUIRY_CANCEL, &[], now); + } + REMOTE_NAME_REQUEST + if chip.status != 0 && shadow_succeeded && pending.parameters.len() >= 6 => + { + self.shadow_only(REMOTE_NAME_REQUEST_CANCEL, &pending.parameters[..6], now); + } + _ => {} + } + } + fn answer(&mut self, pending: Pending, chip: &Completion<'_>, now: u64) -> Vec { let shadow = pending.shadow.first().and_then(|e| Completion::of(e)); match policy::answer(pending.kind, shadow.as_ref(), chip) { Ok(returns) => { + self.follow_answer(&pending, chip, now); self.counters.passed += 1; let mut steps = vec![Step::Guest(chip.event(&returns))]; steps.extend(self.next(now)); diff --git a/crates/stela-soc/src/usb/hci/bridge/link.rs b/crates/stela-soc/src/usb/hci/bridge/link.rs new file mode 100644 index 0000000000..8c999b19d5 --- /dev/null +++ b/crates/stela-soc/src/usb/hci/bridge/link.rs @@ -0,0 +1,182 @@ +//! The owner's side of a lent controller: the host's controller behind a +//! small trait, [`HostController`], which the engine's host drivers and the +//! tests' scripted controller implement alike, and a [`Link`] that carries +//! packets between it and the guest's function over service turns. +//! +//! The function's queues are reached under the devices' lock and the host's +//! controller outside it, so a turn takes what the function queued +//! ([`super::super::Hci::take`]) and how much room it has +//! ([`super::super::Hci::room_left`]), runs [`Link::send`] and +//! [`Link::receive`], then hands what came back to the function. The link +//! keeps what the controller has no room for yet, and what it gave beyond +//! the guest's room, for later turns: one poll can return more packets than +//! the guest's queues take. +use super::super::Outbound; +use alloc::{collections::VecDeque, string::String, vec::Vec}; +pub use stela_drivers::usb::bluetooth::Packet; + +/// The host's controller, as a service turn reaches it. +pub trait HostController { + /// Offers the controller one packet from the guest's function: + /// `Ok(true)` once it took it, `Ok(false)` while it has no room, which + /// keeps the packet for a later turn. An error is the controller's + /// failure, after which it takes nothing. + fn send(&mut self, packet: &Outbound) -> Result; + /// What the controller has for the guest now, never waiting for the + /// radio. + fn poll(&mut self) -> Result, String>; +} + +/// What waits between the function and the host's controller. +#[derive(Debug, Default)] +pub struct Link { + /// The function's packets the controller had no room for. + waiting: VecDeque, + /// The controller's packets the guest had no room for. + held: VecDeque, +} + +impl Link { + /// Queues the function's packets behind those still waiting. + pub fn queue(&mut self, packets: impl IntoIterator) { + self.waiting.extend(packets); + } + + /// Offers `controller` what waits, in order, until it has no room. + pub fn send(&mut self, controller: &mut (impl HostController + ?Sized)) -> Result<(), String> { + while let Some(packet) = self.waiting.front() { + if !controller.send(packet)? { + return Ok(()); + } + self.waiting.pop_front(); + } + Ok(()) + } + + /// At most `room` packets for the guest: those held from an earlier + /// turn first, then what `controller` has, which is polled only while + /// fewer than `room` are held. The rest stays held. + pub fn receive( + &mut self, + controller: &mut (impl HostController + ?Sized), + room: usize, + ) -> Result, String> { + if self.held.len() < room { + self.held.extend(controller.poll()?); + } + let taken = room.min(self.held.len()); + Ok(self.held.drain(..taken).collect()) + } + + /// Drops what waits either way, once the controller has failed. + pub fn clear(&mut self) { + self.waiting.clear(); + self.held.clear(); + } + + /// Packets waiting for the controller, and held for the guest. + pub fn pending(&self) -> (usize, usize) { + (self.waiting.len(), self.held.len()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::{format, vec}; + + /// A controller that takes `room` packets and gives `polls` in turn. + #[derive(Default)] + struct Scripted { + room: usize, + taken: Vec, + polls: VecDeque>, + failed: bool, + } + + impl HostController for Scripted { + fn send(&mut self, packet: &Outbound) -> Result { + if self.failed { + return Err(String::from("gone")); + } + if self.room == 0 { + return Ok(false); + } + self.room -= 1; + self.taken.push(packet.clone()); + Ok(true) + } + + fn poll(&mut self) -> Result, String> { + if self.failed { + return Err(String::from("gone")); + } + Ok(self.polls.pop_front().unwrap_or_default()) + } + } + + fn event(n: u8) -> Packet { + Packet::Event(vec![0x13, 1, n]) + } + + #[test] + fn what_the_controller_has_no_room_for_waits_in_order() { + let mut link = Link::default(); + let mut controller = Scripted { + room: 1, + ..Scripted::default() + }; + let command = |n: u8| Outbound::Command(vec![n, 0x0c, 0]); + link.queue([command(1), command(2)]); + link.send(&mut controller).unwrap(); + assert_eq!(controller.taken, [command(1)]); + assert_eq!(link.pending(), (1, 0)); + link.queue([command(3)]); + controller.room = 5; + link.send(&mut controller).unwrap(); + assert_eq!(controller.taken, [command(1), command(2), command(3)]); + assert_eq!(link.pending(), (0, 0)); + } + + /// Bounded delivery: one poll that gives more than the guest has room + /// for leaves the rest held, in order, and nothing is lost. + #[test] + fn the_guest_gets_at_most_its_room_and_the_rest_is_held() { + let mut link = Link::default(); + let mut controller = Scripted::default(); + controller.polls.push_back((0..5).map(event).collect()); + controller.polls.push_back(vec![event(5)]); + assert_eq!( + link.receive(&mut controller, 2).unwrap(), + [event(0), event(1)] + ); + assert_eq!(link.pending(), (0, 3)); + // Held packets go first; the controller is not polled while as many + // are held as there is room. + assert_eq!( + link.receive(&mut controller, 3).unwrap(), + [event(2), event(3), event(4)] + ); + assert_eq!(controller.polls.len(), 1); + assert!(link.receive(&mut controller, 0).unwrap().is_empty()); + assert_eq!(link.receive(&mut controller, 4).unwrap(), [event(5)]); + assert!(link.receive(&mut controller, 4).unwrap().is_empty()); + } + + #[test] + fn a_failure_is_the_controllers_and_clear_drops_what_waits() { + let mut link = Link::default(); + let mut controller = Scripted { + failed: true, + ..Scripted::default() + }; + link.queue([Outbound::Acl(vec![1, 0, 0, 0])]); + assert_eq!(link.send(&mut controller), Err(String::from("gone"))); + assert_eq!( + format!("{:?}", link.receive(&mut controller, 1)), + "Err(\"gone\")" + ); + link.clear(); + assert_eq!(link.pending(), (0, 0)); + } +} diff --git a/crates/stela-soc/src/usb/hci/bridge/tests.rs b/crates/stela-soc/src/usb/hci/bridge/tests.rs index 76bb242ea1..2b9247c1a2 100644 --- a/crates/stela-soc/src/usb/hci/bridge/tests.rs +++ b/crates/stela-soc/src/usb/hci/bridge/tests.rs @@ -418,3 +418,142 @@ fn the_merge_keeps_the_modules_capabilities_less_what_the_controller_lacks() { assert_eq!(le, [0; 8]); assert_eq!(bridge.fallen(), None); } + +/// The event filter: vendor events and credits alone go nowhere; inquiry +/// results of each kind, LE meta events, completed packets and the rest +/// reach the guest as they are. +#[test] +fn vendor_events_are_dropped_and_the_radios_events_pass_as_they_are() { + let mut bridge = Bridge::new(ADDRESS); + assert!(bridge.chip_event(&[0xff, 3, 0x2a, 1, 2], 0).is_empty()); + assert!( + bridge + .chip_event(&[COMMAND_COMPLETE, 3, 1, 0, 0], 0) + .is_empty() + ); + let passed = [ + // Inquiry Result, with RSSI, Extended; Inquiry Complete. + [&[0x02, 15, 1][..], &[7; 14]].concat(), + [&[0x22, 15, 1][..], &[7; 14]].concat(), + [&[0x2f, 255, 1][..], &[7; 254]].concat(), + vec![0x01, 1, 0], + // Number Of Completed Packets, an LE meta event. + vec![0x13, 5, 1, 0x40, 0, 1, 0], + vec![0x3e, 3, 0x0c, 0, 0], + ]; + for event in &passed { + assert_eq!( + events(bridge.chip_event(event, 0)), + core::slice::from_ref(event) + ); + } + assert_eq!(bridge.counters().dropped, 2); + assert_eq!(bridge.counters().passed, passed.len() as u64); +} + +/// A guest bus reset drops the command in flight, and the controller's +/// events stay out until the guest's next HCI Reset is answered: the real +/// controller is never reset by USB, so it may still be busy with the old +/// session. +#[test] +fn a_bus_reset_keeps_the_controllers_events_out_until_the_next_reset() { + let mut bridge = Bridge::new(ADDRESS); + events(bridge.command(&packet(0xfc01, &[9, 8, 7, 6, 5, 0x42]), 0)); + chip(bridge.command(&packet(0x0c14, &[]), 0)); + bridge.reset(); + assert_eq!(bridge.address(), ADDRESS, "power-on, as the model"); + let result = [&[0x2f, 255, 1][..], &[7; 254]].concat(); + for stale in [complete(0x0c14, 1, 0, &[0; 248]), result.clone()] { + assert!(bridge.chip_event(&stale, 0).is_empty()); + } + // A command before the reset is answered; the reset's answer ends it. + chip(bridge.command(&packet(0x1009, &[]), 0)); + assert_eq!( + events(bridge.chip_event(&complete(0x1009, 1, 0, &CHIP_ADDRESS), 0)).len(), + 1 + ); + chip(bridge.command(&packet(0x0c03, &[]), 0)); + assert!(bridge.chip_event(&result, 0).is_empty()); + assert_eq!( + events(bridge.chip_event(&complete(0x0c03, 1, 0, &[]), 0)).len(), + 1 + ); + assert_eq!( + events(bridge.chip_event(&result, 0)), + core::slice::from_ref(&result) + ); + // A new configuration does the same, keeping the shadow's state. + events(bridge.command(&packet(0xfc01, &[9, 8, 7, 6, 5, 0x42]), 0)); + bridge.resync(); + assert_eq!(bridge.address(), [9, 8, 7, 6, 5, 0x42]); + assert!(bridge.chip_event(&result, 0).is_empty()); + assert_eq!(bridge.fallen(), None); +} + +/// The shadow follows the controller: a procedure the controller ended or +/// refused ends in the shadow too, so a later fallback gives the guest no +/// second end of it; and the controller's address becomes the shadow's. +#[test] +fn the_shadow_follows_the_controllers_procedures_and_address() { + let inquiry = packet(0x0401, &[0x33, 0x8b, 0x9e, 8, 0]); + let mut name = CHIP_ADDRESS.to_vec(); + name.extend_from_slice(&[1, 0, 0, 0]); + let name = packet(0x0419, &name); + let mut ended = vec![0x07, 255, 0]; + ended.extend_from_slice(&CHIP_ADDRESS); + ended.resize(257, b'x'); + for (command, end) in [ + (&inquiry, Some(vec![0x01, 1, 0])), + (&name, Some(ended)), + // Refused by the controller: Command Disallowed. + (&inquiry, None), + (&name, None), + ] { + let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(command, 0)); + let op = opcode(command); + match end { + Some(end) => { + events(bridge.chip_event(&status(op, 1, 0), 0)); + assert_eq!(events(bridge.chip_event(&end, 0)), [end]); + } + None => { + let refused = events(bridge.chip_event(&status(op, 1, 0x0c), 0)); + assert_eq!(refused, [status(op, 1, 0x0c)]); + } + } + events(bridge.chip_failed(0)); + assert!(events(bridge.advance(u64::MAX)).is_empty(), "{op:#06x}"); + } + // The address. + let mut bridge = Bridge::new(ADDRESS); + events(bridge.command(&packet(0xfc01, &[9, 8, 7, 6, 5, 0x42]), 0)); + chip(bridge.command(&packet(0x1009, &[]), 0)); + events(bridge.chip_event(&complete(0x1009, 1, 0, &CHIP_ADDRESS), 0)); + assert!(bridge.address_differs(), "the guest wrote another"); + events(bridge.chip_failed(0)); + let address = events(bridge.command(&packet(0x1009, &[]), 0)); + assert_eq!(address, [complete(0x1009, 1, 0, &CHIP_ADDRESS)]); + let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(&packet(0x1009, &[]), 0)); + events(bridge.chip_event(&complete(0x1009, 1, 0, &CHIP_ADDRESS), 0)); + assert!(!bridge.address_differs(), "the guest wrote none"); +} + +/// In milestone 1 every connection is the shadow's, so ACL data from the +/// guest names none of the controller's: the shadow returns its buffer. +/// The controller's ACL data reaches the guest while the bridge forwards. +#[test] +fn acl_from_the_guest_is_the_shadows_and_the_controllers_passes() { + let mut bridge = Bridge::new(ADDRESS); + assert_eq!( + events(bridge.acl(&[0x40, 0x20, 2, 0, 9, 9])), + [vec![0x13, 5, 1, 0x40, 0, 1, 0]] + ); + assert!(bridge.chip_acl()); + bridge.resync(); + assert!(!bridge.chip_acl(), "until the next reset"); + let mut bridge = Bridge::new(ADDRESS); + events(bridge.chip_failed(0)); + assert!(!bridge.chip_acl()); +} From 086c5d20e69a417aafe68d56eb9c229578f2f3b1 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:11:19 +0000 Subject: [PATCH 05/18] feat(bluetooth): lend the host's Bluetooth controller to macOS behind the modeled Apple module with --bluetooth-lend, off by default, so the guest keeps the module's identity and vendor answers while the bridge sends the controller milestone 1's standard commands, and log the lent controller, a fallback to the model with its command and cause, a BD_ADDR the guest wrote that the controller does not have, and the bridge's counters, where every boot gave macOS the model and dropped the host's controller --- crates/stela-boot-core/src/guest_bluetooth.rs | 28 +++++- crates/stela-boot-core/src/options.rs | 8 ++ crates/stela-boot-core/src/options/parse.rs | 1 + crates/stela-boot-core/src/options/tests.rs | 12 +++ crates/stela-boot/src/engine/bluetooth.rs | 95 +++++++++++++++---- crates/stela-boot/src/engine/start.rs | 6 +- crates/stela-soc/src/machine.rs | 6 ++ crates/stela-soc/src/machine/usb.rs | 49 +++++++++- 8 files changed, 179 insertions(+), 26 deletions(-) diff --git a/crates/stela-boot-core/src/guest_bluetooth.rs b/crates/stela-boot-core/src/guest_bluetooth.rs index a4f9524af8..10e61c29ac 100644 --- a/crates/stela-boot-core/src/guest_bluetooth.rs +++ b/crates/stela-boot-core/src/guest_bluetooth.rs @@ -8,7 +8,20 @@ //! The model has no radio. It is powered, has a stable locally administered //! address, accepts scans and connection attempts and finds nothing, and has //! no paired devices. That is a degraded answer, not Bluetooth, and the line -//! says so once. A host controller is not lent to the guest. +//! says so once. A host controller is not lent to the guest unless the boot +//! asks for it (`--bluetooth-lend`): it then sits behind the same module, +//! which falls back to the model when the controller fails or stalls, and +//! [`lend_line`] names it instead. +use alloc::{format, string::String}; + +/// The line for a boot that lends the host's controller at `location` to +/// the guest behind Apple's module. +pub fn lend_line(location: &str) -> String { + format!( + "BLUETOOTH LEND the guest's controller is {location} behind Apple's module; \ + it falls back to the model on failure\n" + ) +} /// The line for a boot that gives macOS host input, by whether the host /// has a Bluetooth controller; `None` for a boot without host input. @@ -40,6 +53,19 @@ mod tests { } } + /// `--bluetooth-lend`: the line names the controller lent, the module it + /// sits behind, and the fallback. + #[test] + fn a_lent_controller_is_named_with_its_fallback() { + let line = lend_line("xhci 0000:05:00.4 port 2.3"); + assert_eq!( + line, + "BLUETOOTH LEND the guest's controller is xhci 0000:05:00.4 port 2.3 behind \ + Apple's module; it falls back to the model on failure\n" + ); + assert_eq!(line.matches('\n').count(), 1); + } + #[test] fn a_host_controller_is_named_as_not_lent_and_a_boot_without_input_says_nothing() { let line = model_line(true, true).expect("reported"); diff --git a/crates/stela-boot-core/src/options.rs b/crates/stela-boot-core/src/options.rs index 24e4eba69d..bea5dc473e 100644 --- a/crates/stela-boot-core/src/options.rs +++ b/crates/stela-boot-core/src/options.rs @@ -48,6 +48,7 @@ pub const WIFI_KEY: &str = "--wifi-key"; pub const WIFI_COUNTRY: &str = "--wifi-country"; pub const USB4_APPROVE: &str = "--usb4-approve"; pub const BLUETOOTH_TRACE: &str = "--bluetooth-trace"; +pub const BLUETOOTH_LEND: &str = "--bluetooth-lend"; /// The ESP file `--wifi` reads its key from without `--wifi-key`. pub const DEFAULT_WIFI_KEY: &str = "\\EFI\\stela\\wifi.key"; /// IEEE 802.11 SSIDs are 1 to 32 octets. @@ -279,6 +280,11 @@ pub struct System { /// configuration (`--bluetooth-trace`). The packets name nearby devices' /// addresses and names. pub bluetooth_trace: bool, + /// Lend the host's Bluetooth controller to the guest behind the model of + /// Apple's module, which answers its vendor commands and takes over + /// when the host's fails or stalls (`--bluetooth-lend`). Without it the + /// guest gets the model alone. + pub bluetooth_lend: bool, /// Explicit native executors and guest PEs (`--native-cores N`), one per /// logical processor; SMT siblings count after every physical core. pub native_cores: Option, @@ -400,6 +406,7 @@ impl Default for System { idle_skip: false, input: false, bluetooth_trace: false, + bluetooth_lend: false, native_cores: None, guest_pes: None, display_size: None, @@ -847,6 +854,7 @@ impl fmt::Display for System { line.value(IPV4_GATEWAY, self.ipv4_gateway)?; line.value(DNS, (!self.dns.is_empty()).then(|| Servers(&self.dns)))?; line.flag("--input", self.input)?; + line.flag(BLUETOOTH_LEND, self.bluetooth_lend)?; line.flag(BLUETOOTH_TRACE, self.bluetooth_trace)?; line.flag("--idle-skip", self.idle_skip)?; line.flag("--survey", self.survey)?; diff --git a/crates/stela-boot-core/src/options/parse.rs b/crates/stela-boot-core/src/options/parse.rs index 82277c59f3..95a9d54e8e 100644 --- a/crates/stela-boot-core/src/options/parse.rs +++ b/crates/stela-boot-core/src/options/parse.rs @@ -143,6 +143,7 @@ impl ParseState<'_> { "--idle-skip" => options.idle_skip = true, "--input" => options.input = true, BLUETOOTH_TRACE => options.bluetooth_trace = true, + BLUETOOTH_LEND => options.bluetooth_lend = true, "--usb-storage" => { let serial = value().ok_or(Error::MissingUsbStorage)?; if options.usb_storage.iter().any(|other| other == serial) { diff --git a/crates/stela-boot-core/src/options/tests.rs b/crates/stela-boot-core/src/options/tests.rs index 126734eee3..a74006dcf8 100644 --- a/crates/stela-boot-core/src/options/tests.rs +++ b/crates/stela-boot-core/src/options/tests.rs @@ -213,6 +213,18 @@ fn the_bluetooth_capture_round_trips_and_is_off_by_default() { assert!(!System::default().to_string().contains("bluetooth")); } +/// Lending the host's controller is off unless asked for: a line without +/// the flag gives every boot the model, as before. +#[test] +fn the_bluetooth_lend_round_trips_and_is_off_by_default() { + assert!(!System::default().bluetooth_lend); + assert!(!round_trip("--system --input --bluetooth-trace").bluetooth_lend); + let line = format!("--system --storage {DISK} --input {BLUETOOTH_LEND} {BLUETOOTH_TRACE}"); + let options = round_trip(&line); + assert!(options.bluetooth_lend && options.bluetooth_trace); + assert_eq!(options.to_string(), line); +} + #[test] fn usb4_approvals_repeat_and_keep_their_canonical_spelling() { let first = "446ab8f0-5aff-47c9-8962-5870641e4d61"; diff --git a/crates/stela-boot/src/engine/bluetooth.rs b/crates/stela-boot/src/engine/bluetooth.rs index edffc33114..fa7eb3f6f1 100644 --- a/crates/stela-boot/src/engine/bluetooth.rs +++ b/crates/stela-boot/src/engine/bluetooth.rs @@ -7,12 +7,16 @@ //! //! The guest is given the controller model (`stela_soc::usb::hci::model`), //! presented as Apple's internal USB module, which answers inside the -//! guest's function; a host controller is not lent yet (`start`). This -//! reports the model's unknown commands, each once, how many commands the -//! guest sent, at each doubling, and the function's trace: each -//! configuration and reset, and the first commands after each -//! configuration with their answers. With `--bluetooth-trace` it also logs -//! every packet the function captures (`GUEST BLUETOOTH RAW`, at most +//! guest's function. With `--bluetooth-lend` the host's controller is lent +//! behind that module instead (`stela_soc::usb::hci::bridge`): the module's +//! shadow model answers every vendor command and the controller the +//! standard ones listed, until the controller fails or stalls and the model +//! answers everything (`BLUETOOTH LEND FELL BACK`). This reports the +//! model's unknown commands, each once, how many commands the guest sent, +//! at each doubling, and the function's trace: each configuration and +//! reset, and the first commands after each configuration with their +//! answers. With `--bluetooth-trace` it also logs every packet the function +//! captures (`GUEST BLUETOOTH RAW`, at most //! `stela_soc::usb::hci::capture::CAPTURED_PACKETS` per configuration). //! //! One controller serves the guest; others are reported and left idle. A @@ -37,9 +41,12 @@ use stela_drivers::{ use stela_soc::{ machine::{ AppleDevices, Outbound, UsbBluetooth, UsbBluetoothCaptured, UsbBluetoothCounters, - UsbBluetoothTrace, + UsbBluetoothFallback, UsbBluetoothLendCounters, UsbBluetoothTrace, + }, + usb::hci::{ + bridge::{HostController, Link}, + capture::LOG_PREFIX, }, - usb::hci::bridge::{HostController, Link}, }; enum Controller { @@ -145,6 +152,14 @@ pub struct HostBluetooth { capture: bool, /// The packets it captured, to report. captured: Vec, + /// Whether the controller is lent behind Apple's module. + lent: bool, + /// What its bridge reported last: the fallback, its counters, and + /// whether the guest wrote another address than the controller's. + lend: Option<(Option, UsbBluetoothLendCounters, bool)>, + /// Whether the fallback and the address were reported. + fell_back: bool, + address_differs: bool, } /// The controller is dropped in the loader's root. An install runs without @@ -196,6 +211,10 @@ impl HostBluetooth { trace: Vec::new(), capture: false, captured: Vec::new(), + lent: false, + lend: None, + fell_back: false, + address_differs: false, }) } @@ -215,20 +234,38 @@ impl HostBluetooth { trace: Vec::new(), capture: false, captured: Vec::new(), + lent: false, + lend: None, + fell_back: false, + address_differs: false, } } /// The guest's controller for a boot with `options`, said once in the /// log: the model of Apple's internal USB module for every boot with - /// host input. The host's `controller` is not lent: the guest's + /// host input. The host's `controller` is never lent raw: the guest's /// function would carry the host's vendor commands and replies, which - /// BlueTool's chip boot and bluetoothd's bring-up do not take. One not - /// kept is released in the loader's root by its drop. + /// BlueTool's chip boot and bluetoothd's bring-up do not take. With + /// `--bluetooth-lend` it is lent behind the module, which answers those + /// itself and falls back to the model on any failure. One not kept is + /// released in the loader's root by its drop. pub fn guest(controller: Option, options: &System, root: u64) -> Option { - let line = - stela_boot_core::guest_bluetooth::model_line(controller.is_some(), options.input)?; - output::arguments(format_args!("{line}")); - let mut guest = Self::modeled(root); + let mut guest = match controller { + Some(mut lent) if options.input && options.bluetooth_lend => { + let line = stela_boot_core::guest_bluetooth::lend_line(&lent.location); + output::arguments(format_args!("{line}")); + lent.lent = true; + lent + } + controller => { + let line = stela_boot_core::guest_bluetooth::model_line( + controller.is_some(), + options.input, + )?; + output::arguments(format_args!("{line}")); + Self::modeled(root) + } + }; guest.capture = options.bluetooth_trace; Some(guest) } @@ -236,6 +273,7 @@ impl HostBluetooth { /// The guest's USB function for this controller. pub fn kind(&self) -> UsbBluetooth { match self.controller { + _ if self.lent => UsbBluetooth::Bridged, Controller::Modeled => UsbBluetooth::Model, _ => UsbBluetooth::Host, } @@ -247,9 +285,12 @@ impl HostBluetooth { &mut self, devices: &mut AppleDevices, ) -> (Vec, usize, Option<(bool, UsbBluetoothCounters)>) { - if matches!(self.controller, Controller::Modeled) { + if self.lent || matches!(self.controller, Controller::Modeled) { self.unknown.extend(devices.bluetooth_unknown()); } + if self.lent { + self.lend = devices.bluetooth_lend(); + } // Asked at the first service turn, before the guest's USB stack // can configure the function. if core::mem::take(&mut self.capture) { @@ -283,7 +324,19 @@ impl HostBluetooth { output::arguments(format_args!("GUEST BLUETOOTH {entry}\n")); } for packet in self.captured.drain(..) { - output::arguments(format_args!("GUEST BLUETOOTH RAW {packet}\n")); + output::arguments(format_args!("{LOG_PREFIX}{packet}\n")); + } + let (fallback, lend, differs) = self.lend.unwrap_or_default(); + if let Some(fallback) = fallback.filter(|_| !self.fell_back) { + self.fell_back = true; + output::arguments(format_args!("BLUETOOTH LEND FELL BACK {fallback}\n")); + } + if differs && !self.address_differs { + self.address_differs = true; + output::arguments(format_args!( + "BLUETOOTH LEND the guest wrote a BD_ADDR its controller does not have, \ + which keeps its own\n" + )); } for opcode in self.unknown.drain(..) { output::arguments(format_args!( @@ -294,7 +347,7 @@ impl HostBluetooth { )); } let (up, counters) = status.unwrap_or_default(); - if matches!(self.controller, Controller::Modeled) + if (self.lent || matches!(self.controller, Controller::Modeled)) && counters.commands > 0 && counters.commands >= 2 * self.reported_commands { @@ -303,6 +356,12 @@ impl HostBluetooth { "GUEST BLUETOOTH commands={} unknown={}\n", counters.commands, counters.unknown )); + if self.lent { + output::arguments(format_args!( + "GUEST BLUETOOTH LEND forwarded={} local={} passed={} dropped={}\n", + lend.forwarded, lend.local, lend.passed, lend.dropped + )); + } } if self.up != Some(up) { self.up = Some(up); diff --git a/crates/stela-boot/src/engine/start.rs b/crates/stela-boot/src/engine/start.rs index 821f215635..2f0a858e85 100644 --- a/crates/stela-boot/src/engine/start.rs +++ b/crates/stela-boot/src/engine/start.rs @@ -3364,11 +3364,11 @@ fn start_devices( host_usb = Some(usb); // The guest's controller is the model of Apple's internal USB // module, for every boot with host input. The host's controller - // is not lent: the guest's function would carry the host's + // is not lent raw: the guest's function would carry the host's // vendor commands and replies, which BlueTool's chip boot and // bluetoothd's bring-up do not take. It is released in the - // loader's root by its drop (`bluetooth::HostBluetooth::guest`). - // The log says so once. + // loader's root by its drop (`bluetooth::HostBluetooth::guest`, + // which says so once, or lends it with `--bluetooth-lend`). host_bluetooth = bluetooth::HostBluetooth::guest(host_controller, options, handoff.root); // With no adapter started, the screen names each one found and diff --git a/crates/stela-soc/src/machine.rs b/crates/stela-soc/src/machine.rs index ecc7d42b15..bbf0de2e79 100644 --- a/crates/stela-soc/src/machine.rs +++ b/crates/stela-soc/src/machine.rs @@ -32,6 +32,7 @@ pub use crate::usb::{ ecm::Counters as UsbNetworkCounters, hci::{ Counters as UsbBluetoothCounters, Outbound, Traced as UsbBluetoothTrace, + bridge::{Counters as UsbBluetoothLendCounters, Fallback as UsbBluetoothFallback}, capture::Captured as UsbBluetoothCaptured, }, host::{Descriptor as UsbDescriptor, MuxEndpoints}, @@ -402,6 +403,11 @@ pub enum UsbBluetooth { /// Apple's internal USB Bluetooth module, answered by the controller /// model: powered, with no radio, finding nothing. Model, + /// Apple's internal USB Bluetooth module with one of the host's + /// controllers lent behind it (`crate::usb::hci::bridge`): the model + /// answers its vendor commands, the host's controller the standard ones + /// listed, and the model everything once the host's fails or stalls. + Bridged, } impl UsbCables { diff --git a/crates/stela-soc/src/machine/usb.rs b/crates/stela-soc/src/machine/usb.rs index c384280fe1..ce2b89cf3d 100644 --- a/crates/stela-soc/src/machine/usb.rs +++ b/crates/stela-soc/src/machine/usb.rs @@ -8,6 +8,17 @@ use stela_contracts::refuse; /// The reason of the power-off a held power button makes. pub const POWER_BUTTON_HELD: &str = "smc: power button held: system power-off"; +/// The guest's USB Bluetooth function of `kind` on the board whose ECID is +/// `ecid`, which gives the model's address. +fn bluetooth_function(kind: UsbBluetooth, ecid: u64) -> Hci { + let address = || crate::usb::hci::model::address(ecid); + match kind { + UsbBluetooth::Host => Hci::new(), + UsbBluetooth::Model => Hci::modeled(address()), + UsbBluetooth::Bridged => Hci::bridged(address()), + } +} + impl AppleDevices { /// The shared cable state of one Type-C connector. pub(super) fn typec_port(&mut self, number: u32) -> typec::Port { @@ -178,10 +189,7 @@ impl AppleDevices { let attachments = Attachments { input: Peripheral::new(), network, - bluetooth: bluetooth.map(|kind| match kind { - UsbBluetooth::Host => Hci::new(), - UsbBluetooth::Model => Hci::modeled(crate::usb::hci::model::address(self.ecid)), - }), + bluetooth: bluetooth.map(|kind| bluetooth_function(kind, self.ecid)), disks, }; master.peripheral = Some(Hub::new(attachments, "0001")?); @@ -255,6 +263,17 @@ impl AppleDevices { } } + /// What the bridge to a lent host controller reports: why it fell back + /// to the model, if it has, its counters, and whether the guest wrote a + /// BD_ADDR the controller does not have; `None` unless one is lent. + pub fn bluetooth_lend( + &mut self, + ) -> Option<(Option, UsbBluetoothLendCounters, bool)> { + let hci = self.usb_bluetooth()?; + let counters = hci.bridge_counters()?; + Some((hci.fallback(), counters, hci.bridged_address_differs())) + } + /// The next packet the guest sent for the host's Bluetooth controller. pub fn bluetooth_take(&mut self) -> Option { self.usb_bluetooth()?.take() @@ -474,3 +493,25 @@ impl AppleDevices { }) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// `--bluetooth-lend` gives the guest Apple's module with a bridge to + /// the host's controller behind it; the model and the raw function stay + /// as they were. + #[test] + fn each_kind_of_guest_bluetooth_is_its_function() { + let ecid = 0x1234; + let address = crate::usb::hci::model::address(ecid); + let bridged = bluetooth_function(UsbBluetooth::Bridged, ecid); + assert!(bridged.bridge_counters().is_some()); + assert_eq!(bridged.model_address(), Some(address)); + let modeled = bluetooth_function(UsbBluetooth::Model, ecid); + assert!(modeled.bridge_counters().is_none()); + assert_eq!(modeled.model_address(), Some(address)); + let host = bluetooth_function(UsbBluetooth::Host, ecid); + assert_eq!((host.model_address(), host.bridge_counters()), (None, None)); + } +} From b7faa3029f418c5f9796e20e28111d8560143079 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:24:03 +0000 Subject: [PATCH 06/18] test(bluetooth): replay bluetoothd 26B123's start-up and System Settings' discovery through the bridged function, the owner's link and a scripted RTL8852C with devices in range, and check that the start-up completes as Apple's module with every vendor and unlisted command answered here, inquiry results of each mode, Inquiry Complete and remote names reach macOS in order, a burst beyond the guest's room is held with none lost, a bus reset keeps an old inquiry out, and a stall, refusal or transport failure at any of the 18 forwarded start-up steps falls back with the start-up still answered as by the model --- crates/stela-soc/src/usb/hci/bridge.rs | 2 + crates/stela-soc/src/usb/hci/bridge/chip.rs | 265 +++++++++++- crates/stela-soc/src/usb/hci/bridge/replay.rs | 390 ++++++++++++++++++ 3 files changed, 649 insertions(+), 8 deletions(-) create mode 100644 crates/stela-soc/src/usb/hci/bridge/replay.rs diff --git a/crates/stela-soc/src/usb/hci/bridge.rs b/crates/stela-soc/src/usb/hci/bridge.rs index 74388082a0..f322e5687b 100644 --- a/crates/stela-soc/src/usb/hci/bridge.rs +++ b/crates/stela-soc/src/usb/hci/bridge.rs @@ -493,4 +493,6 @@ impl Bridge { #[cfg(test)] mod chip; #[cfg(test)] +mod replay; +#[cfg(test)] mod tests; diff --git a/crates/stela-soc/src/usb/hci/bridge/chip.rs b/crates/stela-soc/src/usb/hci/bridge/chip.rs index 409e02ba10..f6f2c307ff 100644 --- a/crates/stela-soc/src/usb/hci/bridge/chip.rs +++ b/crates/stela-soc/src/usb/hci/bridge/chip.rs @@ -6,12 +6,32 @@ //! answers every standard command it lists with its specified return //! lengths, records every command it is sent, and answers a vendor command, //! which the bridge must never send, Unknown HCI Command. -use alloc::{vec, vec::Vec}; +//! +//! Its air holds the devices in range ([`Responder`]): an inquiry reports +//! each in the inquiry mode the host set, then completes; a remote name +//! request gives a device's name, or Page Timeout for an address no device +//! has. It can also stall at a command, refuse one, fail as a transport, and +//! send what Realtek firmware may after a reset (a vendor event and credits +//! alone). It implements [`HostController`], with the test's clock. +use super::link::{HostController, Packet}; +use crate::{counter::FREQUENCY_HZ, usb::hci::Outbound}; +use alloc::{string::String, vec, vec::Vec}; const COMMAND_COMPLETE: u8 = 0x0e; const COMMAND_STATUS: u8 = 0x0f; +const INQUIRY_COMPLETE: u8 = 0x01; +const INQUIRY_RESULT: u8 = 0x02; +const REMOTE_NAME_REQUEST_COMPLETE: u8 = 0x07; +const INQUIRY_RESULT_WITH_RSSI: u8 = 0x22; +const EXTENDED_INQUIRY_RESULT: u8 = 0x2f; const SUCCESS: u8 = 0x00; const UNKNOWN_COMMAND: u8 = 0x01; +const PAGE_TIMEOUT: u8 = 0x04; +/// System counts in a baseband slot, 625 us, and an inquiry length unit. +const SLOT: u64 = FREQUENCY_HZ * 625 / 1_000_000; +const INQUIRY_UNIT: u64 = 2048 * SLOT; +/// How long after an inquiry starts each device answers, in turn. +pub const RESPONSE: u64 = FREQUENCY_HZ / 100; /// The controller's address in the tests. pub const ADDRESS: [u8; 6] = [0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0x02]; @@ -26,6 +46,10 @@ pub const FEATURES_2: [u8; 8] = [0x0f, 0x03, 0, 0, 0, 0, 0, 0]; pub const LE_FEATURES: [u8; 8] = [0xff, 0x59, 0x01, 0, 0, 0, 0, 0]; /// Read Buffer Size: ACL 1021 x 6, SCO 255 x 12. pub const BUFFERS: [u8; 7] = [0xfd, 0x03, 0xff, 0x06, 0x00, 0x0c, 0x00]; +/// What Realtek firmware may send after a reset: a vendor event and a +/// Command Complete that only gives credits. +pub const VENDOR_EVENT: [u8; 4] = [0xff, 2, 0x34, 0x01]; +pub const CREDITS_ALONE: [u8; 5] = [COMMAND_COMPLETE, 3, 1, 0, 0]; /// Commands that read what a write stored: (read, write, power-on value). const SETTINGS: &[(u16, u16, &[u8])] = &[ @@ -46,11 +70,96 @@ const SETTINGS: &[(u16, u16, &[u8])] = &[ (0x0c6c, 0x0c6d, &[0, 0]), ]; +/// A device in range that answers inquiries and name requests. +#[derive(Debug, Clone)] +pub struct Responder { + pub address: [u8; 6], + pub class: [u8; 3], + pub clock_offset: u16, + pub rssi: i8, + /// Its extended inquiry response, 240 bytes; none for a pre-2.1 device. + pub eir: Option>, + pub name: Vec, +} + +impl Responder { + /// A device whose EIR names it `name`, or with none. + pub fn new(last: u8, name: &str, eir: bool) -> Self { + let mut eir_data = vec![name.len() as u8 + 1, 0x09]; + eir_data.extend_from_slice(name.as_bytes()); + eir_data.resize(240, 0); + Self { + address: [last, 0x11, 0x22, 0x33, 0x44, 0x02], + class: [0x04, 0x04, 0x24], + clock_offset: 0x1234 + u16::from(last), + rssi: -40 - (last % 50) as i8, + eir: eir.then_some(eir_data), + name: name.as_bytes().to_vec(), + } + } + + /// Its report in inquiry mode `mode` (Vol 4 Part E 7.7.2, 7.7.33, + /// 7.7.38). + pub fn report(&self, mode: u8) -> Vec { + let [clock_low, clock_high] = self.clock_offset.to_le_bytes(); + let mut p = vec![1]; + p.extend_from_slice(&self.address); + match (mode, &self.eir) { + (0, _) => { + p.extend_from_slice(&[1, 0, 0]); + p.extend_from_slice(&self.class); + p.extend_from_slice(&[clock_low, clock_high]); + event(INQUIRY_RESULT, &p) + } + (_, eir) => { + p.extend_from_slice(&[1, 0]); + p.extend_from_slice(&self.class); + p.extend_from_slice(&[clock_low, clock_high, self.rssi as u8]); + match eir { + Some(eir) if mode == 2 => { + p.extend_from_slice(eir); + event(EXTENDED_INQUIRY_RESULT, &p) + } + _ => event(INQUIRY_RESULT_WITH_RSSI, &p), + } + } + } + } + + /// Its Remote Name Request Complete (7.7.7). + pub fn named(&self) -> Vec { + name_complete(SUCCESS, self.address, &self.name) + } +} + +fn event(code: u8, parameters: &[u8]) -> Vec { + let mut event = vec![code, parameters.len() as u8]; + event.extend_from_slice(parameters); + event +} + +pub fn name_complete(status: u8, address: [u8; 6], name: &[u8]) -> Vec { + let mut p = vec![status]; + p.extend_from_slice(&address); + p.extend_from_slice(name); + p.resize(1 + 6 + 248, 0); + event(REMOTE_NAME_REQUEST_COMPLETE, &p) +} + +/// What a scheduled event belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Tag { + Answer, + Inquiry, + Name, +} + /// The stand-in controller. #[derive(Debug, Clone)] pub struct Chip { - /// Every command it was sent, in order. + /// Every command it was sent, in order, and its ACL data. pub received: Vec>, + pub acl: Vec>, /// Supported Commands. pub commands: [u8; 64], /// The credits each answer gives. @@ -58,6 +167,25 @@ pub struct Chip { /// LMP features page 0, and Read Buffer Size's return parameters. pub features: [u8; 8], pub buffers: [u8; 7], + /// The devices in range, and how long after each other they answer an + /// inquiry. + pub air: Vec, + pub response: u64, + /// The system count now, which the test sets. + pub now: u64, + /// A command it never answers, from the given time it is sent (1: the + /// first). + pub stall: Option<(u16, usize)>, + /// A command it answers with this error status, its return parameters + /// kept. + pub refuse: Option<(u16, usize, u8)>, + /// A command at which its transport fails. + pub fail: Option<(u16, usize)>, + failed: bool, + /// Whether it sends [`VENDOR_EVENT`] and [`CREDITS_ALONE`] after each + /// reset. + pub noise: bool, + scheduled: Vec<(u64, Tag, Vec)>, /// Its settings since Reset: (write opcode, parameters). written: Vec<(u16, Vec)>, local_name: Vec, @@ -71,10 +199,20 @@ impl Chip { commands[..42].fill(0xff); Self { received: Vec::new(), + acl: Vec::new(), commands, credits: 2, features: FEATURES, buffers: BUFFERS, + air: Vec::new(), + response: RESPONSE, + now: 0, + stall: None, + refuse: None, + fail: None, + failed: false, + noise: false, + scheduled: Vec::new(), written: Vec::new(), local_name: vec![0; 248], eir: vec![0; 241], @@ -89,6 +227,11 @@ impl Chip { .collect() } + /// How many times it was sent `opcode`, this one included. + fn times(&self, opcode: u16) -> usize { + self.opcodes().into_iter().filter(|&o| o == opcode).count() + } + fn complete(&self, opcode: u16, status: u8, returns: &[u8]) -> Vec { let [low, high] = opcode.to_le_bytes(); let mut event = vec![ @@ -120,11 +263,33 @@ impl Chip { vec![self.complete(opcode, SUCCESS, returns)] } - /// One command; its events, in order. + fn schedule(&mut self, after: u64, tag: Tag, event: Vec) { + self.scheduled.push((self.now + after, tag, event)); + } + + /// One command; its answer at once, its procedure's events later. pub fn command(&mut self, packet: &[u8]) -> Vec> { self.received.push(packet.to_vec()); let opcode = u16::from_le_bytes([packet[0], packet[1]]); - let p = packet[3..].to_vec(); + let times = self.times(opcode); + if self.stall == Some((opcode, times)) { + return Vec::new(); + } + let scheduled = self.scheduled.len(); + let mut answer = self.answer(opcode, &packet[3..]); + if let Some((_, _, status)) = self.refuse.filter(|r| (r.0, r.1) == (opcode, times)) { + match answer[0][0] { + COMMAND_STATUS => answer[0][2] = status, + _ => answer[0][5] = status, + } + // A refused procedure does not run. + self.scheduled.truncate(scheduled); + } + answer + } + + fn answer(&mut self, opcode: u16, p: &[u8]) -> Vec> { + let p = p.to_vec(); if let Some(&(_, write, default)) = SETTINGS.iter().find(|s| s.0 == opcode) { return self.ok(opcode, &self.stored(write, default)); } @@ -133,14 +298,56 @@ impl Chip { return self.ok(opcode, &[]); } match opcode { - 0x0401 | 0x0419 => vec![self.status(opcode, SUCCESS)], - 0x041a => self.ok(opcode, &p[..6]), - 0x0402 | 0x0c01 | 0x0c63 | 0x2001 => self.ok(opcode, &[]), + 0x0401 => { + let mode = self.stored(0x0c45, &[0])[0]; + let reports: Vec<_> = self.air.iter().map(|r| r.report(mode)).collect(); + for (at, report) in (1..).zip(reports) { + self.schedule(at * self.response, Tag::Inquiry, report); + } + let end = u64::from(p[3]) * INQUIRY_UNIT; + self.schedule(end, Tag::Inquiry, vec![INQUIRY_COMPLETE, 1, SUCCESS]); + vec![self.status(opcode, SUCCESS)] + } + 0x0402 => { + self.scheduled.retain(|s| s.1 != Tag::Inquiry); + self.ok(opcode, &[]) + } + 0x0419 => { + let peer: [u8; 6] = p[..6].try_into().expect("an address"); + let named = self + .air + .iter() + .find(|r| r.address == peer) + .map(|r| r.named()); + match named { + Some(named) => self.schedule(2 * RESPONSE, Tag::Name, named), + None => { + let timeout = u16::from_le_bytes( + self.stored(0x0c18, &[0, 0x20])[..2] + .try_into() + .expect("two bytes"), + ); + let complete = name_complete(PAGE_TIMEOUT, peer, &[]); + self.schedule(u64::from(timeout) * SLOT, Tag::Name, complete); + } + } + vec![self.status(opcode, SUCCESS)] + } + 0x041a => { + self.scheduled.retain(|s| s.1 != Tag::Name); + self.ok(opcode, &p[..6]) + } + 0x0c01 | 0x0c63 | 0x2001 => self.ok(opcode, &[]), 0x0c03 => { self.written.clear(); + self.scheduled.clear(); self.local_name = vec![0; 248]; self.eir = vec![0; 241]; - self.ok(opcode, &[]) + let mut events = self.ok(opcode, &[]); + if self.noise { + events.extend([VENDOR_EVENT.to_vec(), CREDITS_ALONE.to_vec()]); + } + events } 0x0c13 => { self.local_name = p; @@ -179,3 +386,45 @@ impl Chip { } } } + +impl HostController for Chip { + fn send(&mut self, packet: &Outbound) -> Result { + if self.failed { + return Err(String::from("the scripted controller failed")); + } + match packet { + Outbound::Command(bytes) => { + let opcode = u16::from_le_bytes([bytes[0], bytes[1]]); + if self.fail == Some((opcode, self.times(opcode) + 1)) { + self.received.push(bytes.clone()); + self.failed = true; + return Err(String::from("the scripted controller failed")); + } + for event in self.command(bytes) { + self.schedule(0, Tag::Answer, event); + } + } + Outbound::Acl(bytes) => self.acl.push(bytes.clone()), + } + Ok(true) + } + + fn poll(&mut self) -> Result, String> { + if self.failed { + return Err(String::from("the scripted controller failed")); + } + // In time order, a command's answer before its procedure's events + // at the same time, other ties as scheduled. + self.scheduled.sort_by_key(|s| (s.0, s.1 != Tag::Answer)); + let due = self + .scheduled + .iter() + .take_while(|s| s.0 <= self.now) + .count(); + Ok(self + .scheduled + .drain(..due) + .map(|(_, _, event)| Packet::Event(event)) + .collect()) + } +} diff --git a/crates/stela-soc/src/usb/hci/bridge/replay.rs b/crates/stela-soc/src/usb/hci/bridge/replay.rs new file mode 100644 index 0000000000..484c59be90 --- /dev/null +++ b/crates/stela-soc/src/usb/hci/bridge/replay.rs @@ -0,0 +1,390 @@ +//! The replay harness: the guest's function (`Hci::bridged`), the owner's +//! [`Link`] and the scripted controller ([`Chip`]), driven turn by turn as +//! the engine's service turns and the guest's xHCI drive them, with +//! bluetoothd 26B123's recorded start-up and the procedures System Settings +//! runs to list nearby devices. +use super::{ + Cause, + chip::{self, Chip, Responder}, + link::{Link, Packet}, + policy, +}; +use crate::{ + counter::FREQUENCY_HZ, + usb::{ + BusPeer, Function, Reply, Token, + control::{ + SET_ADDRESS, SET_CONFIGURATION, + tests::{setup, transfer}, + }, + hci::{ + EVENTS, Hci, + capture::{self, Direction, Kind}, + model::Model, + }, + }, +}; +use alloc::{string::ToString, vec, vec::Vec}; + +const ADDRESS: [u8; 6] = [0x11, 0x22, 0x33, 0x44, 0x55, 0x02]; +/// A service turn every millisecond. +const TURN: u64 = FREQUENCY_HZ / 1000; +const BRING_UP: &str = include_str!("fixtures/26B123-bring-up.hci"); +/// The general inquiry access code, for 2.56 s. +const INQUIRY: [u8; 8] = [0x01, 0x04, 5, 0x33, 0x8b, 0x9e, 2, 0]; + +/// The commands the guest sent in a capture. +fn commands(text: &str) -> Vec> { + capture::read(text) + .expect("a capture") + .into_iter() + .filter(|p| p.direction == Direction::FromGuest && p.kind == Kind::Command) + .map(|p| p.bytes) + .collect() +} + +fn opcode(packet: &[u8]) -> u16 { + u16::from_le_bytes([packet[0], packet[1]]) +} + +fn packet(opcode: u16, parameters: &[u8]) -> Vec { + let mut packet = opcode.to_le_bytes().to_vec(); + packet.push(parameters.len() as u8); + packet.extend_from_slice(parameters); + packet +} + +/// Whether `event` answers `opcode`. +fn answers(event: &[u8], opcode: u16) -> bool { + match *event { + [0x0e, _, _, low, high, ..] | [0x0f, _, _, _, low, high, ..] => { + u16::from_le_bytes([low, high]) == opcode + } + _ => false, + } +} + +/// An answer's event, status, return length and command credits. +fn summary(event: &[u8]) -> (u8, u8, usize, u8) { + match event[0] { + 0x0e => (0x0e, event[5], event.len() - 6, event[2]), + _ => (event[0], event[2], 0, event[3]), + } +} + +struct Rig { + hci: Hci, + link: Link, + chip: Chip, + now: u64, + failed: bool, +} + +impl Rig { + fn new(chip: Chip) -> Self { + let mut hci = Hci::bridged(ADDRESS); + transfer(&mut hci, setup(0, SET_ADDRESS, 1, 0, 0), &[]).unwrap(); + transfer(&mut hci, setup(0, SET_CONFIGURATION, 1, 0, 0), &[]).unwrap(); + Self { + hci, + link: Link::default(), + chip, + now: 0, + failed: false, + } + } + + /// A rig whose guest ran bluetoothd's start-up. + fn started(chip: Chip) -> Self { + let mut rig = Self::new(chip); + for command in commands(BRING_UP) { + rig.command(&command); + } + assert_eq!(rig.hci.fallback(), None); + rig + } + + /// One service turn, as the engine's: what the function queued goes to + /// the controller, and what the controller has comes back as far as the + /// guest has room. A failure is told to the function once, and the + /// controller is left alone after it. + fn turn(&mut self) { + self.now += TURN; + self.chip.now = self.now; + self.hci.set_time(self.now); + let outbound: Vec<_> = core::iter::from_fn(|| self.hci.take()).collect(); + if self.failed { + return; + } + self.link.queue(outbound); + let room = self.hci.room_left(); + let received = self + .link + .send(&mut self.chip) + .and_then(|()| self.link.receive(&mut self.chip, room)); + match received { + Ok(packets) => { + for packet in packets { + match packet { + Packet::Event(event) => self.hci.deliver_event(&event), + Packet::Acl(data) => self.hci.deliver_acl(&data), + Packet::Diagnostic(_) => {} + } + } + } + Err(_) => { + self.failed = true; + self.link.clear(); + self.hci.host_failed(); + } + } + } + + /// The events the guest reads now, each in its USB packets. + fn read(&mut self) -> Vec> { + let (mut events, mut event) = (Vec::new(), Vec::new()); + loop { + let mut buffer = [0; 16]; + let Reply::Ack(n) = self.hci.packet(EVENTS, Token::In, &mut buffer).unwrap() else { + return events; + }; + event.extend_from_slice(&buffer[..n]); + if n < buffer.len() { + events.push(core::mem::take(&mut event)); + } + } + } + + /// bluetoothd sends `command` and the turns run until it is answered: + /// every event the guest read meanwhile. + fn command(&mut self, command: &[u8]) -> Vec> { + let op = opcode(command); + let request = setup(0x20, 0, 0, 0, command.len() as u16); + transfer(&mut self.hci, request, command).expect("the function takes it"); + let mut events = self.read(); + for _ in 0..3000 { + if events.iter().any(|e| answers(e, op)) { + return events; + } + self.turn(); + events.extend(self.read()); + } + panic!("{op:#06x} was never answered"); + } + + /// The events the guest reads over `turns` turns. + fn run(&mut self, turns: usize) -> Vec> { + let mut events = Vec::new(); + for _ in 0..turns { + self.turn(); + events.extend(self.read()); + } + events + } +} + +/// With `--bluetooth-lend` and a controller that answers: bluetoothd's +/// start-up completes, every answer the model's status and length with one +/// credit, Apple's identity kept. Every opcode of the start-up off the list, +/// each vendor one above all, is answered without reaching the controller; +/// the controller's vendor event and credits after its reset reach nobody. +#[test] +fn macoss_start_up_through_a_lent_controller_completes_as_apples_module() { + let mut chip = Chip::new(); + chip.noise = true; + let mut rig = Rig::new(chip); + rig.hci.capture(); + let mut model = Model::new(ADDRESS); + let start_up = commands(BRING_UP); + let mut local = 0; + for command in &start_up { + let op = opcode(command); + let sent = rig.chip.received.len(); + let events = rig.command(command); + let answer = events.iter().find(|e| answers(e, op)).unwrap(); + let expected = model.command(command, 0); + let (code, status, returns, _) = summary(&expected[0]); + assert_eq!(summary(answer), (code, status, returns, 1), "{op:#06x}"); + let forwarded = policy::forward(command).is_some(); + assert!(!forwarded || !policy::vendor(op)); + assert_eq!( + rig.chip.received.len(), + sent + usize::from(forwarded), + "{op:#06x}" + ); + if !forwarded { + local += 1; + } + if [0x1001, 0xfc79].contains(&op) { + assert_eq!(answer, &expected[0], "the module's identity"); + } + } + assert_eq!((local, rig.chip.received.len()), (28, 18)); + assert!(rig.chip.opcodes().iter().all(|&op| !policy::vendor(op))); + assert_eq!(rig.hci.fallback(), None); + let counters = rig.hci.bridge_counters().unwrap(); + assert_eq!((counters.forwarded, counters.dropped), (18, 2)); + // The capture holds both sides, and reads back as it was written. + let captured = rig.hci.take_captured(); + for direction in [Direction::ToChip, Direction::FromChip] { + assert!(captured.iter().any(|p| p.direction == direction)); + } + assert!( + captured + .iter() + .filter(|p| p.direction == Direction::ToChip) + .all(|p| !policy::vendor(opcode(&p.bytes))) + ); + let lines: Vec<_> = captured.iter().map(ToString::to_string).collect(); + assert_eq!(capture::read(&lines.join("\n")), Ok(captured)); +} + +/// System Settings' inquiry reaches the controller, and each device's +/// result reaches macOS in the inquiry mode bluetoothd set, in order, then +/// Inquiry Complete. +#[test] +fn an_inquiry_reaches_the_controller_and_each_kind_of_result_reaches_macos() { + let air = vec![ + Responder::new(1, "Headphones", true), + Responder::new(2, "Old phone", false), + Responder::new(3, "Keyboard", true), + ]; + let mut chip = Chip::new(); + chip.air = air.clone(); + let mut rig = Rig::started(chip); + // The start-up set Extended Inquiry Result mode. + for (mode, kinds) in [(2, [0x2f, 0x22, 0x2f]), (1, [0x22; 3]), (0, [0x02; 3])] { + if mode != 2 { + rig.command(&packet(0x0c45, &[mode])); + } + let mut events = rig.command(&INQUIRY); + assert_eq!(events[0], [0x0f, 4, 0, 1, 0x01, 0x04], "status, one credit"); + events.extend(rig.run(3000)); + let mut expected: Vec<_> = air.iter().map(|r| r.report(mode)).collect(); + expected.push(vec![0x01, 1, 0]); + assert_eq!(events[1..], expected, "mode {mode}"); + let codes: Vec = events[1..4].iter().map(|e| e[0]).collect(); + assert_eq!(codes, kinds); + // The device's own name is in its extended result. + if mode == 2 { + assert_eq!(&events[1][17..29], b"\x0b\x09Headphones"); + } + } + assert_eq!(rig.hci.fallback(), None); + // A cancelled inquiry ends with no more results. + rig.command(&INQUIRY); + let cancelled = rig.command(&packet(0x0402, &[])); + assert!(answers(cancelled.last().unwrap(), 0x0402)); + assert!(rig.run(3000).is_empty()); +} + +/// A name request reaches the controller, and the device's name, or Page +/// Timeout for no device, reaches macOS. +#[test] +fn a_remote_name_request_reaches_the_controller_and_the_name_reaches_macos() { + let headphones = Responder::new(1, "Headphones", true); + let mut chip = Chip::new(); + chip.air = vec![headphones.clone()]; + let mut rig = Rig::started(chip); + let mut request = headphones.address.to_vec(); + request.extend_from_slice(&[1, 0, 0, 0]); + let mut events = rig.command(&packet(0x0419, &request)); + assert_eq!(events[0], [0x0f, 4, 0, 1, 0x19, 0x04]); + events.extend(rig.run(100)); + assert_eq!(events[1..], [headphones.named()]); + assert_eq!(&events[1][9..19], b"Headphones"); + // No device has this address: Page Timeout after bluetoothd's page + // timeout, 5.12 s. + let nobody = [9, 9, 9, 9, 9, 0x02]; + let mut request = nobody.to_vec(); + request.extend_from_slice(&[1, 0, 0, 0]); + rig.command(&packet(0x0419, &request)); + assert_eq!(rig.run(6000), [chip::name_complete(0x04, nobody, &[])]); + assert_eq!(rig.hci.fallback(), None); +} + +/// The fallback at each step: whichever forwarded command of the start-up +/// the controller leaves unanswered, refuses or fails at, the guest gets the +/// model's answer to it and to everything after, so bluetoothd's start-up +/// completes as on the model alone, and nothing reaches the controller +/// again. +#[test] +fn the_bridge_falls_back_at_any_start_up_step_and_the_start_up_still_completes() { + let start_up = commands(BRING_UP); + let mut steps = Vec::new(); + for (index, command) in start_up.iter().enumerate() { + if policy::forward(command).is_some() { + let op = opcode(command); + let nth = start_up[..=index] + .iter() + .filter(|c| opcode(c) == op) + .count(); + steps.push((op, nth)); + } + } + assert_eq!(steps.len(), 18); + for (sent, &(op, nth)) in steps.iter().enumerate() { + for cause in [Cause::Timeout, Cause::Refused(0x1f), Cause::HostFailed] { + let mut chip = Chip::new(); + match cause { + Cause::Timeout => chip.stall = Some((op, nth)), + Cause::Refused(status) => chip.refuse = Some((op, nth, status)), + _ => chip.fail = Some((op, nth)), + } + let mut rig = Rig::new(chip); + let mut model = Model::new(ADDRESS); + for command in &start_up { + let answer = rig.command(command); + let answer = answer.iter().find(|e| answers(e, opcode(command))).unwrap(); + let (code, status, returns, _) = summary(&model.command(command, 0)[0]); + assert_eq!( + summary(answer), + (code, status, returns, 1), + "{op:#06x} {cause:?}: {:#06x}", + opcode(command) + ); + } + let fallback = rig.hci.fallback().expect("fell back"); + assert_eq!((fallback.opcode, fallback.cause), (Some(op), cause)); + assert_eq!(rig.chip.received.len(), sent + 1, "{op:#06x} {cause:?}"); + } + } +} + +/// Bounded delivery: a poll that gives more results than the guest's queue +/// holds leaves the rest with the owner, and every one reaches the guest, in +/// order, none overflowed. +#[test] +fn a_burst_beyond_the_guests_room_is_held_and_none_is_lost() { + let air: Vec<_> = (0..100).map(|n| Responder::new(n, "Phone", true)).collect(); + let mut chip = Chip::new(); + chip.air = air.clone(); + chip.response = 0; + let mut rig = Rig::started(chip); + let mut events = rig.command(&INQUIRY); + events.extend(rig.run(3000)); + assert_eq!(events.len(), 1 + 100 + 1); + for (event, responder) in events[1..].iter().zip(&air) { + assert_eq!(event, &responder.report(2)); + } + assert_eq!(rig.hci.counters().overflowed, 0); +} + +/// A guest bus reset mid-inquiry: the old inquiry's results stay out until +/// the guest's next HCI Reset is answered, and the controller is never +/// reset by USB. +#[test] +fn a_bus_reset_mid_inquiry_keeps_the_old_results_out() { + let mut chip = Chip::new(); + chip.air = vec![Responder::new(1, "Headphones", true)]; + chip.response = FREQUENCY_HZ / 2; + let mut rig = Rig::started(chip); + rig.command(&INQUIRY); + rig.hci.reset().unwrap(); + transfer(&mut rig.hci, setup(0, SET_ADDRESS, 1, 0, 0), &[]).unwrap(); + transfer(&mut rig.hci, setup(0, SET_CONFIGURATION, 1, 0, 0), &[]).unwrap(); + assert!(rig.run(3000).is_empty(), "the old inquiry's events"); + assert!(rig.command(&packet(0x0c03, &[])).len() == 1); + assert_eq!(rig.hci.fallback(), None); + assert_eq!(rig.chip.opcodes().last(), Some(&0x0c03)); +} From d6880d418b7ed8035ee08e491756a7d6894984b7 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:59:00 +0000 Subject: [PATCH 07/18] fix(bluetooth): mask every packet --bluetooth-trace captures before the function holds it, keeping headers, statuses and plain parameters, the vendor half and last byte of each address, and hiding names, opaque payloads, vendor parameters and returns, ACL past its HCI and L2CAP headers, keys and secrets and anything no rule names, printed xx and read back as 0, and say once in the log that the trace stays private until checked, where it logged the controller's and the platform's addresses, the Mac's name, every neighbour's address, name and manufacturer data and the guest's vendor parameters raw --- crates/stela-boot-core/src/guest_bluetooth.rs | 18 ++ crates/stela-boot-core/src/options.rs | 5 +- crates/stela-boot/src/engine/bluetooth.rs | 4 + crates/stela-soc/src/usb/hci.rs | 41 ++- crates/stela-soc/src/usb/hci/capture.rs | 241 +++++++++++++++- crates/stela-soc/src/usb/hci/capture/mask.rs | 269 ++++++++++++++++++ 6 files changed, 547 insertions(+), 31 deletions(-) create mode 100644 crates/stela-soc/src/usb/hci/capture/mask.rs diff --git a/crates/stela-boot-core/src/guest_bluetooth.rs b/crates/stela-boot-core/src/guest_bluetooth.rs index 10e61c29ac..dabefe4a7a 100644 --- a/crates/stela-boot-core/src/guest_bluetooth.rs +++ b/crates/stela-boot-core/src/guest_bluetooth.rs @@ -14,6 +14,13 @@ //! [`lend_line`] names it instead. use alloc::{format, string::String}; +/// The line for a boot that logs the guest's Bluetooth packets +/// (`--bluetooth-trace`): what is hidden of them, and what is not. +pub const TRACE_LINE: &str = "BLUETOOTH TRACE the guest's Bluetooth packets are logged masked: \ + addresses keep their vendor half and last byte, and names, payloads and keys are hidden; \ + the log still names nearby devices' classes and signal strengths, so keep it private \ + until it has been checked\n"; + /// The line for a boot that lends the host's controller at `location` to /// the guest behind Apple's module. pub fn lend_line(location: &str) -> String { @@ -53,6 +60,17 @@ mod tests { } } + /// `--bluetooth-trace` says once what its lines hide and that the log + /// still needs checking before it is posted. + #[test] + fn the_capture_says_what_it_hides_and_that_the_log_stays_private() { + assert!(TRACE_LINE.starts_with("BLUETOOTH TRACE ")); + for said in ["masked", "names", "keys", "hidden", "private"] { + assert!(TRACE_LINE.contains(said), "{said}"); + } + assert!(TRACE_LINE.ends_with('\n') && TRACE_LINE.matches('\n').count() == 1); + } + /// `--bluetooth-lend`: the line names the controller lent, the module it /// sits behind, and the fallback. #[test] diff --git a/crates/stela-boot-core/src/options.rs b/crates/stela-boot-core/src/options.rs index bea5dc473e..f54e4ae687 100644 --- a/crates/stela-boot-core/src/options.rs +++ b/crates/stela-boot-core/src/options.rs @@ -277,8 +277,9 @@ pub struct System { /// controller and feed it the host's virtio-input devices (`--input`). pub input: bool, /// Log every packet of the guest's Bluetooth controller, 1024 per - /// configuration (`--bluetooth-trace`). The packets name nearby devices' - /// addresses and names. + /// configuration (`--bluetooth-trace`), masked: addresses keep their + /// vendor half and last byte, names, payloads and keys are hidden. A raw + /// capture is not offered. pub bluetooth_trace: bool, /// Lend the host's Bluetooth controller to the guest behind the model of /// Apple's module, which answers its vendor commands and takes over diff --git a/crates/stela-boot/src/engine/bluetooth.rs b/crates/stela-boot/src/engine/bluetooth.rs index fa7eb3f6f1..146bd58330 100644 --- a/crates/stela-boot/src/engine/bluetooth.rs +++ b/crates/stela-boot/src/engine/bluetooth.rs @@ -267,6 +267,10 @@ impl HostBluetooth { } }; guest.capture = options.bluetooth_trace; + if guest.capture { + let line = stela_boot_core::guest_bluetooth::TRACE_LINE; + output::arguments(format_args!("{line}")); + } Some(guest) } diff --git a/crates/stela-soc/src/usb/hci.rs b/crates/stela-soc/src/usb/hci.rs index 9987996c06..f7b48709c0 100644 --- a/crates/stela-soc/src/usb/hci.rs +++ b/crates/stela-soc/src/usb/hci.rs @@ -1526,29 +1526,26 @@ mod tests { hci.packet(ACL_OUT, Token::Out, &mut rest.to_vec()).unwrap(); hci.deliver_acl(&long); hci.deliver_event(&[0x0e, 4, 1, 0x03, 0x0c, 0]); - let shown = long[..CAPTURED_BYTES].to_vec(); - let cut = long.len() - CAPTURED_BYTES; + let captured = hci.take_captured(); + assert_eq!(captured.len(), 3); + for (packet, direction) in captured[..2] + .iter() + .zip([Direction::FromGuest, Direction::ToGuest]) + { + assert_eq!((packet.direction, packet.kind), (direction, Kind::Acl)); + assert_eq!(packet.bytes.len(), CAPTURED_BYTES); + assert_eq!(packet.cut, long.len() - CAPTURED_BYTES); + // The HCI and L2CAP headers, then the payload hidden. + assert_eq!(packet.bytes[..8], long[..8]); + assert!(packet.hidden[8..].iter().all(|&h| h)); + } assert_eq!( - hci.take_captured(), - [ - Captured { - direction: Direction::FromGuest, - kind: Kind::Acl, - bytes: shown.clone(), - cut, - }, - Captured { - direction: Direction::ToGuest, - kind: Kind::Acl, - bytes: shown, - cut, - }, - Captured::new( - Direction::ToGuest, - Kind::Event, - &[0x0e, 4, 1, 0x03, 0x0c, 0] - ), - ] + captured[2], + Captured::new( + Direction::ToGuest, + Kind::Event, + &[0x0e, 4, 1, 0x03, 0x0c, 0] + ) ); } diff --git a/crates/stela-soc/src/usb/hci/capture.rs b/crates/stela-soc/src/usb/hci/capture.rs index df40b972cc..7ab90c105a 100644 --- a/crates/stela-soc/src/usb/hci/capture.rs +++ b/crates/stela-soc/src/usb/hci/capture.rs @@ -10,9 +10,20 @@ //! B 2), so the kind names it. The capture holds at most //! [`CAPTURED_PACKETS`] packets per configuration, and none unless the owner //! asks for it. +//! +//! A packet is masked as it is captured ([`Captured::new`], `mask`), so no +//! raw byte leaves the function: its headers and the parameters that say +//! nothing of anyone show; the middle bytes of addresses, names, opaque +//! payloads, keys and secrets are held as 0 and printed `xx`, keeping their +//! length, and [`Captured::parse`] reads `xx` back as a hidden 0, so a +//! masked log is itself a fixture. Even so the log names nearby devices' +//! classes, signal strengths and address ends: keep it private until it +//! has been checked. use alloc::vec::Vec; use core::fmt; +mod mask; + /// Packets captured after each configuration. pub const CAPTURED_PACKETS: u16 = 1024; /// Bytes a captured packet shows: every command and event whole (at most @@ -70,19 +81,30 @@ impl Kind { pub struct Captured { pub direction: Direction, pub kind: Kind, - /// Its first [`CAPTURED_BYTES`]. + /// Its first [`CAPTURED_BYTES`], each hidden one as 0. pub bytes: Vec, + /// Which of those are hidden. + pub hidden: Vec, /// How many bytes followed those. pub cut: usize, } impl Captured { + /// `packet`, masked: what is hidden of it is never held. pub fn new(direction: Direction, kind: Kind, packet: &[u8]) -> Self { let shown = packet.len().min(CAPTURED_BYTES); + let mut hidden = mask::hidden(kind, packet); + hidden.truncate(shown); + let bytes = packet[..shown] + .iter() + .zip(&hidden) + .map(|(&byte, &hidden)| if hidden { 0 } else { byte }) + .collect(); Self { direction, kind, - bytes: packet[..shown].to_vec(), + bytes, + hidden, cut: packet.len() - shown, } } @@ -95,7 +117,7 @@ impl Captured { let direction = *Direction::ALL.iter().find(|d| d.token() == direction)?; let kind = words.next()?; let kind = *Kind::ALL.iter().find(|k| k.token() == kind)?; - let mut bytes = Vec::new(); + let (mut bytes, mut hidden) = (Vec::new(), Vec::new()); let mut cut = 0; for word in words { if cut != 0 { @@ -108,12 +130,19 @@ impl Captured { if word.len() != 2 { return None; } - bytes.push(u8::from_str_radix(word, 16).ok()?); + let masked = word == "xx"; + bytes.push(if masked { + 0 + } else { + u8::from_str_radix(word, 16).ok()? + }); + hidden.push(masked); } (!bytes.is_empty() && (cut == 0 || bytes.len() == CAPTURED_BYTES)).then_some(Self { direction, kind, bytes, + hidden, cut, }) } @@ -122,8 +151,12 @@ impl Captured { impl fmt::Display for Captured { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} {}", self.direction.token(), self.kind.token())?; - for byte in &self.bytes { - write!(f, " {byte:02x}")?; + for (byte, &hidden) in self.bytes.iter().zip(&self.hidden) { + if hidden { + f.write_str(" xx")?; + } else { + write!(f, " {byte:02x}")?; + } } if self.cut != 0 { write!(f, " +{}", self.cut)?; @@ -226,7 +259,12 @@ mod tests { let cut = Captured::new(Direction::FromChip, Kind::Acl, &long); assert_eq!((cut.bytes.len(), cut.cut), (CAPTURED_BYTES, 725)); let line = cut.to_string(); - assert!(line.starts_with("chip< acl 00 01 02 ") && line.ends_with(" 2b +725")); + // The HCI and L2CAP headers show, the payload is hidden. + assert!( + line.starts_with("chip< acl 00 01 02 03 04 05 06 07 xx "), + "{line}" + ); + assert!(line.ends_with(" xx +725"), "{line}"); assert_eq!(Captured::parse(&line), Some(cut)); // Extra spaces between words read the same. assert_eq!( @@ -239,6 +277,195 @@ mod tests { ); } + /// A neighbour's address 32:31:30:b8:a7:10, in HCI order. + const NEIGHBOUR: [u8; 6] = [0x10, 0xa7, 0xb8, 0x30, 0x31, 0x32]; + const NAME: &[u8] = b"Garvits Mac"; + const KEY: [u8; 16] = [0x5a; 16]; + + /// Whether `secret` is anywhere in what the capture holds of a packet. + fn holds(captured: &Captured, secret: &[u8]) -> bool { + captured.bytes.windows(secret.len()).any(|w| w == secret) + } + + /// An extended inquiry result, a Write Local Name and a Link Key Request + /// Reply as the capture holds them: no address's middle bytes, no name, + /// no key and no manufacturer data leave the function, while the headers + /// stay, so lines still diff and replay. + #[test] + fn the_capture_never_holds_an_addresss_middle_a_name_or_a_key() { + let mut eir = vec![NAME.len() as u8 + 1, 0x09]; + eir.extend_from_slice(NAME); + eir.extend_from_slice(&[5, 0xff, 0x4c, 0x00, 0x99, 0x98, 3, 0x03, 0x0b, 0x11]); + eir.resize(240, 0); + let mut result = vec![0x2f, 255, 1]; + result.extend_from_slice(&NEIGHBOUR); + result.extend_from_slice(&[1, 0, 0x04, 0x04, 0x24, 0x34, 0x12, 0xd0]); + result.extend_from_slice(&eir); + let mut local_name = vec![0x13, 0x0c, 248]; + local_name.extend_from_slice(NAME); + local_name.resize(3 + 248, 0); + let mut reply = vec![0x0b, 0x04, 22]; + reply.extend_from_slice(&NEIGHBOUR); + reply.extend_from_slice(&KEY); + for (direction, kind, packet) in [ + (Direction::FromChip, Kind::Event, &result), + (Direction::FromGuest, Kind::Command, &local_name), + (Direction::ToChip, Kind::Command, &reply), + ] { + let captured = Captured::new(direction, kind, packet); + for secret in [&NEIGHBOUR[1..3], NAME, &KEY[..], &[0x99, 0x98][..]] { + assert!(!holds(&captured, secret), "{captured}"); + } + let line = captured.to_string(); + assert!(!line.contains("a7 b8"), "{line}"); + assert_eq!(captured.bytes[..3], packet[..3], "the header"); + assert!(!captured.hidden[..3].contains(&true)); + // A masked line reads back as the packet it shows, hidden + // bytes as 00, so a masked log is itself a fixture. + assert_eq!(Captured::parse(&line), Some(captured)); + } + let line = Captured::new(Direction::FromChip, Kind::Event, &result).to_string(); + let name = " xx".repeat(NAME.len()); + assert!( + line.starts_with(&alloc::format!( + "chip< evt 2f ff 01 10 xx xx 30 31 32 01 00 04 04 24 34 12 d0 0c 09{name} \ + 05 ff xx xx xx xx 03 03 0b 11 00 xx" + )), + "{line}" + ); + let line = Captured::new(Direction::ToChip, Kind::Command, &reply).to_string(); + assert!(line.starts_with("chip> cmd 0b 04 16 xx xx xx"), "{line}"); + } + + /// Keys and secrets are never held, wherever they travel: the commands + /// that carry them, their returns, the events and the ACL channels. + #[test] + fn keys_and_secrets_are_never_held() { + const SECRET: u8 = 0xa5; + let none_held = |captured: Captured, from: usize| { + assert!(captured.bytes[from..].iter().all(|&b| b == 0), "{captured}"); + assert!(captured.hidden[from..].iter().all(|&h| h), "{captured}"); + assert!(!captured.hidden[..from].contains(&true), "{captured}"); + }; + let with = |head: &[u8], length: usize| { + let mut packet = head.to_vec(); + packet.resize(head.len() + length, SECRET); + packet + }; + // Link key, PIN, passkey and OOB replies, stored link keys, LE + // encryption, LTK replies and resolving list IRKs. + for opcode in [ + 0x040b, 0x040d, 0x042e, 0x0430, 0x0445, 0x0c11, 0x2017, 0x2019, 0x201a, 0x2027, + ] { + let [low, high] = u16::to_le_bytes(opcode); + let command = with(&[low, high, 32], 32); + none_held( + Captured::new(Direction::FromGuest, Kind::Command, &command), + 3, + ); + } + // LE Encrypt's result, the local OOB data, and every vendor + // command's returns past the status. + for opcode in [0x2017, 0x0c57, 0x0c7d, 0xfc79] { + let [low, high] = u16::to_le_bytes(opcode); + let complete = with(&[0x0e, 36, 1, low, high, 0], 32); + none_held( + Captured::new(Direction::FromChip, Kind::Event, &complete), + 6, + ); + } + // Return Link Keys, Link Key Notification, a vendor event, and LE + // Generate DHKey Complete past its status. + for (head, from) in [ + (&[0x15, 23][..], 2), + (&[0x18, 23][..], 2), + (&[0xff, 23][..], 2), + (&[0x3e, 34, 0x09, 0x00][..], 4), + ] { + let event = with(head, usize::from(head[1]) + 2 - head.len()); + none_held(Captured::new(Direction::ToGuest, Kind::Event, &event), from); + } + // SMP (channels 6 and 7) and every other channel's payload: the HCI + // and L2CAP headers stay; a continuation has no L2CAP header. + for cid in [6u8, 7, 0x40] { + let acl = with(&[0x01, 0x20, 24, 0, 20, 0, cid, 0], 20); + none_held(Captured::new(Direction::FromChip, Kind::Acl, &acl), 8); + } + let continuation = with(&[0x01, 0x10, 20, 0], 20); + none_held( + Captured::new(Direction::FromGuest, Kind::Acl, &continuation), + 4, + ); + // Vendor parameters, the Mac's name and LE advertising data. + for (head, from) in [ + (&[0x4c, 0xfc, 9][..], 3), + (&[0x13, 0x0c, 248][..], 3), + (&[0x08, 0x20, 32, 31][..], 4), + (&[0x09, 0x20, 32, 31][..], 4), + ] { + let command = with(head, usize::from(head[2]) + 3 - head.len()); + none_held( + Captured::new(Direction::FromGuest, Kind::Command, &command), + from, + ); + } + // Read Local Name's return and a remote name past the address. + let read_name = with(&[0x0e, 252, 1, 0x14, 0x0c, 0], 248); + none_held( + Captured::new(Direction::ToGuest, Kind::Event, &read_name), + 6, + ); + let mut named = vec![0x07, 255, 0]; + named.extend_from_slice(&NEIGHBOUR); + let named = with(&named, 248); + let captured = Captured::new(Direction::ToGuest, Kind::Event, &named); + assert_eq!(captured.bytes[3..9], [0x10, 0, 0, 0x30, 0x31, 0x32]); + none_held( + Captured { + bytes: captured.bytes[9..].to_vec(), + hidden: captured.hidden[9..].to_vec(), + ..captured + }, + 0, + ); + } + + /// Commands whose parameters say nothing of anyone stay whole, and the + /// addresses in them keep their vendor half and last byte. + #[test] + fn plain_commands_stay_whole_and_addresses_keep_their_ends() { + for plain in [ + &[0x01, 0x04, 5, 0x33, 0x8b, 0x9e, 8, 0][..], + &[ + 0x01, 0x0c, 8, 0xff, 0xff, 0xfb, 0xff, 0x07, 0xf8, 0xbf, 0x3d, + ][..], + &[0x45, 0x0c, 1, 2][..], + &[0x0e, 12, 1, 0x01, 0x10, 0, 6, 0, 0, 6, 15, 0, 0x0e, 0x41][..], + ] { + let kind = if plain[0] == 0x0e { + Kind::Event + } else { + Kind::Command + }; + let captured = Captured::new(Direction::FromGuest, kind, plain); + assert_eq!(captured.bytes, plain); + assert!(!captured.hidden.contains(&true), "{captured}"); + } + let mut request = vec![0x19, 0x04, 10]; + request.extend_from_slice(&NEIGHBOUR); + request.extend_from_slice(&[1, 0, 0x34, 0x12]); + assert_eq!( + Captured::new(Direction::ToChip, Kind::Command, &request).to_string(), + "chip> cmd 19 04 0a 10 xx xx 30 31 32 01 00 34 12" + ); + let mut address = vec![0x0e, 10, 1, 0x09, 0x10, 0]; + address.extend_from_slice(&NEIGHBOUR); + assert_eq!( + Captured::new(Direction::FromChip, Kind::Event, &address).to_string(), + "chip< evt 0e 0a 01 09 10 00 10 xx xx 30 31 32" + ); + } + #[test] fn other_text_is_no_captured_packet() { for bad in [ diff --git a/crates/stela-soc/src/usb/hci/capture/mask.rs b/crates/stela-soc/src/usb/hci/capture/mask.rs new file mode 100644 index 0000000000..f084ddf9a6 --- /dev/null +++ b/crates/stela-soc/src/usb/hci/capture/mask.rs @@ -0,0 +1,269 @@ +//! What the capture hides of a packet before it holds it: everything but +//! what a rule below shows. Headers always show (opcodes, lengths, event +//! codes, LE subevents, statuses, command credits, ACL handles and L2CAP +//! lengths and channels), so lines still diff and replay; so do the +//! parameters of the commands and returns that say nothing of anyone. An +//! address shows its vendor half and its last byte, as +//! `stela_contracts::masked::Mac` prints one (in HCI order, bytes 0 and 3 to +//! 5); its two middle bytes are hidden. Hidden whatever their place are: +//! +//! - names: the Mac's (Write Local Name, Read Local Name's return), a remote +//! device's, and the name types of extended inquiry and advertising data; +//! - opaque payloads: manufacturer and service data and URIs in that data, +//! LE advertising and scan response data, every vendor command's +//! parameters and every vendor return past its status, vendor events, +//! and ACL data past its HCI and L2CAP headers (so SMP's keys on channels +//! 6 and 7, and a keyboard's reports, never show); +//! - keys and secrets: Link Key and PIN Code Request Replies, User Passkey +//! Request Replies, Remote OOB (Extended) Data Request Replies, Write +//! Stored Link Key, LE Encrypt and its result, LE Enable Encryption, LE +//! Long Term Key Request Reply, LE Add Device To Resolving List, the local +//! OOB data reads' returns, Return Link Keys, Link Key Notification and LE +//! Generate DHKey Complete; +//! - anything of a command, return or event no rule names. +//! +//! Evidence: Bluetooth Core v5.4 Vol 4 Part E 5.4 (packet formats), 7.1-7.8 +//! (parameters) and 7.7 (events); Vol 3 Part C 11 and the Assigned Numbers' +//! AD types; Vol 3 Part A 3 (L2CAP basic frames). +use alloc::{vec, vec::Vec}; +use core::ops::Range; + +/// Commands whose parameters say nothing of anyone. +const PLAIN_COMMANDS: &[u16] = &[ + 0x0401, 0x0402, 0x0406, 0x080f, 0x0c01, 0x0c03, 0x0c16, 0x0c18, 0x0c1a, 0x0c1c, 0x0c1e, 0x0c20, + 0x0c24, 0x0c26, 0x0c31, 0x0c33, 0x0c35, 0x0c43, 0x0c45, 0x0c47, 0x0c56, 0x0c5b, 0x0c63, 0x0c6d, + 0x1004, 0x2001, 0x200a, 0x200b, 0x200c, 0x200e, 0x2010, +]; + +/// Commands whose return parameters, past the status, say nothing of anyone. +const PLAIN_RETURNS: &[u16] = &[ + 0x080e, 0x0c15, 0x0c17, 0x0c19, 0x0c1b, 0x0c1d, 0x0c1f, 0x0c23, 0x0c25, 0x0c42, 0x0c44, 0x0c46, + 0x0c55, 0x0c58, 0x0c5a, 0x0c6c, 0x1001, 0x1002, 0x1003, 0x1004, 0x1005, 0x2002, 0x2003, 0x2007, + 0x200f, 0x201c, +]; + +/// Events whose parameters say nothing of anyone: Inquiry Complete, +/// Disconnection Complete, Encryption Change, Read Remote Supported Features +/// and Version Complete, Hardware Error, Number Of Completed Packets, Data +/// Buffer Overflow, Max Slots Change. +const PLAIN_EVENTS: &[u8] = &[0x01, 0x05, 0x08, 0x0b, 0x0c, 0x10, 0x13, 0x1a, 0x1b]; + +/// AD types whose data say nothing of anyone: flags, service UUID lists, +/// TX power, class of device, OOB flags, connection interval range, +/// solicitation UUIDs, appearance, LE role. +const PLAIN_AD: &[u8] = &[ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x0a, 0x0d, 0x11, 0x12, 0x14, 0x15, 0x19, 0x1c, 0x1f, +]; + +const VENDOR_GROUP: u16 = 0x3f; + +/// Which bytes of a whole `packet` are hidden. +struct Mask<'a> { + packet: &'a [u8], + hidden: Vec, +} + +impl Mask<'_> { + fn show(&mut self, range: Range) { + let end = range.end.min(self.hidden.len()); + if range.start < end { + self.hidden[range.start..end].fill(false); + } + } + + fn rest(&mut self, from: usize) { + self.show(from..self.packet.len()); + } + + /// An address at `at`: its last byte and vendor half. + fn address(&mut self, at: usize) { + self.show(at..at + 1); + self.show(at + 3..at + 6); + } + + /// Extended inquiry or advertising data in `range`: each structure's + /// length and type, and the data of the plain types. + fn data(&mut self, range: Range) { + let end = range.end.min(self.packet.len()); + let mut at = range.start; + while at < end { + let length = usize::from(self.packet[at]); + self.show(at..at + 1); + if length == 0 { + return; + } + if let Some(&kind) = self.packet.get(at + 1) { + self.show(at + 1..at + 2); + if PLAIN_AD.contains(&kind) { + self.show(at + 2..(at + 1 + length).min(end)); + } + } + at += 1 + length; + } + } + + fn command(&mut self) { + self.show(0..3); + let Some(&[low, high]) = self.packet.first_chunk() else { + return; + }; + match u16::from_le_bytes([low, high]) { + // An address first, the rest plain: Create Connection, its + // Cancel, Remote Name Request and its Cancel, LE Set Random + // Address, the module's Write BD_ADDR. + 0x0405 | 0x0408 | 0x0419 | 0x041a | 0x2005 | 0xfc01 => { + self.address(3); + self.rest(9); + } + // LE Add or Remove Device From Filter Accept List. + 0x2011 | 0x2012 => { + self.show(3..4); + self.address(4); + } + // LE Set Advertising Parameters: the peer at 7. + 0x2006 => { + self.show(3..10); + self.address(10); + self.rest(16); + } + // LE Create Connection: the peer at 6. + 0x200d => { + self.show(3..9); + self.address(9); + self.rest(15); + } + // Write Extended Inquiry Response. + 0x0c52 => { + self.show(3..4); + self.data(4..self.packet.len()); + } + // LE Set Advertising Data, LE Set Scan Response Data: the length + // alone. + 0x2008 | 0x2009 => self.show(3..4), + opcode if PLAIN_COMMANDS.contains(&opcode) => self.rest(3), + _ => {} + } + } + + fn event(&mut self) { + self.show(0..2); + let Some(&code) = self.packet.first() else { + return; + }; + match code { + 0x0e => { + // Credits, opcode and status. + self.show(2..6); + let Some(&[low, high]) = self.packet.get(3..5).and_then(|o| o.first_chunk()) else { + return; + }; + let opcode = u16::from_le_bytes([low, high]); + match opcode { + 0x0408 | 0x041a | 0x1009 => self.address(6), + 0x0c51 => { + self.show(6..7); + self.data(7..self.packet.len()); + } + _ if opcode >> 10 == VENDOR_GROUP => {} + _ if PLAIN_RETURNS.contains(&opcode) => self.rest(6), + _ => {} + } + } + 0x0f => self.show(2..6), + // Inquiry Result (14 bytes a device), with RSSI (14 as well). + 0x02 | 0x22 => { + self.show(2..3); + let count = usize::from(self.packet.get(2).copied().unwrap_or(0)); + for device in 0..count { + let at = 3 + 14 * device; + self.address(at); + self.show(at + 6..at + 14); + } + } + // Extended Inquiry Result: one device, then its EIR. + 0x2f => { + self.show(2..3); + self.address(3); + self.show(9..17); + self.data(17..self.packet.len()); + } + // Remote Name Request Complete: the name stays hidden. + 0x07 => { + self.show(2..3); + self.address(3); + } + // Connection Complete, Connection Request, Remote Host Supported + // Features Notification. + 0x03 => { + self.show(2..5); + self.address(5); + self.rest(11); + } + 0x04 | 0x3d => { + self.address(2); + self.rest(8); + } + 0x3e => self.le_meta(), + code if PLAIN_EVENTS.contains(&code) => self.rest(2), + _ => {} + } + } + + fn le_meta(&mut self) { + self.show(2..3); + match self.packet.get(2) { + // LE Connection Complete: status, handle, role, peer type, then + // the peer, then plain timing. + Some(0x01) => { + self.show(3..8); + self.address(8); + self.rest(14); + } + // LE Advertising Report: per report the event and address + // types, the address, the data's length, hidden data, the RSSI. + Some(0x02) => { + self.show(3..4); + let count = usize::from(self.packet.get(3).copied().unwrap_or(0)); + let mut at = 4; + for _ in 0..count { + self.show(at..at + 2); + self.address(at + 2); + let length = usize::from(self.packet.get(at + 8).copied().unwrap_or(0)); + self.show(at + 8..at + 9); + at += 9 + length; + self.show(at..at + 1); + at += 1; + } + } + // Others show their status alone, as LE Generate DHKey Complete. + _ => self.show(3..4), + } + } + + fn acl(&mut self) { + self.show(0..4); + // A start fragment (packet boundary 00 or 10) begins with the L2CAP + // header: length and channel. + if self + .packet + .get(1) + .is_some_and(|&high| high >> 4 & 0b01 == 0) + { + self.show(4..8); + } + } +} + +/// Which bytes of `packet`, of `kind`, the capture hides. +pub(super) fn hidden(kind: super::Kind, packet: &[u8]) -> Vec { + let mut mask = Mask { + packet, + hidden: vec![true; packet.len()], + }; + match kind { + super::Kind::Command => mask.command(), + super::Kind::Event => mask.event(), + super::Kind::Acl => mask.acl(), + } + mask.hidden +} From 3871b06504b33a91000abb516c86ca795c09d1a4 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:03:27 +0000 Subject: [PATCH 08/18] fix(bluetooth): give the guest the model, and say why, when --bluetooth-lend meets --idle-skip, where the guest's clock leaped over the bridge's 1 s wait for the controller and every forwarded command fell back at once --- crates/stela-boot-core/src/guest_bluetooth.rs | 25 +++++++++++++++++++ crates/stela-boot/src/engine/bluetooth.rs | 15 ++++++++--- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/crates/stela-boot-core/src/guest_bluetooth.rs b/crates/stela-boot-core/src/guest_bluetooth.rs index dabefe4a7a..7edbca3f82 100644 --- a/crates/stela-boot-core/src/guest_bluetooth.rs +++ b/crates/stela-boot-core/src/guest_bluetooth.rs @@ -21,6 +21,18 @@ pub const TRACE_LINE: &str = "BLUETOOTH TRACE the guest's Bluetooth packets are the log still names nearby devices' classes and signal strengths, so keep it private \ until it has been checked\n"; +/// Why a boot that asks to lend the host's controller (`--bluetooth-lend`) +/// gives the guest the model instead, as its log line; `None` when nothing +/// stops it. Under `--idle-skip` the guest's clock leaps over waits to the +/// next deadline, and the bridge's wait for the controller's answer is one +/// in guest time, so every forwarded command would fall back at once. +pub fn lend_refusal(idle_skip: bool) -> Option<&'static str> { + idle_skip.then_some( + "BLUETOOTH LEND not lent: --idle-skip leaps the guest's clock over the bridge's wait \ + for the controller's answers, so the model answers alone\n", + ) +} + /// The line for a boot that lends the host's controller at `location` to /// the guest behind Apple's module. pub fn lend_line(location: &str) -> String { @@ -60,6 +72,19 @@ mod tests { } } + /// Under `--idle-skip` the guest's clock leaps to the next deadline, the + /// bridge's 1 s wait for the controller among them, so a lent + /// controller would fall back at once: it is not lent, and the log says + /// why. + #[test] + fn idle_skip_keeps_the_controller_from_being_lent_and_says_why() { + assert_eq!(lend_refusal(false), None); + let line = lend_refusal(true).expect("refused"); + assert!(line.starts_with("BLUETOOTH LEND not lent: --idle-skip ")); + assert!(line.contains("model")); + assert!(line.ends_with('\n') && line.matches('\n').count() == 1); + } + /// `--bluetooth-trace` says once what its lines hide and that the log /// still needs checking before it is posted. #[test] diff --git a/crates/stela-boot/src/engine/bluetooth.rs b/crates/stela-boot/src/engine/bluetooth.rs index 146bd58330..54beba6815 100644 --- a/crates/stela-boot/src/engine/bluetooth.rs +++ b/crates/stela-boot/src/engine/bluetooth.rs @@ -247,11 +247,20 @@ impl HostBluetooth { /// function would carry the host's vendor commands and replies, which /// BlueTool's chip boot and bluetoothd's bring-up do not take. With /// `--bluetooth-lend` it is lent behind the module, which answers those - /// itself and falls back to the model on any failure. One not kept is - /// released in the loader's root by its drop. + /// itself and falls back to the model on any failure, unless the boot + /// leaps the guest's clock (`--idle-skip`). One not kept is released in + /// the loader's root by its drop. pub fn guest(controller: Option, options: &System, root: u64) -> Option { + let refused = options + .bluetooth_lend + .then(|| stela_boot_core::guest_bluetooth::lend_refusal(options.idle_skip)) + .flatten(); + if let Some(line) = refused { + output::arguments(format_args!("{line}")); + } + let lend = options.input && options.bluetooth_lend && refused.is_none(); let mut guest = match controller { - Some(mut lent) if options.input && options.bluetooth_lend => { + Some(mut lent) if lend => { let line = stela_boot_core::guest_bluetooth::lend_line(&lent.location); output::arguments(format_args!("{line}")); lent.lent = true; From b5b16305054512bd45df4bd2bdd4237508edc47d Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:14:12 +0000 Subject: [PATCH 09/18] fix(bluetooth): end at the fallback each inquiry and remote name request the guest saw the lent controller start and not end, with Inquiry Complete and Page Timeout, and stop the shadow's own, where the shadow's end, discarded while the bridge forwarded, could pass first and a fallback then dropped the controller's late one, so bluetoothd never got Inquiry Complete --- crates/stela-soc/src/usb/hci/bridge.rs | 60 ++++++++++++++++++-- crates/stela-soc/src/usb/hci/bridge/tests.rs | 53 +++++++++++++++++ 2 files changed, 109 insertions(+), 4 deletions(-) diff --git a/crates/stela-soc/src/usb/hci/bridge.rs b/crates/stela-soc/src/usb/hci/bridge.rs index f322e5687b..fbb45d3900 100644 --- a/crates/stela-soc/src/usb/hci/bridge.rs +++ b/crates/stela-soc/src/usb/hci/bridge.rs @@ -144,6 +144,8 @@ pub struct Bridge { written: Option<[u8; 6]>, /// Whether the controller reported another address than that. address_differs: bool, + /// The controller's procedures the guest saw start and not yet end. + running: Vec, counters: Counters, } @@ -159,6 +161,16 @@ const READ_BD_ADDR: u16 = 0x1009; const WRITE_BD_ADDR: u16 = 0xfc01; const INQUIRY_COMPLETE: u8 = 0x01; const REMOTE_NAME_REQUEST_COMPLETE: u8 = 0x07; +/// Page Timeout (Vol 1 Part F 1.3). +const PAGE_TIMEOUT: u8 = 0x04; + +/// A procedure of the controller the guest saw start and not yet end. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Running { + Inquiry, + /// A remote name request to this address. + Name([u8; 6]), +} /// A vendor's own event (7.7.65 leaves code 0xFF to vendors). const VENDOR_EVENT: u8 = 0xff; @@ -232,6 +244,7 @@ impl Bridge { resync: false, written: None, address_differs: false, + running: Vec::new(), counters: Counters::default(), } } @@ -261,6 +274,7 @@ impl Bridge { pub fn resync(&mut self) { self.pending = None; self.backlog.clear(); + self.running.clear(); self.resync = true; } @@ -351,7 +365,10 @@ impl Bridge { } /// Falls back for good; the guest gets the shadow's answer to the - /// command in flight, and the commands that waited are the shadow's. + /// command in flight, then the end of each procedure the controller was + /// running (an inquiry completes, a name request times out), which the + /// shadow then no longer runs, and the commands that waited are the + /// shadow's. fn fall(&mut self, cause: Cause, now: u64) -> Vec { let pending = self.pending.take(); self.fallen.get_or_insert(Fallback { @@ -359,6 +376,22 @@ impl Bridge { cause, }); let mut steps = pending.map(|p| guest(p.shadow)).unwrap_or_default(); + for running in core::mem::take(&mut self.running) { + let end = match running { + Running::Inquiry => { + self.shadow_only(INQUIRY_CANCEL, &[], now); + vec![INQUIRY_COMPLETE, 1, 0] + } + Running::Name(peer) => { + self.shadow_only(REMOTE_NAME_REQUEST_CANCEL, &peer, now); + let mut end = vec![REMOTE_NAME_REQUEST_COMPLETE, 255, PAGE_TIMEOUT]; + end.extend_from_slice(&peer); + end.resize(2 + 255, 0); + end + } + }; + steps.push(Step::Guest(end)); + } steps.extend(self.next(now)); steps } @@ -398,9 +431,13 @@ impl Bridge { /// fallback it gives the guest no second end of it. fn follow(&mut self, event: &[u8], now: u64) { match *event { - [INQUIRY_COMPLETE, ..] => self.shadow_only(INQUIRY_CANCEL, &[], now), + [INQUIRY_COMPLETE, ..] => { + self.running.retain(|r| *r != Running::Inquiry); + self.shadow_only(INQUIRY_CANCEL, &[], now); + } [REMOTE_NAME_REQUEST_COMPLETE, _, _, ref peer @ ..] if peer.len() >= 6 => { - let peer = peer[..6].to_vec(); + let peer: [u8; 6] = peer[..6].try_into().expect("six bytes"); + self.running.retain(|r| *r != Running::Name(peer)); self.shadow_only(REMOTE_NAME_REQUEST_CANCEL, &peer, now); } _ => {} @@ -416,10 +453,25 @@ impl Bridge { } /// The shadow follows what the controller's answer to `pending` says: - /// the address it has, and a procedure it refused. + /// the address it has, and a procedure it refused; and the bridge, the + /// procedures it runs. fn follow_answer(&mut self, pending: &Pending, chip: &Completion<'_>, now: u64) { let shadow = pending.shadow.first().and_then(|e| Completion::of(e)); let shadow_succeeded = shadow.is_some_and(|s| s.status == 0); + let peer: Option<[u8; 6]> = pending.parameters.get(..6).and_then(|p| p.try_into().ok()); + match (pending.opcode, peer) { + (INQUIRY, _) if chip.status == 0 && !self.running.contains(&Running::Inquiry) => { + self.running.push(Running::Inquiry); + } + (REMOTE_NAME_REQUEST, Some(peer)) if chip.status == 0 => { + self.running.push(Running::Name(peer)); + } + (INQUIRY_CANCEL, _) if chip.status == 0 => { + self.running.retain(|r| *r != Running::Inquiry); + } + (RESET, _) if chip.status == 0 => self.running.clear(), + _ => {} + } match pending.opcode { RESET if chip.status == 0 => self.resync = false, READ_BD_ADDR if chip.status == 0 && chip.returns.len() == 6 => { diff --git a/crates/stela-soc/src/usb/hci/bridge/tests.rs b/crates/stela-soc/src/usb/hci/bridge/tests.rs index 2b9247c1a2..ab04862274 100644 --- a/crates/stela-soc/src/usb/hci/bridge/tests.rs +++ b/crates/stela-soc/src/usb/hci/bridge/tests.rs @@ -557,3 +557,56 @@ fn acl_from_the_guest_is_the_shadows_and_the_controllers_passes() { events(bridge.chip_failed(0)); assert!(!bridge.chip_acl()); } + +/// A fallback ends what the controller was running: the guest saw the +/// procedure start, and the shadow's own end may already have passed while +/// the bridge forwarded. Each ends exactly once. +#[test] +fn a_fallback_ends_the_procedures_the_controller_was_running() { + // An inquiry the controller runs past the shadow's end. + let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(&packet(0x0401, &[0x33, 0x8b, 0x9e, 1, 0]), 0)); + events(bridge.chip_event(&status(0x0401, 1, 0), 10)); + let shadow_end = bridge.shadow.deadline().expect("the shadow's inquiry"); + assert!(events(bridge.advance(shadow_end)).is_empty(), "discarded"); + let ended = events(bridge.chip_failed(shadow_end + 1)); + assert_eq!(ended, [vec![0x01, 1, 0]]); + assert!(events(bridge.advance(u64::MAX)).is_empty(), "once"); + // A name request, ended with Page Timeout, and an inquiry the shadow + // still runs, ended once, now. + let mut bridge = Bridge::new(ADDRESS); + let mut name = CHIP_ADDRESS.to_vec(); + name.extend_from_slice(&[1, 0, 0, 0]); + chip(bridge.command(&packet(0x0419, &name), 0)); + events(bridge.chip_event(&status(0x0419, 1, 0), 0)); + chip(bridge.command(&packet(0x0401, &[0x33, 0x8b, 0x9e, 8, 0]), 0)); + events(bridge.chip_event(&status(0x0401, 1, 0), 0)); + let mut timeout = vec![0x07, 255, 0x04]; + timeout.extend_from_slice(&CHIP_ADDRESS); + timeout.resize(257, 0); + let ended = events(bridge.chip_failed(0)); + assert_eq!(ended, [timeout, vec![0x01, 1, 0]]); + assert!(events(bridge.advance(u64::MAX)).is_empty(), "once"); + // Procedures the controller ended, cancelled or refused end nothing. + let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(&packet(0x0401, &[0x33, 0x8b, 0x9e, 8, 0]), 0)); + events(bridge.chip_event(&status(0x0401, 1, 0), 0)); + chip(bridge.command(&packet(0x0402, &[]), 0)); + events(bridge.chip_event(&complete(0x0402, 1, 0, &[]), 0)); + chip(bridge.command(&packet(0x0419, &name), 0)); + events(bridge.chip_event(&status(0x0419, 1, 0x0c), 0)); + assert!(events(bridge.chip_failed(0)).is_empty()); + assert!(events(bridge.advance(u64::MAX)).is_empty()); + let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(&packet(0x0401, &[0x33, 0x8b, 0x9e, 8, 0]), 0)); + events(bridge.chip_event(&status(0x0401, 1, 0), 0)); + events(bridge.chip_event(&[0x01, 1, 0], 0)); + chip(bridge.command(&packet(0x0419, &name), 0)); + events(bridge.chip_event(&status(0x0419, 1, 0), 0)); + let mut named = vec![0x07, 255, 0]; + named.extend_from_slice(&CHIP_ADDRESS); + named.resize(257, b'x'); + events(bridge.chip_event(&named, 0)); + assert!(events(bridge.chip_failed(0)).is_empty()); + assert!(events(bridge.advance(u64::MAX)).is_empty()); +} From 874e605aedc58ab933680b541dd63799168b3e75 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:23:55 +0000 Subject: [PATCH 10/18] fix(bluetooth): fall back to the model at bluetoothd's second HCI Reset after the start-up's first answered one, which the model answers, log each restart and the cause, and count them, where bluetoothd rejecting a well-formed merged answer restarted it with reason 108 forever while Setup's Language Chooser waited on it --- crates/stela-boot/src/engine/bluetooth.rs | 16 +++++++- crates/stela-soc/src/usb/hci/bridge.rs | 40 +++++++++++++++++-- crates/stela-soc/src/usb/hci/bridge/replay.rs | 34 ++++++++++++++++ crates/stela-soc/src/usb/hci/bridge/tests.rs | 39 ++++++++++++++++++ 4 files changed, 124 insertions(+), 5 deletions(-) diff --git a/crates/stela-boot/src/engine/bluetooth.rs b/crates/stela-boot/src/engine/bluetooth.rs index 54beba6815..caf0bda8ca 100644 --- a/crates/stela-boot/src/engine/bluetooth.rs +++ b/crates/stela-boot/src/engine/bluetooth.rs @@ -157,9 +157,11 @@ pub struct HostBluetooth { /// What its bridge reported last: the fallback, its counters, and /// whether the guest wrote another address than the controller's. lend: Option<(Option, UsbBluetoothLendCounters, bool)>, - /// Whether the fallback and the address were reported. + /// Whether the fallback and the address were reported, and the + /// restarts reported. fell_back: bool, address_differs: bool, + restarts: u64, } /// The controller is dropped in the loader's root. An install runs without @@ -215,6 +217,7 @@ impl HostBluetooth { lend: None, fell_back: false, address_differs: false, + restarts: 0, }) } @@ -238,6 +241,7 @@ impl HostBluetooth { lend: None, fell_back: false, address_differs: false, + restarts: 0, } } @@ -340,6 +344,16 @@ impl HostBluetooth { output::arguments(format_args!("{LOG_PREFIX}{packet}\n")); } let (fallback, lend, differs) = self.lend.unwrap_or_default(); + if lend.restarts > self.restarts { + self.restarts = lend.restarts; + output::arguments(format_args!( + "BLUETOOTH LEND bluetoothd reset the guest's controller after its start-up \ + ({} of {}); at {} the model takes over\n", + lend.restarts, + stela_soc::usb::hci::bridge::RESTARTS, + stela_soc::usb::hci::bridge::RESTARTS, + )); + } if let Some(fallback) = fallback.filter(|_| !self.fell_back) { self.fell_back = true; output::arguments(format_args!("BLUETOOTH LEND FELL BACK {fallback}\n")); diff --git a/crates/stela-soc/src/usb/hci/bridge.rs b/crates/stela-soc/src/usb/hci/bridge.rs index fbb45d3900..bf18c8ae9d 100644 --- a/crates/stela-soc/src/usb/hci/bridge.rs +++ b/crates/stela-soc/src/usb/hci/bridge.rs @@ -73,8 +73,16 @@ pub enum Cause { Malformed, /// The host's controller failed. HostFailed, + /// bluetoothd reset the controller [`RESTARTS`] times after its + /// start-up: it restarts so when it rejects the bring-up's answers, and + /// Setup's first screen waits for it. + Restarted, } +/// HCI Resets after the start-up's first answered one at which the bridge +/// falls back: one restart passes, the second is the model's. +pub const RESTARTS: u64 = 2; + impl fmt::Display for Cause { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -82,6 +90,10 @@ impl fmt::Display for Cause { Self::Refused(status) => write!(f, "status {status:#04x} where the model succeeds"), Self::Malformed => f.write_str("an answer of another kind or length than the model's"), Self::HostFailed => f.write_str("the host controller failed"), + Self::Restarted => f.write_str( + "bluetoothd reset the controller twice after its start-up, \ + as it does when it rejects the bring-up", + ), } } } @@ -115,6 +127,8 @@ pub struct Counters { /// alone, stale answers, what comes while it is kept out after a guest /// reset, and everything after the fallback. pub dropped: u64, + /// HCI Resets of the guest after the first the controller answered. + pub restarts: u64, } /// The forwarded command in flight. @@ -146,6 +160,8 @@ pub struct Bridge { address_differs: bool, /// The controller's procedures the guest saw start and not yet end. running: Vec, + /// Whether the controller answered an HCI Reset: the start-up ran. + started: bool, counters: Counters, } @@ -245,6 +261,7 @@ impl Bridge { written: None, address_differs: false, running: Vec::new(), + started: false, counters: Counters::default(), } } @@ -342,14 +359,26 @@ impl Bridge { self.counters.local += 1; return guest(shadow); }; - self.counters.forwarded += 1; - self.pending = Some(Pending { + let pending = Pending { opcode: opcode(packet), parameters: packet[3..].to_vec(), kind, shadow, deadline: now.saturating_add(DEADLINE), - }); + }; + // A reset after the start-up is bluetoothd restarting; at the + // second, the model takes over, answering this reset. A reset ends + // the controller's procedures with no event. + if pending.opcode == RESET && self.started { + self.counters.restarts += 1; + if self.counters.restarts >= RESTARTS { + self.running.clear(); + self.pending = Some(pending); + return self.fall(Cause::Restarted, now); + } + } + self.counters.forwarded += 1; + self.pending = Some(pending); vec![Step::Chip(command)] } @@ -469,7 +498,10 @@ impl Bridge { (INQUIRY_CANCEL, _) if chip.status == 0 => { self.running.retain(|r| *r != Running::Inquiry); } - (RESET, _) if chip.status == 0 => self.running.clear(), + (RESET, _) if chip.status == 0 => { + self.running.clear(); + self.started = true; + } _ => {} } match pending.opcode { diff --git a/crates/stela-soc/src/usb/hci/bridge/replay.rs b/crates/stela-soc/src/usb/hci/bridge/replay.rs index 484c59be90..74a449184a 100644 --- a/crates/stela-soc/src/usb/hci/bridge/replay.rs +++ b/crates/stela-soc/src/usb/hci/bridge/replay.rs @@ -388,3 +388,37 @@ fn a_bus_reset_mid_inquiry_keeps_the_old_results_out() { assert_eq!(rig.hci.fallback(), None); assert_eq!(rig.chip.opcodes().last(), Some(&0x0c03)); } + +/// bluetoothd that keeps restarting its start-up, as it does when it rejects +/// what it was answered: the first restart still reaches the controller, +/// the second is the model's, and the start-up completes on it. +#[test] +fn bluetoothd_restarting_its_start_up_twice_falls_back_to_the_model() { + let mut rig = Rig::started(Chip::new()); + let mut model = Model::new(ADDRESS); + for restart in 1..=2 { + for command in commands(BRING_UP) { + let answer = rig.command(&command); + let answer = answer + .iter() + .find(|e| answers(e, opcode(&command))) + .unwrap(); + let (code, status, returns, _) = summary(&model.command(&command, 0)[0]); + assert_eq!( + summary(answer), + (code, status, returns, 1), + "restart {restart}" + ); + } + } + let fallback = rig.hci.fallback().expect("fell back"); + assert_eq!( + (fallback.opcode, fallback.cause), + (Some(0x0c03), Cause::Restarted) + ); + assert_eq!( + rig.chip.received.len(), + 2 * 18, + "the second restart is the model's" + ); +} diff --git a/crates/stela-soc/src/usb/hci/bridge/tests.rs b/crates/stela-soc/src/usb/hci/bridge/tests.rs index ab04862274..2ac2ce8cf7 100644 --- a/crates/stela-soc/src/usb/hci/bridge/tests.rs +++ b/crates/stela-soc/src/usb/hci/bridge/tests.rs @@ -610,3 +610,42 @@ fn a_fallback_ends_the_procedures_the_controller_was_running() { assert!(events(bridge.chip_failed(0)).is_empty()); assert!(events(bridge.advance(u64::MAX)).is_empty()); } + +/// bluetoothd restarts, and resets its controller, when it rejects even a +/// well-formed answer (reason 108), and Setup's first screen waits for it: +/// a second restart after the start-up falls back, so the model answers it. +#[test] +fn bluetoothd_restarting_twice_after_its_start_up_falls_back() { + let mut bridge = Bridge::new(ADDRESS); + let reset = packet(0x0c03, &[]); + // The start-up's reset, then one restart: both the controller's. + for _ in 0..2 { + chip(bridge.command(&reset, 0)); + events(bridge.chip_event(&complete(0x0c03, 1, 0, &[]), 0)); + } + assert_eq!((bridge.fallen(), bridge.counters().restarts), (None, 1)); + // The second restart: the model answers it and everything after. + assert_eq!( + events(bridge.command(&reset, 0)), + [complete(0x0c03, 1, 0, &[])] + ); + let fallback = bridge.fallen().expect("fell back"); + assert_eq!( + (fallback.opcode, fallback.cause), + (Some(0x0c03), Cause::Restarted) + ); + assert_eq!( + fallback.to_string(), + "0x0c03 bluetoothd reset the controller twice after its start-up, \ + as it does when it rejects the bring-up" + ); + assert_eq!(bridge.counters().restarts, 2); + events(bridge.command(&packet(0x1009, &[]), 0)); + // Resets before the controller answered one are the start-up's own. + let mut bridge = Bridge::new(ADDRESS); + for _ in 0..3 { + chip(bridge.command(&reset, 0)); + bridge.resync(); + } + assert_eq!((bridge.fallen(), bridge.counters().restarts), (None, 0)); +} From 90dd7f0b507084941a56ee5d1a2843035773fb04 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:33:09 +0000 Subject: [PATCH 11/18] fix(bluetooth): hold a forwarded command until the lent controller has a command credit, as its last Command Complete or Command Status, stale answers and credits alone among them, said, where the bridge sent the next command whatever credits the controller had left --- crates/stela-soc/src/usb/hci/bridge.rs | 47 +++++++++++++++++--- crates/stela-soc/src/usb/hci/bridge/tests.rs | 36 +++++++++++++++ 2 files changed, 78 insertions(+), 5 deletions(-) diff --git a/crates/stela-soc/src/usb/hci/bridge.rs b/crates/stela-soc/src/usb/hci/bridge.rs index bf18c8ae9d..00ddef8228 100644 --- a/crates/stela-soc/src/usb/hci/bridge.rs +++ b/crates/stela-soc/src/usb/hci/bridge.rs @@ -140,6 +140,8 @@ struct Pending { /// The shadow's answer, the first of its events, given on a fallback. shadow: Vec>, deadline: u64, + /// The command, while it waits for one of the controller's credits. + unsent: Option, } /// The bridge. @@ -162,6 +164,9 @@ pub struct Bridge { running: Vec, /// Whether the controller answered an HCI Reset: the start-up ran. started: bool, + /// The commands the controller takes now, as its last Command Complete + /// or Command Status said (Num_HCI_Command_Packets, Vol 4 Part E 4.4). + credits: u8, counters: Counters, } @@ -262,6 +267,7 @@ impl Bridge { address_differs: false, running: Vec::new(), started: false, + credits: 1, counters: Counters::default(), } } @@ -359,12 +365,13 @@ impl Bridge { self.counters.local += 1; return guest(shadow); }; - let pending = Pending { + let mut pending = Pending { opcode: opcode(packet), parameters: packet[3..].to_vec(), kind, shadow, deadline: now.saturating_add(DEADLINE), + unsent: None, }; // A reset after the start-up is bluetoothd restarting; at the // second, the model takes over, answering this reset. A reset ends @@ -378,7 +385,28 @@ impl Bridge { } } self.counters.forwarded += 1; + // With no credit the command waits for the controller to give one + // back; its deadline runs from now all the same. + let steps = if self.credits == 0 { + pending.unsent = Some(command); + Vec::new() + } else { + self.credits -= 1; + vec![Step::Chip(command)] + }; self.pending = Some(pending); + steps + } + + /// The command waiting for a credit, once the controller has one. + fn send_held(&mut self) -> Vec { + if self.credits == 0 { + return Vec::new(); + } + let Some(command) = self.pending.as_mut().and_then(|p| p.unsent.take()) else { + return Vec::new(); + }; + self.credits -= 1; vec![Step::Chip(command)] } @@ -435,15 +463,24 @@ impl Bridge { return Vec::new(); } if completes(event) { + // Every completion gives the controller's credits, a stale one + // and credits alone too. + match *event { + [COMMAND_COMPLETE, _, credits, ..] | [COMMAND_STATUS, _, _, credits, ..] => { + self.credits = credits; + } + _ => {} + } let completion = Completion::of(event); - let pending = completion - .as_ref() - .and_then(|completion| self.pending.take_if(|p| p.opcode == completion.opcode)); + let pending = completion.as_ref().and_then(|completion| { + self.pending + .take_if(|p| p.unsent.is_none() && p.opcode == completion.opcode) + }); let (Some(completion), Some(pending)) = (completion, pending) else { // Credits alone (opcode 0, no status), or the answer to a // command no longer in flight. self.counters.dropped += 1; - return Vec::new(); + return self.send_held(); }; return self.answer(pending, &completion, now); } diff --git a/crates/stela-soc/src/usb/hci/bridge/tests.rs b/crates/stela-soc/src/usb/hci/bridge/tests.rs index 2ac2ce8cf7..77dfedf5c3 100644 --- a/crates/stela-soc/src/usb/hci/bridge/tests.rs +++ b/crates/stela-soc/src/usb/hci/bridge/tests.rs @@ -646,6 +646,42 @@ fn bluetoothd_restarting_twice_after_its_start_up_falls_back() { for _ in 0..3 { chip(bridge.command(&reset, 0)); bridge.resync(); + // Its late answer, stale now, gives the controller's credit back. + assert!( + bridge + .chip_event(&complete(0x0c03, 1, 0, &[]), 0) + .is_empty() + ); } assert_eq!((bridge.fallen(), bridge.counters().restarts), (None, 0)); } + +/// The controller's own command credits: a forwarded command waits until +/// the controller has one, and falls back at its deadline if none comes. +#[test] +fn a_command_waits_for_the_controllers_credit() { + let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(&packet(0x0c03, &[]), 0)); + // Answered with no credit left; the guest still sees one. + let answer = events(bridge.chip_event(&complete(0x0c03, 0, 0, &[]), 0)); + assert_eq!(answer, [complete(0x0c03, 1, 0, &[])]); + let mask = packet(0x0c01, &[0xff; 8]); + assert!(bridge.command(&mask, 0).is_empty(), "held for a credit"); + assert!(bridge.busy()); + // Credits alone give one back: the command goes. + assert_eq!( + chip(bridge.chip_event(&[COMMAND_COMPLETE, 3, 1, 0, 0], 0)), + mask + ); + events(bridge.chip_event(&complete(0x0c01, 0, 0, &[]), 0)); + // A Command Status gives credits too. + let address = packet(0x1009, &[]); + assert!(bridge.command(&address, 0).is_empty()); + assert_eq!(chip(bridge.chip_event(&status(0x0000, 1, 0), 0)), address); + events(bridge.chip_event(&complete(0x1009, 0, 0, &CHIP_ADDRESS), 0)); + // None comes: the deadline falls back. + assert!(bridge.command(&packet(0x0c14, &[]), 10).is_empty()); + let answer = events(bridge.advance(10 + DEADLINE)); + assert_eq!(answer[0][3..6], [0x14, 0x0c, 0]); + assert_eq!(bridge.fallen().unwrap().cause, Cause::Timeout); +} From d7cbc1f51438223bfd1abe065f5d97ae997efd5e Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 06:03:42 +0000 Subject: [PATCH 12/18] fix(bluetooth): send the lent controller nothing once the bridge fell back, dropping a command the guest's function still had queued for it, and leave the controller alone from then on, where a command queued before the fallback could still reach it --- crates/stela-boot/src/engine/bluetooth.rs | 16 ++++++++++++- crates/stela-soc/src/usb/hci.rs | 24 +++++++++++++++++-- crates/stela-soc/src/usb/hci/bridge/replay.rs | 5 +++- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/stela-boot/src/engine/bluetooth.rs b/crates/stela-boot/src/engine/bluetooth.rs index caf0bda8ca..2b0313c936 100644 --- a/crates/stela-boot/src/engine/bluetooth.rs +++ b/crates/stela-boot/src/engine/bluetooth.rs @@ -399,11 +399,21 @@ impl HostBluetooth { } } + /// Whether the lent controller's bridge fell back to the model, after + /// which nothing goes to the controller and nothing is taken from it. + fn fallen(&self) -> bool { + self.lend.is_some_and(|(fallback, _, _)| fallback.is_some()) + } + pub fn transmit(&mut self, packets: Vec) { // The model answers inside the guest's function. if self.failed || matches!(self.controller, Controller::Modeled) { return; } + if self.fallen() { + self.link.clear(); + return; + } self.link.queue(packets); // SAFETY: the loader root `storage::open` captured, which maps the // controllers' registers and DMA pages for the whole run. @@ -418,7 +428,11 @@ impl HostBluetooth { /// What the controller has for the guest, at most `room` packets; the /// rest waits in the link for a later turn. pub fn receive(&mut self, room: usize) -> Vec { - if self.failed || room == 0 || matches!(self.controller, Controller::Modeled) { + if self.failed + || room == 0 + || self.fallen() + || matches!(self.controller, Controller::Modeled) + { return Vec::new(); } // SAFETY: as in `transmit`. diff --git a/crates/stela-soc/src/usb/hci.rs b/crates/stela-soc/src/usb/hci.rs index f7b48709c0..aacbb1cf95 100644 --- a/crates/stela-soc/src/usb/hci.rs +++ b/crates/stela-soc/src/usb/hci.rs @@ -597,9 +597,15 @@ impl Hci { self.state.capture.take() } - /// The next packet the guest sent for the host's controller. + /// The next packet the guest sent for the host's controller; none once + /// the bridge fell back, which drops what was still queued. pub fn take(&mut self) -> Option { - self.state.outbound.pop_front() + let state = &mut self.state; + if state.bridge.as_ref().is_some_and(|b| b.fallen().is_some()) { + state.outbound.clear(); + return None; + } + state.outbound.pop_front() } /// An event from the host's controller for the guest. Dropped (and @@ -1698,6 +1704,20 @@ mod tests { assert_eq!(hci.fallback(), None); } + /// After the fallback nothing goes to the host's controller, not even a + /// command queued for it before. + #[test] + fn nothing_goes_to_the_controller_after_the_fallback() { + let mut hci = bridged(); + hci.set_time(0); + command(&mut hci, &[0x09, 0x10, 0]).unwrap(); + hci.set_time(bridge::DEADLINE); + assert!(hci.fallback().is_some()); + assert_eq!(hci.take(), None, "the command queued before is dropped"); + command(&mut hci, &[0x03, 0x0c, 0]).unwrap(); + assert_eq!(hci.take(), None); + } + #[test] fn the_room_left_is_the_fuller_queues() { let mut hci = controller(); diff --git a/crates/stela-soc/src/usb/hci/bridge/replay.rs b/crates/stela-soc/src/usb/hci/bridge/replay.rs index 74a449184a..52c1554144 100644 --- a/crates/stela-soc/src/usb/hci/bridge/replay.rs +++ b/crates/stela-soc/src/usb/hci/bridge/replay.rs @@ -113,7 +113,10 @@ impl Rig { self.chip.now = self.now; self.hci.set_time(self.now); let outbound: Vec<_> = core::iter::from_fn(|| self.hci.take()).collect(); - if self.failed { + // As the engine: after a failure or the fallback the controller is + // left alone. + if self.failed || self.hci.fallback().is_some() { + self.link.clear(); return; } self.link.queue(outbound); From fca12c8b791f1876be954ae06c233376eb136aec Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:12:49 +0000 Subject: [PATCH 13/18] fix(bluetooth): print the always-on GUEST BLUETOOTH command trace's first parameter bytes as the capture masks the whole command, a hidden one as xx, so Write Local Name, the module's Write BD_ADDR, Remote Name Request and LE Encrypt show no name, address middle or key, where every boot's log carried the first four raw parameter bytes of the guest's first 48 commands of each configuration --- crates/stela-soc/src/usb/hci.rs | 110 +++++++++++++++++++++++++++----- 1 file changed, 94 insertions(+), 16 deletions(-) diff --git a/crates/stela-soc/src/usb/hci.rs b/crates/stela-soc/src/usb/hci.rs index aacbb1cf95..93f41b19e3 100644 --- a/crates/stela-soc/src/usb/hci.rs +++ b/crates/stela-soc/src/usb/hci.rs @@ -114,7 +114,9 @@ pub const TRACED_COMMANDS: u16 = 48; /// daemon that restarts begins each bring-up with one and need not /// configure the function again. const TRACED_BRING_UPS: u8 = 4; -/// Parameter bytes a traced command shows. +/// Parameter bytes a traced command shows, masked as the capture masks them +/// (`capture`): an address keeps its last byte and vendor half, and names, +/// keys, vendor parameters and anything no rule names are `xx`. pub const TRACED_BYTES: usize = 4; /// Trace entries held until the owner takes them; later ones are dropped. const TRACE_ENTRIES: usize = 64; @@ -126,13 +128,13 @@ const UNKNOWN_COMMAND: u8 = 0x01; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Traced { /// A command the model answered: its opcode, parameter length and - /// first parameter bytes (a vendor command's sub-command), and the + /// first parameter bytes, `None` where the mask hides one, and the /// event that answered it, if any, with its status and the length of /// its return parameters after the status. Command { opcode: u16, parameters: u8, - first: [u8; TRACED_BYTES], + first: [Option; TRACED_BYTES], answer: Option, }, /// The guest set the configuration to this value (0: unconfigured). @@ -183,14 +185,21 @@ fn answered_opcode(event: &[u8]) -> Option { } } -/// A command's first parameter bytes, zero past its parameters. -fn first_bytes(packet: &[u8]) -> [u8; TRACED_BYTES] { - let mut first = [0; TRACED_BYTES]; - let shown = packet[COMMAND_HEADER..].iter().take(TRACED_BYTES); +/// A command's first parameter bytes as the capture masks the whole +/// command, `None` for a hidden one or past its parameters. The raw bytes +/// are never held: the trace is in every boot's log. +fn first_bytes(packet: &[u8]) -> [Option; TRACED_BYTES] { + let masked = capture::Captured::new( + capture::Direction::FromGuest, + capture::Kind::Command, + packet, + ); + let mut first = [None; TRACED_BYTES]; + let shown = masked.bytes.iter().zip(&masked.hidden).skip(COMMAND_HEADER); first .iter_mut() .zip(shown) - .for_each(|(to, from)| *to = *from); + .for_each(|(to, (&byte, &hidden))| *to = (!hidden).then_some(byte)); first } @@ -208,7 +217,11 @@ impl core::fmt::Display for Traced { if !shown.is_empty() { f.write_str("[")?; for (index, byte) in shown.iter().enumerate() { - write!(f, "{}{byte:02x}", if index == 0 { "" } else { " " })?; + f.write_str(if index == 0 { "" } else { " " })?; + match byte { + Some(byte) => write!(f, "{byte:02x}")?, + None => f.write_str("xx")?, + } } f.write_str("] ")?; } @@ -337,7 +350,7 @@ struct State { bridge: Option>, /// Traced commands of the bridge whose answers have not reached the /// guest yet: opcode, parameter length, first parameter bytes. - awaiting: VecDeque<(u16, u8, [u8; TRACED_BYTES])>, + awaiting: VecDeque<(u16, u8, [Option; TRACED_BYTES])>, } /// The function: its pipes and queues. @@ -1381,25 +1394,26 @@ mod tests { Traced::Command { opcode: 0x0c03, parameters: 0, - first: [0; 4], + first: [None; 4], answer: complete(0, 0), }, Traced::Command { opcode: 0x1004, parameters: 1, - first: [2, 0, 0, 0], + first: [Some(2), None, None, None], answer: complete(0, 10), }, + // A vendor command's parameters are hidden. Traced::Command { opcode: 0xfc4c, parameters: 1, - first: [9, 0, 0, 0], + first: [None; 4], answer: complete(UNKNOWN_COMMAND, 0), }, Traced::Command { opcode: 0x0401, parameters: 5, - first: [0x33, 0x8b, 0x9e, 1], + first: [Some(0x33), Some(0x8b), Some(0x9e), Some(1)], answer: Some(Answered { event: COMMAND_STATUS, status: 0, @@ -1409,7 +1423,7 @@ mod tests { Traced::Command { opcode: 0x0c35, parameters: 5, - first: [1, 0x40, 0, 1], + first: [Some(1), Some(0x40), Some(0), Some(1)], answer: None, }, ] @@ -1422,6 +1436,10 @@ mod tests { traced[1].to_string(), "command 0x1004 parameters=1 [02] answered complete status=0x00 returns=10" ); + assert_eq!( + traced[2].to_string(), + "command 0xfc4c parameters=1 [xx] answered complete status=0x01 returns=0" + ); assert_eq!( traced[4].to_string(), "command 0x0c35 parameters=5 [01 40 00 01] answered with no event" @@ -1458,6 +1476,66 @@ mod tests { assert_eq!(Traced::Reset.to_string(), "bus reset"); } + /// The trace is in every boot's log, so its bytes are the capture's + /// masked ones: the Mac's name, the middle of the address bluetoothd + /// writes and of a neighbour's, and LE Encrypt's key show as `xx`, for + /// the model and for a lent controller alike. + #[test] + fn the_always_on_trace_shows_no_name_address_middle_or_key() { + // A synthetic name and addresses, in HCI order. + const NAME: &[u8] = b"Tester's Mac"; + const PLATFORM: [u8; 6] = [0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5]; + const NEIGHBOUR: [u8; 6] = [0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5]; + let with = |opcode: u16, parameters: &[u8]| { + let mut packet = opcode.to_le_bytes().to_vec(); + packet.push(parameters.len() as u8); + packet.extend_from_slice(parameters); + packet + }; + let mut name = NAME.to_vec(); + name.resize(248, 0); + let mut request = NEIGHBOUR.to_vec(); + request.extend_from_slice(&[1, 0, 0, 0]); + let mut eir = vec![0, NAME.len() as u8 + 1, 0x09]; + eir.extend_from_slice(NAME); + eir.resize(241, 0); + let commands = [ + (with(0x0c13, &name), "parameters=248 [xx xx xx xx] "), + (with(0xfc01, &PLATFORM), "parameters=6 [a0 xx xx a3] "), + (with(0x0419, &request), "parameters=10 [b0 xx xx b3] "), + (with(0x2017, &[0x5a; 32]), "parameters=32 [xx xx xx xx] "), + (with(0x0c52, &eir), "parameters=241 [00 0d 09 xx] "), + ]; + for mut hci in [modeled(), bridged()] { + hci.take_trace(); + for (packet, shown) in &commands { + command(&mut hci, packet).unwrap(); + // A lent controller answers what reaches it. + while let Some(Outbound::Command(sent)) = hci.take() { + hci.deliver_event(&[COMMAND_STATUS, 4, 0, 1, sent[0], sent[1]]); + } + while hci.ready_at(EVENTS) == Some(0) { + read(&mut hci, EVENTS, EVENT_PACKET); + } + let traced = hci.take_trace(); + let [Traced::Command { first, .. }] = traced[..] else { + panic!("one traced command: {traced:?}"); + }; + let line = traced[0].to_string(); + assert!(line.contains(shown), "{line}"); + for secret in [&NAME[..2], &PLATFORM[1..3], &NEIGHBOUR[1..3], &[0x5a, 0x5a]] { + let hex = alloc::format!("{:02x} {:02x}", secret[0], secret[1]); + assert!(!line.contains(&hex), "{line}"); + assert!( + !first + .windows(2) + .any(|w| w == [Some(secret[0]), Some(secret[1])]) + ); + } + } + } + } + /// `--bluetooth-trace`: once the owner asks, every packet after each /// configuration, both ways, then one end line until the next /// configuration; nothing before it asks. @@ -1625,7 +1703,7 @@ mod tests { ); assert_eq!( traced[2].to_string(), - "command 0xfc4c parameters=1 [09] answered complete status=0x01 returns=0" + "command 0xfc4c parameters=1 [xx] answered complete status=0x01 returns=0" ); } From 98cabd3f1b3ec848dc9bea27298e35eedec28532 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:13:39 +0000 Subject: [PATCH 14/18] fix(bluetooth): fall back to the model when the lent controller reports a Hardware Error, which the guest never sees, send the controller a listed command only with its specification's parameter length, drop the controller's ACL data, as milestone 1 lends no connection, and say the deadline and the restarts in the log from the constants the bridge uses, where a Hardware Error passed to bluetoothd while the bridge kept forwarding, a listed command of any length reached the controller, its ACL data could reach the guest under a handle the shadow owns, and the log said 1 s and twice whatever DEADLINE and RESTARTS were --- crates/stela-soc/src/usb/hci.rs | 15 ++- crates/stela-soc/src/usb/hci/bridge.rs | 53 ++++++--- crates/stela-soc/src/usb/hci/bridge/policy.rs | 112 +++++++++--------- crates/stela-soc/src/usb/hci/bridge/tests.rs | 108 +++++++++++++++-- 4 files changed, 206 insertions(+), 82 deletions(-) diff --git a/crates/stela-soc/src/usb/hci.rs b/crates/stela-soc/src/usb/hci.rs index 93f41b19e3..7a891f365c 100644 --- a/crates/stela-soc/src/usb/hci.rs +++ b/crates/stela-soc/src/usb/hci.rs @@ -643,7 +643,8 @@ impl Hci { } /// ACL data from the host's controller for the guest, dropped as an - /// event is, and while a bridge keeps the controller out. + /// event is, and always behind a bridge, which in milestone 1 lends no + /// connection (`bridge::Bridge::chip_acl`). pub fn deliver_acl(&mut self, packet: &[u8]) { if !self.up() { return; @@ -1690,9 +1691,15 @@ mod tests { read(&mut hci, EVENTS, EVENT_PACKET), [vec![0x13, 5, 1, 1, 0, 1, 0]] ); - // The controller's ACL data reaches the guest. + // The controller's ACL data names no connection the guest knows: + // it is captured and dropped. + let dropped = hci.bridge_counters().unwrap().dropped; hci.deliver_acl(&[2, 0, 1, 0, 8]); - assert_eq!(read(&mut hci, ACL_IN, 512), [vec![2, 0, 1, 0, 8]]); + assert_eq!(hci.ready_at(ACL_IN), None); + assert_eq!(hci.counters().acl_to_guest, 0); + assert_eq!(hci.bridge_counters().unwrap().dropped, dropped + 1); + let captured = hci.take_captured(); + assert_eq!(captured.last().map(|c| c.direction), Some(FromChip)); assert_eq!(hci.fallback(), None); // The trace names each command with its answer, whoever gave it. let traced = hci.take_trace(); @@ -1724,7 +1731,7 @@ mod tests { [COMMAND_COMPLETE, 10, 1, 0x09, 0x10, 0, 1, 2, 3, 4, 5, 0x02] ); let fallback = hci.fallback().expect("fell back"); - assert_eq!(fallback.to_string(), "0x1009 no answer in 1 s"); + assert_eq!(fallback.to_string(), "0x1009 no answer in 1000 ms"); command(&mut hci, &[0x03, 0x0c, 0]).unwrap(); assert_eq!(hci.take(), None, "nothing goes out again"); assert_eq!( diff --git a/crates/stela-soc/src/usb/hci/bridge.rs b/crates/stela-soc/src/usb/hci/bridge.rs index 00ddef8228..bd99e025ef 100644 --- a/crates/stela-soc/src/usb/hci/bridge.rs +++ b/crates/stela-soc/src/usb/hci/bridge.rs @@ -25,10 +25,11 @@ //! controller. //! - The controller's events reach the guest as they are, but for its //! vendor events, credits alone and answers to commands no longer in -//! flight, which are dropped. After a guest bus reset or a new -//! configuration, which reach the shadow but never the controller (a USB -//! reset would lose its patched firmware), its events stay out until the -//! guest's next HCI Reset is answered. +//! flight, which are dropped, and a Hardware Error, which falls back. Its +//! ACL data is dropped: milestone 1 lends no connection. After a guest +//! bus reset or a new configuration, which reach the shadow but never the +//! controller (a USB reset would lose its patched firmware), its events +//! stay out until the guest's next HCI Reset is answered. //! - The owner carries packets to and from the controller through a //! [`Link`] and the [`HostController`] trait. use super::model::Model; @@ -73,6 +74,10 @@ pub enum Cause { Malformed, /// The host's controller failed. HostFailed, + /// The host's controller reported a Hardware Error with this code + /// (Vol 4 Part E 7.7.16): its firmware has failed, and whatever it was + /// running is lost. + HardwareError(u8), /// bluetoothd reset the controller [`RESTARTS`] times after its /// start-up: it restarts so when it rejects the bring-up's answers, and /// Setup's first screen waits for it. @@ -83,16 +88,23 @@ pub enum Cause { /// falls back: one restart passes, the second is the model's. pub const RESTARTS: u64 = 2; +/// [`DEADLINE`] in milliseconds, as the log says it. +pub const DEADLINE_MS: u64 = DEADLINE * 1000 / FREQUENCY_HZ; + impl fmt::Display for Cause { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Timeout => f.write_str("no answer in 1 s"), + Self::Timeout => write!(f, "no answer in {DEADLINE_MS} ms"), Self::Refused(status) => write!(f, "status {status:#04x} where the model succeeds"), Self::Malformed => f.write_str("an answer of another kind or length than the model's"), Self::HostFailed => f.write_str("the host controller failed"), - Self::Restarted => f.write_str( - "bluetoothd reset the controller twice after its start-up, \ - as it does when it rejects the bring-up", + Self::HardwareError(code) => { + write!(f, "the host controller reported Hardware Error {code:#04x}") + } + Self::Restarted => write!( + f, + "bluetoothd reset the controller {RESTARTS} times after its start-up, \ + as it does when it rejects the bring-up" ), } } @@ -194,6 +206,8 @@ enum Running { } /// A vendor's own event (7.7.65 leaves code 0xFF to vendors). const VENDOR_EVENT: u8 = 0xff; +/// Hardware Error (7.7.16): the controller's firmware failed. +const HARDWARE_ERROR: u8 = 0x10; /// The parts of a Command Complete or Command Status event that answers a /// command, with its status. @@ -307,15 +321,13 @@ impl Bridge { guest(self.shadow.acl(packet)) } - /// Whether ACL data from the controller reaches the guest. + /// Whether ACL data from the controller reaches the guest: never in + /// milestone 1, which lends no connection. The guest's connections are + /// all the shadow's, so the controller's data names none the guest + /// knows, and its handle could be one of the shadow's. pub fn chip_acl(&mut self) -> bool { - let passes = self.fallen.is_none() && !self.resync; - if passes { - self.counters.passed += 1; - } else { - self.counters.dropped += 1; - } - passes + self.counters.dropped += 1; + false } /// Why the bridge fell back to the model, once it has. @@ -456,12 +468,19 @@ impl Bridge { /// One event from the host's controller. The answer to the command in /// flight becomes the guest's; a vendor event, credits alone or a stale /// answer is dropped, as is everything while the controller is kept out - /// or after the fallback; every other event reaches the guest as it is. + /// or after the fallback; a Hardware Error falls back, and the guest, + /// whose controller the model now is, never sees it; every other event + /// reaches the guest as it is. pub fn chip_event(&mut self, event: &[u8], now: u64) -> Vec { if self.fallen.is_some() || event.first() == Some(&VENDOR_EVENT) { self.counters.dropped += 1; return Vec::new(); } + if event.first() == Some(&HARDWARE_ERROR) { + self.counters.dropped += 1; + let code = event.get(2).copied().unwrap_or(0); + return self.fall(Cause::HardwareError(code), now); + } if completes(event) { // Every completion gives the controller's credits, a stale one // and credits alone too. diff --git a/crates/stela-soc/src/usb/hci/bridge/policy.rs b/crates/stela-soc/src/usb/hci/bridge/policy.rs index e16f17e421..2c7925d90f 100644 --- a/crates/stela-soc/src/usb/hci/bridge/policy.rs +++ b/crates/stela-soc/src/usb/hci/bridge/policy.rs @@ -104,62 +104,64 @@ impl Merge { } /// The standard commands milestone 1 forwards (opcode, Supported Commands -/// octet and bit of Bluetooth Core v5.4 Vol 4 Part E 6.27, kind). Each is -/// one the model implements and lists. -pub const FORWARDED: &[(u16, u8, u8, Forward)] = &[ +/// octet and bit of Bluetooth Core v5.4 Vol 4 Part E 6.27, parameter length +/// of 7.1-7.8, kind). Each is one the model implements and lists. A command +/// of another parameter length is the shadow's: the controller is never +/// sent what its specification does not describe. +pub const FORWARDED: &[(u16, u8, u8, u8, Forward)] = &[ // Link control: inquiry and remote names. - (0x0401, 0, 0, Forward::Procedure), // Inquiry - (0x0402, 0, 1, Forward::Procedure), // Inquiry Cancel - (0x0419, 2, 3, Forward::Procedure), // Remote Name Request - (0x041a, 2, 4, Forward::Procedure), // Remote Name Request Cancel + (0x0401, 0, 0, 5, Forward::Procedure), // Inquiry + (0x0402, 0, 1, 0, Forward::Procedure), // Inquiry Cancel + (0x0419, 2, 3, 10, Forward::Procedure), // Remote Name Request + (0x041a, 2, 4, 6, Forward::Procedure), // Remote Name Request Cancel // Link policy. - (0x080e, 5, 3, Forward::Strict), // Read Default Link Policy Settings - (0x080f, 5, 4, Forward::Strict), // Write Default Link Policy Settings + (0x080e, 5, 3, 0, Forward::Strict), // Read Default Link Policy Settings + (0x080f, 5, 4, 2, Forward::Strict), // Write Default Link Policy Settings // Controller and baseband. - (0x0c01, 5, 6, Forward::Strict), // Set Event Mask - (0x0c03, 5, 7, Forward::Strict), // Reset - (0x0c13, 7, 0, Forward::Strict), // Write Local Name - (0x0c14, 7, 1, Forward::Strict), // Read Local Name - (0x0c15, 7, 2, Forward::Strict), // Read Connection Accept Timeout - (0x0c16, 7, 3, Forward::Strict), // Write Connection Accept Timeout - (0x0c17, 7, 4, Forward::Strict), // Read Page Timeout - (0x0c18, 7, 5, Forward::Strict), // Write Page Timeout - (0x0c1b, 8, 0, Forward::Strict), // Read Page Scan Activity - (0x0c1c, 8, 1, Forward::Strict), // Write Page Scan Activity - (0x0c1d, 8, 2, Forward::Strict), // Read Inquiry Scan Activity - (0x0c1e, 8, 3, Forward::Strict), // Write Inquiry Scan Activity - (0x0c1f, 8, 4, Forward::Strict), // Read Authentication Enable - (0x0c20, 8, 5, Forward::Strict), // Write Authentication Enable - (0x0c23, 9, 0, Forward::Strict), // Read Class Of Device - (0x0c24, 9, 1, Forward::Strict), // Write Class Of Device - (0x0c25, 9, 2, Forward::Strict), // Read Voice Setting - (0x0c26, 9, 3, Forward::Strict), // Write Voice Setting - (0x0c42, 12, 4, Forward::Strict), // Read Inquiry Scan Type - (0x0c43, 12, 5, Forward::Strict), // Write Inquiry Scan Type - (0x0c44, 12, 6, Forward::Strict), // Read Inquiry Mode - (0x0c45, 12, 7, Forward::Strict), // Write Inquiry Mode - (0x0c46, 13, 0, Forward::Strict), // Read Page Scan Type - (0x0c47, 13, 1, Forward::Strict), // Write Page Scan Type - (0x0c51, 17, 0, Forward::Strict), // Read Extended Inquiry Response - (0x0c52, 17, 1, Forward::Strict), // Write Extended Inquiry Response - (0x0c55, 17, 5, Forward::Strict), // Read Simple Pairing Mode - (0x0c56, 17, 6, Forward::Strict), // Write Simple Pairing Mode - (0x0c58, 18, 0, Forward::Strict), // Read Inquiry Response Transmit Power Level - (0x0c5a, 18, 2, Forward::Strict), // Read Default Erroneous Data Reporting - (0x0c5b, 18, 3, Forward::Strict), // Write Default Erroneous Data Reporting - (0x0c63, 22, 2, Forward::Strict), // Set Event Mask Page 2 - (0x0c6c, 24, 5, Forward::Strict), // Read LE Host Support - (0x0c6d, 24, 6, Forward::Strict), // Write LE Host Support + (0x0c01, 5, 6, 8, Forward::Strict), // Set Event Mask + (0x0c03, 5, 7, 0, Forward::Strict), // Reset + (0x0c13, 7, 0, 248, Forward::Strict), // Write Local Name + (0x0c14, 7, 1, 0, Forward::Strict), // Read Local Name + (0x0c15, 7, 2, 0, Forward::Strict), // Read Connection Accept Timeout + (0x0c16, 7, 3, 2, Forward::Strict), // Write Connection Accept Timeout + (0x0c17, 7, 4, 0, Forward::Strict), // Read Page Timeout + (0x0c18, 7, 5, 2, Forward::Strict), // Write Page Timeout + (0x0c1b, 8, 0, 0, Forward::Strict), // Read Page Scan Activity + (0x0c1c, 8, 1, 4, Forward::Strict), // Write Page Scan Activity + (0x0c1d, 8, 2, 0, Forward::Strict), // Read Inquiry Scan Activity + (0x0c1e, 8, 3, 4, Forward::Strict), // Write Inquiry Scan Activity + (0x0c1f, 8, 4, 0, Forward::Strict), // Read Authentication Enable + (0x0c20, 8, 5, 1, Forward::Strict), // Write Authentication Enable + (0x0c23, 9, 0, 0, Forward::Strict), // Read Class Of Device + (0x0c24, 9, 1, 3, Forward::Strict), // Write Class Of Device + (0x0c25, 9, 2, 0, Forward::Strict), // Read Voice Setting + (0x0c26, 9, 3, 2, Forward::Strict), // Write Voice Setting + (0x0c42, 12, 4, 0, Forward::Strict), // Read Inquiry Scan Type + (0x0c43, 12, 5, 1, Forward::Strict), // Write Inquiry Scan Type + (0x0c44, 12, 6, 0, Forward::Strict), // Read Inquiry Mode + (0x0c45, 12, 7, 1, Forward::Strict), // Write Inquiry Mode + (0x0c46, 13, 0, 0, Forward::Strict), // Read Page Scan Type + (0x0c47, 13, 1, 1, Forward::Strict), // Write Page Scan Type + (0x0c51, 17, 0, 0, Forward::Strict), // Read Extended Inquiry Response + (0x0c52, 17, 1, 241, Forward::Strict), // Write Extended Inquiry Response + (0x0c55, 17, 5, 0, Forward::Strict), // Read Simple Pairing Mode + (0x0c56, 17, 6, 1, Forward::Strict), // Write Simple Pairing Mode + (0x0c58, 18, 0, 0, Forward::Strict), // Read Inquiry Response Transmit Power Level + (0x0c5a, 18, 2, 0, Forward::Strict), // Read Default Erroneous Data Reporting + (0x0c5b, 18, 3, 1, Forward::Strict), // Write Default Erroneous Data Reporting + (0x0c63, 22, 2, 8, Forward::Strict), // Set Event Mask Page 2 + (0x0c6c, 24, 5, 0, Forward::Strict), // Read LE Host Support + (0x0c6d, 24, 6, 2, Forward::Strict), // Write LE Host Support // Informational: the capabilities, merged, and the controller's own // address. - (0x1002, 14, 4, Forward::Merge(Merge::Commands)), // Read Local Supported Commands - (0x1003, 14, 5, Forward::Merge(Merge::Features)), // Read Local Supported Features - (0x1004, 14, 6, Forward::Merge(Merge::ExtendedFeatures)), // Read Local Extended Features - (0x1005, 14, 7, Forward::Merge(Merge::Buffers)), // Read Buffer Size - (0x1009, 15, 1, Forward::Strict), // Read BD_ADDR + (0x1002, 14, 4, 0, Forward::Merge(Merge::Commands)), // Read Local Supported Commands + (0x1003, 14, 5, 0, Forward::Merge(Merge::Features)), // Read Local Supported Features + (0x1004, 14, 6, 1, Forward::Merge(Merge::ExtendedFeatures)), // Read Local Extended Features + (0x1005, 14, 7, 0, Forward::Merge(Merge::Buffers)), // Read Buffer Size + (0x1009, 15, 1, 0, Forward::Strict), // Read BD_ADDR // LE: the event mask and the features, merged. - (0x2001, 25, 0, Forward::Strict), // LE Set Event Mask - (0x2003, 25, 2, Forward::Merge(Merge::LeFeatures)), // LE Read Local Supported Features + (0x2001, 25, 0, 8, Forward::Strict), // LE Set Event Mask + (0x2003, 25, 2, 0, Forward::Merge(Merge::LeFeatures)), // LE Read Local Supported Features ]; /// The Supported Commands bits of [`FORWARDED`]. @@ -167,7 +169,7 @@ const FORWARD_MASK: [u8; 64] = { let mut mask = [0; 64]; let mut i = 0; while i < FORWARDED.len() { - let (_, octet, bit, _) = FORWARDED[i]; + let (_, octet, bit, _, _) = FORWARDED[i]; mask[octet as usize] |= 1 << bit; i += 1; } @@ -211,13 +213,17 @@ pub fn vendor(opcode: u16) -> bool { } /// `packet`, a whole command, as one for the host's controller, and how its -/// answer becomes the guest's; `None` for a command the shadow answers. +/// answer becomes the guest's; `None` for a command the shadow answers, +/// which a listed command of another parameter length is. pub fn forward(packet: &[u8]) -> Option<(ChipCommand, Forward)> { let opcode = u16::from_le_bytes([*packet.first()?, *packet.get(1)?]); if vendor(opcode) { return None; } - let &(_, _, _, kind) = FORWARDED.iter().find(|entry| entry.0 == opcode)?; + let &(_, _, _, length, kind) = FORWARDED.iter().find(|entry| entry.0 == opcode)?; + if packet.len() != 3 + usize::from(length) || packet[2] != length { + return None; + } if opcode == READ_EXTENDED_FEATURES && packet.get(3).is_none_or(|&page| page > 1) { return None; } diff --git a/crates/stela-soc/src/usb/hci/bridge/tests.rs b/crates/stela-soc/src/usb/hci/bridge/tests.rs index 77dfedf5c3..9ae0c30128 100644 --- a/crates/stela-soc/src/usb/hci/bridge/tests.rs +++ b/crates/stela-soc/src/usb/hci/bridge/tests.rs @@ -107,17 +107,52 @@ fn vendor_and_unlisted_commands_are_the_shadows() { #[test] fn the_forwarded_commands_are_standard_ones_the_model_lists() { let bitmap = super::super::model::supported_commands(); - for (index, &(opcode, octet, bit, _)) in policy::FORWARDED.iter().enumerate() { + for (index, &(opcode, octet, bit, _, _)) in policy::FORWARDED.iter().enumerate() { assert!(!policy::vendor(opcode)); assert!(super::super::model::implements(opcode), "{opcode:#06x}"); assert_ne!(bitmap[usize::from(octet)] & 1 << bit, 0, "{opcode:#06x}"); - for &(other, other_octet, other_bit, _) in &policy::FORWARDED[index + 1..] { + for &(other, other_octet, other_bit, _, _) in &policy::FORWARDED[index + 1..] { assert_ne!(other, opcode); assert_ne!((other_octet, other_bit), (octet, bit), "{opcode:#06x}"); } } } +/// A listed command goes to the controller only with its specification's +/// parameter length; any other is the shadow's, so the controller never +/// reads past what the guest sent or takes bytes no field names. +#[test] +fn a_listed_command_of_another_parameter_length_is_the_shadows() { + for &(opcode, _, _, length, _) in policy::FORWARDED { + let length = usize::from(length); + // Read Local Extended Features forwards pages 0 and 1. + let page = u8::from(opcode == 0x1004); + let mut parameters = vec![0; length]; + if let Some(first) = parameters.first_mut() { + *first = page; + } + assert!( + policy::forward(&packet(opcode, ¶meters)).is_some(), + "{opcode:#06x}" + ); + for other in [length.wrapping_sub(1), length + 1] { + if other > 255 { + continue; + } + let wrong = packet(opcode, &vec![page; other]); + assert!(policy::forward(&wrong).is_none(), "{opcode:#06x} {other}"); + let mut bridge = Bridge::new(ADDRESS); + for step in bridge.command(&wrong, 0) { + assert!(matches!(step, Step::Guest(_)), "{opcode:#06x} {other}"); + } + } + } + // A header that disagrees with the packet's length. + let mut mask = packet(0x0c01, &[0xff; 8]); + mask[2] = 7; + assert!(policy::forward(&mask).is_none()); +} + #[test] fn one_command_is_in_flight_and_the_next_waits_its_turn() { let mut bridge = Bridge::new(ADDRESS); @@ -181,7 +216,7 @@ fn a_deadline_gives_the_shadows_answer_and_falls_back_for_good() { ); assert_eq!( bridge.fallen().unwrap().to_string(), - "0x0c03 no answer in 1 s" + "0x0c03 no answer in 1000 ms" ); // The late answer, and every event after, is dropped. assert!( @@ -542,20 +577,77 @@ fn the_shadow_follows_the_controllers_procedures_and_address() { /// In milestone 1 every connection is the shadow's, so ACL data from the /// guest names none of the controller's: the shadow returns its buffer. -/// The controller's ACL data reaches the guest while the bridge forwards. +/// The controller's ACL data names none the guest knows, so it is dropped, +/// whether the bridge forwards, keeps the controller out or fell back. #[test] -fn acl_from_the_guest_is_the_shadows_and_the_controllers_passes() { +fn acl_from_the_guest_is_the_shadows_and_the_controllers_is_dropped() { let mut bridge = Bridge::new(ADDRESS); assert_eq!( events(bridge.acl(&[0x40, 0x20, 2, 0, 9, 9])), [vec![0x13, 5, 1, 0x40, 0, 1, 0]] ); - assert!(bridge.chip_acl()); + assert!(!bridge.chip_acl()); bridge.resync(); - assert!(!bridge.chip_acl(), "until the next reset"); + assert!(!bridge.chip_acl()); let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(&packet(0x0c03, &[]), 0)); + events(bridge.chip_event(&complete(0x0c03, 1, 0, &[]), 0)); + assert!(!bridge.chip_acl(), "after the reset is answered too"); events(bridge.chip_failed(0)); assert!(!bridge.chip_acl()); + assert_eq!(bridge.counters().dropped, 2); + assert_eq!(bridge.counters().passed, 1, "the reset's answer alone"); +} + +/// A Hardware Error says the controller's firmware failed: the bridge falls +/// back, the command in flight gets the shadow's answer and the procedures +/// the controller ran end, and the guest, whose controller the model now +/// is, never sees the error. +#[test] +fn a_hardware_error_falls_back_with_the_answer_in_flight() { + let mut bridge = Bridge::new(ADDRESS); + chip(bridge.command(&packet(0x0401, &[0x33, 0x8b, 0x9e, 8, 0]), 0)); + events(bridge.chip_event(&status(0x0401, 1, 0), 0)); + chip(bridge.command(&packet(0x0c14, &[]), 0)); + let steps = events(bridge.chip_event(&[0x10, 1, 0x2a], 0)); + assert_eq!(steps.len(), 2, "{steps:02x?}"); + assert_eq!(steps[0][..6], [COMMAND_COMPLETE, 252, 1, 0x14, 0x0c, 0]); + assert_eq!(steps[1], [0x01, 1, 0], "the inquiry ends"); + assert!(steps.iter().all(|e| e[0] != 0x10)); + let fallback = bridge.fallen().expect("fell back"); + assert_eq!( + (fallback.opcode, fallback.cause), + (Some(0x0c14), Cause::HardwareError(0x2a)) + ); + assert_eq!( + fallback.to_string(), + "0x0c14 the host controller reported Hardware Error 0x2a" + ); + // Nothing reaches the controller again. + events(bridge.command(&packet(0x0c03, &[]), 0)); + // Between commands, and while the controller is kept out, alike. + let mut bridge = Bridge::new(ADDRESS); + bridge.resync(); + assert!(events(bridge.chip_event(&[0x10, 1, 0], 0)).is_empty()); + assert_eq!( + bridge.fallen().map(|f| (f.opcode, f.cause)), + Some((None, Cause::HardwareError(0))) + ); +} + +/// The log's words for the deadline and the restarts are the constants'. +#[test] +fn the_causes_name_the_deadline_and_restarts_the_bridge_uses() { + assert_eq!(DEADLINE_MS * FREQUENCY_HZ, DEADLINE * 1000); + assert_eq!( + Cause::Timeout.to_string(), + alloc::format!("no answer in {DEADLINE_MS} ms") + ); + assert!( + Cause::Restarted + .to_string() + .contains(&alloc::format!("controller {RESTARTS} times after")) + ); } /// A fallback ends what the controller was running: the guest saw the @@ -636,7 +728,7 @@ fn bluetoothd_restarting_twice_after_its_start_up_falls_back() { ); assert_eq!( fallback.to_string(), - "0x0c03 bluetoothd reset the controller twice after its start-up, \ + "0x0c03 bluetoothd reset the controller 2 times after its start-up, \ as it does when it rejects the bring-up" ); assert_eq!(bridge.counters().restarts, 2); From ac6a2a87f1e110277234e3413e8027b770c03df1 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:14:32 +0000 Subject: [PATCH 15/18] fix(bluetooth): refill the --bluetooth-trace capture's budget of 1024 packets at most for the boot's first 4 configurations, and say once when the boot's capture is over, where every new configuration refilled it, so a guest that configured the function again and again filled the boot log without end --- crates/stela-soc/src/usb/hci.rs | 45 ++++++- crates/stela-soc/src/usb/hci/capture.rs | 149 ++++++++++++++++++++---- 2 files changed, 170 insertions(+), 24 deletions(-) diff --git a/crates/stela-soc/src/usb/hci.rs b/crates/stela-soc/src/usb/hci.rs index 7a891f365c..058a077e58 100644 --- a/crates/stela-soc/src/usb/hci.rs +++ b/crates/stela-soc/src/usb/hci.rs @@ -146,6 +146,10 @@ pub enum Traced { Ended, /// The capture (`capture`) took its packets for this configuration. CaptureEnded, + /// The capture took its packets of the boot's last configuration it + /// captures (`capture::CAPTURED_CONFIGURATIONS`), or another came after + /// it. + CaptureOver, } /// The event that answered a traced command. @@ -253,6 +257,13 @@ impl core::fmt::Display for Traced { "capture ends after {} packets until the next configuration", capture::CAPTURED_PACKETS ), + Self::CaptureOver => write!( + f, + "capture ends for this boot: at most {} packets of each of its first {} \ + configurations", + capture::CAPTURED_PACKETS, + capture::CAPTURED_CONFIGURATIONS + ), } } } @@ -691,8 +702,15 @@ impl State { } fn captured(&mut self, direction: capture::Direction, kind: capture::Kind, packet: &[u8]) { - if self.capture.record(direction, kind, packet) { - self.trace(Traced::CaptureEnded); + let end = self.capture.record(direction, kind, packet); + self.capture_ended(end); + } + + fn capture_ended(&mut self, end: Option) { + match end { + Some(capture::End::Configuration) => self.trace(Traced::CaptureEnded), + Some(capture::End::Boot) => self.trace(Traced::CaptureOver), + None => {} } } @@ -921,7 +939,8 @@ impl Requests for State { } else { (TRACED_COMMANDS, TRACED_BRING_UPS) }; - self.capture.configured(value); + let end = self.capture.configured(value); + self.capture_ended(end); self.halted = [false; 3]; self.sco_setting = 0; self.outbound.clear(); @@ -1593,6 +1612,26 @@ mod tests { let mut hci = configured(hci); command(&mut hci, &[0x09, 0x10, 0]).unwrap(); assert_eq!(hci.take_captured().len(), 2, "still asked for"); + read(&mut hci, EVENTS, EVENT_PACKET); + // That was the third configuration captured; the fourth is the + // boot's last, and the fifth says so. + hci.take_trace(); + for _ in 0..3 { + transfer(&mut hci, setup(0, SET_CONFIGURATION, 1, 0, 0), &[]).unwrap(); + } + let traced = hci.take_trace(); + assert_eq!( + traced.iter().filter(|&&t| t == Traced::CaptureOver).count(), + 1, + "{traced:?}" + ); + command(&mut hci, &[0x09, 0x10, 0]).unwrap(); + assert!(hci.take_captured().is_empty()); + assert_eq!( + Traced::CaptureOver.to_string(), + "capture ends for this boot: at most 1024 packets of each of its first 4 \ + configurations" + ); } /// A packet longer than the capture shows keeps its first bytes and diff --git a/crates/stela-soc/src/usb/hci/capture.rs b/crates/stela-soc/src/usb/hci/capture.rs index 7ab90c105a..5dec204e03 100644 --- a/crates/stela-soc/src/usb/hci/capture.rs +++ b/crates/stela-soc/src/usb/hci/capture.rs @@ -8,8 +8,8 @@ //! bytes cut, which [`Captured::parse`] reads back. Packets carry no H4 //! indicator: the USB transport has none (Bluetooth Core v5.4 Vol 4 Part //! B 2), so the kind names it. The capture holds at most -//! [`CAPTURED_PACKETS`] packets per configuration, and none unless the owner -//! asks for it. +//! [`CAPTURED_PACKETS`] packets per configuration, of the boot's first +//! [`CAPTURED_CONFIGURATIONS`], and none unless the owner asks for it. //! //! A packet is masked as it is captured ([`Captured::new`], `mask`), so no //! raw byte leaves the function: its headers and the parameters that say @@ -185,6 +185,23 @@ pub fn read(text: &str) -> Result, usize> { .collect() } +/// Configurations captured in a boot. Each refills the budget of +/// [`CAPTURED_PACKETS`]; a guest that configures the function again and +/// again (a daemon restarting, a reset loop) would otherwise fill the boot +/// log without end. +pub const CAPTURED_CONFIGURATIONS: u8 = 4; + +/// Where the capture stopped, for the owner's log. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum End { + /// This configuration's packets were taken; the next configuration + /// starts again. + Configuration, + /// The boot's last configuration to be captured ended, or one came + /// after it. + Boot, +} + /// What the function captures, and what it holds until the owner takes it. #[derive(Debug, Clone, Default)] pub(super) struct Capture { @@ -192,6 +209,10 @@ pub(super) struct Capture { enabled: bool, /// Packets still captured in this configuration. left: u16, + /// Configurations captured so far. + configurations: u8, + /// Whether the boot's capture is over and the log was told. + over: bool, held: Vec, } @@ -202,30 +223,58 @@ impl Capture { if !self.enabled { self.enabled = true; if configured { - self.left = CAPTURED_PACKETS; + self.start(); } } } - /// The guest set the configuration to `value` (0: unconfigured). - pub(super) fn configured(&mut self, value: u8) { - self.left = if self.enabled && value != 0 { - CAPTURED_PACKETS - } else { - 0 - }; + /// A configuration's budget, while the boot has one left. + fn start(&mut self) -> Option { + if self.configurations < CAPTURED_CONFIGURATIONS { + self.configurations += 1; + self.left = CAPTURED_PACKETS; + return None; + } + self.left = 0; + self.over().then_some(End::Boot) } - /// Captures `packet`; true when it was this configuration's last. - pub(super) fn record(&mut self, direction: Direction, kind: Kind, packet: &[u8]) -> bool { + /// Whether the boot's capture is over just now, said once. + fn over(&mut self) -> bool { + !core::mem::replace(&mut self.over, true) + } + + /// The guest set the configuration to `value` (0: unconfigured); `Some` + /// when the capture is over for the boot, once. + pub(super) fn configured(&mut self, value: u8) -> Option { + if !self.enabled || value == 0 { + self.left = 0; + return None; + } + self.start() + } + + /// Captures `packet`; `Some` when it was this configuration's last. + pub(super) fn record( + &mut self, + direction: Direction, + kind: Kind, + packet: &[u8], + ) -> Option { if self.left == 0 { - return false; + return None; } self.left -= 1; if self.held.len() < usize::from(CAPTURED_PACKETS) { self.held.push(Captured::new(direction, kind, packet)); } - self.left == 0 + if self.left != 0 { + return None; + } + if self.configurations < CAPTURED_CONFIGURATIONS { + return Some(End::Configuration); + } + self.over().then_some(End::Boot) } pub(super) fn take(&mut self) -> Vec { @@ -507,18 +556,33 @@ mod tests { #[test] fn the_capture_holds_its_bound_per_configuration_and_only_once_asked() { let mut capture = Capture::default(); - capture.configured(1); - assert!(!capture.record(Direction::FromGuest, Kind::Command, &[3, 0x0c, 0])); + assert_eq!(capture.configured(1), None); + assert_eq!( + capture.record(Direction::FromGuest, Kind::Command, &[3, 0x0c, 0]), + None + ); assert!(capture.take().is_empty()); capture.enable(true); for _ in 1..CAPTURED_PACKETS { - assert!(!capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0])); + assert_eq!( + capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0]), + None + ); } - assert!(capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0])); - assert!(!capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0])); + assert_eq!( + capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0]), + Some(End::Configuration) + ); + assert_eq!( + capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0]), + None + ); assert_eq!(capture.take().len(), usize::from(CAPTURED_PACKETS)); - capture.configured(0); - assert!(!capture.record(Direction::FromGuest, Kind::Command, &[3, 0x0c, 0])); + assert_eq!(capture.configured(0), None); + assert_eq!( + capture.record(Direction::FromGuest, Kind::Command, &[3, 0x0c, 0]), + None + ); capture.configured(1); capture.record(Direction::FromGuest, Kind::Command, &[3, 0x0c, 0]); assert_eq!( @@ -530,4 +594,47 @@ mod tests { )] ); } + + /// A guest that configures the function again and again gets its first + /// [`CAPTURED_CONFIGURATIONS`] captured, then none: the budget refills + /// per configuration, but not without end, and the end is said once. + #[test] + fn the_capture_refills_for_a_bounded_number_of_configurations() { + let mut capture = Capture::default(); + capture.enable(true); + let command = [3, 0x0c, 0]; + for _ in 1..CAPTURED_CONFIGURATIONS { + capture.record(Direction::FromGuest, Kind::Command, &command); + assert_eq!(capture.configured(1), None); + } + // The last configuration captured: its budget's end is the boot's. + for _ in 1..CAPTURED_PACKETS { + capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0]); + } + assert_eq!( + capture.record(Direction::ToGuest, Kind::Event, &[0x0e, 0]), + Some(End::Boot) + ); + assert_eq!(capture.configured(1), None, "said once"); + assert_eq!( + capture.record(Direction::FromGuest, Kind::Command, &command), + None + ); + let held = capture.take(); + assert_eq!(held.len(), usize::from(CAPTURED_PACKETS)); + // Reconfigured before the last budget ran out: the next + // configuration says the end. + let mut capture = Capture::default(); + capture.enable(true); + for _ in 1..CAPTURED_CONFIGURATIONS { + assert_eq!(capture.configured(1), None); + } + assert_eq!(capture.configured(1), Some(End::Boot)); + assert_eq!(capture.configured(1), None); + assert_eq!( + capture.record(Direction::FromGuest, Kind::Command, &command), + None + ); + assert!(capture.take().is_empty()); + } } From cabf150f372db5ac9a775fc1ad73b8cb994a8b42 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:15:09 +0000 Subject: [PATCH 16/18] fix(bluetooth): hide every captured byte past the length a packet's header declares, the extended inquiry or advertising data from a structure that runs past the data's end, and all but the count of an event with several inquiry results or advertising reports, where the capture's rules showed trailing bytes to the frame's end, read a bad length's following bytes out of step as plain structures, and assumed the reports' arrays came device by device, which would show another device's address bytes if they came parameter by parameter --- crates/stela-soc/src/usb/hci/capture.rs | 107 +++++++++++++++++++ crates/stela-soc/src/usb/hci/capture/mask.rs | 86 ++++++++++----- 2 files changed, 165 insertions(+), 28 deletions(-) diff --git a/crates/stela-soc/src/usb/hci/capture.rs b/crates/stela-soc/src/usb/hci/capture.rs index 5dec204e03..065f3522b4 100644 --- a/crates/stela-soc/src/usb/hci/capture.rs +++ b/crates/stela-soc/src/usb/hci/capture.rs @@ -515,6 +515,113 @@ mod tests { ); } + /// Extended inquiry data with a structure whose length runs past the + /// data's end: from there no structure's start can be trusted, so it + /// and all after it stay hidden, a plain type's data too. + #[test] + fn a_structure_past_the_datas_end_hides_the_rest() { + let mut eir = vec![3, 0x03, 0x0b, 0x11, 240, 0x03]; + eir.extend_from_slice(NAME); + eir.resize(240, 0x77); + let mut write = vec![0x52, 0x0c, 241, 0]; + write.extend_from_slice(&eir); + let captured = Captured::new(Direction::FromGuest, Kind::Command, &write); + assert!(!holds(&captured, NAME), "{captured}"); + assert!(captured.hidden[8..].iter().all(|&h| h), "{captured}"); + assert!( + captured + .to_string() + .starts_with("> cmd 52 0c f1 00 03 03 0b 11 xx xx xx"), + "{captured}" + ); + // The same past the event's end in an extended inquiry result. + let mut result = vec![0x2f, 255, 1]; + result.extend_from_slice(&NEIGHBOUR); + result.extend_from_slice(&[1, 0, 0x04, 0x04, 0x24, 0x34, 0x12, 0xd0]); + result.extend_from_slice(&eir); + let captured = Captured::new(Direction::FromChip, Kind::Event, &result); + assert!(!holds(&captured, NAME), "{captured}"); + assert!(captured.hidden[21..].iter().all(|&h| h), "{captured}"); + } + + /// Several inquiry results in one event may be laid out device by device + /// or parameter by parameter; a rule for either would show the other's + /// address bytes, so only the count shows. One reads the same both ways. + #[test] + fn several_inquiry_results_in_one_event_show_only_their_count() { + const OTHER: [u8; 6] = [0x20, 0xc7, 0xc8, 0x40, 0x41, 0x42]; + for code in [0x02u8, 0x22] { + // Two responses, parameter by parameter: both addresses first. + let mut arrays = vec![code, 29, 2]; + arrays.extend_from_slice(&NEIGHBOUR); + arrays.extend_from_slice(&OTHER); + arrays.extend_from_slice(&[1, 1, 0, 0, 0, 0, 4, 4, 0x24, 4, 4, 0x24, 1, 2, 3, 4]); + let captured = Captured::new(Direction::FromChip, Kind::Event, &arrays); + for secret in [&NEIGHBOUR[1..3], &OTHER[1..3]] { + assert!(!holds(&captured, secret), "{captured}"); + } + assert!(!captured.hidden[..3].contains(&true)); + assert!(captured.hidden[3..].iter().all(|&h| h), "{captured}"); + // One response: its address's ends and the rest. + let mut one = vec![code, 15, 1]; + one.extend_from_slice(&NEIGHBOUR); + one.extend_from_slice(&[1, 0, 0, 0x04, 0x04, 0x24, 0x34, 0x12]); + let line = Captured::new(Direction::FromChip, Kind::Event, &one).to_string(); + assert!( + line.ends_with(" 01 10 xx xx 30 31 32 01 00 00 04 04 24 34 12"), + "{line}" + ); + } + // Two LE advertising reports: the count alone. + let mut reports = vec![0x3e, 0, 0x02, 2, 0, 0, 0, 0]; + reports.extend_from_slice(&NEIGHBOUR); + reports.extend_from_slice(&OTHER); + reports.extend_from_slice(&[0, 0, 0xc0, 0xc1]); + reports[1] = (reports.len() - 2) as u8; + let captured = Captured::new(Direction::FromChip, Kind::Event, &reports); + assert!(!holds(&captured, &OTHER[1..3]), "{captured}"); + assert!(captured.hidden[4..].iter().all(|&h| h), "{captured}"); + // One report: types, the address's ends, the data's length, RSSI. + let mut report = vec![0x3e, 0, 0x02, 1, 0, 1]; + report.extend_from_slice(&NEIGHBOUR); + report.extend_from_slice(&[3, 0x02, 0x01, 0x06, 0xc5]); + report[1] = (report.len() - 2) as u8; + assert_eq!( + Captured::new(Direction::FromChip, Kind::Event, &report).to_string(), + "chip< evt 3e 0f 02 01 00 01 10 xx xx 30 31 32 03 xx xx xx c5" + ); + } + + /// A rule's "the rest" ends where the header says the packet does: bytes + /// trailing past the declared length are hidden, even after a plain + /// command's or event's parameters. + #[test] + fn bytes_past_the_declared_length_are_hidden() { + let command = [0x45, 0x0c, 1, 2, 0x99, 0x98]; + assert_eq!( + Captured::new(Direction::FromGuest, Kind::Command, &command).to_string(), + "> cmd 45 0c 01 02 xx xx" + ); + let event = [0x13, 5, 1, 0x40, 0, 1, 0, 0x99, 0x98]; + assert_eq!( + Captured::new(Direction::FromChip, Kind::Event, &event).to_string(), + "chip< evt 13 05 01 40 00 01 00 xx xx" + ); + let mut request = vec![0x19, 0x04, 6]; + request.extend_from_slice(&NEIGHBOUR); + request.extend_from_slice(&[1, 0, 0x34, 0x12]); + assert_eq!( + Captured::new(Direction::ToChip, Kind::Command, &request).to_string(), + "chip> cmd 19 04 06 10 xx xx 30 31 32 xx xx xx xx" + ); + // An ACL packet shorter than an L2CAP header shows its own bytes. + let acl = [0x01, 0x20, 2, 0, 9, 9, 0x99, 0x98]; + assert_eq!( + Captured::new(Direction::FromChip, Kind::Acl, &acl).to_string(), + "chip< acl 01 20 02 00 09 09 xx xx" + ); + } + #[test] fn other_text_is_no_captured_packet() { for bad in [ diff --git a/crates/stela-soc/src/usb/hci/capture/mask.rs b/crates/stela-soc/src/usb/hci/capture/mask.rs index f084ddf9a6..dd4b9f850f 100644 --- a/crates/stela-soc/src/usb/hci/capture/mask.rs +++ b/crates/stela-soc/src/usb/hci/capture/mask.rs @@ -20,7 +20,13 @@ //! Long Term Key Request Reply, LE Add Device To Resolving List, the local //! OOB data reads' returns, Return Link Keys, Link Key Notification and LE //! Generate DHKey Complete; -//! - anything of a command, return or event no rule names. +//! - anything of a command, return or event no rule names, and every byte +//! past the length its header declares; +//! - of an event with several inquiry results or advertising reports, +//! everything past the count: their arrays may come device by device or +//! parameter by parameter; +//! - extended inquiry or advertising data from a structure that runs past +//! the data's end. //! //! Evidence: Bluetooth Core v5.4 Vol 4 Part E 5.4 (packet formats), 7.1-7.8 //! (parameters) and 7.7 (events); Vol 3 Part C 11 and the Assigned Numbers' @@ -61,18 +67,35 @@ const VENDOR_GROUP: u16 = 0x3f; struct Mask<'a> { packet: &'a [u8], hidden: Vec, + /// Where the packet's header says it ends, or its own end if that is + /// sooner: no rule shows a byte past it, whatever trails there. + end: usize, +} + +/// Where `packet`'s header says it ends: its header and the parameter or +/// data length the header gives (Vol 4 Part E 5.4). +fn declared_end(kind: super::Kind, packet: &[u8]) -> usize { + let declared = match kind { + super::Kind::Command => packet.get(2).map(|&length| 3 + usize::from(length)), + super::Kind::Event => packet.get(1).map(|&length| 2 + usize::from(length)), + super::Kind::Acl => packet + .get(2..4) + .map(|length| 4 + usize::from(u16::from_le_bytes([length[0], length[1]]))), + }; + declared.unwrap_or(packet.len()).min(packet.len()) } impl Mask<'_> { fn show(&mut self, range: Range) { - let end = range.end.min(self.hidden.len()); + let end = range.end.min(self.end); if range.start < end { self.hidden[range.start..end].fill(false); } } + /// The parameters from `from` to the declared end. fn rest(&mut self, from: usize) { - self.show(from..self.packet.len()); + self.show(from..self.end); } /// An address at `at`: its last byte and vendor half. @@ -82,21 +105,26 @@ impl Mask<'_> { } /// Extended inquiry or advertising data in `range`: each structure's - /// length and type, and the data of the plain types. + /// length and type, and the data of the plain types, up to the first + /// structure of length 0, which ends the significant part (Vol 3 Part C + /// 11). A structure that runs past the data's end is malformed: it and + /// everything after it stay hidden, since no length read from there on + /// can be trusted to fall on a structure's start. fn data(&mut self, range: Range) { - let end = range.end.min(self.packet.len()); + let end = range.end.min(self.end); let mut at = range.start; while at < end { let length = usize::from(self.packet[at]); - self.show(at..at + 1); if length == 0 { + self.show(at..at + 1); return; } - if let Some(&kind) = self.packet.get(at + 1) { - self.show(at + 1..at + 2); - if PLAIN_AD.contains(&kind) { - self.show(at + 2..(at + 1 + length).min(end)); - } + if at + 1 + length > end { + return; + } + self.show(at..at + 2); + if PLAIN_AD.contains(&self.packet[at + 1]) { + self.show(at + 2..at + 1 + length); } at += 1 + length; } @@ -171,13 +199,16 @@ impl Mask<'_> { } 0x0f => self.show(2..6), // Inquiry Result (14 bytes a device), with RSSI (14 as well). + // Their parameters are arrays, which a controller may send + // device by device (as Linux's `inquiry_info` reads them) or + // parameter by parameter: one response reads the same either + // way, but of several only the count shows, since a rule for one + // layout would show the other's address bytes. 0x02 | 0x22 => { self.show(2..3); - let count = usize::from(self.packet.get(2).copied().unwrap_or(0)); - for device in 0..count { - let at = 3 + 14 * device; - self.address(at); - self.show(at + 6..at + 14); + if self.packet.get(2) == Some(&1) { + self.address(3); + self.show(9..17); } } // Extended Inquiry Result: one device, then its EIR. @@ -219,20 +250,18 @@ impl Mask<'_> { self.address(8); self.rest(14); } - // LE Advertising Report: per report the event and address - // types, the address, the data's length, hidden data, the RSSI. + // LE Advertising Report: the event and address types, the + // address, the data's length, hidden data, the RSSI. Its + // parameters are arrays too, so as for an inquiry result only + // one report shows past the count. Some(0x02) => { self.show(3..4); - let count = usize::from(self.packet.get(3).copied().unwrap_or(0)); - let mut at = 4; - for _ in 0..count { - self.show(at..at + 2); - self.address(at + 2); - let length = usize::from(self.packet.get(at + 8).copied().unwrap_or(0)); - self.show(at + 8..at + 9); - at += 9 + length; - self.show(at..at + 1); - at += 1; + if self.packet.get(3) == Some(&1) { + self.show(4..6); + self.address(6); + self.show(12..13); + let length = usize::from(self.packet.get(12).copied().unwrap_or(0)); + self.show(13 + length..14 + length); } } // Others show their status alone, as LE Generate DHKey Complete. @@ -259,6 +288,7 @@ pub(super) fn hidden(kind: super::Kind, packet: &[u8]) -> Vec { let mut mask = Mask { packet, hidden: vec![true; packet.len()], + end: declared_end(kind, packet), }; match kind { super::Kind::Command => mask.command(), From 4594332f15f3ed9b975152c1484417710b17f198 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:16:21 +0000 Subject: [PATCH 17/18] fix(boot): say why --bluetooth-lend lends nothing when the boot has no --input or no host Bluetooth controller started, as it already said for --idle-skip, where the flag was dropped without a word --- crates/stela-boot-core/src/guest_bluetooth.rs | 58 +++++++++++++++---- crates/stela-boot/src/engine/bluetooth.rs | 15 +++-- 2 files changed, 59 insertions(+), 14 deletions(-) diff --git a/crates/stela-boot-core/src/guest_bluetooth.rs b/crates/stela-boot-core/src/guest_bluetooth.rs index 7edbca3f82..3325834747 100644 --- a/crates/stela-boot-core/src/guest_bluetooth.rs +++ b/crates/stela-boot-core/src/guest_bluetooth.rs @@ -22,11 +22,26 @@ pub const TRACE_LINE: &str = "BLUETOOTH TRACE the guest's Bluetooth packets are until it has been checked\n"; /// Why a boot that asks to lend the host's controller (`--bluetooth-lend`) -/// gives the guest the model instead, as its log line; `None` when nothing -/// stops it. Under `--idle-skip` the guest's clock leaps over waits to the -/// next deadline, and the bridge's wait for the controller's answer is one -/// in guest time, so every forwarded command would fall back at once. -pub fn lend_refusal(idle_skip: bool) -> Option<&'static str> { +/// does not, as its log line; `None` when nothing stops it, so the flag is +/// never ignored without a word. A boot without `--input` gives the guest +/// no Bluetooth controller at all; a host with no controller that started +/// has none to lend; and under `--idle-skip` the guest's clock leaps over +/// waits to the next deadline, and the bridge's wait for the controller's +/// answer is one in guest time, so every forwarded command would fall back +/// at once. +pub fn lend_refusal(input: bool, host_controller: bool, idle_skip: bool) -> Option<&'static str> { + if !input { + return Some( + "BLUETOOTH LEND not lent: the boot has no --input, so the guest has no Bluetooth \ + controller\n", + ); + } + if !host_controller { + return Some( + "BLUETOOTH LEND not lent: no host Bluetooth controller started, so the model \ + answers alone\n", + ); + } idle_skip.then_some( "BLUETOOTH LEND not lent: --idle-skip leaps the guest's clock over the bridge's wait \ for the controller's answers, so the model answers alone\n", @@ -73,18 +88,41 @@ mod tests { } /// Under `--idle-skip` the guest's clock leaps to the next deadline, the - /// bridge's 1 s wait for the controller among them, so a lent - /// controller would fall back at once: it is not lent, and the log says - /// why. + /// bridge's wait for the controller among them, so a lent controller + /// would fall back at once: it is not lent, and the log says why. #[test] fn idle_skip_keeps_the_controller_from_being_lent_and_says_why() { - assert_eq!(lend_refusal(false), None); - let line = lend_refusal(true).expect("refused"); + assert_eq!(lend_refusal(true, true, false), None); + let line = lend_refusal(true, true, true).expect("refused"); assert!(line.starts_with("BLUETOOTH LEND not lent: --idle-skip ")); assert!(line.contains("model")); assert!(line.ends_with('\n') && line.matches('\n').count() == 1); } + /// `--bluetooth-lend` is never dropped without a word: a boot without + /// host input, or a host with no controller that started, says why + /// nothing is lent, before `--idle-skip` is weighed. + #[test] + fn a_lend_with_no_input_or_no_controller_says_why_it_is_not_lent() { + for idle_skip in [false, true] { + let line = lend_refusal(false, true, idle_skip).expect("refused"); + assert!(line.starts_with("BLUETOOTH LEND not lent: the boot has no --input")); + assert_eq!(lend_refusal(false, false, idle_skip), Some(line)); + let line = lend_refusal(true, false, idle_skip).expect("refused"); + assert!(line.starts_with("BLUETOOTH LEND not lent: no host Bluetooth controller")); + assert!(line.contains("model")); + } + for input in [false, true] { + for host_controller in [false, true] { + for idle_skip in [false, true] { + let line = lend_refusal(input, host_controller, idle_skip); + assert_eq!(line.is_none(), input && host_controller && !idle_skip); + assert!(line.is_none_or(|l| l.ends_with('\n') && l.matches('\n').count() == 1)); + } + } + } + } + /// `--bluetooth-trace` says once what its lines hide and that the log /// still needs checking before it is posted. #[test] diff --git a/crates/stela-boot/src/engine/bluetooth.rs b/crates/stela-boot/src/engine/bluetooth.rs index 2b0313c936..ff3a9068e7 100644 --- a/crates/stela-boot/src/engine/bluetooth.rs +++ b/crates/stela-boot/src/engine/bluetooth.rs @@ -252,17 +252,24 @@ impl HostBluetooth { /// BlueTool's chip boot and bluetoothd's bring-up do not take. With /// `--bluetooth-lend` it is lent behind the module, which answers those /// itself and falls back to the model on any failure, unless the boot - /// leaps the guest's clock (`--idle-skip`). One not kept is released in - /// the loader's root by its drop. + /// has no host input or controller to lend, or leaps the guest's clock + /// (`--idle-skip`), which the log then says. One not kept is released + /// in the loader's root by its drop. pub fn guest(controller: Option, options: &System, root: u64) -> Option { let refused = options .bluetooth_lend - .then(|| stela_boot_core::guest_bluetooth::lend_refusal(options.idle_skip)) + .then(|| { + stela_boot_core::guest_bluetooth::lend_refusal( + options.input, + controller.is_some(), + options.idle_skip, + ) + }) .flatten(); if let Some(line) = refused { output::arguments(format_args!("{line}")); } - let lend = options.input && options.bluetooth_lend && refused.is_none(); + let lend = options.bluetooth_lend && refused.is_none(); let mut guest = match controller { Some(mut lent) if lend => { let line = stela_boot_core::guest_bluetooth::lend_line(&lent.location); From 32b361e88ab649f16ab32b5f5d1217cd50f2ab57 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:17:44 +0000 Subject: [PATCH 18/18] fix(drivers): print a Bluetooth controller's bytes in no failure line, Display or Debug: a Qualcomm controller dump's packet, a Broadcom PCIe frame, event and return, an Intel PCIe frame, a Realtek response and a MediaTek dump show their lengths, an Intel identity's or boot parameters' address its vendor half and last byte and its TLVs their lengths, and every initializer's failure and the lent controller's transport errors print any other byte list as its length, where BLUETOOTH FAILED lines printed controller RAM, which can hold link keys, raw frames that can name neighbours, and the controller's full address through Debug --- crates/stela-boot/src/engine/bluetooth.rs | 8 +- crates/stela-drivers/src/bluetooth.rs | 1 + crates/stela-drivers/src/bluetooth/bcm4377.rs | 86 ++++- crates/stela-drivers/src/bluetooth/intel.rs | 5 +- .../src/bluetooth/intel/identity.rs | 33 +- .../src/bluetooth/intel/tests.rs | 14 +- .../stela-drivers/src/bluetooth/intel/tlv.rs | 33 +- .../stela-drivers/src/bluetooth/intel_pcie.rs | 40 ++- .../src/bluetooth/intel_pcie/packet.rs | 16 +- .../stela-drivers/src/bluetooth/redacted.rs | 324 ++++++++++++++++++ crates/stela-drivers/src/usb/bluetooth.rs | 22 +- .../stela-drivers/src/usb/bluetooth/ath3k.rs | 6 +- .../src/usb/bluetooth/ath3k/runtime.rs | 6 +- .../src/usb/bluetooth/broadcom.rs | 6 +- .../src/usb/bluetooth/broadcom/diagnostics.rs | 6 +- .../src/usb/bluetooth/initialization.rs | 6 +- .../src/usb/bluetooth/intel/bulk_iso.rs | 6 +- .../src/usb/bluetooth/mediatek.rs | 6 +- .../src/usb/bluetooth/mediatek/coredump.rs | 16 +- .../src/usb/bluetooth/mediatek/media.rs | 6 +- crates/stela-drivers/src/usb/bluetooth/qca.rs | 6 +- .../src/usb/bluetooth/realtek.rs | 47 ++- 22 files changed, 671 insertions(+), 28 deletions(-) create mode 100644 crates/stela-drivers/src/bluetooth/redacted.rs diff --git a/crates/stela-boot/src/engine/bluetooth.rs b/crates/stela-boot/src/engine/bluetooth.rs index ff3a9068e7..2f6b99d4db 100644 --- a/crates/stela-boot/src/engine/bluetooth.rs +++ b/crates/stela-boot/src/engine/bluetooth.rs @@ -80,7 +80,7 @@ impl HostController for Controller { transport .send(kind, bytes) .map(|_| true) - .map_err(|error| format!("{error:?}")) + .map_err(|error| format!("{error}")) } (Controller::Modeled, _) => Ok(true), (Controller::Broadcom(transport), packet) => { @@ -91,7 +91,7 @@ impl HostController for Controller { match transport.send(kind, bytes) { Ok(_) => Ok(true), Err(bcm4377::Error::QueueFull(_)) => Ok(false), - Err(error) => Err(format!("{error:?}")), + Err(error) => Err(format!("{error}")), } } } @@ -113,7 +113,7 @@ impl HostController for Controller { }) .collect() }) - .map_err(|error| format!("{error:?}")), + .map_err(|error| format!("{error}")), Controller::Broadcom(transport) => transport .poll() .map(|observations| { @@ -126,7 +126,7 @@ impl HostController for Controller { }) .collect() }) - .map_err(|error| format!("{error:?}")), + .map_err(|error| format!("{error}")), } } } diff --git a/crates/stela-drivers/src/bluetooth.rs b/crates/stela-drivers/src/bluetooth.rs index ce39d47c0b..a084df2f6a 100644 --- a/crates/stela-drivers/src/bluetooth.rs +++ b/crates/stela-drivers/src/bluetooth.rs @@ -4,3 +4,4 @@ pub mod bcm4377; pub(crate) mod hci; pub mod intel; pub mod intel_pcie; +pub(crate) mod redacted; diff --git a/crates/stela-drivers/src/bluetooth/bcm4377.rs b/crates/stela-drivers/src/bluetooth/bcm4377.rs index 7e3bd6a93e..aa07cf6b17 100644 --- a/crates/stela-drivers/src/bluetooth/bcm4377.rs +++ b/crates/stela-drivers/src/bluetooth/bcm4377.rs @@ -46,7 +46,7 @@ pub enum Space { Bar0, Bar2, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub enum Error { Unsupported(&'static str), Native(native::Error), @@ -90,9 +90,77 @@ pub enum Error { }, } pub type Result = core::result::Result; +/// The failure line prints no byte a frame or the controller's return held: +/// their lengths alone (`crate::bluetooth::redacted`). impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "Broadcom PCIe Bluetooth {self:?}") + let error = crate::bluetooth::redacted::Lists(self); + write!(f, "Broadcom PCIe Bluetooth {error}") + } +} +impl core::fmt::Debug for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + use crate::bluetooth::redacted::Bytes; + match self { + Self::Unsupported(what) => f.debug_tuple("Unsupported").field(what).finish(), + Self::Native(error) => f.debug_tuple("Native").field(error).finish(), + Self::Memory(error) => f.debug_tuple("Memory").field(error).finish(), + Self::Dma(error) => f.debug_tuple("Dma").field(error).finish(), + Self::Firmware(error) => f.debug_tuple("Firmware").field(error).finish(), + Self::Io { space, offset, raw } => f + .debug_struct("Io") + .field("space", space) + .field("offset", offset) + .field("raw", raw) + .finish(), + Self::Readback { + space, + offset, + observed, + } => f + .debug_struct("Readback") + .field("space", space) + .field("offset", offset) + .field("observed", observed) + .finish(), + Self::Protocol { + requirement, + observed, + } => f + .debug_struct("Protocol") + .field("requirement", requirement) + .field("observed", observed) + .finish(), + Self::Packet { kind, bytes } => f + .debug_struct("Packet") + .field("kind", kind) + .field("bytes", &Bytes(bytes)) + .finish(), + Self::Hci { requirement, bytes } => f + .debug_struct("Hci") + .field("requirement", requirement) + .field("bytes", &Bytes(bytes)) + .finish(), + Self::Controller { + opcode, + status, + returned, + } => f + .debug_struct("Controller") + .field("opcode", opcode) + .field("status", status) + .field("returned", &Bytes(returned)) + .finish(), + Self::State(state) => f.debug_tuple("State").field(state).finish(), + Self::Timeout(what) => f.debug_tuple("Timeout").field(what).finish(), + Self::QueueFull(ring) => f.debug_tuple("QueueFull").field(ring).finish(), + Self::ObservationLimit => f.write_str("ObservationLimit"), + Self::Cleanup { cause, cleanup } => f + .debug_struct("Cleanup") + .field("cause", cause) + .field("cleanup", cleanup) + .finish(), + } } } impl core::error::Error for Error {} @@ -114,7 +182,7 @@ pub enum State { Closed, Failed, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct Packet { pub kind: Kind, pub bytes: Vec, @@ -122,6 +190,18 @@ pub struct Packet { /// Entire completion footer, including original padding. pub footer: Vec, } +/// A packet prints its kind and lengths, never its bytes. +impl core::fmt::Debug for Packet { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + use crate::bluetooth::redacted::Bytes; + f.debug_struct("Packet") + .field("kind", &self.kind) + .field("bytes", &Bytes(&self.bytes)) + .field("completion", &Bytes(&self.completion)) + .field("footer", &Bytes(&self.footer)) + .finish() + } +} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Submission { pub ring: u16, diff --git a/crates/stela-drivers/src/bluetooth/intel.rs b/crates/stela-drivers/src/bluetooth/intel.rs index 83b8c5a5bc..45a93c8f2a 100644 --- a/crates/stela-drivers/src/bluetooth/intel.rs +++ b/crates/stela-drivers/src/bluetooth/intel.rs @@ -182,9 +182,12 @@ pub enum Error { cleanup: Box, }, } +/// The failure line prints no byte the controller sent: an identity's +/// address shows its vendor half and last byte, its TLVs their lengths, and +/// any other byte list its length (`super::redacted`). impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Intel Bluetooth {self:?}") + write!(f, "Intel Bluetooth {}", super::redacted::Lists(self)) } } impl core::error::Error for Error {} diff --git a/crates/stela-drivers/src/bluetooth/intel/identity.rs b/crates/stela-drivers/src/bluetooth/intel/identity.rs index a5b32d4663..0cd525aaa5 100644 --- a/crates/stela-drivers/src/bluetooth/intel/identity.rs +++ b/crates/stela-drivers/src/bluetooth/intel/identity.rs @@ -157,13 +157,27 @@ impl Identity { } } -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct BootParameters { pub device_revision: u16, pub minimum_build: [u8; 3], pub address: [u8; 6], raw: [u8; 23], } +/// The parameters print the controller's address as its vendor half and +/// last byte, and the raw read, which holds it, as its length +/// (`crate::bluetooth::redacted`). +impl core::fmt::Debug for BootParameters { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + use crate::bluetooth::redacted::{Address, Bytes}; + f.debug_struct("BootParameters") + .field("device_revision", &self.device_revision) + .field("minimum_build", &self.minimum_build) + .field("address", &Address(&self.address)) + .field("raw", &Bytes(&self.raw)) + .finish() + } +} impl BootParameters { #[expect( clippy::result_large_err, @@ -245,4 +259,21 @@ mod tests { unknown.descriptor[10] = 0xff; assert!(Identity::usb(&unknown).is_err()); } + + /// The boot parameters hold the controller's own address: printed, it + /// keeps its vendor half and last byte, and the raw read its length. + #[test] + fn boot_parameters_print_no_address_middle_or_raw_byte() { + let mut bytes = [0; 23]; + bytes[6] = 1; + // 32:31:30:b8:a7:10, a synthetic address, in HCI order. + bytes[12..18].copy_from_slice(&[0x10, 0xa7, 0xb8, 0x30, 0x31, 0x32]); + let boot = BootParameters::parse(&bytes).unwrap(); + let text = format!("{boot:?}"); + assert!(text.contains("address: 32:31:30:..:..:10"), "{text}"); + assert!(text.contains("raw: <23 bytes>"), "{text}"); + for secret in ["167", "184", "a7", "b8"] { + assert!(!text.contains(secret), "{text}"); + } + } } diff --git a/crates/stela-drivers/src/bluetooth/intel/tests.rs b/crates/stela-drivers/src/bluetooth/intel/tests.rs index b876a0223c..82c24963e5 100644 --- a/crates/stela-drivers/src/bluetooth/intel/tests.rs +++ b/crates/stela-drivers/src/bluetooth/intel/tests.rs @@ -1730,11 +1730,23 @@ mod iml_tests { let actual = ControllerIdentity::Tlv(TlvIdentity::parse(&device, &payload).unwrap()); script.steps[13].events[0].1 = complete(READ_VERSION, &payload); let mut hci = transport(device, script); + let error = initialize(&mut hci, &catalog).unwrap_err(); + // The failure line names the stages, never an identity's + // address middle or raw TLV bytes (0x30 and 0x90 here). + for text in [format!("{error}"), format!("{error:?}")] { + assert!(text.contains("RejectedBoot"), "{text}"); + for raw in ["1, 2, 3, 4, 5, 6", "165, 90", "06:05:04:03", "03:02:01"] { + assert!(!text.contains(raw), "{raw}: {text}"); + } + if text.contains("address: Some(") { + assert!(text.contains("06:05:04:..:..:01"), "{text}"); + } + } let Error::Stages { cause, completed, pending, - } = initialize(&mut hci, &catalog).unwrap_err() + } = error else { panic!("completed IML retained") }; diff --git a/crates/stela-drivers/src/bluetooth/intel/tlv.rs b/crates/stela-drivers/src/bluetooth/intel/tlv.rs index e183016cec..07b24792f8 100644 --- a/crates/stela-drivers/src/bluetooth/intel/tlv.rs +++ b/crates/stela-drivers/src/bluetooth/intel/tlv.rs @@ -23,7 +23,7 @@ const LIMITED_CCE: u8 = 0x2e; const SBE: u8 = 0x2f; const OTP_ADDRESS: u8 = 0x30; -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct TlvIdentity { pub transport: TransportIdentity, pub cnvi_top: u32, @@ -42,6 +42,37 @@ pub struct TlvIdentity { pub firmware_id: Option, fields: Vec<(u8, Vec)>, } +/// An identity prints its OTP address as its vendor half and last byte and +/// each TLV as its type and length: the address is the controller's own, +/// and a failure line (`Error::RejectedBoot`, `Error::Stages`) reaches the +/// boot log (`crate::bluetooth::redacted`). +impl core::fmt::Debug for TlvIdentity { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + use crate::bluetooth::redacted::{Address, Bytes}; + let fields: Vec<(u8, Bytes<'_>)> = self + .fields + .iter() + .map(|(kind, value)| (*kind, Bytes(value))) + .collect(); + f.debug_struct("TlvIdentity") + .field("transport", &self.transport) + .field("cnvi_top", &self.cnvi_top) + .field("cnvr_top", &self.cnvr_top) + .field("cnvi_bt", &self.cnvi_bt) + .field("cnvr_bt", &self.cnvr_bt) + .field("device_revision", &self.device_revision) + .field("image_type", &self.image_type) + .field("build", &self.build) + .field("build_number", &self.build_number) + .field("secure_boot", &self.secure_boot) + .field("minimum_build", &self.minimum_build) + .field("secure_engine", &self.secure_engine) + .field("address", &self.address.as_ref().map(Address)) + .field("firmware_id", &self.firmware_id) + .field("fields", &fields) + .finish() + } +} impl TlvIdentity { // Legacy operational firmware may answer the FF query with TLVs but its // upload filename requires a fresh legacy-format read, not lossy conversion. diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie.rs b/crates/stela-drivers/src/bluetooth/intel_pcie.rs index b860df26c9..3abdcd40ed 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie.rs @@ -91,7 +91,7 @@ pub struct Snapshot { pub mailbox_status: u32, pub mailboxes: [Option; 4], } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub enum Error { Preparation(crate::bus::pci::requester::preparation::Error), Unsupported(&'static str), @@ -116,9 +116,45 @@ pub enum Error { cleanup: Box, }, } +/// The failure line prints no byte of a refused frame: its length alone +/// (`crate::bluetooth::redacted`). impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "Intel PCIe Bluetooth {self:?}") + let error = crate::bluetooth::redacted::Lists(self); + write!(f, "Intel PCIe Bluetooth {error}") + } +} +impl core::fmt::Debug for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Preparation(error) => f.debug_tuple("Preparation").field(error).finish(), + Self::Unsupported(what) => f.debug_tuple("Unsupported").field(what).finish(), + Self::State(state) => f.debug_tuple("State").field(state).finish(), + Self::Dma(error) => f.debug_tuple("Dma").field(error).finish(), + Self::Mmio(what) => f.debug_tuple("Mmio").field(what).finish(), + Self::Native(error) => f.debug_tuple("Native").field(error).finish(), + Self::MinimumInterrupted => f.write_str("MinimumInterrupted"), + Self::Timeout(what) => f.debug_tuple("Timeout").field(what).finish(), + Self::Protocol { + requirement, + observed, + } => f + .debug_struct("Protocol") + .field("requirement", requirement) + .field("observed", observed) + .finish(), + Self::Controller(snapshot) => f.debug_tuple("Controller").field(snapshot).finish(), + Self::Packet { requirement, raw } => f + .debug_struct("Packet") + .field("requirement", requirement) + .field("raw", &crate::bluetooth::redacted::Bytes(raw)) + .finish(), + Self::Cleanup { cause, cleanup } => f + .debug_struct("Cleanup") + .field("cause", cause) + .field("cleanup", cleanup) + .finish(), + } } } impl core::error::Error for Error {} diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/packet.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/packet.rs index 36ce16e35d..e024f71af1 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/packet.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/packet.rs @@ -12,7 +12,7 @@ pub enum Kind { Event = 4, Iso = 5, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct Packet { pub kind: Kind, pub bytes: Vec, @@ -21,6 +21,20 @@ pub struct Packet { pub completion: u32, pub diagnostic: bool, } +/// A packet prints its framing and lengths, never its bytes. +impl core::fmt::Debug for Packet { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + use crate::bluetooth::redacted::Bytes; + f.debug_struct("Packet") + .field("kind", &self.kind) + .field("bytes", &Bytes(&self.bytes)) + .field("padding", &Bytes(&self.padding)) + .field("receive_header", &self.receive_header) + .field("completion", &self.completion) + .field("diagnostic", &self.diagnostic) + .finish() + } +} pub(super) fn length(kind: Kind, bytes: &[u8]) -> Result { let (header, data) = match kind { Kind::Command | Kind::Sco if bytes.len() >= 3 => (3, usize::from(bytes[2])), diff --git a/crates/stela-drivers/src/bluetooth/redacted.rs b/crates/stela-drivers/src/bluetooth/redacted.rs new file mode 100644 index 0000000000..d3b37e1fb3 --- /dev/null +++ b/crates/stela-drivers/src/bluetooth/redacted.rs @@ -0,0 +1,324 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +//! What a Bluetooth driver's failure says of the bytes it kept, once +//! printed. A failure line reaches the boot log, which owners post, and the +//! bytes a controller sent can be anything: a controller dump is its RAM, +//! which can hold link keys; an event can carry a neighbour's address and +//! name; a version or address read carries the controller's own address. +//! So the errors and observations print what failed and how many bytes it +//! saw, never their values, while the types keep the bytes for the code +//! that reads them: +//! +//! - [`Bytes`] prints a byte string as its length; +//! - [`Address`] prints a BD_ADDR as its vendor half and last byte, as +//! `stela_contracts::masked::Mac` prints a MAC address; +//! - [`Lists`] prints a value's Debug text with every list of plain +//! numbers, the way Debug writes a byte array, slice or vector, as its +//! length, so evidence no rule above names (an attempt's observations, +//! nested causes) prints no byte either. +use alloc::string::String; +use core::fmt::{self, Write as _}; + +/// A byte string, printed as ``. +pub(crate) struct Bytes<'a>(pub &'a [u8]); + +impl fmt::Debug for Bytes<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "<{} bytes>", self.0.len()) + } +} + +/// A BD_ADDR in HCI order (its least significant byte first), printed most +/// significant first as its vendor half and last byte: `aa:bb:cc:..:..:ff`. +pub(crate) struct Address<'a>(pub &'a [u8; 6]); + +impl fmt::Debug for Address<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut address = *self.0; + address.reverse(); + write!(f, "{}", stela_contracts::masked::Mac(&address)) + } +} + +/// `T`'s Debug text, each list of plain numbers in it (`[1, 2, 3]`) written +/// as `<3 bytes>`. Lists of anything else, and text in quotes, are kept. +pub(crate) struct Lists<'a, T: ?Sized>(pub &'a T); + +impl fmt::Display for Lists<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut filter = Filter { + out: f, + list: None, + quote: None, + escaped: false, + }; + write!(filter, "{:?}", self.0)?; + filter.flush() + } +} + +/// Writes Debug text on, holding back each list until it is known to be one +/// of plain numbers. +struct Filter<'a, 'b> { + out: &'a mut fmt::Formatter<'b>, + /// The list held back, from its `[`. + list: Option, + /// The quote of the string or character being written. + quote: Option, + escaped: bool, +} + +impl Filter<'_, '_> { + /// Writes the list held back as it was. + fn flush(&mut self) -> fmt::Result { + match self.list.take() { + Some(list) => self.out.write_str(&list), + None => Ok(()), + } + } +} + +impl fmt::Write for Filter<'_, '_> { + fn write_str(&mut self, text: &str) -> fmt::Result { + for c in text.chars() { + self.write_char(c)?; + } + Ok(()) + } + + fn write_char(&mut self, c: char) -> fmt::Result { + if let Some(quote) = self.quote { + if self.escaped { + self.escaped = false; + } else if c == '\\' { + self.escaped = true; + } else if c == quote { + self.quote = None; + } + return self.out.write_char(c); + } + if let Some(list) = self.list.as_mut() { + match c { + ']' => { + let numbers = list + .split(|c: char| !c.is_ascii_digit()) + .filter(|run| !run.is_empty()) + .count(); + self.list = None; + return if numbers == 0 { + self.out.write_str("[]") + } else { + write!(self.out, "<{numbers} bytes>") + }; + } + '0'..='9' | ',' | '-' => { + list.push(c); + return Ok(()); + } + c if c.is_whitespace() => { + list.push(c); + return Ok(()); + } + // Not a list of plain numbers: it goes out as it is. + _ => self.flush()?, + } + } + match c { + '[' => self.list = Some(String::from("[")), + '"' | '\'' => { + self.quote = Some(c); + self.escaped = false; + self.out.write_char(c)?; + } + c => self.out.write_char(c)?, + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::{format, vec, vec::Vec}; + + #[derive(Debug)] + #[expect(dead_code, reason = "Only its Debug text is read.")] + struct Evidence { + requirement: &'static str, + observed: Vec, + address: Option<[u8; 6]>, + opcodes: Vec, + nested: Vec>, + registers: [Option; 2], + empty: Vec, + offset: u32, + name: char, + } + + /// Every byte list leaves the text as its length, nested ones too; + /// numbers outside lists, lists of anything else and quoted text stay. + #[test] + fn lists_of_numbers_print_as_their_length() { + let evidence = Evidence { + requirement: "a \"[1, 2]\" quoted", + observed: vec![0x47, 0x61, 0x72, 0x76], + address: Some([0x10, 0xa7, 0xb8, 0x30, 0x31, 0x32]), + opcodes: vec![0x0c03, 0x1009], + nested: vec![vec![1, 2], vec![3]], + registers: [Some(7), None], + empty: Vec::new(), + offset: 4660, + name: '[', + }; + let text = format!("{}", Lists(&evidence)); + assert_eq!( + text, + "Evidence { requirement: \"a \\\"[1, 2]\\\" quoted\", observed: <4 bytes>, \ + address: Some(<6 bytes>), opcodes: <2 bytes>, nested: [<2 bytes>, <1 bytes>], \ + registers: [Some(7), None], empty: [], offset: 4660, name: '[' }" + ); + for secret in ["71", "167", "184", "3075"] { + assert!(!text.contains(secret), "{text}"); + } + // Pretty Debug text alike. + assert_eq!(format!("{}", Lists(&PrettyBytes)), "<3 bytes>"); + } + + struct PrettyBytes; + impl fmt::Debug for PrettyBytes { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:#?}", [9u8, 8, 7]) + } + } + + /// A synthetic name and BD_ADDR, as a controller's frames could carry. + const NAME: &[u8] = b"Tester"; + const ADDRESS: [u8; 6] = [0x10, 0xa7, 0xb8, 0x30, 0x31, 0x32]; + + /// `secret`: the name, the address and a controller dump's bytes. + fn secret() -> Vec { + [NAME, &ADDRESS[..], &[0x5a; 8]].concat() + } + + /// Whether `text` shows any of [`secret`]'s values, as Debug writes + /// them or in hex. + fn leaks(text: &str) -> bool { + [ + "84, 101, 115", + "167, 184", + "90, 90", + "a7:b8", + "b8:a7", + "Tester", + ] + .iter() + .any(|value| text.contains(value)) + } + + /// The failure lines of the transports and initializers, Display and + /// Debug alike: a Qualcomm controller dump, a Broadcom PCIe frame, + /// event and return, an Intel PCIe frame and a Realtek response, alone, + /// nested and inside an initialization's failure, show their lengths + /// and never a byte. + #[test] + fn failure_lines_print_no_byte_a_controller_sent() { + use crate::bluetooth::{bcm4377, intel_pcie}; + use crate::usb::bluetooth::{self as usb, InitializationError, broadcom, realtek}; + let dump = || usb::Error { + kind: usb::ErrorKind::ControllerDump { + driver: "qualcomm-usb", + packet: usb::Packet::Diagnostic(secret()), + }, + cleanup: None, + }; + let broadcom_pcie = || bcm4377::Error::Cleanup { + cause: alloc::boxed::Box::new(bcm4377::Error::Packet { + kind: bcm4377::Kind::Event, + bytes: secret(), + }), + cleanup: alloc::boxed::Box::new(bcm4377::Error::Controller { + opcode: 0x1009, + status: 0, + returned: ADDRESS.to_vec(), + }), + }; + let hci = bcm4377::Error::Hci { + requirement: "event", + bytes: secret(), + }; + let intel = intel_pcie::Error::Packet { + requirement: "complete RFH", + raw: secret(), + }; + let realtek = || realtek::Error::Cleanup { + cause: alloc::boxed::Box::new(realtek::Error::Protocol { + requirement: "local version", + observed: secret(), + }), + cleanup: dump(), + }; + let controller = realtek::Error::Controller { + opcode: 0x1009, + status: 0x0c, + parameters: ADDRESS.to_vec(), + }; + let texts = [ + format!("{}", dump()), + format!("{:?}", dump()), + format!("{}", broadcom_pcie()), + format!("{:?}", broadcom_pcie()), + format!("{hci} {hci:?}"), + format!("{intel} {intel:?}"), + format!("{}", realtek()), + format!("{:?}", realtek()), + format!("{controller} {controller:?}"), + format!("{}", InitializationError::Realtek(realtek())), + format!("{}", InitializationError::Transport(dump())), + format!( + "{}", + InitializationError::Broadcom(broadcom::Error::InvalidAddress(ADDRESS)) + ), + ]; + for text in &texts { + assert!(!leaks(text), "{text}"); + } + assert!(texts[0].contains("Diagnostic(<20 bytes>)"), "{}", texts[0]); + assert!(texts[3].contains("returned: <6 bytes>"), "{}", texts[3]); + assert!(texts[5].contains("raw: <20 bytes>"), "{}", texts[5]); + assert!(texts[8].contains("parameters: <6 bytes>"), "{}", texts[8]); + // The packets themselves print their lengths. + let packets = [ + format!("{:?}", usb::Packet::Event(secret())), + format!( + "{:?}", + bcm4377::Packet { + kind: bcm4377::Kind::Acl, + bytes: secret(), + completion: [0x5a; 16], + footer: secret(), + } + ), + format!( + "{:?}", + intel_pcie::Packet { + kind: intel_pcie::Kind::Event, + bytes: secret(), + padding: secret(), + receive_header: [0; 8], + completion: 0, + diagnostic: false, + } + ), + ]; + for text in &packets { + assert!(!leaks(text), "{text}"); + } + } + + #[test] + fn bytes_and_addresses_print_masked() { + assert_eq!(format!("{:?}", Bytes(&[1, 2, 3])), "<3 bytes>"); + // 32:31:30:b8:a7:10 in HCI order. + let address = [0x10, 0xa7, 0xb8, 0x30, 0x31, 0x32]; + assert_eq!(format!("{:?}", Address(&address)), "32:31:30:..:..:10"); + } +} diff --git a/crates/stela-drivers/src/usb/bluetooth.rs b/crates/stela-drivers/src/usb/bluetooth.rs index 7e90161bff..d1ebde990a 100644 --- a/crates/stela-drivers/src/usb/bluetooth.rs +++ b/crates/stela-drivers/src/usb/bluetooth.rs @@ -187,9 +187,12 @@ pub struct Error { /// Preserved separately when stopping the failed transport also failed. pub cleanup: Option, } +/// The failure line prints no byte a controller sent: a controller dump's +/// packet shows its length alone (`crate::bluetooth::redacted`). impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "USB Bluetooth {:?}", self.kind)?; + let kind = crate::bluetooth::redacted::Lists(&self.kind); + write!(f, "USB Bluetooth {kind}")?; if let Some(cleanup) = &self.cleanup { write!(f, "; cancellation failed: {cleanup}")?; } @@ -204,7 +207,7 @@ fn error(kind: ErrorKind) -> Error { } } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub enum Packet { Event(Vec), Acl(Vec), @@ -213,6 +216,21 @@ pub enum Packet { Diagnostic(Vec), } +/// A packet prints its kind and length, never its bytes: a diagnostic frame +/// is controller RAM, an event can name a neighbour. +impl fmt::Debug for Packet { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (kind, bytes) = match self { + Self::Event(bytes) => ("Event", bytes), + Self::Acl(bytes) => ("Acl", bytes), + Self::Diagnostic(bytes) => ("Diagnostic", bytes), + }; + f.debug_tuple(kind) + .field(&crate::bluetooth::redacted::Bytes(bytes)) + .finish() + } +} + /// Raw legacy HCI transport over a validated USB binding. pub struct Hci { binding: Binding, diff --git a/crates/stela-drivers/src/usb/bluetooth/ath3k.rs b/crates/stela-drivers/src/usb/bluetooth/ath3k.rs index a0a443afd0..c2b543b2c0 100644 --- a/crates/stela-drivers/src/usb/bluetooth/ath3k.rs +++ b/crates/stela-drivers/src/usb/bluetooth/ath3k.rs @@ -144,7 +144,11 @@ impl Error { } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "ATH3K USB bootloader {self:?}") + write!( + f, + "ATH3K USB bootloader {}", + crate::bluetooth::redacted::Lists(self) + ) } } impl core::error::Error for Error {} diff --git a/crates/stela-drivers/src/usb/bluetooth/ath3k/runtime.rs b/crates/stela-drivers/src/usb/bluetooth/ath3k/runtime.rs index aa0f1f4782..08d8de5d3f 100644 --- a/crates/stela-drivers/src/usb/bluetooth/ath3k/runtime.rs +++ b/crates/stela-drivers/src/usb/bluetooth/ath3k/runtime.rs @@ -89,7 +89,11 @@ impl From for Error { } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "ATH3012 runtime initialization {self:?}") + write!( + f, + "ATH3012 runtime initialization {}", + crate::bluetooth::redacted::Lists(self) + ) } } impl core::error::Error for Error {} diff --git a/crates/stela-drivers/src/usb/bluetooth/broadcom.rs b/crates/stela-drivers/src/usb/bluetooth/broadcom.rs index 1b0529871d..a333656a58 100644 --- a/crates/stela-drivers/src/usb/bluetooth/broadcom.rs +++ b/crates/stela-drivers/src/usb/bluetooth/broadcom.rs @@ -97,7 +97,11 @@ impl From for Error { } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "Broadcom USB Bluetooth initialization {self:?}") + write!( + f, + "Broadcom USB Bluetooth initialization {}", + crate::bluetooth::redacted::Lists(self) + ) } } impl core::error::Error for Error {} diff --git a/crates/stela-drivers/src/usb/bluetooth/broadcom/diagnostics.rs b/crates/stela-drivers/src/usb/bluetooth/broadcom/diagnostics.rs index 03877c1472..40cf8140ff 100644 --- a/crates/stela-drivers/src/usb/bluetooth/broadcom/diagnostics.rs +++ b/crates/stela-drivers/src/usb/bluetooth/broadcom/diagnostics.rs @@ -53,7 +53,11 @@ pub struct Retirement { } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "Broadcom diagnostic {self:?}") + write!( + f, + "Broadcom diagnostic {}", + crate::bluetooth::redacted::Lists(self) + ) } } impl core::error::Error for Error {} diff --git a/crates/stela-drivers/src/usb/bluetooth/initialization.rs b/crates/stela-drivers/src/usb/bluetooth/initialization.rs index 32789599f8..540325fe82 100644 --- a/crates/stela-drivers/src/usb/bluetooth/initialization.rs +++ b/crates/stela-drivers/src/usb/bluetooth/initialization.rs @@ -52,7 +52,11 @@ impl fmt::Display for InitializationError { } f.write_str(": no vendor setup here takes it, so it stays off") } - _ => write!(f, "native USB Bluetooth initialization {self:?}"), + _ => write!( + f, + "native USB Bluetooth initialization {}", + crate::bluetooth::redacted::Lists(self) + ), } } } diff --git a/crates/stela-drivers/src/usb/bluetooth/intel/bulk_iso.rs b/crates/stela-drivers/src/usb/bluetooth/intel/bulk_iso.rs index f5a079339e..04449f8f17 100644 --- a/crates/stela-drivers/src/usb/bluetooth/intel/bulk_iso.rs +++ b/crates/stela-drivers/src/usb/bluetooth/intel/bulk_iso.rs @@ -69,7 +69,11 @@ pub enum Error { } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "Intel bulk ISO {self:?}") + write!( + f, + "Intel bulk ISO {}", + crate::bluetooth::redacted::Lists(self) + ) } } impl core::error::Error for Error {} diff --git a/crates/stela-drivers/src/usb/bluetooth/mediatek.rs b/crates/stela-drivers/src/usb/bluetooth/mediatek.rs index e75a85f84e..2b8eb0e8e3 100644 --- a/crates/stela-drivers/src/usb/bluetooth/mediatek.rs +++ b/crates/stela-drivers/src/usb/bluetooth/mediatek.rs @@ -159,7 +159,11 @@ impl From for Error { } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "MediaTek Bluetooth initialization {self:?}") + write!( + f, + "MediaTek Bluetooth initialization {}", + crate::bluetooth::redacted::Lists(self) + ) } } impl core::error::Error for Error {} diff --git a/crates/stela-drivers/src/usb/bluetooth/mediatek/coredump.rs b/crates/stela-drivers/src/usb/bluetooth/mediatek/coredump.rs index dbff5f0256..125ca2a620 100644 --- a/crates/stela-drivers/src/usb/bluetooth/mediatek/coredump.rs +++ b/crates/stela-drivers/src/usb/bluetooth/mediatek/coredump.rs @@ -28,7 +28,7 @@ pub enum End { } /// A collected controller memory dump with the devcoredump header facts. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Eq, PartialEq)] pub struct Coredump { /// btmtk_coredump_hdr's "Controller Name": the chip's device ID. pub device_id: u32, @@ -39,6 +39,20 @@ pub struct Coredump { pub end: End, } +/// A dump prints its header facts and length, never the controller's +/// memory, which can hold link keys (`crate::bluetooth::redacted`). +impl core::fmt::Debug for Coredump { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Coredump") + .field("device_id", &self.device_id) + .field("firmware_version", &self.firmware_version) + .field("data", &crate::bluetooth::redacted::Bytes(&self.data)) + .field("frames", &self.frames) + .field("end", &self.end) + .finish() + } +} + struct Active { data: Vec, frames: usize, diff --git a/crates/stela-drivers/src/usb/bluetooth/mediatek/media.rs b/crates/stela-drivers/src/usb/bluetooth/mediatek/media.rs index bdeb9fc189..1afa7c7326 100644 --- a/crates/stela-drivers/src/usb/bluetooth/mediatek/media.rs +++ b/crates/stela-drivers/src/usb/bluetooth/mediatek/media.rs @@ -55,7 +55,11 @@ pub enum Error { } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "USB Bluetooth media {self:?}") + write!( + f, + "USB Bluetooth media {}", + crate::bluetooth::redacted::Lists(self) + ) } } impl core::error::Error for Error {} diff --git a/crates/stela-drivers/src/usb/bluetooth/qca.rs b/crates/stela-drivers/src/usb/bluetooth/qca.rs index bbf8396897..f51ecd4b16 100644 --- a/crates/stela-drivers/src/usb/bluetooth/qca.rs +++ b/crates/stela-drivers/src/usb/bluetooth/qca.rs @@ -107,7 +107,11 @@ impl From for Error { } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "Qualcomm USB Bluetooth initialization {self:?}") + write!( + f, + "Qualcomm USB Bluetooth initialization {}", + crate::bluetooth::redacted::Lists(self) + ) } } impl core::error::Error for Error {} diff --git a/crates/stela-drivers/src/usb/bluetooth/realtek.rs b/crates/stela-drivers/src/usb/bluetooth/realtek.rs index 021b51641c..593e091381 100644 --- a/crates/stela-drivers/src/usb/bluetooth/realtek.rs +++ b/crates/stela-drivers/src/usb/bluetooth/realtek.rs @@ -98,7 +98,6 @@ pub struct OwnedReport { pub v2: Option, pub download: Vec, } -#[derive(Debug)] pub enum Error { Unsupported(&'static str), Protocol { @@ -141,9 +140,53 @@ impl From for Error { Self::Transport(e) } } +/// The failure line prints no byte of a malformed or refused response, which +/// can be a version or address read: its length alone +/// (`crate::bluetooth::redacted`). impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "Realtek Bluetooth initialization {self:?}") + let error = crate::bluetooth::redacted::Lists(self); + write!(f, "Realtek Bluetooth initialization {error}") + } +} +impl core::fmt::Debug for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + use crate::bluetooth::redacted::Bytes; + match self { + Self::Unsupported(what) => f.debug_tuple("Unsupported").field(what).finish(), + Self::Protocol { + requirement, + observed, + } => f + .debug_struct("Protocol") + .field("requirement", requirement) + .field("observed", &Bytes(observed)) + .finish(), + Self::Format(error) => f.debug_tuple("Format").field(error).finish(), + Self::Resource(error) => f.debug_tuple("Resource").field(error).finish(), + Self::Controller { + opcode, + status, + parameters, + } => f + .debug_struct("Controller") + .field("opcode", opcode) + .field("status", status) + .field("parameters", &Bytes(parameters)) + .finish(), + Self::Timeout(what) => f.debug_tuple("Timeout").field(what).finish(), + Self::Transport(error) => f.debug_tuple("Transport").field(error).finish(), + Self::Attempt { cause, observation } => f + .debug_struct("Attempt") + .field("cause", cause) + .field("observation", observation) + .finish(), + Self::Cleanup { cause, cleanup } => f + .debug_struct("Cleanup") + .field("cause", cause) + .field("cleanup", cleanup) + .finish(), + } } } impl core::error::Error for Error {}