garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/hda.rs

raw

//! Intel High Definition Audio: the sound of every Intel laptop and PC
//! since 2004, on PCI (class 04:03), and QEMU's `ich9-intel-hda`. The
//! controller is reset, its codecs found (STATESTS) and spoken to through
//! the command rings (CORB and RIRB; the immediate command registers when
//! those do not answer); the first codec with an analog output has its
//! widget graph walked from the speaker's pin and the headphone jack's
//! back to an output converter (through mixers and selectors), everything
//! on the way powered, unmuted at 0 dB and selected, EAPD set where a pin
//! has it. One output stream plays a ring of [`PERIODS`] periods from the
//! kernel's mixer (`sound`), 48 kHz 16-bit stereo, an interrupt as each
//! period completes, the position read from LPIB.
//!
//! The headphone jack, where its pin senses presence, sends an unsolicited
//! response when something is plugged in or pulled out: the speaker is
//! turned off while headphones are in.
//!
//! Written from Intel's HDA specification (rev. 1.0a) and tried in QEMU's
//! `ich9-intel-hda` with `hda-output` only. Not here: recording, HDMI and
//! DisplayPort audio, a codec's vendor-specific set-up (Realtek's coefficient
//! tables, which some laptops' speakers need), Intel's DSP (class 04:01,
//! the "SOF" mode a firmware may choose instead).

use super::sound::{PERIOD_BYTES, PERIODS};
use crate::mm::pages;
use crate::mmu::physical;
use crate::println;
use alloc::string::String;
use alloc::vec::Vec;
use core::sync::atomic::{Ordering, fence};

/// Multimedia, HDA (its programming interface is always 0).
const CLASS: u32 = 0x04_03_00;

const GCAP: usize = 0x00;
const GCTL: usize = 0x08;
const STATESTS: usize = 0x0e;
const INTCTL: usize = 0x20;
const INTSTS: usize = 0x24;
const CORBLBASE: usize = 0x40;
const CORBUBASE: usize = 0x44;
const CORBWP: usize = 0x48;
const CORBRP: usize = 0x4a;
const CORBCTL: usize = 0x4c;
const CORBSIZE: usize = 0x4e;
const RIRBLBASE: usize = 0x50;
const RIRBUBASE: usize = 0x54;
const RIRBWP: usize = 0x58;
const RINTCNT: usize = 0x5a;
const RIRBCTL: usize = 0x5c;
const RIRBSTS: usize = 0x5d;
const RIRBSIZE: usize = 0x5e;
const ICOI: usize = 0x60;
const ICII: usize = 0x64;
const ICS: usize = 0x68;
/// Stream descriptors: 0x20 bytes each from here, input streams first.
const SD_BASE: usize = 0x80;
const SD_CTL: usize = 0x00;
const SD_STS: usize = 0x03;
const SD_LPIB: usize = 0x04;
const SD_CBL: usize = 0x08;
const SD_LVI: usize = 0x0c;
const SD_FMT: usize = 0x12;
const SD_BDPL: usize = 0x18;
const SD_BDPU: usize = 0x1c;

const GCTL_CRST: u32 = 1;
const GCTL_UNSOL: u32 = 1 << 8;
const INT_GIE: u32 = 1 << 31;
const INT_CIE: u32 = 1 << 30;
const CORBRP_RST: u16 = 1 << 15;
const CORB_RUN: u8 = 1 << 1;
const RIRBWP_RST: u16 = 1 << 15;
const RIRB_INT: u8 = 1;
const RIRB_DMA: u8 = 1 << 1;
const RIRB_STATUS: u8 = 1 | 1 << 2;
const ICS_BUSY: u16 = 1;
const ICS_VALID: u16 = 1 << 1;
const SD_SRST: u32 = 1;
const SD_RUN: u32 = 1 << 1;
const SD_IOCE: u32 = 1 << 2;
/// Buffer complete, FIFO error, descriptor error.
const SD_STATUS: u8 = 0x1c;
/// The stream's tag on the link (1–15), which the converters listen for.
const TAG: u32 = 1;
/// 48 kHz, 16 bits, 2 channels.
const FORMAT: u32 = 1 << 4 | 1;

/// Where the RIRB is in the rings' page (the CORB at 0: 256 × 4 bytes).
const RIRB_AT: usize = 1024;

// Verbs: 12 bits with an 8-bit payload, or 4 bits with a 16-bit one.
const GET_PARAMETER: u32 = 0xf00;
const GET_CONNECTION: u32 = 0xf02;
const GET_POWER: u32 = 0xf05;
const GET_PIN_SENSE: u32 = 0xf09;
const GET_CONFIG: u32 = 0xf1c;
const SET_SELECT: u32 = 0x701;
const SET_POWER: u32 = 0x705;
const SET_STREAM: u32 = 0x706;
const SET_PIN_CONTROL: u32 = 0x707;
const SET_UNSOLICITED: u32 = 0x708;
const SET_PIN_SENSE: u32 = 0x709;
const SET_EAPD: u32 = 0x70c;
const SET_FORMAT: u32 = 0x2;
const SET_AMP: u32 = 0x3;

const P_VENDOR: u32 = 0x00;
const P_NODES: u32 = 0x04;
const P_GROUP: u32 = 0x05;
const P_CAPS: u32 = 0x09;
const P_PIN_CAPS: u32 = 0x0c;
const P_IN_AMP: u32 = 0x0d;
const P_CONNECTIONS: u32 = 0x0e;
const P_OUT_AMP: u32 = 0x12;

const W_OUTPUT: u32 = 0;
const W_MIXER: u32 = 2;
const W_SELECTOR: u32 = 3;
const W_PIN: u32 = 4;
const CAP_IN_AMP: u32 = 1 << 1;
const CAP_OUT_AMP: u32 = 1 << 2;
const CAP_AMP_OVERRIDE: u32 = 1 << 3;
const CAP_CONNECTIONS: u32 = 1 << 8;
const CAP_DIGITAL: u32 = 1 << 9;
const CAP_POWER: u32 = 1 << 10;
const PIN_TRIGGER: u32 = 1 << 1;
const PIN_PRESENCE: u32 = 1 << 2;
const PIN_HP_DRIVE: u32 = 1 << 3;
const PIN_OUTPUT: u32 = 1 << 4;
const PIN_EAPD: u32 = 1 << 16;
const PINCTL_OUT: u32 = 0x40;
const PINCTL_HP: u32 = 0x80;
/// The unsolicited response's tag the headphone jack sends.
const JACK_TAG: u32 = 1;

/// How long a codec has to answer a command.
const COMMAND_MS: u64 = 50;

/// Busy-waits until `done`, at most `ms` milliseconds: whether it was.
fn wait(ms: u64, mut done: impl FnMut() -> bool) -> bool {
    let deadline = crate::timer::now_ms() + ms;
    loop {
        if done() {
            return true;
        }
        if crate::timer::now_ms() > deadline {
            return done();
        }
        core::hint::spin_loop();
    }
}

/// Busy-waits at least `ms` milliseconds.
fn delay(ms: u64) {
    let until = crate::timer::now_ms() + ms + 1;
    while crate::timer::now_ms() < until {
        core::hint::spin_loop();
    }
}

/// An output pin and what it can do.
#[derive(Clone, Copy)]
struct Pin {
    nid: u8,
    eapd: bool,
    /// It senses presence (a jack whose detection is not overridden), and
    /// needs telling to look first.
    sense: bool,
    trigger: bool,
}

/// One widget of the codec's audio function group.
struct Widget {
    nid: u8,
    caps: u32,
    connections: Vec<u8>,
    pin_caps: u32,
    config: u32,
    in_amp: u32,
    out_amp: u32,
}

impl Widget {
    fn kind(&self) -> u32 {
        (self.caps >> 20) & 0xf
    }
}

pub struct Hda {
    regs: usize,
    pub intid: u32,
    codec: u8,
    /// The CORB at 0, the RIRB at [`RIRB_AT`].
    rings: usize,
    corb_entries: u16,
    rirb_entries: u16,
    corb_write: u16,
    rirb_read: u16,
    /// The command rings did not answer: one command at a time through
    /// the immediate registers (and no unsolicited responses).
    immediate: bool,
    /// Unsolicited responses read while waiting for a command's.
    unsolicited: Vec<u32>,
    /// The output stream's descriptor (its registers' offset) and its bit
    /// in INTCTL/INTSTS.
    stream: usize,
    stream_bit: u32,
    bdl: usize,
    periods: [usize; PERIODS],
    /// The next period to give back to the mixer once played.
    next: usize,
    pub running: bool,
    /// The last player left: silence is played until every period played
    /// has been silence, then the stream stops.
    pub stopping: bool,
    pub silent: usize,
    speaker: Option<Pin>,
    headphones: Option<Pin>,
    /// What was found, for the boot log.
    pub found: String,
}

impl Hda {
    fn r8(&self, at: usize) -> u8 {
        // SAFETY: the controller's registers, in its BAR 0.
        unsafe { ((self.regs + at) as *const u8).read_volatile() }
    }
    fn r16(&self, at: usize) -> u16 {
        // SAFETY: as in `r8`.
        unsafe { ((self.regs + at) as *const u16).read_volatile() }
    }
    fn r32(&self, at: usize) -> u32 {
        // SAFETY: as in `r8`.
        unsafe { ((self.regs + at) as *const u32).read_volatile() }
    }
    fn w8(&self, at: usize, v: u8) {
        // SAFETY: as in `r8`.
        unsafe { ((self.regs + at) as *mut u8).write_volatile(v) }
    }
    fn w16(&self, at: usize, v: u16) {
        // SAFETY: as in `r8`.
        unsafe { ((self.regs + at) as *mut u16).write_volatile(v) }
    }
    fn w32(&self, at: usize, v: u32) {
        // SAFETY: as in `r8`.
        unsafe { ((self.regs + at) as *mut u32).write_volatile(v) }
    }

    /// The kernel's address of period `slot`'s samples.
    pub fn period(&self, slot: usize) -> usize {
        self.periods[slot]
    }

    /// Sends a raw command and waits for its response.
    fn send(&mut self, raw: u32) -> Option<u32> {
        if self.immediate {
            return self.send_immediate(raw);
        }
        self.corb_write = (self.corb_write + 1) % self.corb_entries;
        // SAFETY: entry `corb_write` of the CORB, in our page.
        unsafe { ((self.rings + usize::from(self.corb_write) * 4) as *mut u32).write_volatile(raw) };
        fence(Ordering::SeqCst);
        self.w16(CORBWP, self.corb_write);
        let deadline = crate::timer::now_ms() + COMMAND_MS;
        loop {
            if let Some(response) = self.take_responses(true) {
                return Some(response);
            }
            if crate::timer::now_ms() > deadline {
                return None;
            }
            core::hint::spin_loop();
        }
    }

    /// Reads the RIRB up to where the controller has written: unsolicited
    /// responses kept, and the first solicited one returned when `solicited`
    /// (the rest left for the next call).
    ///
    /// The response flag is cleared once it is read: a controller may
    /// hold the CORB until it is (QEMU's does, after RINTCNT responses).
    fn take_responses(&mut self, solicited: bool) -> Option<u32> {
        let written = (self.r16(RIRBWP) & 0xff) % self.rirb_entries;
        let mut answer = None;
        while self.rirb_read != written && answer.is_none() {
            self.rirb_read = (self.rirb_read + 1) % self.rirb_entries;
            let at = self.rings + RIRB_AT + usize::from(self.rirb_read) * 8;
            fence(Ordering::SeqCst);
            // SAFETY: entry `rirb_read` of the RIRB, which the controller wrote.
            let (response, extended) = unsafe {
                (
                    (at as *const u32).read_volatile(),
                    (at as *const u32).add(1).read_volatile(),
                )
            };
            if extended & 0x10 != 0 {
                if self.unsolicited.len() < 16 {
                    self.unsolicited.push(response);
                }
            } else if solicited {
                answer = Some(response);
            }
        }
        if self.r8(RIRBSTS) & RIRB_STATUS != 0 {
            self.w8(RIRBSTS, RIRB_STATUS);
        }
        answer
    }

    fn send_immediate(&mut self, raw: u32) -> Option<u32> {
        if !wait(COMMAND_MS, || self.r16(ICS) & ICS_BUSY == 0) {
            return None;
        }
        self.w32(ICOI, raw);
        self.w16(ICS, ICS_VALID | ICS_BUSY);
        if !wait(COMMAND_MS, || {
            let s = self.r16(ICS);
            s & ICS_BUSY == 0 && s & ICS_VALID != 0
        }) {
            return None;
        }
        let response = self.r32(ICII);
        self.w16(ICS, ICS_VALID);
        Some(response)
    }

    /// A 12-bit verb with an 8-bit payload to node `nid`.
    fn command(&mut self, nid: u8, verb: u32, payload: u32) -> Option<u32> {
        self.send(u32::from(self.codec) << 28 | u32::from(nid) << 20 | verb << 8 | (payload & 0xff))
    }

    /// A 4-bit verb with a 16-bit payload to node `nid`.
    fn command4(&mut self, nid: u8, verb: u32, payload: u32) -> Option<u32> {
        self.send(u32::from(self.codec) << 28 | u32::from(nid) << 20 | verb << 16 | (payload & 0xffff))
    }

    fn parameter(&mut self, nid: u8, id: u32) -> Option<u32> {
        self.command(nid, GET_PARAMETER, id)
    }

    /// Sets an amplifier: output or input (`index` its connection), both
    /// channels, at 0 dB (its offset) and muted or not.
    fn amp(&mut self, nid: u8, output: bool, index: usize, caps: u32, mute: bool) {
        let steps = (caps >> 8) & 0x7f;
        let gain = (caps & 0x7f).min(steps);
        let which = if output { 1 << 15 } else { 1 << 14 };
        let payload = which | 3 << 12 | (index as u32 & 0xf) << 8 | u32::from(mute) << 7 | gain;
        self.command4(nid, SET_AMP, payload);
    }

    /// The node's connections, long and short forms, ranges expanded.
    fn connections(&mut self, nid: u8) -> Vec<u8> {
        let mut list = Vec::new();
        let Some(length) = self.parameter(nid, P_CONNECTIONS) else {
            return list;
        };
        let long = length & 0x80 != 0;
        let count = (length & 0x7f) as usize;
        let (per, bits) = if long { (2, 16) } else { (4, 8) };
        let mut previous = 0u8;
        let mut i = 0;
        while i < count {
            let Some(word) = self.command(nid, GET_CONNECTION, i as u32) else {
                break;
            };
            for k in 0..per {
                if i + k >= count {
                    break;
                }
                let entry = (word >> (k * bits)) & ((1 << bits) - 1);
                let range = entry & (1 << (bits - 1)) != 0;
                let node = (entry & ((1 << (bits - 1)) - 1)) as u8;
                if range && node > previous {
                    // A range is a node of its own in the list; its members
                    // between are not counted, which nobody's codec uses.
                    list.extend(previous + 1..=node);
                } else {
                    list.push(node);
                }
                previous = node;
            }
            i += per;
        }
        list
    }

    fn sense(&mut self, pin: Pin) -> bool {
        if pin.trigger {
            self.command(pin.nid, SET_PIN_SENSE, 0);
            delay(1);
        }
        self.command(pin.nid, GET_PIN_SENSE, 0)
            .is_some_and(|s| s & 1 << 31 != 0)
    }

    /// Headphones in or out: the speaker off while they are in.
    fn jack(&mut self, present: bool) {
        if let Some(speaker) = self.speaker {
            self.command(speaker.nid, SET_PIN_CONTROL, if present { 0 } else { PINCTL_OUT });
        }
    }

    /// Lets the controller interrupt: the stream's completions, and the
    /// RIRB's for the jack's unsolicited responses. Once the kernel is
    /// ready to take them.
    pub fn enable_interrupts(&mut self) {
        let mut mask = INT_GIE | self.stream_bit;
        if !self.immediate {
            self.w8(RIRBCTL, RIRB_DMA | RIRB_INT);
            mask |= INT_CIE;
        }
        self.w32(INTCTL, mask);
    }

    /// Starts the stream from its first period (every period filled).
    pub fn start(&mut self) {
        let sd = self.stream;
        self.w32(sd + SD_CTL, 0);
        wait(10, || self.r32(sd + SD_CTL) & SD_RUN == 0);
        self.w32(sd + SD_CTL, SD_SRST);
        wait(10, || self.r32(sd + SD_CTL) & SD_SRST != 0);
        self.w32(sd + SD_CTL, 0);
        wait(10, || self.r32(sd + SD_CTL) & SD_SRST == 0);
        self.w8(sd + SD_STS, SD_STATUS);
        let bdl = physical(self.bdl) as u64;
        self.w32(sd + SD_BDPL, bdl as u32);
        self.w32(sd + SD_BDPU, (bdl >> 32) as u32);
        self.w32(sd + SD_CBL, (PERIODS * PERIOD_BYTES) as u32);
        self.w16(sd + SD_LVI, (PERIODS - 1) as u16);
        self.w16(sd + SD_FMT, FORMAT as u16);
        fence(Ordering::SeqCst);
        self.w32(sd + SD_CTL, TAG << 20 | SD_IOCE);
        self.w32(sd + SD_CTL, TAG << 20 | SD_IOCE | SD_RUN);
        self.next = 0;
        self.running = true;
        self.stopping = false;
        self.silent = 0;
    }

    /// Stops the stream.
    pub fn stop(&mut self) {
        let sd = self.stream;
        self.w32(sd + SD_CTL, TAG << 20);
        wait(10, || self.r32(sd + SD_CTL) & SD_RUN == 0);
        self.w8(sd + SD_STS, SD_STATUS);
        self.running = false;
        self.stopping = false;
        self.silent = 0;
    }

    /// The controller's interrupt: its causes cleared, the jack followed,
    /// and the periods played since last asked: the first's slot and how
    /// many, in order, to be filled again.
    pub fn interrupt(&mut self) -> (usize, usize) {
        let status = self.r32(INTSTS);
        if status & self.stream_bit != 0 {
            self.w8(self.stream + SD_STS, SD_STATUS);
        }
        if !self.immediate {
            self.w8(RIRBSTS, RIRB_STATUS);
            self.take_responses(false);
            // Each tells of a change; the pin says where it stands now.
            let mut rounds = 0;
            while !self.unsolicited.is_empty() && rounds < 4 {
                rounds += 1;
                let tags = core::mem::take(&mut self.unsolicited);
                if tags.iter().any(|r| r >> 26 == JACK_TAG)
                    && let Some(headphones) = self.headphones
                {
                    let present = self.sense(headphones);
                    self.jack(present);
                    println!("hda: headphones {}", if present { "in" } else { "out" });
                }
            }
        }
        if !self.running {
            return (self.next, 0);
        }
        let position = self.r32(self.stream + SD_LPIB) as usize;
        let now = (position / PERIOD_BYTES).min(PERIODS - 1);
        let played = (now + PERIODS - self.next) % PERIODS;
        let first = self.next;
        self.next = now;
        (first, played)
    }
}

/// The path from pin `from` back to an analog output converter: each
/// node and the connection it takes (the converter's unused), the pin
/// first. Through at most `depth` mixers and selectors; a converter other
/// than `avoid` first.
fn path(widgets: &[Widget], from: u8, depth: usize, avoid: Option<u8>) -> Option<Vec<(u8, usize)>> {
    let widget = widgets.iter().find(|w| w.nid == from)?;
    for pass in 0..2 {
        for (i, &c) in widget.connections.iter().enumerate() {
            let Some(next) = widgets.iter().find(|w| w.nid == c) else {
                continue;
            };
            match next.kind() {
                W_OUTPUT if next.caps & CAP_DIGITAL == 0 && (pass == 1 || avoid != Some(c)) => {
                    return Some(alloc::vec![(from, i), (c, 0)]);
                }
                W_MIXER | W_SELECTOR if depth > 0 => {
                    if let Some(rest) = path(widgets, c, depth - 1, if pass == 0 { avoid } else { None }) {
                        let mut whole = alloc::vec![(from, i)];
                        whole.extend(rest);
                        return Some(whole);
                    }
                }
                _ => {}
            }
        }
    }
    None
}

/// Resets the controller and its link. False if it did not come out.
fn reset(h: &Hda) -> bool {
    // Its DMA stopped first, as a firmware may have left it running.
    h.w8(CORBCTL, 0);
    h.w8(RIRBCTL, 0);
    wait(10, || {
        h.r8(CORBCTL) & CORB_RUN == 0 && h.r8(RIRBCTL) & RIRB_DMA == 0
    });
    h.w32(INTCTL, 0);
    h.w16(STATESTS, 0x7fff);
    h.w32(GCTL, h.r32(GCTL) & !GCTL_CRST);
    if !wait(100, || h.r32(GCTL) & GCTL_CRST == 0) {
        return false;
    }
    delay(1);
    h.w32(GCTL, h.r32(GCTL) | GCTL_CRST);
    if !wait(100, || h.r32(GCTL) & GCTL_CRST != 0) {
        return false;
    }
    // The codecs have 521 µs to ask for an address; some take longer.
    wait(50, || h.r16(STATESTS) & 0x7fff != 0);
    delay(1);
    true
}

/// Entries a ring of size register `size_register` takes, the largest
/// it can be: 256, 16 or 2.
fn ring_size(h: &Hda, size_register: usize) -> u16 {
    let caps = h.r8(size_register) >> 4;
    let (code, entries) = if caps & 4 != 0 {
        (2, 256)
    } else if caps & 2 != 0 {
        (1, 16)
    } else {
        (0, 2)
    };
    h.w8(size_register, (h.r8(size_register) & !3) | code);
    entries
}

/// The CORB and RIRB, reset and running.
fn start_rings(h: &mut Hda) -> bool {
    h.corb_entries = ring_size(h, CORBSIZE);
    h.rirb_entries = ring_size(h, RIRBSIZE);
    let corb = physical(h.rings) as u64;
    let rirb = corb + RIRB_AT as u64;
    h.w32(CORBLBASE, corb as u32);
    h.w32(CORBUBASE, (corb >> 32) as u32);
    h.w32(RIRBLBASE, rirb as u32);
    h.w32(RIRBUBASE, (rirb >> 32) as u32);
    // The read pointer's reset: some controllers show the bit set while
    // it holds, QEMU's never; neither is waited for longer than that.
    h.w16(CORBRP, CORBRP_RST);
    wait(2, || h.r16(CORBRP) & CORBRP_RST != 0);
    h.w16(CORBRP, 0);
    wait(2, || h.r16(CORBRP) & CORBRP_RST == 0);
    h.w16(CORBWP, 0);
    h.w16(RIRBWP, RIRBWP_RST);
    h.w16(RINTCNT, 1);
    h.corb_write = 0;
    h.rirb_read = 0;
    h.w8(CORBCTL, CORB_RUN);
    // The response flag raised (not yet the interrupt: INTCTL is off), as
    // a controller that holds the CORB until it is cleared needs it.
    h.w8(RIRBCTL, RIRB_DMA | RIRB_INT);
    wait(10, || {
        h.r8(CORBCTL) & CORB_RUN != 0 && h.r8(RIRBCTL) & RIRB_DMA != 0
    })
}

/// Codec `codec`'s output: its audio function group walked, the speaker
/// (or a line out, where there is none) and the headphone jack each given
/// a path to a converter, all of it powered and unmuted, the converters
/// set to the stream. False when it has no analog output.
fn set_up_codec(h: &mut Hda, codec: u8) -> bool {
    h.codec = codec;
    let Some(groups) = h.parameter(0, P_NODES) else {
        return false;
    };
    let (start, count) = ((groups >> 16) as u8, groups as u8);
    let Some(afg) = (start..start.saturating_add(count))
        .find(|&nid| h.parameter(nid, P_GROUP).is_some_and(|t| t & 0xff == 1))
    else {
        return false;
    };
    h.command(afg, SET_POWER, 0);
    wait(100, || {
        h.command(afg, GET_POWER, 0).is_none_or(|s| (s >> 4) & 0xf == 0)
    });
    let afg_in_amp = h.parameter(afg, P_IN_AMP).unwrap_or(0);
    let afg_out_amp = h.parameter(afg, P_OUT_AMP).unwrap_or(0);
    let Some(nodes) = h.parameter(afg, P_NODES) else {
        return false;
    };
    let (start, count) = ((nodes >> 16) as u8, nodes as u8);
    let mut widgets = Vec::new();
    for nid in start..start.saturating_add(count) {
        let Some(caps) = h.parameter(nid, P_CAPS) else {
            continue;
        };
        let override_amps = caps & CAP_AMP_OVERRIDE != 0;
        let mut w = Widget {
            nid,
            caps,
            connections: Vec::new(),
            pin_caps: 0,
            config: 0,
            in_amp: afg_in_amp,
            out_amp: afg_out_amp,
        };
        if override_amps {
            w.in_amp = h.parameter(nid, P_IN_AMP).unwrap_or(0);
            w.out_amp = h.parameter(nid, P_OUT_AMP).unwrap_or(0);
        }
        if caps & CAP_CONNECTIONS != 0 {
            w.connections = h.connections(nid);
        }
        if w.kind() == W_PIN {
            w.pin_caps = h.parameter(nid, P_PIN_CAPS).unwrap_or(0);
            w.config = h.command(nid, GET_CONFIG, 0).unwrap_or(0);
        }
        widgets.push(w);
    }
    // Output pins by what the firmware's default configuration says they
    // are: connected to something (not "none"), speaker, headphones, line out.
    let outputs = |device: u32| {
        widgets
            .iter()
            .filter(|w| {
                w.kind() == W_PIN
                    && w.pin_caps & PIN_OUTPUT != 0
                    && w.caps & CAP_DIGITAL == 0
                    && w.config >> 30 != 1
                    && (w.config >> 20) & 0xf == device
            })
            .map(|w| w.nid)
            .collect::<Vec<u8>>()
    };
    let speakers = outputs(1);
    let line_outs = outputs(0);
    let headphones = outputs(2);
    let (speaker_kind, speaker) = match (speakers.first(), line_outs.first()) {
        (Some(&s), _) => ("speaker", Some(s)),
        (None, Some(&l)) => ("line out", Some(l)),
        (None, None) => ("speaker", None),
    };
    let speaker_path = speaker.and_then(|p| path(&widgets, p, 4, None));
    let used = speaker_path.as_ref().and_then(|p| p.last()).map(|&(c, _)| c);
    let headphone = headphones.first().copied();
    let headphone_path = headphone.and_then(|p| path(&widgets, p, 4, used));
    if speaker_path.is_none() && headphone_path.is_none() {
        return false;
    }
    let vendor = h.parameter(0, P_VENDOR).unwrap_or(0);
    // Everything on the way: powered, selected, unmuted.
    for (route, hp) in [(&speaker_path, false), (&headphone_path, true)] {
        let Some(route) = route else { continue };
        for &(nid, index) in route {
            let Some(w) = widgets.iter().find(|w| w.nid == nid) else {
                continue;
            };
            if w.caps & CAP_POWER != 0 {
                h.command(nid, SET_POWER, 0);
            }
            let (caps, in_amp, out_amp, n) = (w.caps, w.in_amp, w.out_amp, w.connections.len());
            match w.kind() {
                W_OUTPUT => {
                    h.command4(nid, SET_FORMAT, FORMAT);
                    h.command(nid, SET_STREAM, TAG << 4);
                }
                W_MIXER => {
                    if caps & CAP_IN_AMP != 0 {
                        for j in 0..n {
                            h.amp(nid, false, j, in_amp, j != index);
                        }
                    }
                }
                _ => {
                    if n > 1 {
                        h.command(nid, SET_SELECT, index as u32);
                    }
                    if caps & CAP_IN_AMP != 0 {
                        h.amp(nid, false, index, in_amp, false);
                    }
                }
            }
            if caps & CAP_OUT_AMP != 0 {
                h.amp(nid, true, 0, out_amp, false);
            }
            if w.kind() == W_PIN {
                let pin_caps = w.pin_caps;
                let control = PINCTL_OUT
                    | if hp && pin_caps & PIN_HP_DRIVE != 0 {
                        PINCTL_HP
                    } else {
                        0
                    };
                h.command(nid, SET_PIN_CONTROL, control);
                if pin_caps & PIN_EAPD != 0 {
                    h.command(nid, SET_EAPD, 0x02);
                }
                let pin = Pin {
                    nid,
                    eapd: pin_caps & PIN_EAPD != 0,
                    // Bit 8 of the configuration: jack detection overridden.
                    sense: pin_caps & PIN_PRESENCE != 0 && w.config & 1 << 8 == 0,
                    trigger: pin_caps & PIN_TRIGGER != 0,
                };
                if hp {
                    h.headphones = Some(pin);
                } else {
                    h.speaker = Some(pin);
                }
            }
        }
    }
    let mut found = alloc::format!("codec {codec}: {:04x}:{:04x}", vendor >> 16, vendor & 0xffff);
    if let Some(p) = h.speaker {
        found += &alloc::format!(", {speaker_kind} on pin {:#04x}", p.nid);
    }
    if let Some(p) = h.headphones {
        found += &alloc::format!(", headphones on {:#04x}", p.nid);
        // The jack followed, where it can be: told by unsolicited response.
        if p.sense && !h.immediate {
            h.command(p.nid, SET_UNSOLICITED, 0x80 | JACK_TAG);
            h.w32(GCTL, h.r32(GCTL) | GCTL_UNSOL);
            let present = h.sense(p);
            h.jack(present);
            found += if present { " (in)" } else { " (out)" };
        }
    }
    if h.speaker.is_some_and(|s| s.eapd) || h.headphones.is_some_and(|s| s.eapd) {
        found += ", EAPD on";
    }
    h.found = found;
    true
}

/// Sets up the first HDA controller on PCI with a codec that plays: its
/// stream ready to start.
pub fn init() -> Option<Hda> {
    for f in crate::pci::find_class(CLASS) {
        let Some(regs) = f.bar_address(0, 0) else {
            continue;
        };
        if f.vendor == 0x8086 {
            // Intel's own: traffic class 0 (TCSEL), and its DMA snooped
            // (DEVC's no-snoop bit off), as Linux has them.
            f.write32(0x44, f.read32(0x44) & !7);
            f.write32(0x78, f.read32(0x78) & !(1 << 11));
        }
        let Some(intid) = f.take_interrupt() else {
            println!("hda: {:04x}:{:04x} has no interrupt", f.vendor, f.id);
            continue;
        };
        crate::pci::claim(&f, "intel-hda", crate::device::Class::Sound);
        if let Some(h) = start(regs, intid) {
            return Some(h);
        }
    }
    None
}

fn start(regs: usize, intid: u32) -> Option<Hda> {
    let rings = pages::alloc(0)?;
    let bdl = pages::alloc(0)?;
    // SAFETY: fresh pages, ours.
    unsafe {
        core::ptr::write_bytes(rings as *mut u8, 0, crate::mm::PAGE);
        core::ptr::write_bytes(bdl as *mut u8, 0, crate::mm::PAGE);
    }
    let mut periods = [0; PERIODS];
    for (i, p) in periods.iter_mut().enumerate() {
        *p = pages::alloc(0)?;
        // SAFETY: a fresh page; and BDL entry `i`, in ours: address,
        // length, an interrupt on completion.
        unsafe {
            core::ptr::write_bytes(*p as *mut u8, 0, crate::mm::PAGE);
            let entry = (bdl + i * 16) as *mut u32;
            let at = physical(*p) as u64;
            entry.write_volatile(at as u32);
            entry.add(1).write_volatile((at >> 32) as u32);
            entry.add(2).write_volatile(PERIOD_BYTES as u32);
            entry.add(3).write_volatile(1);
        }
    }
    let mut h = Hda {
        regs,
        intid,
        codec: 0,
        rings,
        corb_entries: 2,
        rirb_entries: 2,
        corb_write: 0,
        rirb_read: 0,
        immediate: false,
        unsolicited: Vec::new(),
        stream: 0,
        stream_bit: 0,
        bdl,
        periods,
        next: 0,
        running: false,
        stopping: false,
        silent: 0,
        speaker: None,
        headphones: None,
        found: String::new(),
    };
    let gcap = h.r16(GCAP);
    let (outputs, inputs) = (u32::from(gcap >> 12), u32::from((gcap >> 8) & 0xf));
    if outputs == 0 {
        println!("hda: no output stream");
        return None;
    }
    h.stream = SD_BASE + inputs as usize * 0x20;
    h.stream_bit = 1 << inputs;
    if !reset(&h) {
        println!("hda: the controller did not come out of reset");
        return None;
    }
    let codecs = h.r16(STATESTS) & 0x7fff;
    h.w16(STATESTS, codecs);
    if codecs == 0 {
        println!("hda: no codec");
        return None;
    }
    if !start_rings(&mut h) {
        println!("hda: the command rings did not start, using the immediate registers");
        h.immediate = true;
    }
    for codec in 0..15u8 {
        if codecs & 1 << codec == 0 {
            continue;
        }
        h.codec = codec;
        // A codec the rings do not reach: tried once more by the
        // immediate registers, the rings off.
        if h.parameter(0, P_VENDOR).is_none() && !h.immediate {
            println!("hda: no answer through the command rings, trying the immediate registers");
            h.w8(CORBCTL, 0);
            h.w8(RIRBCTL, 0);
            h.immediate = true;
        }
        if set_up_codec(&mut h, codec) {
            println!("hda: {}", h.found);
            return Some(h);
        }
        let vendor = h.parameter(0, P_VENDOR).unwrap_or(0);
        println!(
            "hda: codec {codec}: {:04x}:{:04x}, no analog output",
            vendor >> 16,
            vendor & 0xffff
        );
    }
    None
}