git clone https://garage44.eu/jeroen/pinnacle.gitcartopolis-agent · 2026-11-30T14:36:15Z
feat(kernel): Intel Wi-Fi as far as its firmware's ALIVE (iwlwifi) Stage one of Intel's Wi-Fi: AX201 (8086:02f0, 06f0, 34f0, 4df0, 43f0, a0f0: the 22000 family's Qu/QuZ MAC with an HR radio), AX211 (51f0, 51f1, 54f0, 7af0: So; 7e40: Ma; GF radio) and the AX210 card (2725: Ty). Written from Linux's flow for these generations (pcie/trans.c, trans-gen2.c, ctxt-info.c, ctxt-info-v2.c, rx.c): - BAR 0 mapped, bus mastering on, INTx off (everything is polled); CSR_HW_REV, then the chip taken (PCI_OWN_SET, WAKE_ME retries, at most ~1.8 s), INIT_DONE and its clock, MAC_ACCESS_REQ for the periphery: WFPM's MAC owner bit, the CRF and CNV IDs, CSR_HW_RF_ID (else the RF from the CRF ID); the file chosen by wifi::iwl::firmware_name; - the file read from system:/firmware/intel/, parsed, its use noted for Settings (device::note_firmware) and said in the boot log as Intel's closed firmware, carried as data; - start_hw as Linux: persistence bit (22000), software reset, forced power gating for an integrated 22000, APM init, MSI chicken bit; - start_fw: interrupts masked, rfkill read, nic_config's HW_IF_CONFIG from PHY_SKU (22000), a 512-entry receive queue (64 buffers of 4 KiB), a command queue of 32 or 128 TFDs, shadow registers; every firmware section in DMA memory of its own; the context info at CSR_CTXT_INFO_BA (22000), or context info v2, periphery scratch and the IML at 0x118, 0x120, 0x128 with AUTO_FUNC_BOOT_ENA (AX210 family); LTR as each wants (the CNVi So/Ma kept busy until the IML is done, at most 100 ms); UREG_CPU_INIT_RUN; - ALIVE: the cause polled in CSR_INT (and the MSI-X causes), then the receive buffers given, then the notification read from the closed buffers: status, LMAC and UMAC versions, SKU; the PNVM section for that SKU found (handed over in the next stage). At most 2 s; on a firmware error or a timeout the registers, secure boot status, program counters, IML answer and boot stage are printed. Whatever happens the chip is then stopped (DMA stopped, reset, INIT_DONE cleared), its bus mastering turned off, and only then its memory freed. Every failure says "iwlwifi: stopped at <step>: <why>". Called after the network on both architectures; with no such device it says nothing. Tested on mac-2: `cargo xtask pc` and `cargo xtask laptop` pass and their boot logs have no iwlwifi line; `cargo xtask test` (ARM) passes; clippy for the PC kernel and both ARM boards shows nothing. Untried on a chip: QEMU has no Intel Wi-Fi, so every step past "found" waits for a laptop.
Cargo.lock | 1 +
kernel/Cargo.toml | 1 +
kernel/src/drivers/iwlwifi.rs | 958 ++++++++++++++++++++++++++++++++++++++++++
kernel/src/drivers/mod.rs | 4 +-
kernel/src/main.rs | 4 +
5 files changed, 967 insertions(+), 1 deletion(-)
diff --git a/Cargo.lock b/Cargo.lock
index 01d11cd..53aa916 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -80,6 +80,7 @@ dependencies = [
"pinnacle-pkg",
"pinnacle-ttf",
"pinnacle-vector",
+ "pinnacle-wifi",
]
[[package]]
diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml
index 8883693..e2d4887 100644
--- a/kernel/Cargo.toml
+++ b/kernel/Cargo.toml
@@ -27,6 +27,7 @@ pinnacle-fs = { path = "../pfs" }
pinnacle-hid = { path = "../hid" }
pinnacle-net = { path = "../net" }
pinnacle-pkg = { path = "../pkg" }
+pinnacle-wifi = { path = "../wifi" }
# The console's font, drawn from the system's monospace face at build time
# (`build.rs`): the kernel holds bitmaps, not the face.
diff --git a/kernel/src/drivers/iwlwifi.rs b/kernel/src/drivers/iwlwifi.rs
new file mode 100644
index 0000000..b987767
--- /dev/null
+++ b/kernel/src/drivers/iwlwifi.rs
@@ -0,0 +1,958 @@
+//! Intel's Wi-Fi on PCI, stage one: the chip found and named, its firmware
+//! chosen and read from the system disk, handed to the chip the way its
+//! generation takes it, and the ALIVE notification it sends once that runs
+//! waited for and told. Scanning, joining and carrying packets come next.
+//!
+//! - AX201, the CNVi of 10th and 11th generation Core: the 22000 family's
+//! Qu or QuZ MAC with an HR radio (8086:02f0, 06f0, 34f0, 4df0, 43f0,
+//! a0f0). It reads a *context info* (`CSR_CTXT_INFO_BA`) listing its
+//! firmware's sections in DRAM, its receive queue and command queue.
+//! - AX211, the CNVi from the 12th generation on: the AX210 family's So
+//! (8086:51f0, 51f1, 54f0, 7af0) or Ma (7e40) MAC with a GF radio; and the
+//! AX210 card, its Ty MAC (8086:2725). They read *context info v2* and a
+//! *periphery scratch* area, and run an image loader (IML) from the
+//! firmware file first.
+//!
+//! The driver is Pinnacle's own Rust; the firmware is Intel's closed code,
+//! carried as data (`firmware/intel-wifi.txt`), read from
+//! `system:/firmware/intel/` and handed to the chip, never run here. Its
+//! container and the structures the chip reads are `pinnacle_wifi::iwl`,
+//! tested on the host. Linux's iwlwifi (`pcie/trans.c`, `trans-gen2.c`,
+//! `ctxt-info.c`, `ctxt-info-v2.c`, `rx.c`) is the reference for the
+//! registers and the order of things.
+//!
+//! Untried: QEMU has no Intel Wi-Fi, so nothing here has met a chip. With
+//! none on the bus it says nothing. With one, every wait is bounded; on
+//! any failure the boot log says at which step and with which registers
+//! (a laptop's report is a photograph of its screen), and in every case
+//! the chip is reset and its bus mastering turned off before the memory it
+//! was given is freed: the radio stays off until the next stage drives it.
+//! No interrupts: the causes are polled in `CSR_INT`, as the boot needs.
+
+use crate::mm::pages;
+use crate::mmu::physical;
+use alloc::format;
+use alloc::string::String;
+use alloc::vec::Vec;
+use core::sync::atomic::{Ordering, fence};
+use pinnacle_wifi::iwl::{self, Chip, Family};
+
+// The control and status registers, in BAR 0 (`iwl-csr.h`).
+const HW_IF_CONFIG: usize = 0x000;
+const INT_COALESCING: usize = 0x004;
+const INT: usize = 0x008;
+const INT_MASK: usize = 0x00c;
+const FH_INT_STATUS: usize = 0x010;
+const RESET: usize = 0x020;
+const GP_CNTRL: usize = 0x024;
+const HW_REV: usize = 0x028;
+const GIO: usize = 0x03c;
+const CTXT_INFO_BA: usize = 0x040;
+const UCODE_DRV_GP1: usize = 0x054;
+const UCODE_DRV_GP1_CLR: usize = 0x05c;
+const MBOX_SET: usize = 0x088;
+const HW_RF_ID: usize = 0x09c;
+const MAC_SHADOW_REG_CTRL: usize = 0x0a8;
+const LTR_LONG_VAL_AD: usize = 0x0d4;
+const LTR_LAST_MSG: usize = 0x0dc;
+const GIO_CHICKEN_BITS: usize = 0x100;
+const CTXT_INFO_ADDR: usize = 0x118;
+const IML_DATA_ADDR: usize = 0x120;
+const IML_SIZE_ADDR: usize = 0x128;
+const IML_RESP_ADDR: usize = 0x12c;
+const DBG_HPET_MEM: usize = 0x240;
+const DBG_LINK_PWR_MGMT: usize = 0x250;
+const PRPH_WADDR: usize = 0x444;
+const PRPH_RADDR: usize = 0x448;
+const PRPH_WDAT: usize = 0x44c;
+const PRPH_RDAT: usize = 0x450;
+/// The free receive queue's write index (`RFH_Q0_FRBDCB_WIDX_TRG`).
+const RX_WIDX: usize = 0x1c80;
+const MSIX_FH_CAUSES: usize = 0x2800;
+const MSIX_HW_CAUSES: usize = 0x2808;
+
+// Their bits.
+const HW_IF_HAP_WAKE: u32 = 0x0008_0000;
+const HW_IF_PCI_OWN_SET: u32 = 0x0040_0000;
+const HW_IF_WAKE_ME: u32 = 0x0800_0000;
+/// In `HW_IF_CONFIG`, also `CSR_CTXT_INFO_BOOT_CTRL`: boot by context info v2.
+const AUTO_FUNC_BOOT_ENA: u32 = 1 << 1;
+const INT_ALIVE: u32 = 1 << 0;
+const INT_SW_ERR: u32 = 1 << 25;
+const INT_HW_ERR: u32 = 1 << 29;
+const INT_FH_RX: u32 = 1 << 31;
+/// `MSIX_HW_INT_CAUSES_REG_IML`: the AX210 family's image loader is done.
+const HW_CAUSE_IML: u32 = 1 << 1;
+const RESET_SW: u32 = 0x80;
+const RESET_STOP_MASTER: u32 = 0x200;
+const RESET_MASTER_DISABLED: u32 = 0x100;
+const RESET_LINK_PWR_MGMT_DISABLED: u32 = 0x8000_0000;
+const GP_MAC_CLOCK_READY: u32 = 0x1;
+const GP_INIT_DONE: u32 = 0x4;
+const GP_MAC_ACCESS_REQ: u32 = 0x8;
+const GP_GOING_TO_SLEEP: u32 = 0x10;
+const GP_HW_RF_KILL_SW: u32 = 0x0800_0000;
+const GIO_L0S_DISABLED: u32 = 0x2;
+const GIO_CHICKEN_L1A_NO_L0S_RX: u32 = 0x0080_0000;
+const HPET_MEM_VAL: u32 = 0xffff_0000;
+const MBOX_OS_ALIVE: u32 = 1 << 5;
+const GP1_SW_BIT_RFKILL: u32 = 0x2;
+const GP1_CMD_BLOCKED: u32 = 0x4;
+/// 2048 µs between interrupts (`IWL_HOST_INT_TIMEOUT_DEF`).
+const HOST_INT_TIMEOUT: u8 = 0x40;
+
+// Periphery registers, reached through `PRPH_*` (`iwl-prph.h`); the UMAC's
+// are `Family::umac_prph_offset` further on the AX210 family.
+const UREG_CHICK: u32 = 0xa0_5c00;
+const UREG_CHICK_MSI_ENABLE: u32 = 1 << 24;
+const UREG_CPU_INIT_RUN: u32 = 0xa0_5c44;
+const UREG_UMAC_CURRENT_PC: u32 = 0xa0_5c18;
+const UREG_LMAC1_CURRENT_PC: u32 = 0xa0_5c1c;
+const UMAG_SB_CPU_1_STATUS: u32 = 0xa0_38c0;
+const UMAG_SB_CPU_2_STATUS: u32 = 0xa0_38c4;
+const HPM_MAC_LTR_CSR: u32 = 0xa0_348c;
+const HPM_MAC_LTR_ENABLE_ALL: u32 = 0xf;
+const HPM_UMAC_LTR: u32 = 0xa0_3480;
+const HPM_DEBUG: u32 = 0xa0_3440;
+const PERSISTENCE_BIT: u32 = 1 << 12;
+const PREG_PRPH_WPROT_22000: u32 = 0xa0_4d00;
+const PREG_WFPM_ACCESS: u32 = 1 << 12;
+const HPM_HIPM_GEN_CFG: u32 = 0xa0_3458;
+const HIPM_PG_EN: u32 = 1 << 0;
+const HIPM_SLP_EN: u32 = 1 << 1;
+const HIPM_FORCE_ACTIVE: u32 = 1 << 10;
+const WFPM_CTRL_REG: u32 = 0xa0_3030;
+const WFPM_AUX_CTL_AUX_IF_MAC_OWNER: u32 = 0x8000_0000;
+const WFPM_OTP_CFG1: u32 = 0xa0_3098;
+const SD_REG_VER: u32 = 0xa2_9600;
+const SD_REG_VER_GEN2: u32 = 0xa2_b800;
+const CNVI_AUX_MISC_CHIP: u32 = 0xa2_00b0;
+
+/// The receive queue: 2^9 descriptors, of which [`RBS`] are stocked with a
+/// 4 KiB buffer each: enough for the notifications the boot brings.
+const RX_LOG: u32 = 9;
+const RX_SIZE: usize = 1 << RX_LOG;
+const RBS: usize = 64;
+const RB_BYTES: usize = 4096;
+/// A TFD (`struct iwl_tfh_tfd`) is 256 bytes.
+const TFD: usize = 256;
+/// How long the firmware has to say it runs (Linux's `MVM_UCODE_ALIVE_TIMEOUT`).
+const ALIVE_MS: u64 = 2000;
+
+/// What a PCI ID is.
+struct Model {
+ name: &'static str,
+ family: Family,
+ /// On the chipset (CNVi) rather than a card.
+ integrated: bool,
+}
+
+fn model(id: u16) -> Option<Model> {
+ let (name, family, integrated) = match id {
+ 0x02f0 | 0x06f0 | 0x34f0 | 0x4df0 | 0x43f0 | 0xa0f0 => ("AX201", Family::Gen22000, true),
+ 0x51f0 | 0x51f1 | 0x54f0 | 0x7af0 | 0x7e40 => ("AX211", Family::Ax210, true),
+ 0x2725 => ("AX210", Family::Ax210, false),
+ _ => return None,
+ };
+ Some(Model {
+ name,
+ family,
+ integrated,
+ })
+}
+
+/// Where and why bringing the chip up stopped.
+struct Stop {
+ step: &'static str,
+ why: String,
+}
+
+fn stop<T>(step: &'static str, why: impl Into<String>) -> Result<T, Stop> {
+ Err(Stop {
+ step,
+ why: why.into(),
+ })
+}
+
+/// Microseconds on the core's counter.
+fn now_us() -> u64 {
+ let hz = u128::from(crate::timer::frequency().max(1));
+ (u128::from(crate::arch::counter()) * 1_000_000 / hz) as u64
+}
+
+fn delay_us(us: u64) {
+ let end = now_us() + us;
+ while now_us() < end {
+ core::hint::spin_loop();
+ }
+}
+
+/// The chip's registers.
+struct Dev {
+ regs: usize,
+ family: Family,
+}
+
+impl Dev {
+ fn read(&self, register: usize) -> u32 {
+ // SAFETY: a register in the chip's BAR 0, which is 8 KiB or more
+ // and mapped uncached by the kernel's direct map.
+ unsafe { ((self.regs + register) as *const u32).read_volatile() }
+ }
+
+ fn write(&self, register: usize, value: u32) {
+ // SAFETY: as in `read`.
+ unsafe { ((self.regs + register) as *mut u32).write_volatile(value) }
+ }
+
+ fn write8(&self, register: usize, value: u8) {
+ // SAFETY: as in `read`.
+ unsafe { ((self.regs + register) as *mut u8).write_volatile(value) }
+ }
+
+ fn write64(&self, register: usize, value: u64) {
+ self.write(register, value as u32);
+ self.write(register + 4, (value >> 32) as u32);
+ }
+
+ fn set(&self, register: usize, bits: u32) {
+ self.write(register, self.read(register) | bits);
+ }
+
+ fn clear(&self, register: usize, bits: u32) {
+ self.write(register, self.read(register) & !bits);
+ }
+
+ /// Waits up to `us` for `(register & mask) == bits`.
+ fn poll(&self, register: usize, bits: u32, mask: u32, us: u64) -> bool {
+ let end = now_us() + us;
+ loop {
+ if self.read(register) & mask == bits {
+ return true;
+ }
+ if now_us() > end {
+ return false;
+ }
+ delay_us(5);
+ }
+ }
+
+ fn prph_mask(&self) -> u32 {
+ match self.family {
+ Family::Gen22000 => 0x000f_ffff,
+ Family::Ax210 => 0x00ff_ffff,
+ }
+ }
+
+ /// A periphery register; the chip must be awake ([`Dev::grab`]).
+ fn read_prph(&self, address: u32) -> u32 {
+ self.write(PRPH_RADDR, (address & self.prph_mask()) | 3 << 24);
+ self.read(PRPH_RDAT)
+ }
+
+ fn write_prph(&self, address: u32, value: u32) {
+ self.write(PRPH_WADDR, (address & self.prph_mask()) | 3 << 24);
+ self.write(PRPH_WDAT, value);
+ }
+
+ fn umac(&self, address: u32) -> u32 {
+ address + self.family.umac_prph_offset()
+ }
+
+ /// Wakes the chip's MAC for register access (`MAC_ACCESS_REQ`), for at
+ /// most 15 ms.
+ fn grab(&self) -> bool {
+ self.set(GP_CNTRL, GP_MAC_ACCESS_REQ);
+ delay_us(2);
+ self.poll(
+ GP_CNTRL,
+ GP_MAC_CLOCK_READY,
+ GP_MAC_CLOCK_READY | GP_GOING_TO_SLEEP,
+ 15_000,
+ )
+ }
+
+ fn release(&self) {
+ self.clear(GP_CNTRL, GP_MAC_ACCESS_REQ);
+ }
+
+ /// `f` with the chip awake.
+ fn awake<R>(&self, step: &'static str, f: impl FnOnce(&Dev) -> R) -> Result<R, Stop> {
+ if !self.grab() {
+ return stop(
+ step,
+ format!(
+ "the chip did not wake for access (GP_CNTRL {:#010x})",
+ self.read(GP_CNTRL)
+ ),
+ );
+ }
+ let r = f(self);
+ self.release();
+ Ok(r)
+ }
+
+ /// The registers that say most about a stop, for the boot log.
+ fn state(&self) -> String {
+ format!(
+ "INT {:#010x} HW causes {:#010x} GP_CNTRL {:#010x} HW_IF_CONFIG {:#010x} GP1 {:#010x} RESET {:#010x}",
+ self.read(INT),
+ self.read(MSIX_HW_CAUSES),
+ self.read(GP_CNTRL),
+ self.read(HW_IF_CONFIG),
+ self.read(UCODE_DRV_GP1),
+ self.read(RESET),
+ )
+ }
+
+ /// Takes the chip from whoever has it (`iwl_pcie_prepare_card_hw`):
+ /// `PCI_OWN_SET` asked and seen, at most about 1.8 s with retries.
+ fn prepare(&self) -> Result<(), Stop> {
+ let ready = |d: &Dev| {
+ d.set(HW_IF_CONFIG, HW_IF_PCI_OWN_SET);
+ let ok = d.poll(HW_IF_CONFIG, HW_IF_PCI_OWN_SET, HW_IF_PCI_OWN_SET, 50);
+ if ok {
+ d.set(MBOX_SET, MBOX_OS_ALIVE);
+ }
+ ok
+ };
+ if ready(self) {
+ return Ok(());
+ }
+ self.set(DBG_LINK_PWR_MGMT, RESET_LINK_PWR_MGMT_DISABLED);
+ delay_us(1000);
+ for _ in 0..10 {
+ self.set(HW_IF_CONFIG, HW_IF_WAKE_ME);
+ let end = now_us() + 150_000;
+ while now_us() < end {
+ if ready(self) {
+ return Ok(());
+ }
+ delay_us(200);
+ }
+ delay_us(25_000);
+ }
+ stop(
+ "ownership",
+ format!(
+ "the chip did not let the driver own it (HW_IF_CONFIG {:#010x}): Intel's ME (AMT) may hold it",
+ self.read(HW_IF_CONFIG)
+ ),
+ )
+ }
+
+ /// From D0U to D0A (`iwl_pcie_activate_nic`): `INIT_DONE`, then its
+ /// clock ready within 25 ms.
+ fn activate(&self) -> Result<(), Stop> {
+ self.set(GP_CNTRL, GP_INIT_DONE);
+ if !self.poll(GP_CNTRL, GP_MAC_CLOCK_READY, GP_MAC_CLOCK_READY, 25_000) {
+ return stop(
+ "waking",
+ format!(
+ "its clock did not become ready (GP_CNTRL {:#010x})",
+ self.read(GP_CNTRL)
+ ),
+ );
+ }
+ Ok(())
+ }
+
+ /// A software reset (`CSR_RESET_REG_FLAG_SW_RESET`), 5 ms to settle.
+ fn sw_reset(&self) {
+ self.set(RESET, RESET_SW);
+ delay_us(6000);
+ }
+
+ /// The basic set-up both generations share (`iwl_pcie_apm_init`,
+ /// `iwl_pcie_gen2_apm_init`: their parts for these chips).
+ fn apm_init(&self) -> Result<(), Stop> {
+ self.set(GIO_CHICKEN_BITS, GIO_CHICKEN_L1A_NO_L0S_RX);
+ self.set(DBG_HPET_MEM, HPET_MEM_VAL);
+ self.set(HW_IF_CONFIG, HW_IF_HAP_WAKE);
+ self.set(GIO, GIO_L0S_DISABLED);
+ self.activate()
+ }
+
+ /// Stops it: interrupts masked and acknowledged, its DMA stopped, a
+ /// reset, back to D0U (`iwl_pcie_gen2_apm_stop`).
+ fn stop(&self) {
+ self.write(INT_MASK, 0);
+ self.write(INT, u32::MAX);
+ self.write(FH_INT_STATUS, u32::MAX);
+ self.write(MSIX_HW_CAUSES, u32::MAX);
+ self.write(MSIX_FH_CAUSES, u32::MAX);
+ self.set(RESET, RESET_STOP_MASTER);
+ self.poll(RESET, RESET_MASTER_DISABLED, RESET_MASTER_DISABLED, 1000);
+ self.sw_reset();
+ self.clear(GP_CNTRL, GP_INIT_DONE);
+ }
+}
+
+/// The DMA memory handed to the chip, freed once it is stopped.
+#[derive(Default)]
+struct Dma {
+ blocks: Vec<(usize, usize)>,
+}
+
+impl Dma {
+ /// Zeroed, physically contiguous memory for `bytes`, aligned to its
+ /// size (so no block crosses a 4 GiB line, as the chip needs).
+ fn alloc(&mut self, bytes: usize) -> Result<usize, Stop> {
+ let order = pages::order_for(bytes.max(1));
+ let Some(at) = pages::alloc(order) else {
+ return stop("memory", format!("no {} KiB block of memory for DMA", 4 << order));
+ };
+ // SAFETY: a fresh block, ours.
+ unsafe { core::ptr::write_bytes(at as *mut u8, 0, crate::mm::PAGE << order) };
+ self.blocks.push((at, order));
+ Ok(at)
+ }
+
+ /// `data` copied into DMA memory; its address for the chip.
+ fn copy(&mut self, data: &[u8]) -> Result<u64, Stop> {
+ let at = self.alloc(data.len())?;
+ // SAFETY: `at` holds at least `data.len()` bytes, ours.
+ unsafe { core::ptr::copy_nonoverlapping(data.as_ptr(), at as *mut u8, data.len()) };
+ Ok(physical(at) as u64)
+ }
+
+ fn free(&mut self) {
+ for (at, order) in self.blocks.drain(..) {
+ pages::free(at, order);
+ }
+ }
+}
+
+/// The receive queue: its free descriptors (the buffers offered), used
+/// descriptors (the buffers the chip filled), the chip's status word, and
+/// the buffers.
+struct Rx {
+ free: usize,
+ used: usize,
+ status: usize,
+ rbs: [usize; RBS],
+}
+
+impl Rx {
+ fn new(dma: &mut Dma, family: Family) -> Result<Rx, Stop> {
+ let (free, used, status) = match family {
+ // 64-bit address | ID; 32-bit ID; `struct iwl_rb_status`.
+ Family::Gen22000 => (8, 4, 16),
+ // `iwl_rx_transfer_desc`, `iwl_rx_completion_desc`, a u16.
+ Family::Ax210 => (16, 32, 2),
+ };
+ let mut rx = Rx {
+ free: dma.alloc(RX_SIZE * free)?,
+ used: dma.alloc(RX_SIZE * used)?,
+ status: dma.alloc(status)?,
+ rbs: [0; RBS],
+ };
+ for rb in &mut rx.rbs {
+ *rb = dma.alloc(RB_BYTES)?;
+ }
+ Ok(rx)
+ }
+
+ /// Offers the buffers to the chip, each with its ID (its index + 1),
+ /// and moves the write index (in eights) past them.
+ fn restock(&self, dev: &Dev) {
+ for (i, &rb) in self.rbs.iter().enumerate() {
+ let address = physical(rb) as u64;
+ let id = (i + 1) as u64;
+ // SAFETY: descriptor `i` of the free ring, in our DMA block.
+ unsafe {
+ match dev.family {
+ Family::Gen22000 => ((self.free + 8 * i) as *mut u64).write_volatile(address | id),
+ Family::Ax210 => {
+ ((self.free + 16 * i) as *mut u16).write_volatile(id as u16);
+ ((self.free + 16 * i + 8) as *mut u64).write_volatile(address);
+ }
+ }
+ }
+ }
+ fence(Ordering::SeqCst);
+ dev.write(RX_WIDX, (RBS & !7) as u32);
+ }
+
+ /// How many buffers the chip has closed.
+ fn closed(&self, family: Family) -> usize {
+ // SAFETY: the status word, in our DMA block, which the chip writes.
+ let raw = unsafe { (self.status as *const u16).read_volatile() };
+ match family {
+ Family::Gen22000 => usize::from(raw & 0xfff),
+ Family::Ax210 => usize::from(raw),
+ }
+ }
+
+ /// The buffer the chip filled at used descriptor `i`.
+ fn filled(&self, family: Family, i: usize) -> Option<&[u8]> {
+ // SAFETY: used descriptor `i`, in our DMA block.
+ let id = unsafe {
+ match family {
+ Family::Gen22000 => ((self.used + 4 * i) as *const u32).read_volatile() & 0xfff,
+ Family::Ax210 => u32::from(((self.used + 32 * i + 4) as *const u16).read_volatile()),
+ }
+ } as usize;
+ let rb = *self.rbs.get(id.checked_sub(1)?)?;
+ // SAFETY: a receive buffer of ours, which the chip wrote and closed.
+ Some(unsafe { core::slice::from_raw_parts(rb as *const u8, RB_BYTES) })
+ }
+}
+
+/// What the chip said when its firmware started.
+struct Report {
+ chip: Chip,
+ file: String,
+ ucode: String,
+ alive: iwl::Alive,
+ rfkill: bool,
+ pnvm: Option<String>,
+}
+
+/// Looks for Intel's Wi-Fi on PCI and brings each up as far as ALIVE.
+/// Silent when there is none.
+pub fn init() {
+ for f in crate::pci::find(0x8086, 0..=0xffff) {
+ let Some(model) = model(f.id) else {
+ continue;
+ };
+ let name = format!("pci@{:02x}:{:02x}.{}", f.bus, f.device, f.function);
+ crate::println!(
+ "iwlwifi: Intel {} (8086:{:04x}) at {name}, {}",
+ model.name,
+ f.id,
+ if model.integrated {
+ "in the chipset (CNVi)"
+ } else {
+ "a card"
+ }
+ );
+ crate::pci::claim(&f, "iwlwifi", crate::device::Class::Network);
+ let Some(regs) = f.bar_address(0, 0) else {
+ crate::println!("iwlwifi: stopped at registers: BAR 0 has no address; the device left alone");
+ continue;
+ };
+ let dev = Dev {
+ regs,
+ family: model.family,
+ };
+ let mut dma = Dma::default();
+ let result = bring_up(&f, &dev, &model, &name, &mut dma);
+ // Whatever happened: the chip reset, its DMA off, then its memory
+ // freed. The radio stays off until the next stage drives it.
+ dev.stop();
+ const BUS_MASTER: u16 = 1 << 2;
+ f.write16(0x04, f.read16(0x04) & !BUS_MASTER);
+ dma.free();
+ match result {
+ Ok(r) => {
+ let (lmac, umac) = (r.alive.lmac, r.alive.umac);
+ crate::println!(
+ "iwlwifi: ALIVE from {}: status {:#06x} ({}), LMAC {}.{:08x}, UMAC {}.{:08x}{}",
+ r.file,
+ r.alive.status,
+ if r.alive.status == iwl::Alive::OK {
+ "running"
+ } else {
+ "failed"
+ },
+ lmac.0,
+ lmac.1,
+ umac.0,
+ umac.1,
+ r.alive.sku_id.map_or(String::new(), |s| format!(
+ ", SKU {:08x}:{:08x}:{:08x}",
+ s[0], s[1], s[2]
+ ))
+ );
+ if let Some(pnvm) = r.pnvm {
+ crate::println!("iwlwifi: {pnvm}");
+ }
+ if r.rfkill {
+ crate::println!("iwlwifi: the radio's switch (rfkill) is off");
+ }
+ crate::println!(
+ "iwlwifi: {} {} with {} ({}) stopped again: scanning and joining are the next stage",
+ r.chip.mac_name(),
+ r.chip.rf_name(),
+ r.file,
+ r.ucode
+ );
+ }
+ Err(s) => crate::println!("iwlwifi: stopped at {}: {}; the device is off", s.step, s.why),
+ }
+ }
+}
+
+/// Reads `system:/firmware/intel/<file>`.
+fn read_firmware(file: &str) -> Option<Vec<u8>> {
+ let path = format!("system:/firmware/intel/{file}");
+ crate::drivers::block::with_disk(&path, |fs, p| fs.read(p).ok()).flatten()
+}
+
+fn bring_up(
+ f: &crate::pci::Function,
+ dev: &Dev,
+ model: &Model,
+ name: &str,
+ dma: &mut Dma,
+) -> Result<Report, Stop> {
+ // Memory decoding and bus mastering on, INTx off (it is polled); PCI's
+ // retry timeout (0x41) off, as Linux does.
+ f.enable(false);
+ f.write32(0x40, f.read32(0x40) & !0xff00);
+ let hw_rev = dev.read(HW_REV);
+ if hw_rev == u32::MAX {
+ return stop(
+ "revision",
+ "CSR_HW_REV reads all ones: the device is off, or not there",
+ );
+ }
+ dev.prepare()?;
+ dev.activate()?;
+ // Which radio: CSR_HW_RF_ID, else the CRF ID from the periphery.
+ let (crf, cnv, wfpm) = dev.awake("radio", |d| {
+ let ctrl = d.umac(WFPM_CTRL_REG);
+ d.write_prph(ctrl, d.read_prph(ctrl) | WFPM_AUX_CTL_AUX_IF_MAC_OWNER);
+ let crf = d.read_prph(match d.family {
+ Family::Gen22000 => SD_REG_VER,
+ Family::Ax210 => SD_REG_VER_GEN2,
+ });
+ (
+ crf,
+ d.read_prph(CNVI_AUX_MISC_CHIP),
+ d.read_prph(d.umac(WFPM_OTP_CFG1)),
+ )
+ })?;
+ let mut hw_rf_id = dev.read(HW_RF_ID);
+ if (hw_rf_id >> 12) & 0xfff == 0 {
+ hw_rf_id = iwl::rf_id_from_crf(crf, wfpm).ok_or(Stop {
+ step: "radio",
+ why: format!("CSR_HW_RF_ID 0 and CRF ID {crf:#010x}, a radio not known"),
+ })?;
+ }
+ let chip = Chip::new(hw_rev, hw_rf_id);
+ crate::println!(
+ "iwlwifi: MAC {} step {} (CSR_HW_REV {hw_rev:#010x}), radio {} step {} (RF ID {hw_rf_id:#010x}, CRF {crf:#010x}, CNV {cnv:#010x})",
+ chip.mac_name(),
+ chip.mac_step,
+ chip.rf_name(),
+ chip.rf_step,
+ );
+ if chip.family() != Some(model.family) {
+ return stop(
+ "revision",
+ format!(
+ "MAC type {:#x} is not the {} its PCI ID says",
+ chip.mac_type, model.name
+ ),
+ );
+ }
+ let (file, pnvm_file) = iwl::firmware_name(&chip).map_err(|e| Stop {
+ step: "firmware choice",
+ why: format!("{e}"),
+ })?;
+ let Some(bytes) = read_firmware(&file) else {
+ return stop(
+ "firmware file",
+ format!(
+ "system:/firmware/intel/{file} is not on the system disk (a system built with PINNACLE_NO_FIRMWARE=1 has none)"
+ ),
+ );
+ };
+ let ucode = iwl::parse(&bytes).map_err(|e| Stop {
+ step: "firmware file",
+ why: format!("{file}: {e}"),
+ })?;
+ let layout = ucode.regular.layout().map_err(|e| Stop {
+ step: "firmware file",
+ why: format!("{file}: {e}"),
+ })?;
+ if model.family == Family::Ax210 && ucode.iml.is_none() {
+ return stop("firmware file", format!("{file} has no image loader (IML)"));
+ }
+ crate::device::note_firmware(name, "Intel", &file);
+ crate::println!(
+ "iwlwifi: Intel's closed firmware, as data: system:/firmware/intel/{file} ({}, {} bytes; whose, licence and source in intel-wifi.txt beside it)",
+ ucode.version(),
+ bytes.len()
+ );
+ let pnvm_bytes = pnvm_file.as_deref().and_then(read_firmware);
+
+ // start_hw: the chip taken, reset, powered as its generation wants.
+ dev.prepare()?;
+ if model.family == Family::Gen22000 {
+ // The persistence bit, left by a firmware, keeps the reset away.
+ let hpm = dev.awake("persistence", |d| d.read_prph(d.umac(HPM_DEBUG)))?;
+ if hpm != u32::MAX && hpm & PERSISTENCE_BIT != 0 {
+ let protected = dev.awake("persistence", |d| d.read_prph(d.umac(PREG_PRPH_WPROT_22000)))?;
+ if protected & PREG_WFPM_ACCESS != 0 {
+ return stop("persistence", "its persistence bit is set and write-protected");
+ }
+ dev.awake("persistence", |d| {
+ d.write_prph(d.umac(HPM_DEBUG), hpm & !PERSISTENCE_BIT)
+ })?;
+ }
+ }
+ dev.sw_reset();
+ dev.prepare()?;
+ if model.family == Family::Gen22000 && model.integrated {
+ // `iwl_pcie_gen2_force_power_gating`.
+ dev.activate()?;
+ dev.awake("power gating", |d| {
+ d.write_prph(
+ HPM_HIPM_GEN_CFG,
+ d.read_prph(HPM_HIPM_GEN_CFG) | HIPM_FORCE_ACTIVE,
+ );
+ })?;
+ delay_us(20);
+ dev.awake("power gating", |d| {
+ d.write_prph(
+ HPM_HIPM_GEN_CFG,
+ d.read_prph(HPM_HIPM_GEN_CFG) | HIPM_PG_EN | HIPM_SLP_EN,
+ );
+ })?;
+ delay_us(20);
+ dev.awake("power gating", |d| {
+ d.write_prph(
+ HPM_HIPM_GEN_CFG,
+ d.read_prph(HPM_HIPM_GEN_CFG) & !HIPM_FORCE_ACTIVE,
+ );
+ })?;
+ dev.sw_reset();
+ dev.prepare()?;
+ }
+ dev.apm_init()?;
+ // Interrupts as MSI (not MSI-X), which the polling reads the same way.
+ dev.awake("interrupts", |d| {
+ d.write_prph(d.umac(UREG_CHICK), UREG_CHICK_MSI_ENABLE)
+ })?;
+
+ // start_fw.
+ dev.prepare()?;
+ dev.write(INT_MASK, 0);
+ dev.write(INT, u32::MAX);
+ dev.write(FH_INT_STATUS, u32::MAX);
+ let rfkill = dev.read(GP_CNTRL) & GP_HW_RF_KILL_SW == 0;
+ dev.write(UCODE_DRV_GP1_CLR, GP1_SW_BIT_RFKILL);
+ dev.write(UCODE_DRV_GP1_CLR, GP1_CMD_BLOCKED);
+ dev.write(INT, u32::MAX);
+ dev.apm_init()?;
+ if model.family == Family::Gen22000 {
+ // `iwl_mvm_nic_config`: the MAC's step and the radio's
+ // configuration from the firmware's PHY_SKU.
+ let phy = ucode.phy_sku.unwrap_or(0);
+ let value = (hw_rev & 0xf) | (phy & 0x3) << 10 | ((phy >> 2) & 0x3) << 14 | ((phy >> 4) & 0x3) << 12;
+ let mask = 0xf | 0xc00 | 0xc000 | 0x3000 | 0x200 | 0x100;
+ dev.write(HW_IF_CONFIG, (dev.read(HW_IF_CONFIG) & !mask) | value);
+ }
+ dev.write8(INT_COALESCING, HOST_INT_TIMEOUT);
+ let rx = Rx::new(dma, model.family)?;
+ let (cmd_log, cmd_entries) = match model.family {
+ Family::Gen22000 => (5, 32),
+ // The AX210 family's least queue is 128 TFDs.
+ Family::Ax210 => (7, 128),
+ };
+ let cmd_queue = physical(dma.alloc(cmd_entries * TFD)?) as u64;
+ dev.set(MAC_SHADOW_REG_CTRL, 0x800f_ffff);
+
+ // The firmware's sections, each in DMA memory of its own.
+ let mut map = iwl::DramMap::default();
+ for (list, out) in [
+ (&layout.lmac, &mut map.lmac),
+ (&layout.umac, &mut map.umac),
+ (&layout.paging, &mut map.paging),
+ ] {
+ for section in list {
+ out.push(dma.copy(section.data)?);
+ }
+ }
+ let mac_id = hw_rev as u16;
+ let mut prph_info = 0;
+ match model.family {
+ Family::Gen22000 => {
+ let info = iwl::context_info(&iwl::ContextInfo {
+ mac_id,
+ rx_log: RX_LOG,
+ free_rbd: physical(rx.free) as u64,
+ used_rbd: physical(rx.used) as u64,
+ status: physical(rx.status) as u64,
+ cmd_queue,
+ cmd_log,
+ dram: &map,
+ });
+ let at = dma.copy(&info)?;
+ dev.write(INT_MASK, INT_ALIVE | INT_FH_RX);
+ fence(Ordering::SeqCst);
+ dev.write64(CTXT_INFO_BA, at);
+ }
+ Family::Ax210 => {
+ let scratch = dma.copy(&iwl::prph_scratch(mac_id, physical(rx.free) as u64, &map))?;
+ prph_info = dma.alloc(crate::mm::PAGE)?;
+ let info = dma.copy(&iwl::context_info_v2(&iwl::ContextInfoV2 {
+ prph_info: physical(prph_info) as u64,
+ prph_scratch: scratch,
+ status: physical(rx.status) as u64,
+ used_rbd: physical(rx.used) as u64,
+ rx_log: RX_LOG,
+ cmd_queue,
+ cmd_log,
+ }))?;
+ let iml = ucode.iml.unwrap_or(&[]);
+ let iml_at = dma.copy(iml)?;
+ dev.write(INT_MASK, INT_ALIVE | INT_FH_RX);
+ fence(Ordering::SeqCst);
+ dev.write64(CTXT_INFO_ADDR, info);
+ dev.write64(IML_DATA_ADDR, iml_at);
+ dev.write(IML_SIZE_ADDR, iml.len() as u32);
+ dev.set(HW_IF_CONFIG, AUTO_FUNC_BOOT_ENA);
+ }
+ }
+ // The latency the chip may take to answer the bus, ~250 µs while it
+ // boots (`iwl_pcie_set_ltr`).
+ let ltr = 0x8000_0000 | 2 << 26 | 250 << 16 | 0x8000 | 2 << 10 | 250;
+ let mut keep_busy = false;
+ match (model.family, model.integrated) {
+ (_, false) => dev.write(LTR_LONG_VAL_AD, ltr),
+ (Family::Gen22000, true) => dev.awake("latency", |d| {
+ d.write_prph(HPM_MAC_LTR_CSR, HPM_MAC_LTR_ENABLE_ALL);
+ d.write_prph(HPM_UMAC_LTR, ltr);
+ })?,
+ (Family::Ax210, true) => {
+ dev.write(MSIX_HW_CAUSES, HW_CAUSE_IML);
+ keep_busy = true;
+ }
+ }
+ // Run.
+ dev.awake("start", |d| d.write_prph(d.umac(UREG_CPU_INIT_RUN), 1))?;
+ if keep_busy {
+ // The boot ROM's latency bug: keep the chip busy until its image
+ // loader is done, at most 100 ms (it takes 20 to 30).
+ let end = now_us() + 100_000;
+ while now_us() < end && dev.read(MSIX_HW_CAUSES) & HW_CAUSE_IML == 0 {
+ dev.read(LTR_LAST_MSG);
+ }
+ }
+ let alive = wait_alive(dev, &rx, prph_info)?;
+ let pnvm = match (pnvm_file, pnvm_bytes, alive.sku_id) {
+ (Some(f), None, _) => Some(format!(
+ "{f} is not on the system disk: the platform's settings would be missing"
+ )),
+ (Some(f), Some(b), Some(sku)) => Some(match iwl::Pnvm::parse(&b) {
+ Ok(p) => match p.for_chip(sku, chip.mac_type, chip.rf_type) {
+ Some(s) => format!(
+ "{f}: a section for this SKU, {} chunks: handed over in the next stage, after ALIVE",
+ s.chunks.len()
+ ),
+ None => format!("{f}: no section for this SKU and chip"),
+ },
+ Err(e) => format!("{f}: {e}"),
+ }),
+ _ => None,
+ };
+ Ok(Report {
+ chip,
+ ucode: ucode.version(),
+ file,
+ alive,
+ rfkill,
+ pnvm,
+ })
+}
+
+/// Waits for the ALIVE cause, gives the chip its receive buffers (it has
+/// set its receive DMA up by then), then for the ALIVE notification in one
+/// of them: at most [`ALIVE_MS`] in all.
+fn wait_alive(dev: &Dev, rx: &Rx, prph_info: usize) -> Result<iwl::Alive, Stop> {
+ let end = crate::timer::now_ms() + ALIVE_MS;
+ let mut stocked = false;
+ loop {
+ let (int, hw) = (dev.read(INT), dev.read(MSIX_HW_CAUSES));
+ if int == u32::MAX {
+ return stop("ALIVE", "the registers read all ones: the chip fell off the bus");
+ }
+ if int & (INT_SW_ERR | INT_HW_ERR) != 0 || hw & (INT_SW_ERR | INT_HW_ERR) != 0 {
+ return stop(
+ "ALIVE",
+ format!(
+ "the firmware reported an error: {}{}",
+ dev.state(),
+ why_stuck(dev, prph_info)
+ ),
+ );
+ }
+ if !stocked && (int & INT_ALIVE != 0 || hw & INT_ALIVE != 0) {
+ dev.write(INT, INT_ALIVE);
+ dev.write(MSIX_HW_CAUSES, INT_ALIVE);
+ rx.restock(dev);
+ stocked = true;
+ }
+ if stocked {
+ let closed = rx.closed(dev.family).min(RX_SIZE);
+ fence(Ordering::SeqCst);
+ for i in 0..closed {
+ let Some(rb) = rx.filled(dev.family, i) else {
+ continue;
+ };
+ // A 22000's buffer can hold several packets, each aligned
+ // to 64 bytes; an AX210's holds one.
+ let mut at = 0;
+ while let Some((cmd, group, _, payload)) = iwl::rx_packet(&rb[at..]) {
+ if cmd == iwl::ALIVE && group == 0 {
+ return iwl::Alive::parse(payload).ok_or(Stop {
+ step: "ALIVE",
+ why: format!("a notification of {} bytes, not a shape known", payload.len()),
+ });
+ }
+ at += (payload.len() + 8).next_multiple_of(64);
+ if dev.family == Family::Ax210 || at + 8 > rb.len() {
+ break;
+ }
+ }
+ }
+ }
+ if crate::timer::now_ms() > end {
+ return stop(
+ "ALIVE",
+ format!(
+ "no {} within {ALIVE_MS} ms ({} buffers closed): {}{}",
+ if stocked {
+ "notification after the ALIVE cause"
+ } else {
+ "ALIVE cause"
+ },
+ if stocked { rx.closed(dev.family) } else { 0 },
+ dev.state(),
+ why_stuck(dev, prph_info)
+ ),
+ );
+ }
+ delay_us(100);
+ }
+}
+
+/// What the chip's boot says of itself, where it says it: the secure
+/// boot's status, the CPUs' program counters, the image loader's answer
+/// and the boot stage (AX210 family).
+fn why_stuck(dev: &Dev, prph_info: usize) -> String {
+ let mut out = String::new();
+ if dev.grab() {
+ out += &format!(
+ "; secure boot {:#x} {:#x}, PC UMAC {:#x} LMAC {:#x}",
+ dev.read_prph(dev.umac(UMAG_SB_CPU_1_STATUS)),
+ dev.read_prph(dev.umac(UMAG_SB_CPU_2_STATUS)),
+ dev.read_prph(dev.umac(UREG_UMAC_CURRENT_PC)),
+ dev.read_prph(dev.umac(UREG_LMAC1_CURRENT_PC)),
+ );
+ dev.release();
+ }
+ if dev.family == Family::Ax210 {
+ out += &format!("; IML answer {:#x}", dev.read(IML_RESP_ADDR));
+ if prph_info != 0 {
+ // SAFETY: the periphery info page, ours, which the chip writes.
+ let stage = unsafe { (prph_info as *const u32).read_volatile() };
+ out += &format!(", boot stage {stage:#x}");
+ }
+ }
+ out
+}
diff --git a/kernel/src/drivers/mod.rs b/kernel/src/drivers/mod.rs
index 7059b01..b051949 100644
--- a/kernel/src/drivers/mod.rs
+++ b/kernel/src/drivers/mod.rs
@@ -1,7 +1,8 @@
//! Device drivers. QEMU's are virtio (`virtio`, over MMIO or PCI) and its
//! framebuffer (`display`); a PC's and a laptop's own are on PCI: disks
//! behind NVMe and AHCI, USB (`usb`: keyboards, mice, sticks), Intel HDA
-//! sound (`hda`); a board's come board by board.
+//! sound (`hda`), Intel's Wi-Fi as far as its firmware's start
+//! (`iwlwifi`); a board's come board by board.
pub mod ahci;
pub mod block;
@@ -18,6 +19,7 @@ pub mod i2c_hid;
pub mod input;
#[cfg(target_arch = "x86_64")]
pub mod i915;
+pub mod iwlwifi;
pub mod net;
pub mod nvme;
#[cfg(target_arch = "x86_64")]
diff --git a/kernel/src/main.rs b/kernel/src/main.rs
index 06de0e3..79a4443 100644
--- a/kernel/src/main.rs
+++ b/kernel/src/main.rs
@@ -242,6 +242,8 @@ extern "C" fn kmain(start_info: usize, magic: u32) -> ! {
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]
);
}
+ // Intel's Wi-Fi, as far as its firmware's ALIVE; silent without one.
+ drivers::iwlwifi::init();
let checking = boot.command_line().split(' ').any(|arg| arg == "selfcheck");
{
use device::Class::*;
@@ -393,6 +395,8 @@ extern "C" fn kmain(device_tree: usize, entered_at: usize, slot: u64) -> ! {
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]
);
}
+ // Intel's Wi-Fi on a board's PCIe, as on a PC; silent without one.
+ drivers::iwlwifi::init();
{
use device::Class::*;
selfcheck::devices(&[Interrupts, Storage, Network, Display, Sound, Random]);