phoebus_os/installer-rs/crates/phoebus-core/src/nvidia.rs
Phoebus b4a6b5df80
Some checks are pending
ci / test (push) Waiting to run
feat(nvidia): hardware-driven driver policy, installed integration and live payload
- resolve the NVIDIA branch and kernel-module flavor from PCI device IDs
  (Turing+ open modules; Maxwell/Pascal/Volta proprietary, masked below 595;
  Fermi/Kepler fall back to nouveau, reported; unknown IDs reported)
- capture pci_id/pci_address in the probe; drive VIDEO_CARDS, package.use,
  package.accept_keywords, package.mask, modprobe.d and dracut from the plan,
  preserving hybrid Intel/AMD
- add the nvidia_drivers install stage (after the kernel, before boot) that
  emerges the driver, regenerates the initramfs, records /etc/phoebus/nvidia and
  fails the install on failure; sys update rebuilds modules and the initramfs
- refuse AI changes to x11-drivers/nvidia-drivers
- live ISO: signed non-free components, stable-kernel pin (testing 7.2 breaks
  the 550 driver), DKMS build for the exact kernel, gated pre-greetd load,
  fail-safe entry, gpu-report, and a --verify-live-nvidia build gate that runs
  on cached rootfs builds and fails on any missing component
- docs: ADR 0012, STATUS/CHANGELOG/HANDOFF, live README
- also carries the pending OpenCode model-variant/streaming changes and fixes
  the GUI bridge install thread join that could hang
2026-09-22 21:53:28 -07:00

629 lines
22 KiB
Rust

//! NVIDIA accelerated-driver policy.
//!
//! This module turns the probed PCI display devices into a deterministic driver
//! decision: which NVIDIA driver branch, which kernel-module flavor (NVIDIA's
//! open kernel modules or the proprietary modules), and the exact scoped
//! Portage, dracut, modprobe and Debian-live configuration that follows from
//! it.
//!
//! It is data driven, not marketing-name driven. Device generation is resolved
//! from the PCI device ID via [`crate::nvidia_devices`], which is generated
//! from the public PCI ID database. The AI may explain the decision but has no
//! action that can change it (see `phoebus-ai`'s fixed-policy check).
//!
//! Branch policy (NVIDIA/Gentoo, verified 2026-09):
//!
//! * **Turing / Ampere / Ada / Hopper / Blackwell** use the current
//! `x11-drivers/nvidia-drivers` branch with NVIDIA's *open* kernel modules
//! (`USE=kernel-open`). The open modules support Turing (GTX 16xx / RTX 20xx)
//! and newer. They are mandatory from driver 595 and are required for
//! Blackwell (RTX 50xx).
//! * **Maxwell / Pascal / Volta** cannot use the open modules. They are pinned
//! to the newest proprietary branch below the open-mandatory cut (595) with
//! `USE=-kernel-open`, and `>=x11-drivers/nvidia-drivers-595` is masked.
//! * **Fermi / Kepler and older** are not served by a security-supported
//! proprietary branch; they fall back to the in-tree `nouveau` driver. This
//! is reported, never silently substituted as NVIDIA success.
//!
//! The Debian live medium ships a single signed branch (550.163.01 in Debian
//! 13/testing). That branch's proprietary kernel modules cover Maxwell through
//! Ada/Hopper; it does not support Blackwell, so Blackwell live boots fall back
//! to nouveau and are reported.
use serde::{Deserialize, Serialize};
use crate::hardware::{GpuInfo, GpuVendor, HardwareReport};
use crate::nvidia_devices;
/// The Gentoo package that provides the NVIDIA driver.
pub const GENTOO_ATOM: &str = "x11-drivers/nvidia-drivers";
/// The first NVIDIA driver series that makes the open kernel modules mandatory
/// (`USE=kernel-open` can no longer be disabled). Maxwell/Pascal/Volta are
/// pinned below this cut.
pub const OPEN_MANDATORY_SERIES: u32 = 595;
/// The NVIDIA branch bundled on the Debian live medium. It is a property of
/// the signed Debian archive, not of the detected GPU.
pub const LIVE_DEBIAN_BRANCH: &str = "550.163.01";
/// The Debian package that builds the proprietary kernel module for the live
/// kernel.
pub const LIVE_PROPRIETARY_KMOD: &str = "nvidia-kernel-dkms";
/// The Debian package that builds the open kernel module (Turing+ only).
pub const LIVE_OPEN_KMOD: &str = "nvidia-open-kernel-dkms";
/// NVIDIA GPU architecture generation, derived from the PCI device ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NvidiaGeneration {
Fermi,
Kepler,
Maxwell,
Pascal,
Volta,
Turing,
Ampere,
Ada,
Hopper,
Blackwell,
}
impl NvidiaGeneration {
/// Every generation, oldest first.
pub const ALL: [NvidiaGeneration; 10] = [
NvidiaGeneration::Fermi,
NvidiaGeneration::Kepler,
NvidiaGeneration::Maxwell,
NvidiaGeneration::Pascal,
NvidiaGeneration::Volta,
NvidiaGeneration::Turing,
NvidiaGeneration::Ampere,
NvidiaGeneration::Ada,
NvidiaGeneration::Hopper,
NvidiaGeneration::Blackwell,
];
pub fn as_str(self) -> &'static str {
match self {
NvidiaGeneration::Fermi => "Fermi",
NvidiaGeneration::Kepler => "Kepler",
NvidiaGeneration::Maxwell => "Maxwell",
NvidiaGeneration::Pascal => "Pascal",
NvidiaGeneration::Volta => "Volta",
NvidiaGeneration::Turing => "Turing",
NvidiaGeneration::Ampere => "Ampere",
NvidiaGeneration::Ada => "Ada",
NvidiaGeneration::Hopper => "Hopper",
NvidiaGeneration::Blackwell => "Blackwell",
}
}
/// Whether NVIDIA's open kernel modules support this generation.
pub fn supports_open_modules(self) -> bool {
matches!(
self,
NvidiaGeneration::Turing
| NvidiaGeneration::Ampere
| NvidiaGeneration::Ada
| NvidiaGeneration::Hopper
| NvidiaGeneration::Blackwell
)
}
/// The support decision for this generation.
pub fn support(self) -> NvidiaSupport {
match self {
NvidiaGeneration::Fermi | NvidiaGeneration::Kepler => NvidiaSupport::Unsupported,
NvidiaGeneration::Maxwell | NvidiaGeneration::Pascal | NvidiaGeneration::Volta => {
NvidiaSupport::Proprietary
}
_ => NvidiaSupport::Open,
}
}
}
/// How an NVIDIA generation is served.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NvidiaSupport {
/// Current branch with NVIDIA's open kernel modules.
Open,
/// A proprietary branch (Maxwell/Pascal/Volta), open modules unsupported.
Proprietary,
/// No security-supported proprietary branch: `nouveau` fallback.
Unsupported,
}
/// The kernel-module flavor actually installed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NvidiaModuleFlavor {
Open,
Proprietary,
}
impl NvidiaModuleFlavor {
pub fn as_str(self) -> &'static str {
match self {
NvidiaModuleFlavor::Open => "open",
NvidiaModuleFlavor::Proprietary => "proprietary",
}
}
}
/// One probed NVIDIA display device.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NvidiaDevice {
/// `vendor:device`, lower-case hex, e.g. `10de:2482`.
pub pci_id: String,
/// PCI address, e.g. `0000:01:00.0`, when known.
pub pci_address: Option<String>,
pub description: String,
/// `None` when the PCI ID database has no recognised NVIDIA codename.
pub generation: Option<NvidiaGeneration>,
}
impl NvidiaDevice {
/// Whether the device is claimed by the selected proprietary/open driver.
pub fn is_supported(&self) -> bool {
self.generation
.map(|g| g.support() != NvidiaSupport::Unsupported)
.unwrap_or(false)
}
/// The generation's support class, `Unsupported` for unknown hardware.
pub fn support(&self) -> NvidiaSupport {
self.generation
.map(|g| g.support())
.unwrap_or(NvidiaSupport::Unsupported)
}
}
/// The resolved NVIDIA driver decision for one machine.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NvidiaPlan {
/// Every NVIDIA display device that was probed.
pub devices: Vec<NvidiaDevice>,
/// True when at least one device is served by an NVIDIA branch.
pub supported: bool,
/// The newest supported generation present, if any.
pub generation: Option<NvidiaGeneration>,
/// The module flavor for the selected branch.
pub flavor: Option<NvidiaModuleFlavor>,
/// Human-readable branch label.
pub branch: String,
/// Why this decision was made (and what is left on nouveau).
pub reason: String,
}
impl NvidiaPlan {
/// The decision for a machine with no NVIDIA GPU.
pub fn none() -> Self {
Self {
devices: Vec::new(),
supported: false,
generation: None,
flavor: None,
branch: "none".into(),
reason: "no NVIDIA display device detected".into(),
}
}
/// Resolve the driver decision from probed hardware.
pub fn for_hardware(hardware: &HardwareReport) -> Self {
let devices: Vec<NvidiaDevice> = hardware
.gpus
.iter()
.filter(|g| g.vendor == GpuVendor::Nvidia)
.map(nvidia_device)
.collect();
if devices.is_empty() {
return Self::none();
}
let supported: Vec<&NvidiaDevice> = devices.iter().filter(|d| d.is_supported()).collect();
if supported.is_empty() {
let known: Vec<&str> = devices
.iter()
.map(|d| d.generation.map(|g| g.as_str()).unwrap_or("unknown"))
.collect();
return Self {
devices,
supported: false,
generation: None,
flavor: None,
branch: "nouveau".into(),
reason: format!(
"no security-supported NVIDIA branch for {}; using the in-tree nouveau fallback",
known.join(", ")
),
};
}
// The branch must serve the oldest supported adapter present, because
// one driver install covers every card. Maxwell/Pascal/Volta force the
// proprietary branch; otherwise the open modules are used.
let needs_proprietary = supported
.iter()
.any(|d| d.support() == NvidiaSupport::Proprietary);
let flavor = if needs_proprietary {
NvidiaModuleFlavor::Proprietary
} else {
NvidiaModuleFlavor::Open
};
let generation = supported
.iter()
.filter_map(|d| d.generation)
.max()
.unwrap_or(NvidiaGeneration::Turing);
let mut reason = match flavor {
NvidiaModuleFlavor::Open => format!(
"{} uses the current branch with NVIDIA's open kernel modules",
generation.as_str()
),
NvidiaModuleFlavor::Proprietary => format!(
"{} requires the proprietary branch (open kernel modules do not support Maxwell/Pascal/Volta)",
generation.as_str()
),
};
let unclaimed: Vec<String> = devices
.iter()
.filter(|d| !d.is_supported())
.map(|d| {
format!(
"{} ({})",
d.pci_id,
d.generation.map(|g| g.as_str()).unwrap_or("unknown")
)
})
.collect();
if !unclaimed.is_empty() {
reason.push_str(&format!(
"; {} remains on the nouveau fallback",
unclaimed.join(", ")
));
}
Self {
devices,
supported: true,
generation: Some(generation),
flavor: Some(flavor),
branch: match flavor {
NvidiaModuleFlavor::Open => {
format!("current open kernel modules (>= {OPEN_MANDATORY_SERIES})")
}
NvidiaModuleFlavor::Proprietary => {
format!("proprietary (for Maxwell/Pascal/Volta; capped below {OPEN_MANDATORY_SERIES})")
}
},
reason,
}
}
/// The `VIDEO_CARDS` entry this decision contributes.
pub fn video_cards_entry(&self) -> Option<&'static str> {
self.supported.then_some("nvidia")
}
/// The `x11-drivers/nvidia-drivers` atom, or `None` for nouveau.
pub fn gentoo_atom(&self) -> Option<&'static str> {
self.supported.then_some(GENTOO_ATOM)
}
/// Scoped `package.use` lines for the selected branch.
pub fn gentoo_package_use(&self) -> Vec<String> {
match self.flavor {
Some(NvidiaModuleFlavor::Open) => {
vec![format!("{GENTOO_ATOM} dist-kernel kernel-open")]
}
Some(NvidiaModuleFlavor::Proprietary) => {
vec![format!("{GENTOO_ATOM} dist-kernel -kernel-open")]
}
None => Vec::new(),
}
}
/// `package.mask` lines. Maxwell/Pascal/Volta must stay below the branch
/// that made the open modules mandatory.
pub fn gentoo_package_mask(&self) -> Vec<String> {
match self.flavor {
Some(NvidiaModuleFlavor::Proprietary) => {
vec![format!(">={GENTOO_ATOM}-{OPEN_MANDATORY_SERIES}")]
}
_ => Vec::new(),
}
}
/// Scoped `package.accept_keywords` lines. The NVIDIA branch is a hardware
/// enabler; the keyword stays scoped to this atom, never a global `~amd64`.
pub fn gentoo_accept_keywords(&self) -> Vec<String> {
self.supported
.then(|| format!("{GENTOO_ATOM} ~amd64"))
.into_iter()
.collect()
}
/// Kernel modules that must be present and loaded for acceleration.
pub fn kernel_modules(&self) -> Vec<&'static str> {
if self.supported {
vec!["nvidia", "nvidia_modeset", "nvidia_uvm", "nvidia_drm"]
} else {
Vec::new()
}
}
/// `/etc/modprobe.d` content: keep `nouveau` off the claimed GPU, enable
/// DRM modesetting, and make `nvidia-uvm` a soft dependency so dracut does
/// not embed a dangling module reference.
pub fn modprobe_conf(&self) -> Option<String> {
if !self.supported {
return None;
}
let mut o = String::new();
o.push_str("# NVIDIA accelerated driver (generated by the Phoebus installer).\n");
o.push_str("# Keep the in-tree nouveau driver from binding the GPU that the\n");
o.push_str("# selected NVIDIA branch is meant to drive.\n");
o.push_str("blacklist nouveau\n");
o.push_str("options nouveau modeset=0\n");
o.push_str("options nvidia_drm modeset=1\n");
o.push_str("softdep nvidia post: nvidia-uvm\n");
Some(o)
}
/// `/etc/dracut.conf.d` fragment that forces the modules (and their
/// firmware) into the initramfs for early KMS.
pub fn dracut_conf(&self) -> Option<String> {
if !self.supported {
return None;
}
let drivers = self.kernel_modules().join(" ");
Some(format!(
"# NVIDIA accelerated driver: load DRM/modeset early (generated).\nforce_drivers+=\" {drivers} \"\n"
))
}
/// The live-medium module flavor. The bundled Debian branch is decided at
/// build time; this reflects what the live image records.
pub fn live_flavor(&self) -> NvidiaModuleFlavor {
// The live branch's proprietary modules cover every generation the
// Debian branch supports (Maxwell..Ada/Hopper). Open modules are only
// needed on the installed system for Turing+.
NvidiaModuleFlavor::Proprietary
}
/// Debian packages bundled in the live rootfs so the ISO needs no network
/// and compiles nothing at boot.
pub fn live_packages(&self) -> Vec<&'static str> {
let mut out = vec![
// Kernel modules (built for the exact live kernel during the build).
LIVE_PROPRIETARY_KMOD,
// Userspace: GLX/EGL/GLES/VDPAU/Vulkan, nvidia-smi, modprobe.
"nvidia-driver",
"nvidia-vulkan-icd",
"nvidia-suspend-common",
// Wayland/EGL/GBM integration for nvidia-drm.
"libnvidia-egl-gbm1",
"libnvidia-egl-wayland1",
// Firmware must be present or the module refuses to initialise.
"firmware-nvidia-graphics",
"firmware-nvidia-gsp",
];
out.sort_unstable();
out.dedup();
out
}
/// A human-readable decision line for the installation plan.
pub fn render(&self) -> Option<String> {
if self.devices.is_empty() {
return None;
}
let mut out = String::new();
out.push_str(&format!(" NVIDIA driver : {}\n", self.branch));
if let Some(flavor) = self.flavor {
out.push_str(&format!(
" Module flavor: {}\n",
match flavor {
NvidiaModuleFlavor::Open => "open (kernel-open)",
NvidiaModuleFlavor::Proprietary => "proprietary (kernel-open disabled)",
}
));
}
for device in &self.devices {
out.push_str(&format!(
" {} {} [{}]\n",
device.pci_id,
device
.generation
.map(|g| g.as_str())
.unwrap_or("unknown generation"),
device.description
));
}
out.push_str(&format!(" {}\n", self.reason));
Some(out)
}
}
/// Build a [`NvidiaDevice`] from a probed display device.
fn nvidia_device(gpu: &GpuInfo) -> NvidiaDevice {
let pci_id = gpu.pci_id.clone().unwrap_or_default();
let generation = gpu
.pci_id
.as_deref()
.and_then(parse_pci_pair)
.and_then(|(vendor, device)| {
if vendor == 0x10de {
nvidia_devices::generation_for_device(device)
} else {
None
}
});
NvidiaDevice {
pci_id,
pci_address: gpu.pci_address.clone(),
description: gpu.description.clone(),
generation,
}
}
/// Parse `vendor:device` (hex) into `(vendor, device)`.
pub fn parse_pci_pair(value: &str) -> Option<(u16, u16)> {
let (vendor, device) = value.split_once(':')?;
let vendor = u16::from_str_radix(vendor.trim(), 16).ok()?;
let device = u16::from_str_radix(device.trim(), 16).ok()?;
Some((vendor, device))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hardware::{GpuInfo, HardwareReport};
fn nvidia(id: &str, description: &str) -> GpuInfo {
GpuInfo {
vendor: GpuVendor::Nvidia,
description: description.into(),
pci_id: Some(id.into()),
pci_address: Some("0000:01:00.0".into()),
}
}
fn hardware(gpus: Vec<GpuInfo>) -> HardwareReport {
HardwareReport {
gpus,
..Default::default()
}
}
#[test]
fn turing_uses_open_modules() {
let hw = hardware(vec![nvidia("10de:1e04", "TU102 [GeForce RTX 2080 Ti]")]);
let plan = NvidiaPlan::for_hardware(&hw);
assert!(plan.supported);
assert_eq!(plan.generation, Some(NvidiaGeneration::Turing));
assert_eq!(plan.flavor, Some(NvidiaModuleFlavor::Open));
assert_eq!(plan.video_cards_entry(), Some("nvidia"));
assert_eq!(plan.gentoo_package_mask(), Vec::<String>::new());
assert!(plan.gentoo_package_use()[0].contains("kernel-open"));
}
#[test]
fn pascal_uses_the_proprietary_branch_and_is_masked_below_595() {
let hw = hardware(vec![nvidia("10de:1b81", "GP104 [GeForce GTX 1070]")]);
let plan = NvidiaPlan::for_hardware(&hw);
assert_eq!(plan.flavor, Some(NvidiaModuleFlavor::Proprietary));
assert_eq!(
plan.gentoo_package_mask(),
vec![">=x11-drivers/nvidia-drivers-595".to_string()]
);
assert!(plan.gentoo_package_use()[0].contains("-kernel-open"));
}
#[test]
fn blackwell_uses_open_modules() {
let hw = hardware(vec![nvidia("10de:2b85", "GB202 [GeForce RTX 5090]")]);
let plan = NvidiaPlan::for_hardware(&hw);
assert_eq!(plan.generation, Some(NvidiaGeneration::Blackwell));
assert_eq!(plan.flavor, Some(NvidiaModuleFlavor::Open));
}
#[test]
fn kepler_falls_back_to_nouveau_and_is_reported() {
let hw = hardware(vec![nvidia("10de:0fc0", "GK107 [GeForce GT 640]")]);
let plan = NvidiaPlan::for_hardware(&hw);
assert!(!plan.supported);
assert_eq!(plan.branch, "nouveau");
assert!(plan.reason.contains("nouveau"));
assert_eq!(plan.gentoo_atom(), None);
assert!(plan.modprobe_conf().is_none());
}
#[test]
fn unknown_nvidia_device_is_not_claimed() {
let hw = hardware(vec![nvidia("10de:dead", "NVIDIA Corporation Device")]);
let plan = NvidiaPlan::for_hardware(&hw);
assert!(!plan.supported);
assert!(plan.reason.contains("unknown"));
}
#[test]
fn hybrid_system_keeps_the_igpu_and_selects_nvidia() {
let hw = hardware(vec![
GpuInfo {
vendor: GpuVendor::Intel,
description: "Intel UHD".into(),
pci_id: Some("8086:9a60".into()),
pci_address: Some("0000:00:02.0".into()),
},
nvidia("10de:2482", "GA104 [GeForce RTX 3070]"),
]);
let plan = NvidiaPlan::for_hardware(&hw);
assert!(plan.supported);
assert_eq!(plan.generation, Some(NvidiaGeneration::Ampere));
assert_eq!(plan.flavor, Some(NvidiaModuleFlavor::Open));
}
#[test]
fn mixed_old_and_new_picks_the_proprietary_branch_for_the_oldest() {
let hw = hardware(vec![
nvidia("10de:1b81", "GP104 [GeForce GTX 1070]"),
nvidia("10de:2482", "GA104 [GeForce RTX 3070]"),
]);
let plan = NvidiaPlan::for_hardware(&hw);
assert!(plan.supported);
assert_eq!(plan.flavor, Some(NvidiaModuleFlavor::Proprietary));
}
#[test]
fn no_nvidia_gpu_has_no_plan() {
let hw = hardware(vec![GpuInfo {
vendor: GpuVendor::Amd,
description: "AMD Radeon".into(),
pci_id: Some("1002:73ff".into()),
pci_address: Some("0000:03:00.0".into()),
}]);
let plan = NvidiaPlan::for_hardware(&hw);
assert!(!plan.supported);
assert!(plan.render().is_none());
}
#[test]
fn modprobe_and_dracut_are_consistent() {
let hw = hardware(vec![nvidia("10de:2482", "GA104 [GeForce RTX 3070]")]);
let plan = NvidiaPlan::for_hardware(&hw);
let modprobe = plan.modprobe_conf().unwrap();
assert!(modprobe.contains("blacklist nouveau"));
assert!(modprobe.contains("options nvidia_drm modeset=1"));
let dracut = plan.dracut_conf().unwrap();
for module in plan.kernel_modules() {
assert!(dracut.contains(module), "dracut must force {module}");
}
}
#[test]
fn live_packages_include_module_firmware_and_wayland_gl() {
let hw = hardware(vec![nvidia("10de:2482", "GA104 [GeForce RTX 3070]")]);
let plan = NvidiaPlan::for_hardware(&hw);
let packages = plan.live_packages();
for expected in [
LIVE_PROPRIETARY_KMOD,
"firmware-nvidia-graphics",
"firmware-nvidia-gsp",
"libnvidia-egl-gbm1",
"libnvidia-egl-wayland1",
] {
assert!(packages.contains(&expected), "missing {expected}");
}
}
#[test]
fn parse_pci_pair_is_strict() {
assert_eq!(parse_pci_pair("10de:2482"), Some((0x10de, 0x2482)));
assert_eq!(parse_pci_pair("zzzz"), None);
}
}