diff --git a/NOTICE.txt b/NOTICE.txt index 3eaa8c6b..c24ca645 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -10,3 +10,6 @@ The Turing GSP-RM boot ucode image in src/nvidia/src/gpu/ucode/ is derived from the MIT-licensed open-kernel source at tag 580.178.04 rather than from NVIDIA's firmware packages; its copyright and permission notice is in licenses/gsp-rm-boot-tu10x-mit.txt and is distributed with the image. +The Turing SEC2 Booter images and the generic falcon bootloader in the same +directory come from the same source tag; their notice is in +licenses/gsp-booter-tu10x-mit.txt. diff --git a/README.md b/README.md index 433664b3..cb72152a 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ Key tunable parameters: - `enable_resizable_bar=1` *(default)* — Automatically expands BAR1 to the largest supported ReBAR aperture. - `force_p2p=0x11` *(default)* — Enables PCIe P2P Read+Write (`0x211` opts into PCIe P2P Atomics). - `gsp_abi=620` *(default)* — Selects GSP-RM `620.70.06` / `620.73.04` MCTP+NVDM framing for Turing–Blackwell–Rubin (`580` for `580.178.04` compat); independent of `driver_version=580.178.04` (which sets the userspace NVML/`libcuda` version string — pass e.g. `driver_version=620.73.04` on 620 userspace hosts). -- `ga10x_gsp=1` *(default)* — Turing through Blackwell (`TU10x`/`TU11x`, `GA100`/`GA10x`, `AD10x`, `GH100`, `GB10x`/`GB20x`) GPUs boot GSP-RM `580.178.04` through `ga10x_gsp.rs` (pinned to `580.178.04` regardless of `gsp_abi`) and run the kernel side of split RM in `ga10x*.rs`; `0` leaves them to `gsp_bringup`'s path. +- `ga10x_gsp=1` *(default)* — Turing through Blackwell (`TU10x`/`TU11x`, `GA100`/`GA10x`, `AD10x`, `GH100`, `GB10x`/`GB20x`) GPUs boot GSP-RM `580.178.04` through `ga10x_gsp.rs` regardless of `gsp_abi`; with `driver_version=580.196.07` (userspace 580.196.07), TU102/TU116 and GA102-class GPUs boot GSP-RM `580.196.07` instead and run the kernel side of split RM in `ga10x*.rs`; `0` leaves them to `gsp_bringup`'s path. - `ga10x_events=1` *(default)* — RM events from the GR / copy-engine non-stall interrupts on GA10x and GV100, so blocking-sync waits wake at once instead of on libcuda's 100 ms timer. - `system_memory_pool_retain_mb=0` *(default)* — Trims cached system-memory pages on client close so `MemAvailable` stays accurate. diff --git a/licenses/gsp-booter-tu10x-mit.txt b/licenses/gsp-booter-tu10x-mit.txt new file mode 100644 index 00000000..a37bc412 --- /dev/null +++ b/licenses/gsp-booter-tu10x-mit.txt @@ -0,0 +1,34 @@ +SPDX-FileCopyrightText: Copyright (c) 2016-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: MIT + +This notice covers five Turing falcon ucode images in src/nvidia/src/gpu/ucode/, taken from the MIT-licensed +open-kernel source at tag 580.178.04 (src/nvidia/generated/, stored there deflate-compressed) by +tools/extract_gsp_bindata.py: + - booter_load_tu102.bin and booter_unload_tu102.bin: the SEC2 Booter Load / Unload ucode for TU102, TU104 and + TU106 with their production signatures, g_bindata_kgspGetBinArchiveBooter{Load,Unload}Ucode_TU102.c; + - booter_load_tu116.bin and booter_unload_tu116.bin: the same for TU116 and TU117, + g_bindata_kgspGetBinArchiveBooter{Load,Unload}Ucode_TU116.c; + all four in the nvfw_bin_hdr + nvfw_hs_header_v2 + nvfw_hs_load_header_v2 layout nouveau and linux-firmware use; + - falcon_bl_tu102.bin: the 768-byte generic falcon bootloader, g_bindata_ksec2GetBinArchiveBlUcode_TU102.c + (kernel/inc/sec2/bin/g_sec2_bl_gp10x.h). +The same four Booters of tag 580.196.07 are in src/nvidia/src/gpu/ucode/580.196.07/, from the same files at that tag +(tools/extract_gsp_bindata.py --release 580.196.07). +They are not NVIDIA proprietary firmware and are not taken from gsp_tu10x.bin. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/licenses/gsp-rm-boot-ga102-mit.txt b/licenses/gsp-rm-boot-ga102-mit.txt index d2538dee..84151d11 100644 --- a/licenses/gsp-rm-boot-ga102-mit.txt +++ b/licenses/gsp-rm-boot-ga102-mit.txt @@ -8,6 +8,8 @@ open-kernel source at tag 580.178.04 (src/nvidia/generated/, stored there deflat - booter_load_ga102.bin and booter_unload_ga102.bin: the SEC2 Booter Load / Unload ucode with their production signatures, g_bindata_kgspGetBinArchiveBooterLoadUcode_GA102.c and g_bindata_kgspGetBinArchiveBooterUnloadUcode_GA102.c, in the nvfw_bin_hdr + nvfw_hs_header_v2 + nvfw_hs_load_header_v2 layout nouveau and linux-firmware use. +The GA102 Booter Load / Unload of tag 580.196.07 are in src/nvidia/src/gpu/ucode/580.196.07/, from the same files at that +tag (tools/extract_gsp_bindata.py --release 580.196.07). They are not NVIDIA proprietary firmware and are not taken from gsp_ga10x.bin. Permission is hereby granted, free of charge, to any person obtaining a diff --git a/src/nvidia/kernel/ga10x.rs b/src/nvidia/kernel/ga10x.rs index 69fe4464..cfa0fc0e 100644 --- a/src/nvidia/kernel/ga10x.rs +++ b/src/nvidia/kernel/ga10x.rs @@ -406,6 +406,27 @@ impl Ga10xGpu { ); Ok(()) } + /// Turing: `NV2080_CTRL_CMD_CE_UPDATE_CLASS_DB` (0x20802a06, `stubbedCeMask` u32) on GSP-RM's internal + /// subdevice, as NVIDIA's kernel side does when it loads its copy engines (`kceStateLoad_GP100` -> + /// `kceTopLevelPceLceMappingsUpdate_IMPL` -> `kceUpdateClassDB_KERNEL`, `kernel_ce.c:618`): the copy engines + /// without a physical engine are not exposed. A refusal leaves every copy engine of `engineCaps` exposed. + #[inline(never)] + fn ce_class_db(&mut self) { + let mut p = [0u8; 4]; + let (c, s) = (self.mem.info.client, self.mem.info.subdevice); + let r = self.rm_control(c, s, 0x2080_2a06, &mut p); + if r == Ok(0) { + self.mem.ce_stubbed = u32::from_le_bytes(p); + } + ga10x_gsp::note( + self.pci, + b"tu: CE class DB (stubbed CE mask, status, error), engineCaps[0]\0", + u64::from(self.mem.ce_stubbed), + u64::from(r.unwrap_or(u32::MAX)), + r.err().unwrap_or(0) as u64, + u64::from(self.mem.info.engine_caps[0]), + ); + } #[inline(never)] fn boot_rm(&mut self) -> Result<(), i32> { let info = self.static_info()?; @@ -414,6 +435,8 @@ impl Ga10xGpu { return Err(ENODEV); } self.mem.init(self.pci, info, pci.bar[1], pci.bar_len[1])?; + self.mem.turing = self.boot_id().arch_family() + == Some(nv_rs_core::gpu::chip_arch::ArchFamily::Turing); ga10x_gsp::note( self.pci, b"heap split: user video memory to, kernel-side from, to\0", @@ -427,6 +450,28 @@ impl Ga10xGpu { self.gr_buffer_info()?; self.device_info()?; self.init_telemetry(); + if self.mem.turing { + self.ce_class_db(); + let valid = self + .runlist_valid + .iter() + .enumerate() + .fold(0u64, |m, (i, &v)| m | u64::from(v) << i); + // a copy engine without a runlist has no work-submit token: not offered to clients + self.mem.ce_stubbed = nv_rs_core::gpu::gsp_split_turing::stubbed_without_runlist( + self.mem.ce_stubbed, + &self.mem.info.engine_caps, + valid, + ); + ga10x_gsp::note( + self.pci, + b"tu: runlists COPY0, COPY1, COPY4; copy engines not exposed (mask)\0", + u64::from(self.runlist[9]), + u64::from(self.runlist[0xa]), + u64::from(self.runlist[0xd]), + u64::from(self.mem.ce_stubbed), + ); + } // events are an optimization (libcuda falls back to its own timeouts): a failure only turns them off if let Err(e) = crate::ga10x_events::setup(self) { ga10x_gsp::error(self.pci, b"events off (error)\0", e as u64, 0, 0, 0); diff --git a/src/nvidia/kernel/ga10x_gsp.rs b/src/nvidia/kernel/ga10x_gsp.rs index 9a725a4e..a7957159 100644 --- a/src/nvidia/kernel/ga10x_gsp.rs +++ b/src/nvidia/kernel/ga10x_gsp.rs @@ -8,6 +8,11 @@ //! GSP-RM then runs the CPU sequencer through us and sends `GSP_INIT_DONE`. Unload: `UNLOADING_GUEST_DRIVER`, //! FWSEC-SB, Booter Unload, then both falcons are reset before any system memory GSP-RM or the falcons used is freed. //! +//! Turing (TU102..TU117) takes the same path with the TU102 HALs of 580.178.04 (`kgspBootstrap_TU102` is shared): +//! the falcons reset through their ENGINE register (`kflcnReset_TU102`), FWSEC (`FALCON_UCODE_DESC_V2`) runs on the +//! GSP falcon through the generic bootloader and Booter on SEC2 is written into IMEM / DMEM by the CPU +//! (`kgspExecuteHsFalcon_TU102`), and GSP-RM gets the LibOS2 heap and logs. +//! //! The parsing and layouts are in `nv_rs_core::gpu::ga10x_gsp`; this file holds the register sequences and the //! memory. Every caller after boot holds the RM API node's lock (rmapi_node.c), which serializes the RPCs. use core::ffi::c_void; @@ -16,6 +21,7 @@ use core::ptr::{self, NonNull}; use crate::dma::LinuxDma; use nv_rs_core::dma::{Backend, Backing, DeviceMapping}; use nv_rs_core::gpu::ga10x_gsp::{self as fw, function, GSP_PAGE}; +use nv_rs_core::gpu::gsp_boot::GspFirmwareChipFamily; use nv_rs_core::gpu::gsp_image::GspFirmware; use nv_rs_core::gpu::gsp_sequencer::Command; @@ -91,7 +97,6 @@ const GSP: u32 = 0x11_0000; const SEC2: u32 = 0x84_0000; /// falcon2 / RISC-V registers: falcon base + 0x1000. const RV: u32 = 0x1000; -const GSP_RM_VERSION: &str = "580.178.04"; const QUEUE_BYTES: u64 = 0x4_0000; const IMAGE_RUN: u64 = 0x20_0000; const MAX_IMAGE_RUNS: usize = 48; @@ -355,7 +360,7 @@ struct Hs { } use nv_rs_core::gpu::gsp_ucode::{ - BOOTER_LOAD_GA102 as BOOTER_LOAD, BOOTER_UNLOAD_GA102 as BOOTER_UNLOAD, + booters_for, FALCON_BL_CODE_SIZE, FALCON_BL_START_TAG, FALCON_BL_TU102, }; const HS_NAMES: [&[u8]; 4] = [ @@ -377,6 +382,11 @@ fn rom_slice(p: *mut u8) -> &'static [u8] { pub(crate) struct Ga10xGsp { pub pci: *mut c_void, pub regs: Regs, + /// The GSP-RM release booted: the firmware file, its `.fwversion` and the Booters (all-zero = 580.178.04). + release: nv_rs_core::gpu::gsp_image::GspFwRelease, + fwsec2: fw::FwsecV2, + /// A Turing boot has started FWSEC-FRTS: from here on the falcons may hold our addresses and WPR2 may be ours. + frts_started: bool, dma: LinuxDma, dma_open: bool, bus_master: bool, @@ -544,6 +554,168 @@ impl Ga10xGsp { Ok(()) } + fn turing(&self) -> bool { + fw::is_turing(self.fw_family) + } + + // ---- Turing falcons (580.178.04 kernel_falcon_tu102.c, kernel_gsp_falcon_tu102.c, kernel_gsp_booter_tu102.c) ---- + + /// `kflcnReset_TU102`: `k{gsp,sec2}ResetHw_TU102` sets and clears `NV_P{GSP,SEC}_FALCON_ENGINE_RESET` with 10 reads + /// after each write, `kflcnWaitForResetToFinish_TU102` waits for DMACTL's DMEM / IMEM scrubbing, and + /// `FALCON_RM` gets `PMC_BOOT_0`. Turing has no core select: this is also `kflcnResetIntoRiscv_TU102`. + #[inline(never)] + fn tu_reset(&self, b: u32) -> Result<(), i32> { + for v in [1, 0] { + self.fmask(b, 0x3c0, 1, v); + for _ in 0..10 { + let _ = self.frd(b, 0x3c0); + } + } + if !poll_busy(20_000, || self.frd(b, 0x10c) & 6 == 0) { + return Err(ETIMEDOUT); + } + self.fwr(b, 0x084, self.rd(0)); + Ok(()) + } + + /// `kflcnReset_HAL` of this GPU. + fn reset(&self, b: u32) -> Result<(), i32> { + if self.turing() { + self.tu_reset(b) + } else { + self.flcn_reset(b) + } + } + + /// `kflcnDisableCtxReq_TU102`: `FBIF_CTL.ALLOW_PHYS_NO_CTX`, `DMACTL` 0. + fn disable_ctx_req(&self, b: u32) { + self.fmask(b, 0x624, 0x80, 0x80); + self.fwr(b, 0x10c, 0); + } + + /// `s_imemCopyTo_TU102`: `src` into IMEM at `dst` through port 0 (auto-increment), each 256-byte block tagged from + /// `tag >> 8` on. + fn pio_imem(&self, b: u32, dst: u32, src: &[u8], secure: bool, tag: u32) -> Result<(), i32> { + if dst & 0xff != 0 || src.len() & 3 != 0 { + return Err(EINVAL); + } + self.fwr(b, 0x180, (dst & 0xfffc) | 1 << 24 | u32::from(secure) << 28); + let mut tag = tag >> 8; + for (i, w) in src.chunks_exact(4).enumerate() { + if i & 63 == 0 { + self.fwr(b, 0x188, tag & 0xffff); + tag += 1; + } + self.fwr(b, 0x184, u32::from_le_bytes([w[0], w[1], w[2], w[3]])); + } + Ok(()) + } + + /// `s_dmemCopyTo_TU102`: `src` into DMEM at `dst` through port 0 (auto-increment). + fn pio_dmem(&self, b: u32, dst: u32, src: &[u8]) -> Result<(), i32> { + if dst & 3 != 0 || src.len() & 3 != 0 { + return Err(EINVAL); + } + self.fwr(b, 0x1c0, (dst & 0xfffc) | 1 << 24); + for w in src.chunks_exact(4) { + self.fwr(b, 0x1c4, u32::from_le_bytes([w[0], w[1], w[2], w[3]])); + } + Ok(()) + } + + /// The end of `kgspExecuteHsFalcon_TU102`: the mailboxes if given, `kflcnStartCpu_TU102`, then wait for HALTED. + #[inline(never)] + fn tu_start(&self, b: u32, which: u8, mbox: Option<(u32, u32)>) -> Result<(u32, u32), i32> { + if let Some((m0, m1)) = mbox { + self.fwr(b, 0x040, m0); + self.fwr(b, 0x044, m1); + } + if self.frd(b, 0x100) & 0x40 != 0 { + self.fwr(b, 0x130, 2); + } else { + self.fwr(b, 0x100, 2); + } + let halted = poll_sleep(2_000_000, || self.frd(b, 0x100) & 0x10 != 0); + let (m0, m1) = (self.frd(b, 0x040), self.frd(b, 0x044)); + self.note( + HS_NAMES[usize::from(which.min(3))], + u64::from(halted), + u64::from(m0), + u64::from(m1), + u64::from(b), + ); + if !halted { + return Err(ETIMEDOUT); + } + Ok((m0, m1)) + } + + /// Booter Load (`which` 0) or Unload (1) on SEC2 (`kgspExecuteBooterLoad_TU102`, + /// `kgspExecuteBooterUnloadIfNeeded_TU102`): SEC2 reset, the image with its signature in place + /// (`s_patchBooterUcodeSignature`; the SEC2 fuse version reads 0 on Turing), then `s_prepareHsFalconDirect`: + /// non-secure code at IMEM 0, secure code after it, data at DMEM 0, BOOTVEC 0. + #[inline(never)] + fn tu_booter(&mut self, which: u8, mbox0: u32, mbox1: u32) -> Result<(u32, u32), i32> { + let (load, unload) = booters_for(self.fw_family, self.release).ok_or(EOPNOTSUPP)?; + let blob = if which == 1 { unload } else { load }; + let bt = fw::parse_booter(blob).map_err(fw_errno)?; + let u = bt.ucode; + let len = u.image_len as usize; + if len > fw::MAX_ELEMENT_BYTES { + return Err(E2BIG); + } + let img = unsafe { core::slice::from_raw_parts_mut(self.elem, len) }; + fw::copy(img, fw::span(blob, bt.data_off as usize, len).map_err(fw_errno)?); + let idx = u.signature_index(0).map_err(fw_errno)?; + let sig = fw::span( + blob, + (bt.sigs_off + idx * u.sig_size) as usize, + u.sig_size as usize, + ) + .map_err(fw_errno)?; + fw::copy( + fw::span_mut(img, u.sig_base_img as usize, sig.len()).map_err(fw_errno)?, + sig, + ); + let part = |o: u32, n: u32| fw::span(img, o as usize, n as usize).map_err(fw_errno); + self.tu_reset(SEC2)?; + self.disable_ctx_req(SEC2); + self.pio_imem(SEC2, 0, part(bt.ns_off, bt.ns_size)?, false, bt.ns_off)?; + let sec_at = fw::align_up(u64::from(bt.ns_size), 256) as u32; + let sec = part(u.imem_base_img, u.imem_size)?; + self.pio_imem(SEC2, sec_at, sec, true, u.imem_base_img)?; + self.pio_dmem(SEC2, 0, part(u.dmem_base_img, u.dmem_size)?)?; + self.fwr(SEC2, 0x104, 0); + self.tu_start(SEC2, which, Some((mbox0, mbox1))) + } + + /// FWSEC (`which` 2 SB, 3 FRTS) on the GSP falcon through the generic bootloader (`kgspExecuteFwsec_TU102`, + /// `s_prepareHsFalconWithLoader`): GSP reset, its DMEM descriptor at DMEM 0, FBIF aperture `ctxDma` on coherent + /// system memory, the bootloader's code at the top of IMEM, BOOTVEC at its start tag; no mailboxes. + #[inline(never)] + fn tu_fwsec(&mut self, which: u8) -> Result<(u32, u32), i32> { + let f = self.fwsec2; + let code = self.hs(which).buf.addr(); + let mut desc = [0u8; fw::BL_DMEM_DESC_BYTES]; + fw::write_bl_dmem_desc(&mut desc, code, code + u64::from(f.code_bytes()), &f) + .map_err(fw_errno)?; + self.tu_reset(GSP)?; + self.disable_ctx_req(GSP); + // FBIF_TRANSCFG(ctxDma): TARGET COHERENT_SYSMEM, MEM_TYPE PHYSICAL + self.fmask(GSP, 0x600 + 4 * fw::BL_CTX_DMA, 0x7, 0x5); + self.pio_dmem(GSP, 0, &desc)?; + let blocks = self.frd(GSP, 0x108) & 0x1ff; + let dst = blocks + .checked_sub(FALCON_BL_CODE_SIZE / 256) + .ok_or(EINVAL)? + << 8; + let tag = FALCON_BL_START_TAG << 8; + let bl = &FALCON_BL_TU102[..FALCON_BL_CODE_SIZE as usize]; + self.pio_imem(GSP, dst, bl, false, tag)?; + self.fwr(GSP, 0x104, tag); + self.tu_start(GSP, which, None) + } + /// Picks the signature for this card's fuses and writes it into the image (once). #[inline(never)] fn hs_patch(&mut self, which: u8) -> Result<(), i32> { @@ -569,10 +741,11 @@ impl Ga10xGsp { })?; let size = u.sig_size as usize; let at = sigs_off as usize + idx as usize * size; - let src: &[u8] = match sig_src { - 1 => rom_slice(self.vbios), - 2 => BOOTER_LOAD, - 3 => BOOTER_UNLOAD, + let booters = booters_for(self.fw_family, self.release); + let src: &[u8] = match (sig_src, booters) { + (1, _) => rom_slice(self.vbios), + (2, Some((load, _))) => load, + (3, Some((_, unload))) => unload, _ => return Err(EINVAL), }; let sig = fw::span(src, at, size).map_err(fw_errno)?; @@ -673,6 +846,13 @@ impl Ga10xGsp { mbox0: u32, mbox1: Option, ) -> Result<(u32, u32), i32> { + if self.turing() { + return if which < 2 { + self.tu_booter(which, mbox0, mbox1.unwrap_or(0)) + } else { + self.tu_fwsec(which) + }; + } self.hs_patch(which)?; self.hs_run(b, which, mbox0, mbox1) } @@ -714,6 +894,26 @@ impl Ga10xGsp { ); fw_errno(e) })?; + if self.turing() { + self.fwsec2 = fw::parse_fwsec_v2(rom, &self.vb).map_err(|e| { + self.error( + b"VBIOS: FWSEC V2 descriptor refused (error, desc)\0", + e as u64, + u64::from(self.vb.desc), + 0, + 0, + ); + fw_errno(e) + })?; + self.note( + b"VBIOS: image0, image 0xe0 at, FWSEC V2 desc, IMEM bytes\0", + u64::from(self.vb.image0_size), + u64::from(self.vb.imaged_addr), + u64::from(self.vb.desc), + u64::from(self.fwsec2.imem_size), + ); + return Ok(()); + } self.fwsec = fw::parse_fwsec(rom, &self.vb).map_err(|e| { self.error( b"VBIOS: FWSEC descriptor refused (error, desc)\0", @@ -800,6 +1000,62 @@ impl Ga10xGsp { r } + /// Turing FWSEC from the VBIOS in a new system-memory buffer for slot `which` (2 SB, 3 FRTS): the code + /// (`codeSizeAligned` bytes, image at `imemNsPa`), then the data (`dataSizeAligned`, image at `dmemPa`) with its DMEM + /// mapper patched for `cmd` (`s_vbiosFillFlcnUcodeFromDescV2`, `s_prepareForFwsec_TU102`). + #[inline(never)] + fn fwsec2_build(&mut self, cmd: u32, which: u8) -> Result<(), i32> { + let f = self.fwsec2; + let (code_len, data_len) = (f.code_bytes() as usize, f.data_bytes() as usize); + if data_len > fw::MAX_ELEMENT_BYTES { + return Err(E2BIG); + } + { + let (h, dma) = self.hs_and_dma(which); + h.patched = true; + h.sig_src = 0; + h.buf.alloc_into(dma, (code_len + data_len) as u64)?; + } + let r = (|| -> Result<(), i32> { + let rom = rom_slice(self.vbios); + let code = fw::span(rom, f.rom_code as usize, f.imem_size as usize).map_err(fw_errno)?; + let data = fw::span(rom, f.rom_data as usize, f.dmem_size as usize).map_err(fw_errno)?; + let dbuf = unsafe { core::slice::from_raw_parts_mut(self.elem, data_len) }; + fw::zero(dbuf); + fw::copy(&mut dbuf[f.dmem_pa as usize..], data); + let (frts_addr, frts_size) = (self.layout.frts_addr, self.layout.frts_size); + let dmem_start = f.dmem_pa as usize; + let dmem = &mut dbuf[dmem_start..dmem_start + f.dmem_size as usize]; + let cmd_off = fw::patch_fwsec_dmem(dmem, f.interface, cmd, frts_addr, frts_size) + .map_err(|e| { + self.error( + b"FWSEC: DMEM mapper refused (error, command)\0", + e as u64, + u64::from(cmd), + 0, + 0, + ); + fw_errno(e) + })?; + let (h, dma) = self.hs_and_dma(which); + h.buf.write(dma, u64::from(f.imem_ns_pa), code)?; + h.buf.write(dma, code_len as u64, dbuf)?; + self.note( + b"FWSEC built (command, cmd buffer at DMEM, IMEM, DMEM)\0", + u64::from(cmd), + u64::from(cmd_off), + u64::from(f.imem_size), + u64::from(f.dmem_size), + ); + Ok(()) + })(); + if r.is_err() { + let (h, dma) = self.hs_and_dma(which); + h.buf.free(dma); + } + r + } + /// Booter Load (slot 0) or Unload (slot 1) in a new system-memory image. /// Uses bundled GA102 images for `Ga10x`, and loads per-family firmware via /// `request_firmware` (patching its fuse signature immediately) for Turing, GA100, and Ada. @@ -807,11 +1063,8 @@ impl Ga10xGsp { fn booter_build(&mut self, which: u8) -> Result<(), i32> { use nv_rs_core::gpu::gsp_boot::GspFirmwareChipFamily; if self.fw_family == GspFirmwareChipFamily::Ga10x { - let blob = if which == 1 { - BOOTER_UNLOAD - } else { - BOOTER_LOAD - }; + let (load, unload) = booters_for(self.fw_family, self.release).ok_or(EOPNOTSUPP)?; + let blob = if which == 1 { unload } else { load }; return self.booter_build_from_blob(which, blob, false); } let (load_name, unload_name) = @@ -925,15 +1178,13 @@ impl Ga10xGsp { } #[inline(never)] fn gsprm_load(&mut self) -> Result<(), i32> { - use nv_rs_core::gpu::gsp_image::{self, GspFwRelease}; - // `ga10x_gsp.rs` speaks the 580.178.04 XOR-framed RPC protocol (`GspSystemInfo` 0x3a8, - // `GspStaticConfigInfo` 0x700), so request the 580.178.04 firmware matching `self.fw_family` + use nv_rs_core::gpu::gsp_image; + // `ga10x_gsp.rs` speaks the 580 XOR-framed RPC protocol (`GspSystemInfo` 0x3a8, `GspStaticConfigInfo` + // 0x700), shared by 580.178.04 and 580.196.07, so request that release's firmware for `self.fw_family` // directly (never cross-loading `gsp_ga10x.bin` on Turing/GA100/Hopper/Blackwell or R620). - let Some(name) = gsp_image::firmware_filename_cstr_for_release( - self.fw_family, - GspFwRelease::V580_178_04, - ) else { - self.error(b"gsp firmware: no 580.178.04 image for family\0", 0, 0, 0, 0); + let Some(name) = gsp_image::firmware_filename_cstr_for_release(self.fw_family, self.release) + else { + self.error(b"gsp firmware: no image of this release for the family\0", 0, 0, 0, 0); return Err(EOPNOTSUPP); }; let (mut data, mut size, mut handle) = (ptr::null(), 0usize, ptr::null_mut()); @@ -955,8 +1206,8 @@ impl Ga10xGsp { #[inline(never)] fn gsprm_copy(&mut self, file: &[u8]) -> Result<(), i32> { let elf = GspFirmware::parse(file).map_err(|_| EINVAL)?; - if !elf.validate_version(GSP_RM_VERSION) { - self.error(b"gsp firmware: unsupported .fwversion (want 580.178.04)\0", 0, 0, 0, 0); + if !elf.validate_version(self.release.fw_version()) { + self.error(b"gsp firmware: .fwversion is not the release booted\0", 0, 0, 0, 0); return Err(EINVAL); } let image = elf.fwimage().ok_or(EINVAL)?; @@ -1010,7 +1261,13 @@ impl Ga10xGsp { #[inline(never)] fn libos_init(&mut self) -> Result<(), i32> { self.libos.alloc_into(&mut self.dma, GSP_PAGE)?; - let names: [&[u8]; 3] = [b"LOGINIT", b"LOGINTR", b"LOGRM"]; + // kgspSetupLibosInitArgs: the logs of the LibOS version (`nv_firmware_get_task_log_infos`: LOGINTR is + // LibOS3 only), then RMARGS + let names: &[&[u8]] = if self.turing() { + &[b"LOGINIT", b"LOGRM"] + } else { + &[b"LOGINIT", b"LOGINTR", b"LOGRM"] + }; let elem = unsafe { core::slice::from_raw_parts_mut(self.elem, fw::MAX_ELEMENT_BYTES) }; let args = &mut elem[..GSP_PAGE as usize]; fw::zero(args); @@ -1035,7 +1292,7 @@ impl Ga10xGsp { self.rmargs.alloc_into(&mut self.dma, GSP_PAGE)?; fw::write_libos_arg( args, - 3, + names.len(), fw::libos_id8(b"RMARGS"), self.rmargs.addr(), GSP_PAGE, @@ -1431,7 +1688,11 @@ impl Ga10xGsp { // ---- the CPU sequencer (nouveau r535_gsp_msg_run_cpu_sequencer) ---- + /// `kflcnResetIntoRiscv_HAL`. fn reset_riscv(&self) -> Result<(), i32> { + if self.turing() { + return self.tu_reset(GSP); + } self.flcn_reset_eng(GSP)?; self.fmask(GSP, 0x1668, 0x111, 0x111); Ok(()) @@ -1502,7 +1763,7 @@ impl Ga10xGsp { counts[3] += 1; } Command::CoreReset => { - let _ = self.flcn_reset(GSP); + self.reset(GSP)?; self.fmask(GSP, 0x624, 0x80, 0x80); self.fwr(GSP, 0x10c, 0); counts[3] += 1; @@ -1516,7 +1777,9 @@ impl Ga10xGsp { counts[3] += 1; } Command::CoreWaitForHalt => { - let _ = poll_sleep(2_000_000, || self.frd(GSP, 0x100) & 0x10 != 0); + if !poll_sleep(2_000_000, || self.frd(GSP, 0x100) & 0x10 != 0) { + return Err(ETIMEDOUT); + } counts[3] += 1; } Command::CoreResume => { @@ -1541,8 +1804,11 @@ impl Ga10xGsp { ); return Err(EIO); } - self.fwr(GSP, 0x080, 0); - if self.frd(GSP, RV + 0x388) & 0x80 == 0 { + // FALCON_OS: kgspExecuteSequencerCommand_GA102 only + if !self.turing() { + self.fwr(GSP, 0x080, 0); + } + if !self.riscv_active() { return Err(EIO); } counts[3] += 1; @@ -1559,6 +1825,16 @@ impl Ga10xGsp { Ok(()) } + /// `kflcnIsRiscvActive_HAL`: `NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS.ACTIVE_STAT` on Turing, `RISCV_CPUCTL` bit 7 + /// on GA10x. + fn riscv_active(&self) -> bool { + if self.turing() { + self.frd(GSP, RV + 0x240) & 1 != 0 + } else { + self.frd(GSP, RV + 0x388) & 0x80 != 0 + } + } + // ---- boot ---- #[inline(never)] fn fwsec_frts(&mut self) -> Result<(), i32> { @@ -1576,10 +1852,20 @@ impl Ga10xGsp { ); return Err(EBUSY); } - self.fwsec_build(fw::FWSEC_CMD_FRTS, 3)?; + if self.turing() { + self.fwsec2_build(fw::FWSEC_CMD_FRTS, 3)?; + } else { + self.fwsec_build(fw::FWSEC_CMD_FRTS, 3)?; + } + if !self.bus_master { + unsafe { nv_rs_pci_bus_master(self.pci, true) }; + self.bus_master = true; + } + self.frts_started = true; let r = (|| -> Result<(), i32> { let (m0, m1) = self.run(3, GSP, 0, None)?; - if m0 != 0 { + // the Turing FWSEC gets and returns no mailbox (kgspExecuteFwsec_TU102) + if !self.turing() && m0 != 0 { self.error( b"fwsec-frts: mailbox (mbox0, mbox1)\0", u64::from(m0), @@ -1591,8 +1877,11 @@ impl Ga10xGsp { } Ok(()) })(); - let (h, dma) = self.hs_and_dma(3); - h.buf.free(dma); + // a falcon that did not halt may still read the image: on failure it goes in free_all, after the reset + if r.is_ok() { + let (h, dma) = self.hs_and_dma(3); + h.buf.free(dma); + } let err = self.rd(0x1438) >> 16; let wpr2_lo = self.rd(0x1f_a824); let wpr2_hi = self.rd(0x1f_a828); @@ -1604,8 +1893,8 @@ impl Ga10xGsp { u64::from(wpr2_hi), ); r?; - // Match `_nv041253rm` (`kgspExecuteFwsec`): verify both scratch error == 0 and WPR2 HI != 0. - if err != 0 || (wpr2_hi >> 4) == 0 { + // kgspExecuteFwsec_TU102 (Turing to Ada): FRTS error code 0, WPR2 up, and WPR2 starting at the FRTS region + if err != 0 || (wpr2_hi >> 4) == 0 || u64::from(wpr2_lo >> 4) != self.layout.frts_addr >> 12 { return Err(EIO); } Ok(()) @@ -1620,6 +1909,20 @@ impl Ga10xGsp { let boot42 = self.rd(0xa00); self.boot_id = BootId::from_pmc_boot(boot0, boot42); self.fw_family = GspFirmwareChipFamily::from_boot_id(&self.boot_id); + let mut ver = [0u8; 64]; + let n = nv_rs_core::rmapi::client::copy_driver_version(&mut ver); + self.release = nv_rs_core::gpu::gsp_image::GspFwRelease::for_driver_version(&ver[..n]); + // only the families whose 580.196.07 Booters are bundled (TU102, TU116, GA102) boot that release + if booters_for(self.fw_family, self.release).is_none() { + self.release = nv_rs_core::gpu::gsp_image::GspFwRelease::V580_178_04; + } + self.note( + b"GSP-RM release (580.196.07 = 1, else 580.178.04)\0", + u64::from(self.release == nv_rs_core::gpu::gsp_image::GspFwRelease::V580_196_07), + 0, + 0, + 0, + ); // Accept all FWSEC-FRTS + SEC2 Booter GSP-RM generations: // Turing (TU10x/TU11x), Ampere (GA100/GA10x), and Ada (AD10x). if self.fw_family.boot_mode().is_none() { @@ -1632,6 +1935,12 @@ impl Ga10xGsp { ); return Err(EOPNOTSUPP); } + // kgspIsDebugModeEnabled_TU102: NV_FUSE_OPT_SECURE_GSP_DEBUG_DIS 0 needs the debug-signed Booter and FWSEC, + // and only the production ones are bundled + if self.turing() && self.rd(0x2_174c) & 1 == 0 { + self.error(b"GSP debug mode fused on: no debug Booter here\0", 0, 0, 0, 0); + return Err(EOPNOTSUPP); + } self.note( b"PMC_BOOT_0, GFW boot, WPR2 hi\0", u64::from(boot0), @@ -1652,7 +1961,10 @@ impl Ga10xGsp { // preventing `FWSEC-FRTS` error `0xbf`. Fall back to `read_vram_bytes_for_family` when // `0x1183a4` is unpopulated (e.g. Turing). let usable_fb_mb = self.rd(0x11_83a4); - let raw_fb_mb = if usable_fb_mb != 0 && usable_fb_mb != u32::MAX { + // Turing takes kmemsysReadUsableFbSize_GP102: NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE (0x100ce0) + let raw_fb_mb = if self.turing() { + fw::local_memory_range_mb(self.rd(0x10_0ce0)) + } else if usable_fb_mb != 0 && usable_fb_mb != u32::MAX { usable_fb_mb } else { self.boot_id @@ -1670,16 +1982,31 @@ impl Ga10xGsp { ) >> 20) as u32; let has_frts = !self.is_fmc_boot() && self.fw_family != GspFirmwareChipFamily::Ga100; - self.layout = fw::fb_layout_for_family(fb_mb, self.rd(0x62_5f04), has_frts).map_err(|e| { + // kgspPopulateWprMeta_TU102 reads the VGA workspace on Turing only when gpuFuseSupportsDisplay_GM107 says + // NV_FUSE_STATUS_OPT_DISPLAY (0x21c04) bit 0 is 0; otherwise the last MiB is reserved + let vga = if self.turing() && self.rd(0x2_1c04) & 1 != 0 { + 0 + } else { + self.rd(0x62_5f04) + }; + self.layout = fw::fb_layout_for_family(fb_mb, vga, has_frts).map_err(|e| { self.error( - b"usable FB size register\0", + b"FB layout (FB MiB, VGA workspace)\0", u64::from(fb_mb), - 0, + u64::from(vga), 0, 0, ); fw_errno(e) })?; + if self.turing() { + // the Booters go into SEC2 from the bundled images at each run: only their layout is checked now + let (load, unload) = booters_for(self.fw_family, self.release).ok_or(EOPNOTSUPP)?; + fw::parse_booter(load) + .and(fw::parse_booter(unload)) + .map_err(fw_errno)?; + return self.fwsec2_build(fw::FWSEC_CMD_SB, 2); + } if !self.is_fmc_boot() { self.booter_build(0)?; self.booter_build(1)?; @@ -1745,14 +2072,29 @@ impl Ga10xGsp { } /// Programs a persistent 4 KiB coherent DMA page into `NV_PFB_NISO_FLUSH_SYSMEM_ADDR(_HI)` - /// (`0x100c40`/`0x100c10`, matching `kmemsysProgramSysmemFlushBuffer_GA100`) so `SYS_MEMBAR` - /// and GSP boot flushes never trigger strict-IOMMU (`AMD-Vi`/`DMAR`) `IO_PAGE_FAULT`. + /// (`0x100c40`/`0x100c10`, matching `kmemsysProgramSysmemFlushBuffer_GA100`; on Turing + /// `kmemsysProgramSysmemFlushBuffer_GM107` uses `0x100c10` only and requires a 40-bit DMA + /// address) so `SYS_MEMBAR` and GSP boot flushes never trigger strict-IOMMU `IO_PAGE_FAULT`. #[inline(never)] fn program_sysmem_flush(&mut self) -> Result<(), i32> { self.sysmem_flush.alloc_into(&mut self.dma, GSP_PAGE)?; let addr = self.sysmem_flush.addr(); - self.wr(0x10_0c40, (addr >> 40) as u32); - self.wr(0x10_0c10, (addr >> 8) as u32); + if self.turing() { + if (addr >> 40) != 0 { + self.error( + b"Turing sysmem flush DMA address exceeds 40 bits (dma)\0", + addr, + 0, + 0, + 0, + ); + return Err(EINVAL); + } + self.wr(0x10_0c10, (addr >> 8) as u32); + } else { + self.wr(0x10_0c40, (addr >> 40) as u32); + self.wr(0x10_0c10, (addr >> 8) as u32); + } self.note( b"sysmem flush buffer programmed (dma, hi, lo)\0", addr, @@ -1825,7 +2167,7 @@ impl Ga10xGsp { self.system_info()?; let boot_len = self.boot.backing.bytes; self.layout - .place_wpr2(boot_len, self.image_len) + .place_wpr2(boot_len, self.image_len, self.turing()) .map_err(fw_errno)?; self.note( b"WPR2: start, heap, ELF, FRTS\0", @@ -2004,7 +2346,8 @@ impl Ga10xGsp { return Err(EIO); } self.fwr(GSP, 0x080, 0); // the bootloader's appVersion - if self.frd(GSP, RV + 0x388) & 0x80 == 0 { + // kgspBootstrap_TU102: running, or already suspended waiting for us (LIBOS_INTERRUPT_PROCESSOR_SUSPENDED) + if !self.riscv_active() && self.frd(GSP, 0x040) != 0x8000_0000 { self.dump(b"RISC-V not active after booter-load\0"); return Err(EIO); } @@ -2049,10 +2392,15 @@ impl Ga10xGsp { } #[inline(never)] fn dump(&self, when: &'static [u8]) { + let (status, more) = if self.turing() { + (0x240, 0x268) + } else { + (0x388, 0x400) + }; self.error( when, - u64::from(self.rd(GSP + RV + 0x388)), - u64::from(self.rd(GSP + RV + 0x400)), + u64::from(self.rd(GSP + RV + status)), + u64::from(self.rd(GSP + RV + more)), u64::from(self.rd(GSP + 0x040)), u64::from(self.rd(SEC2 + 0x040)), ); @@ -2091,8 +2439,15 @@ impl Ga10xGsp { } self.running = false; } - if !self.is_fmc_boot() && (self.rd(0x1f_a828) >> 4) != 0 && self.booter_unload.buf.live { - let _ = self.flcn_reset(GSP); + // a Turing boot that stopped before FWSEC-FRTS gave no falcon an address and set up no WPR2 + if self.turing() && !self.frts_started { + return true; + } + if !self.is_fmc_boot() + && (self.rd(0x1f_a828) >> 4) != 0 + && (self.turing() || self.booter_unload.buf.live) + { + let _ = self.reset(GSP); if self.fwsec_sb.buf.live { let r = self.run(2, GSP, 0, None); self.note( @@ -2111,6 +2466,17 @@ impl Ga10xGsp { u64::from(self.rd(0x1f_a828)), 0, ); + // kgspExecuteBooterUnloadIfNeeded_TU102: mailbox 0 is 0 and WPR2 is down + let wpr2_hi = self.rd(0x1f_a828) >> 4; + if !matches!(r, Ok((0, _))) || wpr2_hi != 0 { + self.error( + b"booter-unload failed (mbox0, WPR2 hi)\0", + r.map(|(m0, _)| u64::from(m0)).unwrap_or(u64::MAX), + u64::from(wpr2_hi), + 0, + 0, + ); + } } if self.is_fmc_boot() { // Wait for GSP RISC-V core to halt/idle after UNLOADING_GUEST_DRIVER before resetting falcon. @@ -2121,8 +2487,8 @@ impl Ga10xGsp { return nv_rs_core::gpu::gsp_boot::reset_gsp_falcon_gh100(&mut io).is_ok(); } // the falcons must not touch system memory any more: both reset and their state checked - let gsp = self.flcn_reset(GSP); - let sec2 = self.flcn_reset(SEC2); + let gsp = self.reset(GSP); + let sec2 = self.reset(SEC2); if gsp.is_err() || sec2.is_err() { self.error( b"unload: falcon reset failed (GSP, SEC2): system memory kept\0", @@ -2191,7 +2557,9 @@ impl Ga10xGsp { // IOVA is left for a later flush (a fault under a translating IOMMU) if self.sysmem_flush.live && self.rd(0) != u32::MAX { self.wr(0x10_0c10, 0); - self.wr(0x10_0c40, 0); + if !self.turing() { + self.wr(0x10_0c40, 0); + } } self.free_all(); if self.dma_open && self.dma.close_in_place().is_ok() { @@ -2202,18 +2570,19 @@ impl Ga10xGsp { } } -/// Boots GSP-RM on the GA102 at `pci`. On failure everything is undone (as far as the hardware allows). +/// Boots GSP-RM on the GA10x or Turing GPU at `pci`. On failure everything is undone (as far as the hardware allows). pub(crate) fn boot(pci: *mut c_void) -> Result, i32> { // Safety: every field of Ga10xGsp is valid all-zero (integers, bools, raw pointers, `LinuxDma` = no context). let mut h = unsafe { Heap::::zeroed() }.ok_or(ENOMEM)?; let g = h.get(); Ga10xGsp::new_into(g, pci); - // master's `gsp_abi` picks the firmware and the framing of gsp_bringup's path; this one boots GSP-RM 580.178.04 - // (its .fwversion is checked) and speaks that ABI whatever `gsp_abi` says, so userspace must be 580.178.04 + // master's `gsp_abi` picks the firmware and the framing of gsp_bringup's path; this one boots a 580 GSP-RM + // (580.196.07 on TU102 / TU116 / GA102 when driver_version is 580.196.07, else 580.178.04; its .fwversion is + // checked) and speaks that ABI whatever `gsp_abi` says, so userspace must match driver_version if crate::gsp_bringup::gsp_abi() != nv_rs_core::gpu::gsp_rpc::GspAbiVersion::R580 { note( pci, - b"GSP-RM 580.178.04 (gsp_abi is for gsp_bringup's path, not this one: userspace must be 580.178.04)\0", + b"GSP-RM 580 (gsp_abi is for gsp_bringup's path, not this one; driver_version picks 580.178.04 or 580.196.07)\0", 0, 0, 0, @@ -2245,8 +2614,13 @@ pub(crate) fn boot(pci: *mut c_void) -> Result, i32> { e.0 })?; g.dma_open = true; - unsafe { nv_rs_pci_bus_master(pci, true) }; - g.bus_master = true; + // Turing turns bus mastering on only once FWSEC-FRTS is about to run (`fwsec_frts`), so a refusal before it + // leaves the device as it was + let boot_id = nv_rs_core::gpu::chip_arch::BootId::from_pmc_boot(g.regs.rd(0), g.regs.rd(0xa00)); + if !fw::is_turing(GspFirmwareChipFamily::from_boot_id(&boot_id)) { + unsafe { nv_rs_pci_bus_master(pci, true) }; + g.bus_master = true; + } let r = g.init().and_then(|()| g.boot()); if let Err(e) = r { error(pci, b"boot failed\0", e as u64, 0, 0, 0); diff --git a/src/nvidia/kernel/ga10x_mem.rs b/src/nvidia/kernel/ga10x_mem.rs index 6091ca7c..2dde8b33 100644 --- a/src/nvidia/kernel/ga10x_mem.rs +++ b/src/nvidia/kernel/ga10x_mem.rs @@ -34,9 +34,13 @@ const VF_MMU_INVALIDATE_PDB: u32 = 0xb8_0000 + 0x30a0; const VF_MMU_INVALIDATE_UPDB: u32 = 0xb8_0000 + 0x30a4; const VF_MMU_INVALIDATE: u32 = 0xb8_0000 + 0x30b0; -/// Kernel-side video memory: 512 MiB at the top of the client heap. -pub(crate) const INTERNAL_BYTES: u64 = 512 << 20; -const INTERNAL_PAGES: usize = (INTERNAL_BYTES >> 12) as usize; +/// Kernel-side video memory at the top of the client heap: a 32nd of the heap, 128 to 512 MiB (an 8 GiB Turing card +/// keeps room for its CUDA working set; peak use measured there with llama.cpp was 11 MiB). +pub(crate) const fn internal_bytes(heap: u64) -> u64 { + let b = heap / 32; + let b = if b < (128 << 20) { 128 << 20 } else if b > (512 << 20) { 512 << 20 } else { b }; + b & !0x1f_ffff +} /// `SPLIT_VAS_SERVER_RM_MANAGED_VA_START` / `_SIZE`: GSP-RM's range in a kernel-managed VA space. pub(crate) const SPLIT_VAS_START: u64 = 0x1_0000_0000; @@ -65,8 +69,14 @@ pub(crate) struct Ga10xMem { map: *mut u64, pub int_used: u64, pub int_peak: u64, + int_pages: usize, /// VRAM [0, bar1_mapped) is at BAR1 [0, bar1_mapped). pub bar1_mapped: u64, + /// A TU10x / TU11x GPU: its engines are exposed by NVIDIA's rule for a Turing (`gsp_split_turing`). + pub turing: bool, + /// Turing: `NV2080_CTRL_CE_UPDATE_CLASS_DB_PARAMS.stubbedCeMask` (bit i: COPYi has no physical engine), with + /// the copy engines GSP-RM gave no runlist added. + pub ce_stubbed: u32, } impl Ga10xMem { @@ -83,13 +93,15 @@ impl Ga10xMem { self.bar1_phys = bar1_phys; self.bar1_size = bar1_size; let heap = info.heap_limit - info.heap_base + 1; - if heap < 2 * INTERNAL_BYTES { + let internal = internal_bytes(heap); + if heap < 2 * internal { return Err(ENOSPC); } + self.int_pages = (internal >> 12) as usize; self.int_top = (info.heap_limit + 1) & !0x1f_ffff; - self.int_floor = self.int_top - INTERNAL_BYTES; + self.int_floor = self.int_top - internal; self.client_last = self.int_floor - 1; - let p = crate::ga10x_gsp::alloc_zeroed(INTERNAL_PAGES / 8).cast::(); + let p = crate::ga10x_gsp::alloc_zeroed(self.int_pages / 8).cast::(); if p.is_null() { return Err(ENOMEM); } @@ -99,6 +111,14 @@ impl Ga10xMem { pub fn fini(&mut self) { if !self.map.is_null() { + crate::ga10x_gsp::note( + self.regs.0, + b"kernel-side video memory: peak, in use at teardown, reserved\0", + self.int_peak, + self.int_used, + (self.int_pages as u64) << 12, + 0, + ); crate::ga10x_gsp::free(self.map.cast()); self.map = core::ptr::null_mut(); } @@ -183,7 +203,7 @@ impl Ga10xMem { let floor_page = (self.int_floor >> 12) as usize; let r = (step - floor_page % step) % step; let mut i = r; - while i + n <= INTERNAL_PAGES { + while i + n <= self.int_pages { match (i..i + n).find(|&k| self.bit(k)) { None => { self.set_bits(i, n, true); @@ -471,6 +491,15 @@ impl Ga10xMem { /// 0x13, NVENC0 0x1b, SW 0x22, SEC2 0x26, OFA 0x33). NVIDIA's kernel side exposes all but SEC2 and COPY4 (its /// GET_ENGINES_V2 and CE_GET_ALL_CAPS answers on this card; CE4 work faults with RC 71 when a client uses it). pub fn engine_exposed(&self, t: u32) -> bool { + if self.turing { + // TU1xx: every engine with a class (no SEC2 class) but the copy engines GSP-RM reports stubbed + // (`kceUpdateClassDB_KERNEL`, `gpuUpdateEngineTable_IMPL`); COPY4 is a real engine on a TU116 + return nv_rs_core::gpu::gsp_split_turing::engine_exposed( + &self.info.engine_caps, + self.ce_stubbed, + t, + ); + } if t == 0x26 || t == 0xd || t >= 96 { return false; } diff --git a/src/nvidia/src/gpu.rs b/src/nvidia/src/gpu.rs index 4bc84e6f..a5a6afe4 100644 --- a/src/nvidia/src/gpu.rs +++ b/src/nvidia/src/gpu.rs @@ -89,6 +89,7 @@ pub mod gsp_image; pub mod gsp_live; pub mod gsp_rpc; pub mod gsp_sequencer; +pub mod gsp_split_turing; pub mod gsp_transport; pub mod gsp_ucode; pub mod gv100_ce_scrub; diff --git a/src/nvidia/src/gpu/ga10x_gsp.rs b/src/nvidia/src/gpu/ga10x_gsp.rs index 9d17425d..bf06083a 100644 --- a/src/nvidia/src/gpu/ga10x_gsp.rs +++ b/src/nvidia/src/gpu/ga10x_gsp.rs @@ -1,4 +1,9 @@ -//! GA10x (Ampere GA102..GA107) GSP-RM 580.178.04 on real hardware: the parts that need no hardware. +//! GA10x (Ampere GA102..GA107) and Turing (TU102..TU117) GSP-RM 580.178.04 on real hardware: the parts that need no +//! hardware. +//! +//! Turing boots the same way (`kgspBootstrap_TU102` serves both in 580.178.04) with its own HALs: Booter and the +//! FWSEC of a `FALCON_UCODE_DESC_V2` are loaded without the BROM, the GSP-RM heap is the LibOS2 one, and the firmware +//! is `gsp_tu10x.bin`. //! //! The live boot (`kernel/ga10x_gsp.rs`) runs FWSEC-FRTS from the VBIOS on the GSP falcon, Booter Load on SEC2, the //! RISC-V bootloader and GSP-RM, then talks to GSP-RM through the shared-memory message queues. Everything here is @@ -14,7 +19,14 @@ //! `g_rpc-structures.h`, `nvfw/hs.h`). The sequence was checked call by call against NVIDIA's open 580.178.04 kernel //! modules on an RTX 3090. -use crate::gpu::gsp_boot::GspFwWprMeta; +use crate::gpu::gsp_boot::{GspFirmwareChipFamily, GspFwWprMeta}; + +pub const fn is_turing(family: GspFirmwareChipFamily) -> bool { + matches!( + family, + GspFirmwareChipFamily::Tu10x | GspFirmwareChipFamily::Tu11x + ) +} /// Why a firmware image, the VBIOS or a GSP-RM message was refused. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -192,7 +204,9 @@ impl VbiosFwsec { const ROM_SIG: u16 = 0xaa55; const NPDE: u32 = 0x4544_504e; -const FALCON_APP_FWSEC: u8 = 0x85; +/// `FALCON_UCODE_ENTRY_APPID_FIRMWARE_SEC_LIC` and `_FWSEC_PROD`: the production entries +/// `s_vbiosParseFwsecUcodeDescFromBit` accepts. +const FALCON_APP_FWSEC: [u8; 2] = [0x05, 0x85]; /// Walks the PCI images, finds the BIT table, its falcon-ucode table (`'p'` version 2) and FWSEC's descriptor in /// it. A truncated image record ends the image walk; the BIT entries and the falcon table entries are each checked @@ -265,9 +279,22 @@ pub fn find_fwsec(rom: &[u8]) -> Result { } for i in 0..count { let e = table + header + i * len; - if v.rd8(rom, e)? == FALCON_APP_FWSEC { - let data = v.rd32(rom, e + 2)?; - v.desc = v.translate(data); + if !FALCON_APP_FWSEC.contains(&v.rd8(rom, e)?) { + continue; + } + // s_vbiosParseFwsecUcodeDescFromBit: an entry whose fixed descriptor is unreadable, unversioned, or not a V2 + // of at least 60 bytes or a V3 of at least 44 is skipped + let desc = v.translate(v.rd32(rom, e + 2)?); + let Ok(hdr) = rd32(rom, desc as usize) else { + continue; + }; + let fixed = match ((hdr >> 8) & 0xff, hdr >> 16) { + (2, 60..) => 60, + (3, 44..) => 44, + _ => continue, + }; + if hdr & 1 != 0 && span(rom, desc as usize, fixed).is_ok() { + v.desc = desc; return Ok(v); } } @@ -450,6 +477,105 @@ pub fn parse_fwsec(rom: &[u8], v: &VbiosFwsec) -> Result { }) } +/// FWSEC in a Turing VBIOS (`FALCON_UCODE_DESC_V2`), loaded by the generic falcon bootloader from a code and a data +/// buffer in system memory (`s_vbiosFillFlcnUcodeFromDescV2`, `kernel_gsp_fwsec.c`). The ROM holds the IMEM image right +/// after the descriptor and the DMEM image `DMEMOffset` bytes into it; the signatures are already in the image. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct FwsecV2 { + /// ROM offsets of the IMEM and DMEM images. + pub rom_code: u32, + pub rom_data: u32, + pub imem_size: u32, + pub imem_ns_pa: u32, + pub imem_ns_size: u32, + pub imem_sec_pa: u32, + pub imem_sec_size: u32, + pub dmem_pa: u32, + pub dmem_size: u32, + /// DMEM offset of the application interface table. + pub interface: u32, +} + +impl FwsecV2 { + /// Bytes of the code buffer; the data buffer starts here (both 256-byte aligned). + pub const fn code_bytes(&self) -> u32 { + align_up(self.imem_size as u64, 256) as u32 + } + + pub const fn data_bytes(&self) -> u32 { + align_up(self.dmem_size as u64, 256) as u32 + } +} + +/// `s_vbiosParseFwsecUcodeDescFromBit` (V2 branch) and `s_vbiosFillFlcnUcodeFromDescV2`, with their range checks. +pub fn parse_fwsec_v2(rom: &[u8], v: &VbiosFwsec) -> Result { + let d = v.desc as usize; + let hdr = rd32(rom, d)?; + let size = hdr >> 16; + if hdr & 1 == 0 || (hdr >> 8) & 0xff != 2 || size < 60 { + return Err(Error::Unsupported); + } + let f = |o: usize| rd32(rom, d + o); + let (interface, imem_phys, imem_load, imem_virt) = (f(16)?, f(20)?, f(24)?, f(28)?); + let (imem_sec_base, imem_sec_size, dmem_off, dmem_phys, dmem_load) = + (f(32)?, f(36)?, f(40)?, f(44)?, f(48)?); + let rom_code = v.desc.checked_add(size).ok_or(Error::Truncated)?; + let rom_data = rom_code.checked_add(dmem_off).ok_or(Error::Truncated)?; + span(rom, rom_code as usize, imem_load as usize)?; + span(rom, rom_data as usize, dmem_load as usize)?; + let fw = FwsecV2 { + rom_code, + rom_data, + imem_size: imem_load, + imem_ns_pa: imem_phys, + imem_ns_size: imem_load + .checked_sub(imem_sec_size) + .ok_or(Error::BadLayout)?, + imem_sec_pa: imem_sec_base + .checked_sub(imem_virt) + .and_then(|o| o.checked_add(imem_phys)) + .ok_or(Error::BadLayout)?, + imem_sec_size: align_up(u64::from(imem_sec_size), 256) as u32, + dmem_pa: dmem_phys, + dmem_size: dmem_load, + interface, + }; + let fits = |pa: u32, len: u32, room: u32| { + u64::from(pa) + u64::from(len) <= u64::from(room) && pa < room + }; + if !fits(fw.imem_ns_pa, fw.imem_size, fw.code_bytes()) + || !fits(fw.dmem_pa, fw.dmem_size, fw.data_bytes()) + || interface >= dmem_load + { + return Err(Error::BadLayout); + } + Ok(fw) +} + +/// `RM_FLCN_BL_DMEM_DESC` (`rmflcnbl.h`): what the generic bootloader loads. +pub const BL_DMEM_DESC_BYTES: usize = 0x54; +/// `ctxDma` 4: the FBIF aperture `s_prepareHsFalconWithLoader` points at coherent system memory. +pub const BL_CTX_DMA: u32 = 4; + +/// The bootloader's DMEM descriptor for `fw` with its code at `code_dma` and its data at `data_dma` +/// (`s_prepareHsFalconWithLoader`); reserved, signature, entry point, argc and argv are 0. +pub fn write_bl_dmem_desc( + out: &mut [u8], + code_dma: u64, + data_dma: u64, + fw: &FwsecV2, +) -> Result<()> { + zero(span_mut(out, 0, BL_DMEM_DESC_BYTES)?); + wr32(out, 0x20, BL_CTX_DMA)?; + wr64(out, 0x24, code_dma)?; + wr32(out, 0x2c, fw.imem_ns_pa)?; + wr32(out, 0x30, fw.imem_ns_size)?; + wr32(out, 0x34, fw.imem_sec_pa)?; + wr32(out, 0x38, fw.imem_sec_size)?; + wr64(out, 0x40, data_dma)?; + wr32(out, 0x48, fw.dmem_size) +} + /// Patches FWSEC's DMEM (a copy in the image buffer, `dmem` = its DMEM part) through the DMEM-mapper application /// interface: the command to run and its arguments (nouveau `nvkm_gsp_fwsec_patch`; FRTS: the FRTS region, 4 KiB /// units). Every table, record and the command's whole argument block are checked against `dmem` first. Returns @@ -513,6 +639,10 @@ pub struct Booter { pub data_off: u32, /// Offset of the first signature in the file. pub sigs_off: u32, + /// The non-secure code (`osCodeOffset` / `osCodeSize`) in the image: Turing loads it into IMEM ahead of the + /// secure code (`s_prepareHsFalconDirect`). + pub ns_off: u32, + pub ns_size: u32, } pub fn parse_booter(blob: &[u8]) -> Result { @@ -558,10 +688,16 @@ pub fn parse_booter(blob: &[u8]) -> Result { sig_base_img: patch_loc, }; ucode.check()?; + let (ns_off, ns_size) = (rd32(blob, lh)?, rd32(blob, lh + 4)?); + if u64::from(ns_off) + u64::from(ns_size) > u64::from(data_size) { + return Err(Error::BadLayout); + } Ok(Booter { ucode, data_off, sigs_off, + ns_off, + ns_size, }) } @@ -587,7 +723,24 @@ pub struct FbLayout { pub nonwpr_size: u64, } -/// `NV_USABLE_FB_SIZE_IN_MB` (0x1183a4) and `NV_PDISP_VGA_WORKSPACE_BASE` (0x625f04): the FB size, the VGA +/// Turing's FB size in MiB (`kmemsysReadUsableFbSize_GP102`): `NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE` (0x100ce0) gives +/// `LOWER_MAG` (9:4) << (`LOWER_SCALE` (3:0) + 20) bytes, 15/16 of it with `ECC_MODE` (30) on. A priv error reads 0 +/// (refused by [`fb_layout`]). +pub fn local_memory_range_mb(reg: u32) -> u32 { + if reg & 0xfff0_0000 == 0xbad0_0000 || reg == u32::MAX { + return 0; + } + let bytes = u64::from((reg >> 4) & 0x3f) << ((reg & 0xf) + 20); + let bytes = if reg & (1 << 30) != 0 { + bytes / 16 * 15 + } else { + bytes + }; + (bytes >> 20) as u32 +} + +/// `NV_USABLE_FB_SIZE_IN_MB` (0x1183a4; Turing: [`local_memory_range_mb`]) and `NV_PDISP_VGA_WORKSPACE_BASE` +/// (0x625f04): the FB size, the VGA /// workspace and the FRTS region below it. pub fn fb_layout(usable_fb_mb: u32, vga_workspace: u32) -> Result { fb_layout_for_family(usable_fb_mb, vga_workspace, true) @@ -614,8 +767,10 @@ pub fn fb_layout_for_family( let a = u64::from(vga_workspace & 0xffff_ff00) << 8; if a < base { fb_size - 0x2_0000 - } else { + } else if a < fb_size { a + } else { + return Err(Error::BadLayout); } }; let frts_size = if has_frts { 0x10_0000 } else { 0 }; @@ -631,14 +786,21 @@ pub fn fb_layout_for_family( impl FbLayout { /// The WPR2 contents below FRTS for a bootloader of `boot_size` and a GSP-RM image of `elf_size` bytes - /// (LibOS3 bare-metal heap: r570 `ga102` sizing, as nouveau). - pub fn place_wpr2(&mut self, boot_size: u64, elf_size: u64) -> Result<()> { + /// (`kgspPopulateWprMeta_TU102` with `_kgspCalculateFwHeapSize` / `kgspGetFwHeapSize_IMPL`): the heap is the + /// OS carveout (LibOS3 22 MiB, Turing's LibOS2 0) + 8 MiB + 96 KiB per GB of FB + 96 MiB of client allocations, + /// at least 88 MiB (LibOS2 64 MiB), and inside the 256 MiB at the top of FB the VBIOS scrubbed. + pub fn place_wpr2(&mut self, boot_size: u64, elf_size: u64, libos2: bool) -> Result<()> { let gb = self.fb_size.div_ceil(1 << 30); - let heap = ((22u64 << 20) + let (carveout, min) = if libos2 { + (0, 64u64 << 20) + } else { + (22u64 << 20, 88u64 << 20) + }; + let heap = (carveout + (8u64 << 20) + align_up((96u64 << 10) * gb, 1 << 20) + align_up((48u64 << 10) * 2048, 1 << 20)) - .max(88 << 20); + .max(min); self.boot_size = boot_size; self.boot_addr = align_down( self.frts_addr @@ -653,6 +815,10 @@ impl FbLayout { .ok_or(Error::BadLayout)?, 0x1_0000, ); + let scrubbed = (256u64 << 20) + .checked_sub((2 << 20) + align_up(self.fb_size - self.elf_addr, 1 << 20)) + .ok_or(Error::BadLayout)?; + let heap = heap.min(align_down(scrubbed, 1 << 20)); self.heap_addr = align_down( self.elf_addr.checked_sub(heap).ok_or(Error::BadLayout)?, 0x10_0000, @@ -1284,6 +1450,181 @@ mod tests { ); } + #[test] + fn turing_booters_parse_from_the_580_bindata() { + // g_bindata_kgspGetBinArchiveBooterLoadUcode_TU102.c: header {0, 0x100, 0x8500, 0x6200, 1, 0x100, 0x8400}, + // patch location 0x8700, one 16-byte signature, patch meta {fuse 0, engine 1 (SEC2), ucode 0xd} + let b = parse_booter(include_bytes!("ucode/booter_load_tu102.bin")).unwrap(); + assert_eq!((b.ns_off, b.ns_size), (0, 0x100)); + assert_eq!((b.ucode.imem_base_img, b.ucode.imem_size), (0x100, 0x8400)); + assert_eq!((b.ucode.dmem_base_img, b.ucode.dmem_size), (0x8500, 0x6200)); + assert_eq!( + (b.ucode.sig_base_img, b.ucode.sig_count, b.ucode.sig_size), + (0x8700, 1, 16) + ); + assert_eq!( + (b.ucode.fuse_ver, b.ucode.engine_id, b.ucode.ucode_id), + (0, 1, 0xd) + ); + // ksec2ReadUcodeFuseVersion is 0 on Turing: s_patchBooterUcodeSignature takes the last signature + assert_eq!(b.ucode.signature_index(0).unwrap(), 0); + let b = parse_booter(include_bytes!("ucode/booter_load_tu116.bin")).unwrap(); + assert_eq!( + ( + b.ucode.imem_size, + b.ucode.dmem_base_img, + b.ucode.sig_base_img + ), + (0x8300, 0x8400, 0x8600) + ); + let u = parse_booter(include_bytes!("ucode/booter_unload_tu102.bin")).unwrap(); + assert_eq!( + (u.ns_size, u.ucode.imem_size, u.ucode.dmem_base_img), + (0x100, 0x4b00, 0x4c00) + ); + let u = parse_booter(include_bytes!("ucode/booter_unload_tu116.bin")).unwrap(); + assert_eq!((u.ucode.imem_size, u.ucode.sig_base_img), (0x4a00, 0x4d00)); + } + + fn rom_with_fwsec_v2(desc: &[u32; 15], len: usize) -> (Vec, VbiosFwsec) { + let mut rom = vec![0u8; len]; + for (i, v) in desc.iter().enumerate() { + wr32(&mut rom, 0x400 + 4 * i, *v).unwrap(); + } + ( + rom, + VbiosFwsec { + desc: 0x400, + ..VbiosFwsec::default() + }, + ) + } + + const V2: [u32; 15] = [ + 60 << 16 | 2 << 8 | 1, + 0, + 0, + 0, + 0x40, + 0, + 0x300, + 0, + 0x100, + 0x180, + 0x300, + 0, + 0x120, + 0, + 0, + ]; + + #[test] + fn fwsec_v2_layout_follows_the_descriptor() { + let (rom, v) = rom_with_fwsec_v2(&V2, 0x1000); + let f = parse_fwsec_v2(&rom, &v).unwrap(); + assert_eq!((f.rom_code, f.rom_data), (0x43c, 0x73c)); + assert_eq!((f.imem_ns_pa, f.imem_ns_size), (0, 0x180)); + assert_eq!((f.imem_sec_pa, f.imem_sec_size), (0x100, 0x200)); + assert_eq!( + (f.code_bytes(), f.data_bytes(), f.interface), + (0x300, 0x200, 0x40) + ); + assert!(parse_fwsec(&rom, &v).is_err()); + let mut d = [0u8; BL_DMEM_DESC_BYTES]; + write_bl_dmem_desc(&mut d, 0x1_2345_6700, 0x8900, &f).unwrap(); + assert_eq!(rd32(&d, 0x20).unwrap(), 4); + assert_eq!( + (rd32(&d, 0x24).unwrap(), rd32(&d, 0x28).unwrap()), + (0x2345_6700, 1) + ); + assert_eq!( + (rd32(&d, 0x34).unwrap(), rd32(&d, 0x38).unwrap()), + (0x100, 0x200) + ); + assert_eq!( + (rd64(&d, 0x40).unwrap(), rd32(&d, 0x48).unwrap()), + (0x8900, 0x120) + ); + } + + #[test] + fn fwsec_v2_is_found_through_the_bit_table_as_app_05() { + let mut rom = rom_with_fwsec(); + rom[0x304] = 0x05; + for (i, v) in V2.iter().enumerate() { + wr32(&mut rom, 0x400 + 4 * i, *v).unwrap(); + } + let v = find_fwsec(&rom).unwrap(); + assert_eq!(v.desc, 0x400); + assert_eq!(parse_fwsec_v2(&rom, &v).unwrap().rom_data, 0x73c); + rom[0x304] = 0x45; + assert!(find_fwsec(&rom).is_err()); + // a 0x05 entry with a V1 descriptor first: skipped for the 0x85 entry after it + rom[0x303] = 2; + rom[0x304] = 0x05; + wr32(&mut rom, 0x306, 0x800).unwrap(); + wr32(&mut rom, 0x800, 60 << 16 | 1 << 8 | 1).unwrap(); + rom[0x30a] = 0x85; + wr32(&mut rom, 0x30c, 0x400).unwrap(); + assert_eq!(find_fwsec(&rom).unwrap().desc, 0x400); + rom[0x30a] = 0x45; + assert!(find_fwsec(&rom).is_err()); + // a 0x05 entry whose V2 header is the ROM's last word: its body is missing, the 0x85 after it is taken + rom[0x30a] = 0x85; + let end = rom.len() - 4; + wr32(&mut rom, 0x306, end as u32).unwrap(); + wr32(&mut rom, end, 60 << 16 | 2 << 8 | 1).unwrap(); + assert_eq!(find_fwsec(&rom).unwrap().desc, 0x400); + } + + #[test] + fn vga_workspace_past_the_end_of_fb_is_refused() { + assert!(fb_layout(8192, u32::MAX).is_err()); + assert_eq!( + fb_layout(8192, 0x01ff_f008).unwrap().vga_addr, + 0x1_fff0_0000 + ); + } + + #[test] + fn fwsec_v2_out_of_range_is_refused() { + // the DMEM image ends at 0x73c + 0x120: one byte short of ROM + let (rom, v) = rom_with_fwsec_v2(&V2, 0x85b); + assert!(parse_fwsec_v2(&rom, &v).is_err()); + for (field, value) in [(9usize, 0x400u32), (4, 0x120), (11, 0x100), (5, 0x10)] { + let mut d = V2; + d[field] = value; + let (rom, v) = rom_with_fwsec_v2(&d, 0x1000); + assert!(parse_fwsec_v2(&rom, &v).is_err(), "field {field}"); + } + } + + #[test] + fn turing_fb_size_comes_from_the_local_memory_range() { + assert_eq!(local_memory_range_mb(8 << 4 | 10), 8192); + assert_eq!(local_memory_range_mb(1 << 4 | 13), 8192); + // ECC on a 16 GiB T4: 15/16 + assert_eq!(local_memory_range_mb(1 << 30 | 1 << 4 | 14), 15360); + assert_eq!(local_memory_range_mb(0xbadf_1100), 0); + assert!(fb_layout(local_memory_range_mb(u32::MAX), 0).is_err()); + } + + #[test] + fn turing_heap_is_libos2() { + // an 8 GiB TU104 with the VGA workspace at the end of FB and a 30 MB GSP-RM image + let mut l = fb_layout(8192, 0).unwrap(); + assert_eq!(l.frts_addr, 0x1_ffe0_0000); + l.place_wpr2(0x1000, 30_000_000, true).unwrap(); + assert_eq!((l.boot_addr, l.elf_addr), (0x1_ffdf_f000, 0x1_fe16_0000)); + // 0 + 8 + 1 + 96 MiB + assert_eq!((l.heap_addr, l.heap_size), (0x1_f780_0000, 0x690_0000)); + assert_eq!((l.wpr2_addr, l.nonwpr_addr), (0x1_f770_0000, 0x1_f760_0000)); + // a heap that would reach below the scrubbed 256 MiB is cut to fit + let mut l = fb_layout(8192, 0).unwrap(); + l.place_wpr2(0x1000, 200 << 20, true).unwrap(); + assert_eq!(l.heap_size, 51 << 20); + } + #[test] fn truncated_booters_are_refused() { let full = include_bytes!("ucode/booter_load_ga102.bin"); @@ -1313,7 +1654,7 @@ mod tests { let mut l = fb_layout(24576, 1).unwrap(); assert_eq!((l.vga_addr, l.vga_size), (0x5_fff0_0000, 0x10_0000)); assert_eq!(l.frts_addr, 0x5_ffe0_0000); - l.place_wpr2(0x6000, 74_985_472).unwrap(); + l.place_wpr2(0x6000, 74_985_472, false).unwrap(); assert_eq!(l.boot_addr, 0x5_ffdf_a000); assert_eq!(l.elf_addr, 0x5_fb67_0000); assert_eq!((l.heap_addr, l.heap_size), (0x5_f350_0000, 0x810_0000)); @@ -1382,6 +1723,7 @@ mod tests { rom[0x303] = 1; rom[0x304] = 0x85; wr32(&mut rom, 0x306, 0x400).unwrap(); + wr32(&mut rom, 0x400, 44 << 16 | 3 << 8 | 1).unwrap(); // FALCON_UCODE_DESC_V3 header rom } @@ -1580,7 +1922,7 @@ mod tests { assert_eq!(l.frts_addr, l.vga_addr - 0x10_0000); let boot_len = gsp_ucode::bootloader_for(family).unwrap().image.len() as u64; - l.place_wpr2(boot_len, 74_985_472).unwrap(); + l.place_wpr2(boot_len, 74_985_472, false).unwrap(); assert!(l.nonwpr_addr < l.wpr2_addr); assert!(l.wpr2_addr < l.heap_addr); assert!(l.heap_addr + l.heap_size <= l.elf_addr); @@ -1592,7 +1934,7 @@ mod tests { // 4092 MiB usable FB variant (NV_USABLE_FB_SIZE_IN_MB trimmed by 4 MiB). let mut l_trim = fb_layout_for_family(4092, 0, true).unwrap(); - l_trim.place_wpr2(boot_len, 74_985_472).unwrap(); + l_trim.place_wpr2(boot_len, 74_985_472, false).unwrap(); assert_eq!(l_trim.fb_size, 4092u64 << 20); assert!(l_trim.nonwpr_addr > (3500u64 << 20)); diff --git a/src/nvidia/src/gpu/gsp_image.rs b/src/nvidia/src/gpu/gsp_image.rs index 384a7809..95071e3c 100644 --- a/src/nvidia/src/gpu/gsp_image.rs +++ b/src/nvidia/src/gpu/gsp_image.rs @@ -13,14 +13,20 @@ pub const EXPECTED_FW_VERSION: &str = "580.178.04"; pub const EXPECTED_FW_VERSION_620: &str = "620.70.06"; /// Expected `.fwversion` string embedded in NVIDIA 620.73.04 GSP-RM ELF containers. pub const EXPECTED_FW_VERSION_620_73: &str = "620.73.04"; +/// Expected `.fwversion` string embedded in NVIDIA 580.196.07 GSP-RM ELF containers. Its RPC structures, static +/// configuration and message queues match 580.178.04's; only the Booter ucode differs (open-gpu-kernel-modules +/// `580.178.04..580.196.07`). +pub const EXPECTED_FW_VERSION_580_196: &str = "580.196.07"; /// One GSP-RM firmware release: the `.fwversion` its containers carry and the /// `nvidia//` directory the stock driver loads them from. +#[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum GspFwRelease { - V580_178_04, - V620_70_06, - V620_73_04, + V580_178_04 = 0, + V580_196_07 = 1, + V620_70_06 = 2, + V620_73_04 = 3, } impl GspFwRelease { @@ -28,6 +34,7 @@ impl GspFwRelease { pub const fn fw_version(self) -> &'static str { match self { Self::V580_178_04 => EXPECTED_FW_VERSION, + Self::V580_196_07 => EXPECTED_FW_VERSION_580_196, Self::V620_70_06 => EXPECTED_FW_VERSION_620, Self::V620_73_04 => EXPECTED_FW_VERSION_620_73, } @@ -37,10 +44,21 @@ impl GspFwRelease { pub const fn dir(self) -> &'static str { match self { Self::V580_178_04 => "580.178.04", + Self::V580_196_07 => "580.196.07", Self::V620_70_06 => "620.70.06", Self::V620_73_04 => "620.73.04", } } + + /// The 580 release whose GSP-RM matches the userspace driver version reported to NVML and libcuda + /// (`driver_version`): 580.196.07 for that version, otherwise 580.178.04. + pub fn for_driver_version(version: &[u8]) -> Self { + if version == EXPECTED_FW_VERSION_580_196.as_bytes() { + Self::V580_196_07 + } else { + Self::V580_178_04 + } + } } /// The releases a session speaking `abi` may load, preferred first. R620 carries both @@ -165,6 +183,12 @@ pub const fn firmware_filename_for_release( | GspFirmwareChipFamily::Ga100, GspFwRelease::V580_178_04, ) => Some("nvidia/580.178.04/gsp_tu10x.bin"), + ( + GspFirmwareChipFamily::Tu10x + | GspFirmwareChipFamily::Tu11x + | GspFirmwareChipFamily::Ga100, + GspFwRelease::V580_196_07, + ) => Some("nvidia/580.196.07/gsp_tu10x.bin"), ( GspFirmwareChipFamily::Tu10x | GspFirmwareChipFamily::Tu11x @@ -187,6 +211,16 @@ pub const fn firmware_filename_for_release( | GspFirmwareChipFamily::Gb20y, GspFwRelease::V580_178_04, ) => Some("nvidia/580.178.04/gsp_ga10x.bin"), + ( + GspFirmwareChipFamily::Ga10x + | GspFirmwareChipFamily::Ad10x + | GspFirmwareChipFamily::Gh100 + | GspFirmwareChipFamily::Gb10x + | GspFirmwareChipFamily::Gb20x + | GspFirmwareChipFamily::Gb10y + | GspFirmwareChipFamily::Gb20y, + GspFwRelease::V580_196_07, + ) => Some("nvidia/580.196.07/gsp_ga10x.bin"), ( GspFirmwareChipFamily::Ga10x | GspFirmwareChipFamily::Ad10x @@ -223,6 +257,12 @@ pub const fn firmware_filename_cstr_for_release( | GspFirmwareChipFamily::Ga100, GspFwRelease::V580_178_04, ) => Some(b"nvidia/580.178.04/gsp_tu10x.bin\0"), + ( + GspFirmwareChipFamily::Tu10x + | GspFirmwareChipFamily::Tu11x + | GspFirmwareChipFamily::Ga100, + GspFwRelease::V580_196_07, + ) => Some(b"nvidia/580.196.07/gsp_tu10x.bin\0"), ( GspFirmwareChipFamily::Tu10x | GspFirmwareChipFamily::Tu11x @@ -245,6 +285,16 @@ pub const fn firmware_filename_cstr_for_release( | GspFirmwareChipFamily::Gb20y, GspFwRelease::V580_178_04, ) => Some(b"nvidia/580.178.04/gsp_ga10x.bin\0"), + ( + GspFirmwareChipFamily::Ga10x + | GspFirmwareChipFamily::Ad10x + | GspFirmwareChipFamily::Gh100 + | GspFirmwareChipFamily::Gb10x + | GspFirmwareChipFamily::Gb20x + | GspFirmwareChipFamily::Gb10y + | GspFirmwareChipFamily::Gb20y, + GspFwRelease::V580_196_07, + ) => Some(b"nvidia/580.196.07/gsp_ga10x.bin\0"), ( GspFirmwareChipFamily::Ga10x | GspFirmwareChipFamily::Ad10x @@ -616,6 +666,24 @@ mod tests { EXPECTED_FW_VERSION_620_73 ); assert_eq!(GspFwRelease::V620_73_04.dir(), "620.73.04"); + assert_eq!( + GspFwRelease::for_driver_version(b"580.196.07"), + GspFwRelease::V580_196_07 + ); + for v in [&b"580.178.04"[..], b"620.73.04", b"", b"580.196.0"] { + assert_eq!( + GspFwRelease::for_driver_version(v), + GspFwRelease::V580_178_04 + ); + } + assert_eq!( + firmware_filename_cstr_for_release( + GspFirmwareChipFamily::Tu10x, + GspFwRelease::V580_196_07 + ), + Some(&b"nvidia/580.196.07/gsp_tu10x.bin\0"[..]) + ); + assert_eq!(GspFwRelease::V580_196_07.fw_version(), "580.196.07"); // A GB20x (RTX 5050) workstation that ships only 620.73.04 still gets a path. assert_eq!( firmware_filename_for_release(GspFirmwareChipFamily::Gb20x, GspFwRelease::V620_73_04), diff --git a/src/nvidia/src/gpu/gsp_split_turing.rs b/src/nvidia/src/gpu/gsp_split_turing.rs new file mode 100644 index 00000000..73952881 --- /dev/null +++ b/src/nvidia/src/gpu/gsp_split_turing.rs @@ -0,0 +1,95 @@ +//! Turing (TU10x / TU11x) values of the kernel side of a GPU run by GSP-RM where they differ from the RTX 3090 the +//! split-RM path (`kernel/ga10x*.rs`) was written against. Mirrors NVIDIA's open 580.178.04 RM: +//! +//! - the engines the kernel side exposes (`kceUpdateClassDB_KERNEL`, `kernel_ce.c:618-657`: the copy engines GSP-RM +//! reports stubbed leave the class DB; `gpuUpdateEngineTable_IMPL`, `gpu.c:4891`: an engine without a class is +//! not listed). A TU116 has five copy engines (COPY0..COPY4, `gpuGetEngClassDescriptorList_TU116`: +//! `TURING_DMA_COPY_A` on CE0..CE4) and no SEC2 class. + +/// `NV2080_ENGINE_TYPE_SEC2`. +const ENGINE_SEC2: u32 = 0x26; +/// `NV2080_ENGINE_TYPE_COPY0` and the copy engines of `NV2080_ENGINE_TYPE_COPY_SIZE`. +const ENGINE_COPY0: u32 = 9; +const ENGINE_COPIES: u32 = 10; + +/// Whether the kernel side exposes engine `t` (`NV2080_ENGINE_TYPE`) of a TU1xx: in `GspStaticConfigInfo.engineCaps`, +/// not SEC2 (no class on a TU1xx), and not a copy engine in `NV2080_CTRL_CE_UPDATE_CLASS_DB_PARAMS.stubbedCeMask`. +pub const fn engine_exposed(caps: &[u32; 3], stubbed_ce_mask: u32, t: u32) -> bool { + if t >= 96 || t == ENGINE_SEC2 { + return false; + } + if t >= ENGINE_COPY0 + && t < ENGINE_COPY0 + ENGINE_COPIES + && stubbed_ce_mask >> (t - ENGINE_COPY0) & 1 != 0 + { + return false; + } + caps[(t / 32) as usize] >> (t % 32) & 1 != 0 +} + +/// `stubbedCeMask` with the copy engines of `engineCaps` that GSP-RM's device info table gave no runlist added +/// (`runlist_valid`: bit t for `RM_ENGINE_TYPE` t, COPY0..9 = 9..18 as `NV2080_ENGINE_TYPE`): a channel on such an +/// engine has no work-submit token (`kfifoGenerateWorkSubmitToken_TU102`, `kernel_fifo_tu102.c:108-113`: a channel +/// without a runlist is NV_ERR_INVALID_STATE), so the engine is not offered to clients. +pub const fn stubbed_without_runlist( + stubbed_ce_mask: u32, + caps: &[u32; 3], + runlist_valid: u64, +) -> u32 { + let mut mask = stubbed_ce_mask; + let mut i = 0; + while i < ENGINE_COPIES { + let t = ENGINE_COPY0 + i; + if caps[0] >> t & 1 != 0 && runlist_valid >> t & 1 == 0 { + mask |= 1 << i; + } + i += 1; + } + mask +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exposed_engines_of_the_gtx_1660_super() { + // engineCaps[0] of the card as GSP-RM 580.178.04 reported it: GR0, COPY0..4, NVDEC0, NVENC0 + let caps = [0x0808_3e02u32, 0, 0]; + for t in [1u32, 9, 10, 11, 12, 13, 0x13, 0x1b] { + assert!(engine_exposed(&caps, 0, t), "{t:#x}"); + } + for t in [0u32, 2, 14, 0x26, 0x33, 95, 96, 200] { + assert!(!engine_exposed(&caps, 0, t), "{t:#x}"); + } + // COPY0, COPY1 and COPY4 stubbed: only COPY2 and COPY3 stay + let stubbed = 0b1_0011; + assert!(!engine_exposed(&caps, stubbed, 9)); + assert!(!engine_exposed(&caps, stubbed, 10)); + assert!(engine_exposed(&caps, stubbed, 11)); + assert!(engine_exposed(&caps, stubbed, 12)); + assert!(!engine_exposed(&caps, stubbed, 13)); + assert!(engine_exposed(&caps, stubbed, 1)); + // SEC2 in the caps is still not exposed + assert!(!engine_exposed(&[0, 1 << 6, 0], 0, 0x26)); + } + + #[test] + fn copy_engines_without_a_runlist_are_not_exposed() { + let caps = [0x0808_3e02u32, 0, 0]; + // every copy engine of the caps has a runlist: nothing added + assert_eq!(stubbed_without_runlist(0, &caps, 0x3e02), 0); + assert_eq!(stubbed_without_runlist(0b1_0000, &caps, 0x3e02), 0b1_0000); + // only GR0, COPY2 and COPY3 with a runlist: COPY0, COPY1 and COPY4 go + let m = stubbed_without_runlist(0, &caps, 1 << 1 | 1 << 11 | 1 << 12); + assert_eq!(m, 0b1_0011); + assert!(!engine_exposed(&caps, m, 9)); + assert!(engine_exposed(&caps, m, 11)); + assert!(engine_exposed(&caps, m, 1)); + // an engine that is not in the caps is not marked + assert_eq!( + stubbed_without_runlist(0, &[0x0000_0e02, 0, 0], 1 << 1), + 0b111 + ); + } +} diff --git a/src/nvidia/src/gpu/gsp_ucode.rs b/src/nvidia/src/gpu/gsp_ucode.rs index adc8fb98..d1d0a925 100644 --- a/src/nvidia/src/gpu/gsp_ucode.rs +++ b/src/nvidia/src/gpu/gsp_ucode.rs @@ -18,6 +18,7 @@ //! so only the families whose image is present here are accepted. use crate::gpu::gsp_boot::GspFirmwareChipFamily; +use crate::gpu::gsp_image::GspFwRelease; /// One bootloader ucode image plus the descriptor fields the WPR metadata needs. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -59,6 +60,64 @@ const GA10X: GspBootUcode = GspBootUcode { pub const BOOTER_LOAD_GA102: &[u8] = include_bytes!("ucode/booter_load_ga102.bin"); pub const BOOTER_UNLOAD_GA102: &[u8] = include_bytes!("ucode/booter_unload_ga102.bin"); +/// Turing Booter Load / Unload in the same layout, rebuilt by `tools/extract_gsp_bindata.py` from +/// `g_bindata_kgspGetBinArchiveBooter{Load,Unload}Ucode_{TU102,TU116}.c` at tag 580.178.04 (MIT, the notice in +/// `licenses/gsp-booter-tu10x-mit.txt`). `kgspGetBinArchiveBooterLoadUcode_HAL` picks TU102 for TU102/TU104/TU106 and +/// TU116 for TU116/TU117 (`g_kernel_gsp_nvoc.c`). +pub const BOOTER_LOAD_TU102: &[u8] = include_bytes!("ucode/booter_load_tu102.bin"); +pub const BOOTER_UNLOAD_TU102: &[u8] = include_bytes!("ucode/booter_unload_tu102.bin"); +pub const BOOTER_LOAD_TU116: &[u8] = include_bytes!("ucode/booter_load_tu116.bin"); +pub const BOOTER_UNLOAD_TU116: &[u8] = include_bytes!("ucode/booter_unload_tu116.bin"); + +/// The generic falcon bootloader (`ksec2GetBinArchiveBlUcode_TU102`, `g_sec2_bl_gp10x.h`) that loads a FWSEC with a +/// `FALCON_UCODE_DESC_V2` on the GSP falcon (`s_prepareHsFalconWithLoader`, `kernel_gsp_falcon_tu102.c`). Its +/// `RM_FLCN_BL_DESC`: `blStartTag` 0xfd, `blDmemDescLoadOff` 0, code at 0 of size 0x200. +pub const FALCON_BL_TU102: &[u8] = include_bytes!("ucode/falcon_bl_tu102.bin"); +pub const FALCON_BL_START_TAG: u32 = 0xfd; +pub const FALCON_BL_CODE_SIZE: u32 = 0x200; + +/// The Booters of tag 580.196.07 (`tools/extract_gsp_bindata.py --release 580.196.07`; the notices in +/// `licenses/gsp-rm-boot-ga102-mit.txt` and `licenses/gsp-booter-tu10x-mit.txt`): new ucode for every family, same +/// layout. The bootloaders of 580.196.07 are byte-identical to 580.178.04's. +const BOOTERS_580_196: [(&[u8], &[u8]); 3] = [ + ( + include_bytes!("ucode/580.196.07/booter_load_tu102.bin"), + include_bytes!("ucode/580.196.07/booter_unload_tu102.bin"), + ), + ( + include_bytes!("ucode/580.196.07/booter_load_tu116.bin"), + include_bytes!("ucode/580.196.07/booter_unload_tu116.bin"), + ), + ( + include_bytes!("ucode/580.196.07/booter_load_ga102.bin"), + include_bytes!("ucode/580.196.07/booter_unload_ga102.bin"), + ), +]; + +/// Booter Load and Unload for a firmware family and GSP-RM release, or `None` when none is bundled. +pub const fn booters_for( + family: GspFirmwareChipFamily, + release: GspFwRelease, +) -> Option<(&'static [u8], &'static [u8])> { + let i = match family { + GspFirmwareChipFamily::Tu10x => 0, + GspFirmwareChipFamily::Tu11x => 1, + GspFirmwareChipFamily::Ga10x => 2, + _ => return None, + }; + match release { + GspFwRelease::V580_178_04 => Some( + [ + (BOOTER_LOAD_TU102, BOOTER_UNLOAD_TU102), + (BOOTER_LOAD_TU116, BOOTER_UNLOAD_TU116), + (BOOTER_LOAD_GA102, BOOTER_UNLOAD_GA102), + ][i], + ), + GspFwRelease::V580_196_07 => Some(BOOTERS_580_196[i]), + _ => None, + } +} + /// Returns the bootloader ucode for a firmware family, or `None` when this tree does /// not carry an embedded image for that family (use [`bootloader_firmware_name`] to load /// via `request_firmware` from `/lib/firmware/nvidia/`). @@ -164,6 +223,35 @@ mod tests { ); } + #[test] + fn turing_booters_follow_the_chip_hal() { + use GspFirmwareChipFamily::*; + let v = GspFwRelease::V580_178_04; + let (l, u) = booters_for(Tu10x, v).unwrap(); + assert_eq!((l.len(), u.len()), (59272, 39304)); + let (l, u) = booters_for(Tu11x, v).unwrap(); + assert_eq!((l.len(), u.len()), (59016, 39048)); + assert_eq!(FALCON_BL_TU102.len(), 768); + assert!(booters_for(Ga100, v).is_none()); + } + + #[test] + fn booters_follow_the_gsp_release() { + use GspFirmwareChipFamily::*; + let n = GspFwRelease::V580_196_07; + for (f, load, unload) in [ + (Tu10x, 59784, 40328), + (Tu11x, 59784, 40328), + (Ga10x, 61816, 42616), + ] { + let (l, u) = booters_for(f, n).unwrap(); + assert_eq!((l.len(), u.len()), (load, unload), "{f:?}"); + let (ol, _) = booters_for(f, GspFwRelease::V580_178_04).unwrap(); + assert_ne!(l, ol, "{f:?}"); + } + assert!(booters_for(Tu10x, GspFwRelease::V620_73_04).is_none()); + } + #[test] fn families_without_a_bundled_image_are_reported_unsupported() { for f in [ diff --git a/src/nvidia/src/gpu/ucode/580.196.07/booter_load_ga102.bin b/src/nvidia/src/gpu/ucode/580.196.07/booter_load_ga102.bin new file mode 100644 index 00000000..b7b492b1 Binary files /dev/null and b/src/nvidia/src/gpu/ucode/580.196.07/booter_load_ga102.bin differ diff --git a/src/nvidia/src/gpu/ucode/580.196.07/booter_load_tu102.bin b/src/nvidia/src/gpu/ucode/580.196.07/booter_load_tu102.bin new file mode 100644 index 00000000..b45ddce2 Binary files /dev/null and b/src/nvidia/src/gpu/ucode/580.196.07/booter_load_tu102.bin differ diff --git a/src/nvidia/src/gpu/ucode/580.196.07/booter_load_tu116.bin b/src/nvidia/src/gpu/ucode/580.196.07/booter_load_tu116.bin new file mode 100644 index 00000000..feb954a1 Binary files /dev/null and b/src/nvidia/src/gpu/ucode/580.196.07/booter_load_tu116.bin differ diff --git a/src/nvidia/src/gpu/ucode/580.196.07/booter_unload_ga102.bin b/src/nvidia/src/gpu/ucode/580.196.07/booter_unload_ga102.bin new file mode 100644 index 00000000..2de07dcf Binary files /dev/null and b/src/nvidia/src/gpu/ucode/580.196.07/booter_unload_ga102.bin differ diff --git a/src/nvidia/src/gpu/ucode/580.196.07/booter_unload_tu102.bin b/src/nvidia/src/gpu/ucode/580.196.07/booter_unload_tu102.bin new file mode 100644 index 00000000..e4ca92da Binary files /dev/null and b/src/nvidia/src/gpu/ucode/580.196.07/booter_unload_tu102.bin differ diff --git a/src/nvidia/src/gpu/ucode/580.196.07/booter_unload_tu116.bin b/src/nvidia/src/gpu/ucode/580.196.07/booter_unload_tu116.bin new file mode 100644 index 00000000..2034229c Binary files /dev/null and b/src/nvidia/src/gpu/ucode/580.196.07/booter_unload_tu116.bin differ diff --git a/src/nvidia/src/gpu/ucode/booter_load_tu102.bin b/src/nvidia/src/gpu/ucode/booter_load_tu102.bin new file mode 100644 index 00000000..3f21cff8 Binary files /dev/null and b/src/nvidia/src/gpu/ucode/booter_load_tu102.bin differ diff --git a/src/nvidia/src/gpu/ucode/booter_load_tu116.bin b/src/nvidia/src/gpu/ucode/booter_load_tu116.bin new file mode 100644 index 00000000..9bdee58d Binary files /dev/null and b/src/nvidia/src/gpu/ucode/booter_load_tu116.bin differ diff --git a/src/nvidia/src/gpu/ucode/booter_unload_tu102.bin b/src/nvidia/src/gpu/ucode/booter_unload_tu102.bin new file mode 100644 index 00000000..3c328594 Binary files /dev/null and b/src/nvidia/src/gpu/ucode/booter_unload_tu102.bin differ diff --git a/src/nvidia/src/gpu/ucode/booter_unload_tu116.bin b/src/nvidia/src/gpu/ucode/booter_unload_tu116.bin new file mode 100644 index 00000000..860891a6 Binary files /dev/null and b/src/nvidia/src/gpu/ucode/booter_unload_tu116.bin differ diff --git a/src/nvidia/src/gpu/ucode/falcon_bl_tu102.bin b/src/nvidia/src/gpu/ucode/falcon_bl_tu102.bin new file mode 100644 index 00000000..e5a5c4cc Binary files /dev/null and b/src/nvidia/src/gpu/ucode/falcon_bl_tu102.bin differ diff --git a/src/nvidia/src/rmapi/gpu_tests.rs b/src/nvidia/src/rmapi/gpu_tests.rs index b3a636d0..9a334d2f 100644 --- a/src/nvidia/src/rmapi/gpu_tests.rs +++ b/src/nvidia/src/rmapi/gpu_tests.rs @@ -3330,3 +3330,104 @@ fn wave9_r620_resized_controls_and_multigen_gsp_ucode_names() { Some(gb203_id) ); } + +/// A GTX 1660 SUPER (TU116, PMC_BOOT_0 0x168000a1), run by GSP-RM on the split-RM path. +fn tu116(minor: u32) -> Gpu { + let mut gpu = v100(minor); + gpu.card.pci_info.device_id = 0x21c4; + gpu.facts = Some(GpuFacts::new(0x1680_00a1, 0x21c4_10de, 0x21c4_10de, 0xa1)); + gpu +} + +/// CUDA's object sequence on a Turing GPU: the channel group, context share, channel, compute and copy objects live +/// in GSP-RM, so nvdriver's own server keeps a placeholder for each handle (the kernel's gsp_route.rs makes the +/// GSP-RM object). A group that falls through to the native constructor, which has no engine on a GSP-RM GPU, is +/// NV_ERR_NOT_SUPPORTED: the "RM_ALLOC class=0xa06c status=0x56" a TU116 gave on hardware before its classes were +/// placeholders. +#[test] +fn turing_gsp_objects_get_placeholders_and_other_gpus_keep_their_constructors() { + let who = caller(0, false, 1); + let devices = |gpu: Gpu| { + let mut node = Box::new(Node::new()); + node.gpus.add(gpu).unwrap(); + node.gpu_open(0).unwrap(); + let client = root(&mut node, &who); + let (st, device) = alloc(&mut node, &who, client, CLASS_DEVICE, &device_block(client)); + assert_eq!(st, 0); + let (st, _subdevice) = alloc(&mut node, &who, device, CLASS_SUBDEVICE, &[0; 4]); + assert_eq!(st, 0); + (node, device) + }; + let zeros = [0u8; 0x200]; + // NV0005_ALLOC_PARAMETERS of an event on an object of the caller's own client (hParentClient) + let mut event_params = [0u8; 0x200]; + event_params[0..4].copy_from_slice(&0xc1d0_0000u32.to_le_bytes()); + + let (mut node, device) = devices(tu116(0)); + assert!(node + .gpus + .facts_mut(0xb300) + .is_some_and(|f| f.is_gsp_rm() && !f.is_ga10x())); + let (st, group) = alloc(&mut node, &who, device, 0xa06c, &zeros); + assert_eq!(st, 0, "KEPLER_CHANNEL_GROUP_A on a TU116"); + let (st, _share) = alloc(&mut node, &who, group, 0x9067, &zeros); + assert_eq!(st, 0, "FERMI_CONTEXT_SHARE_A"); + let (st, channel) = alloc(&mut node, &who, group, 0xc46f, &zeros); + assert_eq!(st, 0, "TURING_CHANNEL_GPFIFO_A"); + for class in [0xc5c0u32, 0xc5b5, 0xc597] { + let (st, _) = alloc(&mut node, &who, channel, class, &zeros); + assert_eq!(st, 0, "class {class:#x} under a Turing channel"); + } + // each is a plain child (`Kind::BinaryApi`): nothing of the native channel table is behind the handles + for handle in [group, channel] { + assert!(node + .classes + .find(0xc1d0_0000, handle) + .is_some_and(|e| e.kind == Kind::BinaryApi)); + } + // an event below a GSP-RM object is GSP-RM's too (gsp_route.rs forwards it): a placeholder, as on a GA102 + let (st, event) = alloc(&mut node, &who, channel, 0x79, &event_params); + assert_eq!(st, 0, "NV01_EVENT_OS_EVENT under a Turing channel"); + assert!(node + .classes + .find(0xc1d0_0000, event) + .is_some_and(|e| e.kind == Kind::BinaryApi)); + // the usermode window stays the kernel side's own register window (NV_VIRTUAL_FUNCTION + 0x30000) + let (st, _) = alloc(&mut node, &who, device, 0xc461, &zeros); + assert_ne!(st, status::NOT_SUPPORTED.0); + + // a GV100 keeps its own constructor: with no engine behind the test node the group is NOT_SUPPORTED, which is + // what a Turing got before + let (mut node, device) = devices(v100(0)); + assert!(node + .gpus + .facts_mut(0xb300) + .is_some_and(|f| !f.is_gsp_rm() && !f.is_ga10x())); + assert_eq!( + alloc(&mut node, &who, device, 0xa06c, &zeros).0, + status::NOT_SUPPORTED.0 + ); + + // a GA102: its group, channel and events are placeholders as before + let mut ga102 = v100(0); + ga102.facts = Some(GpuFacts::new(0x1720_00a1, 0x2204_10de, 0x2204_10de, 0xa1)); + let (mut node, device) = devices(ga102); + assert!(node + .gpus + .facts_mut(0xb300) + .is_some_and(|f| f.is_ga10x() && f.is_gsp_rm())); + let (st, group) = alloc(&mut node, &who, device, 0xa06c, &zeros); + assert_eq!(st, 0); + let (st, channel) = alloc(&mut node, &who, group, 0xc56f, &zeros); + assert_eq!(st, 0); + assert!(node + .classes + .find(0xc1d0_0000, channel) + .is_some_and(|e| e.kind == Kind::BinaryApi)); + let (st, event) = alloc(&mut node, &who, channel, 0x79, &event_params); + assert_eq!(st, 0); + assert!(node + .classes + .find(0xc1d0_0000, event) + .is_some_and(|e| e.kind == Kind::BinaryApi)); +} diff --git a/tools/extract_gsp_bindata.py b/tools/extract_gsp_bindata.py new file mode 100644 index 00000000..8b71a1c9 --- /dev/null +++ b/tools/extract_gsp_bindata.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Rebuild the SEC2 Booter and generic falcon bootloader images in src/nvidia/src/gpu/ucode/ from NVIDIA's +MIT-licensed open-gpu-kernel-modules checkout at tag 580.178.04 (src/nvidia/generated/g_bindata_*.c). + +Booters are written as nvfw_bin_hdr + nvfw_hs_header_v2 + nvfw_hs_load_header_v2 with the production image and +signatures (the layout nouveau and linux-firmware use, and ga10x_gsp::parse_booter reads). --check compares +instead of writing; the GA102 images already in the tree reproduce byte for byte. + +The images in ucode/ come from tag 580.178.04. --release 580.196.07 writes the Booters of a checkout of that tag +into ucode/580.196.07/ (its bootloaders are byte-identical to 580.178.04's, so they are not duplicated). + + python3 tools/extract_gsp_bindata.py --ogkm ~/open-gpu-kernel-modules [--release 580.196.07] [--check] +""" +import argparse +import pathlib +import re +import struct +import sys +import zlib + +UCODE = pathlib.Path(__file__).resolve().parent.parent / "src/nvidia/src/gpu/ucode" +BOOTERS = { + "booter_load_ga102.bin": "BooterLoadUcode_GA102", + "booter_unload_ga102.bin": "BooterUnloadUcode_GA102", + "booter_load_tu102.bin": "BooterLoadUcode_TU102", + "booter_unload_tu102.bin": "BooterUnloadUcode_TU102", + "booter_load_tu116.bin": "BooterLoadUcode_TU116", + "booter_unload_tu116.bin": "BooterUnloadUcode_TU116", +} +ENTRY = re.compile( + r'// FUNCTION: \w+\("(\w+)"\)\n(?://.*\n)*?// COMPRESSION: (\w+)\n(?://.*\n)*?' + r'static BINDATA_CONST NvU8 \w+\[\] = \s*\{([^}]*)\}' +) + + +def labels(path): + out = {} + for m in ENTRY.finditer(path.read_text()): + raw = bytes(int(x, 16) for x in re.findall(r"0x([0-9a-fA-F]{2})", m.group(3))) + out[m.group(1)] = zlib.decompress(raw, -15) if m.group(2) == "YES" else raw + return out + + +def booter(path): + b = labels(path) + sig = b["BINDATA_LABEL_SIG_PROD"] + tail = [b[k] for k in ("BINDATA_LABEL_PATCH_LOC", "BINDATA_LABEL_PATCH_SIG", "BINDATA_LABEL_PATCH_META", + "BINDATA_LABEL_NUM_SIGS", "BINDATA_LABEL_HEADER_PROD")] + offs, o = [], 0x18 + 0x24 + len(sig) + for t in tail: + offs.append(o) + o += len(t) + image = b["BINDATA_LABEL_IMAGE_PROD"] + hs = struct.pack("<9I", 0x3c, len(sig), offs[0], offs[1], offs[2], len(tail[2]), offs[3], offs[4], len(tail[4])) + size = o + len(image) + hdr = struct.pack("<6I", 0x10DE, 1, (size + 0xFF) & ~0xFF, 0x18, o, len(image)) + return hdr + hs + sig + b"".join(tail) + image + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ogkm", required=True, type=pathlib.Path) + ap.add_argument("--release", help="write the Booters into ucode//") + ap.add_argument("--check", action="store_true") + a = ap.parse_args() + gen = a.ogkm / "src/nvidia/generated" + images = {name: booter(gen / f"g_bindata_kgspGetBinArchive{src}.c") for name, src in BOOTERS.items()} + out = UCODE / a.release if a.release else UCODE + if not a.release: + bl = labels(gen / "g_bindata_ksec2GetBinArchiveBlUcode_TU102.c") + images["falcon_bl_tu102.bin"] = bl["BINDATA_LABEL_UCODE_IMAGE"] + if not a.check: + out.mkdir(exist_ok=True) + bad = 0 + for name, data in images.items(): + path = out / name + if a.check: + same = path.exists() and path.read_bytes() == data + print(("ok " if same else "DIFF ") + name) + bad += not same + else: + path.write_bytes(data) + print(f"wrote {name} ({len(data)} bytes)") + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main())