From 85bf43e3fcfe833794c094823a09e9c3447424b6 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 3 Dec 2026 01:18:36 +0800 Subject: [PATCH 1/6] feat(lspci): normalize PCI addresses to one spelling Signed-off-by: Leechael Yim --- dstack/lspci/src/bdf.rs | 94 +++++++++++++++++++++++++++++++++++++++++ dstack/lspci/src/lib.rs | 3 ++ 2 files changed, 97 insertions(+) create mode 100644 dstack/lspci/src/bdf.rs diff --git a/dstack/lspci/src/bdf.rs b/dstack/lspci/src/bdf.rs new file mode 100644 index 000000000..e5ebf4d02 --- /dev/null +++ b/dstack/lspci/src/bdf.rs @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! One spelling for a PCI address. +//! +//! The same device reaches dstack written three ways: `1b:00.0` in a VM +//! manifest and QEMU's `host=`, `0000:1b:00.0` from `lspci -D` and sysfs, and +//! `00000000:1b:00.0` from NVML. Comparing them as strings silently fails, so +//! every comparison goes through [`normalize_bdf`]. + +/// Rewrites a PCI address as `dddd:bb:dd.f`, lowercase. +/// +/// Accepts an address with or without the domain, and a domain of up to eight +/// hex digits as NVML writes it. A missing domain is domain 0, which is what +/// QEMU's `vfio-pci,host=` assumes too. Returns `None` for anything that is not +/// a PCI address, rather than passing it through. +pub fn normalize_bdf(address: &str) -> Option { + let mut parts = address.trim().rsplitn(3, ':'); + let device_function = parts.next()?; + let bus = parts.next()?; + let domain = parts.next().unwrap_or("0"); + let (device, function) = device_function.split_once('.')?; + + let domain = parse_hex(domain, 8)?; + let bus = parse_hex(bus, 2)?; + let device = parse_hex(device, 2)?; + let function = parse_hex(function, 1)?; + if domain > 0xffff || device > 0x1f || function > 7 { + return None; + } + Some(format!("{domain:04x}:{bus:02x}:{device:02x}.{function:x}")) +} + +fn parse_hex(digits: &str, max_len: usize) -> Option { + if digits.is_empty() || digits.len() > max_len { + return None; + } + if !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return None; + } + u32::from_str_radix(digits, 16).ok() +} + +#[cfg(test)] +mod tests { + use super::normalize_bdf; + + #[test] + fn every_spelling_of_one_device_normalizes_to_the_same_address() { + for spelling in [ + "1b:00.0", + "0000:1b:00.0", + "00000000:1b:00.0", + "0000:1B:00.0", + ] { + assert_eq!( + normalize_bdf(spelling).as_deref(), + Some("0000:1b:00.0"), + "{spelling}" + ); + } + } + + #[test] + fn a_non_zero_domain_is_kept() { + assert_eq!( + normalize_bdf("0001:4a:00.0").as_deref(), + Some("0001:4a:00.0") + ); + assert_eq!( + normalize_bdf("00000001:4a:00.0").as_deref(), + Some("0001:4a:00.0") + ); + } + + #[test] + fn anything_that_is_not_a_pci_address_is_rejected() { + for input in [ + "", + "1b:00", + "0f.00.0", + "zz:00.0", + "0f:20.0", + "1b:00.8", + "100:00.0", + "1b:00.0,bus=pci.1", + "1:0000:1b:00.0", + "000100000:1b:00.0", + ] { + assert_eq!(normalize_bdf(input), None, "{input:?}"); + } + } +} diff --git a/dstack/lspci/src/lib.rs b/dstack/lspci/src/lib.rs index 10c84e70e..dd875a580 100644 --- a/dstack/lspci/src/lib.rs +++ b/dstack/lspci/src/lib.rs @@ -6,8 +6,11 @@ use std::process::Command; use anyhow::{Context, Result}; +mod bdf; pub mod sysfs; +pub use bdf::normalize_bdf; + /// Represents a PCI device with the specified fields. #[derive(Debug)] pub struct Device { From 18f712d1bb2b6bc5915bd016a445b43942dbf0e4 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 3 Dec 2026 01:18:36 +0800 Subject: [PATCH 2/6] feat(vmm): read each VFIO device's guest and host address from the running QEMU Signed-off-by: Leechael Yim --- dstack/vmm/src/app.rs | 52 +++++ dstack/vmm/src/app/passthrough.rs | 344 ++++++++++++++++++++++++++++++ 2 files changed, 396 insertions(+) create mode 100644 dstack/vmm/src/app/passthrough.rs diff --git a/dstack/vmm/src/app.rs b/dstack/vmm/src/app.rs index a85f25136..c24860964 100644 --- a/dstack/vmm/src/app.rs +++ b/dstack/vmm/src/app.rs @@ -49,6 +49,7 @@ pub(crate) use network::{ resolved_networks, settle_vhost, stranded_ingress, validate_resolved_network, validate_resolved_networks, }; +pub(crate) use passthrough::PassthroughDevice; pub use qemu::VmConfig; // Exported so the RPC layer can assert that everything it reports is // something it also accepts. @@ -61,6 +62,7 @@ mod id_pool; mod image; mod mr_config; pub(crate) mod network; +mod passthrough; mod qemu; mod vm_info; mod workdir; @@ -1835,6 +1837,37 @@ impl App { )) } + /// The id of the VM that owns a vsock CID. + pub(crate) fn vm_id_by_cid(&self, cid: u32) -> Result { + Ok(self + .lock() + .vms + .values() + .find(|vm| vm.config.cid == cid) + .context("VM not found")? + .config + .manifest + .id + .clone()) + } + + /// Host and guest PCI address of each VFIO device of a running VM. + /// + /// Read from the command line of the QEMU that is running, so it holds for + /// a VM launched by an earlier VMM version too. See [`passthrough`]. + pub(crate) async fn passthrough_devices(&self, id: &str) -> Result> { + let info = self + .supervisor + .info(id) + .await? + .context("VM is not running")?; + if !info.state.status.is_running() { + bail!("VM is not running"); + } + let args = qemu_args(&info.config.args)?; + passthrough::passthrough_devices(&args) + } + fn try_allocate_gpus(&self, manifest: &Manifest) -> Result { if !self.config.cvm.gpu.enabled { return Ok(GpuConfig::default()); @@ -2489,6 +2522,25 @@ pub(crate) fn needs_swtpm( && !simulated_tee.is_some_and(mock_attestation::platform_provides_tpm) } +/// QEMU's arguments from a supervisor process. A VM that needs sidecars runs +/// under `dstack-vmm vm-launcher --spec `, and QEMU's arguments are in +/// that file instead. +fn qemu_args(process_args: &[String]) -> Result> { + if process_args.first().map(String::as_str) != Some("vm-launcher") { + return Ok(process_args.to_vec()); + } + let spec_path = process_args + .windows(2) + .find(|pair| pair[0] == "--spec") + .map(|pair| &pair[1]) + .context("vm-launcher has no --spec")?; + let spec: crate::vm_launcher::LaunchSpec = serde_json::from_slice( + &fs::read(spec_path).context("failed to read the VM launch specification")?, + ) + .context("invalid VM launch specification")?; + Ok(spec.qemu.args) +} + #[cfg(test)] mod tests { use super::mr_config::{mr_config_version, MrConfigVersion, MR_CONFIG_V3_REQUIRED}; diff --git a/dstack/vmm/src/app/passthrough.rs b/dstack/vmm/src/app/passthrough.rs new file mode 100644 index 000000000..8cc657e6d --- /dev/null +++ b/dstack/vmm/src/app/passthrough.rs @@ -0,0 +1,344 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! Where each VFIO device of a running VM sits, on the host and in the guest. +//! +//! The guest reports GPU telemetry by its own PCI address and the host reports +//! link health by the host's. Nothing either side sees ties the two together, +//! but the QEMU command line does: each `vfio-pci,host=` hangs off a +//! `pcie-root-port`, and the guest firmware numbers root-port buses in a fixed +//! order. +//! +//! The pairing is read from the command line of the QEMU that is running, not +//! rebuilt from the manifest. A VM keeps the layout of the VMM version that +//! launched it, so recomputing it with this version's layout code would be +//! wrong for a VM started before an upgrade. +//! +//! Bus numbering, as OVMF assigns it: +//! +//! - Root ports on `pcie.0` get buses 1, 2, ... in slot order. QEMU gives a +//! device without `addr=` the lowest free slot, so slot order is command +//! order. +//! - Root ports on a `pxb-pcie` expander get `bus_nr + 1`, `bus_nr + 2`, ... +//! in command order. The expander's own root bus is `bus_nr`. +//! - The device behind a root port is device 0, function 0 of that bus. +//! +//! Only layouts that dstack-vmm builds are recognized. Anything else, such as a +//! bridge type it never emits or an explicit `addr=`, yields no pairing at all +//! rather than a guess: a wrong label is worse than a missing one. + +use std::collections::HashMap; + +use anyhow::{bail, Context, Result}; + +/// The root complex every layout starts from. +const ROOT_BUS: &str = "pcie.0"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct PassthroughDevice { + /// `dddd:bb:dd.f` as the guest sees it. + pub guest_bdf: String, + /// `dddd:bb:dd.f` on the host. + pub host_bdf: String, +} + +/// One `-device` argument, split into its driver and properties. +struct DeviceArg<'a> { + driver: &'a str, + props: HashMap<&'a str, &'a str>, +} + +impl<'a> DeviceArg<'a> { + fn parse(value: &'a str) -> Self { + let mut items = value.split(','); + let driver = items.next().unwrap_or_default(); + let props = items.filter_map(|item| item.split_once('=')).collect(); + Self { driver, props } + } + + fn get(&self, key: &str) -> Option<&'a str> { + self.props.get(key).copied() + } + + fn require(&self, key: &str) -> Result<&'a str> { + self.get(key) + .with_context(|| format!("{} has no {key}=", self.driver)) + } +} + +/// Reads the guest and host address of every VFIO device in a QEMU command. +/// +/// `args` is everything after the executable, and may start with a `taskset` +/// prefix; only `-device` arguments are looked at. Fails on a layout that +/// dstack-vmm does not build. +pub(crate) fn passthrough_devices(args: &[String]) -> Result> { + let devices: Vec = args + .windows(2) + .filter(|pair| pair[0] == "-device") + .map(|pair| DeviceArg::parse(&pair[1])) + .collect(); + + // Root bus number of each expander, by its id. + let mut expanders: HashMap<&str, u32> = HashMap::new(); + // Guest bus of each root port, by its id. + let mut root_ports: HashMap<&str, u32> = HashMap::new(); + // Root ports seen so far on each parent bus. + let mut ports_on: HashMap<&str, u32> = HashMap::new(); + let mut vfio = Vec::new(); + + for device in &devices { + match device.driver { + "pxb-pcie" => { + if device.require("bus")? != ROOT_BUS { + bail!("pxb-pcie off {ROOT_BUS} is not a dstack layout"); + } + let bus_nr = device + .require("bus_nr")? + .parse() + .context("invalid pxb-pcie bus_nr")?; + expanders.insert(device.require("id")?, bus_nr); + } + "pcie-root-port" => { + if device.get("addr").is_some() { + bail!("pcie-root-port with an explicit addr is not a dstack layout"); + } + let parent = device.require("bus")?; + let first_bus = if parent == ROOT_BUS { + 1 + } else { + *expanders + .get(parent) + .with_context(|| format!("pcie-root-port on unknown bus {parent}"))? + + 1 + }; + let index = ports_on.entry(parent).or_default(); + root_ports.insert(device.require("id")?, first_bus + *index); + *index += 1; + } + "vfio-pci" => { + if device.get("addr").is_some_and(|addr| !is_slot_zero(addr)) { + bail!("vfio-pci at a non-zero addr is not a dstack layout"); + } + vfio.push(device); + } + driver if creates_bus(driver) => { + bail!("{driver} is not a dstack layout"); + } + _ => {} + } + } + + vfio.into_iter() + .map(|device| { + let host = device.require("host")?; + let host_bdf = lspci::normalize_bdf(host) + .with_context(|| format!("invalid vfio-pci host address {host}"))?; + let port = device.require("bus")?; + let bus = root_ports + .get(port) + .with_context(|| format!("vfio-pci {host} is not behind a known root port"))?; + if *bus > 0xff { + bail!("guest bus {bus} of {host} is out of range"); + } + Ok(PassthroughDevice { + guest_bdf: format!("0000:{bus:02x}:00.0"), + host_bdf, + }) + }) + .collect() +} + +/// Bridges and expanders dstack-vmm never emits. Any of them would shift the +/// bus numbers this module assumes. +fn creates_bus(driver: &str) -> bool { + driver.contains("bridge") + || driver.contains("pxb") + || driver.contains("root-port") + || driver.contains("upstream") + || driver.contains("downstream") + || driver == "ioh3420" +} + +fn is_slot_zero(addr: &str) -> bool { + let slot = addr.split('.').next().unwrap_or(addr); + let slot = slot.trim_start_matches("0x"); + u32::from_str_radix(slot, 16).is_ok_and(|slot| slot == 0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(devices: &[&str]) -> Vec { + let mut args = vec![ + "-accel".to_string(), + "kvm".into(), + "-device".into(), + "virtio-net-pci,netdev=net0".into(), + ]; + for device in devices { + args.push("-device".into()); + args.push(device.to_string()); + } + args.extend(["-smp".into(), "8".into()]); + args + } + + fn pairs(devices: Vec) -> Vec<(String, String)> { + devices + .into_iter() + .map(|device| (device.guest_bdf, device.host_bdf)) + .collect() + } + + fn owned(pairs: &[(&str, &str)]) -> Vec<(String, String)> { + pairs + .iter() + .map(|(guest, host)| (guest.to_string(), host.to_string())) + .collect() + } + + /// Four GPUs on a non-zero host PCI domain, one root port each. + #[test] + fn flat_layout_numbers_buses_in_command_order() { + let command = args(&[ + "pcie-root-port,id=pci.1,bus=pcie.0,chassis=1", + "vfio-pci,host=0001:1a:00.0,bus=pci.1,iommufd=iommufd0", + "pcie-root-port,id=pci.2,bus=pcie.0,chassis=2", + "vfio-pci,host=0001:2a:00.0,bus=pci.2,iommufd=iommufd0", + "pcie-root-port,id=pci.3,bus=pcie.0,chassis=3", + "vfio-pci,host=0001:3a:00.0,bus=pci.3,iommufd=iommufd0", + "pcie-root-port,id=pci.4,bus=pcie.0,chassis=4", + "vfio-pci,host=0001:4a:00.0,bus=pci.4,iommufd=iommufd0", + ]); + assert_eq!( + pairs(passthrough_devices(&command).unwrap()), + owned(&[ + ("0000:01:00.0", "0001:1a:00.0"), + ("0000:02:00.0", "0001:2a:00.0"), + ("0000:03:00.0", "0001:3a:00.0"), + ("0000:04:00.0", "0001:4a:00.0"), + ]) + ); + } + + /// The guest bus follows the command, not the host address: a list handed + /// over out of order stays out of order. + #[test] + fn host_order_does_not_decide_the_guest_bus() { + let command = args(&[ + "pcie-root-port,id=pci.1,bus=pcie.0,chassis=1", + "vfio-pci,host=8b:00.0,bus=pci.1,iommufd=iommufd0", + "pcie-root-port,id=pci.2,bus=pcie.0,chassis=2", + "vfio-pci,host=1b:00.0,bus=pci.2,iommufd=iommufd0", + ]); + assert_eq!( + pairs(passthrough_devices(&command).unwrap()), + owned(&[ + ("0000:01:00.0", "0000:8b:00.0"), + ("0000:02:00.0", "0000:1b:00.0"), + ]) + ); + } + + /// Short host addresses, as a manifest may carry them, and four + /// NVSwitches after the GPUs. + #[test] + fn short_host_addresses_and_nvswitches_are_included() { + let mut devices = Vec::new(); + let hosts = [ + "1b:00.0", "2b:00.0", "3b:00.0", "4b:00.0", "5b:00.0", "6b:00.0", "7b:00.0", "8b:00.0", + "05:00.0", "06:00.0", "07:00.0", "08:00.0", + ]; + for (index, host) in hosts.iter().enumerate() { + let n = index + 1; + devices.push(format!("pcie-root-port,id=pci.{n},bus=pcie.0,chassis={n}")); + devices.push(format!("vfio-pci,host={host},bus=pci.{n},iommufd=iommufd0")); + } + let devices: Vec<&str> = devices.iter().map(String::as_str).collect(); + let found = passthrough_devices(&args(&devices)).unwrap(); + assert_eq!(found.len(), 12); + assert_eq!(found[0].guest_bdf, "0000:01:00.0"); + assert_eq!(found[0].host_bdf, "0000:1b:00.0"); + assert_eq!(found[11].guest_bdf, "0000:0c:00.0"); + assert_eq!(found[11].host_bdf, "0000:08:00.0"); + } + + /// Hugepage layout: GPUs on per-node expanders, NVSwitches on pcie.0. + /// Bus numbers match what `pxb_buses` hands out for two nodes of two GPUs. + #[test] + fn expander_layout_numbers_buses_from_each_bus_nr() { + let command = args(&[ + "pxb-pcie,id=pcie.node0,bus=pcie.0,addr=0x10,numa_node=0,bus_nr=5", + "pxb-pcie,id=pcie.node1,bus=pcie.0,addr=0x11,numa_node=1,bus_nr=8", + "pcie-root-port,id=pci.1,bus=pcie.node0,chassis=1", + "vfio-pci,host=1b:00.0,bus=pci.1,iommufd=iommufd0", + "pcie-root-port,id=pci.2,bus=pcie.node0,chassis=2", + "vfio-pci,host=2b:00.0,bus=pci.2,iommufd=iommufd0", + "pcie-root-port,id=pci.3,bus=pcie.node1,chassis=3", + "vfio-pci,host=5b:00.0,bus=pci.3,iommufd=iommufd0", + "pcie-root-port,id=pci.4,bus=pcie.node1,chassis=4", + "vfio-pci,host=6b:00.0,bus=pci.4,iommufd=iommufd0", + "pcie-root-port,id=pci.5,bus=pcie.0,chassis=5", + "vfio-pci,host=05:00.0,bus=pci.5,iommufd=iommufd0", + ]); + assert_eq!( + pairs(passthrough_devices(&command).unwrap()), + owned(&[ + ("0000:06:00.0", "0000:1b:00.0"), + ("0000:07:00.0", "0000:2b:00.0"), + ("0000:09:00.0", "0000:5b:00.0"), + ("0000:0a:00.0", "0000:6b:00.0"), + ("0000:01:00.0", "0000:05:00.0"), + ]) + ); + } + + #[test] + fn a_vm_without_passthrough_has_no_devices() { + assert!(passthrough_devices(&args(&[])).unwrap().is_empty()); + } + + /// The `taskset` prefix of a NUMA-pinned VM does not get in the way. + #[test] + fn a_taskset_prefix_is_ignored() { + let mut command = vec!["-c".to_string(), "0-31".into(), "/usr/bin/qemu".into()]; + command.extend(args(&[ + "pcie-root-port,id=pci.1,bus=pcie.0,chassis=1", + "vfio-pci,host=1b:00.0,bus=pci.1,iommufd=iommufd0", + ])); + assert_eq!(passthrough_devices(&command).unwrap().len(), 1); + } + + /// Layouts dstack-vmm never builds shift bus numbers in ways this module + /// does not model, so they must fail instead of producing a wrong pairing. + #[test] + fn unknown_layouts_are_refused() { + for devices in [ + &[ + "pcie-pci-bridge,id=br0,bus=pcie.0", + "pcie-root-port,id=pci.1,bus=pcie.0,chassis=1", + "vfio-pci,host=1b:00.0,bus=pci.1", + ][..], + &[ + "pcie-root-port,id=pci.1,bus=pcie.0,chassis=1,addr=0x5", + "vfio-pci,host=1b:00.0,bus=pci.1", + ][..], + &["vfio-pci,host=1b:00.0,bus=pcie.0"][..], + &[ + "pcie-root-port,id=pci.1,bus=pcie.node9,chassis=1", + "vfio-pci,host=1b:00.0,bus=pci.1", + ][..], + &[ + "pcie-root-port,id=pci.1,bus=pcie.0,chassis=1", + "vfio-pci,host=not-a-bdf,bus=pci.1", + ][..], + ] { + assert!( + passthrough_devices(&args(devices)).is_err(), + "{devices:?} should be refused" + ); + } + } +} From 39dfc67cf41c7d8b86f77ab61fd0b33c089fd77d Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 3 Dec 2026 01:18:36 +0800 Subject: [PATCH 3/6] feat(vmm): fill GPU host PCI addresses in the GpuInfo relay Signed-off-by: Leechael Yim --- dstack/dstack-util/src/gpu_info.rs | 3 + dstack/guest-api/proto/guest_api.proto | 4 + dstack/guest-api/src/lib.rs | 1 + dstack/vmm/src/guest_api_service.rs | 106 ++++++++++++++++++++++++- 4 files changed, 113 insertions(+), 1 deletion(-) diff --git a/dstack/dstack-util/src/gpu_info.rs b/dstack/dstack-util/src/gpu_info.rs index ea634b16d..4a9c16f7b 100644 --- a/dstack/dstack-util/src/gpu_info.rs +++ b/dstack/dstack-util/src/gpu_info.rs @@ -205,6 +205,8 @@ fn collect_device_fields(sampler: &mut Sampler, index: u32, device: &Device<'_>) temperature_c, power_usage_mw, errors, + // Only the host knows it; the guest agent fills it in. + host_pci_bus_id: String::new(), } } @@ -266,6 +268,7 @@ mod tests { temperature_c: Some(40), power_usage_mw: None, errors: vec!["power: not supported".into()], + host_pci_bus_id: String::new(), }], error: String::new(), cc_ready: Some(true), diff --git a/dstack/guest-api/proto/guest_api.proto b/dstack/guest-api/proto/guest_api.proto index 9e2a9f990..9d5d4cb5b 100644 --- a/dstack/guest-api/proto/guest_api.proto +++ b/dstack/guest-api/proto/guest_api.proto @@ -158,6 +158,10 @@ message GpuDevice { optional uint32 power_usage_mw = 10; // Failed queries for this card, one per entry; empty if all fields succeeded repeated string errors = 11; + // PCI address of this card on the host, dddd:bb:dd.f. Reported by the host + // and not verifiable by the guest: use it to label telemetry, never for a + // security decision. Empty when the host did not report one. + string host_pci_bus_id = 12; } // GPU inventory collected through NVML. diff --git a/dstack/guest-api/src/lib.rs b/dstack/guest-api/src/lib.rs index 36aae1ad1..df3e0a353 100644 --- a/dstack/guest-api/src/lib.rs +++ b/dstack/guest-api/src/lib.rs @@ -38,6 +38,7 @@ mod tests { temperature_c: Some(0), power_usage_mw: None, errors: vec!["temperature: timeout".into()], + host_pci_bus_id: "0001:1a:00.0".into(), }], }; let bytes = original.encode_to_vec(); diff --git a/dstack/vmm/src/guest_api_service.rs b/dstack/vmm/src/guest_api_service.rs index 439df00d1..95b235ac5 100644 --- a/dstack/vmm/src/guest_api_service.rs +++ b/dstack/vmm/src/guest_api_service.rs @@ -10,6 +10,9 @@ use guest_api::{ }; use ra_rpc::{CallContext, RpcCall}; use std::ops::Deref; +use tracing::{debug, warn}; + +use crate::app::PassthroughDevice; pub struct GuestApiHandler { state: AppState, @@ -43,7 +46,22 @@ impl ProxiedGuestApiRpc for GuestApiHandler { } async fn gpu_info(self, request: Id) -> Result { - self.guest_agent_client(&request.id)?.gpu_info().await + let mut response = self.guest_agent_client(&request.id)?.gpu_info().await?; + // A guest agent from before `host_pci_bus_id` existed leaves it empty; + // fill it here so the control plane gets it from every image. + if response + .gpus + .iter() + .any(|gpu| gpu.host_pci_bus_id.is_empty()) + { + match self.passthrough_devices(&request.id).await { + Ok(devices) => fill_host_pci_bus_ids(&request.id, &mut response, &devices), + Err(err) => { + debug!(id = request.id, "no GPU host addresses: {err:#}"); + } + } + } + Ok(response) } async fn network_info(self, request: Id) -> Result { @@ -60,3 +78,89 @@ impl ProxiedGuestApiRpc for GuestApiHandler { self.guest_agent_client(&request.id)?.shutdown().await } } + +/// Sets the host address of each GPU the guest reported without one. +/// +/// A value the guest already set is kept: it came from this same host through +/// `HostApi.GpuTopology`. A disagreement is logged, since both are read from +/// the running QEMU and should never differ. +fn fill_host_pci_bus_ids(id: &str, response: &mut GpuInfoResponse, devices: &[PassthroughDevice]) { + for gpu in &mut response.gpus { + let Some(guest_bdf) = lspci::normalize_bdf(&gpu.pci_bus_id) else { + continue; + }; + let Some(device) = devices.iter().find(|device| device.guest_bdf == guest_bdf) else { + continue; + }; + if gpu.host_pci_bus_id.is_empty() { + gpu.host_pci_bus_id = device.host_bdf.clone(); + } else if gpu.host_pci_bus_id != device.host_bdf { + warn!( + id, + guest = guest_bdf, + reported = gpu.host_pci_bus_id, + expected = device.host_bdf, + "guest reported a different GPU host address" + ); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use guest_api::GpuDevice; + + fn device(guest: &str, host: &str) -> PassthroughDevice { + PassthroughDevice { + guest_bdf: guest.into(), + host_bdf: host.into(), + } + } + + fn gpu(index: u32, pci_bus_id: &str, host: &str) -> GpuDevice { + GpuDevice { + index, + pci_bus_id: pci_bus_id.into(), + host_pci_bus_id: host.into(), + ..Default::default() + } + } + + #[test] + fn gpus_are_matched_by_the_guest_address_nvml_reports() { + let mut response = GpuInfoResponse { + gpus: vec![ + gpu(0, "00000000:01:00.0", ""), + gpu(1, "00000000:02:00.0", ""), + gpu(2, "00000000:09:00.0", ""), + ], + ..Default::default() + }; + let devices = [ + device("0000:02:00.0", "0000:2b:00.0"), + device("0000:01:00.0", "0000:1b:00.0"), + ]; + fill_host_pci_bus_ids("vm", &mut response, &devices); + let hosts: Vec<_> = response + .gpus + .iter() + .map(|gpu| gpu.host_pci_bus_id.as_str()) + .collect(); + assert_eq!(hosts, ["0000:1b:00.0", "0000:2b:00.0", ""]); + } + + #[test] + fn a_value_the_guest_set_is_kept() { + let mut response = GpuInfoResponse { + gpus: vec![gpu(0, "00000000:01:00.0", "0000:aa:00.0")], + ..Default::default() + }; + fill_host_pci_bus_ids( + "vm", + &mut response, + &[device("0000:01:00.0", "0000:1b:00.0")], + ); + assert_eq!(response.gpus[0].host_pci_bus_id, "0000:aa:00.0"); + } +} From 1e8c989cc43cf027b73d140442f76e867ff08fa1 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 3 Dec 2026 01:18:36 +0800 Subject: [PATCH 4/6] feat(vmm): serve GpuTopology to guests behind cvm.gpu.share_host_address Signed-off-by: Leechael Yim --- dstack/host-api/proto/host_api.proto | 19 +++++++++++++++++++ dstack/vmm/src/config.rs | 3 +++ dstack/vmm/src/gpu_reset.rs | 1 + dstack/vmm/src/host_api_service.rs | 20 +++++++++++++++++++- dstack/vmm/vmm.toml | 8 ++++++++ 5 files changed, 50 insertions(+), 1 deletion(-) diff --git a/dstack/host-api/proto/host_api.proto b/dstack/host-api/proto/host_api.proto index 85106ed6e..af40579a3 100644 --- a/dstack/host-api/proto/host_api.proto +++ b/dstack/host-api/proto/host_api.proto @@ -33,6 +33,23 @@ message SealedEnv { bytes sealed_env = 1; } +// A device the host passed through to the guest with VFIO. +message PassthroughDevice { + // PCI address as the guest sees it, dddd:bb:dd.f + string guest_bdf = 1; + // PCI address on the host, dddd:bb:dd.f + string host_bdf = 2; +} + +// Where each passed-through device sits on the host. +// +// Reported by the host and not verifiable by the guest: use it to label +// telemetry, never for a security decision. Empty when the VM has no +// passthrough devices, or when the host cannot tell how QEMU laid them out. +message GpuTopologyResponse { + repeated PassthroughDevice devices = 1; +} + service HostApi { rpc Info(google.protobuf.Empty) returns (HostInfo); rpc Notify(Notification) returns (google.protobuf.Empty); @@ -42,4 +59,6 @@ service HostApi { // answer means the window is closed, and the guest starts application code // only after one. rpc UpdateSealedEnv(SealedEnv) returns (google.protobuf.Empty); + // The host PCI address of each GPU and NVSwitch passed through to this VM. + rpc GpuTopology(google.protobuf.Empty) returns (GpuTopologyResponse); } diff --git a/dstack/vmm/src/config.rs b/dstack/vmm/src/config.rs index 4f76e742a..2b664a4d8 100644 --- a/dstack/vmm/src/config.rs +++ b/dstack/vmm/src/config.rs @@ -606,6 +606,9 @@ pub struct GpuConfig { pub sanitize_on_attach: bool, /// Shared deadline for all GPUs to become VFIO-ready after SBR. pub sbr_timeout_ms: u64, + /// Answer `HostApi.GpuTopology`, telling a guest the host PCI address of + /// its passthrough devices. + pub share_host_address: bool, } impl GpuConfig { diff --git a/dstack/vmm/src/gpu_reset.rs b/dstack/vmm/src/gpu_reset.rs index 5e76404d0..e8d8e7d95 100644 --- a/dstack/vmm/src/gpu_reset.rs +++ b/dstack/vmm/src/gpu_reset.rs @@ -325,6 +325,7 @@ mod tests { allow_attach_all: true, sanitize_on_attach: true, sbr_timeout_ms: 10_000, + share_host_address: false, }; let devices = GpuConfig { attach_mode: AttachMode::Listed, diff --git a/dstack/vmm/src/host_api_service.rs b/dstack/vmm/src/host_api_service.rs index 0ad3c53eb..bf43cbdea 100644 --- a/dstack/vmm/src/host_api_service.rs +++ b/dstack/vmm/src/host_api_service.rs @@ -5,7 +5,8 @@ use anyhow::{bail, Context, Result}; use host_api::{ host_api_server::{HostApiRpc, HostApiServer}, - GetSealingKeyRequest, GetSealingKeyResponse, HostInfo, Notification, + GetSealingKeyRequest, GetSealingKeyResponse, GpuTopologyResponse, HostInfo, Notification, + PassthroughDevice, }; use ra_rpc::{CallContext, RemoteEndpoint, RpcCall}; use rocket_vsock_listener::VsockEndpoint; @@ -52,6 +53,23 @@ impl HostApiRpc for HostApiHandler { .await } + async fn gpu_topology(self) -> Result { + if !self.app.config.cvm.gpu.share_host_address { + bail!("sharing GPU host addresses is disabled on this host"); + } + let id = self.app.vm_id_by_cid(self.endpoint.cid)?; + let devices = self.app.passthrough_devices(&id).await?; + Ok(GpuTopologyResponse { + devices: devices + .into_iter() + .map(|device| PassthroughDevice { + guest_bdf: device.guest_bdf, + host_bdf: device.host_bdf, + }) + .collect(), + }) + } + async fn get_sealing_key(self, request: GetSealingKeyRequest) -> Result { let key_provider = &self.app.config.key_provider; if !key_provider.enabled { diff --git a/dstack/vmm/vmm.toml b/dstack/vmm/vmm.toml index da6ae15e7..afcd124f3 100644 --- a/dstack/vmm/vmm.toml +++ b/dstack/vmm/vmm.toml @@ -304,6 +304,14 @@ allow_attach_all = true sanitize_on_attach = false # Maximum time for all reset GPUs to become continuously VFIO-ready. sbr_timeout_ms = 10000 +# Tell each guest the host PCI address of its passed-through GPUs and +# NVSwitches (HostApi.GpuTopology), so the guest agent can label its GPU +# telemetry with the address host-side monitoring uses. The host address is +# not secret, but it is host topology a guest otherwise never sees, and the +# guest agent publishes it on /metrics when the app sets public_sysinfo. +# The VMM's own GpuInfo relay to the control plane carries the address +# whatever this says. +share_host_address = false # Access control for the guest agent's external listener (port 8090). Every # route needs a scope, granted by a signed Ed25519 JWT or by the anonymous list From a80cc1c6709efa00b3ae2a83ab04ad6c6cabda34 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 3 Dec 2026 01:18:36 +0800 Subject: [PATCH 5/6] feat(guest-agent): label GPU telemetry with the host PCI address Signed-off-by: Leechael Yim --- docs/security/cvm-boundaries.md | 2 +- dstack/guest-agent/src/gpu_info.rs | 119 ++++++++++++++++++++++- dstack/guest-agent/src/models.rs | 32 ++++++ dstack/guest-agent/templates/metrics.tpl | 6 ++ 4 files changed, 156 insertions(+), 3 deletions(-) diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index 764536d3b..366536bb0 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -35,7 +35,7 @@ This is the main configuration file for the application in JSON format: | local_key_provider_enabled | 0.3.1 | boolean | Use a local key provider | | key_provider_id | 0.5.1 | string | Optional pin for the key provider identity (hex-encoded bytes). For `kms` this is the KMS CA public key; for `local` the sealing-provider MR. For `tpm`, `sev-snp`, `tdx-seal` and `none` it must be an empty string — the TPM app-root public key is instance-specific and is not used as a provider id or measured as one. When empty, any provider is accepted; its identity is still recorded in the `key-provider` launch event. | | public_logs | 0.3.3 | boolean | Whether logs are publicly visible | -| public_sysinfo | 0.3.3 | boolean | Whether system info is public. Covers the guest dashboard and `/metrics`, including the `dstack_gpu_*` series (since 0.6.0), which expose each GPU's UUID and PCI bus address alongside utilization, memory, temperature and power. | +| public_sysinfo | 0.3.3 | boolean | Whether system info is public. Covers the guest dashboard and `/metrics`, including the `dstack_gpu_*` series (since 0.6.0), which expose each GPU's UUID and PCI bus address alongside utilization, memory, temperature and power. On a host that sets `cvm.gpu.share_host_address`, `dstack_gpu_info` also carries each GPU's host PCI address. | | public_tcbinfo | 0.5.1 | boolean | Whether TCB info is public | | allowed_envs | 0.4.2 | array of string | List of allowed environment variable names. An entry may be `NAME: spec` to also constrain the value, see [Environment value specs](#environment-value-specs). | | no_instance_id | 0.4.2 | boolean | Disable instance ID generation | diff --git a/dstack/guest-agent/src/gpu_info.rs b/dstack/guest-agent/src/gpu_info.rs index 6e62a9641..a23e01e04 100644 --- a/dstack/guest-agent/src/gpu_info.rs +++ b/dstack/guest-agent/src/gpu_info.rs @@ -45,13 +45,16 @@ //! ~2% of a core on every GPU guest whether or not anyone is watching, to //! publish a number the consumer can already derive. +use std::collections::HashMap; use std::path::Path; use std::process::Stdio; use std::sync::{LazyLock, OnceLock}; -use std::time::Duration; +use std::time::{Duration, Instant}; use anyhow::{bail, Context, Result}; use cached_cell::TtlCell; +use dstack_types::shared_filenames::{HOST_SHARED_DIR, SYS_CONFIG}; +use dstack_types::SysConfig; use guest_api::GpuInfoResponse; #[cfg(test)] use or_panic::ResultOrPanic; @@ -235,7 +238,8 @@ async fn refresh_if_free() { /// Caller must hold [`REFRESH_LOCK`]. async fn sample_into_cache() { match timeout(SAMPLE_TIMEOUT, collect()).await { - Ok(Ok(response)) => { + Ok(Ok(mut response)) => { + fill_host_pci_bus_ids(&mut response, &host_topology().await); SNAPSHOT.set(response); } Ok(Err(error)) => { @@ -291,6 +295,92 @@ fn collector_path() -> String { DSTACK_UTIL.to_string() } +/// How long to wait before asking the host again after it did not answer. +/// +/// The usual reason is a VMM older than `HostApi.GpuTopology`. Asking again +/// later picks up a VMM upgraded while this guest keeps running, and one vsock +/// call every few minutes costs nothing. +const TOPOLOGY_RETRY: Duration = Duration::from_secs(300); +/// Upper bound on the host call. A sample must not wait on a slow host. +const TOPOLOGY_TIMEOUT: Duration = Duration::from_secs(3); + +/// Guest PCI address to host PCI address, as the host last reported it. +#[derive(Default)] +struct HostTopology { + /// Set once the host answered. A VM's passthrough devices are fixed at + /// launch, so one answer holds for the life of this guest. + known: Option>, + /// When the last failed call was made. + failed_at: Option, +} + +static HOST_TOPOLOGY: LazyLock> = + LazyLock::new(|| Mutex::new(HostTopology::default())); + +/// The host address of each passthrough device, by guest address. Empty when +/// the host does not report it; never fails. +async fn host_topology() -> HashMap { + let mut topology = HOST_TOPOLOGY.lock().await; + if let Some(known) = &topology.known { + return known.clone(); + } + if topology + .failed_at + .is_some_and(|at| at.elapsed() < TOPOLOGY_RETRY) + { + return HashMap::new(); + } + match timeout(TOPOLOGY_TIMEOUT, query_host_topology()).await { + Ok(Ok(known)) => { + topology.known = Some(known.clone()); + known + } + Ok(Err(error)) => { + debug!("no GPU host addresses from the host: {error:#}"); + topology.failed_at = Some(Instant::now()); + HashMap::new() + } + Err(_) => { + debug!("no GPU host addresses: the host did not answer in {TOPOLOGY_TIMEOUT:?}"); + topology.failed_at = Some(Instant::now()); + HashMap::new() + } + } +} + +async fn query_host_topology() -> Result> { + let sys_config: SysConfig = serde_json::from_str( + &fs_err::read_to_string(format!("{HOST_SHARED_DIR}/{SYS_CONFIG}")) + .context("failed to read the system config")?, + ) + .context("invalid system config")?; + let url = sys_config + .host_api_url + .context("host_api_url is not configured")?; + let response = host_api::client::new_client(url).gpu_topology().await?; + Ok(response + .devices + .into_iter() + .filter_map(|device| { + Some(( + lspci::normalize_bdf(&device.guest_bdf)?, + lspci::normalize_bdf(&device.host_bdf)?, + )) + }) + .collect()) +} + +/// Sets each GPU's host address from the host's table, matched by the guest +/// address NVML reported. +fn fill_host_pci_bus_ids(response: &mut GpuInfoResponse, topology: &HashMap) { + for gpu in &mut response.gpus { + let host = lspci::normalize_bdf(&gpu.pci_bus_id).and_then(|guest| topology.get(&guest)); + if let Some(host) = host { + gpu.host_pci_bus_id = host.clone(); + } + } +} + /// The guest has no NVIDIA hardware. Empty devices with no error is the /// documented encoding for "the collector ran and found nothing". fn no_gpus() -> GpuInfoResponse { @@ -399,6 +489,31 @@ mod tests { assert!(FAILURE_BACKOFF > SAMPLE_TTL); } + /// NVML writes an eight-digit domain and the host a four-digit one; the + /// match must not depend on that. A GPU the host did not list stays empty. + #[test] + fn host_addresses_are_matched_by_guest_address() { + let mut response = GpuInfoResponse { + gpus: vec![ + GpuDevice { + index: 0, + pci_bus_id: "00000000:01:00.0".into(), + ..Default::default() + }, + GpuDevice { + index: 1, + pci_bus_id: "00000000:02:00.0".into(), + ..Default::default() + }, + ], + ..Default::default() + }; + let topology = HashMap::from([("0000:01:00.0".to_string(), "0001:1a:00.0".to_string())]); + fill_host_pci_bus_ids(&mut response, &topology); + assert_eq!(response.gpus[0].host_pci_bus_id, "0001:1a:00.0"); + assert_eq!(response.gpus[1].host_pci_bus_id, ""); + } + /// An empty cache is always due; that is the cold-start path. #[test] fn an_empty_cache_is_due() { diff --git a/dstack/guest-agent/src/models.rs b/dstack/guest-agent/src/models.rs index 7b86f599c..16c123a0a 100644 --- a/dstack/guest-agent/src/models.rs +++ b/dstack/guest-agent/src/models.rs @@ -98,6 +98,18 @@ mod filters { )) } + /// [`gpu_labels`] plus the host PCI address. Kept off every other series + /// so adding it did not change their label sets; join on this one. + pub fn gpu_info_labels(gpu: &guest_api::GpuDevice) -> Result { + Ok(format!( + "{{index=\"{}\", uuid=\"{}\", pci_bus_id=\"{}\", host_pci_bus_id=\"{}\"}}", + gpu.index, + prometheus_label(&gpu.uuid)?, + prometheus_label(&gpu.pci_bus_id)?, + prometheus_label(&gpu.host_pci_bus_id)?, + )) + } + pub fn prometheus_label(s: &str) -> Result { Ok(s.replace('\\', "\\\\") .replace('\n', "\\n") @@ -240,6 +252,26 @@ mod tests { assert!(failed.contains("dstack_gpu_nvml_up 0")); } + /// The host address rides on `dstack_gpu_info` only. The other series + /// keep the label set they had, so upgrading does not split their history. + #[test] + fn the_host_address_is_only_on_the_info_series() { + let body = render(GpuInfoResponse { + gpus: vec![GpuDevice { + host_pci_bus_id: "0001:1a:00.0".into(), + utilization_gpu: Some(5), + ..gpu(1) + }], + ..Default::default() + }); + assert!(body.contains( + r#"dstack_gpu_info{index="1", uuid="GPU-1", pci_bus_id="00000000:01:00.0", host_pci_bus_id="0001:1a:00.0"} 1"# + ), "{body}"); + assert!(body.contains( + r#"dstack_gpu_utilization_percent{index="1", uuid="GPU-1", pci_bus_id="00000000:01:00.0"} 5"# + )); + } + /// Label values are escaped, so a hostile UUID cannot inject a series. #[test] fn label_values_are_escaped() { diff --git a/dstack/guest-agent/templates/metrics.tpl b/dstack/guest-agent/templates/metrics.tpl index 6c864c036..b7ea879d0 100644 --- a/dstack/guest-agent/templates/metrics.tpl +++ b/dstack/guest-agent/templates/metrics.tpl @@ -99,6 +99,12 @@ dstack_gpu_cc_enabled {% if enabled %}1{% else %}0{% endif %} dstack_gpu_cc_ready {% if ready %}1{% else %}0{% endif %} {%- when None %}{% endmatch %} +# HELP dstack_gpu_info Always 1. Carries each GPU's host PCI address, as the host reports it, for joining guest series with host ones. +# TYPE dstack_gpu_info gauge +{%- for gpu in gpu_info.gpus %} +dstack_gpu_info{{ gpu|gpu_info_labels }} 1 +{%- endfor %} + # HELP dstack_gpu_utilization_percent GPU SM duty cycle, percent. # TYPE dstack_gpu_utilization_percent gauge {%- for gpu in gpu_info.gpus %}{% match gpu.utilization_gpu %}{% when Some with (value) %} From 79ca0d32cdebd6fcb64e3053aac56b05f181a236 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 3 Dec 2026 01:24:04 +0800 Subject: [PATCH 6/6] fix(vmm): trust only the VMM reading of GPU host addresses and refuse overlapping buses Signed-off-by: Leechael Yim --- dstack/vmm/src/app.rs | 8 ++-- dstack/vmm/src/app/passthrough.rs | 37 +++++++++++++++- dstack/vmm/src/guest_api_service.rs | 67 +++++++++++++++-------------- 3 files changed, 75 insertions(+), 37 deletions(-) diff --git a/dstack/vmm/src/app.rs b/dstack/vmm/src/app.rs index c24860964..e269eefb7 100644 --- a/dstack/vmm/src/app.rs +++ b/dstack/vmm/src/app.rs @@ -1864,7 +1864,7 @@ impl App { if !info.state.status.is_running() { bail!("VM is not running"); } - let args = qemu_args(&info.config.args)?; + let args = qemu_args(&info.config.args).await?; passthrough::passthrough_devices(&args) } @@ -2525,7 +2525,7 @@ pub(crate) fn needs_swtpm( /// QEMU's arguments from a supervisor process. A VM that needs sidecars runs /// under `dstack-vmm vm-launcher --spec `, and QEMU's arguments are in /// that file instead. -fn qemu_args(process_args: &[String]) -> Result> { +async fn qemu_args(process_args: &[String]) -> Result> { if process_args.first().map(String::as_str) != Some("vm-launcher") { return Ok(process_args.to_vec()); } @@ -2535,7 +2535,9 @@ fn qemu_args(process_args: &[String]) -> Result> { .map(|pair| &pair[1]) .context("vm-launcher has no --spec")?; let spec: crate::vm_launcher::LaunchSpec = serde_json::from_slice( - &fs::read(spec_path).context("failed to read the VM launch specification")?, + &tokio::fs::read(spec_path) + .await + .context("failed to read the VM launch specification")?, ) .context("invalid VM launch specification")?; Ok(spec.qemu.args) diff --git a/dstack/vmm/src/app/passthrough.rs b/dstack/vmm/src/app/passthrough.rs index 8cc657e6d..1e7fec440 100644 --- a/dstack/vmm/src/app/passthrough.rs +++ b/dstack/vmm/src/app/passthrough.rs @@ -129,7 +129,17 @@ pub(crate) fn passthrough_devices(args: &[String]) -> Result= *lowest { + bail!("{flat_ports} root ports on {ROOT_BUS} run into expander bus {lowest}"); + } + } + + let pairs: Vec = vfio + .into_iter() .map(|device| { let host = device.require("host")?; let host_bdf = lspci::normalize_bdf(host) @@ -146,7 +156,12 @@ pub(crate) fn passthrough_devices(args: &[String]) -> Result>()?; + let mut seen = std::collections::HashSet::new(); + if let Some(dup) = pairs.iter().find(|pair| !seen.insert(&pair.guest_bdf)) { + bail!("two devices claim guest address {}", dup.guest_bdf); + } + Ok(pairs) } /// Bridges and expanders dstack-vmm never emits. Any of them would shift the @@ -334,6 +349,24 @@ mod tests { "pcie-root-port,id=pci.1,bus=pcie.0,chassis=1", "vfio-pci,host=not-a-bdf,bus=pci.1", ][..], + // Five NVSwitch root ports on pcie.0: the fifth lands on bus 5, + // the expander's own root bus. No two devices share an address, + // so only the overlap check catches it. + &[ + "pxb-pcie,id=pcie.node0,bus=pcie.0,addr=0x10,numa_node=0,bus_nr=5", + "pcie-root-port,id=pci.1,bus=pcie.node0,chassis=1", + "vfio-pci,host=1b:00.0,bus=pci.1", + "pcie-root-port,id=pci.2,bus=pcie.0,chassis=2", + "vfio-pci,host=01:00.0,bus=pci.2", + "pcie-root-port,id=pci.3,bus=pcie.0,chassis=3", + "vfio-pci,host=02:00.0,bus=pci.3", + "pcie-root-port,id=pci.4,bus=pcie.0,chassis=4", + "vfio-pci,host=03:00.0,bus=pci.4", + "pcie-root-port,id=pci.5,bus=pcie.0,chassis=5", + "vfio-pci,host=04:00.0,bus=pci.5", + "pcie-root-port,id=pci.6,bus=pcie.0,chassis=6", + "vfio-pci,host=05:00.0,bus=pci.6", + ][..], ] { assert!( passthrough_devices(&args(devices)).is_err(), diff --git a/dstack/vmm/src/guest_api_service.rs b/dstack/vmm/src/guest_api_service.rs index 95b235ac5..68e97f82d 100644 --- a/dstack/vmm/src/guest_api_service.rs +++ b/dstack/vmm/src/guest_api_service.rs @@ -47,17 +47,18 @@ impl ProxiedGuestApiRpc for GuestApiHandler { async fn gpu_info(self, request: Id) -> Result { let mut response = self.guest_agent_client(&request.id)?.gpu_info().await?; - // A guest agent from before `host_pci_bus_id` existed leaves it empty; - // fill it here so the control plane gets it from every image. - if response - .gpus - .iter() - .any(|gpu| gpu.host_pci_bus_id.is_empty()) - { - match self.passthrough_devices(&request.id).await { - Ok(devices) => fill_host_pci_bus_ids(&request.id, &mut response, &devices), - Err(err) => { - debug!(id = request.id, "no GPU host addresses: {err:#}"); + if response.gpus.is_empty() { + return Ok(response); + } + // Always the VMM's own reading, never the guest's: the control plane + // must not take a card's identity from the guest it is monitoring. + // It also covers guest agents from before `host_pci_bus_id` existed. + match self.passthrough_devices(&request.id).await { + Ok(devices) => set_host_pci_bus_ids(&request.id, &mut response, &devices), + Err(err) => { + debug!(id = request.id, "no GPU host addresses: {err:#}"); + for gpu in &mut response.gpus { + gpu.host_pci_bus_id.clear(); } } } @@ -79,30 +80,28 @@ impl ProxiedGuestApiRpc for GuestApiHandler { } } -/// Sets the host address of each GPU the guest reported without one. +/// Sets each GPU's host address from the VMM's own reading of the running +/// QEMU, replacing whatever the guest reported. /// -/// A value the guest already set is kept: it came from this same host through -/// `HostApi.GpuTopology`. A disagreement is logged, since both are read from -/// the running QEMU and should never differ. -fn fill_host_pci_bus_ids(id: &str, response: &mut GpuInfoResponse, devices: &[PassthroughDevice]) { +/// The guest's value came from this same host through `HostApi.GpuTopology`, +/// so a disagreement means a bug or a guest that lies; it is logged. A GPU the +/// VMM cannot place gets an empty address rather than the guest's. +fn set_host_pci_bus_ids(id: &str, response: &mut GpuInfoResponse, devices: &[PassthroughDevice]) { for gpu in &mut response.gpus { - let Some(guest_bdf) = lspci::normalize_bdf(&gpu.pci_bus_id) else { - continue; - }; - let Some(device) = devices.iter().find(|device| device.guest_bdf == guest_bdf) else { - continue; - }; - if gpu.host_pci_bus_id.is_empty() { - gpu.host_pci_bus_id = device.host_bdf.clone(); - } else if gpu.host_pci_bus_id != device.host_bdf { + let host_bdf = lspci::normalize_bdf(&gpu.pci_bus_id) + .and_then(|guest_bdf| devices.iter().find(|device| device.guest_bdf == guest_bdf)) + .map(|device| device.host_bdf.clone()) + .unwrap_or_default(); + if !gpu.host_pci_bus_id.is_empty() && gpu.host_pci_bus_id != host_bdf { warn!( id, - guest = guest_bdf, + guest = gpu.pci_bus_id, reported = gpu.host_pci_bus_id, - expected = device.host_bdf, + expected = host_bdf, "guest reported a different GPU host address" ); } + gpu.host_pci_bus_id = host_bdf; } } @@ -141,7 +140,7 @@ mod tests { device("0000:02:00.0", "0000:2b:00.0"), device("0000:01:00.0", "0000:1b:00.0"), ]; - fill_host_pci_bus_ids("vm", &mut response, &devices); + set_host_pci_bus_ids("vm", &mut response, &devices); let hosts: Vec<_> = response .gpus .iter() @@ -151,16 +150,20 @@ mod tests { } #[test] - fn a_value_the_guest_set_is_kept() { + fn the_vmm_reading_replaces_what_the_guest_reported() { let mut response = GpuInfoResponse { - gpus: vec![gpu(0, "00000000:01:00.0", "0000:aa:00.0")], + gpus: vec![ + gpu(0, "00000000:01:00.0", "0000:aa:00.0"), + gpu(1, "00000000:09:00.0", "0000:bb:00.0"), + ], ..Default::default() }; - fill_host_pci_bus_ids( + set_host_pci_bus_ids( "vm", &mut response, &[device("0000:01:00.0", "0000:1b:00.0")], ); - assert_eq!(response.gpus[0].host_pci_bus_id, "0000:aa:00.0"); + assert_eq!(response.gpus[0].host_pci_bus_id, "0000:1b:00.0"); + assert_eq!(response.gpus[1].host_pci_bus_id, ""); } }