garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /wifi/src/iwl.rs

raw

//! 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;