diff --git a/kernel-open/nvidia/gpu_owner.c b/kernel-open/nvidia/gpu_owner.c index e4d650fd..fa74f15a 100644 --- a/kernel-open/nvidia/gpu_owner.c +++ b/kernel-open/nvidia/gpu_owner.c @@ -264,6 +264,20 @@ u32 nv_rs_v100_p0_volt_uv(void) { return 1050000u; return v100_p0_volt_uv; } +/* #136: live board power + `nvidia-smi -pl` on GV100 boards whose PMU PMGR groups are + * otherwise never populated (seen on SXM2-to-PCIe adapter boards). Builds the nine + * PERF/PMGR board-object groups from the card's own VBIOS, sends them to the PMU, then + * reads power through the PWR_DEVICE status copy-out. Opt-in: the field mappings are + * observed on one card, not yet REA-confirmed. */ +static bool v100_pmu_power = false; +module_param(v100_pmu_power, bool, 0444); +MODULE_PARM_DESC(v100_pmu_power, "GV100: build the PMU PERF/PMGR groups from the VBIOS for live board power and power capping (#136; default: 0)"); +bool nv_rs_v100_pmu_power(void) { return v100_pmu_power; } +void nv_rs_pmu_power_log(u32 gpu_id, u32 stage, u32 a, u32 b, u32 c) +{ + pr_info("nvidia_rs: GV100 PMU power gpu=0x%08x stage=%u a=0x%x b=0x%x c=0x%x\n", + gpu_id, stage, a, b, c); +} static unsigned int force_pcie_gen = 0; module_param(force_pcie_gen, uint, 0644); MODULE_PARM_DESC(force_pcie_gen, "Opt-in PCIe link-speed override (0=untouched default, 2=Gen2 5GT/s, 3=Gen3 8GT/s, 4=Gen4 16GT/s for CMP/P10x/legacy hosts, #168)"); diff --git a/kernel-open/nvidia/gpu_owner.h b/kernel-open/nvidia/gpu_owner.h index d0088405..f0e4e0ce 100644 --- a/kernel-open/nvidia/gpu_owner.h +++ b/kernel-open/nvidia/gpu_owner.h @@ -46,6 +46,8 @@ u32 nv_rs_v100_hbm_ndiv_map_gen(void); u32 nv_rs_v100_p0_gpc_ndiv(void); size_t nv_rs_v100_p0_gpc_ndiv_map_copy(u8 *out, size_t cap); u32 nv_rs_v100_p0_volt_uv(void); +bool nv_rs_v100_pmu_power(void); +void nv_rs_pmu_power_log(u32 gpu_id, u32 stage, u32 a, u32 b, u32 c); u32 nv_rs_force_pcie_gen(void); bool nv_rs_idle_pstate(void); u32 nv_rs_idle_pstate_delay_s(void); diff --git a/src/nvidia/kernel/pmu_bringup.rs b/src/nvidia/kernel/pmu_bringup.rs index 15505e63..caefa4db 100644 --- a/src/nvidia/kernel/pmu_bringup.rs +++ b/src/nvidia/kernel/pmu_bringup.rs @@ -75,6 +75,9 @@ use nv_rs_core::{ }, mmu::{bar2_setup, engine_discovery::EngineRecord, placement}, }; +// #136 power path: only built outside the EDU guest, like the code that uses it. +#[cfg(not(nv_rs_edu_guest))] +use nv_rs_core::gpu::{gv100_pmu_tables, rom, rom_bit, rom_descriptors, RuntimeVariant}; unsafe extern "C" { fn nv_rs_os_busy_us(microseconds: u32); @@ -127,6 +130,8 @@ unsafe extern "C" { pwm_after: u32, ); fn nv_rs_pmgr_power_log(gpu_id: u32, load_st: u32, poll_st: u32, ch0_mw: u32, ch7_mw: u32); + fn nv_rs_v100_pmu_power() -> bool; + fn nv_rs_pmu_power_log(gpu_id: u32, stage: u32, a: u32, b: u32, c: u32); fn nv_rs_nvlink_enabled() -> bool; fn nv_rs_nvlink_boot_log( gpu_id: u32, @@ -482,6 +487,18 @@ struct Persist { /// RPCs so kernel stack frames stay strictly <= 1,024 bytes. pmgr_rpc_buf: [u8; pmu_pmgr::RPC_SIZE_PWR_MONITOR_GET_STATUS], volt_rpc_buf: [u8; pmu_volt::RPC_SIZE_VOLT_SET_VOLTAGE], + /// #136 (`v100_pmu_power`): this GPU's request buffer for the built PMU commands. + #[cfg(not(nv_rs_edu_guest))] + power_req_buf: [u8; POWER_REQ_BYTES], + /// #136: PWR_DEVICE (mask, sub-group count) for the power copy-out, set only once + /// this session's boot sequence completed; cleared again by `cleanup` and after the + /// first failed power read. + #[cfg(not(nv_rs_edu_guest))] + status_shape: Option<(u32, u16)>, + /// #136: this GPU's VBIOS, captured in `init_locked` before the PMU starts, taken by + /// `runtime_pmu_power_bringup`, and dropped by `cleanup` if that never ran. + #[cfg(not(nv_rs_edu_guest))] + pmu_vbios: Option, } impl Persist { @@ -516,6 +533,11 @@ impl Persist { (&raw mut (*place).fecs_start).write(None); (&raw mut (*place).gpccs_start).write(None); (&raw mut (*place).budget).write(None); + #[cfg(not(nv_rs_edu_guest))] + { + (&raw mut (*place).status_shape).write(None); + (&raw mut (*place).pmu_vbios).write(None); + } Self::initialise_rpc_scratch(place); } } @@ -526,6 +548,13 @@ impl Persist { for i in 0..pmu_pmgr::RPC_SIZE_PWR_MONITOR_GET_STATUS { core::ptr::write_volatile(pmgr_ptr.add(i), 0); } + #[cfg(not(nv_rs_edu_guest))] + { + let power_ptr = (&raw mut (*place).power_req_buf) as *mut u8; + for i in 0..POWER_REQ_BYTES { + core::ptr::write_volatile(power_ptr.add(i), 0); + } + } let volt_ptr = (&raw mut (*place).volt_rpc_buf) as *mut u8; for i in 0..pmu_volt::RPC_SIZE_VOLT_SET_VOLTAGE { core::ptr::write_volatile(volt_ptr.add(i), 0); @@ -1985,6 +2014,21 @@ fn init_locked(registers: &mut LockedGpuRegisters, parts: &mut Parts<'_>) -> boo // Nothing reads the state before this. unsafe { Persist::initialise(persist.as_ptr(), 0) }; let mut io = PmuIo { registers, parts }; + // #136 (`v100_pmu_power`): capture the VBIOS now, while the PMU is stopped (reading the + // PROM while it runs halted it on its next command, VFIO VM). + #[cfg(not(nv_rs_edu_guest))] + if unsafe { nv_rs_v100_pmu_power() } { + let captured = pmu_vbios_capture(&mut io); + // Stage 1: VBIOS capture failed (error code, see `pmu_vbios_capture`); 2 = not a + // GV100, which is expected and not logged. + if let Err(e) = captured.as_ref() { + if *e != 2 { + let gpu_id = unsafe { nv_rs_pci_gpu_id(io.registers.pci_token()) }; + unsafe { nv_rs_pmu_power_log(gpu_id, 1, *e, 0, 0) }; + } + } + *field!(io, pmu_vbios) = captured.ok(); + } // KernelFifo+170 (core `gr_fecs_start::subcontext_count`): the original // reads it once, before the FIFO load, and keeps the value. let subcontexts = match fecs::subcontext_count(&mut io, GV100_KFIFO_44D) { @@ -2598,6 +2642,11 @@ impl gr_bringup::WhileLoaded for Start<'_, '_> { // 3) Probe live hardware board power via GV100 PMGR HW I2C INA3221 // (scan active pull-up ports 0 & 2, 7-bit addrs 0x40..=0x43). let ina3221_loc = runtime_ina3221_init(io.registers); + // #136: PMU-owned board power (opt-in, `v100_pmu_power`). + #[cfg(not(nv_rs_edu_guest))] + if unsafe { nv_rs_v100_pmu_power() } { + runtime_pmu_power_bringup(&mut io); + } let target_gpc = if req_gpc > 172 && !volt_raised { 172 } else { @@ -2871,9 +2920,24 @@ impl gr_bringup::WhileLoaded for Start<'_, '_> { ); } } - let hw_power_mw = ina3221_loc.and_then(|(port, addr)| { - runtime_ina3221_poll(regs, port, addr) - }); + let hw_power_mw = ina3221_loc + .and_then(|(port, addr)| { + runtime_ina3221_poll(regs, port, addr) + }) + .or_else(|| { + // #136: the PMU's PWR_DEVICE copy-out, once + // `runtime_pmu_power_bringup` succeeded. + #[cfg(not(nv_rs_edu_guest))] + { + let mut pio = PmuIo { + registers: &mut *regs, + parts: unsafe { &mut *parts_ptr }, + }; + pmu_power_read(&mut pio) + } + #[cfg(nv_rs_edu_guest)] + None + }); // Live `nvidia-smi -pl` power-limit enforcement (#136): // closed-loop GPC NAFLL stepping with INA3221 power, or // proportional open-loop GPC cap when no sensor is present. @@ -3452,6 +3516,14 @@ fn pmu_unload_step(registers: &mut LockedGpuRegisters, parts: &mut Parts<'_>) -> /// them once bus mastering is confirmed off, or reports the leak. #[inline(never)] fn cleanup(registers: &mut LockedGpuRegisters, parts: &mut Parts<'_>, pmu_stopped: bool) -> bool { + // #136: the VBIOS image if startup ended before the power bring-up took it, and the + // session's power copy-out shape. + #[cfg(not(nv_rs_edu_guest))] + unsafe { + let persist = parts.persist.as_ptr(); + drop((*persist).pmu_vbios.take()); + (*persist).status_shape = None; + } let mut io = PmuIo { registers, parts }; *field!(io, reset_pending) = false; let deferred = core::mem::take(field!(io, deferred)); @@ -3619,6 +3691,317 @@ fn runtime_ina3221_poll(regs: &mut LockedGpuRegisters, port: u32, addr: u8) -> O } } +// --------------------------------------------------------------------------------------- +// #136: PMU-owned board power on GV100 (opt-in, `v100_pmu_power`). +// +// Stock 580.178.04, before its first power read, sends nine BOARDOBJ_GRP_CMD SETs +// (PERF unit 0x13: pstates, vpstates, VFE variables, VFE equations; PMGR unit 0x18: I2C +// devices, power equations, sensors, devices, policies), each after writing its group +// into the PMU super-surface, then reads power with a PWR_DEVICE copy-out. nvidia_rs +// never populated those groups, so the PMU never sampled the board's INA3221. Here the +// groups, requests and copy-out region are built from this GPU's VBIOS by +// `gv100_pmu_tables`. No LOAD is sent. Evidence: [O] on one adapter-board +// V100-SXM2-16GB (byte-identical to stock there); see the module docs. +// +// Log stages (`nv_rs_pmu_power_log`): 1 VBIOS capture error; 2 (0xffff = VBIOS not +// understood | mask, top-group count); 3 (command, error) group write failed; +// 4 (command, status, CPUCTL) per command; 5 (copy-out, mW, mA); 6 (PC, SP, r14) PMU +// halted; 7 (commands completed, mW) summary; 8 (status, CPUCTL) a live power read +// failed and polling stopped for this session. +// --------------------------------------------------------------------------------------- + +/// Size of `Persist::power_req_buf`: the largest built request +/// (`gv100_pmu_tables::REQUEST_MAX`, 0x434), rounded up. +#[cfg(not(nv_rs_edu_guest))] +const POWER_REQ_BYTES: usize = 0x440; +#[cfg(not(nv_rs_edu_guest))] +const _: () = assert!(gv100_pmu_tables::REQUEST_MAX <= POWER_REQ_BYTES); + +/// This GPU's VBIOS image (`Persist::pmu_vbios`). +#[cfg(not(nv_rs_edu_guest))] +struct PmuVbios { + image: Storage, + len: usize, + bit: u32, + base: u32, + expansion: u32, +} +#[cfg(not(nv_rs_edu_guest))] +impl PmuVbios { + fn bytes(&self) -> &[u8] { + // Exclusively owned and at least GV100_MAX_BYTES >= len long. + unsafe { core::slice::from_raw_parts(self.image.pointer.cast::().as_ptr(), self.len) } + } +} + +/// Captures the PROM the way `gr_bringup::vbios_overrides` does. Err codes: 1 boot +/// register, 2 not a GV100 (expected, not logged), 3 allocation, 4 PROM read, 5 image +/// list, 6 BIT header, 7 no PROM source for this chip. +#[cfg(not(nv_rs_edu_guest))] +#[inline(never)] +fn pmu_vbios_capture(io: &mut PmuIo<'_, '_>) -> Result { + let boot0 = io.registers.read32(0).map_err(|_| 1u32)?; + // GV100 only (PMC_BOOT_0 chip id 0x140): the group layouts and super-surface + // offsets in `gv100_pmu_tables` are GV100's. Other chips are left untouched. + if (boot0 >> 20) & 0x1ff != 0x140 { + return Err(2); + } + // chip_arch: legacy PMC_BOOT_0 architecture and implementation. + let architecture = (boot0 >> 3 & 0x20) | (boot0 >> 24 & 0x1f); + let implementation = (boot0 >> 20) & 0xf; + let source = + rom::PromSelection::select(architecture, implementation, RuntimeVariant::PfMonolithic) + .map_err(|_| 7u32)?; + let image = Storage::zeroed(rom::GV100_MAX_BYTES).ok_or(3u32)?; + // Exclusively owned, GV100_MAX_BYTES long and zeroed until `image` drops. + let buf = unsafe { + core::slice::from_raw_parts_mut(image.pointer.cast::().as_ptr(), rom::GV100_MAX_BYTES) + }; + source.capture(&mut *io.registers, buf).map_err(|_| 4u32)?; + let parsed = rom_descriptors::parse_owned_gv100::<7>(buf); + let Ok(list) = &parsed else { + return Err(5); + }; + let mut end = 0u32; + for entry in list.entries() { + end = end.max(entry.relative_offset.saturating_add(entry.bytes)); + } + let (expansion, base) = gr_level::vbios_expansion( + list.entries() + .iter() + .map(|e| (e.relative_offset, e.bytes, e.code_type)), + ); + let len = (end as usize).min(rom::GV100_MAX_BYTES); + let bit = match rom_bit::locate(&buf[..len], 0) { + Ok(found) if found.status == NvStatus::OK => found.offset, + _ => return Err(6), + }; + Ok(PmuVbios { + image, + len, + bit, + base, + expansion, + }) +} + +/// Zero-fills group `index`'s super-surface region and writes it from the VBIOS. +/// Err codes: 1 index, 2 surface, 3 zero fill, 4 table not understood, 5 BAR2 write. +#[cfg(not(nv_rs_edu_guest))] +#[inline(never)] +fn pmu_write_group( + io: &mut PmuIo<'_, '_>, + vb: &gv100_pmu_tables::Vbios<'_>, + index: usize, +) -> Result<(), u32> { + let g = gv100_pmu_tables::GROUPS.get(index).ok_or(1u32)?; + let at = io + .surface_at(g.surface, g.region as usize) + .map_err(|_| 2u32)?; + // black_box: a constant byte lets LLVM emit memset (refused in the module). + io.bar2_bytes(at, g.region as usize, |_| black_box(0)) + .map_err(|_| 3u32)?; + let mut failed = false; + let built = gv100_pmu_tables::emit(vb, index, &mut |off, byte| { + if io.bar2_bytes(at + off, 1, |_| black_box(byte)).is_err() { + failed = true; + } + }); + if built.is_none() { + return Err(4); + } + if failed { + return Err(5); + } + Ok(()) +} + +/// Writes the PWR_DEVICE copy-out region before a power read. +#[cfg(not(nv_rs_edu_guest))] +#[inline(never)] +fn pmu_write_copy_out(io: &mut PmuIo<'_, '_>, mask: u32, count: u16) -> Result<(), ()> { + let g = gv100_pmu_tables::COPY_OUT; + let len = g.region as usize; + io.surface_at(g.surface, len) + .and_then(|at| { + io.bar2_bytes(at, len, |i| { + black_box(gv100_pmu_tables::copy_out_byte(mask, count, i)) + }) + }) + .map(|_| ()) + .map_err(|_| ()) +} + +/// Sends built request `cmd` on the low queue, as stock does. Returns (status, or +/// 0x8000_0000 | status on a transport error; PMU CPUCTL). +#[cfg(not(nv_rs_edu_guest))] +#[inline(never)] +fn pmu_send_built(io: &mut PmuIo<'_, '_>, cmd: usize) -> (u32, u32) { + let Some(len) = gv100_pmu_tables::request_len(cmd) else { + return (0x8000_ffff, 0); + }; + let buf = field!(io, power_req_buf); + if len > buf.len() { + return (0x8000_fffe, 0); + } + let mut i = 0usize; + while i < len { + buf[i] = black_box(gv100_pmu_tables::request_byte(cmd, i)); + i += 1; + } + let st = match { + let transport = field!(io, transport); + transport.execute_with_scratch(io, pmu_fbq::Queue::Low, &mut buf[..len], 0) + } { + Ok(st) => st.0, + Err(st) => 0x8000_0000 | st.0, + }; + (st, io.registers.read32(0x0010_a100).unwrap_or(0xffff_ffff)) +} + +/// Device 0's (mW, mA) from the copy-out record the PMU fills (+0x1c mW, +0x20 mA, +/// +0x24 uV). +#[cfg(not(nv_rs_edu_guest))] +fn pmu_status_record(io: &mut PmuIo<'_, '_>) -> Option<(u32, u32)> { + let mut rec = [0u8; 8]; + io.surface_at(gv100_pmu_tables::COPY_OUT.surface + 0x1c, 8) + .and_then(|at| io.bar2_read_bytes(at, &mut rec)) + .ok()?; + Some(( + u32::from_le_bytes([rec[0], rec[1], rec[2], rec[3]]), + u32::from_le_bytes([rec[4], rec[5], rec[6], rec[7]]), + )) +} + +/// One live board-power read (mW) for the monitor tick. None until this session's boot +/// sequence completed. +/// +/// A failed read (including a reply timeout, after which the transport refuses every +/// later command, as the original does: a timed-out request may still act in the +/// firmware) turns polling off for the rest of the session and is logged once (stage 8: +/// status, CPUCTL), so the tick never keeps issuing commands to a PMU that stopped +/// answering. The governor then falls back to its no-sensor behaviour. +#[cfg(not(nv_rs_edu_guest))] +#[inline(never)] +fn pmu_power_read(io: &mut PmuIo<'_, '_>) -> Option { + let (mask, count) = (*field!(io, status_shape))?; + let (st, cpuctl) = if pmu_write_copy_out(io, mask, count).is_ok() { + let saved = *field!(io, budget); + *field!(io, budget) = None; + let sent = pmu_send_built(io, gv100_pmu_tables::COPY_OUT_CMD); + *field!(io, budget) = saved; + sent + } else { + (0x8000_00c0, 0) + }; + let record = if st == 0 && cpuctl & 0x10 == 0 { + pmu_status_record(io) + } else { + None + }; + if record.is_none() { + *field!(io, status_shape) = None; + let gpu_id = unsafe { nv_rs_pci_gpu_id(io.registers.pci_token()) }; + unsafe { nv_rs_pmu_power_log(gpu_id, 8, st, cpuctl, 0) }; + } + record.map(|(mw, _)| mw) +} + +/// Stock's boot sequence, built: the nine groups, each followed by its SET request, then +/// three PWR_DEVICE copy-outs 1 s apart (as stock). Stops at the first failed command or +/// halted PMU. Returns the commands completed; on success the copy-out shape is stored +/// for `pmu_power_read`. +#[cfg(not(nv_rs_edu_guest))] +#[inline(never)] +fn pmu_built_sequence( + io: &mut PmuIo<'_, '_>, + gpu_id: u32, + vb: &gv100_pmu_tables::Vbios<'_>, +) -> (u32, u32) { + let log = |stage: u32, a: u32, b: u32, c: u32| unsafe { + nv_rs_pmu_power_log(gpu_id, stage, a, b, c); + }; + let Some((mask, count)) = gv100_pmu_tables::pwr_device_status_shape(vb) else { + log(2, 0xffff, 0, 0); + return (0, 0); + }; + log(2, mask, u32::from(count), 0); + let sets = gv100_pmu_tables::GROUPS.len() as u32; + let mut k = 0u32; + let mut mw = 0u32; + while k < sets + 3 { + let cmd = if k < sets { + if let Err(e) = pmu_write_group(io, vb, k as usize) { + log(3, k + 1, e, 0); + return (k, 0); + } + k as usize + } else { + if pmu_write_copy_out(io, mask, count).is_err() { + log(3, k + 1, 0xc0, 0); + return (k, 0); + } + gv100_pmu_tables::COPY_OUT_CMD + }; + let (st, cpuctl) = pmu_send_built(io, cmd); + // Stage 4: (command number attempted, status, CPUCTL). + log(4, k + 1, st, cpuctl); + if st != 0 || cpuctl & 0x10 != 0 { + // PMU ICD: PC, SP, r14. A halt here is usually the ucode rejecting a group + // (it executes `exit` on bad input); the PC locates the check. + if cpuctl & 0x10 != 0 { + let mut icd = |i: u32| { + let _ = io.registers.write32(0x0010_a200, (i << 8) | 8); + io.registers.read32(0x0010_a20c).unwrap_or(0xffff_ffff) + }; + let (pc, sp, r14) = (icd(0x15), icd(0x14), icd(0xe)); + log(6, pc, sp, r14); + } + // Only the commands that completed are counted. + return (k, 0); + } + k += 1; + if k > sets { + // Stock reads the record about 1 s after each copy-out. + let mut t = 0; + while t < 1000 { + unsafe { nv_rs_os_busy_us(1_000) }; + t += 1; + } + let (p, a) = pmu_status_record(io).unwrap_or((0, 0)); + mw = p; + log(5, k, p, a); + } + } + *field!(io, status_shape) = Some((mask, count)); + (k, mw) +} + +/// Runs once per GPU after the PMU is up (only with `v100_pmu_power=1`, only on GV100). +#[cfg(not(nv_rs_edu_guest))] +#[inline(never)] +fn runtime_pmu_power_bringup(io: &mut PmuIo<'_, '_>) { + let gpu_id = unsafe { nv_rs_pci_gpu_id(io.registers.pci_token()) }; + // Taken here, so the image is freed when this returns. + let Some(captured) = field!(io, pmu_vbios).take() else { + return; + }; + let Some(vb) = gv100_pmu_tables::Vbios::new( + captured.bytes(), + captured.bit, + captured.base, + captured.expansion, + ) else { + unsafe { nv_rs_pmu_power_log(gpu_id, 2, 0xffff, 1, 0) }; + return; + }; + let saved = *field!(io, budget); + *field!(io, budget) = None; + let (done, mw) = pmu_built_sequence(io, gpu_id, &vb); + *field!(io, budget) = saved; + unsafe { nv_rs_pmu_power_log(gpu_id, 7, done, mw, 0) }; +} + #[cfg(not(nv_rs_edu_guest))] #[allow(dead_code)] #[inline(never)] diff --git a/src/nvidia/src/gpu.rs b/src/nvidia/src/gpu.rs index 9a0676c5..028544c1 100644 --- a/src/nvidia/src/gpu.rs +++ b/src/nvidia/src/gpu.rs @@ -102,6 +102,7 @@ pub mod gsp_ucode; pub mod gv100_ce_scrub; pub mod gv100_irq_service; pub mod gv100_p0_boost; +pub mod gv100_pmu_tables; pub mod hbm_clock; pub mod hdcp; pub mod host_time; diff --git a/src/nvidia/src/gpu/gv100_pmu_tables.rs b/src/nvidia/src/gpu/gv100_pmu_tables.rs new file mode 100644 index 00000000..77d1f8c5 --- /dev/null +++ b/src/nvidia/src/gpu/gv100_pmu_tables.rs @@ -0,0 +1,1119 @@ +//! #136 (opt-in, `v100_pmu_power=1`): the nine PMU board-object groups the stock 580.178.04 RM sends +//! (PERF: VFE vars/equations, vpstates, pstates; PMGR: I2C devices, power equations, +//! sensors, devices, policies) before its PWR_DEVICE copy-out, built from the VBIOS. +//! +//! Evidence: [O] — every mapping was matched against one adapter-board V100-SXM2-16GB's +//! stock super-surface (read back through BAR2 after a stock 580.178.04 init, in a VFIO +//! VM) and its VBIOS, not REA-confirmed against `nv-kernel.o_binary`. On that card all nine +//! groups are byte-identical to stock; several fields are [O] constants (marked). +//! [A]: the 0x27 header word 108000 is clock domain 0x17 in `_nv020519rm`. +//! +//! Also the twelve requests that send them (nine `BOARDOBJ_GRP_CMD` SETs, then the +//! PWR_DEVICE status copy-out stock sends to read power) and the copy-out's surface +//! region, so no recorded stock bytes are needed: see [`request_len`], [`request_byte`], +//! [`copy_out_byte`]. +//! +//! Every VBIOS read is bounds-checked: a table this code does not understand yields +//! `None`, never a panic. + +/// One group as stock sends it: board-object class, super-surface offset of the group, +/// and the length of the region stock's command covers (zero-filled before writing). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Group { + pub class: u8, + pub surface: u32, + pub region: u32, +} + +/// In stock command order (#1..#9 of the captured stream). +pub const GROUPS: [Group; 9] = [ + Group { + class: 0x1c, + surface: 0x1d_1130, + region: 0x8410, + }, + Group { + class: 0x1b, + surface: 0x1c_0200, + region: 0x1_0f30, + }, + Group { + class: 0x19, + surface: 0x1a_23b0, + region: 0x1_de50, + }, + Group { + class: 0x1a, + surface: 0x15_a2a0, + region: 0x4_8110, + }, + Group { + class: 0x2a, + surface: 0x01_b6e0, + region: 0x210, + }, + Group { + class: 0x26, + surface: 0x01_b0d0, + region: 0x610, + }, + Group { + class: 0x27, + surface: 0x01_32b0, + region: 0x7e20, + }, + Group { + class: 0x28, + surface: 0x02_03b0, + region: 0x3240, + }, + Group { + class: 0x29, + surface: 0x01_bcf0, + region: 0x46c0, + }, +]; + +/// A VBIOS image with its BIT 'P' (v2) data located. +#[derive(Clone, Copy)] +pub struct Vbios<'a> { + rom: &'a [u8], + p: usize, + /// The 'P' token's declared data size: slots at or past it are absent. + p_len: usize, + /// Pointers above `base` (the legacy image length) live in the extended image: add + /// `expansion` (`gr_level::vbios_expansion`; strict `>` as in `gr_level::vbios_overrides`). + base: u32, + expansion: u32, +} + +impl<'a> Vbios<'a> { + /// `bit`: offset of the BIT header (`rom_bit::locate`). + pub fn new(rom: &'a [u8], bit: u32, base: u32, expansion: u32) -> Option { + let bit = bit as usize; + let header_size = usize::from(*rom.get(bit + 8)?); + let token_size = usize::from(*rom.get(bit + 9)?); + let tokens = usize::from(*rom.get(bit + 10)?); + if !(6..8).contains(&token_size) { + return None; + } + let mut i = 0; + while i < tokens { + let t = bit + header_size + token_size * i; + if *rom.get(t)? == 0x50 && *rom.get(t + 1)? == 2 { + // BIT token: id, version, data size (u16), data pointer (u16). + let size = usize::from(u16::from_le_bytes([*rom.get(t + 2)?, *rom.get(t + 3)?])); + let data = usize::from(u16::from_le_bytes([*rom.get(t + 4)?, *rom.get(t + 5)?])); + return Some(Self { + rom, + p: data, + p_len: size, + base, + expansion, + }); + } + i += 1; + } + None + } + + fn b(&self, at: usize) -> Option { + self.rom.get(at).copied() + } + fn u16(&self, at: usize) -> Option { + Some(u16::from_le_bytes([self.b(at)?, self.b(at + 1)?])) + } + fn u32(&self, at: usize) -> Option { + Some(u32::from_le_bytes([ + self.b(at)?, + self.b(at + 1)?, + self.b(at + 2)?, + self.b(at + 3)?, + ])) + } + fn remap(&self, pointer: u32) -> Option { + let p = if pointer <= self.base { + pointer + } else { + pointer.checked_add(self.expansion)? + }; + let p = p as usize; + (p < self.rom.len()).then_some(p) + } + /// BIT 'P' table pointer at `slot` (byte offset into the 'P' data). A slot outside + /// the token's declared data size is absent, not read from whatever follows it. + fn table(&self, slot: usize) -> Option { + if slot.checked_add(4)? > self.p_len { + return None; + } + self.remap(self.u32(self.p + slot)?) + } + fn dcb_i2c_devices(&self) -> Option { + let dcb = usize::from(self.u16(0x36)?); + Some(usize::from(self.u16(dcb + 0x12)?)) + } +} + +/// Bounds-checked byte writer over one group region. +struct Out<'s, S: FnMut(u32, u8)> { + sink: &'s mut S, + len: u32, +} +impl Out<'_, S> { + fn u8(&mut self, at: usize, v: u8) -> Option<()> { + let at = u32::try_from(at).ok()?; + if at >= self.len { + return None; + } + (self.sink)(at, v); + Some(()) + } + fn u16(&mut self, at: usize, v: u16) -> Option<()> { + let b = v.to_le_bytes(); + self.u8(at, b[0])?; + self.u8(at + 1, b[1]) + } + fn u32(&mut self, at: usize, v: u32) -> Option<()> { + let b = v.to_le_bytes(); + let mut i = 0; + while i < 4 { + self.u8(at + i, b[i])?; + i += 1; + } + Some(()) + } + fn u64(&mut self, at: usize, v: u64) -> Option<()> { + self.u32(at, v as u32)?; + self.u32(at + 4, (v >> 32) as u32) + } + /// Copy `n` VBIOS bytes from `from` to `at`. + fn copy(&mut self, at: usize, vb: &Vbios<'_>, from: usize, n: usize) -> Option<()> { + let mut i = 0; + while i < n { + self.u8(at + i, vb.b(from + i)?)?; + i += 1; + } + Some(()) + } + fn e32_header(&mut self, class: u8, count: u16, mask: u32, byte6: u16) -> Option<()> { + self.u32(0, 0x01 | 0xff << 8 | u32::from(class) << 16)?; + self.u16(4, count)?; + self.u16(6, byte6)?; + self.u32(8, mask) + } + fn mask_bits(&mut self, at: usize, n: usize) -> Option<()> { + let mut i = 0; + while i < n { + let byte = at + i / 8; + let mut v = 0u8; + let mut j = i; + while j < n && j / 8 == i / 8 { + v |= 1 << (j % 8); + j += 1; + } + self.u8(byte, v)?; + i = j; + } + Some(()) + } +} + +/// Writes group `index` (into `GROUPS`) as (offset within the group, byte) pairs. The +/// caller zero-fills `GROUPS[index].region` first; only fields are written. A byte may be +/// written more than once; the last write is the value. `None`: the VBIOS has a shape +/// this code does not handle (the region may then be partly written). +pub fn emit(vb: &Vbios<'_>, index: usize, sink: &mut S) -> Option<()> { + let g = GROUPS.get(index)?; + let mut o = Out { + sink, + len: g.region, + }; + match g.class { + 0x1c => pstate(vb, &mut o), + 0x1b => vpstate(vb, &mut o), + 0x19 => vfe_var(vb, &mut o), + 0x1a => vfe_equ(vb, &mut o), + 0x2a => i2c_dev(vb, &mut o), + 0x26 => pwr_equation(vb, &mut o), + 0x27 => pwr_sensor(vb, &mut o), + 0x28 => pwr_device(vb, &mut o), + 0x29 => pwr_policy(vb, &mut o), + _ => None, + } +} + +// ------------------------------------------------------------------- VFE (P slot 0x20) + +struct Vfe { + at: usize, + hdr: usize, + var_sz: usize, + var_n: usize, + equ_sz: usize, + equ_n: usize, + /// Equations up to the first type-0 entry. + ne: usize, +} + +fn vfe(vb: &Vbios<'_>) -> Option { + let at = vb.table(0x20)?; + let mut v = Vfe { + at, + hdr: usize::from(vb.b(at + 1)?), + var_sz: usize::from(vb.b(at + 2)?), + var_n: usize::from(vb.b(at + 3)?), + equ_sz: usize::from(vb.b(at + 4)?), + equ_n: usize::from(vb.b(at + 5)?), + ne: 0, + }; + if v.var_sz < 22 || v.equ_sz < 24 || v.var_n > 16 { + return None; + } + // [O] stock's count is every non-zero entry, and the serializers index entries + // 0..count, which is only right for a table with no type-0 gaps (as on the reference + // VBIOS). How stock lays out a sparse table is unknown, so refuse one. The dependency + // masks are 64-bit. + v.ne = contiguous_count(v.equ_n, |k| vb.b(v.equ(k)))?; + if v.ne > 64 || contiguous_count(v.var_n, |k| vb.b(v.var(k))).is_none() { + return None; + } + Some(v) +} +/// Number of leading non-zero type bytes among `n` entries; None if a non-zero entry +/// follows a zero one (a sparse table) or a read is out of bounds. +fn contiguous_count(n: usize, ty: impl Fn(usize) -> Option) -> Option { + let mut count = 0; + let mut gap = false; + let mut k = 0; + while k < n { + if ty(k)? == 0 { + gap = true; + } else if gap { + return None; + } else { + count += 1; + } + k += 1; + } + Some(count) +} + +impl Vfe { + fn var(&self, i: usize) -> usize { + self.at + self.hdr + i * self.var_sz + } + fn equ(&self, i: usize) -> usize { + self.at + self.hdr + self.var_n * self.var_sz + i * self.equ_sz + } +} + +/// Variables reading variable x (types 5/6 read bytes 9 and 10), transitively, incl. x. +fn var_dependents(vb: &Vbios<'_>, f: &Vfe, x: usize) -> Option { + let mut s = 1u32 << x; + let mut changed = true; + while changed { + changed = false; + let mut i = 0; + while i < f.var_n { + let v = f.var(i); + let t = vb.b(v)?; + if s & (1 << i) == 0 && (t == 5 || t == 6) { + let (a, b) = (u32::from(vb.b(v + 9)?), u32::from(vb.b(v + 10)?)); + if (a < 32 && s & (1 << a) != 0) || (b < 32 && s & (1 << b) != 0) { + s |= 1 << i; + changed = true; + } + } + i += 1; + } + } + Some(s) +} + +/// A quadratic's `next` byte links a summed chain: the chain from i as a mask. +fn eq_chain(vb: &Vbios<'_>, f: &Vfe, mut i: usize) -> Option { + let mut m = 0u64; + while i < f.ne && m & (1 << i) == 0 { + m |= 1 << i; + let e = f.equ(i); + let next = vb.b(e + 2)?; + if vb.b(e)? == 1 && next != 0xff { + i = usize::from(next); + } else { + break; + } + } + Some(m) +} + +/// Equations reading a variable of `vars` directly (types 1/3, byte 1), or a min/max/ +/// compare whose referenced equation's chain contains one. +fn eq_dependents(vb: &Vbios<'_>, f: &Vfe, vars: u32) -> Option { + let mut d = 0u64; + let mut i = 0; + while i < f.ne { + let e = f.equ(i); + let t = vb.b(e)?; + let var = u32::from(vb.b(e + 1)?); + if (t == 1 || t == 3) && var < 32 && vars & (1 << var) != 0 { + d |= 1 << i; + } + i += 1; + } + let mut changed = true; + while changed { + changed = false; + let mut i = 0; + while i < f.ne { + let e = f.equ(i); + let refs = match vb.b(e)? { + 2 => Some((vb.b(e + 11)?, vb.b(e + 12)?)), + 3 => Some((vb.b(e + 15)?, vb.b(e + 16)?)), + _ => None, + }; + if d & (1 << i) == 0 { + if let Some((a, b)) = refs { + let mut hit = false; + for r in [usize::from(a), usize::from(b)] { + if r < f.ne && eq_chain(vb, f, r)? & d != 0 { + hit = true; + } + } + if hit { + d |= 1 << i; + changed = true; + } + } + } + i += 1; + } + } + Some(d) +} + +/// GV100 fuse id -> (bitfield word = width << 8 | shift, register). [O] only the ids this +/// VBIOS uses; an unknown id refuses the group. +const FUSE: [(u8, u32, u32); 6] = [ + (0x07, 0x0b00, 0x214a8), + (0x08, 0x0200, 0x214a0), + (0x09, 0x0b00, 0x212d4), + (0x0a, 0x0200, 0x214a4), + (0x0e, 0x0300, 0x216ec), + (0x0f, 0x0504, 0x216ec), +]; + +fn fuse(id: u8) -> Option<(u32, u32)> { + let mut i = 0; + while i < FUSE.len() { + if FUSE[i].0 == id { + return Some((FUSE[i].1, FUSE[i].2)); + } + i += 1; + } + None +} + +fn vfe_var(vb: &Vbios<'_>, o: &mut Out<'_, S>) -> Option<()> { + let f = vfe(vb)?; + const HDR: usize = 0x30; + const STRIDE: usize = 0x1e0; + let mut n = 0usize; + let mut i = 0; + while i < f.var_n { + if vb.b(f.var(i))? != 0 { + n += 1; + } + i += 1; + } + o.u32(0, 0x02 | 0xff << 8 | 0x19 << 16)?; + o.u32(4, n as u32)?; + o.mask_bits(8, n)?; + o.u8(0x28, vb.b(f.at + 6)?)?; + let mut i = 0; + while i < f.var_n { + let v = f.var(i); + let t = vb.b(v)?; + if t == 0 { + i += 1; + continue; + } + let e = HDR + i * STRIDE; + let pmu_type = match t { + 0x02 => 9, + 0x03 => 8, + 0x04 => 7, + 0x05 => 2, + 0x06 => 3, + _ => 0, + }; + o.u32(e, pmu_type)?; + o.copy(e + 4, vb, v + 1, 8)?; + if t != 5 && t != 6 { + let deps = var_dependents(vb, &f, i)?; + o.u16(e + 0x0c, deps as u16)?; + o.u64(e + 0x2c, eq_dependents(vb, &f, deps)?)?; + } + if t == 0x03 { + o.u8(e + 0x13c, vb.b(v + 9)?)?; + o.u32(e + 0x140, u32::from(vb.b(v + 10)?) << 5)?; + o.u32(e + 0x144, u32::from(vb.b(v + 11)?) << 5)?; + o.u32(e + 0x14c, 0x9600)?; // [O] constant, unexplained + } + if t == 0x05 || t == 0x06 { + o.u8(e + 0x130, vb.b(v + 9)?)?; + o.u8(e + 0x131, vb.b(v + 10)?)?; + } + if t == 0x04 { + o.u16(e + 0x148, vb.u16(v + 13)?)?; + o.u8(e + 0x14d, vb.b(v + 11)?)?; + if vb.b(v + 12)? & 0x02 != 0 { + o.u8(e + 0x144, 1)?; + o.u8(e + 0x14c, 1)?; + } + o.u8(e + 0x14f, 1)?; + o.u32(e + 0x154, vb.u32(v + 17)?)?; + let (a, b) = (vb.b(v + 9)?, vb.b(v + 10)?); + o.u8(e + 0x15c, a)?; + o.u8(e + 0x15d, b)?; + for (slot, id) in [(0x160usize, a), (0x1a0, b)] { + let (word, reg) = fuse(id)?; + o.u32(e + slot, 1)?; + o.u32(e + slot + 4, 1)?; + o.u32(e + slot + 8, word)?; + o.u32(e + slot + 12, reg)?; + } + } + i += 1; + } + Some(()) +} + +fn vfe_equ(vb: &Vbios<'_>, o: &mut Out<'_, S>) -> Option<()> { + let f = vfe(vb)?; + const HDR: usize = 0x110; + const STRIDE: usize = 0x90; + o.u32(0, 0x05 | 0xff << 8 | 0x1a << 16)?; + o.u32(4, f.ne as u32)?; // count includes the unsent type-4 entries [O] + let mut mask = [0u8; 8]; + let mut i = 0; + while i < f.ne { + let v = f.equ(i); + let t = vb.b(v)?; + let pmu_type = match t { + 0x01 => 3, + 0x02 => 2, + 0x03 => 1, + _ => { + i += 1; + continue; + } + }; + mask[i / 8] |= 1 << (i % 8); + let e = HDR + i * STRIDE; + o.u32(e, pmu_type)?; + o.u16(e + 4, u16::from(vb.b(v + 1)?))?; + let next = vb.b(v + 2)?; + o.u16( + e + 6, + if next == 0xff { + 0xffff + } else { + u16::from(next) + }, + )?; + o.u8(e + 8, vb.b(v + 23)?)?; + o.copy(e + 0x0c, vb, v + 3, 8)?; + match t { + 0x01 => o.copy(e + 0x18, vb, v + 11, 12)?, + 0x02 => { + o.u8(e + 0x18, vb.b(v + 13)? & 1)?; + o.u16(e + 0x1a, u16::from(vb.b(v + 11)?))?; + o.u16(e + 0x1c, u16::from(vb.b(v + 12)?))?; + } + _ => { + o.u8(e + 0x18, vb.b(v + 17)?)?; + o.u16(e + 0x1a, u16::from(vb.b(v + 15)?))?; + o.u16(e + 0x1c, u16::from(vb.b(v + 16)?))?; + o.copy(e + 0x20, vb, v + 11, 4)?; + } + } + i += 1; + } + let mut k = 0; + while k < 8 { + o.u8(8 + k, mask[k])?; + k += 1; + } + Some(()) +} + +// ------------------------------------------------------------------- PERF + +fn vpstate(vb: &Vbios<'_>, o: &mut Out<'_, S>) -> Option<()> { + let t = vb.table(0x38)?; + const HDR: usize = 0x40; + const STRIDE: usize = 0x110; + let (hs, es, n, ss, sn) = ( + usize::from(vb.b(t + 1)?), + usize::from(vb.b(t + 2)?), + usize::from(vb.b(t + 3)?), + usize::from(vb.b(t + 4)?), + usize::from(vb.b(t + 5)?), + ); + if ss < 4 || sn > 32 { + return None; + } + o.u32(0, 0x02 | 0x03 << 8 | 0x1b << 16)?; // E255; byte 1 = 3 here [O] + o.u32(4, n as u32)?; + o.mask_bits(8, n)?; + // [O] AMBIGUOUS named-vpstate array (16 x u8 at +0x28, 0xff = unset), see the tool. + let mut k = 0; + while k < 16 { + let v = match k { + 0 => vb.b(t + 8)?, + 2 => vb.b(t + 7)?, + 15 => vb.b(t + 9)?, + 1 | 3 | 9 => vb.b(t + 6)?, + _ => 0xff, + }; + o.u8(0x28 + k, v)?; + k += 1; + } + o.u8(0x38, n as u8)?; + let mut rec = t + hs; + let mut i = 0; + while i < n { + let e = HDR + i * STRIDE; + o.u32(e, 3)?; + let mut mask = 0u32; + let mut d = 0; + while d < sn { + let sub = vb.u32(rec + es + d * ss)?; + if sub != 0 { + mask |= 1 << d; + let (f, lo) = (sub & 0xfff, (sub >> 14) & 0x7ff); + o.u32(e + 0x0c + d * 8, lo << 16 | f)?; + o.u32(e + 0x10 + d * 8, f << 16 | f)?; + } + d += 1; + } + o.u32(e + 8, mask)?; + rec += es + ss * sn; + i += 1; + } + Some(()) +} + +fn pstate(vb: &Vbios<'_>, o: &mut Out<'_, S>) -> Option<()> { + let t = vb.table(0x00)?; + const HDR: usize = 0x10; + const STRIDE: usize = 0x420; + let (hs, bs, n, ss, sn) = ( + usize::from(vb.b(t + 1)?), + usize::from(vb.b(t + 2)?), + usize::from(vb.b(t + 3)?), + usize::from(vb.b(t + 4)?), + usize::from(vb.b(t + 5)?), + ); + // Each sub-entry takes 12 bytes from +0x14 of its record: refuse a count that would + // spill into the next record (the group-wide bounds check would not catch it). + if bs < 3 || ss < 6 || n > 32 || 0x14 + sn * 12 > STRIDE { + return None; + } + o.u32(0, 0x01 | 0x04 << 8 | 0x1c << 16)?; // E32; byte 1 = 4 here [O] + o.u32(4, n as u32)?; + let (mut mask, mut count, mut last) = (0u32, 0u8, 0xffu8); + let mut rec = t + hs; + let mut i = 0; + while i < n { + if vb.b(rec)? != 0xff { + mask |= 1 << i; + count += 1; + last = i as u8; + let e = HDR + i * STRIDE; + o.u32(e, 3)?; // [O] type + o.u32(e + 4, u32::from(vb.b(rec + 2)?))?; + o.u32(e + 8, 0x480)?; // [O] constant, unexplained + o.u32(e + 0x0c, 1)?; // [O] constant + let mut d = 0; + while d < sn { + let sb = rec + bs + d * ss; + let nom = u32::from(vb.u16(sb)?); + let mm = vb.u32(sb + 2)?; + if nom != 0 || mm != 0 { + let (lo, hi) = (mm & 0x3fff, (mm >> 14) & 0x3fff); + let k = if d < 8 { 1000 } else { 1 }; // [O] domain 8 is not a clock + o.u32(e + 0x14 + d * 12, nom * k)?; + o.u32(e + 0x18 + d * 12, lo * k)?; + o.u32(e + 0x1c + d * 12, hi * k)?; + } + d += 1; + } + } + rec += bs + ss * sn; + i += 1; + } + o.u32(8, mask)?; + o.u8(0x0c, sn as u8)?; + o.u8(0x0d, last)?; // [O] index of the (last) valid pstate + o.u8(0x0e, count) +} + +// ------------------------------------------------------------------- PMGR + +fn i2c_dev(vb: &Vbios<'_>, o: &mut Out<'_, S>) -> Option<()> { + let t = vb.dcb_i2c_devices()?; + let (hs, n, es) = ( + usize::from(vb.b(t + 1)?), + usize::from(vb.b(t + 2)?), + usize::from(vb.b(t + 3)?), + ); + let (mut k, mut mask) = (0usize, 0u32); + let mut i = 0; + while i < n { + let d = t + hs + i * es; + let ty = vb.b(d)?; + if ty != 0xff { + if k >= 32 { + return None; + } + let e = 0x10 + k * 0x10; + o.u32(e, u32::from(ty))?; // device type (0x4e INA3221, 0x45 ...) + o.u8(e + 5, k as u8)?; + o.u16(e + 6, u16::from(vb.b(d + 1)?))?; // 8-bit I2C address + o.u32(e + 8, 0xc28)?; // [O] constants, unexplained + o.u32(e + 0x0c, 2)?; + mask |= 1 << k; + k += 1; + } + i += 1; + } + o.e32_header(0x2a, k as u16, mask, 2) // [O] byte 6 = 2 +} + +fn pwr_equation(vb: &Vbios<'_>, o: &mut Out<'_, S>) -> Option<()> { + let t = vb.table(0x40)?; + let volt = vb.table(0x6c)?; + let vmax = vb.u32(volt + usize::from(vb.b(volt + 1)?) + 12)?; // [O] volt device 0 max uV + let (hs, es, n) = ( + usize::from(vb.b(t + 1)?), + usize::from(vb.b(t + 2)?), + usize::from(vb.b(t + 3)?), + ); + if es < 25 || n > 32 { + return None; + } + let mut mask = 0u32; + let mut i = 0; + while i < n { + let v = t + hs + i * es; + let ty = vb.b(v)?; + if ty != 0 { + mask |= 1 << i; + let e = 0x10 + i * 0x30; + o.u32(e, u32::from(ty) - 1)?; + match ty { + 0x05 => { + o.copy(e + 6, vb, v + 1, 4)?; + o.copy(e + 0x0c, vb, v + 5, 20)?; + } + 0x06 => o.copy(e + 8, vb, v + 5, 4)?, + 0x07 => { + o.copy(e + 8, vb, v + 5, 8)?; + o.u32(e + 0x10, u32::from(vb.u16(v + 13)?))?; + o.u32(e + 0x14, u32::from(vb.u16(v + 15)?))?; + o.copy(e + 0x18, vb, v + 17, 4)?; + o.u32(e + 0x1c, vmax)?; + } + _ => {} + } + } + i += 1; + } + o.e32_header(0x26, mask.count_ones() as u16, mask, 0) +} + +fn pwr_sensor(vb: &Vbios<'_>, o: &mut Out<'_, S>) -> Option<()> { + let t = vb.table(0x28)?; + let i2c = vb.dcb_i2c_devices()?; + let (ihs, in_, ies) = ( + usize::from(vb.b(i2c + 1)?), + usize::from(vb.b(i2c + 2)?), + usize::from(vb.b(i2c + 3)?), + ); + let (hs, es, n) = ( + usize::from(vb.b(t + 1)?), + usize::from(vb.b(t + 2)?), + usize::from(vb.b(t + 3)?), + ); + if es < 13 || n > 32 { + return None; + } + let mut mask = 0u32; + let mut i = 0; + while i < n { + let v = t + hs + i * es; + let ty = vb.b(v)?; + if ty != 0 { + mask |= 1 << i; + let e = 0x20 + i * 0x3f0; + match ty { + 0x01 => { + // I2C sensor: PMU type = the I2C device's type (0x4e INA3221). + let dev = usize::from(vb.b(v + 1)?); + if dev >= in_ { + return None; + } + o.u32(e, u32::from(vb.b(i2c + ihs + dev * ies)?))?; + o.u32(e + 4, 0x1000)?; + // Three INA3221 channel records at +0x0e + 4c: u16 1 ([O] constant), + // then VBIOS bytes 5+2c / 6+2c; config word (VBIOS 11..12) at +0x1a. + // The PMU constructor (fw ~0x1165f) reads exactly these u16 offsets. + let mut c = 0; + while c < 3 { + o.u16(e + 0x0e + 4 * c, 1)?; + o.copy(e + 0x10 + 4 * c, vb, v + 5 + 2 * c, 2)?; + c += 1; + } + o.copy(e + 0x1a, vb, v + 11, 2)?; + // [O] stock 0x1000 (FXP4.12 1.0); [D] PMU firmware 0x116c8 executes + // `exit` (halts) when this u16 is zero. Source field still unknown. + o.u16(e + 0x24, 0x1000)?; + } + 0x02 => { + o.u32(e, u32::from(vb.b(v + 1)?))?; // [O] ambiguous + o.u32(e + 4, 0x1000)?; + // [O] AMBIGUOUS on one card: +0x0c = vb[2], +0x0e = vb[12], +0x10 = + // vb[10], +0x14 = 0xa00007ef (not in the VBIOS), +0x20 = 0x1000, + // +0x30 = 0xff. + o.u8(e + 0x0c, vb.b(v + 2)?)?; + o.u8(e + 0x0e, vb.b(v + 12)?)?; + o.u8(e + 0x10, vb.b(v + 10)?)?; + o.u32(e + 0x14, 0xa000_07ef)?; + o.u32(e + 0x20, 0x1000)?; + o.u8(e + 0x30, 0xff)?; + } + _ => {} + } + } + i += 1; + } + o.e32_header(0x27, n as u16, mask, 0)?; + o.u32(0x0c, 1)?; // [O] constant + o.u32(0x10, 108_000) // [A] _nv020519rm: clock domain 0x17 -> 108000 kHz +} + +/// The PWR_DEVICE table (BIT 'P' slot 0x3c) as both the SET group and the copy-out +/// region read it, so the two cannot disagree: `mask` = devices of type 1 or 2, +/// `smask` / `top` = the inputs of the type-2 devices and the highest input index + 1. +struct PwrDevices { + t: usize, + hs: usize, + es: usize, + n: usize, + mask: u32, + smask: u32, + top: u16, +} + +fn pwr_devices(vb: &Vbios<'_>) -> Option { + let t = vb.table(0x3c)?; + let (hs, es, n) = ( + usize::from(vb.b(t + 1)?), + usize::from(vb.b(t + 2)?), + usize::from(vb.b(t + 3)?), + ); + if es < 16 || n > 32 { + return None; + } + let (mut mask, mut smask, mut top) = (0u32, 0u32, 0u16); + let mut i = 0; + while i < n { + let v = t + hs + i * es; + match vb.b(v)? { + 0x01 => mask |= 1 << i, + 0x02 => { + mask |= 1 << i; + let (a, b) = (vb.b(v + 14)?, vb.b(v + 15)?); + if a >= 32 || b >= 32 { + return None; + } + smask |= 1 << a | 1 << b; + top = top.max(u16::from(a) + 1).max(u16::from(b) + 1); + } + _ => {} + } + i += 1; + } + Some(PwrDevices { + t, + hs, + es, + n, + mask, + smask, + top, + }) +} + +fn pwr_device(vb: &Vbios<'_>, o: &mut Out<'_, S>) -> Option<()> { + let d = pwr_devices(vb)?; + let mut i = 0; + while i < d.n { + let v = d.t + d.hs + i * d.es; + let ty = vb.b(v)?; + if d.mask & 1 << i != 0 { + let e = 0x30 + i * 0x150; + o.u32(e, if ty == 0x01 { 3 } else { 1 })?; + o.u32(e + 4, u32::from(vb.b(v + 1)?))?; + o.u32(e + 0x0c, u32::from(vb.u16(v + 6)?))?; + o.u32(e + 0x18, 0x1000)?; // [O] FXP4.12 1.0, source unknown + o.u32(e + 0x1c, u32::from(vb.b(v + 10)?))?; + o.u8(e + 0x30, vb.b(v + 14)?)?; + o.u8(e + 0x31, vb.b(v + 15)?)?; + if ty == 0x02 { + o.u32(e + 0x20, 3)?; // [O] unexplained + } + } + i += 1; + } + o.e32_header(0x28, 8, d.mask, 0)?; // [O] slot count 8 although the table has 20 + // Header extras: +0x18 device count, +0x1c device mask (derived); +0x0c = 2, + // +0x12 = 100, +0x14 = 1 and five 0xff (named-device indices, unset) are [O]. + o.u32(0x0c, 2)?; + o.u16(0x12, 100)?; + o.u32(0x14, 1)?; + o.u32(0x18, d.mask.count_ones())?; + o.u32(0x1c, d.mask)?; + let mut k = 0; + while k < 5 { + o.u8(0x20 + k, 0xff)?; + k += 1; + } + // Sub-group after the 32 device slots: the inputs of each type-2 (derived) device, + // bytes 14 / 15 weighted -1.0 / +1.0 (FXP4.12). [O] one card; [D] PMU firmware + // 0x17a0f halts when this header's type byte does not match. + let sub = 0x30 + 32 * 0x150; + let mut i = 0; + while i < d.n { + let v = d.t + d.hs + i * d.es; + if vb.b(v)? == 0x02 { + let (a, b) = (usize::from(vb.b(v + 14)?), usize::from(vb.b(v + 15)?)); + o.u32(sub + 0x10 + a * 0x40 + 4, 1)?; + o.u32(sub + 0x10 + a * 0x40 + 8, 0xffff_f000)?; + o.u32(sub + 0x10 + b * 0x40 + 8, 0x1000)?; + } + i += 1; + } + o.u32(sub, 0x01 | 0xff << 8 | 0xff << 16)?; + o.u16(sub + 4, d.top)?; // [O] count = highest index + 1 + o.u32(sub + 8, d.smask) +} + +fn pwr_policy(vb: &Vbios<'_>, o: &mut Out<'_, S>) -> Option<()> { + let t = vb.table(0x2c)?; + let (hs, es, n) = ( + usize::from(vb.b(t + 1)?), + usize::from(vb.b(t + 2)?), + usize::from(vb.b(t + 3)?), + ); + if es < 42 || n > 32 { + return None; + } + let mut mask = 0u32; + let mut i = 0; + while i < n { + let v = t + hs + i * es; + let ty = vb.b(v)?; + let (pmu_type, b5) = match ty { + 0x0a => (0x0b, 3), + 0x04 => (0x03, 1), + _ => { + i += 1; + continue; + } + }; + mask |= 1 << i; + let e = 0xa0 + i * 0x1e0; + o.u32(e, pmu_type)?; + o.u8(e + 4, vb.b(v + 1)?)?; + o.u8(e + 5, b5)?; + o.u8(e + 7, vb.b(v + 41)?)?; + o.copy(e + 8, vb, v + 2, 12)?; // min / rated / max limit (mW) + o.u32(e + 0x14, 0xffff_ffff)?; + o.u32(e + 0x18, 0xffff_ffff)?; + o.u32(e + 0x1c, 0x100)?; + o.u32(e + 0x20, vb.u32(v + 6)?)?; + o.u32(e + 0x24, vb.u32(v + 10)?)?; + o.u32(e + 0x28, 0xfe)?; + o.u32(e + 0x2c, vb.u32(v + 10)?)?; + o.u32(e + 0x68, 0x100)?; + o.u32(e + 0x6c, 0xffff_ffff)?; + o.u32(e + 0x74, 0xfe)?; + o.u32(e + 0x78, 0xffff_ffff)?; + if ty == 0x0a { + o.u8(e + 0xd2, vb.b(v + 21)?)?; + o.u8(e + 0xd5, vb.b(v + 18)?)?; + o.u8(e + 0xd7, vb.b(v + 15)?)?; + o.copy(e + 0xd8, vb, v + 16, 2)?; + o.u32(e + 0xe4, 0x94)?; // [O] + o.u16(e + 0xe8, 1)?; + o.u16(e + 0xea, 0xffff)?; + } else { + o.u8(e + 0xc9, 1)?; + o.u8(e + 0xca, vb.b(v + 16)?)?; + } + i += 1; + } + o.e32_header(0x29, 16, mask, 0)?; + // Header extras. Derived: +0x24/+0x26 = VBIOS header u16s at 4/6; +0x28 mask of + // type-0x0a policies, split by entry byte 34 into +0x2c (0) / +0x30 (1); +0x34 mask + // of type-0x04 policies. [O] AMBIGUOUS on one card: +0x0c (= hdr[0]), +0x0d/+0x0e + // = 1, +0x10 (= hdr[0x1e]), the 0xff array +0x11..+0x23 with +0x12 = hdr[0x0a] and + // +0x15 = hdr[9] (0x0f is also hdr[0x1f]), +0x4c / +0x88 = 0xff, +0x58 = 1. + if hs < 0x1f { + return None; + } + let (mut m0a, mut m0a0, mut m0a1, mut m04) = (0u32, 0u32, 0u32, 0u32); + let mut i = 0; + while i < n { + let v = t + hs + i * es; + match vb.b(v)? { + 0x0a => { + m0a |= 1 << i; + if vb.b(v + 34)? != 0 { + m0a1 |= 1 << i; + } else { + m0a0 |= 1 << i; + } + } + 0x04 => m04 |= 1 << i, + _ => {} + } + i += 1; + } + o.u8(0x0c, vb.b(t)?)?; + o.u8(0x0d, 1)?; + o.u8(0x0e, 1)?; + o.u8(0x10, vb.b(t + 0x1e)?)?; + let mut k = 0x11; + while k < 0x24 { + o.u8(k, 0xff)?; + k += 1; + } + o.u8(0x12, vb.b(t + 0x0a)?)?; + o.u8(0x15, vb.b(t + 9)?)?; + o.copy(0x24, vb, t + 4, 4)?; + o.u32(0x28, m0a)?; + o.u32(0x2c, m0a0)?; + o.u32(0x30, m0a1)?; + o.u32(0x34, m04)?; + o.u8(0x4c, 0xff)?; + o.u8(0x58, 1)?; + o.u8(0x88, 0xff)?; + // Sub-group 1 after the 32 slots: BIT 'P' slot 0x4c (5-byte entries: type, u16 + // weight FXP8.8 -> FXP4.12). Sub-group 2: slot 0x44 (count only; empty here). [O] + let sub = 0xa0 + 32 * 0x1e0; + let rel = vb.table(0x4c)?; + let (rhs, res, rn) = ( + usize::from(vb.b(rel + 1)?), + usize::from(vb.b(rel + 2)?), + usize::from(vb.b(rel + 3)?), + ); + if res < 3 || rn > 32 { + return None; + } + let mut i = 0; + while i < rn { + let r = rel + rhs + i * res; + o.u32(sub + 0x10 + i * 0x30 + 4, u32::from(vb.b(r)?))?; + o.u32(sub + 0x10 + i * 0x30 + 8, u32::from(vb.u16(r + 1)?) << 4)?; + i += 1; + } + o.u32(sub, 0x01 | 0xff << 8 | 0xff << 16)?; + o.u16(sub + 4, rn as u16)?; + o.u32(sub + 8, if rn == 32 { u32::MAX } else { (1u32 << rn) - 1 })?; + let sub2 = sub + 0x10 + 32 * 0x30; + let empty = vb.table(0x44)?; + o.u32(sub2, 0x01 | 0xff << 8 | 0xff << 16)?; + o.u16(sub2 + 4, u16::from(vb.b(empty + 3)?)) // [O] count only +} + +/// The PWR_DEVICE status region stock rewrites before each power copy-out: an E32 header +/// (class 0x28) and an empty sub-group header; the PMU fills the per-device records +/// (power mW at +0x1c, current mA +0x20, voltage uV +0x24 for device 0). [O] +pub const COPY_OUT: Group = Group { + class: 0x28, + surface: 0x3_8690, + region: 0xe20, +}; + +/// Index of the copy-out in [`request_len`] / [`request_byte`] (0..=8 are the SETs). +pub const COPY_OUT_CMD: usize = 9; + +/// Largest request [`request_len`] returns. +pub const REQUEST_MAX: usize = 0x434; + +/// [O] Request length per command in stock's stream (`GROUPS` order, then the copy-out). +/// Eight are 0x14 + the group's entry stride (0x420, 0x110, 0x1e0, 0x10, 0x30, 0x3f0, +/// 0x150, 0x1e0) and the copy-out is 0x14 + the 0x60 status stride; VFE equations (0x1a, +/// stride 0x90) are the exception at 0x124, so the sizes are kept as recorded. +const REQUEST_LEN: [u16; 10] = [ + 0x434, 0x124, 0x1f4, 0x124, 0x24, 0x44, 0x404, 0x164, 0x1f4, 0x74, +]; + +/// Length of request `cmd` (0..=8: the SET for `GROUPS[cmd]`; [`COPY_OUT_CMD`]: the +/// copy-out), or `None` past the end. +pub fn request_len(cmd: usize) -> Option { + REQUEST_LEN.get(cmd).map(|&n| usize::from(n)) +} + +/// Byte `i` of request `cmd`. Stock's requests (all on the low-priority queue) are zero +/// except: [1] unit (0x13 PERF for classes 0x19..0x1c, 0x18 PMGR otherwise), [4] 0x1b +/// ([O] constant, meaning unknown), [0x10] class, [0x11] 1 for the copy-out (bCopyOut). +pub fn request_byte(cmd: usize, i: usize) -> u8 { + let (class, copy_out) = match cmd { + COPY_OUT_CMD => (COPY_OUT.class, true), + c if c < GROUPS.len() => (GROUPS[c].class, false), + _ => return 0, + }; + match i { + 1 if (0x19..=0x1c).contains(&class) => 0x13, + 1 => 0x18, + 4 => 0x1b, + 0x10 => class, + 0x11 => u8::from(copy_out), + _ => 0, + } +} + +/// What the copy-out region needs from the VBIOS: the PWR_DEVICE mask (devices of type +/// 1 or 2) and the sub-group count (highest input index of a type-2 device + 1), the same +/// values the SET group (command 8) carries. `None` if the table is not understood. +pub fn pwr_device_status_shape(vb: &Vbios<'_>) -> Option<(u32, u16)> { + let d = pwr_devices(vb)?; + Some((d.mask, d.top)) +} + +/// Byte `i` of the copy-out region for a [`pwr_device_status_shape`]: header +/// `01 ff 28 00`, slots 8 ([O], as the SET group), mask; at 0xc10 (after 32 status +/// slots of 0x60) the sub-group header `01 ff ff 00`, count, mask 0; zero elsewhere. +pub fn copy_out_byte(mask: u32, count: u16, i: usize) -> u8 { + const SUB: usize = 0x10 + 32 * 0x60; + let m = mask.to_le_bytes(); + let c = count.to_le_bytes(); + match i { + 0 | SUB => 0x01, + 1 => 0xff, + 2 => COPY_OUT.class, + 4 => 8, + 8..=11 => m[i - 8], + _ if i == SUB + 1 || i == SUB + 2 => 0xff, + _ if i == SUB + 4 || i == SUB + 5 => c[i - SUB - 4], + _ => 0, + } +} + +#[cfg(test)] +#[path = "gv100_pmu_tables_tests.rs"] +mod tests; diff --git a/src/nvidia/src/gpu/gv100_pmu_tables_tests.rs b/src/nvidia/src/gpu/gv100_pmu_tables_tests.rs new file mode 100644 index 00000000..4c6243bc --- /dev/null +++ b/src/nvidia/src/gpu/gv100_pmu_tables_tests.rs @@ -0,0 +1,271 @@ +use super::*; +extern crate std; +use std::vec; +use std::vec::Vec; + +/// Builds every group into a buffer laid out like the super-surface. +fn build(vb: &Vbios<'_>) -> Vec<(usize, Vec)> { + let mut out = Vec::new(); + for (i, g) in GROUPS.iter().enumerate() { + let mut buf = vec![0u8; g.region as usize]; + emit(vb, i, &mut |at, byte| buf[at as usize] = byte).expect("group builds"); + out.push((g.surface as usize, buf)); + } + out +} + +/// Bytes that differ from stock on the reference card: none since 3 Dec (all nine +/// groups byte-identical; several fields are [O] constants, see the module). +const UNRESOLVED_BYTES: usize = 0; + +/// Needs the reference card's VBIOS and stock super-surface (not in the repo; stock bytes +/// are not redistributed): NV_RS_V100_VBIOS= NV_RS_V100_SURF=, +/// the surface being the super-surface read back after stock's ninth group SET. +/// The legacy image is 0xe400 bytes and the extended image starts at 0x1fc00 there. +#[test] +fn matches_reference_stock_surface_when_fixture_present() { + let (Ok(rom), Ok(surf)) = ( + std::env::var("NV_RS_V100_VBIOS"), + std::env::var("NV_RS_V100_SURF"), + ) else { + return; + }; + let rom = std::fs::read(rom).unwrap(); + let surf = std::fs::read(surf).unwrap(); + let bit = (0..rom.len() - 4) + .find(|&i| &rom[i..i + 4] == b"BIT\0") + .unwrap() as u32 + - 2; + let vb = Vbios::new(&rom, bit, 0xe400, 0x1fc00 - 0xe400).expect("BIT 'P' found"); + let mut differ = 0; + for ((surface, buf), g) in build(&vb).iter().zip(GROUPS.iter()) { + let d = buf + .iter() + .zip(&surf[*surface..*surface + buf.len()]) + .filter(|(a, b)| a != b) + .count(); + std::println!("class {:02x}: {} bytes differ of {}", g.class, d, buf.len()); + differ += d; + } + assert_eq!(differ, UNRESOLVED_BYTES); +} + +#[test] +fn refuses_an_empty_image_without_panicking() { + let rom = [0u8; 64]; + assert!(Vbios::new(&rom, 0, 0, 0).is_none()); +} + +/// A pseudo-random VBIOS whose BIT 'P' slots (and the DCB I2C device table) point at +/// in-ROM tables with small headers, so the serializers run on junk entries. Bytes lean +/// towards small values so entry types hit the cases the serializers handle. +fn random_rom(seed: u64) -> Vec { + const LEN: usize = 0x4000; + let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + let mut next = move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x + }; + let mut rom = vec![0u8; LEN]; + for b in rom.iter_mut() { + let r = next(); + *b = if r & 1 == 0 { + (r >> 8) as u8 % 8 + } else { + (r >> 8) as u8 + }; + } + // BIT header at 0 (12 bytes, 6-byte tokens, one token): 'P' v2, 0x70 bytes at 0x40. + rom[0..12].copy_from_slice(&[0xff, 0xb8, b'B', b'I', b'T', 0, 0, 0, 12, 6, 1, 0]); + rom[12..18].copy_from_slice(&[0x50, 2, 0x70, 0, 0x40, 0]); + // DCB at 0x20; its I2C device table pointer (+0x12) is the eleventh table below. + rom[0x36..0x38].copy_from_slice(&0x20u16.to_le_bytes()); + let slots = [0x00, 0x20, 0x28, 0x2c, 0x38, 0x3c, 0x40, 0x44, 0x4c, 0x6c]; + let mut k = 0; + while k <= slots.len() { + let at = 0x100 + k * 0x600; + if k < slots.len() { + let p = 0x40 + slots[k]; + rom[p..p + 4].copy_from_slice(&(at as u32).to_le_bytes()); + } else { + rom[0x32..0x34].copy_from_slice(&(at as u16).to_le_bytes()); + } + // Header: size 6..=9, then sizes and counts that pass the guards most of the time. + let r = next(); + rom[at + 1] = 6 + (r % 4) as u8; + let mut j = 2; + while j < 6 { + rom[at + j] = (next() % 48) as u8; + j += 1; + } + k += 1; + } + rom +} + +/// Junk VBIOS tables: every group is refused or written inside its region, never a +/// panic (an overflowing offset or shift panics here, as tests build with overflow +/// checks), and every serializer really writes on some inputs, so the check is live. +#[test] +fn writes_stay_inside_each_region() { + let mut written = [0usize; GROUPS.len()]; + let mut seed = 1u64; + while seed <= 4000 { + let rom = random_rom(seed); + let vb = Vbios::new(&rom, 0, rom.len() as u32, 0).expect("token found"); + for (i, g) in GROUPS.iter().enumerate() { + let mut n = 0usize; + let _ = emit(&vb, i, &mut |at, _| { + assert!(at < g.region, "class {:02x} wrote {at:#x}", g.class); + n += 1; + }); + written[i] += n; + } + // The copy-out shape and the SET group come from one reading of the table. + if let Some((mask, _)) = pwr_device_status_shape(&vb) { + let mut hdr = [0u8; 12]; + let idx = GROUPS.iter().position(|g| g.class == 0x28).unwrap(); + if emit(&vb, idx, &mut |at, b| { + if (at as usize) < hdr.len() { + hdr[at as usize] = b; + } + }) + .is_some() + { + assert_eq!(hdr[8..12], mask.to_le_bytes()); + } + } + seed += 1; + } + for (g, n) in GROUPS.iter().zip(written) { + assert!(n > 0, "class {:02x} never wrote a byte", g.class); + } +} + +/// Stock's twelve recorded requests (the nine SETs and three PWR_DEVICE copy-outs) have +/// these non-zero bytes and lengths, nothing else. [O] +#[test] +fn requests_match_the_recorded_stock_requests() { + let stock: [(usize, u8, u8, u8); 10] = [ + (0x434, 0x13, 0x1c, 0), + (0x124, 0x13, 0x1b, 0), + (0x1f4, 0x13, 0x19, 0), + (0x124, 0x13, 0x1a, 0), + (0x24, 0x18, 0x2a, 0), + (0x44, 0x18, 0x26, 0), + (0x404, 0x18, 0x27, 0), + (0x164, 0x18, 0x28, 0), + (0x1f4, 0x18, 0x29, 0), + (0x74, 0x18, 0x28, 1), + ]; + for (cmd, &(len, unit, class, copy_out)) in stock.iter().enumerate() { + assert_eq!(request_len(cmd), Some(len), "cmd {cmd}"); + assert!(len <= REQUEST_MAX); + for i in 0..len { + let want = match i { + 1 => unit, + 4 => 0x1b, + 0x10 => class, + 0x11 => copy_out, + _ => 0, + }; + assert_eq!(request_byte(cmd, i), want, "cmd {cmd} byte {i:#x}"); + } + } + assert_eq!(request_len(COPY_OUT_CMD + 1), None); +} + +/// Stock's copy-out region on the reference card has exactly nine non-zero bytes. [O] +#[test] +fn copy_out_region_matches_the_recorded_stock_span() { + let mut nonzero = Vec::new(); + for i in 0..COPY_OUT.region as usize { + let b = copy_out_byte(0x83, 7, i); + if b != 0 { + nonzero.push((i, b)); + } + } + assert_eq!( + nonzero, + vec![ + (0, 0x01), + (1, 0xff), + (2, 0x28), + (4, 0x08), + (8, 0x83), + (0xc10, 0x01), + (0xc11, 0xff), + (0xc12, 0xff), + (0xc14, 0x07), + ] + ); +} + +#[test] +fn status_shape_matches_reference_card_when_fixture_present() { + let Ok(rom) = std::env::var("NV_RS_V100_VBIOS") else { + return; + }; + let rom = std::fs::read(rom).unwrap(); + let bit = (0..rom.len() - 4) + .find(|&i| &rom[i..i + 4] == b"BIT\0") + .unwrap() as u32 + - 2; + let vb = Vbios::new(&rom, bit, 0xe400, 0x1fc00 - 0xe400).unwrap(); + assert_eq!(pwr_device_status_shape(&vb), Some((0x83, 7))); +} + +/// A BIT header at 0 with one 'P' v2 token whose data (at 0x40) is `p_size` bytes long. +fn rom_with_p(p_size: u16) -> Vec { + let mut rom = vec![0u8; 0x400]; + rom[0..12].copy_from_slice(&[0xff, 0xb8, b'B', b'I', b'T', 0, 0, 0, 12, 6, 1, 0]); + let [lo, hi] = p_size.to_le_bytes(); + rom[12..18].copy_from_slice(&[0x50, 2, lo, hi, 0x40, 0]); + rom +} + +#[test] +fn table_slots_past_the_declared_p_data_are_absent() { + let mut rom = rom_with_p(4); + // Slot 0x3c holds a plausible in-ROM pointer, but the token declares 4 data bytes. + rom[0x40 + 0x3c..0x40 + 0x40].copy_from_slice(&0x100u32.to_le_bytes()); + let vb = Vbios::new(&rom, 0, 0x400, 0).expect("token found"); + assert_eq!(vb.table(0x3c), None); + assert_eq!(vb.table(0x00), Some(0)); + let mut rom = rom_with_p(0x40); + rom[0x40 + 0x3c..0x40 + 0x40].copy_from_slice(&0x100u32.to_le_bytes()); + let vb = Vbios::new(&rom, 0, 0x400, 0).expect("token found"); + assert_eq!(vb.table(0x3c), Some(0x100)); +} + +#[test] +fn sparse_type_tables_are_refused() { + let t = |types: &'static [u8]| move |k: usize| types.get(k).copied(); + assert_eq!(contiguous_count(3, t(&[1, 1, 0])), Some(2)); + assert_eq!(contiguous_count(3, t(&[2, 2, 2])), Some(3)); + assert_eq!(contiguous_count(3, t(&[0, 0, 0])), Some(0)); + assert_eq!(contiguous_count(3, t(&[1, 0, 1])), None); + assert_eq!(contiguous_count(3, t(&[2, 0, 2])), None); + assert_eq!(contiguous_count(3, t(&[1, 1])), None, "short table"); +} + +#[test] +fn pstate_sub_entries_that_spill_into_the_next_record_are_refused() { + // P slot 0x00 -> pstate table at 0x100: header 6 bytes, base 3, 1 entry, sub 6 bytes. + let pstate = |sn: u8| { + let mut rom = rom_with_p(0x80); + rom[0x40..0x44].copy_from_slice(&0x100u32.to_le_bytes()); + rom[0x100..0x106].copy_from_slice(&[0x10, 6, 3, 1, 6, sn]); + rom + }; + let pstate_index = GROUPS.iter().position(|g| g.class == 0x1c).unwrap(); + for (sn, fits) in [(86u8, true), (87, false)] { + let mut rom = pstate(sn); + rom.resize(0x2000, 0); + let vb = Vbios::new(&rom, 0, 0x2000, 0).expect("token found"); + let built = emit(&vb, pstate_index, &mut |_, _| {}); + assert_eq!(built.is_some(), fits, "sn = {sn}"); + } +}