git clone https://garage44.eu/jeroen/pinnacle.gitcartopolis-agent · 2026-11-30T14:36:15Z
feat(wifi): Intel's firmware files and boot structures, read (wifi::iwl) A no_std module for the kernel's Intel driver and the host's tests, written from Linux's iwlwifi as the reference for the formats: - the .ucode TLV container: header (magic, human-readable version, ver, build), SEC_RT/SEC_INIT/SEC_WOWLAN (and their SECURE_ forms) into images, IML, PAGING, NUM_OF_CPU, PHY_SKU, FLAGS, API_CHANGES_SET, ENABLED_CAPABILITIES, FW_VERSION; each length checked, an error saying where; an image split into LMAC, UMAC and paged sections at the separators, as iwl_pcie_init_fw_sec counts them; - the .pnvm file: its sections per SKU, their HW_TYPE pairs, version and payloads, and the one for a chip's SKU, MAC and radio; - Chip and firmware_name: from CSR_HW_REV and CSR_HW_RF_ID to the file iwl_drv_get_fwname_pre names (and why none, for a radio or step not carried); rf_id_from_crf for a blank OTP, as map_crf_id; - context_info (22000 family), prph_scratch and context_info_v2 (AX210 family) as bytes at Linux's offsets; - rx_packet and Alive: a packet in a receive buffer and the ALIVE notification, version 3 and 4 on. Tested: cargo test -p pinnacle-wifi on mac-2, 24 tests; synthetic files always, and Intel's own ten files when `cargo xtask firmware` has fetched them (the test says it skipped otherwise): every .ucode parses (77.3cda2a2c.0 and 89.a67023b2.0, 14-15 LMAC, 15-17 UMAC, 20-26 paged sections, IML only in the AX210 family's), every .pnvm has 4 SKU sections fitting its chip; every file firmware_name names is one the description carries. Clippy shows nothing.
wifi/src/iwl.rs | 826 ++++++++++++++++++++++++++++++++++++++++++++++++++
wifi/src/iwl/tests.rs | 453 +++++++++++++++++++++++++++
wifi/src/lib.rs | 4 +
3 files changed, 1283 insertions(+)
diff --git a/wifi/src/iwl.rs b/wifi/src/iwl.rs
new file mode 100644
index 0000000..73ac4c2
--- /dev/null
+++ b/wifi/src/iwl.rs
@@ -0,0 +1,826 @@
+//! Intel's Wi-Fi as data: the firmware files the chip runs, which file a
+//! chip needs, the structures that tell it where its firmware is, and what
+//! it says when it has started. Pure functions over bytes, for the
+//! kernel's driver (`kernel/src/drivers/iwlwifi.rs`) and for host tests.
+//!
+//! Written from Linux's `iwlwifi` (`fw/file.h`, `iwl-drv.c`, `fw/pnvm.c`,
+//! `pcie/ctxt-info*.c`, `fw/api/alive.h`, `fw/api/ctxt-info*.h`) as the
+//! reference for the formats; no code of it is here. The firmware itself
+//! is Intel's closed code and is never run by Pinnacle, only handed to the
+//! chip: this reads its container (the TLV list Linux documents), not the
+//! code inside.
+//!
+//! - [`Ucode`]: a `.ucode` file. A header (zero, the magic `IWL\n`, 64
+//! bytes of human-readable version, a version and a build number) and a
+//! list of TLVs, each a type, a length and that many bytes padded to 4.
+//! The sections the chip loads come as `SEC_RT` (the regular image),
+//! `SEC_INIT` and `SEC_WOWLAN`, each an address in the chip and the bytes
+//! for it; in an image, the LMAC's sections come first, then a separator
+//! section, the UMAC's, another separator, then the paged ones
+//! ([`Image::layout`]).
+//! - [`Pnvm`]: a `.pnvm` file, the platform's settings the AX210 family's
+//! firmware asks for once it runs: a TLV list of sections, one per SKU,
+//! each with the chips it is for and its payload.
+//! - [`Chip`] and [`firmware_name`]: from the MAC's and the radio's
+//! revision registers to the file Linux would load.
+//! - [`context_info`], [`prph_scratch`], [`context_info_v2`]: the
+//! structures the 22000 family (AX201) and the AX210 family read, in
+//! DMA memory, to find their firmware and their first queues.
+//! - [`rx_packet`], [`Alive`]: a packet the chip put in a receive buffer,
+//! and the ALIVE notification it sends once its firmware runs.
+
+use alloc::string::String;
+use alloc::vec::Vec;
+
+/// `IWL\n`, little-endian: a TLV firmware file.
+pub const MAGIC: u32 = 0x0a4c_5749;
+/// A section with this address ends the LMAC's sections.
+pub const CPU1_CPU2_SEPARATOR: u32 = 0xffff_cccc;
+/// A section with this address ends the UMAC's; paged sections follow.
+pub const PAGING_SEPARATOR: u32 = 0xaaaa_bbbb;
+/// Linux's limits: at most 64 DRAM chunks per kind (`IWL_MAX_DRAM_ENTRY`),
+/// and the paged image at most 33 blocks of 32 KiB (`MAX_PAGING_IMAGE_SIZE`).
+pub const MAX_DRAM_ENTRIES: usize = 64;
+const MAX_PAGING: u32 = 33 * 8 * 4096;
+const HEADER: usize = 88;
+
+/// TLV types (`enum iwl_ucode_tlv_type`).
+pub mod tlv {
+ pub const INST: u32 = 1;
+ pub const DATA: u32 = 2;
+ pub const INIT: u32 = 3;
+ pub const INIT_DATA: u32 = 4;
+ pub const MEM_DESC: u32 = 7;
+ pub const FLAGS: u32 = 18;
+ pub const SEC_RT: u32 = 19;
+ pub const SEC_INIT: u32 = 20;
+ pub const SEC_WOWLAN: u32 = 21;
+ pub const PHY_SKU: u32 = 23;
+ pub const SECURE_SEC_RT: u32 = 24;
+ pub const SECURE_SEC_INIT: u32 = 25;
+ pub const SECURE_SEC_WOWLAN: u32 = 26;
+ pub const NUM_OF_CPU: u32 = 27;
+ pub const API_CHANGES_SET: u32 = 29;
+ pub const ENABLED_CAPABILITIES: u32 = 30;
+ pub const PAGING: u32 = 32;
+ pub const FW_VERSION: u32 = 36;
+ pub const IML: u32 = 52;
+ pub const HW_TYPE: u32 = 58;
+ pub const PNVM_VERSION: u32 = 62;
+ pub const PNVM_SKU: u32 = 64;
+}
+
+/// Why a file was not taken: each says where, for a boot log.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Error {
+ /// Shorter than the header.
+ TooShort(usize),
+ /// Its first word is not zero: an old (pre-TLV) file.
+ NotTlv,
+ /// Not `IWL\n`.
+ Magic(u32),
+ /// A TLV at this offset runs past the end.
+ Overrun { at: usize, tlv: u32, len: u32 },
+ /// A TLV whose length is not what its type has.
+ Length { tlv: u32, len: u32 },
+ /// A section TLV shorter than its address.
+ Section { at: usize },
+ /// The paged image's size, too large or not whole pages.
+ Paging(u32),
+ /// More CPUs than two.
+ Cpus(u32),
+ /// The regular image has no sections.
+ NoImage,
+ /// More sections of one kind than the chip's map holds.
+ TooManySections { kind: &'static str, count: usize },
+}
+
+impl core::fmt::Display for Error {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ match *self {
+ Error::TooShort(n) => write!(f, "{n} bytes, shorter than a firmware file's header"),
+ Error::NotTlv => write!(f, "not a TLV firmware file (its first word is not zero)"),
+ Error::Magic(m) => write!(f, "magic {m:#010x}, not IWL"),
+ Error::Overrun { at, tlv, len } => {
+ write!(f, "TLV {tlv} at byte {at} says {len} bytes, past the end")
+ }
+ Error::Length { tlv, len } => write!(f, "TLV {tlv} has {len} bytes, not its size"),
+ Error::Section { at } => write!(f, "a section at byte {at} too short for its address"),
+ Error::Paging(n) => write!(f, "a paged image of {n} bytes"),
+ Error::Cpus(n) => write!(f, "{n} CPUs (at most 2)"),
+ Error::NoImage => write!(f, "no regular image (SEC_RT)"),
+ Error::TooManySections { kind, count } => write!(f, "{count} {kind} sections (at most 64)"),
+ }
+ }
+}
+
+fn u16_at(b: &[u8], at: usize) -> u16 {
+ u16::from_le_bytes([b[at], b[at + 1]])
+}
+
+fn u32_at(b: &[u8], at: usize) -> u32 {
+ u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
+}
+
+/// The TLVs of `bytes`, each (offset of its header, type, data), checked
+/// against the end; the first error ends the list.
+fn tlvs(bytes: &[u8], base: usize) -> impl Iterator<Item = Result<(usize, u32, &[u8]), Error>> {
+ let mut at = 0;
+ let mut failed = false;
+ core::iter::from_fn(move || {
+ if failed || bytes.len() - at < 8 {
+ return None;
+ }
+ let (kind, len) = (u32_at(bytes, at), u32_at(bytes, at + 4));
+ let start = at + 8;
+ let padded = (len as usize).next_multiple_of(4);
+ if bytes.len() - start < len as usize {
+ failed = true;
+ return Some(Err(Error::Overrun {
+ at: base + at,
+ tlv: kind,
+ len,
+ }));
+ }
+ let data = &bytes[start..start + len as usize];
+ let here = at;
+ // The last TLV's padding may be missing.
+ at = (start + padded).min(bytes.len());
+ Some(Ok((base + here, kind, data)))
+ })
+}
+
+/// One section of an image: where in the chip it goes, and its bytes.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Section<'a> {
+ pub offset: u32,
+ pub data: &'a [u8],
+}
+
+/// An image: its sections in the file's order, separators included.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Image<'a> {
+ pub sections: Vec<Section<'a>>,
+}
+
+/// An image's sections as the chip's DRAM map has them.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Layout<'a> {
+ pub lmac: Vec<Section<'a>>,
+ pub umac: Vec<Section<'a>>,
+ pub paging: Vec<Section<'a>>,
+}
+
+impl<'a> Image<'a> {
+ /// The LMAC's sections (up to the first separator), the UMAC's (to the
+ /// next) and the paged ones (after it), as Linux's
+ /// `iwl_pcie_init_fw_sec` counts them: each run ends at either
+ /// separator.
+ pub fn layout(&self) -> Result<Layout<'a>, Error> {
+ let separator = |s: &Section| s.offset == CPU1_CPU2_SEPARATOR || s.offset == PAGING_SEPARATOR;
+ let run = |from: usize| -> Vec<Section<'a>> {
+ self.sections
+ .get(from..)
+ .unwrap_or(&[])
+ .iter()
+ .take_while(|s| !separator(s))
+ .copied()
+ .collect()
+ };
+ let lmac = run(0);
+ let umac = run(lmac.len() + 1);
+ let paging = run(lmac.len() + umac.len() + 2);
+ for (kind, list) in [("LMAC", &lmac), ("UMAC", &umac), ("paged", &paging)] {
+ if list.len() > MAX_DRAM_ENTRIES {
+ return Err(Error::TooManySections {
+ kind,
+ count: list.len(),
+ });
+ }
+ }
+ Ok(Layout { lmac, umac, paging })
+ }
+
+ /// Bytes in all its sections, separators aside.
+ pub fn bytes(&self) -> usize {
+ self.sections
+ .iter()
+ .filter(|s| s.offset != CPU1_CPU2_SEPARATOR && s.offset != PAGING_SEPARATOR)
+ .map(|s| s.data.len())
+ .sum()
+ }
+}
+
+/// A `.ucode` file, read.
+#[derive(Clone, Debug, Default)]
+pub struct Ucode<'a> {
+ /// What the file calls its version: `release/core86:signed_remote:a67023b2`.
+ pub human_readable: &'a str,
+ /// The header's version word (major in the top byte in new files) and
+ /// build.
+ pub ver: u32,
+ pub build: u32,
+ /// `FW_VERSION`: major, minor, local component.
+ pub fw_version: Option<(u32, u32, u32)>,
+ pub regular: Image<'a>,
+ pub init: Image<'a>,
+ pub wowlan: Image<'a>,
+ /// The image loader the AX210 family's boot ROM runs first.
+ pub iml: Option<&'a [u8]>,
+ pub paging_mem_size: Option<u32>,
+ pub cpus: Option<u32>,
+ /// `PHY_SKU`: the radio's configuration and antennas.
+ pub phy_sku: Option<u32>,
+ pub flags: Option<u32>,
+ /// `API_CHANGES_SET` and `ENABLED_CAPABILITIES`: (index, 32 bits).
+ pub api: Vec<(u32, u32)>,
+ pub capa: Vec<(u32, u32)>,
+ /// TLVs in all, and of types not read here.
+ pub tlvs: usize,
+ pub other: usize,
+}
+
+impl Ucode<'_> {
+ /// The version as Linux prints it: `89.a67023b2.0` from `FW_VERSION`,
+ /// else the header's four bytes.
+ pub fn version(&self) -> String {
+ match self.fw_version {
+ Some((major, minor, local)) => alloc::format!("{major}.{minor:08x}.{local}"),
+ None => alloc::format!(
+ "{}.{}.{}.{}",
+ self.ver >> 24,
+ (self.ver >> 16) & 0xff,
+ (self.ver >> 8) & 0xff,
+ self.ver & 0xff
+ ),
+ }
+ }
+}
+
+/// Reads a `.ucode` file as Linux's `iwl_parse_tlv_firmware` does, keeping
+/// what loading it needs.
+pub fn parse(bytes: &[u8]) -> Result<Ucode<'_>, Error> {
+ if bytes.len() < HEADER {
+ return Err(Error::TooShort(bytes.len()));
+ }
+ if u32_at(bytes, 0) != 0 {
+ return Err(Error::NotTlv);
+ }
+ let magic = u32_at(bytes, 4);
+ if magic != MAGIC {
+ return Err(Error::Magic(magic));
+ }
+ let name = &bytes[8..72];
+ let name = &name[..name.iter().position(|&b| b == 0).unwrap_or(name.len())];
+ let mut ucode = Ucode {
+ human_readable: core::str::from_utf8(name).unwrap_or(""),
+ ver: u32_at(bytes, 72),
+ build: u32_at(bytes, 76),
+ ..Ucode::default()
+ };
+ let word = |kind: u32, data: &[u8]| -> Result<u32, Error> {
+ if data.len() != 4 {
+ return Err(Error::Length {
+ tlv: kind,
+ len: data.len() as u32,
+ });
+ }
+ Ok(u32_at(data, 0))
+ };
+ for item in tlvs(&bytes[HEADER..], HEADER) {
+ let (at, kind, data) = item?;
+ ucode.tlvs += 1;
+ let section = || -> Result<Section<'_>, Error> {
+ if data.len() < 4 {
+ return Err(Error::Section { at });
+ }
+ Ok(Section {
+ offset: u32_at(data, 0),
+ data: &data[4..],
+ })
+ };
+ match kind {
+ tlv::SEC_RT | tlv::SECURE_SEC_RT => ucode.regular.sections.push(section()?),
+ tlv::SEC_INIT | tlv::SECURE_SEC_INIT => ucode.init.sections.push(section()?),
+ tlv::SEC_WOWLAN | tlv::SECURE_SEC_WOWLAN => ucode.wowlan.sections.push(section()?),
+ tlv::IML => ucode.iml = Some(data),
+ tlv::PAGING => {
+ let size = word(kind, data)?;
+ if size > MAX_PAGING || !size.is_multiple_of(4096) {
+ return Err(Error::Paging(size));
+ }
+ ucode.paging_mem_size = Some(size);
+ }
+ tlv::NUM_OF_CPU => {
+ let n = word(kind, data)?;
+ if !(1..=2).contains(&n) {
+ return Err(Error::Cpus(n));
+ }
+ ucode.cpus = Some(n);
+ }
+ tlv::PHY_SKU => ucode.phy_sku = Some(word(kind, data)?),
+ tlv::FLAGS => ucode.flags = Some(word(kind, data)?),
+ tlv::API_CHANGES_SET | tlv::ENABLED_CAPABILITIES => {
+ if data.len() != 8 {
+ return Err(Error::Length {
+ tlv: kind,
+ len: data.len() as u32,
+ });
+ }
+ let entry = (u32_at(data, 0), u32_at(data, 4));
+ if kind == tlv::API_CHANGES_SET {
+ ucode.api.push(entry);
+ } else {
+ ucode.capa.push(entry);
+ }
+ }
+ tlv::FW_VERSION => {
+ if data.len() != 12 {
+ return Err(Error::Length {
+ tlv: kind,
+ len: data.len() as u32,
+ });
+ }
+ ucode.fw_version = Some((u32_at(data, 0), u32_at(data, 4), u32_at(data, 8)));
+ }
+ _ => ucode.other += 1,
+ }
+ }
+ if ucode.regular.sections.is_empty() {
+ return Err(Error::NoImage);
+ }
+ Ok(ucode)
+}
+
+/// One section of a `.pnvm` file: the SKU it is for, and what it holds.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct PnvmSku<'a> {
+ pub sku_id: [u32; 3],
+ pub version: Option<u32>,
+ /// (MAC type, RF type) pairs it says it fits.
+ pub hw_types: Vec<(u16, u16)>,
+ /// Its payloads (`SEC_RT`, their address dropped), for the chip.
+ pub chunks: Vec<&'a [u8]>,
+ /// A `MEM_DESC` instead of chunks (newer files).
+ pub mem_desc: bool,
+}
+
+impl PnvmSku<'_> {
+ /// Whether it is for a chip of `mac_type` with a radio of `rf_type`.
+ pub fn fits(&self, mac_type: u16, rf_type: u16) -> bool {
+ self.hw_types.iter().any(|&(m, r)| m == mac_type && r == rf_type)
+ }
+}
+
+/// A `.pnvm` file: its sections in order.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Pnvm<'a> {
+ pub skus: Vec<PnvmSku<'a>>,
+}
+
+impl<'a> Pnvm<'a> {
+ /// Reads it as Linux's `iwl_pnvm_parse` walks it: TLVs before the
+ /// first `PNVM_SKU` belong to no section and are skipped.
+ pub fn parse(bytes: &'a [u8]) -> Result<Pnvm<'a>, Error> {
+ let mut pnvm = Pnvm::default();
+ for item in tlvs(bytes, 0) {
+ let (_, kind, data) = item?;
+ if kind == tlv::PNVM_SKU {
+ if data.len() < 12 {
+ return Err(Error::Length {
+ tlv: kind,
+ len: data.len() as u32,
+ });
+ }
+ pnvm.skus.push(PnvmSku {
+ sku_id: [u32_at(data, 0), u32_at(data, 4), u32_at(data, 8)],
+ ..PnvmSku::default()
+ });
+ continue;
+ }
+ let Some(sku) = pnvm.skus.last_mut() else {
+ continue;
+ };
+ match kind {
+ tlv::PNVM_VERSION if data.len() >= 4 => sku.version = Some(u32_at(data, 0)),
+ tlv::HW_TYPE if data.len() >= 4 => sku.hw_types.push((u16_at(data, 0), u16_at(data, 2))),
+ tlv::SEC_RT if data.len() >= 4 => {
+ // A deprecated separator Linux skips.
+ if u32_at(data, 0) != 0xdddd_eeee {
+ sku.chunks.push(&data[4..]);
+ }
+ }
+ tlv::MEM_DESC => sku.mem_desc = true,
+ _ => {}
+ }
+ }
+ Ok(pnvm)
+ }
+
+ /// The section for the chip whose ALIVE said `sku_id`, if it fits the
+ /// chip (`mac_type`, `rf_type` as [`Chip`] has them).
+ pub fn for_chip(&self, sku_id: [u32; 3], mac_type: u16, rf_type: u16) -> Option<&PnvmSku<'a>> {
+ self.skus
+ .iter()
+ .find(|s| s.sku_id == sku_id && s.fits(mac_type, rf_type) && !s.chunks.is_empty())
+ }
+}
+
+/// The MAC types (`IWL_CFG_MAC_TYPE_*`, `CSR_HW_REV` bits 4–15).
+pub mod mac {
+ pub const QU: u16 = 0x33;
+ pub const QUZ: u16 = 0x35;
+ pub const SO: u16 = 0x37;
+ pub const TY: u16 = 0x42;
+ pub const SOF: u16 = 0x43;
+ pub const MA: u16 = 0x44;
+}
+
+/// The radio types (`IWL_CFG_RF_TYPE_*`, `CSR_HW_RF_ID` bits 12–23).
+pub mod rf {
+ pub const JF2: u16 = 0x105;
+ pub const JF1: u16 = 0x108;
+ pub const HR2: u16 = 0x10a;
+ pub const HR1: u16 = 0x10c;
+ pub const GF: u16 = 0x10d;
+ pub const FM: u16 = 0x112;
+}
+
+/// Which generation of the boot flow a chip takes.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Family {
+ /// The 22000 family (AX201's Qu and QuZ): context info, `CSR_CTXT_INFO_BA`.
+ Gen22000,
+ /// The AX210 family (So, Ty, Ma): context info v2, the periphery
+ /// scratch area, the image loader.
+ Ax210,
+}
+
+impl Family {
+ /// The firmware API Linux asks for (`IWL_22000_UCODE_API_MAX`,
+ /// `IWL_AX210_UCODE_API_MAX`), and so the files `firmware/` carries.
+ pub fn api(self) -> u32 {
+ match self {
+ Family::Gen22000 => 77,
+ Family::Ax210 => 89,
+ }
+ }
+
+ /// Where the UMAC's periphery registers sit (`umac_prph_offset`).
+ pub fn umac_prph_offset(self) -> u32 {
+ match self {
+ Family::Gen22000 => 0,
+ Family::Ax210 => 0x30_0000,
+ }
+ }
+
+ /// Whether the PNVM file goes with its firmware.
+ pub fn pnvm(self) -> bool {
+ self == Family::Ax210
+ }
+}
+
+/// A chip as its revision registers describe it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Chip {
+ pub mac_type: u16,
+ pub mac_step: u8,
+ pub rf_type: u16,
+ pub rf_step: u8,
+ /// Two radios in one (`CDB`: the "gf4" files).
+ pub cdb: bool,
+}
+
+impl Chip {
+ /// From `CSR_HW_REV` and `CSR_HW_RF_ID` (or the RF ID [`rf_id_from_crf`]
+ /// made): the step is `CSR_HW_REV`'s low four bits from the 8000 family
+ /// on.
+ pub fn new(hw_rev: u32, hw_rf_id: u32) -> Chip {
+ Chip {
+ mac_type: ((hw_rev & 0xfff0) >> 4) as u16,
+ mac_step: (hw_rev & 0xf) as u8,
+ rf_type: ((hw_rf_id & 0x0fff_f000) >> 12) as u16,
+ rf_step: ((hw_rf_id & 0xf00) >> 8) as u8,
+ cdb: hw_rf_id & 0x1000_0000 != 0,
+ }
+ }
+
+ pub fn family(&self) -> Option<Family> {
+ match self.mac_type {
+ mac::QU | mac::QUZ => Some(Family::Gen22000),
+ mac::SO | mac::SOF | mac::TY | mac::MA => Some(Family::Ax210),
+ _ => None,
+ }
+ }
+
+ pub fn mac_name(&self) -> &'static str {
+ match self.mac_type {
+ mac::QU => "Qu",
+ mac::QUZ => "QuZ",
+ mac::SO => "So",
+ mac::SOF => "SoF",
+ mac::TY => "Ty",
+ mac::MA => "Ma",
+ _ => "unknown",
+ }
+ }
+
+ pub fn rf_name(&self) -> &'static str {
+ match self.rf_type {
+ rf::JF1 | rf::JF2 => "JF",
+ rf::HR1 => "HR1",
+ rf::HR2 => "HR2",
+ rf::GF => "GF",
+ rf::FM => "FM",
+ 0 => "none read",
+ _ => "unknown",
+ }
+ }
+}
+
+/// A step as Linux names it: `a` for 0, … (`iwl_drv_get_step`).
+fn step(step: u8) -> char {
+ match step {
+ 0xf => 'z',
+ 0xe => 'a',
+ s => (b'a' + s.min(25)) as char,
+ }
+}
+
+/// Why no file fits a chip.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum NoFirmware {
+ /// A MAC this driver does not know.
+ Mac(u16),
+ /// A radio this driver carries no firmware for (JF's are Wi-Fi 5, FM
+ /// Wi-Fi 7, CDB a "gf4" part).
+ Rf(u16),
+ /// Ma's A step: linux-firmware has no current file for it.
+ Step(u8),
+}
+
+impl core::fmt::Display for NoFirmware {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ match *self {
+ NoFirmware::Mac(t) => write!(f, "MAC type {t:#x}, not one this driver knows"),
+ NoFirmware::Rf(t) => write!(f, "radio type {t:#x}, for which no firmware is carried"),
+ NoFirmware::Step(s) => write!(f, "MAC step {}, for which no firmware is carried", step(s)),
+ }
+ }
+}
+
+/// The firmware file Linux's `iwl_drv_get_fwname_pre` and
+/// `iwl_request_firmware` name for `chip` — of those `firmware/intel-wifi.txt`
+/// carries: `iwlwifi-Qu-b0-hr-b0-77.ucode`, and the `.pnvm` beside it for
+/// the AX210 family.
+pub fn firmware_name(chip: &Chip) -> Result<(String, Option<String>), NoFirmware> {
+ let family = chip.family().ok_or(NoFirmware::Mac(chip.mac_type))?;
+ let (name, mac_step) = match chip.mac_type {
+ mac::QU => ("Qu", step(chip.mac_step)),
+ // All QuZ, So, SoF and Ty use the A step's firmware.
+ mac::QUZ => ("QuZ", 'a'),
+ mac::SO | mac::SOF => ("so", 'a'),
+ mac::TY => ("ty", 'a'),
+ mac::MA => ("ma", step(chip.mac_step)),
+ other => return Err(NoFirmware::Mac(other)),
+ };
+ let radio = match chip.rf_type {
+ rf::HR1 | rf::HR2 if family == Family::Gen22000 => "hr-b0",
+ rf::GF if family == Family::Ax210 && !chip.cdb => "gf-a0",
+ other => return Err(NoFirmware::Rf(other)),
+ };
+ if chip.mac_type == mac::QU && !matches!(chip.mac_step, 1 | 2) {
+ return Err(NoFirmware::Step(chip.mac_step));
+ }
+ if chip.mac_type == mac::MA && mac_step != 'b' {
+ return Err(NoFirmware::Step(chip.mac_step));
+ }
+ let prefix = alloc::format!("iwlwifi-{name}-{mac_step}0-{radio}");
+ let ucode = alloc::format!("{prefix}-{}.ucode", family.api());
+ let pnvm = family.pnvm().then(|| alloc::format!("{prefix}.pnvm"));
+ Ok((ucode, pnvm))
+}
+
+/// The RF ID from the CRF ID register, where `CSR_HW_RF_ID` reads 0 (a
+/// blank OTP), as Linux's `map_crf_id`: `crf` from `SD_REG_VER` (or
+/// `_GEN2`), `wfpm` from `WFPM_OTP_CFG1`.
+pub fn rf_id_from_crf(crf: u32, wfpm: u32) -> Option<u32> {
+ let rf = match crf & 0xfff {
+ 0x201 => rf::JF1,
+ 0x202 => rf::JF2,
+ 0x501 => rf::HR1,
+ 0x503 | 0x504 => rf::HR2,
+ 0x410 => rf::GF,
+ 0x910 => rf::FM,
+ _ => return None,
+ };
+ let step = (crf >> 24) & 0xf;
+ let slave = (crf >> 19) & 1;
+ let cdb = (wfpm >> 4) & 1;
+ let mut id = u32::from(rf) << 12 | step << 8;
+ if cdb != 0 || slave != 0 {
+ id += 1 << 28;
+ }
+ Some(id)
+}
+
+fn put16(b: &mut [u8], at: usize, v: u16) {
+ b[at..at + 2].copy_from_slice(&v.to_le_bytes());
+}
+
+fn put32(b: &mut [u8], at: usize, v: u32) {
+ b[at..at + 4].copy_from_slice(&v.to_le_bytes());
+}
+
+fn put64(b: &mut [u8], at: usize, v: u64) {
+ b[at..at + 8].copy_from_slice(&v.to_le_bytes());
+}
+
+/// The DRAM addresses of an image's sections, as the chip's map takes
+/// them (`struct iwl_context_info_dram_nonfseq`: UMAC, LMAC, paged).
+#[derive(Clone, Debug, Default)]
+pub struct DramMap {
+ pub lmac: Vec<u64>,
+ pub umac: Vec<u64>,
+ pub paging: Vec<u64>,
+}
+
+/// Writes `struct iwl_context_info_dram_nonfseq` (3 × 64 addresses) at `at`.
+fn put_dram(b: &mut [u8], at: usize, map: &DramMap) {
+ for (kind, list) in [(0, &map.umac), (1, &map.lmac), (2, &map.paging)] {
+ for (i, &a) in list.iter().take(MAX_DRAM_ENTRIES).enumerate() {
+ put64(b, at + kind * 64 * 8 + i * 8, a);
+ }
+ }
+}
+
+/// The receive buffers' size the chip is told: 4 KiB, a page each.
+pub const RB_SIZE_4K: u32 = 0x4;
+
+/// `struct iwl_context_info` (BOOT_LOADER_CONTEXT_INFO_S): 1792 bytes.
+pub const CONTEXT_INFO_SIZE: usize = 1792;
+
+/// What the 22000 family's context info points at.
+pub struct ContextInfo<'a> {
+ /// `CSR_HW_REV`'s low 16 bits.
+ pub mac_id: u16,
+ /// The receive queue: 2^`rx_log` descriptors.
+ pub rx_log: u32,
+ /// Its free descriptors, used descriptors and status (DMA addresses).
+ pub free_rbd: u64,
+ pub used_rbd: u64,
+ pub status: u64,
+ /// The command queue: its TFDs and 2^`cmd_log` of them.
+ pub cmd_queue: u64,
+ pub cmd_log: u32,
+ pub dram: &'a DramMap,
+}
+
+/// The 22000 family's context info, as `iwl_pcie_ctxt_info_init` fills it.
+pub fn context_info(c: &ContextInfo) -> [u8; CONTEXT_INFO_SIZE] {
+ const TFD_FORMAT_LONG: u32 = 0x100;
+ let mut b = [0u8; CONTEXT_INFO_SIZE];
+ // version: mac_id, version 0, size in words.
+ put16(&mut b, 0, c.mac_id);
+ put16(&mut b, 4, (CONTEXT_INFO_SIZE / 4) as u16);
+ // control: the RBD ring's size exponent (bits 4–7), long TFDs, the
+ // receive buffer's size (bits 9–12).
+ let control = TFD_FORMAT_LONG | (c.rx_log.min(12) & 0xf) << 4 | (RB_SIZE_4K & 0xf) << 9;
+ put32(&mut b, 8, control);
+ // rbd_cfg at 24: free, used, status.
+ put64(&mut b, 24, c.free_rbd);
+ put64(&mut b, 32, c.used_rbd);
+ put64(&mut b, 40, c.status);
+ // hcmd_cfg at 48: the command queue and its size (the exponent less 3).
+ put64(&mut b, 48, c.cmd_queue);
+ b[56] = (c.cmd_log - 3) as u8;
+ // dump (80), early debug (96), PNVM (112) and reserved2 (128) stay
+ // zero; the DRAM map at 192.
+ put_dram(&mut b, 192, c.dram);
+ b
+}
+
+/// `struct iwl_prph_scratch` (PERIPH_SCRATCH_S): 1724 bytes; the chip is
+/// told 1660 of them, its FSEQ entries unused.
+pub const PRPH_SCRATCH_SIZE: usize = 1724;
+pub const PRPH_SCRATCH_TOLD: usize = 1660;
+
+/// The AX210 family's periphery scratch area, as
+/// `iwl_pcie_ctxt_info_v2_alloc` fills it: version, control (4 KiB
+/// buffers, 256-byte TFDs), the free RBD ring, the DRAM map.
+pub fn prph_scratch(mac_id: u16, free_rbd: u64, dram: &DramMap) -> [u8; PRPH_SCRATCH_SIZE] {
+ const RB_SIZE_4K: u32 = 1 << 16;
+ const MTR_MODE: u32 = 1 << 17;
+ const MTR_FORMAT_256B: u32 = 0xc_0000;
+ let mut b = [0u8; PRPH_SCRATCH_SIZE];
+ put16(&mut b, 0, mac_id);
+ put16(&mut b, 4, (PRPH_SCRATCH_SIZE / 4) as u16);
+ put32(&mut b, 8, RB_SIZE_4K | MTR_MODE | MTR_FORMAT_256B);
+ // control_flags_ext (12), PNVM (16), hwm (32) stay zero; rbd_cfg at 48.
+ put64(&mut b, 48, free_rbd);
+ // reduce_power (60), step (76), fseq_override, analog, reserved: zero.
+ // The DRAM map's common part at 124.
+ put_dram(&mut b, 124, dram);
+ b
+}
+
+/// `struct iwl_context_info_v2` (IPC_CONTEXT_INFO_S): 104 bytes.
+pub const CONTEXT_INFO_V2_SIZE: usize = 104;
+
+/// What the AX210 family's context info points at.
+pub struct ContextInfoV2 {
+ /// The periphery info page; its second half holds the dummy TR and CR
+ /// tail pointers the chip still writes.
+ pub prph_info: u64,
+ pub prph_scratch: u64,
+ /// The receive queue's status (the closed RB index), used descriptors,
+ /// and 2^`rx_log` of them.
+ pub status: u64,
+ pub used_rbd: u64,
+ pub rx_log: u32,
+ /// The command queue's TFDs and 2^`cmd_log` of them.
+ pub cmd_queue: u64,
+ pub cmd_log: u32,
+}
+
+pub fn context_info_v2(c: &ContextInfoV2) -> [u8; CONTEXT_INFO_V2_SIZE] {
+ let mut b = [0u8; CONTEXT_INFO_V2_SIZE];
+ put64(&mut b, 8, c.prph_info);
+ put64(&mut b, 16, c.status);
+ put64(&mut b, 24, c.prph_info + 2048);
+ put64(&mut b, 32, c.prph_info + 3072);
+ put64(&mut b, 52, c.cmd_queue);
+ put64(&mut b, 60, c.used_rbd);
+ put16(&mut b, 68, (c.cmd_log - 3) as u16);
+ put16(&mut b, 70, c.rx_log as u16);
+ put64(&mut b, 88, c.prph_scratch);
+ put32(&mut b, 96, PRPH_SCRATCH_TOLD as u32);
+ b
+}
+
+/// What `len_n_flags` holds in an RB the chip has not written.
+pub const FRAME_INVALID: u32 = 0x5555_0000;
+
+/// A packet at the start of a receive buffer: (command, group, sequence,
+/// payload). None for an empty buffer or a length past its end.
+pub fn rx_packet(rb: &[u8]) -> Option<(u8, u8, u16, &[u8])> {
+ if rb.len() < 8 {
+ return None;
+ }
+ let len_n_flags = u32_at(rb, 0);
+ if len_n_flags == FRAME_INVALID {
+ return None;
+ }
+ let len = (len_n_flags & 0x3fff) as usize;
+ if len < 4 || 4 + len > rb.len() {
+ return None;
+ }
+ Some((rb[4], rb[5], u16_at(rb, 6), &rb[8..4 + len]))
+}
+
+/// The ALIVE notification's command (`UCODE_ALIVE_NTFY`, legacy group).
+pub const ALIVE: u8 = 0x1;
+
+/// What the firmware said when it started (`struct iwl_alive_ntf`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Alive {
+ /// `0xcafe`: it runs; `0xdead`: it failed.
+ pub status: u16,
+ pub flags: u16,
+ pub lmac: (u32, u32),
+ pub umac: (u32, u32),
+ /// Where its error logs are in its memory, for a report.
+ pub lmac_error_table: u32,
+ pub umac_error_table: u32,
+ /// Versions 5 on: the SKU, which picks the PNVM section.
+ pub sku_id: Option<[u32; 3]>,
+}
+
+impl Alive {
+ pub const OK: u16 = 0xcafe;
+
+ /// Version 3 (one LMAC, 68 bytes) or 4 on (two LMACs, the SKU from 5).
+ pub fn parse(p: &[u8]) -> Option<Alive> {
+ // status, flags, then an LMAC's 48 bytes: major, minor, four bytes,
+ // a timestamp, its debug pointers (the error table first).
+ let lmac = |at: usize| ((u32_at(p, at), u32_at(p, at + 4)), u32_at(p, at + 16));
+ let (lmac_at, umac_at, sku_at) = match p.len() {
+ 68 => (4, 52, None),
+ n if n >= 116 => (4, 100, (n >= 128).then_some(116)),
+ _ => return None,
+ };
+ let ((lmac_major, lmac_minor), lmac_error_table) = lmac(lmac_at);
+ Some(Alive {
+ status: u16_at(p, 0),
+ flags: u16_at(p, 2),
+ lmac: (lmac_major, lmac_minor),
+ umac: (u32_at(p, umac_at), u32_at(p, umac_at + 4)),
+ lmac_error_table,
+ umac_error_table: u32_at(p, umac_at + 8),
+ sku_id: sku_at.map(|at| [u32_at(p, at), u32_at(p, at + 4), u32_at(p, at + 8)]),
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/wifi/src/iwl/tests.rs b/wifi/src/iwl/tests.rs
new file mode 100644
index 0000000..771e905
--- /dev/null
+++ b/wifi/src/iwl/tests.rs
@@ -0,0 +1,453 @@
+//! The firmware container, the file a chip needs, the structures the chip
+//! reads and what it answers: on bytes made here (always), and on Intel's
+//! own files where `cargo xtask firmware` has fetched them.
+
+extern crate std;
+
+use super::*;
+use alloc::vec;
+use std::println;
+
+fn tlv(kind: u32, data: &[u8]) -> Vec<u8> {
+ let mut out = Vec::new();
+ out.extend_from_slice(&kind.to_le_bytes());
+ out.extend_from_slice(&(data.len() as u32).to_le_bytes());
+ out.extend_from_slice(data);
+ while out.len() % 4 != 0 {
+ out.push(0);
+ }
+ out
+}
+
+fn section(offset: u32, data: &[u8]) -> Vec<u8> {
+ let mut out = offset.to_le_bytes().to_vec();
+ out.extend_from_slice(data);
+ tlv(tlv::SEC_RT, &out)
+}
+
+fn header(name: &str) -> Vec<u8> {
+ let mut out = vec![0u8; 88];
+ out[4..8].copy_from_slice(&MAGIC.to_le_bytes());
+ out[8..8 + name.len()].copy_from_slice(name.as_bytes());
+ out[72..76].copy_from_slice(&0x5900_0000u32.to_le_bytes());
+ out[76..80].copy_from_slice(&42u32.to_le_bytes());
+ out
+}
+
+/// A file as Intel's are laid out: two LMAC sections, a separator, a UMAC
+/// one, the paging separator, a paged one; and the TLVs around them.
+fn synthetic() -> Vec<u8> {
+ let mut f = header("release/test:synthetic");
+ f.extend(tlv(
+ tlv::FW_VERSION,
+ &[89, 0, 0, 0, 0xb2, 0x23, 0x70, 0xa6, 0, 0, 0, 0],
+ ));
+ f.extend(tlv(tlv::NUM_OF_CPU, &2u32.to_le_bytes()));
+ f.extend(tlv(tlv::PHY_SKU, &0x0033_0018u32.to_le_bytes()));
+ f.extend(tlv(tlv::API_CHANGES_SET, &[0, 0, 0, 0, 1, 0, 0, 0]));
+ f.extend(tlv(tlv::ENABLED_CAPABILITIES, &[1, 0, 0, 0, 0xff, 0, 0, 0]));
+ f.extend(tlv(0x0100_0005, &[9; 7]));
+ f.extend(section(0x0044_0000, &[1; 10]));
+ f.extend(section(0x0080_0000, &[2; 8]));
+ f.extend(section(CPU1_CPU2_SEPARATOR, &[]));
+ f.extend(section(0x8044_0000, &[3; 12]));
+ f.extend(section(PAGING_SEPARATOR, &[]));
+ f.extend(section(0, &[4; 4096]));
+ f.extend(tlv(tlv::SEC_INIT, &[0, 0, 0, 0, 5, 5]));
+ f.extend(tlv(tlv::PAGING, &8192u32.to_le_bytes()));
+ // The last TLV without its padding, as a file may end.
+ let mut iml = tlv(tlv::IML, &[7, 7, 7]);
+ iml.truncate(8 + 3);
+ f.extend(iml);
+ f
+}
+
+#[test]
+fn a_synthetic_file_reads_whole() {
+ let bytes = synthetic();
+ let u = parse(&bytes).unwrap();
+ assert_eq!(u.human_readable, "release/test:synthetic");
+ assert_eq!(u.build, 42);
+ assert_eq!(u.version(), "89.a67023b2.0");
+ assert_eq!(u.cpus, Some(2));
+ assert_eq!(u.phy_sku, Some(0x0033_0018));
+ assert_eq!(u.api, vec![(0, 1)]);
+ assert_eq!(u.capa, vec![(1, 0xff)]);
+ assert_eq!(u.paging_mem_size, Some(8192));
+ assert_eq!(u.iml, Some(&[7u8, 7, 7][..]));
+ assert_eq!(u.other, 1);
+ assert_eq!(u.regular.sections.len(), 6);
+ assert_eq!(
+ u.init.sections,
+ vec![Section {
+ offset: 0,
+ data: &[5, 5]
+ }]
+ );
+ assert_eq!(u.regular.bytes(), 10 + 8 + 12 + 4096);
+ let layout = u.regular.layout().unwrap();
+ assert_eq!(
+ layout.lmac.iter().map(|s| s.offset).collect::<Vec<_>>(),
+ [0x0044_0000, 0x0080_0000]
+ );
+ assert_eq!(layout.umac.iter().map(|s| s.data.len()).collect::<Vec<_>>(), [12]);
+ assert_eq!(layout.paging.len(), 1);
+ assert_eq!(layout.paging[0].data.len(), 4096);
+}
+
+#[test]
+fn a_broken_file_says_where() {
+ let good = synthetic();
+ assert_eq!(parse(&good[..40]).unwrap_err(), Error::TooShort(40));
+ let mut old = good.clone();
+ old[0] = 1;
+ assert_eq!(parse(&old).unwrap_err(), Error::NotTlv);
+ let mut magic = good.clone();
+ magic[4] = b'X';
+ assert!(matches!(parse(&magic).unwrap_err(), Error::Magic(_)));
+ // The first TLV (at 88) claims more than there is.
+ let mut long = good.clone();
+ long[92..96].copy_from_slice(&0x00ff_ffffu32.to_le_bytes());
+ assert_eq!(
+ parse(&long).unwrap_err(),
+ Error::Overrun {
+ at: 88,
+ tlv: tlv::FW_VERSION,
+ len: 0x00ff_ffff
+ }
+ );
+ let mut f = header("x");
+ f.extend(tlv(tlv::FW_VERSION, &[1, 2, 3, 4]));
+ assert_eq!(
+ parse(&f).unwrap_err(),
+ Error::Length {
+ tlv: tlv::FW_VERSION,
+ len: 4
+ }
+ );
+ let mut f = header("x");
+ f.extend(tlv(tlv::PAGING, &1000u32.to_le_bytes()));
+ assert_eq!(parse(&f).unwrap_err(), Error::Paging(1000));
+ let f = header("nothing");
+ assert_eq!(parse(&f).unwrap_err(), Error::NoImage);
+}
+
+#[test]
+fn each_chip_gets_the_file_linux_names() {
+ // CSR_HW_REV: type in bits 4-15, step in 0-3; CSR_HW_RF_ID: type in
+ // 12-23, step in 8-11, CDB bit 28.
+ let chip = |mac: u16, step: u32, rf: u16, rf_step: u32| {
+ Chip::new(u32::from(mac) << 4 | step, u32::from(rf) << 12 | rf_step << 8)
+ };
+ let name = |c: Chip| firmware_name(&c).map(|(u, p)| (u, p.unwrap_or_default()));
+ assert_eq!(
+ name(chip(mac::QU, 1, rf::HR2, 1)).unwrap().0,
+ "iwlwifi-Qu-b0-hr-b0-77.ucode"
+ );
+ assert_eq!(
+ name(chip(mac::QU, 2, rf::HR2, 1)).unwrap().0,
+ "iwlwifi-Qu-c0-hr-b0-77.ucode"
+ );
+ assert_eq!(
+ name(chip(mac::QU, 2, rf::HR1, 0)).unwrap().0,
+ "iwlwifi-Qu-c0-hr-b0-77.ucode"
+ );
+ assert_eq!(
+ name(chip(mac::QUZ, 1, rf::HR2, 1)).unwrap().0,
+ "iwlwifi-QuZ-a0-hr-b0-77.ucode"
+ );
+ assert_eq!(
+ name(chip(mac::SO, 0, rf::GF, 0)).unwrap(),
+ (
+ "iwlwifi-so-a0-gf-a0-89.ucode".into(),
+ "iwlwifi-so-a0-gf-a0.pnvm".into()
+ )
+ );
+ assert_eq!(
+ name(chip(mac::SOF, 2, rf::GF, 1)).unwrap().0,
+ "iwlwifi-so-a0-gf-a0-89.ucode"
+ );
+ assert_eq!(
+ name(chip(mac::TY, 0, rf::GF, 0)).unwrap(),
+ (
+ "iwlwifi-ty-a0-gf-a0-89.ucode".into(),
+ "iwlwifi-ty-a0-gf-a0.pnvm".into()
+ )
+ );
+ assert_eq!(
+ name(chip(mac::MA, 1, rf::GF, 0)).unwrap().0,
+ "iwlwifi-ma-b0-gf-a0-89.ucode"
+ );
+ // What is not carried says why.
+ assert_eq!(name(chip(mac::MA, 0, rf::GF, 0)), Err(NoFirmware::Step(0)));
+ assert_eq!(name(chip(mac::QU, 0, rf::HR2, 1)), Err(NoFirmware::Step(0)));
+ assert_eq!(name(chip(mac::SO, 0, rf::FM, 0)), Err(NoFirmware::Rf(rf::FM)));
+ assert_eq!(name(chip(mac::QU, 1, rf::JF2, 1)), Err(NoFirmware::Rf(rf::JF2)));
+ assert_eq!(name(chip(0x46, 0, rf::FM, 0)), Err(NoFirmware::Mac(0x46)));
+ let cdb = Chip::new(u32::from(mac::SO) << 4, u32::from(rf::GF) << 12 | 1 << 28);
+ assert_eq!(firmware_name(&cdb), Err(NoFirmware::Rf(rf::GF)));
+ // And every file named is one the description carries.
+ let description = include_str!("../../../firmware/intel-wifi.txt");
+ for c in [
+ chip(mac::QU, 1, rf::HR2, 1),
+ chip(mac::QU, 2, rf::HR2, 1),
+ chip(mac::QUZ, 0, rf::HR2, 1),
+ chip(mac::SO, 0, rf::GF, 0),
+ chip(mac::TY, 0, rf::GF, 0),
+ chip(mac::MA, 1, rf::GF, 0),
+ ] {
+ let (ucode, pnvm) = firmware_name(&c).unwrap();
+ for file in core::iter::once(ucode).chain(pnvm) {
+ assert!(
+ description.contains(&alloc::format!("file: {file}\n")),
+ "{file} not described"
+ );
+ }
+ }
+}
+
+#[test]
+fn a_blank_otp_reads_the_radio_from_its_crf() {
+ // GF, step 1: CRF type 0x410, step in bits 24-27.
+ assert_eq!(
+ rf_id_from_crf(0x0100_0410, 0),
+ Some(u32::from(rf::GF) << 12 | 1 << 8)
+ );
+ assert_eq!(
+ rf_id_from_crf(0x0000_0504, 0x10),
+ Some((u32::from(rf::HR2) << 12) + (1 << 28))
+ );
+ assert_eq!(rf_id_from_crf(0x0000_0123, 0), None);
+ let chip = Chip::new(u32::from(mac::SO) << 4, rf_id_from_crf(0x0000_0410, 0).unwrap());
+ assert_eq!((chip.rf_type, chip.cdb), (rf::GF, false));
+}
+
+#[test]
+fn the_context_info_is_where_the_chip_reads_it() {
+ let dram = DramMap {
+ lmac: vec![0x1000, 0x2000],
+ umac: vec![0x3000],
+ paging: vec![0x4000],
+ };
+ let b = context_info(&ContextInfo {
+ mac_id: 0x0351,
+ rx_log: 9,
+ free_rbd: 0xa000,
+ used_rbd: 0xb000,
+ status: 0xc000,
+ cmd_queue: 0xd000,
+ cmd_log: 5,
+ dram: &dram,
+ });
+ let at64 = |at: usize| u64::from_le_bytes(b[at..at + 8].try_into().unwrap());
+ assert_eq!(u16::from_le_bytes([b[0], b[1]]), 0x0351);
+ assert_eq!(u16::from_le_bytes([b[4], b[5]]), 448);
+ // Long TFDs, 512 RBDs (2^9 in bits 4-7), 4 KiB buffers (4 in bits 9-12).
+ assert_eq!(
+ u32::from_le_bytes(b[8..12].try_into().unwrap()),
+ 0x100 | 9 << 4 | 4 << 9
+ );
+ assert_eq!((at64(24), at64(32), at64(40)), (0xa000, 0xb000, 0xc000));
+ assert_eq!((at64(48), b[56]), (0xd000, 2));
+ // UMAC's map first, then LMAC's, then the paged image's.
+ assert_eq!(at64(192), 0x3000);
+ assert_eq!((at64(192 + 512), at64(192 + 520)), (0x1000, 0x2000));
+ assert_eq!(at64(192 + 1024), 0x4000);
+ assert!(b[1728..].iter().all(|&x| x == 0));
+
+ let s = prph_scratch(0x0370, 0xe000, &dram);
+ assert_eq!(u16::from_le_bytes([s[4], s[5]]), 431);
+ assert_eq!(
+ u32::from_le_bytes(s[8..12].try_into().unwrap()),
+ 1 << 16 | 1 << 17 | 0xc_0000
+ );
+ assert_eq!(u64::from_le_bytes(s[48..56].try_into().unwrap()), 0xe000);
+ assert_eq!(u64::from_le_bytes(s[124..132].try_into().unwrap()), 0x3000);
+ assert_eq!(
+ u64::from_le_bytes(s[124 + 512..132 + 512].try_into().unwrap()),
+ 0x1000
+ );
+
+ let v = context_info_v2(&ContextInfoV2 {
+ prph_info: 0x10_0000,
+ prph_scratch: 0x20_0000,
+ status: 0x30_0000,
+ used_rbd: 0x40_0000,
+ rx_log: 9,
+ cmd_queue: 0x50_0000,
+ cmd_log: 7,
+ });
+ let v64 = |at: usize| u64::from_le_bytes(v[at..at + 8].try_into().unwrap());
+ assert_eq!(
+ (v64(8), v64(16), v64(24), v64(32)),
+ (0x10_0000, 0x30_0000, 0x10_0800, 0x10_0c00)
+ );
+ assert_eq!((v64(52), v64(60)), (0x50_0000, 0x40_0000));
+ assert_eq!(
+ (
+ u16::from_le_bytes([v[68], v[69]]),
+ u16::from_le_bytes([v[70], v[71]])
+ ),
+ (4, 9)
+ );
+ assert_eq!(v64(88), 0x20_0000);
+ assert_eq!(u32::from_le_bytes(v[96..100].try_into().unwrap()), 1660);
+}
+
+fn alive_packet(payload: &[u8]) -> Vec<u8> {
+ let mut rb = vec![0u8; 4096];
+ let len = (payload.len() + 4) as u32;
+ rb[0..4].copy_from_slice(&len.to_le_bytes());
+ rb[4] = ALIVE;
+ rb[5] = 0;
+ rb[6..8].copy_from_slice(&0x8000u16.to_le_bytes());
+ rb[8..8 + payload.len()].copy_from_slice(payload);
+ rb
+}
+
+#[test]
+fn the_alive_notification_reads_in_both_shapes() {
+ let mut v3 = vec![0u8; 68];
+ v3[0..2].copy_from_slice(&0xcafeu16.to_le_bytes());
+ v3[4..8].copy_from_slice(&77u32.to_le_bytes());
+ v3[8..12].copy_from_slice(&0x3cda_2a2cu32.to_le_bytes());
+ v3[20..24].copy_from_slice(&0x0080_0000u32.to_le_bytes());
+ v3[52..56].copy_from_slice(&77u32.to_le_bytes());
+ v3[60..64].copy_from_slice(&0x00c0_0000u32.to_le_bytes());
+ let rb = alive_packet(&v3);
+ let (cmd, group, _, payload) = rx_packet(&rb).unwrap();
+ assert_eq!((cmd, group, payload.len()), (ALIVE, 0, 68));
+ let a = Alive::parse(payload).unwrap();
+ assert_eq!(a.status, Alive::OK);
+ assert_eq!(a.lmac, (77, 0x3cda_2a2c));
+ assert_eq!(a.umac.0, 77);
+ assert_eq!(
+ (a.lmac_error_table, a.umac_error_table),
+ (0x0080_0000, 0x00c0_0000)
+ );
+ assert_eq!(a.sku_id, None);
+
+ let mut v6 = vec![0u8; 144];
+ v6[0..2].copy_from_slice(&0xdeadu16.to_le_bytes());
+ v6[100..104].copy_from_slice(&89u32.to_le_bytes());
+ v6[116..120].copy_from_slice(&0x11u32.to_le_bytes());
+ v6[124..128].copy_from_slice(&0x33u32.to_le_bytes());
+ let a = Alive::parse(&v6).unwrap();
+ assert_eq!(
+ (a.status, a.umac.0, a.sku_id),
+ (0xdead, 89, Some([0x11, 0, 0x33]))
+ );
+ assert_eq!(Alive::parse(&[0; 70]), None);
+
+ let mut empty = vec![0u8; 64];
+ empty[0..4].copy_from_slice(&FRAME_INVALID.to_le_bytes());
+ assert_eq!(rx_packet(&empty), None);
+ let mut long = alive_packet(&v3);
+ long[0..4].copy_from_slice(&5000u32.to_le_bytes());
+ assert_eq!(rx_packet(&long[..4096]), None);
+}
+
+#[test]
+fn a_pnvm_file_gives_each_sku_its_section() {
+ let mut f = tlv(tlv::PNVM_VERSION, &[1, 0, 0, 0]);
+ f.extend(tlv(tlv::PNVM_SKU, &[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]));
+ f.extend(tlv(tlv::PNVM_VERSION, &0xabcdu32.to_le_bytes()));
+ f.extend(tlv(tlv::HW_TYPE, &[0x37, 0, 0x0d, 0x01]));
+ f.extend(tlv(tlv::SEC_RT, &[0xee, 0xee, 0xdd, 0xdd]));
+ f.extend(tlv(tlv::SEC_RT, &[0, 0, 0, 0, 9, 9, 9]));
+ f.extend(tlv(tlv::PNVM_SKU, &[4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0]));
+ f.extend(tlv(tlv::HW_TYPE, &[0x42, 0, 0x0d, 0x01]));
+ f.extend(tlv(tlv::SEC_RT, &[0, 0, 0, 0, 8]));
+ let p = Pnvm::parse(&f).unwrap();
+ assert_eq!(p.skus.len(), 2);
+ assert_eq!(p.skus[0].version, Some(0xabcd));
+ assert_eq!(p.skus[0].chunks, vec![&[9u8, 9, 9][..]]);
+ assert_eq!(
+ p.for_chip([1, 2, 3], mac::SO, rf::GF).map(|s| s.chunks.len()),
+ Some(1)
+ );
+ assert_eq!(p.for_chip([1, 2, 3], mac::TY, rf::GF), None);
+ assert_eq!(
+ p.for_chip([4, 5, 6], mac::TY, rf::GF).unwrap().chunks,
+ vec![&[8u8][..]]
+ );
+ assert_eq!(p.for_chip([7, 7, 7], mac::TY, rf::GF), None);
+}
+
+/// Intel's files, where `cargo xtask firmware` put them.
+fn fetched() -> Option<Vec<(std::string::String, Vec<u8>)>> {
+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../target/firmware/intel-wifi");
+ let Ok(entries) = std::fs::read_dir(&dir) else {
+ println!(
+ "iwl: {} is absent (`cargo xtask firmware` fetches Intel's files): skipped",
+ dir.display()
+ );
+ return None;
+ };
+ let mut files: Vec<_> = entries
+ .filter_map(|e| e.ok())
+ .map(|e| (e.file_name().to_string_lossy().into_owned(), e.path()))
+ .filter(|(n, _)| n.ends_with(".ucode") || n.ends_with(".pnvm"))
+ .map(|(n, p)| (n, std::fs::read(p).unwrap()))
+ .collect();
+ files.sort();
+ Some(files)
+}
+
+#[test]
+fn intels_files_read_as_their_chips_need() {
+ let Some(files) = fetched() else {
+ return;
+ };
+ for (name, bytes) in files.iter().filter(|(n, _)| n.ends_with(".ucode")) {
+ let u = parse(bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
+ let ax210 = !name.contains("-Qu");
+ let layout = u.regular.layout().unwrap();
+ assert!(!layout.lmac.is_empty() && !layout.umac.is_empty(), "{name}");
+ // Each section fits one DRAM chunk of at most 32 KiB.
+ assert!(
+ u.regular.sections.iter().all(|s| s.data.len() <= 32 * 1024),
+ "{name}"
+ );
+ assert_eq!(u.iml.is_some(), ax210, "{name}: the image loader");
+ assert_eq!(u.cpus, Some(2), "{name}");
+ let api = if ax210 { 89 } else { 77 };
+ assert!(
+ u.fw_version.is_some_and(|v| v.0 == api),
+ "{name}: {:?}",
+ u.fw_version
+ );
+ println!(
+ "iwl: {name}: {} ({}), {} LMAC + {} UMAC + {} paged sections, {} KiB, IML {} bytes",
+ u.version(),
+ u.human_readable,
+ layout.lmac.len(),
+ layout.umac.len(),
+ layout.paging.len(),
+ u.regular.bytes() / 1024,
+ u.iml.map_or(0, <[u8]>::len)
+ );
+ }
+ for (name, bytes) in files.iter().filter(|(n, _)| n.ends_with(".pnvm")) {
+ let p = Pnvm::parse(bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
+ assert!(!p.skus.is_empty(), "{name}");
+ assert!(
+ p.skus
+ .iter()
+ .all(|s| !s.chunks.is_empty() && !s.hw_types.is_empty()),
+ "{name}"
+ );
+ let mac = if name.contains("-so-") {
+ mac::SO
+ } else if name.contains("-ty-") {
+ mac::TY
+ } else {
+ mac::MA
+ };
+ assert!(
+ p.skus.iter().any(|s| s.fits(mac, rf::GF)),
+ "{name}: no section for its chip"
+ );
+ println!("iwl: {name}: {} SKU sections", p.skus.len());
+ }
+}
diff --git a/wifi/src/lib.rs b/wifi/src/lib.rs
index 5ae217f..48c8a91 100644
--- a/wifi/src/lib.rs
+++ b/wifi/src/lib.rs
@@ -16,12 +16,16 @@
//!
//! [`wpa`] is WPA2-Personal's handshake for a radio that leaves it to the
//! host (Intel's), as a state machine of its own.
+//!
+//! [`iwl`] is Intel's Wi-Fi as data: its firmware files, which a chip
+//! needs, and the structures its boot reads, for the kernel's driver.
#![no_std]
extern crate alloc;
pub mod host;
+pub mod iwl;
pub mod protocol;
pub mod sim;
pub mod wpa;