From e4e08e35c77af174e1eec2f8832ae5487799edb8 Mon Sep 17 00:00:00 2001 From: Garvit Surana <251430630+garvitsurana271@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:42:31 +0000 Subject: [PATCH] fix(wifi): keep the first and last cause of a failed RTL8852C bring-up, the firmware's raw 0x01E0 status and a MAC found left on, power the chip off after a failed power-on, and name each cause once, where the log kept only the last of five attempts, dropped the left-on warning on failure and repeated its prefixes --- .../stela-driver-net/src/wifi/realtek/ax.rs | 2 +- .../src/wifi/realtek/ax/bringup.rs | 147 +++++++++-- .../src/wifi/realtek/ax/bringup/tests.rs | 247 ++++++++++++++++-- .../src/wifi/realtek/ax/efuse.rs | 6 +- .../src/wifi/realtek/ax/fwdl.rs | 53 ++-- .../src/wifi/realtek/ax/fwdl/tests.rs | 71 ++++- .../src/wifi/realtek/ax/io.rs | 27 +- .../src/wifi/realtek/ax/pci.rs | 2 +- .../src/wifi/realtek/ax/pci/tests.rs | 2 +- .../src/wifi/realtek/ax/power.rs | 57 +++- crates/stela-drivers/src/probe.rs | 69 ++++- crates/stela-drivers/src/probe/native.rs | 158 ++++++++--- 12 files changed, 717 insertions(+), 124 deletions(-) diff --git a/crates/stela-driver-net/src/wifi/realtek/ax.rs b/crates/stela-driver-net/src/wifi/realtek/ax.rs index 0a570c8629..645905e2e8 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax.rs @@ -16,7 +16,7 @@ pub mod power; #[cfg(test)] pub(crate) mod tests; -pub use bringup::{BringUpError, Running, bring_up, quiesce}; +pub use bringup::{BringUpError, Earlier, Running, bring_up, quiesce}; pub use fwdl::download; pub use io::{ AxError, AxIo, NativeAxIo, Polled, clear8, clear16, clear32, field8, field16, field32, diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/bringup.rs b/crates/stela-driver-net/src/wifi/realtek/ax/bringup.rs index 4234f7767a..8b278e496f 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/bringup.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/bringup.rs @@ -32,7 +32,9 @@ const R_AX_SCOREBOARD: u32 = 0x00AC; /// `MAC_AX_NOTIFY_PWR_MAJOR`. const MAC_AX_NOTIFY_TP_MAJOR: u8 = 0x81; /// `rtw89_fw_download`: `for (retry = 0; retry < 5; retry++)` (`fw.c:2048`). -const FWDL_TRIES: usize = 5; +const FWDL_TRIES: u8 = 5; +/// `rtw89_mac_pwr_on` (`mac.c:1588`): one power switch and one retry. +const POWER_ON_TRIES: u8 = 2; /// An RTL8852CE whose firmware reported `RTW89_FWDL_WCPU_FW_INIT_RDY`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -76,24 +78,93 @@ pub struct BringUpError { /// runs [`quiesce`] before [`bring_up`] adds `"register window"`, /// `"identity"`, `"firmware"` and `"quiesce"`. pub step: &'static str, + /// The step's last failure. pub error: AxError, + /// What the step's retries ran into before `error`, kept because the + /// first failure is the likelier root cause. + pub earlier: Earlier, +} + +/// What a retried bring-up step ran into before the error it reports. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Earlier { + /// The step was not retried, or its first attempt failed the same way. + #[default] + Nothing, + /// The first of `tries` attempts failed with `error`, which the last + /// attempt's error differs from. + First { tries: u8, error: AxError }, + /// A `"pci pre-init"` re-run inside the firmware download: download + /// attempt `attempt` (from 1) failed with `stopped`, which left CH12 + /// stopped, so the next attempt re-ran `pci::pre_init` first. `first` + /// is attempt 1's error, when that was an earlier, different one. + Ch12Stopped { + attempt: u8, + stopped: AxError, + first: Option, + }, +} + +impl Earlier { + /// `First`, when `first` differs from `last`. + fn first_of(tries: u8, first: AxError, last: AxError) -> Self { + if first == last { + Self::Nothing + } else { + Self::First { + tries, + error: first, + } + } + } +} + +impl BringUpError { + /// `step` failed with `error`, with nothing earlier. + pub const fn new(step: &'static str, error: AxError) -> Self { + Self { + step, + error, + earlier: Earlier::Nothing, + } + } } impl fmt::Display for BringUpError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "RTL8852CE bring-up: {}: {}", self.step, self.error) + write!(f, "RTL8852CE bring-up: {}: {}", self.step, self.error)?; + match self.earlier { + Earlier::Nothing => Ok(()), + Earlier::First { tries, error } => write!(f, " (first of {tries} attempts: {error})"), + Earlier::Ch12Stopped { + attempt, + stopped, + first, + } => { + write!( + f, + " (re-run after firmware download attempt {attempt} of {FWDL_TRIES} failed \ + and stopped CH12: {stopped}" + )?; + if let Some(first) = first { + write!(f, "; first of {FWDL_TRIES} attempts: {first}")?; + } + f.write_str(")") + } + } } } fn at(step: &'static str) -> impl FnOnce(AxError) -> BringUpError { - move |error| BringUpError { step, error } + move |error| BringUpError::new(step, error) } /// Bring an RTL8852CE of chip cut `cut` up to running firmware `image`, and /// read its MAC address, then power it off again. Steps, in Linux's order: /// /// 1. `"power on"`: `power::power_on`, with Linux's own power-off and -/// single retry (`rtw89_mac_pwr_on`). A failure here returns at once. +/// single retry (`rtw89_mac_pwr_on`). When the retry fails too, the error +/// keeps both tries' failures. /// 2. `"secure boot"`: the efuse secure-boot bytes, then the /// `MAC_AX_NOTIFY_TP_MAJOR` scoreboard write that closes /// `rtw89_mac_power_switch(true)`. A secure-boot chip is refused with @@ -102,15 +173,19 @@ fn at(step: &'static str) -> impl FnOnce(AxError) -> BringUpError { /// 4. `"mac pre-init"`: `dmac::pre_init`. /// 5. `"pci pre-init"`: `pci::pre_init`. /// 6. `"firmware download"`: up to five `fwdl::download` attempts -/// (`fw.c:2043`), the last error returned. An attempt whose CH12 submit -/// failed leaves CH12 stopped; the next attempt then runs `pci::pre_init` -/// again first (a failure there is reported as `"pci pre-init"`). +/// (`fw.c:2043`), the last error returned, with the first when they +/// differ. An attempt whose CH12 submit failed leaves CH12 stopped; the +/// next attempt then runs `pci::pre_init` again first (a failure there is +/// reported as `"pci pre-init"`, with the download error that stopped +/// CH12 and, when earlier and different, the first one). /// 7. `"efuse"`: the whole physical map, its logical map and the MAC. /// -/// After `"power on"` succeeded, success and every failure end as -/// `rtw89_chip_info_setup` does, in `rtw89_mac_pwr_off`: `power::power_off`, -/// then, only if it succeeded, the `MAC_AX_NOTIFY_PWR_MAJOR` scoreboard -/// write. Linux ignores the result of that power-off, and so does this. +/// Success and every failure end as `rtw89_chip_info_setup` does after a +/// power-on, in `rtw89_mac_pwr_off`: `power::power_off`, then, only if it +/// succeeded, the `MAC_AX_NOTIFY_PWR_MAJOR` scoreboard write. Linux ignores +/// the result of that power-off, and so does this. A failed `"power on"` +/// ends the same way, so the chip is left off; Linux returns from it +/// without, but its retry ran the same power-off between the two tries. /// /// On success the firmware result is reported with the `Rings` that DMA was /// started on. The caller must keep them (dropping them leaves every mapping @@ -132,7 +207,14 @@ pub unsafe fn bring_up( cut: u8, image: &AxImage<'_>, ) -> Result<(Running, Rings), BringUpError> { - power::power_on(io).map_err(at("power on"))?; + if let Err(error) = power::power_on(io) { + power_down(io); + return Err(BringUpError { + step: "power on", + error: error.retry, + earlier: Earlier::first_of(POWER_ON_TRIES, error.first, error.retry), + }); + } // SAFETY: the caller's `Rings::install` contract, forwarded unchanged. let mut rings = match unsafe { prepare(io, source, domain) } { Ok(rings) => rings, @@ -250,9 +332,10 @@ unsafe fn start( } /// `rtw89_fw_download(RTW89_FW_NORMAL)` (`fw.c:2043`): up to five attempts -/// of `__rtw89_fw_download`, the last error returned. A failed CH12 submit -/// stops the queue (Linux's queue has no such state), so the next attempt -/// restarts it with `pci::pre_init` first. +/// of `__rtw89_fw_download`, the last error returned, with the first when it +/// differs. A failed CH12 submit stops the queue (Linux's queue has no such +/// state), so the next attempt restarts it with `pci::pre_init` first; if +/// that fails, it is reported with the download error that stopped CH12. /// /// # Safety /// The `pci::pre_init` and `Ch12::submit` contracts for `io` and `rings`. @@ -262,20 +345,40 @@ unsafe fn download( rings: &mut Rings, image: &AxImage<'_>, ) -> Result<(), BringUpError> { - let mut last = AxError::Firmware("not attempted"); - for attempt in 0..FWDL_TRIES { - if attempt > 0 && rings.ch12_stopped() { + // SAFETY: the caller's `Ch12::submit` contract; `pci::pre_init` + // programmed `rings` through this `io`. + let first = match unsafe { fwdl::download(io, &mut rings.ch12(), image) } { + Ok(()) => return Ok(()), + Err(error) => error, + }; + let mut last = first; + for attempt in 2..=FWDL_TRIES { + if rings.ch12_stopped() { // SAFETY: the caller's `pci::pre_init` contract for these rings. - unsafe { pci::pre_init(io, cut, rings) }.map_err(at("pci pre-init"))?; + if let Err(error) = unsafe { pci::pre_init(io, cut, rings) } { + return Err(BringUpError { + step: "pci pre-init", + error, + earlier: Earlier::Ch12Stopped { + attempt: attempt - 1, + stopped: last, + first: (attempt > 2 && first != last).then_some(first), + }, + }); + } } - // SAFETY: the caller's `Ch12::submit` contract; `pci::pre_init` - // programmed `rings` through this `io`. + // SAFETY: as for the first attempt; a stopped CH12 was restarted by + // `pci::pre_init` on these rings just above. match unsafe { fwdl::download(io, &mut rings.ch12(), image) } { Ok(()) => return Ok(()), Err(error) => last = error, } } - Err(at("firmware download")(last)) + Err(BringUpError { + step: "firmware download", + error: last, + earlier: Earlier::first_of(FWDL_TRIES, first, last), + }) } #[cfg(test)] diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/bringup/tests.rs b/crates/stela-driver-net/src/wifi/realtek/ax/bringup/tests.rs index 051a24d83d..f8cbea42e6 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/bringup/tests.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/bringup/tests.rs @@ -256,10 +256,7 @@ fn secure_boot_on_refuses_and_powers_off() { let err = failed(run(&mut c.io, &m)); assert_eq!( err, - BringUpError { - step: "secure boot", - error: AxError::SecureBootUnsupported, - } + BringUpError::new("secure boot", AxError::SecureBootUnsupported) ); assert_eq!( err.to_string(), @@ -277,12 +274,22 @@ fn download_retries_five_times_then_fails() { let m = Arc::new(Mutex::new(Model::default())); let mut c = chip(efuse_with_mac(), 0, never); let err = failed(run(&mut c.io, &m)); + // Every attempt failed the same way, so only the last is named, with + // the whole 0x01E0 read after its wait: path bits 1 and 2, FWDL_EN, and + // status 0 in [7:5]. assert_eq!( err, - BringUpError { - step: "firmware download", - error: AxError::Firmware("not ready"), - } + BringUpError::new( + "firmware download", + AxError::FirmwareStatus { + what: "not ready", + fw_ctrl: 0x0000_0007, + } + ) + ); + assert_eq!( + err.to_string(), + "RTL8852CE bring-up: firmware download: not ready (0x01E0=0x00000007)" ); // rtw89_fw_download (fw.c:2043): five attempts. CH12 never failed, so // no PCI pre-init re-ran between them. @@ -333,15 +340,186 @@ fn ch12_failure_reruns_pci_pre_init_before_the_retry() { } #[test] -fn power_on_failure_does_not_power_off_again() { - // RDY_SYSPWR never comes up and XTAL SI never completes: - // rtw89_mac_pwr_on's own power-off and retry fail, and the bring-up adds - // nothing after them. +fn download_failure_names_the_first_attempt_when_it_differs() { + // Attempt 1: CH12 never consumes the header packet, so its submit times + // out and stops the queue. Attempts 2-5, after a fresh PCI pre-init: + // the firmware never reports ready. + fn first_pre_init(pre_inits: usize) -> bool { + pre_inits < 2 + } + let m = Arc::new(Mutex::new(Model::default())); + let mut c = chip(efuse_with_mac(), 0, first_pre_init); + let err = failed(run(&mut c.io, &m)); + assert_eq!( + err, + BringUpError { + step: "firmware download", + error: AxError::FirmwareStatus { + what: "not ready", + fw_ctrl: 0x0000_0007, + }, + earlier: Earlier::First { + tries: 5, + error: AxError::Timeout { + register: 0x1080, + mask: 0x0FFF_0000, + }, + }, + } + ); + assert_eq!( + err.to_string(), + "RTL8852CE bring-up: firmware download: not ready (0x01E0=0x00000007) (first of 5 \ + attempts: timeout waiting on register 0x1080 mask 0xfff0000)" + ); + assert_eq!(count(&c.io, ATTEMPT), 5); + assert_eq!(c.pre_inits.load(Ordering::Relaxed), 2); + assert_ends_with_power_off(&c.io); +} + +#[test] +fn a_failed_pci_re_init_keeps_the_download_error_that_stopped_ch12() { + // Attempt 1's header packet is never consumed, which stops CH12; the + // PCI pre-init re-run for attempt 2 then finds the TX DMA busy (CH12, + // R_AX_HAXI_DMA_BUSY1 bit 18) and times out. + fn always(_: usize) -> bool { + true + } + let m = Arc::new(Mutex::new(Model::default())); + let mut c = chip(efuse_with_mac(), 7, always); + let mut busy_reads = 0; + c.io.on_read( + 0x101C, + Box::new(move |_: &mut RegisterModel| { + busy_reads += 1; + if busy_reads == 1 { 0 } else { 1 << 18 } + }), + ); + let err = failed(run(&mut c.io, &m)); + assert_eq!( + err, + BringUpError { + step: "pci pre-init", + error: AxError::Timeout { + register: 0x101C, + mask: 0x0007_FF00, + }, + earlier: Earlier::Ch12Stopped { + attempt: 1, + stopped: AxError::Timeout { + register: 0x1080, + mask: 0x0FFF_0000, + }, + first: None, + }, + } + ); + assert_eq!( + err.to_string(), + "RTL8852CE bring-up: pci pre-init: timeout waiting on register 0x101c mask 0x7ff00 \ + (re-run after firmware download attempt 1 of 5 failed and stopped CH12: timeout \ + waiting on register 0x1080 mask 0xfff0000)" + ); + // One download attempt; the second never started. + assert_eq!(count(&c.io, ATTEMPT), 1); + assert_ends_with_power_off(&c.io); +} + +#[test] +fn a_ch12_stop_after_a_different_first_failure_names_both() { + let err = BringUpError { + step: "pci pre-init", + error: AxError::AllOnes { register: 0x3848 }, + earlier: Earlier::Ch12Stopped { + attempt: 3, + stopped: AxError::Dma("ring memory visibility failed"), + first: Some(AxError::FirmwareStatus { + what: "checksum failed", + fw_ctrl: 0x0000_0047, + }), + }, + }; + assert_eq!( + err.to_string(), + "RTL8852CE bring-up: pci pre-init: register 0x3848 read all ones (re-run after firmware \ + download attempt 3 of 5 failed and stopped CH12: ring memory visibility failed; first \ + of 5 attempts: checksum failed (0x01E0=0x00000047))" + ); +} + +#[test] +fn power_on_failure_keeps_both_errors_and_ends_powered_off() { + // The MAC reads on at first, so rtw89_mac_pwr_on powers it off and + // retries; then RDY_SYSPWR never comes up. Power-off itself works. + let m = Arc::new(Mutex::new(Model::default())); + let mut io = RegisterModel::new(); + io.on_read( + 0x0004, + Box::new(|m: &mut RegisterModel| m.get32(0x0004) & !(1 << 17 | 1 << 8 | 1 << 9)), + ); + io.on_read( + 0x0270, + Box::new(|m: &mut RegisterModel| m.get32(0x0270) & 0x7FFF_FFFF), + ); + let mut reads = 0; + io.on_read( + 0x03F0, + Box::new(move |_: &mut RegisterModel| { + reads += 1; + if reads == 1 { 0x100 } else { 0 } + }), + ); + let err = failed(run(&mut io, &m)); + assert_eq!( + err, + BringUpError { + step: "power on", + error: AxError::Timeout { + register: 0x0004, + mask: 1 << 17, + }, + earlier: Earlier::First { + tries: 2, + error: AxError::AlreadyPowered, + }, + } + ); + assert_eq!( + err.to_string(), + "RTL8852CE bring-up: power on: timeout waiting on register 0x4 mask 0x20000 (first of 2 \ + attempts: MAC has already powered on)" + ); + // The retry's power-off, then the bring-up's own: the chip is left off + // and coex is told, twice. + assert_ends_with_power_off(&io); + assert_eq!(count(&io, Op::W8(0x00AF, 0x80)), 2); + assert!(m.lock().unwrap().mappings.is_empty()); +} + +#[test] +fn power_on_failure_still_tries_the_power_off() { + // RDY_SYSPWR never comes up and XTAL SI never completes: both tries + // fail the same way, and so do the retry's power-off and the bring-up's + // own, each at its first XTAL SI command, so coex is never told. let m = Arc::new(Mutex::new(Model::default())); let mut io = RegisterModel::new(); let err = failed(run(&mut io, &m)); - assert_eq!(err.step, "power on"); - assert!(matches!(err.error, AxError::Timeout { .. })); + assert_eq!( + err, + BringUpError::new( + "power on", + AxError::Timeout { + register: 0x0004, + mask: 1 << 17, + } + ) + ); + assert_eq!(count(&io, xtal(0x90, 0x10, 0x10)), 2); + let last_write = io + .writes() + .into_iter() + .rfind(|op| !matches!(op, Op::Delay(_))); + assert_eq!(last_write, Some(xtal(0x90, 0x10, 0x10))); assert!(!io.trace.iter().any(|o| matches!(o, Op::W8(0x00AF, _)))); assert!(m.lock().unwrap().mappings.is_empty()); } @@ -414,7 +592,7 @@ fn quiesce_refuses_a_mac_in_lps_or_an_undefined_state_and_writes_nothing() { assert_eq!( AxError::MacPowerState(2).to_string(), "the MAC is in firmware-managed low power (LPS), so its firmware may still run; Bus \ - Master stays off" + Master stays off; power the machine fully off (not restart) and boot again" ); assert_eq!( AxError::MacPowerState(3).to_string(), @@ -477,3 +655,42 @@ fn a_firmware_file_error_is_its_message_alone() { "rtw89/rtw8852c_fw-2.bin is not on the USB stick" ); } + +#[test] +fn every_bring_up_line_names_its_subsystem_once() { + for (err, line) in [ + ( + BringUpError::new("efuse", AxError::Efuse("logical map out of range")), + "RTL8852CE bring-up: efuse: logical map out of range", + ), + ( + BringUpError::new("dma rings", AxError::Dma("out of ring memory")), + "RTL8852CE bring-up: dma rings: out of ring memory", + ), + ( + BringUpError::new( + "firmware download", + AxError::Firmware("WCPU already enabled"), + ), + "RTL8852CE bring-up: firmware download: WCPU already enabled", + ), + ( + BringUpError::new( + "firmware download", + AxError::FirmwareStatus { + what: "H2C path not ready", + fw_ctrl: 0x0000_0001, + }, + ), + "RTL8852CE bring-up: firmware download: H2C path not ready (0x01E0=0x00000001)", + ), + ( + BringUpError::new("quiesce", AxError::MacPowerState(2)), + "RTL8852CE bring-up: quiesce: the MAC is in firmware-managed low power (LPS), so its \ + firmware may still run; Bus Master stays off; power the machine fully off (not \ + restart) and boot again", + ), + ] { + assert_eq!(err.to_string(), line); + } +} diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/efuse.rs b/crates/stela-driver-net/src/wifi/realtek/ax/efuse.rs index 994ac55c20..3a36788ba7 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/efuse.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/efuse.rs @@ -176,9 +176,7 @@ pub fn secure_boot(io: &mut I) -> Result /// from physical index 4. Linux's `-EINVAL` returns are `AxError::Efuse`. pub fn logical_map(physical: &[u8]) -> Result, AxError> { if physical.len() < PHYSICAL_EFUSE_SIZE { - return Err(AxError::Efuse( - "physical efuse map is shorter than 1216 bytes", - )); + return Err(AxError::Efuse("physical map is shorter than 1216 bytes")); } let mut log = vec![0xFFu8; LOGICAL_EFUSE_SIZE]; let end = PHYSICAL_EFUSE_SIZE - SEC_CTRL_EFUSE_SIZE; @@ -198,7 +196,7 @@ pub fn logical_map(physical: &[u8]) -> Result, AxError> { } let log_idx = (blk_idx << 3) + (i << 1); if phy_idx + 1 > end - 1 || log_idx + 1 > LOGICAL_EFUSE_SIZE { - return Err(AxError::Efuse("efuse logical map out of range")); + return Err(AxError::Efuse("logical map out of range")); } log[log_idx] = physical[phy_idx]; log[log_idx + 1] = physical[phy_idx + 1]; diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/fwdl.rs b/crates/stela-driver-net/src/wifi/realtek/ax/fwdl.rs index b3383269ba..c8ece42cca 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/fwdl.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/fwdl.rs @@ -20,8 +20,10 @@ //! chip before it gets here, so no MSS key is inserted and the idmem share //! mode is not recorded. This module does not grant the retry loop of //! `rtw89_fw_download` (`fw.c:2043`), the failure dump -//! `rtw89_fw_dl_fail_dump`, any H2C after the download, or anything past -//! the firmware's own ready status: no C2H, scan or radio state. +//! `rtw89_fw_dl_fail_dump` past its first read (the whole +//! `R_AX_WCPU_FW_CTRL`, kept in the error), any H2C after the download, or +//! anything past the firmware's own ready status: no C2H, scan or radio +//! state. use super::io::{AxError, AxIo, Polled, clear32, field16, poll_sample_atomic, set32}; use super::pci::{Ch12, FWCMD_SLOT_BYTES}; use crate::wifi::realtek::firmware::{AxImage, AxSection}; @@ -174,10 +176,10 @@ pub unsafe fn download( // before touching the chip. let sections = image .sections() - .map_err(|_| AxError::Firmware("image sections"))?; + .map_err(|_| AxError::Firmware("image sections unreadable"))?; let header = header_packet(image, H2C_SEQ_AT_DOWNLOAD); if header.len() > FWCMD_SLOT_BYTES { - return Err(AxError::Firmware("header packet too long")); + return Err(AxError::Firmware("header packet longer than a CH12 slot")); } disable_cpu(io)?; @@ -279,7 +281,8 @@ fn fw_ctrl8(io: &mut I) -> Result { Ok(value) } -/// `rtw89_fwdl_check_path_ready_ax` (`mac.c:7419`) on PCIe. +/// `rtw89_fwdl_check_path_ready_ax` (`mac.c:7419`) on PCIe; on expiry, the +/// whole register is read once more for the error. fn path_ready(io: &mut I, check: u8) -> Result<(), AxError> { match poll_sample_atomic( io, @@ -290,10 +293,27 @@ fn path_ready(io: &mut I, check: u8) -> Result<(), AxError> { |value| value & check != 0, )? { Polled::Met(_) => Ok(()), - Polled::Expired(_) => Err(AxError::Timeout { + Polled::Expired(_) => Err(expired( + io, + if check == B_AX_H2C_PATH_RDY { + "H2C path not ready" + } else { + "FWDL path not ready" + }, + )), + } +} + +/// The error of a download wait that expired: `what`, with the whole +/// `R_AX_WCPU_FW_CTRL` read once more, as `rtw89_fw_dl_fail_dump` +/// (`fw.c:1943`) reads it first. All ones there means the device is gone. +fn expired(io: &mut I, what: &'static str) -> AxError { + match io.read32(R_AX_WCPU_FW_CTRL) { + Ok(u32::MAX) => AxError::AllOnes { register: R_AX_WCPU_FW_CTRL, - mask: u32::from(check), - }), + }, + Ok(fw_ctrl) => AxError::FirmwareStatus { what, fw_ctrl }, + Err(error) => error, } } @@ -304,7 +324,7 @@ fn fwdl_status(value: u8) -> u8 { /// `rtw89_fw_check_rdy(RTW89_FWDL_CHECK_FREERTOS_DONE)` (`fw.c:106`): wait /// the whole 400 ms for `RTW89_FWDL_WCPU_FW_INIT_RDY`, then name the last -/// status. +/// status, with the whole register read after the wait. fn check_ready(io: &mut I) -> Result<(), AxError> { match poll_sample_atomic( io, @@ -315,12 +335,15 @@ fn check_ready(io: &mut I) -> Result<(), AxError> { |value| fwdl_status(value) == RTW89_FWDL_WCPU_FW_INIT_RDY, )? { Polled::Met(_) => Ok(()), - Polled::Expired(value) => Err(AxError::Firmware(match fwdl_status(value) { - RTW89_FWDL_CHECKSUM_FAIL => "checksum", - RTW89_FWDL_SECURITY_FAIL => "security", - RTW89_FWDL_CV_NOT_MATCH => "cut mismatch", - _ => "not ready", - })), + Polled::Expired(value) => Err(expired( + io, + match fwdl_status(value) { + RTW89_FWDL_CHECKSUM_FAIL => "checksum failed", + RTW89_FWDL_SECURITY_FAIL => "security check failed", + RTW89_FWDL_CV_NOT_MATCH => "cut mismatch", + _ => "not ready", + }, + )), } } diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/fwdl/tests.rs b/crates/stela-driver-net/src/wifi/realtek/ax/fwdl/tests.rs index e2ae89d669..e437f2f349 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/fwdl/tests.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/fwdl/tests.rs @@ -4,7 +4,7 @@ use crate::wifi::realtek::ax::pci::{Rings, pre_init}; use crate::wifi::realtek::ax::tests::model::{Op, RegisterModel}; use crate::wifi::realtek::beacon::tests::{Domain, Model, Source}; use crate::wifi::realtek::firmware::{Ce, Rtw89}; -use alloc::{boxed::Box, sync::Arc, vec, vec::Vec}; +use alloc::{boxed::Box, string::ToString, sync::Arc, vec, vec::Vec}; use core::sync::atomic::{AtomicU8, Ordering}; use std::sync::Mutex; @@ -351,9 +351,9 @@ fn download_sequence() { fn ready_error_codes() { let bytes = image_bytes(); let fw = Rtw89::parse(&bytes, 2, Ce::Never).unwrap(); - for (status, error) in [ - (2, "checksum"), - (3, "security"), + for (status, what) in [ + (2, "checksum failed"), + (3, "security check failed"), (4, "cut mismatch"), (1, "not ready"), (6, "not ready"), @@ -361,11 +361,20 @@ fn ready_error_codes() { let (_m, mut rings, mut io, _sent) = running(); wcpu(&mut io, 5, Arc::new(AtomicU8::new(status))); watchdog(&mut io); + // The error carries the whole 0x01E0, read once after the wait: + // FWDL_EN, both path bits and the status in [7:5]. assert_eq!( run(&mut rings, &mut io, &fw.image), - Err(AxError::Firmware(error)), + Err(AxError::FirmwareStatus { + what, + fw_ctrl: 0x07 | u32::from(status) << 5, + }), "status {status}" ); + assert_eq!( + io.trace[io.trace.len() - 2..], + [Op::R8(0x01E0), Op::R32(0x01E0)] + ); // rtw89_fw_check_rdy waits for ready for FWDL_WAIT_CNT (400 ms) of // `read_poll_timeout_atomic` budget (iopoll.h: 399_602 samples, so // 399_601 1 us waits, with free reads) and only then decodes the @@ -389,7 +398,10 @@ fn retry_after_ready_failure_starts_over() { watchdog(&mut io); assert_eq!( run(&mut rings, &mut io, &fw.image), - Err(AxError::Firmware("checksum")) + Err(AxError::FirmwareStatus { + what: "checksum failed", + fw_ctrl: 0x0000_0047, + }) ); // Linux's next __rtw89_fw_download starts with disable_cpu; the queue // continues at slot 5 and the WCPU reports ready this time. @@ -435,11 +447,12 @@ fn path_ready_timeout_sends_nothing() { let (_m, mut rings, mut io, sent) = running(); watchdog(&mut io); let began = io.now; + // FWDL_EN alone, as rtw89_mac_enable_cpu_ax left it. assert_eq!( run(&mut rings, &mut io, &fw.image), - Err(AxError::Timeout { - register: 0x01E0, - mask: 1 << 1 + Err(AxError::FirmwareStatus { + what: "H2C path not ready", + fw_ctrl: 0x0000_0001, }) ); // read_poll_timeout_atomic: 399_601 waits of 1 us with free reads. @@ -502,6 +515,46 @@ fn submit_failure_stops_the_download() { assert!(!io.trace.contains(&Op::Delay(5000))); } +#[test] +fn an_expired_wait_reads_the_whole_status_register_once() { + let mut m = RegisterModel::new(); + m.set32(0x01E0, 0x0000_0C01); + assert_eq!( + path_ready(&mut m, 1 << 2), + Err(AxError::FirmwareStatus { + what: "FWDL path not ready", + fw_ctrl: 0x0000_0C01, + }) + ); + assert_eq!(m.trace.last(), Some(&Op::R32(0x01E0))); + assert_eq!( + m.trace.iter().filter(|op| **op == Op::R32(0x01E0)).count(), + 1 + ); + assert_eq!( + AxError::FirmwareStatus { + what: "FWDL path not ready", + fw_ctrl: 0x0000_0C01, + } + .to_string(), + "FWDL path not ready (0x01E0=0x00000c01)" + ); + // A device gone by then reads all ones there: that is the error. + let mut m = RegisterModel::new(); + let mut reads = 0; + m.on_read( + 0x01E0, + Box::new(move |_: &mut RegisterModel| { + reads += 1; + if reads > 399_602 { u32::MAX } else { 0 } + }), + ); + assert_eq!( + check_ready(&mut m), + Err(AxError::AllOnes { register: 0x01E0 }) + ); +} + /// Reads of `R_AX_WCPU_FW_CTRL` (the 8-bit sample). fn ctrl_reads(m: &RegisterModel) -> usize { m.trace diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/io.rs b/crates/stela-driver-net/src/wifi/realtek/ax/io.rs index d966f1e525..a0634d3436 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/io.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/io.rs @@ -28,9 +28,22 @@ pub enum AxError { }, /// Uncalibrated, retired or non-advancing time source. Clock, + /// The firmware download refused or failed; the message says why. Firmware(&'static str), + /// The WCPU never reached the download state waited on: `what` names the + /// state, and `fw_ctrl` is the whole `R_AX_WCPU_FW_CTRL` (0x01E0) read + /// once the wait expired, as `rtw89_fw_dl_fail_dump` (`fw.c:1943`) + /// logs it. + FirmwareStatus { + what: &'static str, + fw_ctrl: u32, + }, /// The firmware file itself is missing or unusable; the message names it. FirmwareFile(&'static str), + /// The PCI function is not the chip this bring-up drives; the message + /// says what it is instead. + Identity(&'static str), + /// The rings or the CH12 queue failed; the message says how. Dma(&'static str), SecureBootUnsupported, /// The efuse could not be parsed (`-EINVAL` in `efuse.c`). @@ -57,15 +70,19 @@ impl fmt::Display for AxError { write!(f, "register {register:#x} is outside the usable window") } Self::Clock => f.write_str("time source unavailable or not advancing"), - Self::Firmware(what) => write!(f, "firmware: {what}"), - Self::FirmwareFile(what) => f.write_str(what), - Self::Dma(what) => write!(f, "dma: {what}"), + // The bring-up step already names the subsystem, so these print + // their message alone. + Self::Firmware(what) + | Self::FirmwareFile(what) + | Self::Identity(what) + | Self::Dma(what) + | Self::Efuse(what) => f.write_str(what), + Self::FirmwareStatus { what, fw_ctrl } => write!(f, "{what} (0x01E0={fw_ctrl:#010x})"), Self::SecureBootUnsupported => f.write_str("secure-boot firmware is unsupported"), - Self::Efuse(what) => write!(f, "efuse: {what}"), Self::AlreadyPowered => f.write_str("MAC has already powered on"), Self::MacPowerState(2) => f.write_str( "the MAC is in firmware-managed low power (LPS), so its firmware may still run; \ - Bus Master stays off", + Bus Master stays off; power the machine fully off (not restart) and boot again", ), Self::MacPowerState(state) => write!( f, diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/pci.rs b/crates/stela-driver-net/src/wifi/realtek/ax/pci.rs index 9f5ad929d5..14b38b0aff 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/pci.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/pci.rs @@ -639,7 +639,7 @@ impl Ch12<'_> { return Err(AxError::Dma("CH12 is stopped")); } if packet.is_empty() || packet.len() > FWCMD_SLOT_BYTES { - return Err(AxError::Dma("CH12 packet length")); + return Err(AxError::Dma("CH12 packet length out of range")); } let slot = usize::from(rings.ch12_host.get()); let at = slot * FWCMD_SLOT_BYTES; diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/pci/tests.rs b/crates/stela-driver-net/src/wifi/realtek/ax/pci/tests.rs index 0b55198060..45e61f4bef 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/pci/tests.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/pci/tests.rs @@ -460,7 +460,7 @@ fn submit_refuses_before_pre_init_and_bad_lengths() { start(&mut io, 2, &rings).unwrap(); assert!(!rings.ch12_stopped()); io.trace.clear(); - let length = Err(AxError::Dma("CH12 packet length")); + let length = Err(AxError::Dma("CH12 packet length out of range")); assert_eq!(send(&mut rings, &mut io, &[]), length); assert_eq!(send(&mut rings, &mut io, &[0; 4097]), length); assert!(io.trace.is_empty()); diff --git a/crates/stela-driver-net/src/wifi/realtek/ax/power.rs b/crates/stela-driver-net/src/wifi/realtek/ax/power.rs index 949bef0987..f163a9f6b8 100644 --- a/crates/stela-driver-net/src/wifi/realtek/ax/power.rs +++ b/crates/stela-driver-net/src/wifi/realtek/ax/power.rs @@ -209,14 +209,22 @@ pub(crate) fn power_switch_off(io: &mut I) -> Result<(), AxErr io.write8(R_AX_SCOREBOARD + 3, MAC_AX_NOTIFY_PWR_MAJOR) } +/// Both failures of a [`power_on`] whose retry failed too. Linux returns only +/// the retry's; the first is kept as the likelier root cause. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PowerOnError { + pub first: AxError, + pub retry: AxError, +} + /// `rtw89_mac_pwr_on`: on any failure, power off (its result ignored) and /// try the power switch once more. -pub fn power_on(io: &mut I) -> Result<(), AxError> { - if power_on_once(io).is_ok() { +pub fn power_on(io: &mut I) -> Result<(), PowerOnError> { + let Err(first) = power_on_once(io) else { return Ok(()); - } + }; let _ = power_switch_off(io); - power_on_once(io) + power_on_once(io).map_err(|retry| PowerOnError { first, retry }) } /// `rtw8852c_pwr_on_func` (`rtw8852c.c:327-437`), PCIe. @@ -626,13 +634,52 @@ mod tests { fn power_on_still_on_after_retry_is_an_error() { let mut m = settled(); m.on_read(0x03F0, Box::new(|_m: &mut RegisterModel| 0x100)); - assert_eq!(power_on(&mut m), Err(AxError::AlreadyPowered)); + assert_eq!( + power_on(&mut m), + Err(PowerOnError { + first: AxError::AlreadyPowered, + retry: AxError::AlreadyPowered, + }) + ); // Exactly one power-off ran; the power-on body never started. let mut expected = off_trace(); expected.push(Op::W8(0x00AF, 0x80)); assert_eq!(m.writes(), expected); } + #[test] + fn power_on_keeps_the_first_error_when_the_retry_fails_differently() { + // The MAC reads on at first; after the power-off it reads off, but + // RDY_SYSPWR never comes up. + let mut m = RegisterModel::new(); + m.on_read( + 0x0004, + Box::new(|m: &mut RegisterModel| m.get32(0x0004) & !(1 << 17 | 1 << 8 | 1 << 9)), + ); + m.on_read( + 0x0270, + Box::new(|m: &mut RegisterModel| m.get32(0x0270) & 0x7FFF_FFFF), + ); + let mut reads = 0; + m.on_read( + 0x03F0, + Box::new(move |_m: &mut RegisterModel| { + reads += 1; + if reads == 1 { 0x100 } else { 0 } + }), + ); + assert_eq!( + power_on(&mut m), + Err(PowerOnError { + first: AxError::AlreadyPowered, + retry: AxError::Timeout { + register: 0x0004, + mask: 1 << 17 + }, + }) + ); + } + #[test] fn power_on_failure_midway_powers_off_then_retries() { // rtw89_mac_pwr_on retries after any power_switch failure, and diff --git a/crates/stela-drivers/src/probe.rs b/crates/stela-drivers/src/probe.rs index 75b975172b..ea1a49f970 100644 --- a/crates/stela-drivers/src/probe.rs +++ b/crates/stela-drivers/src/probe.rs @@ -951,6 +951,19 @@ fn rtw89_started(devices: &mut Devices, address: Address, class: [u8; 3], up: na devices.owners.push(up.kept); } +/// Record an RTL8852CE whose bring-up failed: whether its MAC had been left +/// on and was powered off, as on success, then the failure. Whatever it +/// claimed stays kept. +fn rtw89_failed(devices: &mut Devices, address: Address, down: native::Rtw89Down) { + if down.was_on { + devices + .warnings + .push((address, Warning::Message(RTW89_WAS_ON))); + } + devices.failures.push((address, down.error)); + devices.owners.extend(down.kept); +} + /// The function a driver here claimed whose start is being accounted for, /// with the count of outcomes recorded before it started. #[derive(Default)] @@ -2776,10 +2789,7 @@ unsafe fn attach_native( // SAFETY: as for tg3 below. match unsafe { native::rtw89_wifi(services, address, rtw89) } { Ok(up) => rtw89_started(devices, address, function.class, up), - Err((error, kept)) => { - devices.failures.push((address, error)); - devices.owners.extend(kept); - } + Err(down) => rtw89_failed(devices, address, down), } return; } @@ -4269,6 +4279,57 @@ mod tests { assert!(devices.failures.is_empty()); } + /// An RTL8852CE whose MAC was left on and powered off, then whose + /// bring-up failed, still says its MAC was left on, before the failure, + /// and its owner is kept. + #[test] + fn an_rtl8852ce_that_failed_after_its_mac_was_powered_off_says_so() { + use net::wifi::realtek::ax::{AxError, BringUpError, Earlier}; + let wifi = identity(3, 0, 0x10ec, 0xc852, 0x02_80_00); + let mut devices = Devices { + network_functions: alloc::vec![wifi], + ..Devices::default() + }; + let down = native::Rtw89Down { + error: Error::Rtw89Wifi(BringUpError { + step: "firmware download", + error: AxError::FirmwareStatus { + what: "not ready", + fw_ctrl: 0x0000_0007, + }, + earlier: Earlier::First { + tries: 5, + error: AxError::Timeout { + register: 0x1080, + mask: 0x0FFF_0000, + }, + }, + }), + was_on: true, + kept: Some(Box::new(())), + }; + rtw89_failed(&mut devices, wifi.address, down); + let warnings: Vec = devices + .warnings + .iter() + .map(|(address, warning)| format!("HOST WARNING pci={address}: {warning}")) + .collect(); + assert_eq!( + warnings, + [ + "HOST WARNING pci=0000:03:00.0: RTL8852CE: its MAC was left powered on; Stela \ + powered it off before taking the device over" + ] + ); + assert_eq!(devices.failures.len(), 1); + assert_eq!( + format!("{}", devices.failures[0].1), + "rtw89: RTL8852CE bring-up: firmware download: not ready (0x01E0=0x00000007) (first \ + of 5 attempts: timeout waiting on register 0x1080 mask 0xfff0000)" + ); + assert_eq!(devices.owners.len(), 1); + } + /// A warning of owned text prints on the boot log's `HOST WARNING` /// line, as an RTL8852CE's running firmware does. #[test] diff --git a/crates/stela-drivers/src/probe/native.rs b/crates/stela-drivers/src/probe/native.rs index 2326e66efe..ddd2fa6709 100644 --- a/crates/stela-drivers/src/probe/native.rs +++ b/crates/stela-drivers/src/probe/native.rs @@ -676,6 +676,27 @@ pub struct Rtw89Inputs { pub clock: Clock, } +/// An RTL8852CE whose bring-up failed. +pub struct Rtw89Down { + pub error: Error, + /// As [`Rtw89Up::was_on`]: whether its MAC had been left on, and so was + /// powered off, before the failure. + pub was_on: bool, + /// Whatever must outlive the device once claimed: its requester and + /// domain, its BAR2 mapping and register window, and any rings. + pub kept: Option>, +} + +impl From for Rtw89Down { + fn from((error, kept): Failure) -> Self { + Self { + error, + was_on: false, + kept, + } + } +} + /// An RTL8852CE whose firmware ran, powered off again. pub struct Rtw89Up { pub running: Running, @@ -706,7 +727,7 @@ pub(super) unsafe fn rtw89_wifi( services: &dyn NativeServices, address: Address, inputs: Rtw89Inputs, -) -> Result { +) -> Result { let minimum = services .minimum_delay() .map_err(|error| (Error::Native(error), None))?; @@ -714,14 +735,14 @@ pub(super) unsafe fn rtw89_wifi( let mut preparing = services.prepare_requester(address).map_err(refused)?; let bars = match rtw89_wake(preparing.function_mut(), minimum.as_ref()) { Ok(bars) => bars, - Err(error) => return Err(keep_error(error, preparing)), + Err(error) => return Err(keep_error(error, preparing).into()), }; // A BAR is mapped during preparation, before any binding, as Intel's // PCIe Bluetooth maps its BAR0: the mapping grants register access only, // and the seal still holds Bus Master clear. let registers = match map(services, address, &bars, 2) { Ok(registers) => registers, - Err(error) => return Err(keep_error(Error::Native(error), preparing)), + Err(error) => return Err(keep_error(Error::Native(error), preparing).into()), }; let (base, bytes) = match registers .bytes() @@ -732,13 +753,14 @@ pub(super) unsafe fn rtw89_wifi( return Err(keep_error( Error::Native(ServiceError::Mapping(error)), (preparing, registers), - )); + ) + .into()); } }; let (subsystem_vendor, subsystem_device, pci_revision) = match rtw89_decode(preparing.function_mut()) { Ok(identity) => identity, - Err(error) => return Err(keep_error(error, (preparing, registers))), + Err(error) => return Err(keep_error(error, (preparing, registers)).into()), }; let (vendor, device) = { let function = preparing.function_mut(); @@ -753,25 +775,20 @@ pub(super) unsafe fn rtw89_wifi( { Ok(io) => io, Err(error) => { - let error = BringUpError { - step: "register window", - error, - }; + let error = BringUpError::new("register window", error); return Err(( Error::Rtw89Wifi(error), - Some(Box::new((preparing, mapping))), - )); + Some(Box::new((preparing, mapping)) as Box), + ) + .into()); } }; // SYS_CFG1, with memory decode on: a read only. let sys_cfg1 = match io.read32(0xf0) { Ok(sys_cfg1) => sys_cfg1, Err(error) => { - let error = BringUpError { - step: "identity", - error, - }; - return Err((Error::Rtw89Wifi(error), Some(Box::new((preparing, io))))); + let error = BringUpError::new("identity", error); + return Err(keep_error(Error::Rtw89Wifi(error), (preparing, io)).into()); } }; let observed = realtek_wifi::identity::Observed { @@ -803,7 +820,11 @@ pub(super) unsafe fn rtw89_wifi( }), // A failure after the rings were programmed left them quarantined; // the requester, its domain and BAR2 stay kept. - Err(error) => Err((error, Some(Box::new(device)))), + Err((error, was_on)) => Err(Rtw89Down { + error, + was_on, + kept: Some(Box::new(device)), + }), } } @@ -947,7 +968,9 @@ impl Rtw89Device for Rtw89Native { /// 4. set Bus Master; /// 5. [`bring_up`] on that domain. /// -/// Returns the report, the rings DMA ran on, and whether the MAC was on. +/// Returns the report, the rings DMA ran on, and whether the MAC was on; +/// a failure is returned with whether the MAC was on as well, since a MAC +/// left on was powered off before any failure past step 2. /// /// # Safety /// `device.io()` is the exclusive uncached BAR2 window of the original PCI @@ -967,10 +990,11 @@ pub(super) unsafe fn rtw89_attach( observed: realtek_wifi::identity::Observed, firmware: &dyn crate::firmware::Provider, pages: &dyn PageSource, -) -> Result<(Running, Rings, bool), Error> { +) -> Result<(Running, Rings, bool), (Error, bool)> { use realtek_wifi::firmware::Layout; - let fail = |step, error| Error::Rtw89Wifi(BringUpError { step, error }); - let (profile, staged) = rtw89_stage(observed, firmware).map_err(Error::Rtw89Wifi)?; + let fail = |step, error| (Error::Rtw89Wifi(BringUpError::new(step, error)), false); + let (profile, staged) = + rtw89_stage(observed, firmware).map_err(|error| (Error::Rtw89Wifi(error), false))?; let Layout::Rtw89(parsed) = &staged.layout else { return Err(fail( "firmware", @@ -978,6 +1002,28 @@ pub(super) unsafe fn rtw89_attach( )); }; let was_on = quiesce(device.io()).map_err(|error| fail("quiesce", error))?; + // SAFETY: this function's contract, with the chip just quiesced. + match unsafe { rtw89_take_over(device, profile.cut(), &parsed.image, pages) } { + Ok((running, rings)) => Ok((running, rings, was_on)), + Err(error) => Err((error, was_on)), + } +} + +/// Steps 3 to 5 of [`rtw89_attach`], on a chip [`quiesce`] just stopped. +/// +/// # Safety +/// As for [`rtw89_attach`], and `quiesce` returned `Ok` on `device.io()` +/// just before. +#[expect( + clippy::result_large_err, + reason = "The shared error preserves exact source and cleanup causes without allocating on propagation." +)] +unsafe fn rtw89_take_over( + device: &mut D, + cut: u8, + image: &realtek_wifi::firmware::AxImage<'_>, + pages: &dyn PageSource, +) -> Result<(Running, Rings), Error> { // SAFETY: `acknowledge_quiescence`'s contract, point by point: // - Engine stop and submission exclusion, with no restart: Bus Master // has been clear since the mount parked the function, so no engine of @@ -1004,7 +1050,6 @@ pub(super) unsafe fn rtw89_attach( // Stela DMA backing before this point. let domain = unsafe { device.finalize() }?; device.master()?; - let image = &parsed.image; // SAFETY: `bring_up`'s contract: // - `device.io()` is the exclusive register window of exactly the // requester whose own domain `finalize` just bound: the receipt @@ -1016,9 +1061,7 @@ pub(super) unsafe fn rtw89_attach( // Bus Master, memory decode and INTx Disable). // - One worker: the probe drives this function alone, with no // interrupt handler, reset or other engine reaching it. - let (running, rings) = unsafe { bring_up(device.io(), pages, domain, profile.cut(), image) } - .map_err(Error::Rtw89Wifi)?; - Ok((running, rings, was_on)) + unsafe { bring_up(device.io(), pages, domain, cut, image) }.map_err(Error::Rtw89Wifi) } /// The RTL8852C profile of `observed`, and its firmware staged from @@ -1034,7 +1077,7 @@ fn rtw89_stage( BringUpError, > { use realtek_wifi::identity::{Chip, IdentityError, Profile}; - let fail = |step, error| BringUpError { step, error }; + let fail = BringUpError::new; let profile = match Profile::select(observed) { Ok(profile) if profile.chip() == Chip::Rtl8852C => profile, Err(IdentityError::FailedRead) => { @@ -1043,7 +1086,9 @@ fn rtw89_stage( Ok(_) | Err(IdentityError::UnsupportedPci | IdentityError::TestChip) => { return Err(fail( "identity", - AxError::FirmwareFile("not an RTL8852CE, whose firmware this is"), + AxError::Identity( + "its PCI vendor and device IDs are not the RTL8852CE's 10ec:c852", + ), )); } }; @@ -2071,7 +2116,11 @@ mod tests { let result = unsafe { rtw89_wifi(&services, address(), inputs) }; assert!(matches!( result, - Err((Error::Native(ServiceError::Unavailable), None)) + Err(Rtw89Down { + error: Error::Native(ServiceError::Unavailable), + was_on: false, + kept: None, + }) )); // Through the cold preparation, never the sealed stopped claim. assert_eq!(*services.preparations.borrow(), [address()]); @@ -2253,7 +2302,7 @@ mod tests { } /// What [`rtw89_attach`] returns. - type Attached = Result<(Running, Rings, bool), Error>; + type Attached = Result<(Running, Rings, bool), (Error, bool)>; /// Run [`rtw89_attach`] on a chip whose MAC reads `mac`. fn attach( @@ -2286,8 +2335,8 @@ mod tests { #[test] fn missing_firmware_fails_before_any_register_access() { let (events, result) = attach(0, false, &crate::firmware::HandoffProvider::new(None)); - let Err(error) = result else { - panic!("an RTL8852CE came up with no firmware") + let Err((error, false)) = result else { + panic!("an RTL8852CE came up with no firmware, or its MAC read on") }; assert!(events.is_empty(), "{events:x?}"); assert!(matches!( @@ -2295,6 +2344,7 @@ mod tests { Error::Rtw89Wifi(BringUpError { step: "firmware", error: AxError::FirmwareFile("rtw89/rtw8852c_fw-2.bin is not on the USB stick"), + .. }) )); let at = address(); @@ -2326,8 +2376,8 @@ mod tests { &crate::firmware::HandoffProvider::new(Some(&catalog)), ); assert!(events.is_empty(), "{events:x?}"); - let Err(error) = result else { - panic!("an RTL8852CE came up on a malformed image") + let Err((error, false)) = result else { + panic!("an RTL8852CE came up on a malformed image, or its MAC read on") }; assert_eq!( alloc::format!("{error}"), @@ -2363,20 +2413,24 @@ mod tests { assert!(events.len() > 3); assert!(matches!( result, - Err(Error::Rtw89Wifi(BringUpError { step, .. })) if step != "firmware" && step != "quiesce" + Err((Error::Rtw89Wifi(BringUpError { step, .. }), false)) + if step != "firmware" && step != "quiesce" )); } /// A chip left on is powered off, coex told last, before its - /// quiescence is acknowledged; nothing is written before that. + /// quiescence is acknowledged; nothing is written before that. The + /// bring-up after it fails here (the model domain maps nothing), and the + /// failure still says the MAC was left on. #[test] fn a_chip_left_on_is_powered_off_before_the_acknowledgement() { let catalog = empty_image(); - let (events, _) = attach( + let (events, result) = attach( 0x100, false, &crate::firmware::HandoffProvider::new(Some(&catalog)), ); + assert!(matches!(result, Err((Error::Rtw89Wifi(_), true)))); let finalize = position(&events, Event::Finalize); assert_eq!(events[0], Event::Read(0x03F0)); let before = &events[..finalize]; @@ -2413,14 +2467,15 @@ mod tests { &crate::firmware::HandoffProvider::new(Some(&catalog)), ); assert_eq!(events, [Event::Read(0x03F0)], "{mac:#x}"); - let Err(error) = result else { - panic!("a MAC in state {state} came up") + let Err((error, false)) = result else { + panic!("a MAC in state {state} came up, or was taken as on") }; assert!(matches!( error, Error::Rtw89Wifi(BringUpError { step: "quiesce", error: AxError::MacPowerState(found), + .. }) if found == state )); if state == 2 { @@ -2433,7 +2488,8 @@ mod tests { ), "HOST DEVICE FAILED pci=0000:03:00.0 (Wi-Fi) error=rtw89: RTL8852CE bring-up: \ quiesce: the MAC is in firmware-managed low power (LPS), so its firmware may \ - still run; Bus Master stays off" + still run; Bus Master stays off; power the machine fully off (not restart) \ + and boot again" ); } } @@ -2449,8 +2505,8 @@ mod tests { &crate::firmware::HandoffProvider::new(Some(&catalog)), ); assert!(events.is_empty(), "{events:x?}"); - let Err(error) = result else { - panic!("an RTL8852CE came up on the firmware of another adapter") + let Err((error, false)) = result else { + panic!("an RTL8852CE came up on the firmware of another adapter, or its MAC read on") }; assert_eq!( alloc::format!("{error}"), @@ -2493,10 +2549,28 @@ mod tests { assert_eq!(events, [Event::Read(0x03F0), Event::Finalize]); assert!(matches!( result, - Err(Error::Native(ServiceError::Refused("model refusal"))) + Err((Error::Native(ServiceError::Refused("model refusal")), false)) )); } + /// A function whose IDs name another chip fails its identity, with no + /// firmware wording. + #[test] + fn another_chip_is_refused_by_its_identity() { + let observed = realtek_wifi::identity::Observed { + device: 0xb852, + ..rtl8852ce() + }; + let Err(error) = rtw89_stage(observed, &crate::firmware::HandoffProvider::new(None)) else { + panic!("an RTL8852BE was staged as an RTL8852CE") + }; + assert_eq!( + alloc::format!("{error}"), + "RTL8852CE bring-up: identity: its PCI vendor and device IDs are not the RTL8852CE's \ + 10ec:c852" + ); + } + /// An RTL8852CE configuration space with MSI enabled by firmware: /// subsystem 1043:1b0d, revision 0, and an MSI capability at 0x50. struct Config([u32; 64], Vec);