chore(gpu): remove the unhooked NVIDIA open-RM port, its feature, xtask gpu nvidia, its check lane and the nvidia submodule

This commit is contained in:
Tyler Smith committed 2026-11-11 04:35:52 +00:00
1 parent 3bd4ec41a6
commit b8afc4706e
81 files changed
+51 -9892

No files matched your search

-4
View File
@@ -6,10 +6,6 @@
path = third_party/mesa
url = https://gitlab.freedesktop.org/mesa/mesa.git
shallow = true
[submodule "nvidia"]
path = third_party/nvidia
url = https://github.com/NVIDIA/open-gpu-kernel-modules.git
shallow = true
[submodule "llvm"]
path = third_party/llvm
url = https://github.com/llvm/llvm-project.git
Generated
-21
View File
@@ -1325,17 +1325,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5edeac3ec657925dececc672bdd58fa2212291886ddcb3e08aa46924c78340c6"
[[package]]
name = "lzma-sys"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fda04ab3764e6cde78b9974eec4f779acaba7c4e84b36eca3cf77c581b85d27"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]]
name = "managed"
version = "0.8.0"
@@ -3096,19 +3085,9 @@ dependencies = [
"stela-loader",
"stela-runtime",
"tempfile",
"xz2",
"zip",
]
[[package]]
name = "xz2"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "388c44dc09d76f1536602ead6d325eb532f5c122f17782bd57fb47baeeb767e2"
dependencies = [
"lzma-sys",
]
[[package]]
name = "yoke"
version = "0.8.4"
-6
View File
@@ -18,8 +18,6 @@ workspace = true
[features]
# Common native Linux kernel services; selecting this attaches no GPU.
linux-kernel = ["dep:cc", "dep:stela-c-build", "stela-c-build/linux", "dep:stela-linux", "stela-linux/kernel"]
# Build the implemented native NVIDIA OS hooks, not a complete GPU driver.
nvidia-port = ["dep:cc", "dep:stela-c-build", "stela-c-build/native"]
# nouveau's hardware resource manager (NVKM), compiled unchanged; it reaches
# no device until the kernel services it imports are supplied.
nouveau-port = ["linux-kernel", "stela-c-build/linux-registry"]
@@ -50,7 +48,3 @@ sha2 = { version = "0.10", default-features = false }
object = { version = "0.37", default-features = false, features = ["read"] }
cc = { version = "1", optional = true }
stela-c-build = { path = "../stela-c-build", optional = true }
[[test]]
name = "nvidia_mmio"
required-features = ["nvidia-port"]
+1 -6
View File
@@ -1,7 +1,7 @@
#[cfg(feature = "nouveau-port")]
#[path = "build/kbuild.rs"]
mod kbuild;
#[cfg(any(feature = "nvidia-port", feature = "linux-kernel"))]
#[cfg(feature = "linux-kernel")]
#[path = "build/native.rs"]
mod native;
#[cfg(feature = "nouveau-port")]
@@ -9,9 +9,6 @@ mod native;
mod nouveau;
#[path = "build/nouveau_firmware.rs"]
mod nouveau_firmware;
#[cfg(feature = "nvidia-port")]
#[path = "build/nvidia.rs"]
mod nvidia;
fn main() {
nouveau_firmware::validate();
@@ -33,8 +30,6 @@ fn main() {
);
#[cfg(feature = "linux-kernel")]
linux.tests(&mut tests);
#[cfg(feature = "nvidia-port")]
nvidia::port();
#[cfg(feature = "nouveau-port")]
let mut linux = linux;
#[cfg(feature = "nouveau-port")]
-4
View File
@@ -11,14 +11,10 @@ use stela_c_build::{
};
#[cfg(feature = "linux-kernel")]
pub const LINUX: &str = "../../third_party/linux";
#[cfg(feature = "nvidia-port")]
pub const NVIDIA: &str = "../../third_party/nvidia";
pub fn require_sources() {
#[cfg(feature = "linux-kernel")]
require_source(LINUX);
#[cfg(feature = "nvidia-port")]
require_source(NVIDIA);
}
fn require_source(source: &str) {
assert!(
-67
View File
@@ -1,67 +0,0 @@
//! Stela's NVIDIA OS hooks over NVIDIA's unchanged interface headers, in the
//! vendor's FreeBSD configuration as `cargo xtask gpu nvidia` builds the cores.
use super::native;
use std::fs;
pub fn port() {
native::require_sources();
let source = native::NVIDIA;
let port = "src/nvidia";
let version_mk = format!("{source}/version.mk");
let version = fs::read_to_string(&version_mk).expect("read NVIDIA version.mk");
let version = version
.lines()
.find_map(|line| line.strip_prefix("NVIDIA_VERSION = "))
.expect("NVIDIA_VERSION in retained version.mk");
assert!(
version
.bytes()
.all(|byte| byte.is_ascii_digit() || byte == b'.')
);
let generated = stela_c_build::linux_build::out_dir().join("nvidia-include");
fs::create_dir_all(&generated).expect("create NVIDIA generated include");
fs::write(
generated.join("version.h"),
format!("#define NVIDIA_VERSION \"{version}\"\n"),
)
.expect("generate NVIDIA version.h");
println!("cargo:rerun-if-changed={version_mk}");
let mut build = stela_c_build::native::configure();
// NVIDIA's Unix resource manager for an OS with its own interface layer.
// Its headers take a predefined __linux__ for Linux's kernel layer, which
// a Linux host's compiler defines even for this freestanding build.
build
.flag("-U__linux__")
.flag("-U__linux")
.flag("-Ulinux")
.define("NV_BSD", None)
// cpuopsys.h must not also select the hosted compiler's Linux OS.
.flag("-U__linux__")
.include(&generated)
.include(port)
// FreeBSD headers NVIDIA's interface layer includes, where none exist.
.flag("-idirafter")
.flag("src/compat/freebsd");
for directory in [
"src/common/sdk/nvidia/inc",
"src/nvidia/arch/nvalloc/unix/include",
"src/nvidia/arch/nvalloc/common/inc",
"src/nvidia/inc/kernel",
"src/common/inc",
"src/common/inc/swref",
"src/common/uproc/os/common/include",
"src/common/nvlink/interface",
"src/common/nvswitch/interface",
"src/common/unix/common/inc",
"src/nvidia-modeset/os-interface/include",
"src/nvidia-modeset/kapi/interface",
"src/nvidia-modeset/interface",
] {
// NVIDIA's headers keep their own warning profile.
build.flag("-isystem").flag(format!("{source}/{directory}"));
println!("cargo:rerun-if-changed={source}/{directory}");
}
build
.files(stela_c_build::linux_build::sources(port))
.compile("stela-nvidia-port");
}
@@ -1,6 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_SYS_STDDEF_H
#define STELA_NVIDIA_SYS_STDDEF_H
/* NVIDIA's FreeBSD interface layer reads the kernel's stddef through here. */
#include <stddef.h>
#endif
@@ -1,10 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_SYS_STDINT_H
#define STELA_NVIDIA_SYS_STDINT_H
/* NVIDIA's FreeBSD interface layer reads the kernel's stdint, and the
* __aligned spelling FreeBSD's sys/cdefs.h supplies with it, through here. */
#include <stdint.h>
#ifndef __aligned
#define __aligned(x) __attribute__((__aligned__(x)))
#endif
#endif
@@ -1,6 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_SYS_TYPES_H
#define STELA_NVIDIA_SYS_TYPES_H
/* NVIDIA's FreeBSD interface layer reads the kernel's fixed-width types here. */
#include <stdint.h>
#endif
-3
View File
@@ -8,9 +8,6 @@ use stela_driver_base::bus;
use crate::bus::pci::{Address, ConfigSpace, Function};
#[cfg(feature = "nvidia-port")]
pub mod nvidia;
#[cfg(feature = "metal")]
pub mod metal;
@@ -1,381 +0,0 @@
//! Native RAM CPU views for the official RM kernel-mapping hooks.
//! This accepts canonical pins; it does not allocate RAM, create MMIO aliases,
//! pin guest pages, install GPU page tables or infer device addresses.
use super::memory;
use crate::bus::dma::memory::{CpuMapping, MemoryError, PinnedPages};
use core::{ffi::c_void, marker::PhantomData, marker::PhantomPinned, pin::Pin, ptr, ptr::NonNull};
/// An existing native RAM allocation, with its established CPU cache policy.
/// Pin before borrowing its opaque pointer for an original RM mapping call.
/// The pointer is valid only while this handle lives; C keeps no borrow of
/// this handle after that call. Each successful view independently keeps the
/// underlying pins, so the parent may then be dropped without freeing its RAM.
/// All calls and final releases obey the common heap/backing's execution rules.
/// No implicit DMA completion or IRQ-safe release is supplied.
pub struct Allocation {
pages: PinnedPages,
pub(super) origin: Option<super::services::Origin>,
_owner: PhantomData<*mut ()>,
_pin: PhantomPinned,
}
impl Allocation {
pub fn new(pages: PinnedPages) -> Self {
Self {
pages,
origin: None,
_owner: PhantomData,
_pin: PhantomPinned,
}
}
pub(super) fn pages(&self) -> &PinnedPages {
&self.pages
}
/// Allocation-private pointer accepted by `nv_alloc_kernel_mapping`.
/// It must not be used as any other vendor allocation/import handle.
///
/// # Safety
/// Serialize native C/Rust access and exclude callback/interrupt reentry.
/// Every call dereferencing this pointer must end before this pinned handle
/// is dropped. CPU accesses through returned views require the owner's
/// exclusive-access/coherence protocol; raw pointers do not supply it.
/// Native page indices/offsets must use this allocation's page
/// granule, matching the real backend's `os_page_shift` configuration.
pub unsafe fn as_raw(self: Pin<&mut Self>) -> *mut c_void {
// SAFETY: obtain a stable opaque pointer without moving the object.
unsafe { self.get_unchecked_mut() as *mut Self }.cast()
}
fn mapping(
&self,
page_index: u64,
page_offset: u32,
bytes: u64,
) -> Result<CpuMapping, MemoryError> {
let page_bytes = 1usize << self.pages.page_shift();
if page_offset as usize >= page_bytes {
return Err(MemoryError::InvalidSize);
}
let start = usize::try_from(page_index)
.ok()
.and_then(|index| index.checked_mul(page_bytes))
.and_then(|start| start.checked_add(page_offset as usize))
.ok_or(MemoryError::InvalidSize)?;
let bytes = usize::try_from(bytes).map_err(|_| MemoryError::InvalidSize)?;
let end = start
.checked_add(bytes)
.filter(|end| *end <= self.pages.logical_bytes())
.ok_or(MemoryError::InvalidSize)?;
// Keep the existing mapping/pin and cache attribute. Do not expose
// whole-page padding beyond the allocation's exact logical payload.
self.pages
.cpu_mapping_range(self.pages.cache_attribute(), start..end)
}
}
// CpuMapping is Rust-private; C sees only a unique opaque token. The common
// metadata wrapper must support its alignment, including on the UEFI ABI.
const _: () = assert!(align_of::<CpuMapping>() <= memory::ALIGNMENT);
fn map_with(
allocation: &Allocation,
page_index: u64,
page_offset: u32,
bytes: u64,
allocate: impl FnOnce(u64) -> Option<NonNull<c_void>>,
) -> Option<(NonNull<c_void>, NonNull<CpuMapping>)> {
let mapping = allocation.mapping(page_index, page_offset, bytes).ok()?;
let address = mapping.address(0, mapping.bytes()).ok()?.cast();
let token = allocate(size_of::<CpuMapping>() as u64)?.cast::<CpuMapping>();
// SAFETY: the common metadata allocator supplied distinct aligned writable
// storage for this exact type. The token owns its mapping/pin.
unsafe { token.as_ptr().write(mapping) };
Some((address, token))
}
/// # Safety
/// The C shim supplies a live pinned Allocation and writable output slot.
/// The owner excludes reentry and obeys the shared heap/backing context rules.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_map_ram(
allocation: *mut c_void,
page_index: u64,
page_offset: u32,
bytes: u64,
private: *mut *mut c_void,
) -> *mut c_void {
// SAFETY: the owner supplies this exclusively borrowed live opaque handle.
let allocation = unsafe { &*allocation.cast::<Allocation>() };
let Some((address, token)) = map_with(allocation, page_index, page_offset, bytes, |bytes| {
memory::allocate(bytes).ok()
}) else {
return ptr::null_mut();
};
// SAFETY: the C shim checked its caller's writable output slot. Ownership
// of this distinct token passes to exactly one matching unmap operation.
unsafe { private.write(token.as_ptr().cast()) };
address.as_ptr()
}
/// # Safety
/// Return a live view token once, after all CPU/device users stop. The owner
/// obeys the backing/global heap's process/deferred-context release rules.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_unmap_ram(private: *mut c_void) {
if private.is_null() {
return;
}
// SAFETY: the matching native caller exclusively owns this live token;
// dropping CpuMapping releases the pin, then its metadata storage.
unsafe {
private.cast::<CpuMapping>().drop_in_place();
memory::free(private);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bus::dma::memory::{CacheAttribute, PageBacking};
use alloc::{
alloc::{alloc_zeroed, dealloc},
boxed::Box,
sync::Arc,
vec::Vec,
};
use core::{
alloc::Layout,
sync::atomic::{AtomicUsize, Ordering},
};
unsafe extern "C" {
fn nv_alloc_kernel_mapping(
nv: *mut c_void,
allocation: *mut c_void,
page_index: u64,
page_offset: u32,
bytes: u64,
private: *mut *mut c_void,
) -> *mut c_void;
fn nv_free_kernel_mapping(
nv: *mut c_void,
allocation: *mut c_void,
address: *mut c_void,
private: *mut c_void,
);
}
struct Backing {
cpu: NonNull<u8>,
physical: Vec<u64>,
page_shift: u8,
attribute: CacheAttribute,
layout: Layout,
released: Arc<AtomicUsize>,
}
// SAFETY: the model owns one zeroed aligned RAM allocation, immutable
// mapping metadata and independent physical labels. No hardware uses it.
// Only unsafe, externally serialized test accesses dereference CPU views.
unsafe impl Send for Backing {}
// SAFETY: shared references rely on the same argument as `Send` above.
unsafe impl Sync for Backing {}
// SAFETY: the model keeps the same allocation/layout/cache metadata
// until the last pin ends; physical labels differ from VA.
unsafe impl PageBacking for Backing {
fn cpu_base(&self) -> NonNull<u8> {
self.cpu
}
fn physical_pages(&self) -> &[u64] {
&self.physical
}
fn page_shift(&self) -> u8 {
self.page_shift
}
fn cache_attribute(&self) -> CacheAttribute {
self.attribute
}
}
impl Drop for Backing {
fn drop(&mut self) {
self.released.fetch_add(1, Ordering::SeqCst);
// SAFETY: the last pin is gone; return this model
// allocation once, with its original layout.
unsafe { dealloc(self.cpu.as_ptr(), self.layout) };
}
}
fn backing(
page_shift: u8,
logical_bytes: usize,
attribute: CacheAttribute,
released: Arc<AtomicUsize>,
) -> (PinnedPages, NonNull<u8>) {
let page_bytes = 1usize << page_shift;
let pages = logical_bytes.div_ceil(page_bytes);
let layout = Layout::from_size_align(pages * page_bytes, page_bytes).unwrap();
// SAFETY: a nonzero checked model allocation, kept by Backing.
let cpu = NonNull::new(unsafe { alloc_zeroed(layout) }).unwrap();
let backing = Backing {
cpu,
// Non-contiguous model physical pages. The existing
// canonical CPU mapping remains consecutive and independent.
physical: (0..pages)
.map(|index| 0x8000_0000 + (index * 2 * page_bytes) as u64)
.collect(),
page_shift,
attribute,
layout,
released,
};
(
PinnedPages::new(Box::new(backing), logical_bytes, page_bytes).unwrap(),
cpu,
)
}
#[test]
fn original_c_views_keep_pins_after_parent_release() {
let released = Arc::new(AtomicUsize::new(0));
let (pages, cpu) = backing(
12,
3 * 4096,
CacheAttribute::WriteBack,
Arc::clone(&released),
);
let mut allocation = Box::pin(Allocation::new(pages));
let (mut first, mut second) = (ptr::null_mut(), ptr::null_mut());
// SAFETY: the handle is live/pinned; all native calls and CPU uses
// here are synchronous, serialized and in a normal test context.
let (a, b) = unsafe {
let raw = allocation.as_mut().as_raw();
let a = nv_alloc_kernel_mapping(ptr::null_mut(), raw, 1, 4090, 32, &mut first);
let b = nv_alloc_kernel_mapping(ptr::null_mut(), raw, 2, 0, 20, &mut second);
(a, b)
};
assert!(!first.is_null() && !second.is_null());
assert_ne!(first, second, "independent view ownership tokens");
// SAFETY: these checked ranges lie in the live model allocation.
unsafe {
assert_eq!(a, cpu.add(8186).as_ptr().cast());
assert_eq!(b, cpu.add(8192).as_ptr().cast());
a.cast::<u8>().write_bytes(0x6d, 32);
assert_eq!(b.cast::<u8>().read(), 0x6d);
}
drop(allocation);
assert_eq!(released.load(Ordering::SeqCst), 0);
// SAFETY: both tokens independently keep their ranges/pins, so the
// parent is no longer needed. Return each token once after its uses.
unsafe {
nv_free_kernel_mapping(ptr::null_mut(), ptr::null_mut(), a, first);
assert_eq!(released.load(Ordering::SeqCst), 0);
assert_eq!(b.cast::<u8>().read(), 0x6d);
nv_free_kernel_mapping(ptr::null_mut(), ptr::null_mut(), b, second);
}
assert_eq!(released.load(Ordering::SeqCst), 1);
}
#[test]
fn original_c_bounds_use_native_pages_and_exact_logical_length() {
let released = Arc::new(AtomicUsize::new(0));
let page_bytes = 16384;
let logical_bytes = 2 * page_bytes + 37;
let (pages, cpu) = backing(
14,
logical_bytes,
CacheAttribute::Uncached,
Arc::clone(&released),
);
let mut allocation = Box::pin(Allocation::new(pages));
// SAFETY: live pinned native handle with serialized C calls.
unsafe {
let raw = allocation.as_mut().as_raw();
for (index, offset, bytes) in [
(u64::MAX, 0, 1),
(0, page_bytes as u32, 1),
(0, u32::MAX, 1),
(0, 0, u64::MAX),
(2, 37, 1),
(2, 36, 2),
(3, 0, 0),
] {
let mut private = ptr::dangling_mut();
assert!(
nv_alloc_kernel_mapping(
ptr::null_mut(),
raw,
index,
offset,
bytes,
&mut private
)
.is_null()
);
assert!(private.is_null(), "failure clears the output token");
}
let mut private = ptr::dangling_mut();
assert!(
nv_alloc_kernel_mapping(ptr::null_mut(), ptr::null_mut(), 0, 0, 1, &mut private)
.is_null()
);
assert!(private.is_null());
assert!(
nv_alloc_kernel_mapping(ptr::null_mut(), raw, 0, 0, 1, ptr::null_mut()).is_null()
);
// Cross a real native page boundary and end exactly at the
// logical payload; whole-page tail padding is never exposed.
let address = nv_alloc_kernel_mapping(
ptr::null_mut(),
raw,
1,
page_bytes as u32 - 11,
48,
&mut private,
);
assert_eq!(address, cpu.add(2 * page_bytes - 11).as_ptr().cast());
assert!(!private.is_null());
nv_free_kernel_mapping(ptr::null_mut(), raw, address, private);
// An empty view at the logical end keeps a real pin and token;
// it grants no byte access to the page padding.
let address = nv_alloc_kernel_mapping(ptr::null_mut(), raw, 2, 37, 0, &mut private);
assert_eq!(address, cpu.add(logical_bytes).as_ptr().cast());
assert!(!private.is_null());
nv_free_kernel_mapping(ptr::null_mut(), raw, address, private);
nv_free_kernel_mapping(ptr::null_mut(), raw, ptr::null_mut(), ptr::null_mut());
}
drop(allocation);
assert_eq!(released.load(Ordering::SeqCst), 1);
}
#[test]
fn view_metadata_failure_does_not_leak_the_temporary_pin() {
let released = Arc::new(AtomicUsize::new(0));
let (pages, _) = backing(
12,
4096,
CacheAttribute::WriteCombining,
Arc::clone(&released),
);
let allocation = Allocation::new(pages);
let mut called = false;
assert!(
map_with(&allocation, 0, 0, 17, |bytes| {
called = true;
assert_eq!(bytes, size_of::<CpuMapping>() as u64);
None
})
.is_none()
);
assert!(called);
let view = allocation.mapping(0, 0, 17).unwrap();
assert_eq!(view.cache_attribute(), CacheAttribute::WriteCombining);
drop(view);
drop(allocation);
assert_eq!(released.load(Ordering::SeqCst), 1);
}
}
@@ -1,24 +0,0 @@
# SPDX-License-Identifier: GPL-2.0-or-later
# Shared by core.mk and modeset.mk, which `cargo xtask gpu nvidia` reads after
# NVIDIA's unchanged component Makefile, with STELA naming this port's
# directory. NVIDIA's own rules compile every object; these add Stela's port
# sources and archive the COFF objects for the UEFI link instead of NVIDIA's
# ELF partial link.
$(foreach src,$(STELA_SRCS),$(eval $(call DEFINE_OBJECT_RULE,TARGET,$(src))))
STELA_PORT_OBJS := $(call BUILD_OBJECT_LIST,$(STELA_SRCS))
$(STELA_PORT_OBJS): CFLAGS += -I $(STELA) -idirafter $(STELA)/../compat/freebsd -I $(OUTPUTDIR)
# The port names its firmware directory by version.mk's generated header.
$(STELA_PORT_OBJS): $(OUTPUTDIR)/version.h
# NVIDIA's object rules drop source directories, so refuse a Stela source whose
# object would replace one of NVIDIA's.
STELA_BASENAMES := $(notdir $(basename $(ALL_SRCS) $(STELA_SRCS)))
ifneq ($(words $(STELA_BASENAMES)),$(words $(sort $(STELA_BASENAMES))))
$(error duplicate NVIDIA object basenames: $(sort $(foreach name,$(STELA_BASENAMES),$(if $(word 2,$(filter $(name),$(STELA_BASENAMES))),$(name)))))
endif
.PHONY: stela-archive
stela-archive: $(STELA_ARCHIVE)
$(STELA_ARCHIVE): $(STELA_OBJS) $(STELA_PORT_OBJS)
$(RM) $@
$(AR) rcs $@ $^
@@ -1,11 +0,0 @@
# SPDX-License-Identifier: GPL-2.0-or-later
# Stela's archive of NVIDIA's unchanged resource manager; see common.mk.
STELA_SRCS := $(addprefix $(STELA)/,stela_pci.c stela_memory.c stela_ram_mapping.c stela_pages.c \
stela_page_geometry.c stela_ordering.c stela_device.c stela_mmio.c stela_firmware.c \
stela_primitives.c stela_nvlink_primitives.c stela_nvswitch_primitives.c \
stela_nvlink_memory.c)
# Stela's runtime owns the standard memory symbols. gcc_helper.c aliases them
# to os_mem_*, which would recurse when the port's hooks call the runtime.
STELA_OBJS = $(filter-out $(OUTPUTDIR)/gcc_helper.o,$(OBJS))
STELA_ARCHIVE := $(OUTPUTDIR)/libnv-kernel.a
include $(STELA)/build/common.mk
@@ -1,16 +0,0 @@
# SPDX-License-Identifier: GPL-2.0-or-later
# Stela's archive of NVIDIA's unchanged display core; see common.mk.
STELA_SRCS := $(addprefix $(STELA)/,stela_nvkms_primitives.c stela_nvkms_memory.c)
# NVIDIA embeds its compressed shaders with an ELF binary link. Stela embeds the
# same files into COFF objects with the symbols NVKMS reads.
STELA_SHADERS := $(SHADER_OBJS:.xz.o=.xz)
STELA_SHADER_OBJS := $(addsuffix .coff.o,$(STELA_SHADERS))
STELA_OBJS = $(filter-out $(SHADER_OBJS),$(OBJS)) $(STELA_SHADER_OBJS)
STELA_ARCHIVE := $(OUTPUTDIR)/libnv-modeset-kernel.a
include $(STELA)/build/common.mk
$(STELA_SHADER_OBJS): %.coff.o: %
symbol=_binary_$(subst -,_,$(subst .,_,$(notdir $<))); \
printf '.section .rdata,"dr"\n.globl %s_start\n%s_start:\n.incbin "%s"\n.globl %s_end\n%s_end:\n' \
$$symbol $$symbol $(abspath $<) $$symbol $$symbol > $@.S
$(CC) $(EXTRA_CFLAGS) -c -x assembler $@.S -o $@
@@ -1,481 +0,0 @@
//! Owned CPU preparation of the original native device state, before RM.
//! No RM entry, PCI enable, GPU mapping, IRQ, firmware or submission is invoked.
use super::{
PciHandle,
services::{MemoryServices, ServiceError},
};
use crate::bus::{
dma::{mapping::DmaDomain, memory::PageSource},
mmio::owned::{Resource, ResourceKind},
pci::{Address, ConfigSpace},
};
use alloc::{
alloc::{alloc_zeroed, dealloc},
boxed::Box,
sync::Arc,
};
use core::{
alloc::Layout,
cell::{Cell, UnsafeCell},
ffi::c_void,
marker::{PhantomData, PhantomPinned},
pin::Pin,
ptr::NonNull,
};
use triomphe::UniqueArc;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Identity {
pub address: Address,
pub vendor: u16,
pub device: u16,
pub subsystem_vendor: u16,
pub subsystem: u16,
pub virtual_function: bool,
}
/// The index is the PCI configuration BAR index, not the original RM role.
pub struct Aperture {
pub index: u8,
pub resource: Resource,
}
/// Original REGS/FB/IMEM roles. The C constructor checks their original order
/// against BAR encodings; a caller cannot relabel arbitrary resources.
pub struct Apertures {
pub registers: Aperture,
pub framebuffer: Aperture,
pub instance: Option<Aperture>,
}
/// Same-PF power/reset/resource epoch. No implementation is supplied.
///
/// # Safety
/// This owns the immutable identity, exclusive D0/parent-bridge/reset/
/// removal epoch and Resources of the SAME function as the owned ConfigSpace.
/// Resources independently keep teardown-critical backing, including canonical
/// mapping quarantine. Their reported spans/kinds/roles are assigned BARs.
/// Exclude every other driver, firmware, DMA, IRQ, reset and configuration user.
/// `check_context` checks the allowed process/native CPU without device
/// access, allocation, unwind or reentry. Calls and final release obey the heap,
/// PageSource, domain and resource owners' real context rules. It supplies no
/// allocator, IRQ-context predicate, timer or initialized-RM assertion.
pub unsafe trait Owner: 'static {
fn identity(&self) -> Identity;
fn apertures(&self) -> Apertures;
fn check_context(&self) -> Result<(), i32>;
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Error {
InvalidOwner,
InvalidResource,
InvalidLayout,
OutOfMemory,
Context(i32),
Config(crate::bus::pci::ConfigError),
Native(u32),
Services(ServiceError),
Retired,
}
#[repr(C)]
struct NativeBar {
physical: u64,
bytes: u64,
index: u32,
prefetchable: u32,
}
#[repr(C)]
struct NativeIdentity {
domain: u32,
bus: u32,
slot: u32,
function: u32,
vendor: u32,
device: u32,
subsystem_vendor: u32,
subsystem: u32,
}
const _: () = assert!(size_of::<NativeBar>() == 24 && size_of::<NativeIdentity>() == 32);
unsafe extern "C" {
fn stela_nvidia_state_layout(bytes: *mut u64, alignment: *mut u64);
fn stela_nvidia_prepare_device(
state: *mut c_void,
handle: *mut c_void,
identity: &NativeIdentity,
bars: *const NativeBar,
count: u32,
) -> u32;
fn stela_nvidia_prepared_device_retirable(state: *const c_void, handle: *const c_void) -> u32;
}
struct State {
pointer: NonNull<u8>,
layout: Layout,
}
impl State {
fn reserve() -> Result<Self, Error> {
let (mut bytes, mut alignment) = (0, 0);
// SAFETY: original C type layout query; no native resource access.
unsafe { stela_nvidia_state_layout(&mut bytes, &mut alignment) };
let bytes = usize::try_from(bytes).map_err(|_| Error::InvalidLayout)?;
let alignment = usize::try_from(alignment).map_err(|_| Error::InvalidLayout)?;
let layout = Layout::from_size_align(bytes, alignment).map_err(|_| Error::InvalidLayout)?;
if bytes == 0 {
return Err(Error::InvalidLayout);
}
#[cfg(test)]
tests::reserve()?;
// SAFETY: exact checked original type layout, existing common allocator.
let pointer = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(Error::OutOfMemory)?;
Ok(Self { pointer, layout })
}
fn raw(&self) -> *mut c_void {
self.pointer.as_ptr().cast()
}
}
impl Drop for State {
fn drop(&mut self) {
// SAFETY: exact checked allocation; no users remain on known retirement.
unsafe { dealloc(self.pointer.as_ptr(), self.layout) };
}
}
// Drop order matters: internal references end before their wholly owned targets.
// UnsafeCell prevents a shared Bundle observation freezing the private C-owned
// service/configuration storage. There are no public field projections.
struct Bundle<C: ConfigSpace + 'static> {
services: UnsafeCell<Option<MemoryServices<'static>>>,
pci: UnsafeCell<Option<PciHandle<'static>>>,
state: State,
config: UnsafeCell<Box<C>>,
_source: Box<dyn PageSource>,
owner: Box<dyn Owner>,
_apertures: Apertures,
identity: Identity,
callback_failure: Cell<Option<Error>>,
_pin: PhantomPinned,
}
impl<C: ConfigSpace + 'static> Bundle<C> {
fn callback_context(&self) -> Result<(), Error> {
if let Some(status) = self.callback_failure.get() {
return Err(status);
}
let result = self.owner.check_context().map_err(Error::Context);
if let Err(status) = result {
// Preserve the first callback-context failure. A later
// successful query cannot certify an effect that was uncertain.
self.callback_failure.set(Some(status));
}
result
}
}
// These private callbacks reuse the existing three-word PCI ABI and its exact
// failure return, not a ConfigSpace sentinel value or a new transport. The
// native constructor owns no other access to config. Bundle/owner/config are
// stable and callbacks are serialized, with no reentry or public raw escape.
unsafe extern "C" fn checked_read<C: ConfigSpace + 'static>(
context: *mut c_void,
offset: u32,
width: u32,
value: *mut u32,
) -> u32 {
// SAFETY: this context is the same live private pinned Bundle.
let this = unsafe { &*context.cast::<Bundle<C>>() };
if this.callback_context().is_err() || !super::valid_access(offset, width) {
return 0;
}
// SAFETY: exclusive serialized config access, disjoint from owner/latch.
let config = unsafe { &**this.config.get() };
let result = match super::read_config(config, offset as u16, width) {
Ok(result) => result,
Err(error) => {
// Seal admission BEFORE another owner callback can run/recover.
this.callback_failure.set(Some(Error::Config(error)));
return 0;
}
};
if this.callback_context().is_err() {
return 0;
}
// SAFETY: original C shim supplies live aligned writable u32.
unsafe { value.write(result) };
1
}
unsafe extern "C" fn checked_write<C: ConfigSpace + 'static>(
context: *mut c_void,
offset: u32,
width: u32,
value: u32,
) -> u32 {
// SAFETY: same private stable Bundle and serialized callback ABI.
let this = unsafe { &*context.cast::<Bundle<C>>() };
if this.callback_context().is_err() || !super::valid_access(offset, width) {
return 0;
}
// SAFETY: unique configuration target through its disjoint UnsafeCell.
let config = unsafe { &mut **this.config.get() };
if let Err(error) = super::write_config(config, offset as u16, width, value) {
this.callback_failure.set(Some(Error::Config(error)));
return 0;
}
if this.callback_context().is_err() {
return 0;
}
1
}
/// Pinned, fully owned prepared metadata. Neither Send nor Sync. No safe C
/// pointer or runtime-ready token escapes, and no method calls original RM.
/// Explicit retirement failure keeps the whole bundle. Drop uncertainty
/// keeps that SAME allocation and every owner indefinitely;
/// it cannot extend a borrow, fake reset/drain or release partially live state.
pub struct PreparedDevice<C: ConfigSpace + 'static> {
bundle: Option<Pin<UniqueArc<Bundle<C>>>>,
}
fn native_bar(bar: &Aperture) -> Result<NativeBar, Error> {
let span = bar.resource.physical_span();
if bar.index >= 6 || span.start() == 0 {
return Err(Error::InvalidResource);
}
Ok(NativeBar {
physical: span.start(),
bytes: span.bytes(),
index: u32::from(bar.index),
prefetchable: u32::from(bar.resource.kind() == ResourceKind::PrefetchableMemory),
})
}
impl<C: ConfigSpace + 'static> PreparedDevice<C> {
/// Assemble native input ownership, without invoking RM.
///
/// # Safety
/// `owner`, owned `config`, source and attached `domain` describe the SAME
/// PF/reset epoch. The domain/address_limit is its real isolated DMA
/// policy, not identity DMA or a guessed GPU address width. Source
/// geometry must already be installed before any RM callers. The heap and
/// all owned dependencies remain valid through final retirement/quarantine.
/// No caller keeps configuration/native aliases or may reenter this scope.
/// Box/Arc inputs must own their dependencies; borrowed/non-static stand-ins
/// cannot survive uncertainty and are excluded.
pub unsafe fn prepare(
config: Box<C>,
owner: Box<dyn Owner>,
source: Box<dyn PageSource>,
domain: Arc<dyn DmaDomain>,
page_shift: u8,
address_limit: u64,
) -> Result<Self, Error> {
if let Err(status) = owner.check_context() {
// No allocation or final owner release is safe in an unchecked
// context. These inputs are already wholly owned; keep all of
// them without allocating a bundle or extending any borrow.
core::mem::forget((config, owner, source, domain));
return Err(Error::Context(status));
}
// Keep every dependency and prepared allocation outside this fallible
// phase. A provider callback may refuse after context is lost; no `?`
// inside the phase may then release the last owner.
let (mut apertures, mut services, mut state) = (None, None, None);
let prepared = (|| {
let identity = owner.identity();
owner.check_context().map_err(Error::Context)?;
if identity.vendor != 0x10de
|| identity.device == 0xffff
|| identity.virtual_function
|| identity.address.device >= 32
|| identity.address.function >= 8
{
return Err(Error::InvalidOwner);
}
apertures = Some(owner.apertures());
owner.check_context().map_err(Error::Context)?;
let apertures = apertures.as_ref().expect("prepared apertures");
if apertures.registers.resource.kind() != ResourceKind::Registers {
return Err(Error::InvalidResource);
}
let mut bars = [
native_bar(&apertures.registers)?,
native_bar(&apertures.framebuffer)?,
NativeBar {
physical: 0,
bytes: 0,
index: 0,
prefetchable: 0,
},
];
let count = if let Some(bar) = &apertures.instance {
bars[2] = native_bar(bar)?;
3
} else {
2
};
for i in 0..count {
for j in i + 1..count {
if bars[i].physical < bars[j].physical + bars[j].bytes
&& bars[j].physical < bars[i].physical + bars[i].bytes
{
return Err(Error::InvalidResource);
}
}
}
// Metadata callbacks cannot authorize the following provider call.
owner.check_context().map_err(Error::Context)?;
// SAFETY: stable owned Box target. The private bundle drops services
// before source, or BOTH are held on uncertain context. No
// internal lifetime or source reference is exposed to a caller.
let source_ref: &'static dyn PageSource =
unsafe { &*(&*source as *const dyn PageSource) };
// SAFETY: caller supplies the requester/domain/cache contract.
// Keep the original Arc until context is checked on either result;
// the constructor's error may drop only this non-final clone.
services = Some(
unsafe {
MemoryServices::new(
source_ref,
Arc::clone(&domain),
identity.address,
page_shift,
address_limit,
)
}
.map_err(Error::Services)?,
);
// A successful geometry callback can still lose context. Do not
// allocate state or touch configuration until it is requalified.
owner.check_context().map_err(Error::Context)?;
state = Some(State::reserve()?);
// Requalify before the next heap effect; a failed phase still
// keeps this reserved State with all dependency owners.
owner.check_context().map_err(Error::Context)?;
#[cfg(test)]
tests::reserve()?;
let storage =
UniqueArc::<Bundle<C>>::try_new_uninit().map_err(|_| Error::OutOfMemory)?;
Ok((identity, bars, count, storage))
})();
if let Err(status) = owner.check_context() {
// Covers success AND error of every callback/reservation above,
// including source geometry refusal. Keep all exact ownership;
// no final Arc release, metadata free or allocation is attempted.
core::mem::forget((
config, owner, source, domain, apertures, services, state, prepared,
));
return Err(Error::Context(status));
}
let (identity, bars, count, mut storage) = prepared?;
// The service owns another Arc, and the context remains valid.
drop(domain);
storage.write(Bundle {
services: UnsafeCell::new(services),
pci: UnsafeCell::new(None),
state: state.expect("reserved state"),
config: UnsafeCell::new(config),
_source: source,
owner,
_apertures: apertures.expect("prepared apertures"),
identity,
callback_failure: Cell::new(None),
_pin: PhantomPinned,
});
// SAFETY: every field was initialized once in its final unique allocation.
let mut bundle = unsafe { Pin::new_unchecked(UniqueArc::assume_init(storage)) };
// SAFETY: unique unpublished pinned allocation; no native/Rust aliases.
let this = unsafe { bundle.as_mut().get_unchecked_mut() };
let context = (this as *mut Bundle<C>).cast();
// SAFETY: still unpublished. The same existing PciHandle ABI points
// back to this pinned owned Bundle; no safe reference or raw C pointer
// escapes. Per-access callbacks check context and keep the
// first failure before native preparation may publish any state.
let pci = unsafe { &mut *this.pci.get() };
*pci = Some(PciHandle {
context,
read: checked_read::<C>,
write: checked_write::<C>,
target: core::ptr::null_mut(),
failure: Cell::new(None),
_borrow: PhantomData,
_pin: PhantomPinned,
});
// SAFETY: handle now occupies its final pinned slot until retirement.
let handle =
unsafe { Pin::new_unchecked(pci.as_mut().expect("initialized handle")).as_raw() };
let id = NativeIdentity {
domain: u32::from(identity.address.segment),
bus: u32::from(identity.address.bus),
slot: u32::from(identity.address.device),
function: u32::from(identity.address.function),
vendor: u32::from(identity.vendor),
device: u32::from(identity.device),
subsystem_vendor: u32::from(identity.subsystem_vendor),
subsystem: u32::from(identity.subsystem),
};
// SAFETY: original C state, pinned handle and bounded disjoint
// CPU inputs. This reads configuration only; error publishes no state.
let status = unsafe {
stela_nvidia_prepare_device(this.state.raw(), handle, &id, bars.as_ptr(), count as u32)
};
if let Err(status) = this.callback_context() {
// Configuration callbacks cannot grant a different CPU/context.
// Keep the same complete reserved bundle if validation is lost.
core::mem::forget(bundle);
return Err(status);
}
if status != 0 {
return Err(Error::Native(status));
}
// SAFETY: all fallible reservations/validation finished. Original state
// has real PCI identity and empty slots; no native caller can access it.
unsafe {
Pin::new_unchecked(
(&mut *this.services.get())
.as_mut()
.expect("reserved service"),
)
.bind(this.state.raw())
}
.map_err(Error::Services)?;
Ok(Self {
bundle: Some(bundle),
})
}
pub fn identity(&self) -> Option<Identity> {
self.bundle.as_ref().map(|b| b.identity)
}
/// Retire only still-prepared metadata. A real refusal leaves ALL ownership
/// intact and retryable; this performs no hardware/RM/reset operation.
pub fn retire(&mut self) -> Result<(), Error> {
let bundle = self.bundle.as_mut().ok_or(Error::Retired)?;
if let Some(status) = bundle.callback_failure.get() {
return Err(status);
}
bundle.owner.check_context().map_err(Error::Context)?;
// SAFETY: exclusive prepared device, no C pointer escaped. Context and
// the existing services' live counters govern final release.
let this = unsafe { bundle.as_mut().get_unchecked_mut() };
// SAFETY: `this` is exclusive, and the bound handle never moves out of its cell.
let handle = unsafe {
Pin::new_unchecked((&mut *this.pci.get()).as_mut().expect("bound handle")).as_raw()
};
// SAFETY: both pointers belong to this live prepared device.
let status = unsafe { stela_nvidia_prepared_device_retirable(this.state.raw(), handle) };
this.callback_context()?;
if status != 0 {
return Err(Error::Native(status));
}
// SAFETY: `this` is exclusive, and the bound services never move out of their cell.
unsafe {
Pin::new_unchecked((&mut *this.services.get()).as_mut().expect("bound service"))
.unbind()
}
.map_err(Error::Services)?;
self.bundle = None;
Ok(())
}
}
impl<C: ConfigSpace + 'static> Drop for PreparedDevice<C> {
fn drop(&mut self) {
if self.bundle.is_some() && self.retire().is_err() {
// Keep wholly OWNED state/handles/source/config/resources/
// reset owner, using existing allocation ownership. No borrow is
// extended and no quarantine registry or late allocation is added.
if let Some(bundle) = self.bundle.take() {
core::mem::forget(bundle);
}
}
}
}
#[cfg(test)]
mod tests;
@@ -1,769 +0,0 @@
//! CPU-only owned canonical resource/config/page models; no RM or hardware.
use super::*;
use crate::bus::pci::ConfigError;
use crate::bus::{
dma::{
mapping::{Direction, DmaError, DomainMapping},
memory::{CacheAttribute, MemoryError, PageBacking, PageGeometry, PinnedPages},
},
mmio::owned::{PhysicalSpan, ResourceBacking},
};
use alloc::vec::Vec;
use core::{
cell::Cell,
ops::Range,
sync::atomic::{AtomicBool, AtomicUsize, Ordering},
};
extern crate std;
std::thread_local! { static BUDGET: Cell<Option<usize>> = const {Cell::new(None)}; }
pub(super) fn reserve() -> Result<(), Error> {
BUDGET.with(|b| match b.get() {
Some(0) => Err(Error::OutOfMemory),
Some(n) => {
b.set(Some(n - 1));
Ok(())
}
None => Ok(()),
})
}
struct Counts {
drops: [AtomicUsize; 5],
context: AtomicBool,
reads: AtomicUsize,
lose_context: AtomicBool,
lose_at: AtomicUsize,
geometry_failure: AtomicUsize,
geometry_calls: AtomicUsize,
metadata_loss: AtomicUsize,
recover_on_check: AtomicBool,
writes: AtomicUsize,
write_width: AtomicUsize,
write_value: AtomicUsize,
write_loss: AtomicBool,
config_read_failure: AtomicBool,
config_write_failure: AtomicBool,
}
impl Counts {
fn new() -> Arc<Self> {
Arc::new(Self {
drops: core::array::from_fn(|_| AtomicUsize::new(0)),
context: AtomicBool::new(true),
reads: AtomicUsize::new(0),
lose_context: AtomicBool::new(false),
lose_at: AtomicUsize::new(60),
geometry_failure: AtomicUsize::new(0),
geometry_calls: AtomicUsize::new(0),
metadata_loss: AtomicUsize::new(0),
recover_on_check: AtomicBool::new(false),
writes: AtomicUsize::new(0),
write_width: AtomicUsize::new(0),
write_value: AtomicUsize::new(0),
write_loss: AtomicBool::new(false),
config_read_failure: AtomicBool::new(false),
config_write_failure: AtomicBool::new(false),
})
}
fn values(&self) -> [usize; 5] {
core::array::from_fn(|i| self.drops[i].load(Ordering::SeqCst))
}
}
struct Config {
words: [u32; 16],
counts: Arc<Counts>,
}
impl ConfigSpace for Config {
fn read32(&self, offset: u16) -> Result<u32, crate::bus::pci::ConfigError> {
self.counts.reads.fetch_add(1, Ordering::SeqCst);
if self.counts.config_read_failure.load(Ordering::SeqCst) {
return Err(ConfigError::before_effect(
crate::bus::pci::ConfigFailure::ForeignGrant,
));
}
if usize::from(offset) == self.counts.lose_at.load(Ordering::SeqCst)
&& self.counts.lose_context.load(Ordering::SeqCst)
{
self.counts.context.store(false, Ordering::SeqCst);
}
Ok(self.words[usize::from(offset) / 4])
}
fn write32(&mut self, offset: u16, value: u32) -> Result<(), crate::bus::pci::ConfigError> {
self.record_write(4, value);
if self.counts.config_write_failure.load(Ordering::SeqCst) {
return Err(ConfigError::write_may_have_applied(
offset,
4,
crate::bus::pci::ConfigFailure::ForeignGrant,
));
}
Ok(())
}
fn write16(&mut self, offset: u16, value: u16) -> Result<(), crate::bus::pci::ConfigError> {
self.record_write(2, u32::from(value));
if self.counts.config_write_failure.load(Ordering::SeqCst) {
return Err(ConfigError::write_may_have_applied(
offset,
2,
crate::bus::pci::ConfigFailure::ForeignGrant,
));
}
Ok(())
}
fn write8(&mut self, offset: u16, value: u8) -> Result<(), crate::bus::pci::ConfigError> {
self.record_write(1, u32::from(value));
if self.counts.config_write_failure.load(Ordering::SeqCst) {
return Err(ConfigError::write_may_have_applied(
offset,
1,
crate::bus::pci::ConfigFailure::ForeignGrant,
));
}
Ok(())
}
fn read8(&self, offset: u16) -> Result<u8, crate::bus::pci::ConfigError> {
Ok((self.read32(offset & !3)? >> (8 * (offset & 3))) as u8)
}
fn read16(&self, offset: u16) -> Result<u16, crate::bus::pci::ConfigError> {
Ok((self.read32(offset & !3)? >> (8 * (offset & 2))) as u16)
}
}
impl Config {
fn record_write(&self, width: usize, value: u32) {
self.counts.writes.fetch_add(1, Ordering::SeqCst);
self.counts.write_width.store(width, Ordering::SeqCst);
self.counts
.write_value
.store(value as usize, Ordering::SeqCst);
if self.counts.write_loss.load(Ordering::SeqCst) {
self.counts.context.store(false, Ordering::SeqCst);
}
}
}
impl Drop for Config {
fn drop(&mut self) {
self.counts.drops[1].fetch_add(1, Ordering::SeqCst);
}
}
struct Backing {
span: PhysicalSpan,
kind: ResourceKind,
counts: Arc<Counts>,
}
// SAFETY: immutable distinct synthetic resource labels; never a native grant.
unsafe impl ResourceBacking for Backing {
fn begin_mapping(
&self,
) -> Result<crate::bus::pci::assignment::OpaqueUse, crate::bus::mmio::owned::Error> {
// Metadata-only RM preparation never supplies a mapper or real BAR RAM.
// Do not fabricate an assignment use or dummy allocation from labels.
Err(crate::bus::mmio::owned::Error::Unavailable)
}
fn physical_span(&self) -> PhysicalSpan {
self.span
}
fn kind(&self) -> ResourceKind {
self.kind
}
}
impl Drop for Backing {
fn drop(&mut self) {
self.counts.drops[4].fetch_add(1, Ordering::SeqCst);
}
}
struct Epoch {
identity: Identity,
bars: Apertures,
counts: Arc<Counts>,
}
// SAFETY: all input callbacks/resources are bounded CPU-only models in this test.
unsafe impl Owner for Epoch {
fn identity(&self) -> Identity {
if self.counts.metadata_loss.load(Ordering::SeqCst) == 1 {
self.counts.context.store(false, Ordering::SeqCst);
}
self.identity
}
fn apertures(&self) -> Apertures {
if self.counts.metadata_loss.load(Ordering::SeqCst) == 2 {
self.counts.context.store(false, Ordering::SeqCst);
}
let copy = |x: &Aperture| Aperture {
index: x.index,
resource: x.resource.clone(),
};
Apertures {
registers: copy(&self.bars.registers),
framebuffer: copy(&self.bars.framebuffer),
instance: self.bars.instance.as_ref().map(copy),
}
}
fn check_context(&self) -> Result<(), i32> {
if self.counts.context.load(Ordering::SeqCst) {
Ok(())
} else {
if self.counts.recover_on_check.swap(false, Ordering::SeqCst) {
self.counts.context.store(true, Ordering::SeqCst);
}
Err(-77)
}
}
}
impl Drop for Epoch {
fn drop(&mut self) {
self.counts.drops[0].fetch_add(1, Ordering::SeqCst);
}
}
struct Source(Arc<Counts>);
struct Page {
pointer: NonNull<u8>,
physical: [u64; 1],
layout: Layout,
}
// SAFETY: exclusively allocated model bytes, immutable metadata, no hardware.
unsafe impl Send for Page {}
// SAFETY: only the CPU-model pin accesses these bytes, serialized here.
unsafe impl Sync for Page {}
// SAFETY: zeroed aligned CPU allocation with distinct model PA label, pinned to Drop.
unsafe impl PageBacking for Page {
fn cpu_base(&self) -> NonNull<u8> {
self.pointer
}
fn physical_pages(&self) -> &[u64] {
&self.physical
}
fn page_shift(&self) -> u8 {
12
}
fn cache_attribute(&self) -> CacheAttribute {
CacheAttribute::WriteBack
}
}
impl Drop for Page {
fn drop(&mut self) {
// SAFETY: the pointer came from the matching allocation with this layout and is freed
// once.
unsafe { dealloc(self.pointer.as_ptr(), self.layout) }
}
}
impl PageSource for Source {
fn page_geometry(&self) -> Result<PageGeometry, MemoryError> {
self.0.geometry_calls.fetch_add(1, Ordering::SeqCst);
match self.0.geometry_failure.load(Ordering::SeqCst) {
1 => return Err(MemoryError::Unavailable),
2 => {
self.0.context.store(false, Ordering::SeqCst);
return Err(MemoryError::Unavailable);
}
3 => self.0.context.store(false, Ordering::SeqCst),
_ => {}
}
PageGeometry::base_only(12)
}
fn allocate(
&self,
bytes: usize,
alignment: usize,
cache: CacheAttribute,
) -> Result<PinnedPages, MemoryError> {
assert_eq!(
(bytes, alignment, cache),
(4096, 4096, CacheAttribute::WriteBack)
);
let layout = Layout::from_size_align(4096, 4096).unwrap();
let pointer =
// SAFETY: the layout has a nonzero size.
NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(MemoryError::OutOfMemory)?;
PinnedPages::new(
Box::new(Page {
pointer,
physical: [0x8000_0000],
layout,
}),
bytes,
alignment,
)
}
}
impl Drop for Source {
fn drop(&mut self) {
self.0.drops[2].fetch_add(1, Ordering::SeqCst);
}
}
struct Domain(Arc<Counts>);
// SAFETY: model explicitly refuses all DMA; no fake successful map or IOVA.
unsafe impl DmaDomain for Domain {
unsafe fn map(
&self,
_: &crate::bus::dma::pages::DmaPages,
_: Direction,
_: u64,
) -> Result<DomainMapping, DmaError> {
Err(DmaError::IommuUnavailable)
}
unsafe fn unmap(&self, _: DomainMapping) -> Result<(), DmaError> {
panic!("no DMA mappings")
}
unsafe fn sync_for_device(
&self,
_: DomainMapping,
_: Range<usize>,
_: Direction,
) -> Result<(), DmaError> {
panic!("no DMA mappings")
}
unsafe fn sync_for_cpu(
&self,
_: DomainMapping,
_: Range<usize>,
_: Direction,
) -> Result<(), DmaError> {
panic!("no DMA mappings")
}
}
impl Drop for Domain {
fn drop(&mut self) {
self.0.drops[3].fetch_add(1, Ordering::SeqCst);
}
}
type Inputs = (
Box<Config>,
Box<Epoch>,
Box<Source>,
Arc<Domain>,
Arc<Counts>,
);
fn inputs() -> Inputs {
super::super::page_geometry::tests::initialize_model(12);
let counts = Counts::new();
let aperture = |index, start, bytes, kind| Aperture {
index,
resource: Resource::new(Box::new(Backing {
span: PhysicalSpan::new(start, bytes).unwrap(),
kind,
counts: counts.clone(),
})),
};
let bars = Apertures {
registers: aperture(0, 0x1_1000_0000, 0x1_0000, ResourceKind::Registers),
framebuffer: aperture(
2,
0x2_2000_0000,
0x20_0000,
ResourceKind::PrefetchableMemory,
),
instance: Some(aperture(
4,
0x3_3000_0000,
0x1_0000,
ResourceKind::Registers,
)),
};
let identity = Identity {
address: Address {
segment: 3,
bus: 0x42,
device: 5,
function: 0,
},
vendor: 0x10de,
device: 0x2684,
subsystem_vendor: 0x10de,
subsystem: 0x1234,
virtual_function: false,
};
let mut words = [0; 16];
words[0] = 0x2684_10de;
words[2] = 0x0300_0001;
words[4] = 0x1000_0004;
words[5] = 1;
words[6] = 0x2000_000c;
words[7] = 2;
words[8] = 0x3000_0004;
words[9] = 3;
words[11] = 0x1234_10de;
(
Box::new(Config {
words,
counts: counts.clone(),
}),
Box::new(Epoch {
identity,
bars,
counts: counts.clone(),
}),
Box::new(Source(counts.clone())),
Arc::new(Domain(counts.clone())),
counts,
)
}
#[test]
fn original_state_identity_owned_pinning_and_known_retirement() {
let (config, owner, source, domain, c) = inputs();
let id = owner.identity;
// SAFETY: the model device, its pages and its domain belong to this test alone; no other
// driver, worker or DMA touches them.
let mut d =
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) }.unwrap();
assert_eq!(d.identity(), Some(id));
assert_eq!(c.reads.load(Ordering::SeqCst), 16);
assert_eq!(c.writes.load(Ordering::SeqCst), 0);
assert_eq!(c.values(), [0; 5]);
let state = d.bundle.as_ref().unwrap().state.raw();
let moved = Vec::from([d]);
d = moved.into_iter().next().unwrap();
assert_eq!(d.bundle.as_ref().unwrap().state.raw(), state);
d.retire().unwrap();
assert_eq!(d.identity(), None);
assert_eq!(c.values(), [1, 1, 1, 1, 3]);
assert_eq!(d.retire(), Err(Error::Retired));
drop(d);
assert_eq!(c.values(), [1, 1, 1, 1, 3]);
}
#[test]
fn mismatched_configuration_bar_roles_context_and_metadata_oom_do_not_bind() {
for failure in 0..8 {
let (mut config, mut owner, source, domain, c) = inputs();
match failure {
0 => config.words[0] ^= 1,
1 => config.words[11] ^= 1,
2 => config.words[4] ^= 0x10000,
3 => owner.bars.framebuffer.index = 4,
4 => owner.identity.virtual_function = true,
5 => c.context.store(false, Ordering::SeqCst),
6 | 7 => BUDGET.with(|b| b.set(Some(failure - 6))),
_ => unreachable!(),
}
let result =
// SAFETY: the model device, its pages and its domain belong to this test alone; no
// other driver, worker or DMA touches them.
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) };
BUDGET.with(|b| b.set(None));
assert!(result.is_err());
assert_eq!(
c.values(),
if failure == 5 {
[0; 5]
} else {
[1, 1, 1, 1, 3]
}
);
}
}
unsafe extern "C" {
fn nv_alloc_pages(
state: *mut c_void,
count: u32,
size: u64,
contiguous: u8,
cache: u32,
zeroed: u8,
unencrypted: u8,
node: i32,
ptes: *mut u64,
private: *mut *mut c_void,
) -> u32;
fn nv_free_pages(
state: *mut c_void,
count: u32,
contiguous: u8,
cache: u32,
private: *mut c_void,
) -> u32;
}
#[test]
fn real_allocation_counter_refusal_keeps_every_owner_and_can_retry() {
let (config, owner, source, domain, c) = inputs();
// SAFETY: the model device, its pages and its domain belong to this test alone; no other
// driver, worker or DMA touches them.
let mut d =
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) }.unwrap();
let state = d.bundle.as_ref().unwrap().state.raw();
let (mut pa, mut allocation) = (0, core::ptr::null_mut());
assert_eq!(
// SAFETY: `state` is this test's prepared device, and the out pointers are live locals.
unsafe { nv_alloc_pages(state, 1, 4096, 0, 0, 1, 0, -1, &mut pa, &mut allocation) },
0
);
assert_eq!(pa, 0x8000_0000);
assert!(matches!(d.retire(), Err(Error::Services(_))));
assert_eq!(c.values(), [0; 5]);
assert!(d.identity().is_some());
// SAFETY: the model device is stopped and drained, so nothing still uses what this
// releases.
assert_eq!(unsafe { nv_free_pages(state, 1, 0, 0, allocation) }, 0);
d.retire().unwrap();
assert_eq!(c.values(), [1, 1, 1, 1, 3]);
}
#[test]
fn drop_uncertainty_keeps_whole_owned_bundle_without_extending_borrows() {
let (config, owner, source, domain, c) = inputs();
// SAFETY: the model device, its pages and its domain belong to this test alone; no other
// driver, worker or DMA touches them.
let mut d =
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) }.unwrap();
c.context.store(false, Ordering::SeqCst);
assert_eq!(d.retire(), Err(Error::Context(-77)));
drop(d);
assert_eq!(c.values(), [0; 5]); // Intentional permanent owned retention.
c.context.store(true, Ordering::SeqCst);
assert_eq!(c.values(), [0; 5]);
}
#[test]
fn lost_context_after_config_and_live_allocation_drop_keep_all_storage_alive() {
let (config, owner, source, domain, c) = inputs();
c.lose_context.store(true, Ordering::SeqCst);
assert!(matches!(
// SAFETY: the model device, its pages and its domain belong to this test alone; no
// other driver, worker or DMA touches them.
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) },
Err(Error::Context(-77))
));
assert_eq!(c.reads.load(Ordering::SeqCst), 16);
assert_eq!(c.values(), [0; 5]);
let (config, owner, source, domain, c) = inputs();
// SAFETY: the model device, its pages and its domain belong to this test alone; no other
// driver, worker or DMA touches them.
let mut d =
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) }.unwrap();
let state = d.bundle.as_ref().unwrap().state.raw();
let (mut pa, mut allocation) = (0, core::ptr::null_mut());
assert_eq!(
// SAFETY: `state` is this test's prepared device, and the out pointers are live locals.
unsafe { nv_alloc_pages(state, 1, 4096, 0, 0, 1, 0, -1, &mut pa, &mut allocation) },
0
);
assert!(matches!(d.retire(), Err(Error::Services(_))));
drop(d);
assert_eq!(c.values(), [0; 5]);
// This test-only kept token is the allocation produced above.
// Its successful real free after Drop exercises still-live State/services,
// source and domain, rather than observing leaked bookkeeping.
// SAFETY: the model device is stopped and drained, so nothing still uses what this
// releases.
assert_eq!(unsafe { nv_free_pages(state, 1, 0, 0, allocation) }, 0);
assert_eq!(c.values(), [0; 5]);
}
#[test]
fn configured_geometry_refusal_precedes_allocation_and_binding() {
let (config, owner, source, domain, c) = inputs();
assert!(matches!(
// SAFETY: the model device, its pages and its domain belong to this test alone; no
// other driver, worker or DMA touches them.
unsafe { PreparedDevice::prepare(config, owner, source, domain, 13, u64::MAX) },
Err(Error::Services(_))
));
assert_eq!(c.reads.load(Ordering::SeqCst), 0);
assert_eq!(c.values(), [1, 1, 1, 1, 3]);
}
#[test]
fn native_failure_and_provider_error_context_loss_keep_all_owned_inputs() {
let (mut config, owner, source, domain, c) = inputs();
config.words[0] ^= 1;
c.lose_context.store(true, Ordering::SeqCst);
assert!(matches!(
// SAFETY: the model device, its pages and its domain belong to this test alone; no
// other driver, worker or DMA touches them.
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) },
Err(Error::Context(-77))
));
assert_eq!(c.reads.load(Ordering::SeqCst), 16);
assert_eq!(c.values(), [0; 5]);
for failure in 1..=3 {
let (config, owner, source, domain, c) = inputs();
c.geometry_failure.store(failure, Ordering::SeqCst);
BUDGET.with(|b| b.set(Some(2)));
let result =
// SAFETY: the model device, its pages and its domain belong to this test alone; no
// other driver, worker or DMA touches them.
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) };
BUDGET.with(|b| {
assert_eq!(
b.get(),
Some(2),
"no metadata allocation after provider loss"
);
b.set(None);
});
if failure == 1 {
assert!(matches!(result, Err(Error::Services(_))));
assert_eq!(c.values(), [1, 1, 1, 1, 3]);
} else {
assert!(matches!(result, Err(Error::Context(-77))));
assert_eq!(c.values(), [0; 5]);
}
assert_eq!(c.reads.load(Ordering::SeqCst), 0);
}
}
#[test]
fn metadata_context_loss_precedes_provider_allocation_and_config_access() {
for loss in 1..=2 {
let (config, owner, source, domain, c) = inputs();
c.metadata_loss.store(loss, Ordering::SeqCst);
BUDGET.with(|b| b.set(Some(2)));
assert!(matches!(
// SAFETY: the model device, its pages and its domain belong to this test alone; no
// other driver, worker or DMA touches them.
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) },
Err(Error::Context(-77))
));
BUDGET.with(|b| {
assert_eq!(b.get(), Some(2));
b.set(None);
});
assert_eq!(c.geometry_calls.load(Ordering::SeqCst), 0);
assert_eq!(c.reads.load(Ordering::SeqCst), 0);
assert_eq!(c.values(), [0; 5]);
}
}
#[test]
fn every_config_read_loss_stops_before_the_next_effect() {
for word in 0..16 {
for (mismatch, transient) in [(false, false), (true, false), (false, true), (true, true)] {
let (mut config, owner, source, domain, c) = inputs();
if mismatch {
config.words[0] ^= 1;
}
c.lose_context.store(true, Ordering::SeqCst);
c.lose_at.store(word * 4, Ordering::SeqCst);
c.recover_on_check.store(transient, Ordering::SeqCst);
assert!(matches!(
// SAFETY: the model device, its pages and its domain belong to this test alone;
// no other driver, worker or DMA touches them.
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) },
Err(Error::Context(-77))
));
assert_eq!(c.reads.load(Ordering::SeqCst), word + 1);
assert_eq!(c.values(), [0; 5]);
}
}
}
unsafe extern "C" {
fn os_pci_read_dword(handle: *mut c_void, offset: u32, out: *mut u32) -> u32;
fn os_pci_write_byte(handle: *mut c_void, offset: u32, value: u8) -> u32;
fn os_pci_write_word(handle: *mut c_void, offset: u32, value: u16) -> u32;
fn os_pci_write_dword(handle: *mut c_void, offset: u32, value: u32) -> u32;
}
// Test-only projection; the public PreparedDevice exposes no C pointer.
fn handle(d: &mut PreparedDevice<Config>) -> *mut c_void {
// SAFETY: the test only reads fields through this reference and never moves the pinned
// bundle.
let this = unsafe { d.bundle.as_mut().unwrap().as_mut().get_unchecked_mut() };
// SAFETY: the PCI owner stays pinned inside the bundle, and this test holds the only
// reference to it.
unsafe { Pin::new_unchecked((&mut *this.pci.get()).as_mut().unwrap()).as_raw() }
}
#[test]
fn pci_callback_failures_widths_and_latched_uncertainty() {
let (config, owner, source, domain, c) = inputs();
// SAFETY: the model device, its pages and its domain belong to this test alone; no other
// driver, worker or DMA touches them.
let mut d =
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) }.unwrap();
// A context refusal before any effect can be retried in the valid context.
c.context.store(false, Ordering::SeqCst);
assert_eq!(d.retire(), Err(Error::Context(-77)));
c.context.store(true, Ordering::SeqCst);
d.retire().unwrap();
assert_eq!(c.values(), [1, 1, 1, 1, 3]);
for failure in 0..=2 {
let (config, owner, source, domain, c) = inputs();
let mut d =
// SAFETY: the model device, its pages and its domain belong to this test alone; no
// other driver, worker or DMA touches them.
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) }
.unwrap();
let h = handle(&mut d);
// SAFETY: `h` is this test's model PCI handle, and `out` is a live local.
assert_eq!(unsafe { os_pci_write_byte(h, 0x40, 0xa5) }, 0);
assert_eq!(
(
c.write_width.load(Ordering::SeqCst),
c.write_value.load(Ordering::SeqCst)
),
(1, 0xa5)
);
// SAFETY: `h` is this test's model PCI handle, and `out` is a live local.
assert_eq!(unsafe { os_pci_write_word(h, 0x42, 0x8abc) }, 0);
assert_eq!(
(
c.write_width.load(Ordering::SeqCst),
c.write_value.load(Ordering::SeqCst)
),
(2, 0x8abc)
);
// SAFETY: `h` is this test's model PCI handle, and `out` is a live local.
assert_eq!(unsafe { os_pci_write_dword(h, 0x44, 0x81234567) }, 0);
assert_eq!(
(
c.write_width.load(Ordering::SeqCst),
c.write_value.load(Ordering::SeqCst)
),
(4, 0x81234567)
);
if failure == 0 {
d.retire().unwrap();
assert_eq!(c.values(), [1, 1, 1, 1, 3]);
continue;
}
if failure == 1 {
c.context.store(false, Ordering::SeqCst);
} else {
c.write_loss.store(true, Ordering::SeqCst);
c.recover_on_check.store(true, Ordering::SeqCst);
}
// SAFETY: `h` is this test's model PCI handle, and `out` is a live local.
assert_ne!(unsafe { os_pci_write_dword(h, 0x48, 0xabcdef01) }, 0);
let reads = c.reads.load(Ordering::SeqCst);
let writes = c.writes.load(Ordering::SeqCst);
assert_eq!(writes, if failure == 1 { 3 } else { 4 });
c.context.store(true, Ordering::SeqCst);
let mut out = 0x12345678;
// SAFETY: `h` is this test's model PCI handle, and `out` is a live local.
assert_ne!(unsafe { os_pci_read_dword(h, 0, &mut out) }, 0);
assert_eq!(out, u32::MAX); // Original C shim's explicit failed-read output.
// SAFETY: `h` is this test's model PCI handle, and `out` is a live local.
assert_ne!(unsafe { os_pci_write_dword(h, 0x48, 0) }, 0);
assert_eq!(c.reads.load(Ordering::SeqCst), reads);
assert_eq!(c.writes.load(Ordering::SeqCst), writes);
assert_eq!(d.retire(), Err(Error::Context(-77)));
drop(d);
assert_eq!(c.values(), [0; 5]);
}
}
#[test]
fn typed_config_preparation_and_after_write_refusals_keep_actual_graph() {
let (config, owner, source, domain, counts) = inputs();
counts.config_read_failure.store(true, Ordering::SeqCst);
let error = ConfigError::before_effect(crate::bus::pci::ConfigFailure::ForeignGrant);
// SAFETY: CPU-only immutable synthetic owner; no hardware activity.
let prepared = unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) };
assert!(matches!(prepared, Err(Error::Config(actual)) if actual == error));
assert_eq!(counts.values(), [0; 5]);
assert_eq!(counts.reads.load(Ordering::SeqCst), 1);
let (config, owner, source, domain, counts) = inputs();
// SAFETY: same bounded model with exact owned configuration/resources.
let mut device =
unsafe { PreparedDevice::prepare(config, owner, source, domain, 12, u64::MAX) }.unwrap();
let raw = handle(&mut device);
counts.config_write_failure.store(true, Ordering::SeqCst);
// SAFETY: private pinned model handle; native ABI reports failure.
assert_ne!(unsafe { os_pci_write_word(raw, 0x42, 7) }, 0);
let error =
ConfigError::write_may_have_applied(0x42, 2, crate::bus::pci::ConfigFailure::ForeignGrant);
assert_eq!(device.retire(), Err(Error::Config(error)));
counts.config_write_failure.store(false, Ordering::SeqCst);
let before = counts.writes.load(Ordering::SeqCst);
// SAFETY: serialized pinned CPU-only fixture; output/configuration is live and owned.
assert_ne!(unsafe { os_pci_write_dword(raw, 0x44, 0) }, 0);
assert_eq!(counts.writes.load(Ordering::SeqCst), before);
drop(device);
assert_eq!(counts.values(), [0; 5]);
}
-210
View File
@@ -1,210 +0,0 @@
//! Original NVIDIA DMA allocation hooks over canonical attached-domain leases.
//! Opaque dma_dev values are compared with allocation/token provenance before
//! any platform access; they are never cast into an arbitrary C device object.
use super::{
allocation::Allocation,
memory,
services::{MemoryServices, Status},
};
use crate::bus::dma::mapping::{Direction, DmaError, DmaMapping};
use alloc::sync::Arc;
use core::{ffi::c_void, ptr};
struct Token {
lease: DmaMapping,
device_key: *mut c_void,
count: u64,
}
const _: () = assert!(align_of::<Token>() <= memory::ALIGNMENT);
fn dma_error(error: DmaError) -> Status {
match error {
DmaError::IommuUnavailable => Status::NotSupported,
DmaError::InvalidRange => Status::InvalidArgument,
DmaError::AddressLimit => Status::InvalidAddress,
DmaError::Unmapped => Status::InvalidState,
_ => Status::OperatingSystem,
}
}
/// # Safety
/// The original C caller supplies the live producer Allocation in *private,
/// one writable native address slot for contiguous allocations or count slots
/// otherwise, and serialized process/deferred context. On success *private
/// changes ownership kind to a unique DMA token; the Allocation remains owned
/// separately by its original memory descriptor. No guest pointers are valid.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_dma_map(
device_key: *mut c_void,
count: u64,
addresses: *mut u64,
contiguous: u8,
read_only: u8,
private: *mut *mut c_void,
) -> Status {
// SAFETY: the C shim checks slots; the caller supplies this live
// native Allocation kind, not another import or a previous DMA token.
let allocation = unsafe { &*(*private).cast::<Allocation>() };
let Some(origin) = allocation.origin.as_ref() else {
return Status::NotSupported;
};
if device_key != origin.device_key
|| count != u64::from(origin.count)
|| contiguous != u8::from(origin.contiguous)
|| read_only > 1
{
return Status::InvalidArgument;
}
// SAFETY: producer provenance identifies the live pinned service, whose
// unbind refuses any surviving producer allocation or published DMA token.
// The arbitrary incoming device key was compared before this dereference.
let services = unsafe { &*origin.device_key.cast::<MemoryServices<'_>>() };
if !services.bound_to(origin.state) {
return Status::InvalidState;
}
if let Err(status) = services.can_map() {
return status;
}
let pages = allocation.pages();
let page_bytes = 1u64 << pages.page_shift();
let physical = pages.physical_pages();
let entries = if contiguous != 0 { 1 } else { physical.len() };
for (index, &expected) in physical.iter().take(entries).enumerate() {
// SAFETY: count/policy match the original allocation; caller supplies
// its complete native physical-PTE input/output capacity.
if unsafe { addresses.add(index).read() } != expected {
return Status::InvalidArgument;
}
}
// Reserve metadata before creating a live domain mapping. This is the
// shared global heap, not another mapping registry or DMA allocator.
let storage = match memory::allocate(size_of::<Token>() as u64) {
Ok(storage) => storage,
Err(_) => return Status::NoMemory,
};
let prepare = (|| -> Result<DmaMapping, Status> {
let direction = if read_only != 0 {
Direction::ToDevice
} else {
Direction::Bidirectional
};
let mut lease = DmaMapping::map(
Arc::clone(&origin.domain),
pages.clone(),
direction,
origin.address_limit,
)
.map_err(dma_error)?;
let valid_address = lease
.address()
.is_ok_and(|address| address.is_multiple_of(page_bytes));
let visibility = if valid_address {
lease.sync_for_device(0..lease.bytes()).map_err(dma_error)
} else {
Err(Status::InvalidAddress)
};
if let Err(error) = visibility {
// No IOVA has escaped this API, so this newly installed mapping
// has never been submitted. Real removal/invalidation still must
// finish; a failure drops into canonical observable quarantine.
// SAFETY: no device/worker can know the unpublished address.
if let Err(removal) = unsafe { lease.unmap() } {
return Err(dma_error(removal));
}
return Err(error);
}
Ok(lease)
})();
let lease = match prepare {
Ok(lease) => lease,
Err(status) => {
// SAFETY: uninitialized private metadata storage never escaped.
unsafe { memory::free(storage.as_ptr()) };
return status;
}
};
// Successful visibility, immutable live address and full bounds were
// checked before the first caller output is changed.
let address = match lease.address() {
Ok(address) => address,
Err(error) => {
// This cannot occur for the unmodified lease. Dropping
// it still quarantines pins rather than assuming teardown.
// SAFETY: the private metadata storage never escaped.
unsafe { memory::free(storage.as_ptr()) };
return dma_error(error);
}
};
// SAFETY: distinct aligned metadata owns this lease through the
// single original unmap call. It has not been published to the caller.
unsafe {
storage.cast::<Token>().as_ptr().write(Token {
lease,
device_key,
count,
});
}
services.mapped();
for index in 0..entries {
// SAFETY: output capacity matches the validated allocation policy;
// canonical mapping bounds cover the complete native page sequence.
unsafe {
addresses
.add(index)
.write(address + index as u64 * page_bytes)
};
}
// SAFETY: all fallible work/accounting completed before caller publication.
unsafe { private.write(storage.as_ptr()) };
Status::Ok
}
/// # Safety
/// Return this device's live DMA token once, with matching count, only after
/// device completion, removed GPU bindings and stopped/drained native
/// submission/IRQ workers. No new device access may start. Context must permit
/// the real domain/backing/global-heap operations and their final release.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_dma_unmap(
device_key: *mut c_void,
count: u64,
private: *mut *mut c_void,
) -> Status {
// SAFETY: the shim checked slots; the caller returns the live token
// kind created by dma_map. Never dereference the untrusted device key.
let token = unsafe { &*(*private).cast::<Token>() };
if token.device_key != device_key || token.count != count {
return Status::InvalidArgument;
}
// SAFETY: the pinned service/state outlive every published token; unbind
// refuses this live mapping count. Never dereference the supplied key.
let services = unsafe { &*token.device_key.cast::<MemoryServices<'_>>() };
if !services.has_mapping() {
return Status::InvalidState;
}
// SAFETY: validation completed and the caller transfers unique ownership
// after real quiescence. The metadata is now uninitialized and private.
let mut token = unsafe { (*private).cast::<Token>().read() };
// SAFETY: `private` is the caller's valid handle slot, read just above.
let storage = unsafe { private.replace(ptr::null_mut()) };
// Match real dma_unmap's CPU visibility before releasing translations.
// SAFETY: the caller establishes exclusive CPU ownership/completion.
let result = unsafe { token.lease.sync_for_cpu(0..token.lease.bytes()) }.and_then(|()| {
// SAFETY: the same caller-supplied complete quiescence applies.
unsafe { token.lease.unmap() }
});
// Official osIovaUnmap logs an error then clears pOsData unconditionally.
// Consume a failed live lease into canonical observable quarantine here;
// never rely on that original caller keeping a retry token. Drop keeps
// the domain/pins on any uncertain sync/removal/invalidation error.
drop(token);
services.retired();
// SAFETY: the token's value was moved out and dropped once; return only
// this exact private metadata block to the existing shared heap.
unsafe { memory::free(storage) };
match result {
Ok(()) => Status::Ok,
Err(error) => dma_error(error),
}
}
@@ -1,179 +0,0 @@
//! Original RM firmware lookup over Stela's immutable firmware catalog.
//!
//! This supplies CPU image bytes only. Manifest length/SHA-256 integrity is not
//! vendor authentication. Original RM ELF/version/signature checks, upload,
//! reset, IRQ/context services and device initialization remain required.
use super::{memory, services::MemoryServices, services::ServiceError};
use core::{ffi::CStr, ffi::c_char, ffi::c_void, ptr, ptr::NonNull};
use stela_driver_core::firmware::{Image, Provider, Requirement, Target};
unsafe extern "C" {
fn stela_nvidia_firmware_family(architecture: u32, implementation: u32) -> u32;
fn stela_nvidia_firmware_alignment() -> u64;
}
/// A provider bound to one native device's observed NVIDIA chip family. The
/// original vendor helper selects the family; no parallel architecture table.
/// Attach before pinning/binding [`MemoryServices::with_firmware`].
pub struct FirmwareBinding<'a> {
provider: &'a dyn Provider,
family: u32,
}
impl<'a> FirmwareBinding<'a> {
/// # Safety
/// `architecture` and `implementation` are the device's observed
/// original NV_ARCH facts (not PCI IDs or a guest's assertions). This binding
/// and its MemoryServices requester describe the same device/reset epoch.
/// Keep provider/catalog immutable, CPU-readable and live until all firmware
/// tokens are returned and the pinned service/state successfully unbinds.
/// Serialize every lookup/release with the other service operations; exclude
/// interrupt, allocator and provider reentry. The global heap must be live.
pub unsafe fn new(
provider: &'a dyn Provider,
architecture: u32,
implementation: u32,
) -> Result<Self, ServiceError> {
// SAFETY: pure original C selector, same native integer ABI.
let family = unsafe { stela_nvidia_firmware_family(architecture, implementation) };
if family == 0 {
return Err(ServiceError::InvalidConfiguration);
}
Ok(Self { provider, family })
}
}
struct Token<'a> {
image: Image<'a>,
owner: *const MemoryServices<'a>,
}
const _: () = assert!(align_of::<Token<'_>>() <= memory::ALIGNMENT);
fn native_length(length: usize, address: usize, alignment: usize) -> Option<u32> {
if length == 0 || alignment == 0 || !address.is_multiple_of(alignment) {
return None;
}
u32::try_from(length).ok()
}
/// All fallible preparation precedes publication/counting. The internal bounded
/// allocator seam exercises real metadata OOM without exhausting the host heap.
fn prepare<'a>(
owner: &'a MemoryServices<'a>,
state: *mut c_void,
family: u32,
requirement: Requirement<'_>,
allocate: impl FnOnce() -> Option<NonNull<c_void>>,
) -> Option<(NonNull<Token<'a>>, *const c_void, u32)> {
if !owner.bound_to(state) {
return None;
}
let binding = owner.firmware.as_ref()?;
if binding.family != family {
return None;
}
let count = owner.firmware_tokens.get().checked_add(1)?;
let image = binding.provider.load(requirement).ok()?;
// A delegating Provider can accidentally return a different valid catalog
// image. Exact name/target still must match the original vendor request.
if image.name() != requirement.name || image.target() != requirement.target {
return None;
}
// SAFETY: a pure layout query on the original vendor ELF types.
let alignment = unsafe { stela_nvidia_firmware_alignment() } as usize;
let bytes = native_length(
image.bytes().len(),
image.bytes().as_ptr() as usize,
alignment,
)?;
let buffer = image.bytes().as_ptr().cast();
let storage = allocate()?.cast::<Token<'a>>();
// SAFETY: the common heap returned sufficient/aligned exclusively owned
// metadata. The token keeps its Image/provider borrow until the unique put.
unsafe { storage.as_ptr().write(Token { image, owner }) };
owner.firmware_tokens.set(count);
Some((storage, buffer, bytes))
}
/// # Safety
/// Only the native C shim supplies this bound state/service and static original
/// selector strings. Output slots are writable, aligned and disjoint. The pinned
/// owner, catalog and original state remain live through every published token;
/// all operations obey the serialized nonreentrant process/heap contract above.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_get_firmware(
services: *mut c_void,
state: *mut c_void,
family: u32,
name: *const c_char,
hardware: *const c_char,
revision: *const c_char,
buffer: *mut *const c_void,
bytes: *mut u32,
) -> *const c_void {
// SAFETY: C only forwards the handle installed in this live original state.
let owner = unsafe { &*services.cast::<MemoryServices<'_>>() };
// SAFETY: these are static, terminated ASCII strings from original helpers.
let labels = unsafe {
(
CStr::from_ptr(name).to_str(),
CStr::from_ptr(hardware).to_str(),
CStr::from_ptr(revision).to_str(),
)
};
let (Ok(name), Ok(hardware), Ok(revision)) = labels else {
return ptr::null();
};
let result = prepare(
owner,
state,
family,
Requirement {
name,
target: Target {
driver: "nvidia-rm",
hardware,
revision,
board: None,
},
minimum_bytes: 1,
},
|| memory::allocate(size_of::<Token<'_>>() as u64).ok(),
);
let Some((token, data, size)) = result else {
return ptr::null();
};
// SAFETY: caller-owned checked native output slots. No fallible operation
// follows; publish the one unique token only after both outputs are ready.
unsafe {
bytes.write(size);
buffer.write(data);
}
token.as_ptr().cast()
}
/// # Safety
/// Return only a live firmware token from this adapter, once, after all CPU
/// readers stop. Provider/service/state/global heap remain live and operations
/// are serialized, noninterrupt and nonreentrant. No invented completion.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_put_firmware(token: *const c_void) {
// SAFETY: original nv_put_firmware filters NULL; unique token kind.
let token = token.cast_mut().cast::<Token<'_>>();
// SAFETY: the raw ownership contract keeps token and pinned service.
let value = unsafe { &*token };
// SAFETY: the token keeps its pinned owner service alive.
let owner = unsafe { &*value.owner };
debug_assert!(owner.firmware_tokens.get() > 0);
// Read the image borrow before release; no image copy or ownership escape.
let _ = value.image.bytes();
owner.firmware_tokens.set(owner.firmware_tokens.get() - 1);
// SAFETY: unique put after all token users stop; exact common-heap free.
unsafe {
token.drop_in_place();
memory::free(token.cast());
}
}
#[cfg(test)]
mod tests;
@@ -1,365 +0,0 @@
use super::*;
use crate::bus::{
dma::{
mapping::{Direction, DmaDomain, DmaError, DomainMapping},
memory::{CacheAttribute, MemoryError, PageSource, PinnedPages},
},
pci::Address,
};
use alloc::{alloc::alloc_zeroed, alloc::dealloc, boxed::Box, format, sync::Arc, vec};
use core::{alloc::Layout, cell::Cell, ops::Range, pin::Pin};
use sha2::{Digest, Sha256};
use stela_driver_core::firmware::{Catalog, Provenance, Resource};
unsafe extern "C" {
fn stela_nvidia_state_layout(bytes: *mut u64, alignment: *mut u64);
fn stela_nvidia_firmware_version() -> *const c_char;
fn nv_get_firmware(
state: *mut c_void,
kind: u32,
family: u32,
buffer: *mut *const c_void,
bytes: *mut u32,
) -> *const c_void;
fn nv_put_firmware(token: *const c_void);
}
// The explicit CPU model attests only its 4KiB geometry. It never exercises
// RAM or DMA: unsupported operations are
// failures so an accidental dependency cannot masquerade as native success.
struct Unavailable;
impl PageSource for Unavailable {
fn page_geometry(&self) -> Result<crate::bus::dma::memory::PageGeometry, MemoryError> {
crate::bus::dma::memory::PageGeometry::base_only(12)
}
fn allocate(&self, _: usize, _: usize, _: CacheAttribute) -> Result<PinnedPages, MemoryError> {
panic!("firmware lookup must not allocate RAM pins")
}
}
// SAFETY: this model can never publish any device mapping or successful sync.
unsafe impl DmaDomain for Unavailable {
unsafe fn map(
&self,
_: &crate::bus::dma::pages::DmaPages,
_: Direction,
_: u64,
) -> Result<DomainMapping, DmaError> {
panic!("firmware bytes must not become DMA addresses")
}
unsafe fn unmap(&self, _: DomainMapping) -> Result<(), DmaError> {
panic!("no DMA mapping exists")
}
unsafe fn sync_for_device(
&self,
_: DomainMapping,
_: Range<usize>,
_: Direction,
) -> Result<(), DmaError> {
panic!("no DMA mapping exists")
}
unsafe fn sync_for_cpu(
&self,
_: DomainMapping,
_: Range<usize>,
_: Direction,
) -> Result<(), DmaError> {
panic!("no DMA mapping exists")
}
}
struct State(NonNull<u8>, Layout);
impl State {
fn new() -> Self {
let (mut bytes, mut alignment) = (0, 0);
// SAFETY: writable native integer slots for original type layout.
unsafe { stela_nvidia_state_layout(&mut bytes, &mut alignment) };
let layout = Layout::from_size_align(bytes as usize, alignment as usize).unwrap();
// SAFETY: original type layout; zero PCI fixture, never GPU init.
Self(
NonNull::new(unsafe { alloc_zeroed(layout) }).unwrap(),
layout,
)
}
fn raw(&self) -> *mut c_void {
self.0.as_ptr().cast()
}
}
impl Drop for State {
fn drop(&mut self) {
// SAFETY: fixture callers and bindings ended before final release.
unsafe { dealloc(self.0.as_ptr(), self.1) };
}
}
#[repr(align(16))]
struct Aligned([u8; 32]);
static DATA: Aligned = Aligned([0x5a; 32]);
fn version() -> &'static str {
// SAFETY: C returns the static version generated from vendor version.mk.
unsafe { CStr::from_ptr(stela_nvidia_firmware_version()) }
.to_str()
.unwrap()
}
fn target(hardware: &str) -> Target<'_> {
Target {
driver: "nvidia-rm",
hardware,
revision: version(),
board: None,
}
}
fn make_catalog(name: &str, hardware: &str, bytes: &'static [u8]) -> Catalog {
Catalog::from_persistent_handoff(vec![Resource {
name,
target: target(hardware),
provenance: Provenance {
source: "synthetic CPU fixture",
revision: "1",
member: name,
license: "MIT",
},
expected_length: bytes.len(),
expected_sha256: Sha256::digest(bytes).into(),
bytes,
}])
.unwrap()
}
fn bind<'a>(
provider: Option<&'a dyn Provider>,
architecture: u32,
implementation: u32,
state: &State,
) -> Pin<Box<MemoryServices<'a>>> {
static SOURCE: Unavailable = Unavailable;
crate::nvidia::page_geometry::tests::initialize_model(12);
// SAFETY: CPU model only, same zero PCI requester; no hardware operations.
let mut service = unsafe {
MemoryServices::new(
&SOURCE,
Arc::new(Unavailable),
Address {
segment: 0,
bus: 0,
device: 0,
function: 0,
},
12,
u64::MAX,
)
}
.unwrap();
if let Some(provider) = provider {
// SAFETY: test attests this synthetic observed architecture to this model.
service = service.with_firmware(
unsafe { FirmwareBinding::new(provider, architecture, implementation) }.unwrap(),
);
}
let mut service = Box::pin(service);
// SAFETY: live original fixture state, no concurrent callers, pinned owner.
unsafe { service.as_mut().bind(state.raw()) }.unwrap();
service
}
fn request(state: *mut c_void, kind: u32, family: u32) -> (*const c_void, *const c_void, u32) {
let mut buffer = ptr::dangling::<c_void>();
let mut bytes = 0xabcd;
// SAFETY: either NULL or live fixture state; distinct writable outputs.
let token = unsafe { nv_get_firmware(state, kind, family, &mut buffer, &mut bytes) };
(token, buffer, bytes)
}
fn failed(state: *mut c_void, kind: u32, family: u32) {
let (token, buffer, bytes) = request(state, kind, family);
assert!(token.is_null());
assert_eq!(buffer, ptr::dangling());
assert_eq!(bytes, 0xabcd);
}
#[test]
fn original_selectors_cover_architecture_splits_and_all_package_kinds() {
// Frozen independent expectations from the original nv-firmware*.h switch
// bodies at the vendor pin. No production enum/selector mirror.
for (arch, implementation, family, hardware, suffix) in [
(0x160, 6, 1, "tu10x", "tu10x"),
(0x160, 7, 2, "tu11x", "tu10x"),
(0x170, 0, 3, "ga100", "tu10x"),
(0x170, 2, 4, "ga10x", "ga10x"),
(0x190, 2, 5, "ad10x", "ga10x"),
(0x180, 0, 6, "gh100", "ga10x"),
(0x1a0, 0, 8, "gb10x", "ga10x"),
(0x1b0, 0, 9, "gb20x", "ga10x"),
(0x1c0, 0, 10, "gr10x", "ga10x"),
(0x1a0, 11, 11, "gb10y", "ga10x"),
(0x1b0, 11, 12, "gb20y", "ga10x"),
(0x1b0, 12, 12, "gb20y", "ga10x"),
] {
assert_eq!(
// SAFETY: pure selector on scalar fixture values.
unsafe { stela_nvidia_firmware_family(arch, implementation) },
family
);
for (kind, prefix) in [(0, "gsp"), (1, "gsp_log"), (2, "ucodes")] {
let name = format!("nvidia/{}/{}_{}.bin", version(), prefix, suffix);
let catalog = make_catalog(&name, hardware, &DATA.0);
let state = State::new();
let mut owner = bind(Some(&catalog), arch, implementation, &state);
let (token, buffer, bytes) = request(state.raw(), kind, family);
assert!(!token.is_null());
assert_eq!(buffer, DATA.0.as_ptr().cast());
assert_eq!(bytes, 32);
assert_eq!(owner.firmware_tokens.get(), 1);
assert_eq!(
// SAFETY: a token is still live, so refusal preserves installed slots.
unsafe { owner.as_mut().unbind() },
Err(ServiceError::Native(0x40))
);
// SAFETY: no more byte readers, unique token, supported context.
unsafe { nv_put_firmware(token) };
assert_eq!(owner.firmware_tokens.get(), 0);
// SAFETY: every token/caller ended, no hardware was activated.
unsafe { owner.as_mut().unbind() }.unwrap();
}
}
}
#[test]
fn original_abi_rejects_invalid_inputs_and_preserves_outputs() {
let name = format!("nvidia/{}/gsp_ga10x.bin", version());
let catalog = make_catalog(&name, "ga10x", &DATA.0);
let state = State::new();
failed(ptr::null_mut(), 0, 4);
failed(state.raw(), 0, 4);
let mut owner = bind(Some(&catalog), 0x170, 2, &state);
for (kind, family) in [
(3, 4),
(u32::MAX, 4),
(0, 0),
(0, 7),
(0, 13),
(0, u32::MAX),
(0, 5),
(1, 4),
] {
failed(state.raw(), kind, family);
}
let mut bytes = 73;
let mut buffer = ptr::dangling::<c_void>();
// SAFETY: invalid NULL output slots are rejected before lookup/publication.
unsafe {
assert!(nv_get_firmware(state.raw(), 0, 4, ptr::null_mut(), &mut bytes).is_null());
assert!(nv_get_firmware(state.raw(), 0, 4, &mut buffer, ptr::null_mut()).is_null());
nv_put_firmware(ptr::null());
}
assert_eq!(bytes, 73);
assert_eq!(buffer, ptr::dangling());
assert_eq!(owner.firmware_tokens.get(), 0);
// SAFETY: no tokens or callers remain.
unsafe { owner.as_mut().unbind() }.unwrap();
let state = State::new();
let mut owner = bind(None, 0x170, 2, &state);
failed(state.raw(), 0, 4);
// SAFETY: no tokens or callers remain.
unsafe { owner.as_mut().unbind() }.unwrap();
// SAFETY: pure invalid architecture fixture, must refuse binding.
assert!(unsafe { FirmwareBinding::new(&catalog, 0, 0) }.is_err());
}
#[test]
fn multiple_real_tokens_prevent_unbind_until_last_put_and_keep_same_bytes() {
let name = format!("nvidia/{}/gsp_ga10x.bin", version());
let catalog = make_catalog(&name, "ga10x", &DATA.0);
let state = State::new();
let mut owner = bind(Some(&catalog), 0x170, 2, &state);
let (first, data, _) = request(state.raw(), 0, 4);
let (second, again, _) = request(state.raw(), 0, 4);
assert!(!first.is_null() && !second.is_null());
assert_ne!(first, second);
assert_eq!(data, again);
// SAFETY: first token retired, second still owned/readable; unbind refuses.
unsafe {
nv_put_firmware(first);
assert_eq!(owner.as_mut().unbind(), Err(ServiceError::Native(0x40)));
}
assert_eq!(
// SAFETY: second immutable CPU view remains held by its real token.
unsafe { core::slice::from_raw_parts(again.cast::<u8>(), 32) },
&DATA.0
);
// SAFETY: last readers stopped, return token then unbind owner.
unsafe {
nv_put_firmware(second);
owner.as_mut().unbind().unwrap();
}
failed(state.raw(), 0, 4);
}
#[test]
fn metadata_oom_count_overflow_and_invalid_image_never_publish_tokens() {
let name = format!("nvidia/{}/gsp_ga10x.bin", version());
let catalog = make_catalog(&name, "ga10x", &DATA.0);
let state = State::new();
let mut owner = bind(Some(&catalog), 0x170, 2, &state);
let requirement = Requirement {
name: &name,
target: target("ga10x"),
minimum_bytes: 1,
};
assert!(prepare(&owner, state.raw(), 4, requirement, || None).is_none());
assert_eq!(owner.firmware_tokens.get(), 0);
owner.firmware_tokens.set(usize::MAX);
assert!(
prepare(&owner, state.raw(), 4, requirement, || panic!(
"overflow must fail before metadata allocation"
))
.is_none()
);
assert_eq!(owner.firmware_tokens.get(), usize::MAX);
owner.firmware_tokens.set(0);
// SAFETY: tests' exact resource count reset; no published token ever existed.
unsafe { owner.as_mut().unbind() }.unwrap();
for (hardware, bytes) in [
("ad10x", &DATA.0[..]),
("ga10x", &DATA.0[1..]),
("ga10x", &DATA.0[0..0]),
] {
let catalog = make_catalog(&name, hardware, bytes);
let state = State::new();
let mut owner = bind(Some(&catalog), 0x170, 2, &state);
failed(state.raw(), 0, 4);
assert_eq!(owner.firmware_tokens.get(), 0);
// SAFETY: failure published no token.
unsafe { owner.as_mut().unbind() }.unwrap();
}
assert_eq!(native_length(u32::MAX as usize, 0x1000, 8), Some(u32::MAX));
assert_eq!(native_length(u32::MAX as usize + 1, 0x1000, 8), None);
assert_eq!(native_length(1, 0x1001, 8), None);
assert_eq!(native_length(0, 0x1000, 8), None);
}
#[test]
fn delegating_provider_cannot_substitute_another_valid_catalog_image() {
struct Wrong<'a>(&'a Catalog, &'a str, &'a str, Cell<usize>);
impl Provider for Wrong<'_> {
fn load(
&self,
_: Requirement<'_>,
) -> Result<Image<'_>, stela_driver_core::firmware::Error> {
self.3.set(self.3.get() + 1);
self.0.load(Requirement {
name: self.1,
target: target(self.2),
minimum_bytes: 1,
})
}
}
let wanted = format!("nvidia/{}/gsp_ga10x.bin", version());
for (name, hardware) in [("other.bin", "ga10x"), (&wanted, "ad10x")] {
let catalog = make_catalog(name, hardware, &DATA.0);
let provider = Wrong(&catalog, name, hardware, Cell::new(0));
let state = State::new();
let mut owner = bind(Some(&provider), 0x170, 2, &state);
failed(state.raw(), 0, 4);
assert_eq!(provider.3.get(), 1);
assert_eq!(owner.firmware_tokens.get(), 0);
// SAFETY: failed lookup published nothing and all callers stopped.
unsafe { owner.as_mut().unbind() }.unwrap();
}
}
@@ -1,191 +0,0 @@
//! Unsized RM metadata allocation over Stela's existing global allocator.
//!
//! The native owner must establish the global heap and obey its execution
//! context rules before calling RM: no interrupt handler, interrupt reentry or
//! allocator reentry. All users must finish before the heap is torn down.
//! These are ordinary CPU pointers, never DMA addresses, physical page pins,
//! MMIO mappings or a promise of physical contiguity/cache policy.
use alloc::alloc::{alloc, dealloc};
use core::{alloc::Layout, ffi::c_void, ptr, ptr::NonNull};
// The official API frees without a byte count. Keep the exact shared-heap
// layout immediately before the payload; no allocation registry or pool.
// Sixteen bytes also covers the native C/C++ fundamental type alignment.
#[repr(align(16))]
struct Header {
layout: Layout,
}
pub(super) const ALIGNMENT: usize = align_of::<Header>();
// Internal result tags mirror stela_memory.h, not NVIDIA's status namespace.
#[repr(u32)]
#[derive(Debug, Eq, PartialEq)]
pub(super) enum AllocationStatus {
Success = 0,
InvalidSize = 1,
OutOfMemory = 2,
}
/// CPU metadata from the existing global heap, with the unsized free prefix.
pub(super) fn allocate(bytes: u64) -> Result<NonNull<c_void>, AllocationStatus> {
allocate_with(bytes, |layout| {
// SAFETY: a nonzero checked layout, forwarded to the common allocator.
unsafe { alloc(layout) }
})
}
fn allocate_with(
bytes: u64,
allocate: impl FnOnce(Layout) -> *mut u8,
) -> Result<NonNull<c_void>, AllocationStatus> {
let size = usize::try_from(bytes)
.ok()
.and_then(|size| size.checked_add(size_of::<Header>()))
.ok_or(AllocationStatus::InvalidSize)?;
let layout = Layout::from_size_align(size, align_of::<Header>())
.map_err(|_| AllocationStatus::InvalidSize)?;
let base = NonNull::new(allocate(layout)).ok_or(AllocationStatus::OutOfMemory)?;
// SAFETY: the allocator supplied this exclusively owned aligned layout;
// it contains one header followed by the entire requested payload.
unsafe {
base.cast::<Header>().as_ptr().write(Header { layout });
Ok(base.add(size_of::<Header>()).cast())
}
}
/// Called only through the native C shim, after the owner's heap/context setup.
///
/// # Safety
/// `out` must be a writable native pointer slot, owned by the C shim.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_alloc(bytes: u64, out: *mut *mut c_void) -> AllocationStatus {
let result = allocate(bytes);
let (pointer, status) = match result {
Ok(pointer) => (pointer.as_ptr(), AllocationStatus::Success),
Err(status) => (ptr::null_mut(), status),
};
// SAFETY: the C shim checked its caller's native output slot.
unsafe { out.write(pointer) };
status
}
unsafe fn free_with(pointer: *mut c_void, release: impl FnOnce(*mut u8, Layout)) {
if pointer.is_null() {
return;
}
// SAFETY: the C/RM caller returns this allocator's live payload exactly
// once, without modifying its prefix; all payload users have stopped.
let base = unsafe { pointer.cast::<u8>().sub(size_of::<Header>()) };
// SAFETY: `base` is this allocation's header, written when it was allocated.
let header = unsafe { base.cast::<Header>().read() };
release(base, header.layout);
}
/// # Safety
/// Return only this allocator's live pointer, once, after all uses stop, in the
/// same heap's supported owner-established execution context.
pub(super) unsafe fn free(pointer: *mut c_void) {
// SAFETY: the native C/RM caller satisfies the contract above; `free_with`
// recovers the same pointer/layout originally obtained from this heap.
unsafe { free_with(pointer, |base, layout| dealloc(base, layout)) }
}
/// # Safety
/// Return only a live `stela_nvidia_alloc` pointer, once, after all uses stop.
/// The same heap and supported owner-established execution context must remain.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_free(pointer: *mut c_void) {
// SAFETY: the C/RM caller returns exactly this allocator's pointer.
unsafe { free(pointer) }
}
#[cfg(test)]
mod tests {
use super::*;
unsafe extern "C" {
fn os_alloc_mem(out: *mut *mut c_void, bytes: u64) -> u32;
fn os_free_mem(pointer: *mut c_void);
}
#[test]
fn vendor_c_allocation_owns_aligned_disjoint_writable_payloads() {
let sizes = [0, 1, 15, 16, 17, 4095, 4096, 4097, 65537];
let mut pointers = [ptr::null_mut::<c_void>(); 9];
for (index, (&size, pointer)) in sizes.iter().zip(&mut pointers).enumerate() {
// SAFETY: writable output; the native hosted global heap is ready.
assert_eq!(unsafe { os_alloc_mem(pointer, size) }, 0);
assert!(!pointer.is_null());
assert_eq!(*pointer as usize % 16, 0);
// SAFETY: successful allocation owns exactly `size` writable bytes.
unsafe { pointer.cast::<u8>().write_bytes(index as u8, size as usize) };
}
for (index, (&size, &pointer)) in sizes.iter().zip(&pointers).enumerate().rev() {
// SAFETY: every payload is still live and held by this test alone.
let bytes = unsafe { core::slice::from_raw_parts(pointer.cast::<u8>(), size as usize) };
assert!(bytes.iter().all(|byte| *byte == index as u8));
// SAFETY: every vendor allocation is returned once, after all use.
unsafe { os_free_mem(pointer) };
}
}
#[test]
fn vendor_errors_clear_output_and_null_free_is_valid() {
// Stable vendor ABI values from the pinned nvstatuscodes.h. These calls
// execute the C adapter compiled against those declarations.
const NV_ERR_INVALID_ARGUMENT: u32 = 0x1f;
for bytes in [u64::MAX, isize::MAX as u64] {
let mut out = ptr::dangling_mut::<c_void>();
assert_eq!(
// SAFETY: writable output; invalid sizes fail before allocation.
unsafe { os_alloc_mem(&mut out, bytes) },
NV_ERR_INVALID_ARGUMENT
);
assert!(out.is_null());
}
// SAFETY: null outputs are rejected and null free is explicitly valid.
unsafe {
assert_eq!(os_alloc_mem(ptr::null_mut(), 1), NV_ERR_INVALID_ARGUMENT);
os_free_mem(ptr::null_mut());
}
}
#[test]
fn allocation_failure_and_exact_shared_heap_release() {
let mut called = false;
let failed = allocate_with(37, |_| {
called = true;
ptr::null_mut()
});
assert!(called);
assert_eq!(failed, Err(AllocationStatus::OutOfMemory));
let (mut original_base, mut original_layout) = (ptr::null_mut(), None);
let pointer = allocate_with(37, |layout| {
original_layout = Some(layout);
// SAFETY: the checked nonzero layout is forwarded to the heap.
original_base = unsafe { alloc(layout) };
original_base
})
.unwrap();
// SAFETY: this uniquely owned payload was returned by allocate_with.
unsafe {
free_with(pointer.as_ptr(), |base, layout| {
assert_eq!(base, original_base);
assert_eq!(Some(layout), original_layout);
dealloc(base, layout);
});
}
}
#[test]
fn invalid_sizes_never_call_the_heap() {
for bytes in [u64::MAX, isize::MAX as u64, isize::MAX as u64 - 16] {
assert_eq!(
allocate_with(bytes, |_| panic!("invalid native layout reached the heap")),
Err(AllocationStatus::InvalidSize)
);
}
}
}
-422
View File
@@ -1,422 +0,0 @@
//! Original tokenless RM physical mapping ABI over the canonical MMIO permission.
//!
//! This module owns only returned-VA/size -> Mapping lease bookkeeping. Actual
//! resource registration, aliases, effective cache policy, native roots and TLB
//! acknowledgement belong to `bus::mmio::owned` and the real platform adapter.
//! No platform adapter or GPU activation is supplied here. Cached RAM/firmware
//! mapping remains a separate unsupported integration requirement.
use crate::bus::mmio::owned::{
Authority, CacheAttribute, Error as MappingError, Mapping, PhysicalSpan, Protection,
Status as AuthorityStatus,
};
use alloc::vec::Vec;
use core::{
ffi::c_void,
marker::{PhantomData, PhantomPinned},
pin::Pin,
ptr,
sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering},
};
static INSTALLED: AtomicPtr<MmioServices> = AtomicPtr::new(ptr::null_mut());
// Fail reentry before constructing any Rust reference to the installed object.
// This guard is ownership serialization, never an ISR/context predicate.
static ENTERED: AtomicBool = AtomicBool::new(false);
static REFUSED_CALLS: AtomicU64 = AtomicU64::new(0);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Error {
AlreadyInstalled,
NotInstalled,
Busy,
LiveMappings,
UnknownMapping,
Mapping(MappingError),
}
impl From<MappingError> for Error {
fn from(error: MappingError) -> Self {
Self::Mapping(error)
}
}
/// Historical failures remain visible because the original unmap ABI is void.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Status {
pub live: usize,
pub pending: usize,
pub busy_retirements: u64,
pub failed_maps: u64,
pub failed_unmaps: u64,
pub unmap_quarantines: u64,
pub last_failure: Option<Error>,
/// Boot-global entry refusals before any service reference is constructed.
pub refused_calls: u64,
}
struct Lease {
address: *mut c_void,
bytes: u64,
mapping: Mapping,
pending: bool,
}
/// Pinned native installation for the original global, tokenless mapping hooks.
/// It keeps a clone of the one canonical Permission, not a BAR/resource table.
/// No resources are registered here. This handle is neither Send nor Sync.
pub struct MmioServices {
authority: Authority,
leases: Vec<Lease>,
busy_retirements: u64,
failed_maps: u64,
failed_unmaps: u64,
unmap_quarantines: u64,
last_failure: Option<Error>,
_owner: PhantomData<*mut ()>,
_pin: PhantomPinned,
}
struct Entry;
impl Entry {
fn acquire() -> Result<Self, Error> {
ENTERED
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.map_err(|_| Error::Busy)?;
Ok(Self)
}
}
impl Drop for Entry {
fn drop(&mut self) {
ENTERED.store(false, Ordering::Release);
}
}
impl MmioServices {
pub fn new(authority: Authority) -> Self {
Self {
authority,
leases: Vec::new(),
busy_retirements: 0,
failed_maps: 0,
failed_unmaps: 0,
unmap_quarantines: 0,
last_failure: None,
_owner: PhantomData,
_pin: PhantomPinned,
}
}
/// Publish only after the real global heap, registered resources and native
/// mapping platform are ready. This performs no mapping or initialization.
///
/// # Safety
/// Keep this pinned object alive until successful uninstall, with the same
/// native CPU ABI/address space. Serialize all native callers and Rust
/// service access; exclude interrupts, callback/allocator reentry and final
/// release outside the providers' process/deferred context. Do not create
/// Rust references to this object while any C callback can access it.
/// Stop/drain all callers and retire live/pending leases before uninstall;
/// they may not outlive installation. The guard rejects reentry but cannot make an
/// invalid lifetime/context or an interrupted allocator safe.
pub unsafe fn install(self: Pin<&mut Self>) -> Result<(), Error> {
let _entry = Entry::acquire()?;
// SAFETY: pin remains in place through all callbacks and uninstall.
let pointer = unsafe { self.get_unchecked_mut() as *mut Self };
INSTALLED
.compare_exchange(
ptr::null_mut(),
pointer,
Ordering::AcqRel,
Ordering::Acquire,
)
.map_err(|_| Error::AlreadyInstalled)?;
Ok(())
}
/// # Safety
/// All native callers have stopped/drained and cannot restart, including
/// callbacks/workers with raw addresses. The install lifetime/context and
/// serialization contract still applies. Failure leaves the slot installed.
/// Canonically quarantined leases keep platform/resources without
/// this object; their failure remains a real teardown error in diagnostics.
/// Live AND pending leases refuse uninstall. Drain pending retirements at
/// real quiescent points, and before attempting final uninstall.
pub unsafe fn uninstall(self: Pin<&mut Self>) -> Result<(), Error> {
let _entry = Entry::acquire()?;
// SAFETY: caller excludes callbacks and keeps the object pinned.
let services = unsafe { self.get_unchecked_mut() };
let pointer = services as *mut Self;
if INSTALLED.load(Ordering::Acquire) != pointer {
return Err(Error::NotInstalled);
}
if !services.leases.is_empty() {
return Err(Error::LiveMappings);
}
INSTALLED.store(ptr::null_mut(), Ordering::Release);
Ok(())
}
/// Inspect only between serialized callbacks, as required by install.
pub fn status(&self) -> Status {
let pending = self.leases.iter().filter(|lease| lease.pending).count();
Status {
live: self.leases.len() - pending,
pending,
busy_retirements: self.busy_retirements,
failed_maps: self.failed_maps,
failed_unmaps: self.failed_unmaps,
unmap_quarantines: self.unmap_quarantines,
last_failure: self.last_failure,
refused_calls: REFUSED_CALLS.load(Ordering::Relaxed),
}
}
/// Shared-permission state, including uncertain maps that never
/// returned a VA and quarantine from every native permission consumer.
pub fn authority_status(&self) -> Result<AuthorityStatus, MappingError> {
self.authority.status()
}
/// Retry pending exact canonical tokens, using their existing ledger slots.
/// No adapter allocation, queue or worker is created. Returns the number
/// retired if all attempts succeed; an error may follow earlier progress,
/// which remains visible in status. Busy keeps the pending Mapping even
/// if the platform was called and canonical state is already uncertain.
///
/// # Safety
/// Call only on the installed pinned native owner, serialized with all C
/// hooks in the real platform/global heap's process/deferred context. Every
/// pending lease's initial unmap has already proved complete raw CPU/device/
/// callback/worker and posted/WC drain; no future access may restart. Retry
/// at quiescent points and before uninstall. Never infer that Busy
/// means a platform callback was not entered or a raw VA is usable again.
pub unsafe fn drain_pending_retirements(self: Pin<&mut Self>) -> Result<usize, Error> {
let _entry = Entry::acquire()?;
// SAFETY: caller excludes native callbacks and preserves pin/lifetime.
let services = unsafe { self.get_unchecked_mut() };
if !ptr::eq(INSTALLED.load(Ordering::Acquire), services) {
return Err(Error::NotInstalled);
}
let mut at = 0;
let mut retired = 0;
let mut failure = None;
while at < services.leases.len() {
if !services.leases[at].pending {
at += 1;
continue;
}
// SAFETY: initial unmap permanently ended raw access; retry the
// same canonical token in owner-established context.
match unsafe { services.retire(at) } {
Ok(()) => retired += 1,
Err(error) => {
services.record_unmap_failure(error);
failure.get_or_insert(error);
if error == Error::Mapping(MappingError::Busy) {
at += 1; // in this same slot
}
// Other failures consumed this slot into quarantine; its
// swapped-in neighbor still needs inspection at this index.
}
}
}
failure.map_or(Ok(retired), Err)
}
fn map(&mut self, physical: u64, bytes: u64, mode: u32) -> Result<*mut c_void, Error> {
let attribute = match mode {
1 | 6 => CacheAttribute::Uncached,
2 => CacheAttribute::WriteCombining,
_ => return Err(MappingError::UnsupportedCache.into()),
};
if physical == 0 {
return Err(MappingError::InvalidRange.into());
}
let span = PhysicalSpan::new(physical, bytes)?;
let size = usize::try_from(bytes).map_err(|_| MappingError::InvalidRange)?;
// Validate context and complete rounded ownership BEFORE any
// allocator operation. map_physical repeats lookup and atomically
// reserves the resource/cache range; no GPU BAR metadata is trusted.
drop(self.authority.resolve_resource(span)?);
let authority = &self.authority;
publish(
&mut self.leases,
|leases| {
leases
.try_reserve(1)
.map_err(|_| MappingError::Unavailable.into())
},
|| {
let mapping = authority.map_physical(span, attribute, Protection::ReadWrite)?;
// A canonical address failure (e.g. concurrent identity
// quarantine) drops into canonical quarantine, never unmaps a
// token or publishes an invalid/partially valid raw pointer.
let address = mapping.address(0, size)?.as_ptr().cast();
Ok((
Lease {
address,
bytes,
mapping,
pending: false,
},
address,
))
},
)
}
/// # Safety
/// Original caller has stopped/drained every raw consumer and posted/WC
/// effect of precisely this mapping. No future access may begin.
unsafe fn unmap(&mut self, address: *mut c_void, bytes: u64) -> Result<(), Error> {
let at = self
.leases
.iter()
.position(|lease| !lease.pending && lease.address == address && lease.bytes == bytes)
.ok_or(Error::UnknownMapping)?;
// The void ABI ended the caller's raw access regardless of whether
// canonical retirement can finish now. Never hand this lease out again.
self.leases[at].pending = true;
// SAFETY: initial caller proves permanent raw-user/post-write drain.
unsafe { self.retire(at) }
}
/// # Safety
/// This pending slot has permanently stopped/drained all raw users/effects.
unsafe fn retire(&mut self, at: usize) -> Result<(), Error> {
// SAFETY: caller proves complete raw-user drain; Mapping keeps the
// platform/resource and validates exact canonical identity.
match unsafe { self.leases[at].mapping.retire() } {
Ok(()) => {
self.leases.swap_remove(at);
Ok(())
}
Err(MappingError::Busy) => Err(MappingError::Busy.into()),
Err(error) => {
self.unmap_quarantines = self.unmap_quarantines.saturating_add(1);
// Fatal/ambiguous failures consume into canonical permanent
// quarantine, keeping owners and uncertain aliases.
// Busy instead keeps the exact token without guessing if
// native unmap ran, for explicit native-owner retry above.
self.leases.swap_remove(at);
Err(error.into())
}
}
}
fn record_unmap_failure(&mut self, error: Error) {
if error == Error::Mapping(MappingError::Busy) {
self.busy_retirements = self.busy_retirements.saturating_add(1);
} else {
self.failed_unmaps = self.failed_unmaps.saturating_add(1);
}
self.last_failure = Some(error);
}
}
// All fallible bookkeeping precedes the real mapping. This internal seam lets
// tests model bounded metadata OOM without exhausting the Rust test harness.
fn publish<T, R>(
leases: &mut Vec<T>,
reserve: impl FnOnce(&mut Vec<T>) -> Result<(), Error>,
map: impl FnOnce() -> Result<(T, R), Error>,
) -> Result<R, Error> {
reserve(leases)?;
if leases.len() == leases.capacity() {
return Err(MappingError::Unavailable.into());
}
let (lease, result) = map()?;
leases.push(lease);
Ok(result)
}
fn refuse() {
let _ = REFUSED_CALLS.try_update(Ordering::Relaxed, Ordering::Relaxed, |count| {
Some(count.saturating_add(1))
});
}
fn with_installed<R>(fallback: R, call: impl FnOnce(&mut MmioServices) -> R) -> R {
let Ok(_entry) = Entry::acquire() else {
refuse();
return fallback;
};
let pointer = INSTALLED.load(Ordering::Acquire);
if pointer.is_null() {
refuse();
return fallback;
}
// SAFETY: unsafe install keeps this pinned native object; global entry
// ownership excludes all other callbacks before constructing this borrow.
call(unsafe { &mut *pointer })
}
#[unsafe(no_mangle)]
extern "C" fn stela_nvidia_map_mmio(physical: u64, bytes: u64, mode: u32) -> *mut c_void {
with_installed(ptr::null_mut(), |services| {
match services.map(physical, bytes, mode) {
Ok(address) => address,
Err(error) => {
services.failed_maps = services.failed_maps.saturating_add(1);
services.last_failure = Some(error);
ptr::null_mut()
}
}
})
}
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_unmap_mmio(address: *mut c_void, bytes: u64) {
with_installed((), |services| {
// SAFETY: original C caller satisfies the installed unmap contract.
if let Err(error) = unsafe { services.unmap(address, bytes) } {
services.record_unmap_failure(error);
}
});
}
#[cfg(test)]
mod tests {
use super::*;
use core::cell::Cell;
#[test]
fn failed_metadata_reservation_never_maps_or_publishes() {
let mut leases = Vec::<u8>::new();
let calls = Cell::new(0);
let result = publish(
&mut leases,
|_| Err(MappingError::Unavailable.into()),
|| {
calls.set(calls.get() + 1);
Ok((1, ()))
},
);
assert_eq!(result, Err(Error::Mapping(MappingError::Unavailable)));
assert!(leases.is_empty());
assert_eq!(calls.get(), 0);
assert_eq!(
publish(
&mut leases,
|_| Ok(()),
|| {
calls.set(1);
Ok((1, ()))
}
),
Err(Error::Mapping(MappingError::Unavailable))
);
assert_eq!(calls.get(), 0);
leases.try_reserve(1).unwrap();
assert_eq!(
publish(
&mut leases,
|_| Ok(()),
|| Err::<(u8, ()), _>(MappingError::MappingFailed.into())
),
Err(Error::Mapping(MappingError::MappingFailed))
);
assert!(leases.is_empty());
assert_eq!(publish(&mut leases, |_| Ok(()), || Ok((7, 3))), Ok(3));
assert_eq!(leases, [7]);
}
}
@@ -1,276 +0,0 @@
//! Original RM global page facts from a canonical RAM provider.
//! This publishes metadata only, never RAM, cache policy or RM readiness.
use crate::bus::dma::memory::{MemoryError, PageGeometry, PageSource};
use core::sync::atomic::{AtomicU32, Ordering};
const EMPTY: u32 = 0;
const INSTALLING: u32 = 1;
const READY: u32 = 2;
const BASE_SHIFT_FIELD: u32 = 8;
const MAX_SHIFT_FIELD: u32 = 16;
static PROFILE: AtomicU32 = AtomicU32::new(EMPTY);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Error {
Source(MemoryError),
InvalidGeometry,
UnsupportedGeometry,
Unbound,
Busy,
Conflict,
Native(u32),
}
unsafe extern "C" {
fn stela_nvidia_set_page_geometry(base: u64, max: u64, mask: u64, shift: u8) -> u32;
}
fn encoded(geometry: PageGeometry) -> u32 {
READY
| u32::from(geometry.base_shift()) << BASE_SHIFT_FIELD
| u32::from(geometry.max_shift()) << MAX_SHIFT_FIELD
}
fn decode(value: u32) -> Result<PageGeometry, Error> {
match value {
EMPTY => Err(Error::Unbound),
INSTALLING => Err(Error::Busy),
_ => PageGeometry::contiguous(
(value >> BASE_SHIFT_FIELD) as u8,
(value >> MAX_SHIFT_FIELD) as u8,
)
.map_err(|_| Error::InvalidGeometry),
}
}
fn values(geometry: PageGeometry) -> Result<(u64, u64, u64, u8), Error> {
// The current native allocation hook accepts only the configured base
// granule. Never publish a broader original allocation capability mask.
if geometry.max_shift() != geometry.base_shift() {
return Err(Error::UnsupportedGeometry);
}
let base = u64::try_from(geometry.base_bytes()).map_err(|_| Error::InvalidGeometry)?;
let max = u64::try_from(geometry.max_bytes()).map_err(|_| Error::InvalidGeometry)?;
// The original supported-mask accessor doubles max before subtracting1.
// Keep that arithmetic representable as well as the canonical usize extent.
max.checked_mul(2).ok_or(Error::InvalidGeometry)?;
let low = base.checked_sub(1).ok_or(Error::InvalidGeometry)?;
Ok((base, max, !low, geometry.base_shift()))
}
fn install_with(
state: &AtomicU32,
source: &dyn PageSource,
publish: impl FnOnce(PageGeometry, (u64, u64, u64, u8)) -> Result<(), u32>,
) -> Result<PageGeometry, Error> {
let geometry = source.page_geometry().map_err(Error::Source)?;
let native_values = values(geometry)?;
let expected = encoded(geometry);
match state.compare_exchange(EMPTY, INSTALLING, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => {}
Err(INSTALLING) => return Err(Error::Busy),
Err(value) if value == expected => return Ok(geometry),
Err(_) => return Err(Error::Conflict),
}
if let Err(status) = publish(geometry, native_values) {
state.store(EMPTY, Ordering::Release);
return Err(Error::Native(status));
}
state.store(expected, Ordering::Release);
Ok(geometry)
}
/// Query the original global ABI's successfully published immutable profile.
/// This is metadata, not permission to activate RM or access a device.
pub fn installed() -> Result<PageGeometry, Error> {
decode(PROFILE.load(Ordering::Acquire))
}
/// Publish once before any original RM/native page-fact consumer runs. Matching
/// repeats query the source but do not write the C data again. Unknown
/// providers, concurrent installation and conflicting profiles explicitly fail.
/// Multi-granule profiles are unsupported by the current native page producer
/// and fail before publication; the source profile is never narrowed.
/// No reset/uninstall is provided: all native callers share these original globals.
///
/// # Safety
/// `source` must be the native RAM provider, with truthful immutable
/// geometry for every RM device using these facts. Exclude all original C/RM
/// callers throughout the initial installation; plain original global reads
/// must never race these writes. Keep the native profile stable for the entire
/// RM lifetime, including every allocation/mapping/kept quarantine. Calls
/// obey the provider's real process/context rules and cannot unwind or reenter
/// native RM. This does not establish a heap, physical mapping, cache policy,
/// DMA domain, IRQ context or complete RM initialization.
pub unsafe fn install(source: &dyn PageSource) -> Result<PageGeometry, Error> {
install_with(&PROFILE, source, |_, (base, max, mask, shift)| {
// SAFETY: install's caller excludes all original readers. The single
// publisher owns this initial write; helper errors mutate no C data.
let status = unsafe { stela_nvidia_set_page_geometry(base, max, mask, shift) };
if status == 0 { Ok(()) } else { Err(status) }
})
}
fn check_with(
state: &AtomicU32,
source: &dyn PageSource,
shift: u8,
) -> Result<PageGeometry, Error> {
let geometry = source.page_geometry().map_err(Error::Source)?;
values(geometry)?;
if geometry != decode(state.load(Ordering::Acquire))? || shift != geometry.base_shift() {
return Err(Error::Conflict);
}
Ok(geometry)
}
pub(super) fn check_source(source: &dyn PageSource, shift: u8) -> Result<PageGeometry, Error> {
check_with(&PROFILE, source, shift)
}
#[cfg(test)]
pub(super) mod tests {
use super::*;
use crate::bus::dma::memory::{CacheAttribute, PinnedPages};
use alloc::string::ToString;
use core::cell::Cell;
extern crate std;
struct Source(Result<PageGeometry, MemoryError>, Cell<usize>);
impl PageSource for Source {
fn page_geometry(&self) -> Result<PageGeometry, MemoryError> {
self.1.set(self.1.get() + 1);
self.0
}
fn allocate(
&self,
_: usize,
_: usize,
_: CacheAttribute,
) -> Result<PinnedPages, MemoryError> {
panic!("geometry queries must not allocate pages");
}
}
/// One explicit CPU-model source profile per test process. No production
/// default is supplied, and tests cannot reset already published original data.
pub(crate) fn initialize_model(shift: u8) {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
let source = Source(PageGeometry::base_only(shift), Cell::new(0));
// SAFETY: this fresh hosted test process has no original RM callers;
// only explicit RAM models use the immutable test source profile.
unsafe { install(&source).unwrap() };
});
assert_eq!(
installed().unwrap(),
PageGeometry::base_only(shift).unwrap()
);
}
/// Original 16KiB-native RAM models run unchanged in fresh processes instead of
/// changing global native geometry while other 4KiB models keep allocations.
pub(crate) fn separate_model_process(test: &str, shift: u8) -> bool {
const VARIABLE: &str = "STELA_NVIDIA_PAGE_GEOMETRY_MODEL";
if let Ok(value) = std::env::var(VARIABLE) {
assert_eq!(value, shift.to_string());
return false;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", test, "--nocapture"])
.env(VARIABLE, shift.to_string())
.output()
.unwrap();
assert!(
output.status.success()
&& std::string::String::from_utf8_lossy(&output.stdout)
.contains("1 passed; 0 failed;"),
"{}{}",
std::string::String::from_utf8_lossy(&output.stdout),
std::string::String::from_utf8_lossy(&output.stderr)
);
true
}
#[test]
fn queries_precede_publication_and_unknown_sources_never_install_defaults() {
let state = AtomicU32::new(EMPTY);
let unknown = Source(Err(MemoryError::Unavailable), Cell::new(0));
assert_eq!(
install_with(&state, &unknown, |_, _| panic!("unknown provider")),
Err(Error::Source(MemoryError::Unavailable))
);
assert_eq!(decode(state.load(Ordering::Acquire)), Err(Error::Unbound));
let broad = Source(PageGeometry::contiguous(12, 14), Cell::new(0));
assert_eq!(
install_with(&state, &broad, |_, _| panic!("unsupported publisher")),
Err(Error::UnsupportedGeometry)
);
assert_eq!(state.load(Ordering::Acquire), EMPTY);
let source = Source(PageGeometry::base_only(12), Cell::new(0));
assert_eq!(check_with(&state, &source, 12), Err(Error::Unbound));
assert_eq!(
install_with(&state, &source, |_, native| {
assert_eq!(native, (4096, 4096, !4095, 12));
assert_eq!(decode(state.load(Ordering::Acquire)), Err(Error::Busy));
assert_eq!(
install_with(&state, &source, |_, _| panic!("reentrant publisher")),
Err(Error::Busy)
);
Ok(())
}),
PageGeometry::base_only(12).map_err(Error::Source)
);
assert_eq!(source.1.get(), 3);
assert_eq!(check_with(&state, &source, 14), Err(Error::Conflict));
assert_eq!(check_with(&state, &source, 12).unwrap(), source.0.unwrap());
assert_eq!(
install_with(&state, &source, |_, _| panic!("duplicate publication")),
PageGeometry::base_only(12).map_err(Error::Source)
);
assert_eq!(
install_with(&state, &unknown, |_, _| panic!("unknown repeat")),
Err(Error::Source(MemoryError::Unavailable))
);
let conflict = Source(PageGeometry::contiguous(12, 14), Cell::new(0));
assert_eq!(
install_with(&state, &conflict, |_, _| panic!("conflicting publisher")),
Err(Error::UnsupportedGeometry)
);
assert_eq!(
check_with(&state, &conflict, 12),
Err(Error::UnsupportedGeometry)
);
assert_eq!(
decode(state.load(Ordering::Acquire)).unwrap(),
source.0.unwrap()
);
}
#[test]
fn failed_native_publication_is_retryable_and_range_values_preserve_original_mask_arithmetic() {
let state = AtomicU32::new(EMPTY);
let source = Source(PageGeometry::base_only(14), Cell::new(0));
assert_eq!(
install_with(&state, &source, |_, _| Err(0x40)),
Err(Error::Native(0x40))
);
assert_eq!(state.load(Ordering::Acquire), EMPTY);
assert_eq!(
install_with(&state, &source, |geometry, (base, max, mask, shift)| {
assert_eq!((base, max, mask, shift), (16384, 16384, !16383, 14));
let supported = ((max << 1) - 1) & !(base - 1);
for candidate in 0..64 {
assert_eq!(
supported & (1u64 << candidate) != 0,
geometry.supports(candidate)
);
}
Ok(())
}),
source.0.map_err(Error::Source)
);
let largest = PageGeometry::base_only((usize::BITS - 2) as u8).unwrap();
assert!(values(largest).unwrap().1.checked_mul(2).is_some());
}
}
@@ -1,440 +0,0 @@
//! Per-device RAM services for the original NVIDIA allocation hooks. Binding
//! installs borrowed/kept platform resources, not a GPU initializer.
//! No global registry, fallback allocator, IRQ-context predicate or DMA identity
//! conversion is introduced. RM activation still requires its remaining native
//! services, including its original interrupt-allocation/context contract.
use super::{allocation::Allocation, firmware::FirmwareBinding, memory, page_geometry};
use crate::bus::{
dma::{
mapping::DmaDomain,
memory::{CacheAttribute, MemoryError, PageGeometry, PageSource},
},
pci::Address,
};
use alloc::sync::Arc;
use core::{cell::Cell, ffi::c_void, marker::PhantomData, marker::PhantomPinned, pin::Pin, ptr};
/// Native vendor status ABI, checked against nvstatus.h by stela_services.h.
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum Status {
Ok = 0,
InvalidAddress = 0x1e,
InvalidArgument = 0x1f,
InvalidState = 0x40,
NoMemory = 0x51,
NotSupported = 0x56,
OperatingSystem = 0x59,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ServiceError {
InvalidConfiguration,
AlreadyBound,
Native(u32),
PageGeometry(page_geometry::Error),
}
/// Allocation provenance. DMA uses this attached domain and
/// compares opaque device keys BEFORE dereferencing any supplied dma_dev.
pub(super) struct Origin {
pub device_key: *mut c_void,
pub state: *mut c_void,
pub domain: Arc<dyn DmaDomain>,
pub address_limit: u64,
pub count: u32,
pub contiguous: bool,
pub cache: u32,
}
/// A pinned device's real native RAM source and attached DMA domain. Calls are
/// serialized and nonreentrant in the source/domain/global heap's permitted
/// process/deferred context. This handle is neither Send nor Sync.
///
/// Keep the source, state and handle alive through all native callers and all
/// producer allocations/published DMA tokens and firmware tokens. Unbind refuses
/// until every allocation is freed, every DMA token is retired or quarantined,
/// and every firmware token is returned. Therefore
/// no map-capable old handle can legitimately survive a rebind/address reuse.
/// CPU-only views and consumed quarantine independently keep pins/domain
/// and may survive. Final releases still obey backing/domain/heap context rules.
pub struct MemoryServices<'a> {
source: &'a dyn PageSource,
domain: Arc<dyn DmaDomain>,
requester: Address,
page_shift: u8,
geometry: PageGeometry,
address_limit: u64,
state: *mut c_void,
allocations: Cell<usize>,
mappings: Cell<usize>,
pub(super) firmware: Option<FirmwareBinding<'a>>,
pub(super) firmware_tokens: Cell<usize>,
_owner: PhantomData<*mut ()>,
_pin: PhantomPinned,
}
unsafe extern "C" {
fn stela_nvidia_bind_memory(
state: *mut c_void,
services: *mut c_void,
domain: u32,
bus: u8,
slot: u8,
function: u8,
) -> u32;
fn stela_nvidia_unbind_memory(state: *mut c_void, services: *mut c_void) -> u32;
}
impl<'a> MemoryServices<'a> {
/// # Safety
/// `domain` must be the real isolated DMA domain attached to exactly
/// `requester`, with `address_limit` from that device's DMA policy.
/// `page_shift` is the real native granule, matching the backend's global
/// os_page_shift facts before RM runs; it is never a guest granule. The
/// source must attest the installed PageGeometry; an unknown
/// source, conflicting maximum or non-base configured shift is refused. The
/// provider must establish the requested CPU cache policy or refuse it,
/// without introducing incompatible aliases.
pub unsafe fn new(
source: &'a dyn PageSource,
domain: Arc<dyn DmaDomain>,
requester: Address,
page_shift: u8,
address_limit: u64,
) -> Result<Self, ServiceError> {
if requester.device >= 32
|| requester.function >= 8
|| !(12..usize::BITS as u8 - 1).contains(&page_shift)
|| address_limit < (1u64 << page_shift) - 1
{
return Err(ServiceError::InvalidConfiguration);
}
let geometry =
page_geometry::check_source(source, page_shift).map_err(ServiceError::PageGeometry)?;
Ok(Self {
source,
domain,
requester,
page_shift,
geometry,
address_limit,
state: ptr::null_mut(),
allocations: Cell::new(0),
mappings: Cell::new(0),
firmware: None,
firmware_tokens: Cell::new(0),
_owner: PhantomData,
_pin: PhantomPinned,
})
}
/// Attach an immutable firmware provider before pinning/binding. Its
/// device-family attestation shares this service's requester/reset epoch.
pub fn with_firmware(mut self, firmware: FirmwareBinding<'a>) -> Self {
self.firmware = Some(firmware);
self
}
/// Bind an initialized native nv_state_t's empty OS/DMA slots. C checks
/// its PCI identity against the requester. This neither
/// enables hardware nor creates a channel, IRQ route or GPU VA mapping.
///
/// # Safety
/// The state must be a live exclusively owned original nv_state_t with
/// initialized PCI identity. Keep it and this pinned handle alive while any
/// native caller can dereference either. Exclude all calls during bind.
pub unsafe fn bind(self: Pin<&mut Self>, state: *mut c_void) -> Result<(), ServiceError> {
// SAFETY: access pinned fields without moving the handle.
let this = unsafe { self.get_unchecked_mut() };
if !this.state.is_null() {
return Err(ServiceError::AlreadyBound);
}
let raw = (this as *mut Self).cast();
// SAFETY: the native owner establishes the original state/handle ABI
// and excludes all callers while the C helper validates/binds slots.
let status = unsafe {
stela_nvidia_bind_memory(
state,
raw,
u32::from(this.requester.segment),
this.requester.bus,
this.requester.device,
this.requester.function,
)
};
if status != 0 {
return Err(ServiceError::Native(status));
}
this.state = state;
Ok(())
}
/// # Safety
/// Hardware is quiescent, all native allocation/mapping/IRQ workers are
/// stopped and drained, all producer handles freed, every published DMA
/// token retired or consumed into canonical quarantine, all firmware tokens
/// returned after their CPU readers stop, and no new native
/// call can start. Keep this pinned service/state live until this succeeds;
/// dropping/reusing them while resources remain violates the bind contract.
/// CPU-only views and consumed quarantine may remain. The real domain
/// must remain attached while any lease or quarantine needs it.
/// This method clears only the slots owned by this handle; it invents
/// no device reset, retirement or completion proof.
pub unsafe fn unbind(self: Pin<&mut Self>) -> Result<(), ServiceError> {
// SAFETY: field access without moving the pinned handle.
let this = unsafe { self.get_unchecked_mut() };
if this.state.is_null() {
return Err(ServiceError::Native(Status::InvalidState as u32));
}
if this.allocations.get() != 0
|| this.mappings.get() != 0
|| this.firmware_tokens.get() != 0
{
return Err(ServiceError::Native(Status::InvalidState as u32));
}
// SAFETY: the owner excludes callers; C compares installed slots.
let status = unsafe { stela_nvidia_unbind_memory(this.state, (this as *mut Self).cast()) };
if status != 0 {
return Err(ServiceError::Native(status));
}
this.state = ptr::null_mut();
Ok(())
}
}
impl MemoryServices<'_> {
pub(super) fn bound_to(&self, state: *mut c_void) -> bool {
!state.is_null() && self.state == state
}
pub(super) fn can_map(&self) -> Result<(), Status> {
if self.state.is_null() {
return Err(Status::InvalidState);
}
self.mappings.get().checked_add(1).ok_or(Status::NoMemory)?;
Ok(())
}
pub(super) fn mapped(&self) {
// Serialized, no callback reentry; can_map checked before preparation.
self.mappings.set(self.mappings.get() + 1);
}
pub(super) fn has_mapping(&self) -> bool {
self.mappings.get() != 0 && !self.state.is_null()
}
pub(super) fn retired(&self) {
// The unique validated token consumes one previously published entry.
self.mappings.set(self.mappings.get() - 1);
}
}
fn cache_attribute(cache: u32) -> Result<CacheAttribute, Status> {
// Stable NV_MEMORY_* encodings, checked against the original header in C.
const MEMORY_CACHED: u32 = 0;
const MEMORY_UNCACHED: u32 = 1;
const MEMORY_WRITECOMBINED: u32 = 2;
match cache {
MEMORY_CACHED => Ok(CacheAttribute::WriteBack),
MEMORY_UNCACHED => Ok(CacheAttribute::Uncached),
MEMORY_WRITECOMBINED => Ok(CacheAttribute::WriteCombining),
_ => Err(Status::NotSupported),
}
}
fn memory_error(error: MemoryError) -> Status {
match error {
MemoryError::OutOfMemory | MemoryError::OutsideReservation => Status::NoMemory,
MemoryError::CacheAttributeUnavailable | MemoryError::Unavailable => Status::NotSupported,
_ => Status::OperatingSystem,
}
}
struct Request {
count: u32,
contiguous: bool,
cache: u32,
force_dma32: bool,
}
unsafe fn allocate_pages(
services: &MemoryServices<'_>,
key: *mut c_void,
request: Request,
ptes: *mut u64,
private: *mut *mut c_void,
) -> Result<(), Status> {
let Request {
count,
contiguous,
cache,
force_dma32,
} = request;
let page_bytes = 1usize << services.page_shift;
let live_allocations = services
.allocations
.get()
.checked_add(1)
.ok_or(Status::NoMemory)?;
let bytes = (count as usize)
.checked_mul(page_bytes)
.filter(|bytes| *bytes <= isize::MAX as usize)
.ok_or(Status::InvalidArgument)?;
let attribute = cache_attribute(cache)?;
let pages = services
.source
.allocate(bytes, page_bytes, attribute)
.map_err(memory_error)?;
if pages.logical_bytes() != bytes
|| pages.bytes() != bytes
|| pages.page_shift() != services.page_shift
|| !services.geometry.supports(pages.page_shift())
|| pages.cache_attribute() != attribute
{
return Err(Status::OperatingSystem);
}
let physical = pages.physical_pages();
if contiguous
&& !physical
.windows(2)
.all(|pair| pair[0] + page_bytes as u64 == pair[1])
{
return Err(Status::NoMemory);
}
if force_dma32
&& physical
.iter()
.any(|pa| pa + page_bytes as u64 - 1 > u64::from(u32::MAX))
{
return Err(Status::NoMemory);
}
let storage = memory::allocate(size_of::<Allocation>() as u64).map_err(|_| Status::NoMemory)?;
let mut allocation = Allocation::new(pages);
allocation.origin = Some(Origin {
device_key: key,
state: services.state,
domain: Arc::clone(&services.domain),
address_limit: services.address_limit,
count,
contiguous,
cache,
});
// SAFETY: common heap storage is sufficient and aligned; the raw object
// stays pinned until its one vendor free. No output has been published.
unsafe { storage.cast::<Allocation>().as_ptr().write(allocation) };
services.allocations.set(live_allocations);
// All fallible operations and ownership accounting completed before the
// first caller output changes. The object remains private until the end.
// SAFETY: this new object is uniquely owned and its immutable pins are live.
let allocation = unsafe { storage.cast::<Allocation>().as_ref() };
let physical = allocation.pages().physical_pages();
for (index, &address) in physical
.iter()
.take(if contiguous { 1 } else { physical.len() })
.enumerate()
{
// SAFETY: caller supplies one PTE for contiguous allocations,
// otherwise exactly count writable native u64 slots.
unsafe { ptes.add(index).write(address) };
}
// SAFETY: writable native output; publish unique parent ownership last.
unsafe { private.write(storage.as_ptr()) };
Ok(())
}
const _: () = assert!(align_of::<Allocation>() <= memory::ALIGNMENT);
/// # Safety
/// The native C shim supplies its live bound service/state, validated pointer
/// slots, and the caller's complete native PTE capacity. Context rules above apply.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_alloc_pages(
key: *mut c_void,
state: *mut c_void,
count: u32,
page_size: u64,
contiguous: u8,
cache: u32,
zeroed: u8,
unencrypted: u8,
node: i32,
force_dma32: u8,
ptes: *mut u64,
private: *mut *mut c_void,
) -> Status {
// SAFETY: C only forwards the OS handle installed by bind into this state.
let services = unsafe { &*key.cast::<MemoryServices<'_>>() };
if services.state != state || state.is_null() {
return Status::InvalidState;
}
if count == 0 || contiguous > 1 || zeroed > 1 || unencrypted > 1 || force_dma32 > 1 {
return Status::InvalidArgument;
}
if page_size == 0 {
return Status::InvalidArgument;
}
if page_size != 1u64 << services.page_shift || unencrypted != 0 || node != -1 {
return Status::NotSupported;
}
// Canonical PageBacking is initially zeroed. Extra zeroing when zeroed=0
// is valid; it does not advertise encryption, NUMA or higher-order support.
// SAFETY: validated policy and the shim's checked caller-owned outputs.
match unsafe {
allocate_pages(
services,
key,
Request {
count,
contiguous: contiguous != 0,
cache,
force_dma32: force_dma32 != 0,
},
ptes,
private,
)
} {
Ok(()) => Status::Ok,
Err(status) => status,
}
}
/// # Safety
/// Return one live producer-owned Allocation, once, after parent C users stop.
/// Outstanding CPU views/DMA maps independently keep pins/domain. This cannot
/// be used for a manually supplied Allocation or another imported handle kind.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvidia_free_pages(
state: *mut c_void,
count: u32,
contiguous: u8,
cache: u32,
private: *mut c_void,
) -> Status {
// SAFETY: the caller supplies the original allocation-kind live pointer.
let allocation = unsafe { &*private.cast::<Allocation>() };
let Some(origin) = allocation.origin.as_ref() else {
return Status::NotSupported;
};
if origin.state != state
|| origin.count != count
|| u8::from(origin.contiguous) != contiguous
|| origin.cache != cache
{
return Status::InvalidArgument;
}
// SAFETY: the pinned binding must remain alive while any producer handle
// or DMA token exists; unbind refuses this live allocation count.
let services = unsafe { &*origin.device_key.cast::<MemoryServices<'_>>() };
if services.state != state || services.allocations.get() == 0 {
return Status::InvalidState;
}
services.allocations.set(services.allocations.get() - 1);
// SAFETY: validated producer ownership; exactly one free, no live parent
// C reference. CpuMapping/DmaMapping keep any outstanding pins.
unsafe {
private.cast::<Allocation>().drop_in_place();
memory::free(private);
}
Status::Ok
}
#[cfg(test)]
mod tests;
File diff suppressed because it is too large. Load diff
@@ -1,114 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include "stela_device.h"
NV_STATUS stela_nvidia_prepare_device(nv_state_t *nv, void *handle,
const struct stela_nvidia_device_identity *id,
const struct stela_nvidia_device_bar *bars, NvU32 count)
{
NvU32 config[NVRM_PCICFG_NUM_DWORDS], used = 0;
if (!nv || !handle || !id || !bars || count < 2 || count > NV_GPU_NUM_BARS ||
id->domain > 0xffff || id->bus > 255 || id->slot > 31 || id->function > 7 ||
id->vendor != 0x10de || id->device > 0xffff ||
id->subsystem_vendor > 0xffff || id->subsystem > 0xffff)
return NV_ERR_INVALID_ARGUMENT;
if (nv->priv || nv->os_state || nv->dma_dev || nv->niso_dma_dev || nv->handle)
return NV_ERR_INVALID_STATE;
for (NvU32 i = 0; i < NVRM_PCICFG_NUM_DWORDS; ++i) {
NV_STATUS status = os_pci_read_dword(handle, i * 4, &config[i]);
if (status != NV_OK) return status;
}
if ((config[0] & 0xffff) != id->vendor || (config[0] >> 16) != id->device ||
(config[11] & 0xffff) != id->subsystem_vendor || (config[11] >> 16) != id->subsystem ||
((config[3] >> 16) & 0x7f) != 0)
return NV_ERR_INVALID_ARGUMENT;
for (NvU32 i = 0; i < count; ++i) {
const struct stela_nvidia_device_bar *bar = &bars[i];
if (bar->index >= NVRM_PCICFG_NUM_BARS || !bar->physical || !bar->bytes ||
bar->bytes > NV_U64_MAX - bar->physical || bar->prefetchable > 1 ||
(i == NV_GPU_BAR_INDEX_REGS && bar->prefetchable))
return NV_ERR_INVALID_ARGUMENT;
NvU32 low = config[NVRM_PCICFG_BAR_OFFSET(bar->index) / 4];
NvU32 type = low & NVRM_PCICFG_BAR_MEMTYPE_MASK;
if ((low & NVRM_PCICFG_BAR_REQTYPE_MASK) != NVRM_PCICFG_BAR_REQTYPE_MEMORY ||
(type != 0 && type != NVRM_PCICFG_BAR_MEMTYPE_64BIT) ||
((low >> 3) & 1) != bar->prefetchable)
return NV_ERR_INVALID_ARGUMENT;
NvU32 selected = 1U << bar->index;
NvU64 address = low & NVRM_PCICFG_BAR_ADDR_MASK;
if (type == NVRM_PCICFG_BAR_MEMTYPE_64BIT) {
if (bar->index + 1 >= NVRM_PCICFG_NUM_BARS) return NV_ERR_INVALID_ARGUMENT;
address |= (NvU64)config[NVRM_PCICFG_BAR_OFFSET(bar->index + 1) / 4] << 32;
selected |= 1U << (bar->index + 1);
}
if ((used & selected) || address != bar->physical) return NV_ERR_INVALID_ARGUMENT;
used |= selected;
}
/* Decode assigned memory resources as PCI resource metadata does, excluding
* 64-bit upper slots. No destructive sizing or address-as-pointer use. */
NvU32 memory = 0, first = NVRM_PCICFG_NUM_BARS;
for (NvU32 i = 0; i < NVRM_PCICFG_NUM_BARS; ++i) {
NvU32 low = config[NVRM_PCICFG_BAR_OFFSET(i) / 4];
if (low & NVRM_PCICFG_BAR_REQTYPE_MASK) continue;
NvU32 type = low & NVRM_PCICFG_BAR_MEMTYPE_MASK;
if (type != 0 && type != NVRM_PCICFG_BAR_MEMTYPE_64BIT) return NV_ERR_NOT_SUPPORTED;
NvU64 address = low & NVRM_PCICFG_BAR_ADDR_MASK;
if (type == NVRM_PCICFG_BAR_MEMTYPE_64BIT) {
if (i + 1 >= NVRM_PCICFG_NUM_BARS) return NV_ERR_INVALID_ARGUMENT;
address |= (NvU64)config[NVRM_PCICFG_BAR_OFFSET(i + 1) / 4] << 32;
}
if (address) {
memory |= 1U << i;
if (first == NVRM_PCICFG_NUM_BARS) first = i;
}
if (type == NVRM_PCICFG_BAR_MEMTYPE_64BIT) ++i;
}
if (bars[NV_GPU_BAR_INDEX_REGS].index != first) return NV_ERR_INVALID_ARGUMENT;
/* Preserve the original second loop's index skip exactly: j==REGS skips
* the FIRST PCI INDEX, not the first valid memory resource. A layout that
* would repeat REGS as FB cannot satisfy our distinct retained spans. */
NvU32 j = 0;
for (NvU32 i = 0; i < NVRM_PCICFG_NUM_BARS && j < NV_GPU_NUM_BARS; ++i) {
if (j == NV_GPU_BAR_INDEX_REGS) {
++j;
continue;
}
if (memory & (1U << i)) {
if (j >= count || bars[j].index != i) return NV_ERR_INVALID_ARGUMENT;
++j;
}
}
if (j != count) return NV_ERR_INVALID_ARGUMENT;
/* Original POD type and original role constants; no private record mirror,
* active RM flag, IRQ, firmware policy, mapping or DMA mask is supplied. */
nv_state_t prepared = {0};
prepared.pci_info.domain = id->domain;
prepared.pci_info.bus = (NvU8)id->bus;
prepared.pci_info.slot = (NvU8)id->slot;
prepared.pci_info.function = (NvU8)id->function;
prepared.pci_info.vendor_id = (NvU16)id->vendor;
prepared.pci_info.device_id = (NvU16)id->device;
prepared.subsystem_vendor = (NvU16)id->subsystem_vendor;
prepared.subsystem_id = (NvU16)id->subsystem;
prepared.handle = handle;
for (NvU32 i = 0; i < NVRM_PCICFG_NUM_DWORDS; ++i) prepared.pci_cfg_space[i] = config[i];
for (NvU32 i = 0; i < count; ++i) {
prepared.bars[i].cpu_address = bars[i].physical;
prepared.bars[i].size = bars[i].bytes;
prepared.bars[i].offset = NVRM_PCICFG_BAR_OFFSET(bars[i].index);
}
*nv = prepared;
nv->regs = &nv->bars[NV_GPU_BAR_INDEX_REGS];
nv->fb = &nv->bars[NV_GPU_BAR_INDEX_FB];
return NV_OK;
}
NV_STATUS stela_nvidia_prepared_device_retirable(const nv_state_t *nv, const void *handle)
{
if (!nv || !handle || nv->handle != handle) return NV_ERR_INVALID_ARGUMENT;
if (nv->priv || nv->flags || nv->queue || nv->event_list || nv->event_spinlock ||
nv->kern_mappings || nv->rc_timer_enabled || nv->rmapi.hClient || nv->rmapi.hDevice ||
nv->rmapi.hSubDevice || nv->rmapi.hI2C || nv->rmapi.hDisp)
return NV_ERR_INVALID_STATE;
for (NvU32 i = 0; i < NV_GPU_NUM_BARS; ++i)
if (nv->bars[i].map || nv->bars[i].map_u) return NV_ERR_INVALID_STATE;
return NV_OK;
}
@@ -1,23 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_DEVICE_H
#define STELA_NVIDIA_DEVICE_H
#include "stela_services.h"
#include "os-interface.h"
#include <stddef.h>
/* Private same-CPU input ABI. Physical spans come only from retained canonical
* Resources; neither this value record nor a PCI address grants ownership. */
struct stela_nvidia_device_bar { NvU64 physical, bytes; NvU32 index, prefetchable; };
struct stela_nvidia_device_identity {
NvU32 domain, bus, slot, function, vendor, device, subsystem_vendor, subsystem;
};
_Static_assert(sizeof(struct stela_nvidia_device_bar) == 24, "device BAR input ABI");
_Static_assert(sizeof(struct stela_nvidia_device_identity) == 32, "identity input ABI");
/* CPU metadata construction only; all validation/config reads precede writes.
* Roles are original NV_GPU_BAR_INDEX_{REGS,FB,IMEM}, never inferred from PA.
* The zeroed actual nv_state_t is private, pinned and has no native callers. */
NV_STATUS stela_nvidia_prepare_device(nv_state_t *, void *,
const struct stela_nvidia_device_identity *, const struct stela_nvidia_device_bar *, NvU32);
/* No reset/drain/free. Validate this still-uninitialized private state before
* actual counter-checked service unbind. Failure preserves every slot. */
NV_STATUS stela_nvidia_prepared_device_retirable(const nv_state_t *, const void *);
#endif
@@ -1,53 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include "version.h"
/* Same original package-name policy as kernel-open/nvidia/nv.c at the retained
* NVIDIA pin. version.h is generated from the existing vendor version.mk. */
#define NV_FIRMWARE_FOR_NAME(name) "nvidia/" NVIDIA_VERSION "/" name ".bin"
#include "stela_firmware.h"
/* Original optional log tables use intentional zero-filled partial initializers. */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#include "nv-firmware-chip-family-select.h"
#pragma GCC diagnostic pop
#include "libelf.h"
_Static_assert(sizeof(nv_firmware_type_t) == sizeof(NvU32) &&
sizeof(nv_firmware_chip_family_t) == sizeof(NvU32),
"native firmware enum ABI");
NvU32 stela_nvidia_firmware_family(NvU32 architecture, NvU32 implementation)
{
return nv_firmware_get_chip_family(architecture, implementation);
}
NvU64 stela_nvidia_firmware_alignment(void)
{
return _Alignof(LibosElf64Header) > _Alignof(LibosElf64SectionHeader) ?
_Alignof(LibosElf64Header) : _Alignof(LibosElf64SectionHeader);
}
const char *stela_nvidia_firmware_version(void)
{
return NVIDIA_VERSION;
}
const void *NV_API_CALL nv_get_firmware(nv_state_t *nv,
nv_firmware_type_t type,
nv_firmware_chip_family_t family,
const void **buffer, NvU32 *bytes)
{
if (nv == NULL || nv->os_state == NULL || buffer == NULL || bytes == NULL)
return NULL;
const char *name = nv_firmware_for_chip_family(type, family);
const char *hardware = nv_firmware_chip_family_to_string(family);
if (name[0] == '\0' || hardware[0] == '\0')
return NULL;
return stela_nvidia_get_firmware(nv->os_state, nv, family, name, hardware,
NVIDIA_VERSION, buffer, bytes);
}
void NV_API_CALL nv_put_firmware(const void *token)
{
if (token != NULL)
stela_nvidia_put_firmware(token);
}
@@ -1,27 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_FIRMWARE_H
#define STELA_NVIDIA_FIRMWARE_H
#include "stela_services.h"
/* Native same-CPU ABI, borrowing immutable canonical catalog bytes. The pinned
* MemoryServices owner supplies the actual device's observed architecture and
* implementation before binding. All calls/releases are serialized, nonreentrant
* process/deferred operations with a live global heap, never ISR callbacks.
* Every non-NULL token is returned once after CPU readers stop. The catalog,
* provider, state and service remain alive until all tokens are put and unbind
* succeeds. NULL put is valid. Failure preserves both caller output slots.
* Bytes are CPU-only: not physical/IOVA addresses, pinned DMA storage or GPU VA.
* Catalog manifest integrity does not authenticate NVIDIA firmware. Original RM
* version/ELF/signature validation, upload and device initialization still apply.
*/
NvU32 stela_nvidia_firmware_family(NvU32 architecture, NvU32 implementation);
NvU64 stela_nvidia_firmware_alignment(void);
const char *stela_nvidia_firmware_version(void);
const void *stela_nvidia_get_firmware(void *services, void *state, NvU32 family,
const char *name, const char *hardware,
const char *revision, const void **buffer,
NvU32 *bytes);
void stela_nvidia_put_firmware(const void *token);
#endif
@@ -1,27 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_MAPPING_H
#define STELA_NVIDIA_MAPPING_H
#include "nvtypes.h"
#if !NVOS_IS_FREEBSD
#error "native CPU mapping hooks build in NVIDIA's FreeBSD configuration"
#endif
/* Native same-CPU C ABI. The allocation is a pinned Rust Allocation accepting
* only real canonical PinnedPages with an established CPU mapping/cache policy.
* The caller serializes access and excludes callback/interrupt reentry. Indices
* and offsets use the allocation's actual native page granule, never the guest's.
* Only exact logical bytes are exposed; no page padding or cache-policy alias.
*
* Success returns CPU VA and a unique retained CPU-view token in *private; failure
* returns NULL with *private NULL. Each view retains the actual pin independently
* of the parent. Return each token once after CPU/device users stop, in the common
* heap/backing's allowed process/deferred context. Free needs no live parent.
* These are not guest, MMIO, VRAM, physical, IOVA or GPU-VA mapping services.
*/
void *stela_nvidia_map_ram(void *allocation, NvU64 page_index, NvU32 page_offset,
NvU64 bytes, void **private);
void stela_nvidia_unmap_ram(void *private);
#endif
@@ -1,30 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include <stddef.h>
#include "os-interface.h"
#include "stela_memory.h"
/* Match the original RM declarations and status values. Invalid/overflowing
* native layouts and exhausted shared heaps cannot produce a usable pointer.
*/
NV_STATUS NV_API_CALL os_alloc_mem(void **out, NvU64 bytes)
{
if (out == NULL)
return NV_ERR_INVALID_ARGUMENT;
*out = NULL;
switch (stela_nvidia_alloc(bytes, out))
{
case STELA_NVIDIA_ALLOC_SUCCESS:
return NV_OK;
case STELA_NVIDIA_ALLOC_INVALID_SIZE:
return NV_ERR_INVALID_ARGUMENT;
case STELA_NVIDIA_ALLOC_OUT_OF_MEMORY:
return NV_ERR_NO_MEMORY;
default:
return NV_ERR_GENERIC;
}
}
void NV_API_CALL os_free_mem(void *pointer)
{
stela_nvidia_free(pointer);
}
@@ -1,31 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_MEMORY_H
#define STELA_NVIDIA_MEMORY_H
#include "nvtypes.h"
#if !NVOS_IS_FREEBSD
#error "native metadata hooks build in NVIDIA's FreeBSD configuration"
#endif
/* Same native CPU/C ABI as Rust's extern C, including UEFI's calling convention.
* Stela's existing global allocator owns the bytes. The native owner establishes
* a live heap and obeys its context restrictions: no interrupt handlers, interrupt
* reentry or allocator reentry. Free once, after every CPU user stops, before heap
* teardown. NULL free is valid. Payloads have 16-byte alignment and uninitialized
* contents. Zero bytes still returns a distinct freeable allocation. The output
* is always written: NULL for either an invalid layout or real heap exhaustion.
* These are CPU metadata pointers,
* never guest/physical/device addresses, page pins, MMIO or cache-policy aliases.
*/
enum {
STELA_NVIDIA_ALLOC_SUCCESS = 0,
STELA_NVIDIA_ALLOC_INVALID_SIZE = 1,
STELA_NVIDIA_ALLOC_OUT_OF_MEMORY = 2,
};
NvU32 stela_nvidia_alloc(NvU64 bytes, void **out);
void stela_nvidia_free(void *pointer);
_Static_assert(sizeof(NvU64) == 8, "allocation lengths are 64-bit");
#endif
@@ -1,15 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include "os-interface.h"
#include "stela_mmio.h"
/* Original vendor declarations stay unchanged. Only the native Stela build
* selects these hooks; Linux's reference implementation remains separate. */
void *NV_API_CALL os_map_kernel_space(NvU64 physical, NvU64 bytes, NvU32 mode)
{
return stela_nvidia_map_mmio(physical, bytes, mode);
}
void NV_API_CALL os_unmap_kernel_space(void *address, NvU64 bytes)
{
stela_nvidia_unmap_mmio(address, bytes);
}
@@ -1,36 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_MMIO_H
#define STELA_NVIDIA_MMIO_H
#include "nvtypes.h"
#include "os/nv_memory_type.h"
#if !NVOS_IS_FREEBSD
#error "native physical mappings build in NVIDIA's FreeBSD configuration"
#endif
_Static_assert(NV_MEMORY_CACHED == 0 && NV_MEMORY_UNCACHED == 1 &&
NV_MEMORY_WRITECOMBINED == 2 && NV_MEMORY_WRITEBACK == 5 &&
NV_MEMORY_DEFAULT == 6 && NV_MEMORY_UNCACHED_WEAK == 7,
"preserve original NVIDIA cache-mode values");
/* Native same-CPU ABI. A pinned installed Rust MmioServices retains the single
* canonical native Authority and every published Mapping. It resolves the
* complete physical/page span to an actual registered ResourceBacking; there
* is no PA=VA conversion, BAR ownership inference or cached-RAM mapping here.
* UC/default request genuine UC; WC requests genuine WC or fails. Other modes
* fail. The real platform must enforce context/cache/root/TLB requirements.
*
* The native owner serializes all callbacks/install/uninstall in permitted
* process/deferred context and keeps the installed services/global heap alive.
* Unmap returns the exact pointer and requested byte count once, after ALL raw
* CPU/device/callback/worker uses and posted/WC writes stop and drain. It cannot
* report failure through the original void ABI: owner-visible Rust diagnostics
* retain failures. Busy keeps the exact Mapping pending for explicit native-
* owner quiescent drain; other failures retain uncertain owners through
* canonical quarantine. Pending leases block uninstall and never resume raw
* use after the initial unmap.
* These pointers authorize raw access only, never safe Rust references.
*/
void *stela_nvidia_map_mmio(NvU64 physical, NvU64 bytes, NvU32 mode);
void stela_nvidia_unmap_mmio(void *address, NvU64 bytes);
#endif
@@ -1,26 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* nvkms_alloc and nvkms_free, as nvidia-modeset-os-interface.h declares them,
* over Stela's checked global-heap boundary (stela_memory.h). A nonzero zero flag
* clears the allocation; the heap keeps its own layout, so free needs no size.
* There is no atomic or timer-context allocation. */
#include "nvidia-modeset-os-interface.h"
#include "stela_memory.h"
void *nvkms_alloc(size_t size, NvBool zero)
{
void *pointer = NULL;
if (stela_nvidia_alloc(size, &pointer) != STELA_NVIDIA_ALLOC_SUCCESS)
return NULL;
if (zero)
nvkms_memset(pointer, 0, size);
return pointer;
}
void nvkms_free(void *pointer, size_t size)
{
(void)size;
stela_nvidia_free(pointer);
}
_Static_assert(sizeof(size_t) == sizeof(NvU64), "native allocation length");
_Static_assert(sizeof(NvBool) == 1, "NvBool is one byte");
@@ -1,30 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* NVKMS's CPU primitives, as nvidia-modeset-os-interface.h declares them, over
* the shared C runtime with size_t lengths. */
#include "stela_primitives.h"
#include "nvidia-modeset-os-interface.h"
void *nvkms_memset(void *ptr, NvU8 c, size_t size)
{
return memset(ptr, c, size);
}
void *nvkms_memcpy(void *dest, const void *src, size_t n)
{
return memcpy(dest, src, n);
}
void *nvkms_memmove(void *dest, const void *src, size_t n)
{
return memmove(dest, src, n);
}
int nvkms_memcmp(const void *s1, const void *s2, size_t n)
{
return memcmp(s1, s2, n);
}
size_t nvkms_strlen(const char *s)
{
return strlen(s);
}
@@ -1,21 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* nvlink_malloc and nvlink_free, as nvlink_os.h declares them, over Stela's
* checked global-heap boundary (stela_memory.h). They have no atomic mode. */
#include <stddef.h>
#include "nvlink_os.h"
#include "stela_memory.h"
void *nvlink_malloc(NvLength size)
{
void *pointer = NULL;
if (stela_nvidia_alloc(size, &pointer) != STELA_NVIDIA_ALLOC_SUCCESS)
return NULL;
return pointer;
}
void nvlink_free(void *pointer)
{
stela_nvidia_free(pointer);
}
_Static_assert(sizeof(NvLength) == sizeof(NvU64), "native allocation length");
@@ -1,20 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* NVLink's CPU primitives, as nvlink_os.h declares them, over the shared C
* runtime with 64-bit NvLength lengths. */
#include "stela_primitives.h"
#include "nvlink_os.h"
NvLength nvlink_strlen(const char *s)
{
return strlen(s);
}
void *nvlink_memset(void *dest, int value, NvLength size)
{
return memset(dest, value, size);
}
void *nvlink_memcpy(void *dest, const void *src, NvLength size)
{
return memcpy(dest, src, size);
}
@@ -1,20 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* NVSwitch's CPU primitives, as export_nvswitch.h declares them, over the
* shared C runtime with 64-bit NvLength lengths. */
#include "stela_primitives.h"
#include "export_nvswitch.h"
NvLength nvswitch_os_strlen(const char *str)
{
return strlen(str);
}
void *nvswitch_os_memset(void *dest, int value, NvLength size)
{
return memset(dest, value, size);
}
void *nvswitch_os_memcpy(void *dest, const void *src, NvLength size)
{
return memcpy(dest, src, size);
}
@@ -1,15 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* os_flush_cpu_write_combine_buffer, as os-interface.h declares it, for
* x86-64: sfence orders this CPU's earlier write-combining stores before its
* later ones. It is not cache maintenance, posted-write completion or DMA
* visibility. */
#include "os-interface.h"
#if !defined(NVCPU_X86_64)
#error "Stela's NVIDIA port builds for x86-64"
#endif
void NV_API_CALL os_flush_cpu_write_combine_buffer(void)
{
__asm__ volatile("sfence" ::: "memory");
}
@@ -1,29 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include "stela_page_geometry.h"
/* Actual original os-interface.h data types. No guessed platform defaults;
* native owner publication is a prerequisite for every original RM accessor.
*/
NvU64 os_page_size;
NvU64 os_max_page_size;
NvU64 os_page_mask;
NvU8 os_page_shift;
NV_STATUS stela_nvidia_set_page_geometry(NvU64 base, NvU64 max, NvU64 mask, NvU8 shift)
{
if (shift < 12 || shift >= 63 || base != (1ULL << shift) ||
max < base || max > (1ULL << 62) || (max & (max - 1)) ||
mask != ~(base - 1))
return NV_ERR_INVALID_ARGUMENT;
/* nv_alloc_pages currently accepts only the configured base granule. */
if (max != base)
return NV_ERR_NOT_SUPPORTED;
if (os_page_size || os_max_page_size || os_page_mask || os_page_shift)
return os_page_size == base && os_max_page_size == max &&
os_page_mask == mask && os_page_shift == shift ? NV_OK : NV_ERR_INVALID_STATE;
os_max_page_size = max;
os_page_mask = mask;
os_page_shift = shift;
os_page_size = base;
return NV_OK;
}
@@ -1,18 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_PAGE_GEOMETRY_H
#define STELA_NVIDIA_PAGE_GEOMETRY_H
#include "os-interface.h"
/* Private publisher of the Rust actual-PageSource owner. Original RM data
* symbols remain unavailable/zero until that owner queries and binds genuine
* native geometry before all C callers. Never call this instead of install().
* Initial publication excludes every original reader; values never change.
* All validation precedes writes; repeats match exactly or preserve old facts.
*/
/* Current native producer admits base-only profiles; broader valid geometry
* returns NV_ERR_NOT_SUPPORTED without changing any original data symbol. */
NV_STATUS stela_nvidia_set_page_geometry(NvU64, NvU64, NvU64, NvU8);
_Static_assert(sizeof(os_page_size) == 8 && sizeof(os_max_page_size) == 8 &&
sizeof(os_page_mask) == 8 && sizeof(os_page_shift) == 1,
"original native RM page globals ABI");
#endif
@@ -1,88 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include "stela_services.h"
NV_STATUS stela_nvidia_bind_memory(nv_state_t *nv, void *services,
NvU32 domain, NvU8 bus, NvU8 slot, NvU8 function)
{
if (nv == NULL || services == NULL)
return NV_ERR_INVALID_ARGUMENT;
if (nv->os_state != NULL || nv->dma_dev != NULL || nv->niso_dma_dev != NULL)
return NV_ERR_INVALID_STATE;
if (nv->pci_info.domain != domain || nv->pci_info.bus != bus ||
nv->pci_info.slot != slot || nv->pci_info.function != function)
return NV_ERR_INVALID_ARGUMENT;
nv->os_state = services;
nv->dma_dev = (nv_dma_device_t *)services;
return NV_OK;
}
NV_STATUS stela_nvidia_unbind_memory(nv_state_t *nv, void *services)
{
if (nv == NULL || services == NULL)
return NV_ERR_INVALID_ARGUMENT;
if (nv->os_state != services || nv->dma_dev != (nv_dma_device_t *)services)
return NV_ERR_INVALID_STATE;
nv->os_state = NULL;
nv->dma_dev = NULL;
return NV_OK;
}
void stela_nvidia_state_layout(NvU64 *bytes, NvU64 *alignment)
{
*bytes = sizeof(nv_state_t);
*alignment = _Alignof(nv_state_t);
}
NvBool NV_API_CALL nv_requires_dma_remap(nv_state_t *nv)
{
return nv != NULL && nv->os_state != NULL &&
nv->dma_dev == (nv_dma_device_t *)nv->os_state;
}
NV_STATUS NV_API_CALL nv_alloc_pages(nv_state_t *nv, NvU32 count, NvU64 size,
NvBool contiguous, NvU32 cache, NvBool zeroed,
NvBool unencrypted, NvS32 node, NvU64 *ptes,
void **private)
{
if (private == NULL || ptes == NULL)
return NV_ERR_INVALID_ARGUMENT;
/* No global/deviceless allocator and no physical-to-DMA fallback. */
if (!nv_requires_dma_remap(nv))
return NV_ERR_NOT_SUPPORTED;
return stela_nvidia_alloc_pages(nv->os_state, nv, count, size, contiguous,
cache, zeroed, unencrypted, node,
nv->force_dma32_alloc, ptes, private);
}
NV_STATUS NV_API_CALL nv_free_pages(nv_state_t *nv, NvU32 count, NvBool contiguous,
NvU32 cache, void *private)
{
if (private == NULL)
return NV_ERR_INVALID_ARGUMENT;
return stela_nvidia_free_pages(nv, count, contiguous, cache, private);
}
NV_STATUS NV_API_CALL nv_dma_map_alloc(nv_dma_device_t *device, NvU64 count,
NvU64 *addresses, NvBool contiguous,
NvBool read_only, void **private)
{
if (private == NULL)
return NV_ERR_NOT_SUPPORTED;
if (*private == NULL || addresses == NULL || device == NULL)
return NV_ERR_INVALID_ARGUMENT;
/* Rust validates device equality against retained allocation provenance;
* never dereference an arbitrary C dma_dev value as platform state. */
return stela_nvidia_dma_map(device, count, addresses, contiguous, read_only, private);
}
NV_STATUS NV_API_CALL nv_dma_unmap_alloc(nv_dma_device_t *device, NvU64 count,
NvU64 *addresses, void **private)
{
if (private == NULL)
return NV_ERR_NOT_SUPPORTED;
if (*private == NULL || addresses == NULL || device == NULL)
return NV_ERR_INVALID_ARGUMENT;
/* The owned token supplies the true mapping; this original address array
* is not trusted to select a different domain or removal target. */
return stela_nvidia_dma_unmap(device, count, private);
}
@@ -1,56 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include <stddef.h>
#include "os-interface.h"
#include "stela_pci.h"
/* Use the vendor's actual declarations and status definitions. Device discovery,
* reset and removal are separate lifecycle work, not successful no-op hooks.
*/
#define PCI_CONFIG_BYTES 4096U
static NV_STATUS read_config(void *handle, NvU32 offset, NvU32 width, NvU32 *value)
{
struct stela_nvidia_pci *pci = handle;
if (pci == NULL)
return NV_ERR_INVALID_POINTER;
if (offset >= PCI_CONFIG_BYTES)
return NV_ERR_NOT_SUPPORTED;
if (!pci->read(pci->context, offset, width, value))
return NV_ERR_INVALID_ARGUMENT;
return NV_OK;
}
static NV_STATUS write_config(void *handle, NvU32 offset, NvU32 width, NvU32 value)
{
struct stela_nvidia_pci *pci = handle;
if (pci == NULL)
return NV_ERR_INVALID_POINTER;
if (offset >= PCI_CONFIG_BYTES)
return NV_ERR_NOT_SUPPORTED;
if (!pci->write(pci->context, offset, width, value))
return NV_ERR_INVALID_ARGUMENT;
return NV_OK;
}
/* Initialize failed reads to all ones: existing RM callers can ignore status.
* Narrow writes stay narrow through the Rust ConfigSpace implementation.
*/
#define PCI_ACCESS(suffix, type, width, all_ones) \
NV_STATUS NV_API_CALL os_pci_read_##suffix(void *handle, NvU32 offset, type *out) \
{ \
NvU32 value = all_ones; \
NV_STATUS status; \
if (out == NULL) \
return NV_ERR_INVALID_POINTER; \
status = read_config(handle, offset, width, &value); \
*out = (type)value; \
return status; \
} \
NV_STATUS NV_API_CALL os_pci_write_##suffix(void *handle, NvU32 offset, type value) \
{ \
return write_config(handle, offset, width, value); \
}
PCI_ACCESS(byte, NvU8, 1U, 0xffU)
PCI_ACCESS(word, NvU16, 2U, 0xffffU)
PCI_ACCESS(dword, NvU32, 4U, 0xffffffffU)
@@ -1,31 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_PCI_H
#define STELA_NVIDIA_PCI_H
#include <stddef.h>
#include "nvtypes.h"
#if !NVOS_IS_FREEBSD
#error "native PCI hooks build in NVIDIA's FreeBSD configuration"
#endif
/* Native, same-CPU ABI, mirrored by nvidia::PciHandle. The physical device's
* owner pins this handle and keeps its configuration space exclusively borrowed
* until all RM users stop. Calls are serialized; neither callback may reenter
* the driver. These are not guest pointers or a macOS transport.
*
* Width is 1, 2 or 4 bytes. Callbacks reject unaligned/out-of-page accesses
* without touching hardware, returning 0; return 1 after a valid access.
*/
struct stela_nvidia_pci {
void *context;
NvU32 (*read)(void *, NvU32 offset, NvU32 width, NvU32 *value);
NvU32 (*write)(void *, NvU32 offset, NvU32 width, NvU32 value);
};
_Static_assert(sizeof(NvU32) == 4, "PCI values use 32-bit integers");
_Static_assert(sizeof(struct stela_nvidia_pci) == 3 * sizeof(void *), "PCI handle size");
_Static_assert(offsetof(struct stela_nvidia_pci, read) == sizeof(void *), "PCI read offset");
_Static_assert(offsetof(struct stela_nvidia_pci, write) == 2 * sizeof(void *), "PCI write offset");
#endif
@@ -1,25 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* RM's CPU primitives, as os-interface.h declares them, over the shared C
* runtime. Lengths keep RM's NvU32 width. */
#include "os-interface.h"
#include "stela_primitives.h"
NvU32 NV_API_CALL os_string_length(const char *str)
{
return (NvU32)strlen(str);
}
void *NV_API_CALL os_mem_copy(void *dst, const void *src, NvU32 length)
{
return memcpy(dst, src, length);
}
void *NV_API_CALL os_mem_set(void *dst, NvU8 c, NvU32 length)
{
return memset(dst, (int)c, length);
}
NvS32 NV_API_CALL os_mem_cmp(const NvU8 *buf0, const NvU8 *buf1, NvU32 length)
{
return memcmp(buf0, buf1, length);
}
@@ -1,27 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_PRIMITIVES_H
#define STELA_NVIDIA_PRIMITIVES_H
#include <stddef.h>
#include "nvtypes.h"
#if !NVOS_IS_FREEBSD || !NVCPU_IS_X86_64
#error "these original RM primitives build for x86-64 in NVIDIA's FreeBSD configuration"
#endif
/* Declarations of the existing shared C runtime, not a private implementation.
* Native UEFI resolves these to Rust's compiler_builtins; hosted tests use the
* host C runtime. Calls require ordinary valid CPU buffers, nonoverlapping copy
* ranges and terminated readable strings. They do not perform usercopy, MMIO
* ordering, cache maintenance, pinning or allocation and establish no ISR state.
*/
void *memcpy(void *, const void *, size_t);
void *memmove(void *, const void *, size_t);
void *memset(void *, int, size_t);
int memcmp(const void *, const void *, size_t);
size_t strlen(const char *);
_Static_assert(sizeof(size_t) == sizeof(NvLength) && sizeof(NvLength) == 8,
"native shared C runtime uses pointer-sized lengths");
_Static_assert(sizeof(NvU32) == 4 && sizeof(NvU8) == 1 && sizeof(NvS32) == sizeof(int),
"preserve original RM primitive scalar ABI");
#endif
@@ -1,38 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Select the vendor's native kernel-interface declarations, not core nvport
* implementation dependencies. The API declarations in nv.h require NVRM. */
#ifndef NVRM
#define NVRM
#endif
#ifndef NV_KERNEL_INTERFACE_LAYER
#define NV_KERNEL_INTERFACE_LAYER
#endif
#include "nv.h"
#include "stela_mapping.h"
/* These are the original vendor declarations. The native RAM view token
* replaces Linux's vmap bookkeeping and independently owns the actual CPU pin.
*/
void *NV_API_CALL nv_alloc_kernel_mapping(nv_state_t *nv, void *allocation,
NvU64 page_index, NvU32 page_offset,
NvU64 bytes, void **private)
{
(void)nv;
if (private == NULL)
return NULL;
*private = NULL;
if (allocation == NULL)
return NULL;
return stela_nvidia_map_ram(allocation, page_index, page_offset, bytes, private);
}
void NV_API_CALL nv_free_kernel_mapping(nv_state_t *nv, void *allocation,
void *address, void *private)
{
/* The unique view token owns the mapping. Its parent may already be gone;
* never dereference these original API arguments during view release. */
(void)nv;
(void)allocation;
(void)address;
stela_nvidia_unmap_ram(private);
}
@@ -1,72 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#ifndef STELA_NVIDIA_SERVICES_H
#define STELA_NVIDIA_SERVICES_H
#ifndef NVRM
#define NVRM
#endif
#ifndef NV_KERNEL_INTERFACE_LAYER
#define NV_KERNEL_INTERFACE_LAYER
#endif
#include "nv.h"
#include "os/nv_memory_type.h"
/* Mirror the stable vendor status/cache ABI used by Rust, against the actual
* pinned declarations. A vendor update changing it must fail this build. */
_Static_assert(NV_OK == 0 && NV_ERR_INVALID_ADDRESS == 0x1e &&
NV_ERR_INVALID_ARGUMENT == 0x1f && NV_ERR_INVALID_STATE == 0x40 &&
NV_ERR_NO_MEMORY == 0x51 && NV_ERR_NOT_SUPPORTED == 0x56 &&
NV_ERR_OPERATING_SYSTEM == 0x59, "native status ABI");
_Static_assert(NV_MEMORY_CACHED == 0 && NV_MEMORY_UNCACHED == 1 &&
NV_MEMORY_WRITECOMBINED == 2 && sizeof(NvBool) == 1,
"native cache/boolean ABI");
/* Native same-CPU ABI. Only the device owner binds this live pinned service;
* its source/domain/requester facts are real platform resources, not guest
* handles. Calls and final releases are serialized process/deferred operations,
* never ISR allocation or completion. Stop callers and prove real hardware
* quiescence before unbind/removal. MemoryServices refuses unbind while any
* producer allocation, published DMA token or firmware token remains; keep service/state live
* until all those handles are freed/retired/quarantined/put and unbind succeeds.
* Only CPU views and consumed quarantine may survive. Remaining RM/IRQ services
* are prerequisites. Bind/unbind below are private helpers of the Rust owner;
* use MemoryServices methods so their live-resource checks cannot be bypassed.
*/
NV_STATUS stela_nvidia_bind_memory(nv_state_t *, void *, NvU32, NvU8, NvU8, NvU8);
NV_STATUS stela_nvidia_unbind_memory(nv_state_t *, void *);
/* Storage facts only: no initialization or default device state is supplied. */
void stela_nvidia_state_layout(NvU64 *bytes, NvU64 *alignment);
/* RAM producer: nonzero native-size pages; CACHED/UNCACHED/WRITECOMBINED only,
* node=-1 and no unencrypted request. Other orders/policies are explicit errors.
* Source pins must have exact logical/reserved lengths, native granule and actual
* cache attributes. True contiguity and force_dma32 are verified on physical
* pages. Canonical pages are initially zeroed even if zeroed was not requested.
* Contiguous PTE output has one physical base; otherwise count native physical
* entries. All outputs remain unchanged on error. Allocation-private ownership
* is unique and stays live/pinned through its one matching free; CPU views and
* actual DMA leases retain the backing independently.
*
* DMA input addresses must match those physical PTEs and count/contiguity.
* The retained allocation supplies the actual domain; arbitrary dma_dev values
* are compared as opaque keys, never dereferenced to choose platform state.
* Read-only means TO_DEVICE, otherwise BIDIRECTIONAL. Successful preparation
* finishes real sync_for_device before publishing native IOVAs and a different
* unique DMA-token ownership kind in *private. These are NEVER GPU virtual VAs.
* Failures preserve input addresses/private and remove unpublished mappings, or
* quarantine their actual pins/domain if removal is uncertain.
*
* Unmap requires caller-proven hardware completion, removed GPU bindings and
* stopped/drained submissions/IRQ workers. It performs actual sync_for_cpu,
* removal and invalidation. The original osIovaUnmap discards pOsData even on
* error, so a valid retirement consumes *private: failure enters canonical,
* observable quarantine with a real error, never releases uncertain pages.
* Wrong device/count refuses the request without consuming a different token.
*/
NV_STATUS stela_nvidia_alloc_pages(void *, void *, NvU32, NvU64, NvBool, NvU32,
NvBool, NvBool, NvS32, NvBool, NvU64 *, void **);
NV_STATUS stela_nvidia_free_pages(void *, NvU32, NvBool, NvU32, void *);
NV_STATUS stela_nvidia_dma_map(void *, NvU64, NvU64 *, NvBool, NvBool, void **);
NV_STATUS stela_nvidia_dma_unmap(void *, NvU64, void **);
#endif
-657
View File
@@ -1,657 +0,0 @@
use super::*;
use alloc::vec::Vec;
use core::{cell::RefCell, pin::pin, ptr};
unsafe extern "C" {
fn os_pci_read_byte(handle: *mut c_void, offset: u32, value: *mut u8) -> u32;
fn os_pci_read_word(handle: *mut c_void, offset: u32, value: *mut u16) -> u32;
fn os_pci_read_dword(handle: *mut c_void, offset: u32, value: *mut u32) -> u32;
fn os_pci_write_byte(handle: *mut c_void, offset: u32, value: u8) -> u32;
fn os_pci_write_word(handle: *mut c_void, offset: u32, value: u16) -> u32;
fn os_pci_write_dword(handle: *mut c_void, offset: u32, value: u32) -> u32;
}
/// PCI command followed by W1C status, with a log of bus transaction
/// widths. An ordinary RAM fake cannot detect an accidental dword RMW here.
struct Config {
bytes: [u8; PCI_CONFIG_BYTES as usize],
accesses: RefCell<Vec<(bool, u16, usize)>>,
}
impl Config {
fn new() -> Self {
let mut bytes = [0xa5; PCI_CONFIG_BYTES as usize];
// Command=IO enable; status=capability list plus the six W1C errors
// (bits 15, 14, 13, 12, 11 and 8). Other status bits are read-only.
bytes[4..8].copy_from_slice(&[0x01, 0x00, 0x10, 0xf9]);
Self {
bytes,
accesses: RefCell::new(Vec::new()),
}
}
fn read(&self, offset: u16, width: usize) -> u32 {
self.accesses.borrow_mut().push((false, offset, width));
let mut value = [0; 4];
value[..width].copy_from_slice(&self.bytes[usize::from(offset)..][..width]);
u32::from_le_bytes(value)
}
fn write(&mut self, offset: u16, width: usize, value: u32) {
self.accesses.borrow_mut().push((true, offset, width));
for (index, byte) in value.to_le_bytes().into_iter().take(width).enumerate() {
let address = usize::from(offset) + index;
if address == 6 {
// The low status byte has no W1C bits.
} else if address == 7 {
self.bytes[address] &= !(byte & 0xf9);
} else {
self.bytes[address] = byte;
}
}
}
}
impl ConfigSpace for Config {
fn read32(&self, offset: u16) -> Result<u32, crate::bus::pci::ConfigError> {
Ok(self.read(offset, 4))
}
fn read16(&self, offset: u16) -> Result<u16, crate::bus::pci::ConfigError> {
Ok(self.read(offset, 2) as u16)
}
fn read8(&self, offset: u16) -> Result<u8, crate::bus::pci::ConfigError> {
Ok(self.read(offset, 1) as u8)
}
fn write32(&mut self, offset: u16, value: u32) -> Result<(), crate::bus::pci::ConfigError> {
self.write(offset, 4, value);
Ok(())
}
fn write16(&mut self, offset: u16, value: u16) -> Result<(), crate::bus::pci::ConfigError> {
self.write(offset, 2, u32::from(value));
Ok(())
}
fn write8(&mut self, offset: u16, value: u8) -> Result<(), crate::bus::pci::ConfigError> {
self.write(offset, 1, u32::from(value));
Ok(())
}
}
#[test]
fn vendor_c_hooks_preserve_bus_width_and_adjacent_status() {
let mut config = Config::new();
{
let mut handle = pin!(PciHandle::new(&mut config));
let (mut byte, mut word, mut dword) = (0, 0, 0);
// SAFETY: handle stays pinned and exclusively borrowed for these
// synchronous C calls; outputs are live and no callback reenters.
unsafe {
let raw = handle.as_mut().as_raw();
assert_eq!(os_pci_write_word(raw, 4, 0x0406), 0);
assert_eq!(os_pci_read_word(raw, 6, &mut word), 0);
assert_eq!(word, 0xf910, "command write must not clear status");
assert_eq!(os_pci_write_byte(raw, 7, 0x09), 0);
assert_eq!(os_pci_read_byte(raw, 7, &mut byte), 0);
assert_eq!(byte, 0xf0, "status byte clears only selected bits");
assert_eq!(os_pci_read_word(raw, 4, &mut word), 0);
assert_eq!(word, 0x0406, "status write must not alter command");
assert_eq!(os_pci_write_dword(raw, 4092, 0x1234_5678), 0);
assert_eq!(os_pci_read_dword(raw, 4092, &mut dword), 0);
assert_eq!(dword, 0x1234_5678);
}
}
assert_eq!(config.bytes[6], 0x10, "capability-list bit is read-only");
assert_eq!(
*config.accesses.borrow(),
[
(true, 4, 2),
(false, 6, 2),
(true, 7, 1),
(false, 7, 1),
(false, 4, 2),
(true, 4092, 4),
(false, 4092, 4),
]
);
}
#[test]
fn invalid_vendor_accesses_fail_without_a_bus_transaction() {
let mut config = Config::new();
{
let mut handle = pin!(PciHandle::new(&mut config));
// SAFETY: same pinned/exclusive synchronous contract as above. Null
// arguments are explicitly accepted as errors by the C entry points.
unsafe {
let raw = handle.as_mut().as_raw();
for offset in [4096, 4097, 65536, u32::MAX] {
let (mut byte, mut word, mut dword) = (0, 0, 0);
assert_ne!(os_pci_read_byte(raw, offset, &mut byte), 0);
assert_ne!(os_pci_read_word(raw, offset, &mut word), 0);
assert_ne!(os_pci_read_dword(raw, offset, &mut dword), 0);
assert_eq!((byte, word, dword), (u8::MAX, u16::MAX, u32::MAX));
assert_ne!(os_pci_write_byte(raw, offset, 0), 0);
assert_ne!(os_pci_write_word(raw, offset, 0), 0);
assert_ne!(os_pci_write_dword(raw, offset, 0), 0);
}
for offset in [1, 3, 4093, 4095] {
let mut word = 0;
assert_ne!(os_pci_read_word(raw, offset, &mut word), 0);
assert_eq!(word, u16::MAX);
assert_ne!(os_pci_write_word(raw, offset, 0), 0);
}
for offset in [1, 2, 3, 4093, 4094, 4095] {
let mut dword = 0;
assert_ne!(os_pci_read_dword(raw, offset, &mut dword), 0);
assert_eq!(dword, u32::MAX);
assert_ne!(os_pci_write_dword(raw, offset, 0), 0);
}
let (mut byte, mut word, mut dword) = (0, 0, 0);
assert_ne!(os_pci_read_byte(ptr::null_mut(), 0, &mut byte), 0);
assert_ne!(os_pci_read_word(ptr::null_mut(), 0, &mut word), 0);
assert_ne!(os_pci_read_dword(ptr::null_mut(), 0, &mut dword), 0);
assert_eq!((byte, word, dword), (u8::MAX, u16::MAX, u32::MAX));
assert_ne!(os_pci_write_byte(ptr::null_mut(), 0, 0), 0);
assert_ne!(os_pci_write_word(ptr::null_mut(), 0, 0), 0);
assert_ne!(os_pci_write_dword(ptr::null_mut(), 0, 0), 0);
assert_ne!(os_pci_read_byte(raw, 0, ptr::null_mut()), 0);
assert_ne!(os_pci_read_word(raw, 0, ptr::null_mut()), 0);
assert_ne!(os_pci_read_dword(raw, 0, ptr::null_mut()), 0);
}
}
assert!(config.accesses.borrow().is_empty());
assert_eq!(config.bytes, Config::new().bytes);
}
#[test]
fn the_end_of_config_space_accepts_each_natural_width() {
let mut config = Config::new();
{
let mut handle = pin!(PciHandle::new(&mut config));
// SAFETY: pinned/exclusive synchronous calls with live outputs.
unsafe {
let raw = handle.as_mut().as_raw();
let (mut byte, mut word, mut dword) = (0, 0, 0);
assert_eq!(os_pci_write_dword(raw, 4092, 0x1234_5678), 0);
assert_eq!(os_pci_write_word(raw, 4094, 0xabcd), 0);
assert_eq!(os_pci_write_byte(raw, 4095, 0xef), 0);
assert_eq!(os_pci_read_byte(raw, 4095, &mut byte), 0);
assert_eq!(os_pci_read_word(raw, 4094, &mut word), 0);
assert_eq!(os_pci_read_dword(raw, 4092, &mut dword), 0);
assert_eq!((byte, word, dword), (0xef, 0xefcd, 0xefcd_5678));
}
}
assert_eq!(config.accesses.borrow().len(), 6);
}
unsafe extern "C" {
fn os_mem_copy(destination: *mut c_void, source: *const c_void, bytes: u32) -> *mut c_void;
fn os_mem_set(destination: *mut c_void, value: u8, bytes: u32) -> *mut c_void;
fn os_mem_cmp(left: *const u8, right: *const u8, bytes: u32) -> i32;
fn os_string_length(string: *const core::ffi::c_char) -> u32;
}
#[test]
fn original_memory_primitives_preserve_returns_bytes_and_untouched_spans() {
let mut source = [0u8; 4096 + 32];
for (index, byte) in source.iter_mut().enumerate() {
*byte = (index.wrapping_mul(37) + 0x80) as u8;
}
for size in [
0, 1, 2, 3, 7, 8, 15, 16, 31, 32, 127, 128, 129, 255, 256, 4096,
] {
for source_offset in 0..16 {
for destination_offset in 0..16 {
let mut destination = [0xa5u8; 4096 + 32];
// SAFETY: real nonoverlapping CPU arrays cover the complete
// ranges; zero-byte calls also use valid array pointers.
let pointer = unsafe { destination.as_mut_ptr().add(destination_offset) };
// SAFETY: the pointer addresses this test's own live pages, and the stopped
// model writes nothing concurrently.
let input = unsafe { source.as_ptr().add(source_offset) };
assert_eq!(
// SAFETY: the arguments are live locals sized for the call, and the test
// owns any state it touches.
unsafe { os_mem_copy(pointer.cast(), input.cast(), size as u32) },
pointer.cast()
);
for (index, &byte) in destination.iter().enumerate() {
let expected = if (destination_offset..destination_offset + size)
.contains(&index)
{
((source_offset + index - destination_offset).wrapping_mul(37) + 0x80) as u8
} else {
0xa5
};
assert_eq!(
byte, expected,
"copy span: {size}/{source_offset}/{destination_offset}/{index}"
);
}
// SAFETY: the same full CPU ranges remain readable.
assert_eq!(unsafe { os_mem_cmp(pointer, input, size as u32) }, 0);
}
}
for offset in 0..16 {
for value in [0, 0x80, 0xff] {
let mut destination = [0xa5u8; 4096 + 32];
// SAFETY: writable CPU array covers this complete span.
let pointer = unsafe { destination.as_mut_ptr().add(offset) };
assert_eq!(
// SAFETY: the arguments are live locals sized for the call, and the test
// owns any state it touches.
unsafe { os_mem_set(pointer.cast(), value, size as u32) },
pointer.cast()
);
for (index, &byte) in destination.iter().enumerate() {
assert_eq!(
byte,
if (offset..offset + size).contains(&index) {
value
} else {
0xa5
}
);
}
}
}
}
}
#[test]
fn original_compare_uses_unsigned_first_difference_and_exact_requested_length() {
for size in [1, 2, 7, 8, 15, 16, 31, 32, 127, 128, 129, 256] {
for mismatch in 0..size {
for (left_byte, right_byte) in [(0, 0xff), (0x80, 0x7f), (0xff, 1)] {
let mut left = [0x6du8; 288];
let mut right = left;
left[mismatch] = left_byte;
right[mismatch] = right_byte;
// Differences outside the requested span cannot affect results.
left[size] = 0xff;
right[size] = 0;
let expected = (i32::from(left_byte) - i32::from(right_byte)).signum();
assert_eq!(
// SAFETY: both arrays cover the exact requested CPU byte range.
unsafe { os_mem_cmp(left.as_ptr(), right.as_ptr(), size as u32) }.signum(),
expected
);
assert_eq!(
// SAFETY: the arguments are live locals sized for the call, and the test
// owns any state it touches.
unsafe { os_mem_cmp(right.as_ptr(), left.as_ptr(), size as u32) }.signum(),
-expected
);
assert_eq!(
// SAFETY: both slices are live locals at least `mismatch` bytes long.
unsafe { os_mem_cmp(left.as_ptr(), right.as_ptr(), mismatch as u32) },
0
);
}
}
}
}
#[test]
fn original_string_length_counts_bytes_until_first_nul() {
let mut string = [0x80u8; 4096 + 32];
for offset in 0..16 {
for length in [0, 1, 2, 7, 8, 15, 16, 31, 32, 127, 128, 129, 4096] {
string.fill(0x80);
string[offset + length] = 0;
// SAFETY: readable real CPU array, bounded terminated C string.
let pointer = unsafe { string.as_ptr().add(offset) };
// SAFETY: `pointer` addresses a NUL-terminated string inside the local array.
assert_eq!(unsafe { os_string_length(pointer.cast()) }, length as u32);
}
}
}
unsafe extern "C" {
fn nvkms_memcpy(destination: *mut c_void, source: *const c_void, bytes: usize) -> *mut c_void;
fn nvkms_memmove(destination: *mut c_void, source: *const c_void, bytes: usize) -> *mut c_void;
fn nvkms_memset(destination: *mut c_void, value: u8, bytes: usize) -> *mut c_void;
fn nvkms_memcmp(left: *const c_void, right: *const c_void, bytes: usize) -> i32;
fn nvkms_strlen(string: *const core::ffi::c_char) -> usize;
fn nvlink_memcpy(destination: *mut c_void, source: *const c_void, bytes: u64) -> *mut c_void;
fn nvlink_memset(destination: *mut c_void, value: i32, bytes: u64) -> *mut c_void;
fn nvlink_strlen(string: *const core::ffi::c_char) -> u64;
fn nvswitch_os_memcpy(
destination: *mut c_void,
source: *const c_void,
bytes: u64,
) -> *mut c_void;
fn nvswitch_os_memset(destination: *mut c_void, value: i32, bytes: u64) -> *mut c_void;
fn nvswitch_os_strlen(string: *const core::ffi::c_char) -> u64;
}
#[test]
fn copy_helpers_match_native_results() {
let mut source = [0u8; 4096 + 32];
for (index, byte) in source.iter_mut().enumerate() {
*byte = (index.wrapping_mul(53) + 0x81) as u8;
}
for size in [0, 1, 2, 7, 8, 15, 16, 31, 32, 127, 128, 129, 4096] {
for source_offset in 0..8 {
for destination_offset in 0..16 {
for variant in 0..3 {
let mut destination = [0xa5u8; 4096 + 32];
// SAFETY: real nonoverlapping CPU arrays cover both spans.
let pointer = unsafe { destination.as_mut_ptr().add(destination_offset) };
// SAFETY: `source` is a local array long enough for every offset and size.
let input = unsafe { source.as_ptr().add(source_offset) };
// SAFETY: `pointer` and `input` cover `size` bytes of two local arrays.
let returned = unsafe {
match variant {
0 => nvkms_memcpy(pointer.cast(), input.cast(), size),
1 => nvlink_memcpy(pointer.cast(), input.cast(), size as u64),
_ => nvswitch_os_memcpy(pointer.cast(), input.cast(), size as u64),
}
};
assert_eq!(returned, pointer.cast());
for (index, &byte) in destination.iter().enumerate() {
let expected =
if (destination_offset..destination_offset + size).contains(&index) {
((source_offset + index - destination_offset).wrapping_mul(53)
+ 0x81) as u8
} else {
0xa5
};
assert_eq!(byte, expected);
}
}
}
}
for offset in 0..16 {
for value in [-1i32, 0, 0x80, 0x180, 0x1ff] {
for variant in 0..3 {
let mut destination = [0xa5u8; 4096 + 32];
// SAFETY: CPU storage covers the complete span.
let pointer = unsafe { destination.as_mut_ptr().add(offset) };
// SAFETY: `pointer` covers `size` bytes of the local array.
let returned = unsafe {
match variant {
0 => nvkms_memset(pointer.cast(), value as u8, size),
1 => nvlink_memset(pointer.cast(), value, size as u64),
_ => nvswitch_os_memset(pointer.cast(), value, size as u64),
}
};
assert_eq!(returned, pointer.cast());
for (index, &byte) in destination.iter().enumerate() {
assert_eq!(
byte,
if (offset..offset + size).contains(&index) {
value as u8
} else {
0xa5
}
);
}
}
}
}
}
}
#[test]
fn original_display_memmove_handles_both_overlap_directions_and_same_range() {
for size in [0, 1, 2, 7, 8, 15, 16, 31, 127, 128, 129, 256, 4096] {
for (source_offset, destination_offset) in [(0, 1), (1, 0), (7, 14), (14, 7), (8, 8)] {
let mut bytes = [0u8; 4096 + 32];
for (index, byte) in bytes.iter_mut().enumerate() {
*byte = (index.wrapping_mul(19) + 0x83) as u8;
}
// SAFETY: one real CPU allocation covers both full possibly
// overlapping ranges, which original memmove explicitly permits.
let source = unsafe { bytes.as_ptr().add(source_offset) };
// SAFETY: `bytes` is long enough for every offset and size.
let destination = unsafe { bytes.as_mut_ptr().add(destination_offset) };
assert_eq!(
// SAFETY: both ranges lie inside the one local array; memmove permits overlap.
unsafe { nvkms_memmove(destination.cast(), source.cast(), size) },
destination.cast()
);
for (index, &byte) in bytes.iter().enumerate() {
let original_index =
if (destination_offset..destination_offset + size).contains(&index) {
source_offset + index - destination_offset
} else {
index
};
assert_eq!(byte, (original_index.wrapping_mul(19) + 0x83) as u8);
}
}
}
}
#[test]
fn original_display_compare_and_native_length_returns_use_raw_unsigned_bytes() {
for size in [1, 2, 7, 8, 15, 16, 31, 127, 128, 129, 256] {
for mismatch in 0..size {
let mut left = [0x55u8; 288];
let mut right = left;
left[mismatch] = 0x80;
right[mismatch] = 0x7f;
left[size] = 0;
right[size] = 0xff;
// SAFETY: readable CPU arrays cover the exact requested spans.
unsafe {
assert_eq!(
nvkms_memcmp(left.as_ptr().cast(), right.as_ptr().cast(), size).signum(),
1
);
assert_eq!(
nvkms_memcmp(right.as_ptr().cast(), left.as_ptr().cast(), size).signum(),
-1
);
assert_eq!(
nvkms_memcmp(left.as_ptr().cast(), right.as_ptr().cast(), mismatch),
0
);
}
}
}
let mut string = [0x80u8; 4096 + 32];
for offset in 0..16 {
for length in [0, 1, 7, 8, 15, 16, 31, 127, 128, 129, 4096] {
string.fill(0x80);
string[offset + length] = 0;
// SAFETY: readable CPU bytes include their terminating NUL.
let pointer = unsafe { string.as_ptr().add(offset) };
// SAFETY: `pointer` addresses a NUL-terminated string inside the local array.
unsafe {
assert_eq!(nvkms_strlen(pointer.cast()), length);
assert_eq!(nvlink_strlen(pointer.cast()), length as u64);
assert_eq!(nvswitch_os_strlen(pointer.cast()), length as u64);
}
}
}
}
#[test]
fn nvlink_c_metadata_keeps_full_payload_and_zero_size_ownership() {
unsafe extern "C" {
fn nvlink_malloc(bytes: u64) -> *mut c_void;
fn nvlink_free(pointer: *mut c_void);
}
let sizes = [0, 1, 7, 8, 15, 16, 17, 4095, 4096, 4097, 65537];
let mut pointers = [ptr::null_mut::<c_void>(); 11];
for (index, (&bytes, pointer)) in sizes.iter().zip(&mut pointers).enumerate() {
// SAFETY: this hosted process has a live common heap and no reentry.
*pointer = unsafe { nvlink_malloc(bytes) };
assert!(!pointer.is_null());
assert_eq!(*pointer as usize % 16, 0);
// SAFETY: the checked allocation owns the complete requested payload.
unsafe {
pointer
.cast::<u8>()
.write_bytes(index as u8, bytes as usize)
};
}
for (index, (&bytes, &pointer)) in sizes.iter().zip(&pointers).enumerate().rev() {
assert!(!pointers[..index].contains(&pointer));
// SAFETY: all allocations are still live and held only by this test.
let payload = unsafe { core::slice::from_raw_parts(pointer.cast::<u8>(), bytes as usize) };
assert!(payload.iter().all(|&byte| byte == index as u8));
// SAFETY: free exactly this allocator's original live pointer once.
unsafe { nvlink_free(pointer) };
}
// SAFETY: the original null-free contract is preserved by the common heap.
unsafe { nvlink_free(ptr::null_mut()) };
}
#[test]
fn nvlink_c_invalid_native_layouts_return_null_before_allocating() {
unsafe extern "C" {
fn nvlink_malloc(bytes: u64) -> *mut c_void;
}
for bytes in [u64::MAX, isize::MAX as u64, isize::MAX as u64 - 16] {
// SAFETY: a scalar request; checked layouts refuse this before the heap.
assert!(unsafe { nvlink_malloc(bytes) }.is_null());
}
}
#[test]
fn nvkms_c_metadata_zero_flags_and_native_sizes_use_the_real_common_heap() {
unsafe extern "C" {
fn nvkms_alloc(bytes: u64, zero: u8) -> *mut c_void;
fn nvkms_free(pointer: *mut c_void, bytes: u64);
}
let cases = [(0, 255), (1, 1), (15, 2), (16, 255), (17, 0), (4097, 1)];
let mut pointers = [ptr::null_mut::<c_void>(); 6];
for (index, (&(bytes, zero), pointer)) in cases.iter().zip(&mut pointers).enumerate() {
// SAFETY: ordinary hosted process context, live shared heap, no reentry.
*pointer = unsafe { nvkms_alloc(bytes, zero) };
assert!(!pointer.is_null());
assert_eq!(*pointer as usize % 16, 0);
if zero != 0 {
// SAFETY: successful allocation initialized the full requested span.
let payload =
unsafe { core::slice::from_raw_parts(pointer.cast::<u8>(), bytes as usize) };
assert!(payload.iter().all(|&byte| byte == 0));
}
// SAFETY: uniquely owned complete payload, initialized before reading.
unsafe {
pointer
.cast::<u8>()
.write_bytes(0x70 + index as u8, bytes as usize)
};
}
for (index, (&(bytes, _), &pointer)) in cases.iter().zip(&pointers).enumerate().rev() {
assert!(!pointers[..index].contains(&pointer));
// SAFETY: all allocations are still live and exclusively held here.
let payload = unsafe { core::slice::from_raw_parts(pointer.cast::<u8>(), bytes as usize) };
assert!(payload.iter().all(|&byte| byte == 0x70 + index as u8));
// SAFETY: original pointer and exact size, once, after all access stops.
unsafe { nvkms_free(pointer, bytes) };
}
// SAFETY: original NULL-free contract is valid independently of the size.
unsafe { nvkms_free(ptr::null_mut(), u64::MAX) };
}
#[test]
fn nvkms_c_invalid_layouts_fail_for_every_original_zero_flag_value() {
unsafe extern "C" {
fn nvkms_alloc(bytes: u64, zero: u8) -> *mut c_void;
}
for zero in [0, 1, 2, 255] {
for bytes in [u64::MAX, isize::MAX as u64, isize::MAX as u64 - 16] {
// SAFETY: invalid scalar layouts are rejected before heap access.
assert!(unsafe { nvkms_alloc(bytes, zero) }.is_null());
}
}
}
// An explicit provider denial is distinct from a successful all-ones read.
// This models only Rust/C status/latch semantics, never physical hardware.
struct Denied<'a> {
mode: &'a core::cell::Cell<u8>,
calls: &'a core::cell::Cell<usize>,
}
impl Denied<'_> {
fn read(&self) -> Result<u32, ConfigError> {
self.calls.set(self.calls.get() + 1);
if self.mode.get() == 0 {
Ok(u32::MAX)
} else {
Err(ConfigError::before_effect(
crate::bus::pci::ConfigFailure::ForeignGrant,
))
}
}
fn write(&self, offset: u16, width: u8) -> Result<(), ConfigError> {
self.calls.set(self.calls.get() + 1);
Err(ConfigError::write_may_have_applied(
offset,
width,
crate::bus::pci::ConfigFailure::ForeignGrant,
))
}
}
impl ConfigSpace for Denied<'_> {
fn read8(&self, _: u16) -> Result<u8, ConfigError> {
self.read().map(|v| v as u8)
}
fn read16(&self, _: u16) -> Result<u16, ConfigError> {
self.read().map(|v| v as u16)
}
fn read32(&self, _: u16) -> Result<u32, ConfigError> {
self.read()
}
fn write8(&mut self, o: u16, _: u8) -> Result<(), ConfigError> {
self.write(o, 1)
}
fn write16(&mut self, o: u16, _: u16) -> Result<(), ConfigError> {
self.write(o, 2)
}
fn write32(&mut self, o: u16, _: u32) -> Result<(), ConfigError> {
self.write(o, 4)
}
}
#[test]
fn original_pci_prefix_preserves_typed_denial_and_closes_after_uncertain_write() {
let mode = core::cell::Cell::new(0);
let calls = core::cell::Cell::new(0);
let mut config = Denied {
mode: &mode,
calls: &calls,
};
{
let mut handle = pin!(PciHandle::new(&mut config));
// SAFETY: pinned handle, exclusive serialized model, live output.
let raw = unsafe { handle.as_mut().as_raw() };
let mut value = 0;
// SAFETY: serialized pinned CPU-only fixture; output/configuration is live and owned.
assert_eq!(unsafe { os_pci_read_dword(raw, 0, &mut value) }, 0);
assert_eq!(value, u32::MAX);
assert_eq!(handle.failure(), None);
mode.set(1);
// SAFETY: serialized pinned CPU-only fixture; output/configuration is live and owned.
assert_ne!(unsafe { os_pci_read_dword(raw, 0, &mut value) }, 0);
let error = ConfigError::before_effect(crate::bus::pci::ConfigFailure::ForeignGrant);
assert_eq!(handle.failure(), Some(error));
mode.set(0);
// SAFETY: serialized pinned CPU-only fixture; output/configuration is live and owned.
assert_ne!(unsafe { os_pci_write_dword(raw, 4, 0) }, 0);
assert_eq!(calls.get(), 2, "denial closes later bus access");
assert_eq!(handle.failure(), Some(error));
}
let mut handle = pin!(PciHandle::new(&mut config));
// SAFETY: same exact model/pinning contract, no physical writes.
let raw = unsafe { handle.as_mut().as_raw() };
// SAFETY: serialized pinned CPU-only fixture; output/configuration is live and owned.
assert_ne!(unsafe { os_pci_write_word(raw, 4, 7) }, 0);
let error =
ConfigError::write_may_have_applied(4, 2, crate::bus::pci::ConfigFailure::ForeignGrant);
assert_eq!(handle.failure(), Some(error));
let before = calls.get();
let mut value = 0;
// SAFETY: serialized pinned CPU-only fixture; output/configuration is live and owned.
assert_ne!(unsafe { os_pci_read_dword(raw, 0, &mut value) }, 0);
assert_eq!(calls.get(), before);
assert_eq!(handle.failure(), Some(error));
}
@@ -1,15 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include "x86emu/x86emu.h"
_Static_assert(sizeof(((X86EMU_sysEnv *)0)->mem_base) == sizeof(void *),
"emulator host addresses must be pointer-sized");
_Static_assert(sizeof(((X86EMU_sysEnv *)0)->mem_size) == sizeof(void *),
"emulator lengths must be pointer-sized");
_Static_assert(__builtin_offsetof(X86EMU_sysEnv, private) == 2 * sizeof(void *),
"preserve the LP64 memory-state layout");
/* -Werror also rejects truncation of these concrete addresses above 4 GiB. */
const X86EMU_sysEnv high_memory = {
.mem_base = 0x100001000ULL,
.mem_size = 0x100002000ULL,
};
@@ -1,11 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Compile these actual driver types under the native COFF and Linux ABIs. */
#include "os/workitem.h"
constexpr OsQueueWorkItemFlags read_only = {
.apiLock = WORKITEM_FLAGS_API_LOCK_READ_ONLY,
};
static_assert(read_only.apiLock == WORKITEM_FLAGS_API_LOCK_READ_ONLY,
"read-only lock selection must survive packed storage");
static_assert(sizeof(OsQueueWorkItemFlags) == sizeof(NvU32),
"preserve the vendor flag ABI");
@@ -1,79 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Original C records and private input ABI; compile-only layout arrays on every
* native target. Host main uses only bounded CPU config, never RM/hardware. */
#include "../stela_device.h"
#include "../stela_pci.h"
const NvU64 stela_nvidia_device_layout[] = {
sizeof(struct stela_nvidia_device_bar), _Alignof(struct stela_nvidia_device_bar),
offsetof(struct stela_nvidia_device_bar, bytes), offsetof(struct stela_nvidia_device_bar, index),
offsetof(struct stela_nvidia_device_bar, prefetchable),
sizeof(struct stela_nvidia_device_identity), _Alignof(struct stela_nvidia_device_identity),
offsetof(struct stela_nvidia_device_identity, subsystem),
sizeof(nv_state_t), _Alignof(nv_state_t), offsetof(nv_state_t, bars),
offsetof(nv_state_t, handle), offsetof(nv_state_t, regs), offsetof(nv_state_t, fb),
sizeof(nv_aperture_t), offsetof(nv_aperture_t, offset),
NV_GPU_NUM_BARS, NV_GPU_BAR_INDEX_REGS, NV_GPU_BAR_INDEX_FB, NV_GPU_BAR_INDEX_IMEM,
};
#ifdef STELA_NVIDIA_DEVICE_TEST_MAIN
#include <assert.h>
#include <stdio.h>
#include <string.h>
struct config { NvU32 words[NVRM_PCICFG_NUM_DWORDS], reads; };
static NvU32 read_config(void *p, NvU32 offset, NvU32 width, NvU32 *out)
{
struct config *c = p;
assert(width == 4 && offset < sizeof(c->words) && !(offset & 3));
++c->reads; *out = c->words[offset / 4]; return 1;
}
static NvU32 write_config(void *p, NvU32 offset, NvU32 width, NvU32 value)
{ (void)p; (void)offset; (void)width; (void)value; assert(0); return 0; }
int main(void)
{
const struct config original = {.words = {[0]=0x268410de, [2]=0x03000001,
[4]=0x10000004, [5]=1, [6]=0x2000000c, [7]=2, [8]=0x30000004, [9]=3,
[11]=0x123410de}};
const struct stela_nvidia_device_identity id = {3,0x42,5,0,0x10de,0x2684,0x10de,0x1234};
const struct stela_nvidia_device_bar original_bars[3] = {
{0x110000000,0x10000,0,0},{0x220000000,0x200000,2,1},{0x330000000,0x10000,4,0}};
unsigned refused = 0;
for (unsigned mode=0; mode<13; ++mode) {
struct config config=original;
struct stela_nvidia_pci handle={&config,read_config,write_config};
struct stela_nvidia_device_identity identity=id;
struct stela_nvidia_device_bar bars[3]; memcpy(bars,original_bars,sizeof(bars));
nv_state_t state, before; memset(&state,0,sizeof(state)); memcpy(&before,&state,sizeof(state));
switch(mode) {
case 0: break; case 1:config.words[0]^=1;break;case 2:config.words[11]^=1;break;
case 3:config.words[3]=0x10000;break;case 4:bars[0].physical^=0x10000;break;
case 5:bars[1].index=4;break;case 6:bars[0].prefetchable=1;break;
case 7:bars[1].bytes=NV_U64_MAX;break;case 8:identity.function=8;break;
case 9:config.words[4]|=1;break;case 10:config.words[8]=0;config.words[9]=0;break;
case 11: { struct stela_nvidia_device_bar tmp=bars[0];bars[0]=bars[2];bars[2]=tmp; break; }
case 12:
/* A generic ordered-memory scan would accept this, but the
* original second loop skips index0 then repeats index1 as FB. */
memset(&config.words[4],0,6*sizeof(NvU32));
config.words[5]=0x10000000;config.words[6]=0x20000008;config.words[7]=0x30000000;
bars[0]=(struct stela_nvidia_device_bar){0x10000000,0x10000,1,0};
bars[1]=(struct stela_nvidia_device_bar){0x20000000,0x200000,2,1};
bars[2]=(struct stela_nvidia_device_bar){0x30000000,0x10000,3,0};
break;
}
NV_STATUS status=stela_nvidia_prepare_device(&state,&handle,&identity,bars,3);
if(mode) {assert(status!=NV_OK);assert(!memcmp(&state,&before,sizeof(state)));++refused;continue;}
assert(status==NV_OK && config.reads==NVRM_PCICFG_NUM_DWORDS);
assert(state.handle==&handle && !state.priv && !state.os_state && !state.dma_dev && !state.flags);
assert(state.pci_info.domain==3 && state.pci_info.bus==0x42 && state.pci_info.slot==5);
assert(state.regs==&state.bars[NV_GPU_BAR_INDEX_REGS]);assert(state.fb==&state.bars[NV_GPU_BAR_INDEX_FB]);
for(unsigned i=0;i<NV_GPU_NUM_BARS;++i){assert(state.bars[i].cpu_address==bars[i].physical);
assert(state.bars[i].size==bars[i].bytes && state.bars[i].offset==NVRM_PCICFG_BAR_OFFSET(bars[i].index));
assert(!state.bars[i].map&&!state.bars[i].map_u);}
assert(!memcmp(state.pci_cfg_space,original.words,sizeof(original.words)));
assert(stela_nvidia_prepared_device_retirable(&state,&handle)==NV_OK);
state.flags=NV_FLAG_INITIALIZED;assert(stela_nvidia_prepared_device_retirable(&state,&handle)==NV_ERR_INVALID_STATE);
state.flags=0;state.priv=&config;assert(stela_nvidia_prepared_device_retirable(&state,&handle)==NV_ERR_INVALID_STATE);
}
printf("original C nv_state/BAR roles+layout, %u atomic refusals; CPU-only preparation\n",refused);
return 0;
}
#endif
@@ -1,113 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Separate CPU-only fixture. Include the unchanged original allocation unit
* so its private prefix is real, never a reconstructed vendor record. Link
* unchanged nvkms-lut.c for the actual upload loop, with dead-code removal.
* The two metadata hook definitions below exist only in this test process.
*/
#include "nvkms-utils.c"
#include "nvkms-lut.h"
#include "stela_memory.h"
void stela_nvkms_test_heap_initialize(void);
size_t stela_nvkms_test_heap_live(void);
static void *allocation;
static size_t allocation_bytes;
static unsigned int allocated, freed, invalid_free;
void *nvkms_alloc(size_t size, NvBool zero)
{
void *p = NULL;
if (stela_nvidia_alloc(size, &p) != STELA_NVIDIA_ALLOC_SUCCESS)
return NULL;
allocation = p;
allocation_bytes = size;
allocated++;
if (zero)
nvkms_memset(p, 0, size);
return p;
}
void nvkms_free(void *p, size_t size)
{
if (p != allocation || size != allocation_bytes)
invalid_free++;
stela_nvidia_free(p);
freed++;
}
static NvU16 value_at(unsigned int output, size_t entry, size_t channel)
{
return (NvU16)((output ? 0x9000 : 0x1000) +
entry * (channel * 2 + 3) + channel * 0x111);
}
/* An independent byte-coordinate expectation, including both rounded slots.
* This does not replay the original dword upload algorithm or use a round trip.
*/
static NvU8 expected_at(size_t byte)
{
const size_t array_bytes = 8232;
const unsigned int output = byte >= 8448;
const size_t local = output ? byte - 8448 : byte;
NvU16 value;
if (local >= array_bytes)
return 0;
value = value_at(output, local / 8, (local % 8) / 2);
return (NvU8)(value >> ((local % 2) * 8));
}
int main(void)
{
static _Alignas(16) NvU8 destination[16896 + 32];
NVSurfaceEvoRec surface = {0};
NVDispEvoRec display = {0};
NVEvoLutDataRec *p;
size_t i;
const size_t entries = NV_LUT_VSS_HEADER_SIZE + NV_NUM_EVO_LUT_ENTRIES;
stela_nvkms_test_heap_initialize();
if (stela_nvkms_test_heap_live() != 0)
return 1;
p = nvInternalAlloc(sizeof(*p), TRUE);
if (p == NULL || sizeof(nvkms_memory_info_t) != 8 ||
offsetof(nvkms_memory_info_t, data) != 8 ||
(NvU8 *)p - (NvU8 *)allocation != 8 ||
allocation_bytes != sizeof(*p) + 8 ||
((NvUPtr)p & 15) != 8 || ((NvUPtr)p & 255) == 0 ||
((NvUPtr)p & 3) != 0)
return 2;
for (i = 0; i < sizeof(*p); i++) {
if (((const NvU8 *)p)[i] != 0)
return 3;
}
for (i = 0; i < entries; i++) {
p->base[i].Red = value_at(0, i, 0);
p->base[i].Green = value_at(0, i, 1);
p->base[i].Blue = value_at(0, i, 2);
p->base[i].Unused = value_at(0, i, 3);
p->output[i].Red = value_at(1, i, 0);
p->output[i].Green = value_at(1, i, 1);
p->output[i].Blue = value_at(1, i, 2);
p->output[i].Unused = value_at(1, i, 3);
}
nvkms_memset(destination, 0xa5, sizeof(destination));
surface.cpuAddress[0] = destination + 16;
surface.planes[0].rmObjectSizeInBytes = sizeof(*p);
display.displayOwner = 0;
nvUploadDataToLutSurfaceEvo(&surface, p, &display);
for (i = 0; i < sizeof(*p); i++) {
if (((const NvU8 *)p)[i] != expected_at(i) ||
destination[16 + i] != expected_at(i))
return 4;
}
for (i = 0; i < 16; i++) {
if (destination[i] != 0xa5 || destination[16 + sizeof(*p) + i] != 0xa5)
return 5;
}
nvInternalFree(p);
if (allocated != 1 || freed != 1 || invalid_free != 0 ||
stela_nvkms_test_heap_live() != 0)
return 6;
return 0;
}
@@ -1,47 +0,0 @@
//! CPU fixture only: the common heap and metadata adapter, with a
//! process-owned host buffer. This is never linked into the production driver.
#![no_std]
#![expect(
dead_code,
reason = "the fixture uses part of the shared heap and the metadata adapter"
)]
extern crate alloc;
// `cargo xtask gpu` builds this file alone with rustc
// (`xtask/src/gpu/nvidia/lut.rs`), which records the heap source it includes.
// No Cargo edge links the driver to the boot heap.
#[path = "../../../../stela-boot-core/src/heap.rs"]
mod common_heap;
#[path = "../memory.rs"]
mod nvidia_memory;
#[global_allocator]
static HEAP: common_heap::Heap = common_heap::Heap::new();
#[repr(align(4096))]
struct Buffer([u8; 128 * 1024]);
static mut BUFFER: Buffer = Buffer([0; 128 * 1024]);
/// # Safety
/// The separate single-thread CPU fixture calls once before any allocation;
/// no aliases, interrupts, migration or concurrent users reach its buffer.
#[unsafe(no_mangle)]
unsafe extern "C" fn stela_nvkms_test_heap_initialize() {
// SAFETY: the fixture owns the full aligned static buffer for its lifetime.
unsafe { HEAP.initialize(core::ptr::addr_of_mut!(BUFFER).cast(), size_of::<Buffer>()) };
}
#[unsafe(no_mangle)]
extern "C" fn stela_nvkms_test_heap_live() -> usize {
HEAP.usage().live
}
#[panic_handler]
fn fixture_panic(_: &core::panic::PanicInfo) -> ! {
unsafe extern "C" {
fn abort() -> !;
}
// SAFETY: host C runtime termination for this separate CPU fixture.
// No NVIDIA fatal, purecall, thunk or production runtime hook is supplied.
unsafe { abort() }
}
@@ -1,49 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Compile as C11 and C++11 with the real NVKMS header for each native/host
* ABI. These constants freeze the device byte layout and the declared CPU
* alignment. This fixture supplies no platform services.
*/
#include "nvkms-types.h"
#ifdef __cplusplus
extern "C" {
extern const NvU64 stela_nvkms_lut_layout[];
extern const char *const stela_nvkms_lut_layout_labels[];
extern const NvU64 stela_nvkms_lut_layout_count;
#endif
#define STELA_LUT_LAYOUT(M) \
M("sizeof(NVEvoLutEntryRec)", sizeof(NVEvoLutEntryRec)) \
M("alignof(NVEvoLutEntryRec)", NV_ALIGNOF(NVEvoLutEntryRec)) \
M("sizeof(NVEvoLutDataRec)", sizeof(NVEvoLutDataRec)) \
M("alignof(NVEvoLutDataRec)", NV_ALIGNOF(NVEvoLutDataRec)) \
M("offsetof(base)", offsetof(NVEvoLutDataRec, base)) \
M("offsetof(output)", offsetof(NVEvoLutDataRec, output)) \
M("sizeof(base)", sizeof(((NVEvoLutDataRec *)0)->base)) \
M("sizeof(output)", sizeof(((NVEvoLutDataRec *)0)->output))
#define STELA_LUT_VALUE(label, value) (NvU64)(value),
const NvU64 stela_nvkms_lut_layout[] = { STELA_LUT_LAYOUT(STELA_LUT_VALUE) };
#undef STELA_LUT_VALUE
#define STELA_LUT_LABEL(label, value) label,
const char *const stela_nvkms_lut_layout_labels[] = { STELA_LUT_LAYOUT(STELA_LUT_LABEL) };
#undef STELA_LUT_LABEL
const NvU64 stela_nvkms_lut_layout_count =
sizeof(stela_nvkms_lut_layout) / sizeof(stela_nvkms_lut_layout[0]);
ct_assert(sizeof(NVEvoLutDataRec) == 16896);
ct_assert(offsetof(NVEvoLutDataRec, base) == 0);
ct_assert(offsetof(NVEvoLutDataRec, output) == 8448);
ct_assert(sizeof(((NVEvoLutDataRec *)0)->base) == 8232);
ct_assert(sizeof(((NVEvoLutDataRec *)0)->output) == 8232);
ct_assert(NV_ALIGNOF(NVEvoLutDataRec) == 256);
void stela_nvkms_lut_first_entry_store(NVEvoLutDataRec *p, NvU16 value);
void stela_nvkms_lut_first_entry_store(NVEvoLutDataRec *p, NvU16 value)
{
p->output[0].Red = value;
}
#ifdef __cplusplus
}
#endif
@@ -1,223 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Separate CPU process. Keep the original private prefix/realloc algorithm,
* observing only its sized free call. The production backend is a separately
* compiled real stela_nvkms_memory.c; only its common-heap/zero callees are
* renamed to the bounded observation/denial seams below. These definitions
* never enter a production archive. The existing lut_heap.rs supplies the
* actual shared Heap and metadata adapter, with no alternate heap algorithm.
*/
#include "nvidia-modeset-os-interface.h"
void stela_nvkms_observed_free(void *pointer, size_t size);
#define nvkms_free stela_nvkms_observed_free
#include "nvkms-utils.c"
#undef nvkms_free
#include "stela_memory.h"
void stela_nvkms_test_heap_initialize(void);
size_t stela_nvkms_test_heap_live(void);
NvU32 stela_nvkms_model_alloc(NvU64 bytes, void **out);
void stela_nvkms_model_free(void *pointer);
void *stela_nvkms_model_zero(void *pointer, NvU8 value, size_t bytes);
/* Two simultaneously live allocations cover the original realloc transition.
* This is fixture ownership accounting, never a production allocation registry.
*/
static struct {
void *pointer;
NvU64 bytes;
} live[2];
static NvU32 deny_status;
static NvU64 last_request;
static unsigned int allocation_calls, free_calls, zero_calls;
static unsigned int sized_frees, null_frees, errors;
static int live_index(void *pointer)
{
unsigned int i;
for (i = 0; i < 2; i++) {
if (live[i].pointer == pointer)
return (int)i;
}
return -1;
}
NvU32 stela_nvkms_model_alloc(NvU64 bytes, void **out)
{
NvU32 status;
unsigned int i;
allocation_calls++;
last_request = bytes;
*out = NULL;
if (deny_status != 0)
return deny_status;
status = stela_nvidia_alloc(bytes, out);
if (status != STELA_NVIDIA_ALLOC_SUCCESS)
return status;
for (i = 0; i < 2; i++) {
if (live[i].pointer == NULL) {
live[i].pointer = *out;
live[i].bytes = bytes;
return status;
}
}
errors++;
stela_nvidia_free(*out);
*out = NULL;
return STELA_NVIDIA_ALLOC_OUT_OF_MEMORY;
}
void stela_nvkms_model_free(void *pointer)
{
int i;
if (pointer == NULL) {
null_frees++;
stela_nvidia_free(NULL);
return;
}
i = live_index(pointer);
if (i < 0) {
errors++;
return;
}
live[i].pointer = NULL;
live[i].bytes = 0;
free_calls++;
stela_nvidia_free(pointer);
}
void *stela_nvkms_model_zero(void *pointer, NvU8 value, size_t bytes)
{
int i = live_index(pointer);
if (i < 0 || value != 0 || live[i].bytes != bytes) {
errors++;
return pointer;
}
zero_calls++;
return nvkms_memset(pointer, value, bytes);
}
void stela_nvkms_observed_free(void *pointer, size_t size)
{
int i = live_index(pointer);
if (i < 0 || live[i].bytes != size)
errors++;
sized_frees++;
nvkms_free(pointer, size);
}
static NvU8 pattern(size_t index)
{
return (NvU8)(0x63 ^ (index * 13));
}
static int bytes_match(const NvU8 *pointer, size_t bytes)
{
size_t i;
for (i = 0; i < bytes; i++) {
if (pointer[i] != pattern(i))
return 0;
}
return 1;
}
int main(void)
{
const size_t sizes[] = {0, 1, 15, 16, 17, 4096, 4097, 65537};
const NvBool zero_flags[] = {0, 1, 2, 255};
const NvU32 statuses[] = {
STELA_NVIDIA_ALLOC_INVALID_SIZE, STELA_NVIDIA_ALLOC_OUT_OF_MEMORY,
};
unsigned int i, j, before_alloc, before_free, before_zero;
size_t k, before_live;
NvU8 *p, *q;
stela_nvkms_test_heap_initialize();
if (stela_nvkms_test_heap_live() != 0)
return 1;
for (i = 0; i < sizeof(zero_flags) / sizeof(zero_flags[0]); i++) {
for (j = 0; j < sizeof(sizes) / sizeof(sizes[0]); j++) {
before_zero = zero_calls;
p = nvkms_alloc(sizes[j], zero_flags[i]);
if (p == NULL || ((NvUPtr)p & 15) != 0 ||
zero_calls != before_zero + (zero_flags[i] != 0) ||
last_request != sizes[j])
return 2;
for (k = 0; k < sizes[j]; k++) {
if (zero_flags[i] != 0 && p[k] != 0)
return 3;
p[k] = pattern(k);
}
if (!bytes_match(p, sizes[j]))
return 4;
nvkms_free(p, sizes[j]);
}
}
for (i = 0; i < sizeof(statuses) / sizeof(statuses[0]); i++) {
deny_status = statuses[i];
for (j = 0; j < sizeof(zero_flags) / sizeof(zero_flags[0]); j++) {
before_zero = zero_calls;
before_free = free_calls;
before_alloc = allocation_calls;
p = nvkms_alloc(((NvU64)1 << 32) + 17, zero_flags[j]);
if (p != NULL || last_request != ((NvU64)1 << 32) + 17 ||
zero_calls != before_zero || free_calls != before_free ||
allocation_calls != before_alloc + 1)
return 5;
}
}
deny_status = 0;
before_zero = zero_calls;
p = nvInternalAlloc(63, TRUE);
if (p == NULL || sizeof(nvkms_memory_info_t) != 8 ||
offsetof(nvkms_memory_info_t, data) != 8 ||
((NvUPtr)p & 15) != 8 || last_request != 71 ||
zero_calls != before_zero + 1)
return 6;
for (k = 0; k < 63; k++) {
if (p[k] != 0)
return 7;
p[k] = pattern(k);
}
before_live = stela_nvkms_test_heap_live();
before_free = free_calls;
before_zero = zero_calls;
deny_status = STELA_NVIDIA_ALLOC_OUT_OF_MEMORY;
q = nvInternalRealloc(p, 101);
if (q != NULL || !bytes_match(p, 63) || free_calls != before_free ||
zero_calls != before_zero || last_request != 109 ||
stela_nvkms_test_heap_live() != before_live)
return 8;
deny_status = 0;
before_alloc = allocation_calls;
q = nvInternalRealloc(p, ~(size_t)0);
if (q != NULL || allocation_calls != before_alloc ||
free_calls != before_free || !bytes_match(p, 63))
return 9;
q = nvInternalRealloc(p, ((NvU64)1 << 63) - 1);
if (q != NULL || free_calls != before_free || !bytes_match(p, 63) ||
stela_nvkms_test_heap_live() != before_live)
return 10;
q = nvInternalRealloc(p, 101);
if (q == NULL || !bytes_match(q, 63) || free_calls != before_free + 1 ||
zero_calls != before_zero)
return 11;
for (k = 63; k < 101; k++)
q[k] = pattern(k);
p = nvInternalRealloc(q, 17);
if (p == NULL || !bytes_match(p, 17) || free_calls != before_free + 2)
return 12;
q = nvInternalRealloc(p, 0);
if (q != NULL || free_calls != before_free + 3)
return 13;
p = nvInternalRealloc(NULL, 0);
if (p == NULL || last_request != 8)
return 14;
nvInternalFree(p);
nvInternalFree(NULL);
nvkms_free(NULL, ~(size_t)0);
if (errors != 0 || live[0].pointer != NULL || live[1].pointer != NULL ||
null_frees != 1 || sized_frees != 4 ||
stela_nvkms_test_heap_live() != 0)
return 15;
return 0;
}
@@ -1,52 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Separate CPU-only process: link the actual production stela_nvlink_memory.c
* against this bounded denial provider, never into the driver. Real-success
* heap ownership is exercised by the Rust tests through the actual C hooks.
*/
#include <stddef.h>
#include "nvlink_os.h"
#include "stela_memory.h"
static NvU64 observed_size;
static NvU32 allocations;
static NvU32 frees;
static NvU32 denied_status;
static void *observed_free;
NvU32 stela_nvidia_alloc(NvU64 size, void **out)
{
allocations++;
observed_size = size;
*out = NULL;
return denied_status;
}
void stela_nvidia_free(void *pointer)
{
frees++;
observed_free = pointer;
}
int main(void)
{
const NvU64 sizes[] = {0, 1, 4096, ((NvU64)1 << 32) + 17, ~(NvU64)0};
const NvU32 statuses[] = {
STELA_NVIDIA_ALLOC_INVALID_SIZE,
STELA_NVIDIA_ALLOC_OUT_OF_MEMORY,
};
NvU32 i, j;
for (i = 0; i < sizeof(statuses) / sizeof(statuses[0]); i++) {
denied_status = statuses[i];
for (j = 0; j < sizeof(sizes) / sizeof(sizes[0]); j++) {
NvU32 before = allocations;
if (nvlink_malloc(sizes[j]) != NULL ||
allocations != before + 1 || observed_size != sizes[j] ||
frees != 0)
return 1;
}
}
nvlink_free(NULL);
if (frees != 1 || observed_free != NULL || allocations != 10)
return 2;
return 0;
}
@@ -1,109 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* CPU-only original-hook fixture. The optional renamed-provider object observes
* ABI forwarding without pretending a short buffer covers a huge byte range. */
#include "export_nvswitch.h"
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#ifdef NDEBUG
#error "NVSwitch primitive tests require active assertions"
#endif
_Static_assert(sizeof(NvLength) == 8, "native NVSwitch lengths remain 64-bit");
#ifdef STELA_NVSWITCH_FORWARD_TEST
static void *destination;
static const void *source;
static NvLength count;
static int byte_value;
static unsigned copy_calls, set_calls, length_calls;
void *stela_nvswitch_test_memcpy(void *dest, const void *src, size_t size);
void *stela_nvswitch_test_memset(void *dest, int value, size_t size);
size_t stela_nvswitch_test_strlen(const char *str);
void *stela_nvswitch_test_memcpy(void *dest, const void *src, size_t size)
{
assert(dest == destination && src == source && size == count);
copy_calls++;
return dest;
}
void *stela_nvswitch_test_memset(void *dest, int value, size_t size)
{
assert(dest == destination && value == byte_value && size == count);
set_calls++;
return dest;
}
size_t stela_nvswitch_test_strlen(const char *str)
{
assert(str == source);
length_calls++;
return count;
}
int main(void)
{
unsigned char actual_destination = 0xa5;
const unsigned char actual_source = 0x81;
destination = &actual_destination;
source = &actual_source;
const NvLength sizes[] = {0, 1, UINT64_C(0x100000001), UINT64_MAX};
const int values[] = {-1, 0, 0x180, INT32_MIN, INT32_MAX};
for (unsigned i = 0; i < sizeof(sizes) / sizeof(sizes[0]); i++)
{
count = sizes[i];
assert(nvswitch_os_memcpy(destination, source, count) == destination);
assert(nvswitch_os_strlen(source) == count);
for (unsigned v = 0; v < sizeof(values) / sizeof(values[0]); v++)
{
byte_value = values[v];
assert(nvswitch_os_memset(destination, byte_value, count) == destination);
}
}
assert(copy_calls == 4 && length_calls == 4 && set_calls == 20);
assert(actual_destination == 0xa5 && actual_source == 0x81);
puts("original NVSwitch wrappers preserve full-width scalar/provider forwarding");
return 0;
}
#else
int main(void)
{
unsigned char source[4096 + 32], destination[4096 + 32];
const NvLength sizes[] = {0, 1, 2, 7, 8, 15, 16, 31, 32, 127, 128, 129, 4096};
const int values[] = {-1, 0, 0x80, 0x180, INT32_MIN, INT32_MAX};
for (unsigned i = 0; i < sizeof(source); i++)
source[i] = (unsigned char)(i * 37 + 0x81);
for (unsigned s = 0; s < sizeof(sizes) / sizeof(sizes[0]); s++)
{
NvLength size = sizes[s];
for (unsigned offset = 0; offset < 16; offset++)
{
for (unsigned i = 0; i < sizeof(destination); i++)
destination[i] = 0xa5;
assert(nvswitch_os_memcpy(destination + offset, source + 15 - offset, size)
== destination + offset);
for (unsigned i = 0; i < sizeof(destination); i++)
assert(destination[i] == ((i >= offset && i - offset < size)
? (unsigned char)((i - offset + 15 - offset) * 37 + 0x81) : 0xa5));
for (unsigned v = 0; v < sizeof(values) / sizeof(values[0]); v++)
{
for (unsigned i = 0; i < sizeof(destination); i++)
destination[i] = 0xa5;
assert(nvswitch_os_memset(destination + offset, values[v], size)
== destination + offset);
for (unsigned i = 0; i < sizeof(destination); i++)
assert(destination[i] == ((i >= offset && i - offset < size)
? (unsigned char)values[v] : 0xa5));
}
for (unsigned i = 0; i < sizeof(destination); i++)
destination[i] = 0x80;
destination[offset + size] = 0;
assert(nvswitch_os_strlen((const char *)destination + offset) == size);
}
}
puts("original NVSwitch CPU primitives preserve bytes, returns and untouched spans");
return 0;
}
#endif
@@ -1,15 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later
* Compile/disassembly fixture only. This is not a CPU/GPU ordering litmus test.
* Include the actual adapter so the emitted probe exposes its compiler clobber
* and instruction between ordinary CPU stores, without calling hardware.
*/
#include "../stela_ordering.c"
void stela_nvidia_ordering_compile_probe(NvU32 *before, NvU32 *after);
void stela_nvidia_ordering_compile_probe(NvU32 *before, NvU32 *after)
{
*before = 0x12345678;
os_flush_cpu_write_combine_buffer();
*after = 0x76543210;
}
@@ -1,69 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Original global-data ABI plus unchanged original accessor bodies, linked in
* a fresh hosted process. No actual RAM/cache/physical support is attested. */
#include "../stela_page_geometry.h"
#include "page_geometry_accessors.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef NDEBUG
#error "page geometry tests require assertions"
#endif
static void unchanged(NvU64 base, NvU64 max, NvU64 mask, NvU8 shift)
{
assert(os_page_size == base && os_max_page_size == max &&
os_page_mask == mask && os_page_shift == shift);
}
int main(int argc, char **argv)
{
assert(argc == 3);
unsigned base_shift = (unsigned)strtoul(argv[1], NULL, 10);
unsigned max_shift = (unsigned)strtoul(argv[2], NULL, 10);
assert(base_shift >= 12 && base_shift <= max_shift && max_shift <= 62);
NvU64 base = 1ULL << base_shift, max = 1ULL << max_shift, mask = ~(base - 1);
unchanged(0, 0, 0, 0);
const struct { NvU64 base, max, mask; NvU8 shift; } bad[] = {
{0, 0, 0, 0}, {4096, 4096, ~4095ULL, 11},
{4096, 4096, ~4095ULL, 63}, {4096, 4096, ~4095ULL, 255},
{8192, 8192, ~8191ULL, 12}, {4096, 0, ~4095ULL, 12},
{8192, 4096, ~8191ULL, 13}, {4096, 6144, ~4095ULL, 12},
{4096, 1ULL << 63, ~4095ULL, 12}, {4096, ~0ULL, ~4095ULL, 12},
{4096, 4096, 0, 12},
};
for (unsigned i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) {
assert(stela_nvidia_set_page_geometry(bad[i].base, bad[i].max, bad[i].mask, bad[i].shift)
== NV_ERR_INVALID_ARGUMENT);
unchanged(0, 0, 0, 0);
}
if (base_shift != max_shift) {
assert(stela_nvidia_set_page_geometry(base, max, mask, (NvU8)base_shift)
== NV_ERR_NOT_SUPPORTED);
unchanged(0, 0, 0, 0);
printf("original RM broad page profile refused before publication: base%u max%u; CPU-only\n",
base_shift, max_shift);
return 0;
}
assert(stela_nvidia_set_page_geometry(base, max, mask, (NvU8)base_shift) == NV_OK);
unchanged(base, max, mask, (NvU8)base_shift);
assert(osGetPageSize() == base && osGetPageShift() == base_shift);
NvU64 supported = osGetSupportedSysmemPageSizeMask();
for (unsigned i = 0; i < 64; i++)
assert(!!(supported & (1ULL << i)) == (i >= base_shift && i <= max_shift));
assert(stela_nvidia_set_page_geometry(base, max, mask, (NvU8)base_shift) == NV_OK);
assert(stela_nvidia_set_page_geometry(4096, 16384, ~4095ULL, 12) == NV_ERR_NOT_SUPPORTED);
unchanged(base, max, mask, (NvU8)base_shift);
NvU64 other_base = base_shift == 12 ? 16384 : 4096;
NvU8 other_shift = base_shift == 12 ? 14 : 12;
assert(stela_nvidia_set_page_geometry(other_base, other_base, ~(other_base - 1), other_shift)
== NV_ERR_INVALID_STATE);
unchanged(base, max, mask, (NvU8)base_shift);
for (unsigned i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) {
assert(stela_nvidia_set_page_geometry(bad[i].base, bad[i].max, bad[i].mask, bad[i].shift)
== NV_ERR_INVALID_ARGUMENT);
unchanged(base, max, mask, (NvU8)base_shift);
}
printf("original RM page globals/accessors: base%u max%u, exact mask and atomic refusals; CPU-only\n",
base_shift, max_shift);
return 0;
}
@@ -1,182 +0,0 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Compile the actual vendor declarations under both the full-core target and
* Cargo's OS-hook target. Every active record/scalar measurement must match;
* ordinary long is reported separately and never relaxes a record comparison.
* Core builds use their genuine NvPort atomic/module defines; OS-hook builds
* also define NV_KERNEL_INTERFACE_LAYER, as the real adapter headers do.
* This fixture supplies constants only, no fake records or platform provider.
*/
#include <stddef.h>
#include "nv.h"
#include "stela_pci.h"
#include "libelf.h"
#define STELA_NVIDIA_RECORD_LAYOUT(M) \
M("sizeof(nv_state_t)", sizeof(nv_state_t)) \
M("alignof(nv_state_t)", _Alignof(nv_state_t)) \
M("sizeof(nv_pci_info_t)", sizeof(nv_pci_info_t)) \
M("alignof(nv_pci_info_t)", _Alignof(nv_pci_info_t)) \
M("sizeof(nv_aperture_t)", sizeof(nv_aperture_t)) \
M("alignof(nv_aperture_t)", _Alignof(nv_aperture_t)) \
M("sizeof(nv_cached_gpu_info_t)", sizeof(nv_cached_gpu_info_t)) \
M("alignof(nv_cached_gpu_info_t)", _Alignof(nv_cached_gpu_info_t)) \
M("sizeof(nv_phys_addr_range_t)", sizeof(nv_phys_addr_range_t)) \
M("alignof(nv_phys_addr_range_t)", _Alignof(nv_phys_addr_range_t)) \
M("sizeof(nv_soc_irq_info_t)", sizeof(nv_soc_irq_info_t)) \
M("alignof(nv_soc_irq_info_t)", _Alignof(nv_soc_irq_info_t)) \
M("sizeof(nv_event_t)", sizeof(nv_event_t)) \
M("alignof(nv_event_t)", _Alignof(nv_event_t)) \
M("sizeof(nv_kern_mapping_t)", sizeof(nv_kern_mapping_t)) \
M("alignof(nv_kern_mapping_t)", _Alignof(nv_kern_mapping_t)) \
M("sizeof(nv_usermap_access_params_t)", sizeof(nv_usermap_access_params_t)) \
M("alignof(nv_usermap_access_params_t)", _Alignof(nv_usermap_access_params_t)) \
M("sizeof(nv_alloc_mapping_context_t)", sizeof(nv_alloc_mapping_context_t)) \
M("alignof(nv_alloc_mapping_context_t)", _Alignof(nv_alloc_mapping_context_t)) \
M("sizeof(nv_alloc_mapping_list_node_t)", sizeof(nv_alloc_mapping_list_node_t)) \
M("alignof(nv_alloc_mapping_list_node_t)", _Alignof(nv_alloc_mapping_list_node_t)) \
M("sizeof(nvidia_stack_t)", sizeof(nvidia_stack_t)) \
M("alignof(nvidia_stack_t)", _Alignof(nvidia_stack_t)) \
M("sizeof(LibosElf64Header)", sizeof(LibosElf64Header)) \
M("alignof(LibosElf64Header)", _Alignof(LibosElf64Header)) \
M("sizeof(LibosElf64SectionHeader)", sizeof(LibosElf64SectionHeader)) \
M("alignof(LibosElf64SectionHeader)", _Alignof(LibosElf64SectionHeader)) \
M("sizeof(struct stela_nvidia_pci)", sizeof(struct stela_nvidia_pci)) \
M("alignof(struct stela_nvidia_pci)", _Alignof(struct stela_nvidia_pci)) \
M("sizeof(nv_firmware_type_t)", sizeof(nv_firmware_type_t)) \
M("alignof(nv_firmware_type_t)", _Alignof(nv_firmware_type_t)) \
M("sizeof(nv_firmware_chip_family_t)", sizeof(nv_firmware_chip_family_t)) \
M("alignof(nv_firmware_chip_family_t)", _Alignof(nv_firmware_chip_family_t)) \
M("sizeof(NvBool)", sizeof(NvBool)) \
M("alignof(NvBool)", _Alignof(NvBool)) \
M("sizeof(NvLength)", sizeof(NvLength)) \
M("alignof(NvLength)", _Alignof(NvLength)) \
M("sizeof(NvUPtr)", sizeof(NvUPtr)) \
M("alignof(NvUPtr)", _Alignof(NvUPtr)) \
M("sizeof(NV_STATUS)", sizeof(NV_STATUS)) \
M("alignof(NV_STATUS)", _Alignof(NV_STATUS)) \
M("sizeof(void *)", sizeof(void *)) \
M("alignof(void *)", _Alignof(void *)) \
M("offsetof(nv_state_t,priv)", offsetof(nv_state_t,priv)) \
M("offsetof(nv_state_t,os_state)", offsetof(nv_state_t,os_state)) \
M("offsetof(nv_state_t,flags)", offsetof(nv_state_t,flags)) \
M("offsetof(nv_state_t,pci_info)", offsetof(nv_state_t,pci_info)) \
M("offsetof(nv_state_t,subsystem_id)", offsetof(nv_state_t,subsystem_id)) \
M("offsetof(nv_state_t,subsystem_vendor)", offsetof(nv_state_t,subsystem_vendor)) \
M("offsetof(nv_state_t,gpu_id)", offsetof(nv_state_t,gpu_id)) \
M("offsetof(nv_state_t,iovaspace_id)", offsetof(nv_state_t,iovaspace_id)) \
M("offsetof(nv_state_t,nv_uuid_cache)", offsetof(nv_state_t,nv_uuid_cache)) \
M("offsetof(nv_state_t,handle)", offsetof(nv_state_t,handle)) \
M("offsetof(nv_state_t,pci_cfg_space)", offsetof(nv_state_t,pci_cfg_space)) \
M("offsetof(nv_state_t,bars)", offsetof(nv_state_t,bars)) \
M("offsetof(nv_state_t,regs)", offsetof(nv_state_t,regs)) \
M("offsetof(nv_state_t,dpaux)", offsetof(nv_state_t,dpaux)) \
M("offsetof(nv_state_t,hdacodec_regs)", offsetof(nv_state_t,hdacodec_regs)) \
M("offsetof(nv_state_t,mipical_regs)", offsetof(nv_state_t,mipical_regs)) \
M("offsetof(nv_state_t,fb)", offsetof(nv_state_t,fb)) \
M("offsetof(nv_state_t,ud)", offsetof(nv_state_t,ud)) \
M("offsetof(nv_state_t,simregs)", offsetof(nv_state_t,simregs)) \
M("offsetof(nv_state_t,num_dpaux_instance)", offsetof(nv_state_t,num_dpaux_instance)) \
M("offsetof(nv_state_t,interrupt_line)", offsetof(nv_state_t,interrupt_line)) \
M("offsetof(nv_state_t,dpaux_irqs)", offsetof(nv_state_t,dpaux_irqs)) \
M("offsetof(nv_state_t,dpaux_devname)", offsetof(nv_state_t,dpaux_devname)) \
M("offsetof(nv_state_t,soc_irq_info)", offsetof(nv_state_t,soc_irq_info)) \
M("offsetof(nv_state_t,current_soc_irq)", offsetof(nv_state_t,current_soc_irq)) \
M("offsetof(nv_state_t,num_soc_irqs)", offsetof(nv_state_t,num_soc_irqs)) \
M("offsetof(nv_state_t,hdacodec_irq)", offsetof(nv_state_t,hdacodec_irq)) \
M("offsetof(nv_state_t,tcpc2disp_irq)", offsetof(nv_state_t,tcpc2disp_irq)) \
M("offsetof(nv_state_t,soc_dcb_blob)", offsetof(nv_state_t,soc_dcb_blob)) \
M("offsetof(nv_state_t,soc_dcb_size)", offsetof(nv_state_t,soc_dcb_size)) \
M("offsetof(nv_state_t,disp_sw_soc_chip_id)", offsetof(nv_state_t,disp_sw_soc_chip_id)) \
M("offsetof(nv_state_t,soc_is_dpalt_mode_supported)", offsetof(nv_state_t,soc_is_dpalt_mode_supported)) \
M("offsetof(nv_state_t,soc_is_hfrp_supported)", offsetof(nv_state_t,soc_is_hfrp_supported)) \
M("offsetof(nv_state_t,soc_is_external_phy_supported)", offsetof(nv_state_t,soc_is_external_phy_supported)) \
M("offsetof(nv_state_t,dma_mask)", offsetof(nv_state_t,dma_mask)) \
M("offsetof(nv_state_t,is_tegra_pci_igpu)", offsetof(nv_state_t,is_tegra_pci_igpu)) \
M("offsetof(nv_state_t,supports_tegra_igpu_rg)", offsetof(nv_state_t,supports_tegra_igpu_rg)) \
M("offsetof(nv_state_t,is_tegra_pci_igpu_rg_enabled)", offsetof(nv_state_t,is_tegra_pci_igpu_rg_enabled)) \
M("offsetof(nv_state_t,tegra_pci_igpu_pg_mask)", offsetof(nv_state_t,tegra_pci_igpu_pg_mask)) \
M("offsetof(nv_state_t,gpc_fuse_status_offset)", offsetof(nv_state_t,gpc_fuse_status_offset)) \
M("offsetof(nv_state_t,primary_vga)", offsetof(nv_state_t,primary_vga)) \
M("offsetof(nv_state_t,sim_env)", offsetof(nv_state_t,sim_env)) \
M("offsetof(nv_state_t,rc_timer_enabled)", offsetof(nv_state_t,rc_timer_enabled)) \
M("offsetof(nv_state_t,event_list)", offsetof(nv_state_t,event_list)) \
M("offsetof(nv_state_t,event_spinlock)", offsetof(nv_state_t,event_spinlock)) \
M("offsetof(nv_state_t,kern_mappings)", offsetof(nv_state_t,kern_mappings)) \
M("offsetof(nv_state_t,dma_dev)", offsetof(nv_state_t,dma_dev)) \
M("offsetof(nv_state_t,niso_dma_dev)", offsetof(nv_state_t,niso_dma_dev)) \
M("offsetof(nv_state_t,queue)", offsetof(nv_state_t,queue)) \
M("offsetof(nv_state_t,request_firmware)", offsetof(nv_state_t,request_firmware)) \
M("offsetof(nv_state_t,request_fw_client_rm)", offsetof(nv_state_t,request_fw_client_rm)) \
M("offsetof(nv_state_t,allow_fallback_to_monolithic_rm)", offsetof(nv_state_t,allow_fallback_to_monolithic_rm)) \
M("offsetof(nv_state_t,enable_firmware_logs)", offsetof(nv_state_t,enable_firmware_logs)) \
M("offsetof(nv_state_t,removed)", offsetof(nv_state_t,removed)) \
M("offsetof(nv_state_t,console_device)", offsetof(nv_state_t,console_device)) \
M("offsetof(nv_state_t,is_external_gpu)", offsetof(nv_state_t,is_external_gpu)) \
M("offsetof(nv_state_t,preserve_vidmem_allocations)", offsetof(nv_state_t,preserve_vidmem_allocations)) \
M("offsetof(nv_state_t,force_dma32_alloc)", offsetof(nv_state_t,force_dma32_alloc)) \
M("offsetof(nv_state_t,d0_state_in_suspend)", offsetof(nv_state_t,d0_state_in_suspend)) \
M("offsetof(nv_state_t,profiler_owner)", offsetof(nv_state_t,profiler_owner)) \
M("offsetof(nv_state_t,profiler_context)", offsetof(nv_state_t,profiler_context)) \
M("offsetof(nv_state_t,rmapi)", offsetof(nv_state_t,rmapi)) \
M("offsetof(nv_state_t,dma_buf_supported)", offsetof(nv_state_t,dma_buf_supported)) \
M("offsetof(nv_state_t,is_shutdown)", offsetof(nv_state_t,is_shutdown)) \
M("offsetof(nv_state_t,coherent)", offsetof(nv_state_t,coherent)) \
M("offsetof(nv_state_t,mem_has_struct_page)", offsetof(nv_state_t,mem_has_struct_page)) \
M("offsetof(nv_state_t,coherent_gpu_mem_mode)", offsetof(nv_state_t,coherent_gpu_mem_mode)) \
M("offsetof(nv_state_t,ats_support)", offsetof(nv_state_t,ats_support)) \
M("offsetof(nv_state_t,cpu_numa_node_id)", offsetof(nv_state_t,cpu_numa_node_id)) \
M("offsetof(nv_state_t,iommus)", offsetof(nv_state_t,iommus)) \
M("offsetof(nv_state_t,clocks)", offsetof(nv_state_t,clocks)) \
M("offsetof(nv_state_t,client_managed_console)", offsetof(nv_state_t,client_managed_console)) \
M("offsetof(nv_state_t,sysmem_mapped_console)", offsetof(nv_state_t,sysmem_mapped_console)) \
M("offsetof(nv_state_t,cached_gpu_info)", offsetof(nv_state_t,cached_gpu_info)) \
M("offsetof(nv_state_t,is_pm_unsupported)", offsetof(nv_state_t,is_pm_unsupported)) \
M("offsetof(nv_state_t,is_cxl_dev)", offsetof(nv_state_t,is_cxl_dev)) \
M("offsetof(nv_state_t,cached_persistence_mode)", offsetof(nv_state_t,cached_persistence_mode)) \
M("offsetof(nv_state_t,nv_uuid_cache.valid)", offsetof(nv_state_t,nv_uuid_cache.valid)) \
M("offsetof(nv_state_t,nv_uuid_cache.uuid)", offsetof(nv_state_t,nv_uuid_cache.uuid)) \
M("offsetof(nv_state_t,nv_uuid_cache.pci_uuid_read_attempted)", offsetof(nv_state_t,nv_uuid_cache.pci_uuid_read_attempted)) \
M("offsetof(nv_state_t,nv_uuid_cache.pci_uuid_from_dvsec_pdi)", offsetof(nv_state_t,nv_uuid_cache.pci_uuid_from_dvsec_pdi)) \
M("offsetof(nv_state_t,nv_uuid_cache.pci_uuid_status)", offsetof(nv_state_t,nv_uuid_cache.pci_uuid_status)) \
M("offsetof(nv_state_t,pci_info.domain)", offsetof(nv_state_t,pci_info.domain)) \
M("offsetof(nv_state_t,pci_info.bus)", offsetof(nv_state_t,pci_info.bus)) \
M("offsetof(nv_state_t,pci_info.slot)", offsetof(nv_state_t,pci_info.slot)) \
M("offsetof(nv_state_t,pci_info.function)", offsetof(nv_state_t,pci_info.function)) \
M("offsetof(nv_state_t,rmapi.hClient)", offsetof(nv_state_t,rmapi.hClient)) \
M("offsetof(nv_state_t,iommus.iso_iommu_present)", offsetof(nv_state_t,iommus.iso_iommu_present)) \
M("offsetof(nv_state_t,iommus.dispIsoStreamId)", offsetof(nv_state_t,iommus.dispIsoStreamId)) \
M("offsetof(nv_state_t,clocks.max_dispclk_rate_using_disppllkhz)", offsetof(nv_state_t,clocks.max_dispclk_rate_using_disppllkhz)) \
M("offsetof(nv_pci_info_t,domain)", offsetof(nv_pci_info_t,domain)) \
M("offsetof(nv_pci_info_t,bus)", offsetof(nv_pci_info_t,bus)) \
M("offsetof(nv_pci_info_t,slot)", offsetof(nv_pci_info_t,slot)) \
M("offsetof(nv_pci_info_t,function)", offsetof(nv_pci_info_t,function)) \
M("offsetof(nv_pci_info_t,vendor_id)", offsetof(nv_pci_info_t,vendor_id)) \
M("offsetof(nv_pci_info_t,device_id)", offsetof(nv_pci_info_t,device_id)) \
M("offsetof(nv_aperture_t,cpu_address)", offsetof(nv_aperture_t,cpu_address)) \
M("offsetof(nv_aperture_t,size)", offsetof(nv_aperture_t,size)) \
M("offsetof(nv_aperture_t,offset)", offsetof(nv_aperture_t,offset)) \
M("offsetof(nv_aperture_t,map)", offsetof(nv_aperture_t,map)) \
M("offsetof(nv_aperture_t,map_u)", offsetof(nv_aperture_t,map_u)) \
M("offsetof(struct stela_nvidia_pci,context)", offsetof(struct stela_nvidia_pci,context)) \
M("offsetof(struct stela_nvidia_pci,read)", offsetof(struct stela_nvidia_pci,read)) \
M("offsetof(struct stela_nvidia_pci,write)", offsetof(struct stela_nvidia_pci,write))
#define STELA_LAYOUT_VALUE(label, expression) (expression),
const unsigned long long stela_nvidia_record_layout_values[] = {
STELA_NVIDIA_RECORD_LAYOUT(STELA_LAYOUT_VALUE)
};
#undef STELA_LAYOUT_VALUE
#define STELA_LAYOUT_LABEL(label, expression) (label),
const char *const stela_nvidia_record_layout_labels[] = {
STELA_NVIDIA_RECORD_LAYOUT(STELA_LAYOUT_LABEL)
};
#undef STELA_LAYOUT_LABEL
const unsigned long long stela_nvidia_record_layout_count =
sizeof(stela_nvidia_record_layout_values) / sizeof(stela_nvidia_record_layout_values[0]);
/* LP64 hosted tests do not exchange pointers/callers with the Win64 core.
* These two platform facts are deliberately outside the active-record vector.
*/
const unsigned long long stela_nvidia_platform_long[] = {sizeof(long), _Alignof(long)};
@@ -1,851 +0,0 @@
//! CPU-only original-C-ABI integration model; never maps hardware or a PA cast.
use std::{
cell::UnsafeCell,
ffi::c_void,
pin::Pin,
ptr::{self, NonNull},
sync::{
Arc, Barrier, Mutex,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
};
use stela_driver_base::bus::mmio::owned::{
AddressSpace, Authority, CacheAttribute, Error as MappingError, ExistingAlias,
InstalledMapping, MapFailure, MapRequest, MappingPlatform, PhysicalSpan, Protection, Resource,
ResourceBacking, ResourceKind,
};
use stela_driver_gpu::nvidia::mmio::{Error, MmioServices};
const PAGE: u64 = 4096;
const BASE: u64 = 0x800000;
const PREFETCH: u64 = 0x900000;
const PARTIAL: u64 = 0xa00000;
const SPACE: AddressSpace = AddressSpace {
identity: 31,
physical_bits: 48,
virtual_bits: 48,
};
unsafe extern "C" {
fn os_map_kernel_space(physical: u64, bytes: u64, mode: u32) -> *mut c_void;
fn os_unmap_kernel_space(address: *mut c_void, bytes: u64);
}
#[repr(align(4096))]
struct Pages([u8; 65536]);
struct Window(UnsafeCell<Pages>);
// SAFETY: model memory is accessed only as raw bytes while an exclusive mapping
// lease is live. Mutex-protected model bookkeeping does not create references
// to mapped bytes. The test drains all uses before acknowledged unmap.
unsafe impl Send for Window {}
// SAFETY: shared references rely on the same argument as `Send` above.
unsafe impl Sync for Window {}
struct Backing {
span: PhysicalSpan,
kind: ResourceKind,
window: Arc<Window>,
dropped: Arc<AtomicUsize>,
mapping: stela_driver_base::bus::mmio::owned::model::MappingRetention<(
Arc<Window>,
Arc<AtomicBool>,
)>,
}
fn mapping_context(
pin: &(Arc<Window>, Arc<AtomicBool>),
) -> Result<(), stela_driver_base::bus::pci::assignment::Error> {
if pin.1.load(Ordering::Acquire) {
Ok(())
} else {
Err(stela_driver_base::bus::pci::assignment::Error::Context)
}
}
// SAFETY: each immutable model reservation owns a distinct aligned allocation
// and isolated physical interval. There is no firmware, physical map or device.
unsafe impl ResourceBacking for Backing {
fn begin_mapping(
&self,
) -> Result<stela_driver_base::bus::pci::assignment::OpaqueUse, MappingError> {
self.mapping.begin_mapping()
}
fn physical_span(&self) -> PhysicalSpan {
self.span
}
fn kind(&self) -> ResourceKind {
self.kind
}
}
impl Drop for Backing {
fn drop(&mut self) {
self.dropped.fetch_add(1, Ordering::Relaxed);
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Mode {
Normal,
Unchanged,
Uncertain,
WrongCache,
RefuseWc,
}
struct Installed {
request: MapRequest,
cpu: usize,
window: Arc<Window>,
}
struct State {
installed: Vec<Installed>,
mode: Mode,
calls: usize,
unmaps: usize,
ack: bool,
busy_unmap: bool,
reenter: Option<(u64, usize, u64)>,
map_gates: Option<(Arc<Barrier>, Arc<Barrier>)>,
}
struct Model {
state: Mutex<State>,
allowed: Arc<AtomicBool>,
}
impl Model {
fn new() -> Arc<Self> {
Arc::new(Self {
state: Mutex::new(State {
installed: Vec::new(),
mode: Mode::Normal,
calls: 0,
unmaps: 0,
ack: true,
busy_unmap: false,
reenter: None,
map_gates: None,
}),
allowed: Arc::new(AtomicBool::new(true)),
})
}
fn calls(&self) -> (usize, usize, usize) {
let state = self.state.lock().unwrap();
(state.calls, state.unmaps, state.installed.len())
}
fn mode(&self, mode: Mode) {
self.state.lock().unwrap().mode = mode;
}
fn reenter(&self) {
let reenter = self.state.lock().unwrap().reenter.take();
if let Some((physical, address, bytes)) = reenter {
// SAFETY: model native callback reentry while the
// adapter's entry guard is held; neither nested call may act.
unsafe {
assert!(os_map_kernel_space(physical, bytes, 1).is_null());
os_unmap_kernel_space(address as *mut c_void, bytes);
}
}
}
}
// SAFETY: model maps kept allocations, never physical addresses as
// pointers. It preserves the request and exact aligned CPU range through ack.
// Fault modes return malformed/uncertain replies for refusal tests.
unsafe impl MappingPlatform for Model {
fn check_context(&self, space: AddressSpace) -> Result<(), MappingError> {
if space == SPACE && self.allowed.load(Ordering::Acquire) {
Ok(())
} else {
Err(MappingError::Unavailable)
}
}
unsafe fn map(
&self,
resource: &Resource,
request: MapRequest,
) -> Result<InstalledMapping, MapFailure> {
let backing = resource.backing().downcast_ref::<Backing>().unwrap();
assert_eq!(request.address_space, SPACE);
assert_eq!(request.physical.start() % PAGE, 0);
assert_eq!(request.physical.bytes() % PAGE, 0);
assert!(request.physical.start() >= backing.span.start());
assert!(request.physical.end() <= backing.span.end());
assert_eq!(request.protection, Protection::ReadWrite);
let (mode, gates) = {
let mut state = self.state.lock().unwrap();
state.calls += 1;
(state.mode, state.map_gates.take())
};
self.reenter();
if mode == Mode::Unchanged {
return Err(MapFailure::Unchanged(MappingError::MappingFailed));
}
if mode == Mode::RefuseWc && request.attribute == CacheAttribute::WriteCombining {
return Err(MapFailure::Unchanged(MappingError::UnsupportedCache));
}
let offset = (request.physical.start() - backing.span.start()) as usize;
// SAFETY: pinned model allocation, full request bounds checked
// against its immutable physical reservation; never derive VA from PA.
let cpu = unsafe {
ptr::addr_of_mut!((*backing.window.0.get()).0)
.cast::<u8>()
.add(offset)
};
let reply = InstalledMapping {
token: request.id,
cpu_base: NonNull::new(cpu).unwrap(),
physical: request.physical,
attribute: if mode == Mode::WrongCache {
CacheAttribute::WriteBack
} else {
request.attribute
},
protection: request.protection,
};
self.state.lock().unwrap().installed.push(Installed {
request,
cpu: cpu as usize,
window: Arc::clone(&backing.window),
});
if let Some((ready, release)) = gates {
ready.wait();
release.wait();
}
if mode == Mode::Uncertain {
return Err(MapFailure::Uncertain(MappingError::MappingFailed));
}
Ok(reply)
}
unsafe fn unmap(
&self,
request: MapRequest,
mapping: InstalledMapping,
) -> Result<(), MappingError> {
{
let mut state = self.state.lock().unwrap();
state.unmaps += 1;
let live = state
.installed
.iter()
.find(|live| live.request == request)
.unwrap();
assert_eq!(mapping.token, request.id);
assert_eq!(mapping.cpu_base.as_ptr() as usize, live.cpu);
assert_eq!(mapping.physical, request.physical);
assert_eq!(mapping.attribute, request.attribute);
assert_eq!(mapping.protection, request.protection);
assert!(Arc::strong_count(&live.window) >= 2);
}
self.reenter();
let mut state = self.state.lock().unwrap();
if state.busy_unmap {
return Err(MappingError::Busy);
}
if !state.ack {
return Err(MappingError::UnmapFailed);
}
let at = state
.installed
.iter()
.position(|live| live.request == request)
.unwrap();
state.installed.swap_remove(at);
Ok(()) // model all-root TLB/write drain acknowledgement
}
}
type MappingControl =
stela_driver_base::bus::mmio::owned::model::MappingOwner<(Arc<Window>, Arc<AtomicBool>)>;
fn resource(
start: u64,
bytes: u64,
kind: ResourceKind,
guard: &Arc<AtomicBool>,
) -> (Resource, Arc<AtomicUsize>, MappingControl) {
let dropped = Arc::new(AtomicUsize::new(0));
let window = Arc::new(Window(UnsafeCell::new(Pages([0; 65536]))));
// SAFETY: the SAME real allocated model RAM and original isolated guard;
// neither owns a Resource, Authority, Source or mapping/control callback.
let mapping = unsafe {
stela_driver_base::bus::mmio::owned::model::MappingOwner::from_owned(
(window.clone(), guard.clone()),
mapping_context,
)
};
(
Resource::new(Box::new(Backing {
span: PhysicalSpan::new(start, bytes).unwrap(),
kind,
window,
mapping: mapping.retention().unwrap(),
dropped: Arc::clone(&dropped),
})),
dropped,
mapping,
)
}
fn rejected(
services: &Pin<Box<MmioServices>>,
model: &Model,
physical: u64,
bytes: u64,
mode: u32,
expected: MappingError,
provider_called: bool,
) {
let before = services.status();
let calls = model.calls();
// SAFETY: installed service/model, serialized process-context call.
assert!(unsafe { os_map_kernel_space(physical, bytes, mode) }.is_null());
assert_eq!(services.status().live, before.live);
assert_eq!(services.status().failed_maps, before.failed_maps + 1);
assert_eq!(
services.status().last_failure,
Some(Error::Mapping(expected))
);
assert_eq!(model.calls().0, calls.0 + usize::from(provider_called));
}
#[test]
fn original_global_abi_keeps_real_canonical_leases_and_quarantines_failures() {
// Separate integration process preserves canonical production singleton.
// SAFETY: no installed services; hooks must refuse without a provider call.
unsafe {
assert!(os_map_kernel_space(BASE, PAGE, 1).is_null());
os_unmap_kernel_space(ptr::null_mut(), PAGE);
}
let model = Model::new();
// SAFETY: isolated CPU model machine, complete alias inventory, genuine
// backing and explicit all-root/cache/context acknowledgements.
let authority = unsafe {
Authority::activate(
model.clone(),
SPACE,
vec![
ExistingAlias {
physical: PhysicalSpan::new(BASE + 4 * PAGE, PAGE).unwrap(),
attribute: Some(CacheAttribute::WriteBack),
},
ExistingAlias {
physical: PhysicalSpan::new(BASE + 5 * PAGE, PAGE).unwrap(),
attribute: None,
},
ExistingAlias {
physical: PhysicalSpan::new(BASE + 6 * PAGE, PAGE).unwrap(),
attribute: Some(CacheAttribute::Uncached),
},
],
)
}
.unwrap();
let (registers, register_drop, mut register_control) =
resource(BASE, 16 * PAGE, ResourceKind::Registers, &model.allowed);
let register_id = authority.register_resource(registers.clone()).unwrap();
let (prefetch, prefetch_drop, mut prefetch_control) = resource(
PREFETCH,
16 * PAGE,
ResourceKind::PrefetchableMemory,
&model.allowed,
);
let prefetch_id = authority.register_resource(prefetch).unwrap();
let (partial, partial_drop, mut partial_control) = resource(
PARTIAL + 1,
PAGE - 2,
ResourceKind::Registers,
&model.allowed,
);
let partial_id = authority.register_resource(partial).unwrap();
let mut services = Box::pin(MmioServices::new(authority.clone()));
let mut second = Box::pin(MmioServices::new(authority.clone()));
// SAFETY: pinned services remain alive, serial callbacks in this one test;
// all raw consumers stop before exact unmap and successful uninstall.
unsafe {
services.as_mut().install().unwrap();
assert_eq!(second.as_mut().install(), Err(Error::AlreadyInstalled));
assert_eq!(second.as_mut().uninstall(), Err(Error::NotInstalled));
}
for (physical, bytes) in [(0, PAGE), (BASE, 0), (u64::MAX - 1, 4), (BASE, u64::MAX)] {
rejected(
&services,
&model,
physical,
bytes,
1,
MappingError::InvalidRange,
false,
);
}
for mode in [0, 3, 4, 5, 7, u32::MAX] {
rejected(
&services,
&model,
BASE,
PAGE,
mode,
MappingError::UnsupportedCache,
false,
);
}
for (physical, bytes) in [
(PARTIAL + 1, 1),
(BASE - 1, 2),
(BASE + 16 * PAGE - 1, 2),
(0xb00000, PAGE),
(BASE, (1u64 << 32) + PAGE),
] {
rejected(
&services,
&model,
physical,
bytes,
1,
MappingError::OutsideResource,
false,
);
}
for page in [4, 5] {
rejected(
&services,
&model,
BASE + page * PAGE + 1,
1,
1,
MappingError::CacheConflict,
false,
);
}
rejected(
&services,
&model,
BASE,
PAGE,
2,
MappingError::UnsupportedCache,
false,
);
model.allowed.store(false, Ordering::Release);
rejected(
&services,
&model,
BASE,
PAGE,
1,
MappingError::Unavailable,
false,
);
model.allowed.store(true, Ordering::Release);
// Unaligned logical bytes map only owned rounded pages, preserving offset.
// SAFETY: model storage remains mapped and exclusively raw-accessed.
let address = unsafe { os_map_kernel_space(BASE + 17, 100, 1) };
assert!(!address.is_null());
let actual = registers.backing().downcast_ref::<Backing>().unwrap();
assert_eq!(
address.cast::<u8>(),
actual.window.0.get().cast::<u8>().wrapping_add(17)
);
// SAFETY: the pointer addresses live memory this test's model owns, in bounds, and nothing
// accesses it concurrently.
unsafe {
address.cast::<u8>().write_volatile(0x19);
address.cast::<u8>().add(99).write_volatile(0xe7);
assert_eq!(address.cast::<u8>().read_volatile(), 0x19);
assert_eq!(address.cast::<u8>().add(99).read_volatile(), 0xe7);
}
assert_eq!(
model.state.lock().unwrap().installed[0].request.physical,
PhysicalSpan::new(BASE, PAGE).unwrap()
);
assert_eq!(services.status().live, 1);
assert_eq!(
// SAFETY: the model device is stopped and drained, so nothing still uses what this
// releases.
unsafe { services.as_mut().uninstall() },
Err(Error::LiveMappings)
);
rejected(
&services,
&model,
BASE + 1,
1,
1,
MappingError::ResourceConflict,
false,
);
let calls = model.calls();
for (pointer, bytes) in [
(address, 99),
(address.wrapping_byte_add(1), 100),
(ptr::null_mut(), 0),
] {
// SAFETY: invalid keys are never dereferenced or allowed to retire.
unsafe { os_unmap_kernel_space(pointer, bytes) };
assert_eq!(services.status().live, 1);
assert_eq!(services.status().last_failure, Some(Error::UnknownMapping));
assert_eq!(model.calls(), calls);
}
// Default is original UC, including a compatible imported raw UC alias.
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
let default = unsafe { os_map_kernel_space(BASE + 6 * PAGE, PAGE, 6) };
assert!(!default.is_null());
assert_eq!(
model.state.lock().unwrap().installed[1].request.attribute,
CacheAttribute::Uncached
);
model.state.lock().unwrap().reenter = Some((BASE + 2 * PAGE, address as usize, 100));
let refused = services.status().refused_calls;
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
let third = unsafe { os_map_kernel_space(BASE + PAGE, PAGE, 1) };
assert!(!third.is_null());
assert_eq!(services.status().refused_calls, refused + 2);
assert_eq!(services.status().live, 3);
model.state.lock().unwrap().reenter = Some((BASE + 2 * PAGE, address as usize, 100));
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(third, PAGE) };
assert_eq!(services.status().refused_calls, refused + 4);
assert_eq!(services.status().live, 2);
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe {
os_unmap_kernel_space(default, PAGE);
os_unmap_kernel_space(address, 100);
}
assert_eq!(model.calls().2, 0);
assert_eq!(services.status().live, 0);
let calls = model.calls();
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(address, 100) };
assert_eq!(services.status().last_failure, Some(Error::UnknownMapping));
assert_eq!(model.calls(), calls);
model.mode(Mode::RefuseWc);
rejected(
&services,
&model,
PREFETCH,
PAGE,
2,
MappingError::UnsupportedCache,
true,
);
model.mode(Mode::Normal);
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
let wc = unsafe { os_map_kernel_space(PREFETCH, PAGE, 2) };
assert!(!wc.is_null());
assert_eq!(
model.state.lock().unwrap().installed[0].request.attribute,
CacheAttribute::WriteCombining
);
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(wc, PAGE) };
model.mode(Mode::Unchanged);
rejected(
&services,
&model,
BASE + 7 * PAGE,
PAGE,
1,
MappingError::MappingFailed,
true,
);
assert_eq!(services.authority_status().unwrap().uncertain, 0);
model.mode(Mode::Normal);
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
let restored = unsafe { os_map_kernel_space(BASE + 7 * PAGE, PAGE, 1) };
assert!(!restored.is_null());
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(restored, PAGE) };
// A canonical independent view keeps its backing alive; NVIDIA gets
// no alternate permission, widened pointer or safe Rust reference to it.
let mut parent = authority
.map_physical(
PhysicalSpan::new(BASE + 8 * PAGE, PAGE).unwrap(),
CacheAttribute::Uncached,
Protection::ReadWrite,
)
.unwrap();
let view = parent.view(17..117).unwrap();
assert_eq!(view.bytes(), 100);
// SAFETY: the model device is stopped and drained, so nothing still uses what this releases.
assert_eq!(unsafe { parent.retire() }, Err(MappingError::Busy));
drop(view);
// SAFETY: the model device is stopped and drained, so nothing still uses what this releases.
unsafe { parent.retire() }.unwrap();
// Another real canonical consumer may have a platform map in flight.
// Original void unmap ends raw access now, keeping the same ledger slot
// and Mapping until the native owner reaches a true quiescent retry point.
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
let busy = unsafe { os_map_kernel_space(BASE + 12 * PAGE, PAGE, 1) };
assert!(!busy.is_null());
let ready = Arc::new(Barrier::new(2));
let release = Arc::new(Barrier::new(2));
model.state.lock().unwrap().map_gates = Some((ready.clone(), release.clone()));
let other_authority = authority.clone();
let other = std::thread::spawn(move || {
other_authority
.map_physical(
PhysicalSpan::new(PREFETCH + PAGE, PAGE).unwrap(),
CacheAttribute::Uncached,
Protection::ReadWrite,
)
.unwrap()
});
ready.wait();
let before = services.status();
let calls = model.calls();
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(busy, PAGE) };
assert_eq!(services.status().live, 0);
assert_eq!(services.status().pending, 1);
assert_eq!(
services.status().busy_retirements,
before.busy_retirements + 1
);
assert_eq!(services.status().failed_unmaps, before.failed_unmaps);
assert_eq!(
services.status().unmap_quarantines,
before.unmap_quarantines
);
assert_eq!(services.authority_status().unwrap().quarantined, 0);
assert_eq!(
// SAFETY: the model device is stopped and drained, so nothing still uses what this
// releases.
unsafe { services.as_mut().uninstall() },
Err(Error::LiveMappings)
);
for _ in 0..3 {
assert_eq!(
// SAFETY: the model device, its pages and its domain belong to this test alone; no
// other driver, worker or DMA touches them.
unsafe { services.as_mut().drain_pending_retirements() },
Err(Error::Mapping(MappingError::Busy))
);
assert_eq!(services.status().pending, 1);
assert_eq!(model.calls(), calls); // no native unmap or new mapping
}
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(busy, PAGE - 1) };
assert_eq!(services.status().last_failure, Some(Error::UnknownMapping));
assert_eq!(services.status().pending, 1);
assert_eq!(model.calls(), calls);
let before_duplicate = services.status();
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(busy, PAGE) };
assert_eq!(services.status().last_failure, Some(Error::UnknownMapping));
assert_eq!(services.status().pending, 1);
assert_eq!(
services.status().busy_retirements,
before_duplicate.busy_retirements
);
assert_eq!(
services.status().unmap_quarantines,
before_duplicate.unmap_quarantines
);
assert_eq!(model.calls(), calls); // consumed raw-use key cannot retry
release.wait();
let mut other = other.join().unwrap();
model.state.lock().unwrap().reenter = Some((BASE + 2 * PAGE, busy as usize, PAGE));
let refused = services.status().refused_calls;
assert_eq!(
// SAFETY: the model device, its pages and its domain belong to this test alone; no other
// driver, worker or DMA touches them.
unsafe { services.as_mut().drain_pending_retirements() },
Ok(1)
);
assert_eq!(services.status().refused_calls, refused + 2);
assert_eq!(services.status().pending, 0);
assert_eq!(services.authority_status().unwrap().quarantined, 0);
assert_eq!(model.calls().1, calls.1 + 1); // one acknowledged retire
// SAFETY: the model device is stopped and drained, so nothing still uses what this releases.
unsafe { other.retire() }.unwrap();
// Busy returned AFTER entering native unmap makes canonical state uncertain.
// Do not infer that Busy means unchanged: keep/block access and retry the
// exact token. The model verifies the same token/request on every attempt.
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
let busy = unsafe { os_map_kernel_space(BASE + 13 * PAGE, PAGE, 1) };
assert!(!busy.is_null());
let before = services.status();
let calls = model.calls();
model.state.lock().unwrap().busy_unmap = true;
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(busy, PAGE) };
assert_eq!(services.status().pending, 1);
assert_eq!(services.status().live, 0);
assert_eq!(services.authority_status().unwrap().uncertain, 1);
assert_eq!(services.authority_status().unwrap().quarantined, 0);
assert_eq!(model.calls().1, calls.1 + 1);
let duplicate_calls = model.calls();
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(busy, PAGE) };
assert_eq!(services.status().last_failure, Some(Error::UnknownMapping));
assert_eq!(services.status().pending, 1);
assert_eq!(services.authority_status().unwrap().uncertain, 1);
assert_eq!(model.calls(), duplicate_calls); // owner drain is sole retry seam
assert_eq!(
// SAFETY: the model device, its pages and its domain belong to this test alone; no other
// driver, worker or DMA touches them.
unsafe { services.as_mut().drain_pending_retirements() },
Err(Error::Mapping(MappingError::Busy))
);
assert_eq!(model.calls().1, calls.1 + 2);
assert_eq!(services.authority_status().unwrap().uncertain, 1);
rejected(
&services,
&model,
BASE + 13 * PAGE,
PAGE,
1,
MappingError::ResourceConflict,
false,
);
model.state.lock().unwrap().busy_unmap = false;
assert_eq!(
// SAFETY: the model device, its pages and its domain belong to this test alone; no other
// driver, worker or DMA touches them.
unsafe { services.as_mut().drain_pending_retirements() },
Ok(1)
);
assert_eq!(
services.status().busy_retirements,
before.busy_retirements + 2
);
assert_eq!(services.status().failed_unmaps, before.failed_unmaps + 1); // duplicate key only
assert_eq!(
services.status().unmap_quarantines,
before.unmap_quarantines
);
assert_eq!(services.status().pending, 0);
assert_eq!(services.authority_status().unwrap().uncertain, 0);
assert_eq!(model.calls().1, calls.1 + 3);
assert_eq!(
// SAFETY: the model device, its pages and its domain belong to this test alone; no other
// driver, worker or DMA touches them.
unsafe { services.as_mut().drain_pending_retirements() },
Ok(0)
);
// Failed retirement consumes the void native ABI into canonical
// quarantine. The provider's allocation/token and resource stay held.
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
let failed = unsafe { os_map_kernel_space(BASE + 9 * PAGE, PAGE, 1) };
assert!(!failed.is_null());
model.state.lock().unwrap().ack = false;
let before = services.status();
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(failed, PAGE) };
assert_eq!(services.status().live, 0);
assert_eq!(services.status().failed_unmaps, before.failed_unmaps + 1);
assert_eq!(
services.status().unmap_quarantines,
before.unmap_quarantines + 1
);
assert_eq!(
services.status().last_failure,
Some(Error::Mapping(MappingError::UnmapFailed))
);
assert_eq!(services.authority_status().unwrap().quarantined, 1);
assert_eq!(model.calls().2, 1);
assert_eq!(
authority.unregister_resource(register_id),
Err(MappingError::Busy)
);
let calls = model.calls();
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe { os_unmap_kernel_space(failed, PAGE) };
assert_eq!(model.calls(), calls); // no guessed retry/double unmap
model.state.lock().unwrap().ack = true;
rejected(
&services,
&model,
BASE + 9 * PAGE,
PAGE,
1,
MappingError::ResourceConflict,
false,
);
model.mode(Mode::Uncertain);
rejected(
&services,
&model,
BASE + 10 * PAGE,
PAGE,
1,
MappingError::MappingFailed,
true,
);
assert_eq!(services.authority_status().unwrap().quarantined, 2);
model.mode(Mode::WrongCache);
rejected(
&services,
&model,
BASE + 11 * PAGE,
PAGE,
1,
MappingError::InvalidPlatformReply,
true,
);
assert_eq!(services.authority_status().unwrap().quarantined, 3);
assert_eq!(model.calls().2, 3);
// SAFETY: the model device is stopped and drained, so nothing still uses what this releases.
unsafe { services.as_mut().uninstall() }.unwrap();
assert_eq!(
// SAFETY: the model device, its pages and its domain belong to this test alone; no other
// driver, worker or DMA touches them.
unsafe { services.as_mut().drain_pending_retirements() },
Err(Error::NotInstalled)
);
assert_eq!(
// SAFETY: the model device is stopped and drained, so nothing still uses what this
// releases.
unsafe { services.as_mut().uninstall() },
Err(Error::NotInstalled)
);
let calls = model.calls();
// SAFETY: the installed test services own the model BAR and refuse any address or length they
// did not map.
unsafe {
assert!(os_map_kernel_space(PREFETCH, PAGE, 1).is_null());
os_unmap_kernel_space(failed, PAGE);
}
assert_eq!(model.calls(), calls);
drop(services);
drop(registers);
assert_eq!(register_drop.load(Ordering::Relaxed), 0);
assert_eq!(
authority.unregister_resource(register_id),
Err(MappingError::Busy)
);
authority.unregister_resource(prefetch_id).unwrap();
authority.unregister_resource(partial_id).unwrap();
// SAFETY: these exact normal resources have no lookup, mapping/view or raw
// C tail after acknowledged unmaps and service uninstall above. Controllers
// stay outside their backings and return the same actual allocated Windows.
unsafe { prefetch_control.retire() }.unwrap();
// SAFETY: the partial resource never produced a pointer and lookup is gone.
unsafe { partial_control.retire() }.unwrap();
// The register resource still has real quarantined users. Deny admission
// only; default source-control abandonment keeps its same actual allocation.
register_control.abandon_admission();
assert_eq!(prefetch_drop.load(Ordering::Relaxed), 1);
assert_eq!(partial_drop.load(Ordering::Relaxed), 1);
assert_eq!(authority.status().unwrap().quarantined, 3);
assert_eq!(model.calls().2, 3);
}
-1
View File
@@ -18,7 +18,6 @@ workspace = true
native-acpi = ["stela-driver-base/native-acpi", "stela-driver-net/native-acpi"]
ram-disk = ["stela-driver-base/ram-disk"]
irq-diagnostics = ["stela-driver-base/irq-diagnostics"]
nvidia-port = ["stela-driver-gpu/nvidia-port"]
nouveau-port = ["stela-driver-gpu/nouveau-port"]
metal = ["stela-driver-gpu/metal"]
metal-vulkan = ["stela-driver-gpu/metal-vulkan"]
Submodule third_party/nvidia deleted from 1a82fbfda8.
-10
View File
@@ -1,10 +0,0 @@
# The resource-manager and display cores with their dependencies. The Linux
# module adapters are not used; Stela supplies its own platform port.
/*
!/.github/
!/kernel-open/
!/nouveau/
!/CODE_OF_CONDUCT.md
!/CONTRIBUTING.md
!/SECURITY.md
!/Makefile
-6
View File
@@ -32,15 +32,9 @@ sha1 = "0.10"
sha2.workspace = true
shlex = "2"
zip = { version = "4", default-features = false, features = ["deflate"] }
xz2 = { version = "0.1.7", features = ["static"] }
[build-dependencies]
object = { version = "0.37", features = ["read"] }
[features]
# The tests that read the NVIDIA hook layouts `cargo xtask gpu fetch` checks
# out; `cargo xtask check` turns it on.
fetched-sources = []
[lints]
workspace = true
+1 -6
View File
@@ -90,10 +90,7 @@ pub fn run(fix: bool, nvk: bool, low_memory: bool) -> Result<()> {
uefi(["-p", "stela-driver-net", "--features", "native-acpi"]),
uefi(["-p", "stela-driver-storage"]),
uefi(["-p", "stela-driver-audio"]),
// Native GPU hooks are optional while their larger vendor port is
// in progress, but their C/Rust ABI and UEFI target still belong to
// the gate.
uefi(["-p", "stela-driver-gpu", "--features", "nvidia-port"]),
uefi(["-p", "stela-driver-gpu"]),
uefi(["-p", "stela-drivers", "--features", "native-acpi"]),
];
if nvk {
@@ -141,8 +138,6 @@ pub fn run(fix: bool, nvk: bool, low_memory: bool) -> Result<()> {
.env("CC_aarch64_apple_darwin", "true")
.env("AR_aarch64_apple_darwin", "true");
boot_lane.push(release_host);
// `--all-features` includes xtask's `fetched-sources`, whose tests read
// the fetched sources.
let test = ["test", "--workspace", "--all-features", "--locked"];
let host_lane = vec![
{
+1 -11
View File
@@ -93,15 +93,6 @@ pub enum Command {
#[arg(long, num_args = 2, requires = "llvm_library", value_names = ["TRIANGLE", "TEXTURE"])]
render_inputs: Vec<PathBuf>,
},
/// Compile NVIDIA's resource-manager and display cores for native Stela
/// or as Linux reference objects, keeping unresolved platform imports.
Nvidia {
#[arg(long, value_enum, default_value_t = nvidia::Target::Stela)]
target: nvidia::Target,
/// Maximum parallel native compiler processes.
#[arg(long, default_value_t = 8, value_parser = clap::value_parser!(u16).range(1..))]
jobs: u16,
},
/// Compile NVK, NIR and NAK's C for `stela.efi` against Stela's C library,
/// and generate the sources of Mesa's Rust crates.
Nvk {
@@ -149,11 +140,10 @@ pub fn run(command: Command) -> Result<()> {
threadgroup_inputs: &threadgroup_inputs,
render_inputs: &render_inputs,
}),
Command::Nvidia { jobs, target } => nvidia::build(jobs, target),
// `stela.efi` carries the kext it links against each boot's kernel.
Command::Nvk { jobs } => build_nvk(jobs),
Command::MetalSuite(command) => metal_suite::run(command),
Command::Llvm { jobs, test } => llvm::build(&nvidia::Toolchain::discover()?, jobs, test),
Command::Llvm { jobs, test } => llvm::build(&toolchain::Toolchain::discover()?, jobs, test),
}
}
+1 -1
View File
@@ -9,11 +9,11 @@
//! [`SKIPPED`] cuts what would reach past those needs at its root, and
//! `compat/llvm` answers what is left of those units.
use super::{
nvidia::Toolchain,
nvk::{
LIBC, LIBC_TEST_FLAGS, TARGET_FLAGS, Unit, compile, gather_constructors, resource_directory,
},
support::{NATIVE_TARGET, build_directory, gpu, third_party},
toolchain::Toolchain,
};
use crate::tools::exec;
use anyhow::{Context, Result, ensure};
+1 -387
View File
@@ -1,387 +1 @@
//! Reproducible compilation of the vendor cores without installing Linux
//! modules. The unresolved symbol list is the platform port's work inventory.
use super::support::{
NATIVE_TARGET, build_directory, capture, evidence_directory, gpu, source_binding, third_party,
};
use crate::tools;
use anyhow::{Context, Result, bail, ensure};
use clap::ValueEnum;
use object::{Object, ObjectSymbol};
use serde_json::json;
use sha2::{Digest, Sha256};
use std::{
collections::BTreeSet,
fs::{self, File},
io::Write,
path::{Path, PathBuf},
process::{Command, Stdio},
};
use xz2::{
stream::{Check, Stream},
write::XzEncoder,
};
mod archive;
mod layout;
mod lut;
mod memory;
mod ordering;
mod page_geometry;
mod primitives;
#[derive(Clone, Copy, Debug, ValueEnum, PartialEq, Eq)]
pub enum Target {
Stela,
Linux,
}
impl Target {
fn profile(self) -> &'static str {
match self {
Self::Stela => "stela-x86_64-coff-v1",
Self::Linux => "linux-x86_64-clang-v1",
}
}
}
pub(super) struct Toolchain {
pub(super) clang: PathBuf,
pub(super) clangxx: PathBuf,
pub(super) linker: PathBuf,
objcopy: PathBuf,
pub(super) archiver: PathBuf,
}
impl Toolchain {
pub(super) fn discover() -> Result<Self> {
let rustc = tools::which("rustc").context("rustc is not in PATH")?;
let sysroot = capture(Command::new(&rustc).args(["--print", "sysroot"]))?;
let version = capture(Command::new(&rustc).arg("-vV"))?;
let host = version
.lines()
.find_map(|line| line.strip_prefix("host: "))
.context("rustc did not report its host target")?;
let directory = Path::new(sysroot.trim())
.join("lib/rustlib")
.join(host)
.join("bin");
let tool = |name: &str| directory.join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
let toolchain = Self {
clang: tools::which("clang").context("install Clang")?,
clangxx: tools::which("clang++").context("install Clang's C++ compiler")?,
linker: tool("gcc-ld/ld.lld"),
objcopy: tool("llvm-objcopy"),
archiver: tool("llvm-ar"),
};
for path in [&toolchain.linker, &toolchain.objcopy, &toolchain.archiver] {
ensure!(
path.is_file(),
"{} is missing; install llvm-tools-preview for the active Rust toolchain",
path.display()
);
}
Ok(toolchain)
}
}
fn compress_shader(data: &[u8]) -> Result<Vec<u8>> {
// Match the decoder's supported XZ profile: LZMA2 with no check field.
let stream = Stream::new_easy_encoder(6, Check::None)?;
let mut encoder = XzEncoder::new_stream(Vec::new(), stream);
encoder.write_all(data)?;
Ok(encoder.finish()?)
}
fn prepare_shaders(source: &Path, output: &Path) -> Result<()> {
for generation in ["turing", "ampere", "hopper", "blackwell", "gb20x"] {
let source = source.join(format!("src/shaders/g_{generation}_shaders"));
let destination = output.join(format!("{generation}_shaders.xz"));
let compressed = compress_shader(&fs::read(&source)?)?;
// Make owns embedding and linking; Rust supplies its compressed input.
// Always replace it before make so a stale source timestamp cannot
// suppress regeneration of the embedded shader object.
fs::write(destination, compressed)?;
}
Ok(())
}
fn inspect(path: &Path) -> Result<(u64, String, BTreeSet<String>)> {
let data = fs::read(path).with_context(|| format!("cannot read {}", path.display()))?;
let file = object::File::parse(&*data)?;
ensure!(
file.format() == object::BinaryFormat::Elf
&& file.architecture() == object::Architecture::X86_64
&& file.kind() == object::ObjectKind::Relocatable,
"{} is not an x86-64 ELF relocatable object",
path.display()
);
let imports = file
.symbols()
.filter(|symbol| symbol.is_undefined())
.map(|symbol| symbol.name().map(str::to_owned))
.collect::<Result<BTreeSet<_>, _>>()?;
let imports = imports
.into_iter()
.filter(|name| !name.is_empty())
.collect();
Ok((
data.len() as u64,
format!("{:x}", Sha256::digest(&data)),
imports,
))
}
/// NVIDIA's open modules (`third_party/nvidia`) and Stela's port of them
/// (`gpu/nvidia`), named together as one tree.
pub(super) struct Sources {
upstream: PathBuf,
port: PathBuf,
}
impl Sources {
pub(super) fn new() -> Self {
Self {
upstream: third_party("nvidia"),
port: gpu().join("nvidia"),
}
}
/// `port/...` is Stela's port; every other path is NVIDIA's.
pub(super) fn join(&self, path: &str) -> PathBuf {
if path == "port" {
self.port.clone()
} else if let Some(path) = path.strip_prefix("port/") {
self.port.join(path)
} else {
self.upstream.join(path)
}
}
/// Binds both trees as checked out.
fn binding(&self) -> Result<String> {
let identity = format!(
"{}\0{}",
source_binding(&self.upstream)?,
source_binding(&self.port)?
);
Ok(format!("{:x}", Sha256::digest(identity.as_bytes())))
}
}
/// NVIDIA's FreeBSD interface layer includes a few FreeBSD kernel headers;
/// Stela's stand-ins apply only where the compiler's own system has none.
fn freebsd_headers(command: &mut Command) {
command.arg("-idirafter").arg(gpu().join("compat/freebsd"));
}
pub fn build(jobs: u16, target: Target) -> Result<()> {
let toolchain = Toolchain::discover()?;
let source = Sources::new();
let source_hash = source.binding()?;
let compiler = capture(Command::new(&toolchain.clang).arg("--version"))?;
let compilerxx = capture(Command::new(&toolchain.clangxx).arg("--version"))?;
let linker = capture(Command::new(&toolchain.linker).arg("--version"))?;
let archiver = capture(Command::new(&toolchain.archiver).arg("--version"))?;
// The kept makefiles track header dependencies but not compiler or
// option changes. Partition their cache by the full source/tool identity.
let identity = format!(
"{source_hash}\0{compiler}\0{compilerxx}\0{linker}\0{archiver}\0{}",
target.profile()
);
let build_key = format!("{:x}", Sha256::digest(identity.as_bytes()));
let build = build_directory("nvidia")
.join(target.profile())
.join(&build_key);
// The kept makefiles do not support whitespace in paths. Do not
// silently split a compiler or output path into shell arguments.
for path in [
&source.upstream,
&source.port,
&build,
&toolchain.clang,
&toolchain.clangxx,
&toolchain.linker,
&toolchain.objcopy,
&toolchain.archiver,
] {
ensure!(
!path.to_string_lossy().chars().any(char::is_whitespace),
"the native NVIDIA makefiles require paths without whitespace: {}",
path.display()
);
}
let evidence = evidence_directory()?;
if target == Target::Stela {
layout::verify(&toolchain.clang, &source, &evidence.join("record-layout"))?;
lut::verify(&toolchain.clang, &source, &evidence.join("lut-layout"))?;
memory::verify(&toolchain.clang, &source, &evidence.join("nvkms-memory"))?;
primitives::verify(&toolchain.clang, &source, &evidence.join("cpu-primitives"))?;
page_geometry::verify(&toolchain.clang, &source, &evidence.join("page-geometry"))?;
ordering::verify(&toolchain.clang, &source, &evidence.join("ordering"))?;
}
for (component, subdirectory, reference_artifact) in [
("core", "src/nvidia", "nv-kernel.o"),
("modeset", "src/nvidia-modeset", "nv-modeset-kernel.o"),
] {
let output = build.join(component);
fs::create_dir_all(&output)?;
let source_directory = source.join(subdirectory);
let port = source.join("port");
if component == "modeset" {
prepare_shaders(&source_directory, &output)?;
}
let log_path = evidence.join(format!("{component}.log"));
let log = File::create(&log_path)?;
let mut command = Command::new(tools::which("make").context("install make")?);
command
.current_dir(&source_directory)
.arg(format!("-j{jobs}"))
.arg("TARGET_ARCH=x86_64")
.arg(format!("CC={}", toolchain.clang.display()))
.arg(format!("CXX={}", toolchain.clangxx.display()))
.arg(format!("LD={}", toolchain.linker.display()))
.arg(format!("OBJCOPY={}", toolchain.objcopy.display()))
.arg(format!("AR={}", toolchain.archiver.display()))
.arg("NV_BUILD_USER=stela")
.arg("NV_BUILD_HOST=native")
// NVIDIA's ID string runs $(DATE); name the source instead of the time.
.arg(format!("DATE=echo source-{source_hash}"))
.arg(format!("OUTPUTDIR={}", output.display()))
.arg(format!("OUTPUTDIR_ABSOLUTE={}", output.display()))
.arg(format!("STELA={}", port.display()))
.env_remove("MAKEFLAGS")
.env_remove("CFLAGS")
.env_remove("CXXFLAGS")
.env_remove("CPPFLAGS")
.env_remove("LDFLAGS")
.stdout(Stdio::from(log.try_clone()?))
.stderr(Stdio::from(log));
match target {
// NVIDIA's FreeBSD configuration is its Unix resource manager for
// an OS that supplies its own kernel interface layer, as Stela's
// port does. The fragment archives COFF objects for the UEFI link.
Target::Stela => command
.args(["-f", "Makefile", "-f"])
.arg(port.join("build").join(format!("{component}.mk")))
.args(["stela-archive", "TARGET_OS=FreeBSD"])
.arg(format!(
"EXTRA_CFLAGS=--target={NATIVE_TARGET} -mno-incremental-linker-compatible"
)),
Target::Linux => command.args([
"all",
"TARGET_OS=Linux",
"EXTRA_CFLAGS=--target=x86_64-unknown-linux-gnu",
]),
};
println!("NVIDIA {component}: {}", log_path.display());
let status = command
.status()
.with_context(|| format!("cannot execute {command:?}"))?;
if !status.success() {
bail!(
"NVIDIA {component} failed with {status}; see {}",
log_path.display()
);
}
let artifact = match (target, component) {
(Target::Stela, "core") => "libnv-kernel.a",
(Target::Stela, _) => "libnv-modeset-kernel.a",
(Target::Linux, _) => reference_artifact,
};
let path = output.join(artifact);
let (bytes, sha256, imports, members) = match target {
Target::Linux => {
let (bytes, sha256, imports) = inspect(&path)?;
(bytes, sha256, imports, None)
}
Target::Stela => {
let report =
archive::inspect(&path, &source_directory.join("exports_link_command.txt"))?;
(
report.bytes,
report.sha256,
report.imports,
Some(report.members),
)
}
};
ensure!(
source.binding()? == source_hash,
"NVIDIA source changed during the build; rerun against a stable tree"
);
let receipt = json!({
"schema": 1,
"stage": match target {
Target::Stela => "stela-coff-archive-compilation-only",
Target::Linux => "linux-elf-core-compilation-only",
},
"stela_platform_port": false, "hardware_executed": false,
"limits": "Core compilation only; not a complete OS-service port, final linked driver, GPU initialization or Metal execution. Archive imports conservatively include every retained member, before reachability analysis.",
"origin": super::fetch::origins()?,
"source_tree_sha256": source_hash,
"command": format!("{command:?}"),
"compiler": compiler, "compilerxx": compilerxx, "linker": linker, "archiver": archiver,
"build_key": build_key,
"artifact": {"path": path, "bytes": bytes, "sha256": sha256, "members": members},
"unresolved_symbols": imports,
});
let receipt_path = evidence.join(format!("{component}.json"));
File::create_new(&receipt_path)?.write_all(&serde_json::to_vec_pretty(&receipt)?)?;
println!(
" {artifact}: {bytes} bytes, {} unresolved platform/runtime imports",
imports.len()
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
#[test]
fn display_shader_compression_uses_the_supported_xz_profile() {
let input: Vec<_> = (0..8192).map(|n| (n % 251) as u8).collect();
let encoded = compress_shader(&input).unwrap();
assert_eq!(&encoded[..6], b"\xfd7zXZ\0");
assert_eq!(encoded[7], 0, "the driver decoder requires no check field");
let mut decoded = Vec::new();
xz2::read::XzDecoder::new(&*encoded)
.read_to_end(&mut decoded)
.unwrap();
assert_eq!(decoded, input);
}
#[cfg_attr(not(feature = "fetched-sources"), ignore = "feature: fetched-sources")]
#[test]
fn vendor_types_preserve_flags_and_host_addresses_on_both_abis() {
let tools = Toolchain::discover().unwrap();
let source = Sources::new();
for (target, os) in [
(NATIVE_TARGET, "-DNV_BSD"),
("x86_64-unknown-linux-gnu", "-DNV_LINUX"),
] {
for (compiler, fixture, standard) in [
(&tools.clangxx, "abi.cpp", "-std=c++20"),
(&tools.clang, "abi.c", "-std=c11"),
] {
let mut command = Command::new(compiler);
command
.args(["-target", target, os, "-ffreestanding"])
.args([standard, "-fsyntax-only", "-Werror"])
.args(["-Wno-missing-field-initializers"])
.arg(source.join("port/tests").join(fixture));
for include in [
"src/common/sdk/nvidia/inc",
"src/nvidia/inc/kernel",
"src/nvidia/arch/nvalloc/unix/include",
] {
command.arg("-I").arg(source.join(include));
}
freebsd_headers(&mut command);
capture(&mut command).unwrap();
}
}
}
}
pub(super) use super::toolchain::Toolchain;
-181
View File
@@ -1,181 +0,0 @@
//! Inspect every member rather than trust the archive's filename or first object.
use anyhow::{Context, Result, ensure};
use object::{Object, ObjectSymbol, read::archive::ArchiveFile};
use sha2::{Digest, Sha256};
use std::{collections::BTreeSet, fs, path::Path};
#[derive(Debug)]
pub struct Report {
pub bytes: u64,
pub sha256: String,
pub members: usize,
pub imports: BTreeSet<String>,
}
pub fn inspect(path: &Path, exports: &Path) -> Result<Report> {
let data = fs::read(path)?;
let archive = ArchiveFile::parse(data.as_slice())?;
let mut definitions = BTreeSet::new();
let mut imports = BTreeSet::new();
let mut members = 0;
for member in archive.members() {
let member = member?;
let bytes = member.data(data.as_slice())?;
let file = object::File::parse(bytes).with_context(|| {
format!("invalid object in {}: {:?}", path.display(), member.name())
})?;
ensure!(
file.format() == object::BinaryFormat::Coff
&& file.architecture() == object::Architecture::X86_64
&& file.kind() == object::ObjectKind::Relocatable,
"{} contains a non-x86-64 COFF member: {:?}",
path.display(),
member.name()
);
let stamp = match &file {
object::File::Coff(coff) => {
coff.coff_header().time_date_stamp.get(object::LittleEndian)
}
object::File::CoffBig(coff) => {
coff.coff_header().time_date_stamp.get(object::LittleEndian)
}
_ => unreachable!("COFF format checked above"),
};
ensure!(
stamp == 0,
"{} contains a timestamped COFF member: {:?}",
path.display(),
member.name()
);
members += 1;
for symbol in file.symbols() {
let name = symbol.name()?;
if name.is_empty() {
continue;
}
if symbol.is_undefined() {
imports.insert(name.to_owned());
} else if symbol.is_global() {
definitions.insert(name.to_owned());
}
}
}
ensure!(members > 0, "{} is empty", path.display());
let export_list = fs::read_to_string(exports)?;
for symbol in export_list.split_whitespace() {
let name = symbol
.strip_prefix("--undefined=")
.context("unexpected NVIDIA export-list syntax")?;
ensure!(definitions.contains(name), "missing vendor export: {name}");
}
if path.file_name().and_then(|name| name.to_str()) == Some("libnv-kernel.a") {
for width in ["byte", "word", "dword"] {
for operation in ["read", "write"] {
let name = format!("os_pci_{operation}_{width}");
ensure!(
definitions.contains(&name),
"missing native PCI hook {name}"
);
}
}
}
imports.retain(|name| !definitions.contains(name));
Ok(Report {
bytes: data.len() as u64,
sha256: format!("{:x}", Sha256::digest(&data)),
members,
imports,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gpu::{nvidia::Toolchain, support::capture};
use std::process::Command;
fn fixture(mixed: bool) -> (tempfile::TempDir, std::path::PathBuf, std::path::PathBuf) {
let tools = Toolchain::discover().unwrap();
let directory = tempfile::tempdir().unwrap();
let sources = [
"extern int helper(void); extern int platform(void); int entry(void) { return helper() + platform(); }",
"int helper(void) { return 7; }",
];
let mut objects = Vec::new();
for (index, text) in sources.into_iter().enumerate() {
let source = directory.path().join(format!("part{index}.c"));
let output = source.with_extension("o");
fs::write(&source, text).unwrap();
let target = if mixed && index == 1 {
"x86_64-unknown-linux-gnu"
} else {
crate::gpu::support::NATIVE_TARGET
};
capture(
Command::new(&tools.clang)
.arg(format!("--target={target}"))
.args(["-ffreestanding", "-mno-incremental-linker-compatible", "-c"])
.arg(&source)
.arg("-o")
.arg(&output),
)
.unwrap();
objects.push(output);
}
let archive = directory.path().join("fixture.a");
capture(
Command::new(tools.archiver)
.arg("rcs")
.arg(&archive)
.args(objects),
)
.unwrap();
let exports = directory.path().join("exports.txt");
fs::write(&exports, "--undefined=entry").unwrap();
(directory, archive, exports)
}
#[test]
fn archive_inventory_resolves_members_and_exports() {
let (_directory, archive, exports) = fixture(false);
let report = inspect(&archive, &exports).unwrap();
assert_eq!(report.members, 2);
assert_eq!(report.imports, BTreeSet::from(["platform".into()]));
fs::write(&exports, "--undefined=absent").unwrap();
assert!(
inspect(&archive, &exports)
.unwrap_err()
.to_string()
.contains("absent")
);
}
#[test]
fn archive_inventory_rejects_a_foreign_object_after_a_valid_member() {
let (_directory, archive, exports) = fixture(true);
assert!(
inspect(&archive, &exports)
.unwrap_err()
.to_string()
.contains("non-x86-64 COFF")
);
}
#[test]
fn archive_inventory_rejects_nondeterministic_object_timestamps() {
let (_directory, archive, exports) = fixture(false);
let mut data = fs::read(&archive).unwrap();
let parsed = ArchiveFile::parse(data.as_slice()).unwrap();
let (offset, _) = parsed.members().next().unwrap().unwrap().file_range();
// IMAGE_FILE_HEADER.TimeDateStamp follows the two 16-bit fields.
let offset = usize::try_from(offset).unwrap() + 4;
data[offset..offset + 4].copy_from_slice(&1_u32.to_le_bytes());
fs::write(&archive, data).unwrap();
assert!(
inspect(&archive, &exports)
.unwrap_err()
.to_string()
.contains("timestamped")
);
}
}
-152
View File
@@ -1,152 +0,0 @@
//! Compare compiled vendor records across the core and OS-hook ABIs.
use super::{NATIVE_TARGET, Sources, capture, tools};
use anyhow::{Context, Result, ensure};
use object::{Architecture, Object, ObjectSection, ObjectSymbol};
use serde_json::json;
use std::{fs, path::Path, process::Command};
pub(super) fn constants(object: &object::File<'_>, name: &str, count: usize) -> Result<Vec<u64>> {
let symbol = object
.symbols()
.find(|s| {
s.name()
.is_ok_and(|n| n == name || n.strip_prefix('_') == Some(name))
})
.with_context(|| format!("missing compiled layout symbol {name}"))?;
let section =
object.section_by_index(symbol.section_index().context("layout has no section")?)?;
let bytes = section
.data_range(
symbol.address(),
u64::try_from(count.checked_mul(8).context("layout size overflow")?)?,
)?
.context("truncated compiled layout array")?;
Ok(bytes
.as_chunks::<8>()
.0
.iter()
.map(|bytes| u64::from_le_bytes(*bytes))
.collect())
}
pub(super) fn verify(clang: &Path, source: &Sources, output: &Path) -> Result<()> {
fs::create_dir_all(output)?;
let fixture = source.join("port/tests/record_layout.c");
let text = fs::read_to_string(&fixture)?;
let labels: Vec<_> = text
.lines()
.filter_map(|line| {
line.trim()
.strip_prefix("M(\"")
.and_then(|rest| rest.split_once('"'))
.map(|(label, _)| label)
})
.collect();
ensure!(!labels.is_empty(), "empty NVIDIA record fixture");
let makefile = fs::read_to_string(source.join("src/nvidia/Makefile"))?;
let core_defines: Vec<_> = makefile
.lines()
.filter_map(|line| line.strip_prefix("CFLAGS += -DPORT_"))
.map(|suffix| format!("-DPORT_{suffix}"))
.collect();
ensure!(
!core_defines.is_empty()
&& core_defines
.iter()
.all(|s| !s.chars().any(char::is_whitespace)),
"unrecognized core NvPort definitions"
);
let mut baseline = None;
let mut profiles = Vec::new();
for (profile, target, kernel_interface) in [
("core", NATIVE_TARGET, false),
("shim", NATIVE_TARGET, true),
("shim-host-darwin", "x86_64-apple-macosx", true),
] {
let artifact = output.join(format!("{profile}.o"));
let mut command = Command::new(clang);
command.args([
"-target",
target,
"-DNV_BSD",
"-DNVRM",
"-ffreestanding",
"-fno-stack-protector",
"-mno-red-zone",
"-mgeneral-regs-only",
"-std=gnu11",
"-Werror",
]);
if kernel_interface {
command.arg("-DNV_KERNEL_INTERFACE_LAYER");
} else {
command.args(&core_defines);
}
for include in [
"port",
"src/common/sdk/nvidia/inc",
"src/nvidia/arch/nvalloc/unix/include",
"src/nvidia/arch/nvalloc/common/inc",
"src/nvidia/inc/kernel",
"src/nvidia/inc/libraries",
"src/common/inc",
"src/common/uproc/os/common/include",
] {
command.arg("-I").arg(source.join(include));
}
super::freebsd_headers(&mut command);
command.arg("-c").arg(&fixture).arg("-o").arg(&artifact);
capture(&mut command)?;
let bytes = fs::read(&artifact)?;
let object = object::File::parse(bytes.as_slice())?;
ensure!(
object.architecture() == Architecture::X86_64 && object.is_little_endian(),
"wrong layout target"
);
let count = constants(&object, "stela_nvidia_record_layout_count", 1)?[0];
ensure!(count == labels.len() as u64, "layout label/count mismatch");
let values = constants(&object, "stela_nvidia_record_layout_values", labels.len())?;
if let Some(base) = &baseline {
for ((label, expected), actual) in labels.iter().zip(base).zip(&values) {
ensure!(
expected == actual,
"{profile}: {label}: core={expected}, actual={actual}"
);
}
} else {
baseline = Some(values.clone());
}
let platform_long = constants(&object, "stela_nvidia_platform_long", 2)?;
ensure!(
platform_long == [8, 8],
"{profile} is not LP64, as NVIDIA's Unix resource manager assumes"
);
profiles.push(
json!({"profile":profile,"target":target,"command":format!("{command:?}"),
"artifact":tools::binding(&artifact)?,"values":values,"platform_long":platform_long}),
);
}
fs::write(
output.join("receipt.json"),
serde_json::to_vec_pretty(&json!({
"schema":1,"scope":"Exact compiled record compatibility; no execution or full driver link",
"fixture":tools::binding(&fixture)?,"makefile":tools::binding(&source.join("src/nvidia/Makefile"))?,
"task":tools::binding(&tools::root().join(file!()))?,
"labels":labels,"core_defines":core_defines,"profiles":profiles
}))?,
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg_attr(not(feature = "fetched-sources"), ignore = "feature: fetched-sources")]
#[test]
fn core_and_os_hook_layouts_match_across_abis() {
let compiler = tools::which("clang").unwrap();
let source = Sources::new();
let directory = tempfile::tempdir().unwrap();
verify(&compiler, &source, directory.path()).unwrap();
}
}
-252
View File
@@ -1,252 +0,0 @@
//! NVKMS types and upstream CPU upload over the common heap.
use super::{NATIVE_TARGET, Sources, capture, layout, tools};
use anyhow::{Context, Result, ensure};
use object::{Architecture, Object};
use serde_json::json;
use std::{fs, path::Path, process::Command};
pub(super) struct Flags {
pub(super) common: Vec<String>,
pub(super) c: Vec<String>,
cxx: Vec<String>,
}
pub(super) fn flags(clang: &Path, source: &Sources, output: &Path) -> Result<Flags> {
let makefile = output.join("flags.mk");
// Let the Makefile and its ordinary shell expand each argument.
// No second flag parser or copied vendor build configuration is needed.
fs::write(
&makefile,
".PHONY: stela-lut-flags\nstela-lut-flags:\n\t@printf '%s\\n' STELA_COMMON $(CFLAGS) STELA_C $(CC_ONLY_CFLAGS) STELA_CXX $(CXX_ONLY_CFLAGS)\n",
)?;
let mut make = Command::new(tools::which("make").context("install make")?);
make.current_dir(source.join("src/nvidia-modeset"))
.args(["-s", "-f", "Makefile", "-f"])
.arg(makefile)
.args(["stela-lut-flags", "TARGET_OS=FreeBSD", "TARGET_ARCH=x86_64"])
.arg(format!("CC={}", clang.display()))
.arg(format!("OUTPUTDIR={}", output.join("flags").display()))
.arg(format!(
"OUTPUTDIR_ABSOLUTE={}",
output.join("flags").display()
));
for name in ["CFLAGS", "CXXFLAGS", "CPPFLAGS", "LDFLAGS", "MAKEFLAGS"] {
make.env_remove(name);
}
let text = capture(&mut make)?;
let mut sections: [Vec<String>; 3] = Default::default();
let mut section = None;
for line in text.lines() {
match line {
"STELA_COMMON" => section = Some(0),
"STELA_C" => section = Some(1),
"STELA_CXX" => section = Some(2),
_ => sections[section.context("unexpected Make flag output")?].push(line.to_owned()),
}
}
let [mut common, c, cxx] = sections;
ensure!(
section == Some(2) && !common.is_empty() && !c.is_empty() && !cxx.is_empty(),
"incomplete NVKMS flags"
);
// Only the probe's object format changes. Full production builds keep
// their original machine-model and external return-thunk options.
common.retain(|flag| !flag.starts_with("--target="));
Ok(Flags { common, c, cxx })
}
pub(super) fn verify(clang: &Path, source: &Sources, output: &Path) -> Result<()> {
fs::create_dir_all(output)?;
let flags = flags(clang, source, output)?;
let fixture = source.join("port/tests/lut_layout.c");
let mut profiles = Vec::new();
for (profile, target, linux) in [
("native", NATIVE_TARGET, false),
("host-darwin", "x86_64-apple-macosx", false),
("linux", "x86_64-unknown-linux-gnu", true),
] {
for (language, suffix) in [("c", &flags.c), ("c++", &flags.cxx)] {
let artifact = output.join(format!("{profile}-{language}.o"));
let mut command = Command::new(clang);
command.current_dir(source.join("src/nvidia-modeset"));
for flag in &flags.common {
command.arg(if linux && flag == "-DNV_BSD" {
"-DNV_LINUX"
} else {
flag
});
}
command
.args(suffix)
.arg(format!("--target={target}"))
.args(["-x", language, "-c"])
.arg(&fixture)
.arg("-o")
.arg(&artifact);
capture(&mut command)?;
let bytes = fs::read(&artifact)?;
let object = object::File::parse(bytes.as_slice())?;
ensure!(
object.architecture() == Architecture::X86_64 && object.is_little_endian(),
"wrong LUT object ABI"
);
let count = layout::constants(&object, "stela_nvkms_lut_layout_count", 1)?;
ensure!(count == [8], "changed LUT fixture inventory");
let values = layout::constants(&object, "stela_nvkms_lut_layout", 8)?;
ensure!(
values == [8, 2, 16896, 256, 0, 8448, 8232, 8232],
"changed LUT byte layout or CPU alignment"
);
profiles.push(json!({"profile":profile,"target":target,"language":language,
"command":format!("{command:?}"),"artifact":tools::binding(&artifact)?,"values":values}));
}
}
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
let cpu = Some(cpu_model(CpuModelOptions {
clang,
source,
output,
flags: &flags,
sources: &[
("port/tests/lut_access.c", &[]),
("src/nvidia-modeset/src/nvkms-lut.c", &[]),
("port/stela_nvkms_primitives.c", &[]),
],
})?);
#[cfg(not(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux"))))]
let cpu: Option<serde_json::Value> = None;
fs::write(
output.join("receipt.json"),
serde_json::to_vec_pretty(&json!({
"scope":"Actual C/C++ object layouts and separate hosted common-heap/original-upload fixture; no production context qualification or GPU execution",
"task":tools::binding(&tools::root().join(file!()))?,"fixture":tools::binding(&fixture)?,
"header":tools::binding(&source.join("src/nvidia-modeset/include/nvkms-types.h"))?,
"makefile":tools::binding(&source.join("src/nvidia-modeset/Makefile"))?,
"common_flags":flags.common,"c_flags":flags.c,"cxx_flags":flags.cxx,
"profiles":profiles,"hosted_CPU_access":cpu,
}))?,
)?;
Ok(())
}
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
/// Vendor CPU fixture sources, compiler flags and output location.
pub(super) struct CpuModelOptions<'a> {
pub(super) clang: &'a Path,
pub(super) source: &'a Sources,
pub(super) output: &'a Path,
pub(super) flags: &'a Flags,
pub(super) sources: &'a [(&'a str, &'a [&'a str])],
}
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
pub(super) fn cpu_model(options: CpuModelOptions<'_>) -> Result<serde_json::Value> {
let CpuModelOptions {
clang,
source,
output,
flags,
sources,
} = options;
// This executable models ordinary host OS-hook calls. These full-core
// options belong to the separately built kernel archives, not this process.
let excluded = [
"-mfunction-return=thunk-extern",
"-mcmodel=kernel",
"-fno-pic",
"-msoft-float",
"-mno-mmx",
"-mno-sse",
"-mno-sse2",
"-mno-3dnow",
];
let mut objects = Vec::new();
let mut commands = Vec::new();
for (index, (file, extra)) in sources.iter().enumerate() {
let artifact = output.join(format!("cpu-{index}.o"));
let mut command = Command::new(clang);
command
.current_dir(source.join("src/nvidia-modeset"))
.args(
flags
.common
.iter()
.filter(|f| !excluded.contains(&f.as_str())),
)
.args(&flags.c)
.args([
"-mgeneral-regs-only",
"-ffunction-sections",
"-fdata-sections",
"-fno-inline",
"-I",
])
.arg(source.join("port"))
.arg("-idirafter")
.arg(super::gpu().join("compat/freebsd"))
// The fixtures include the original NVKMS sources they model.
.arg("-iquote")
.arg(source.join("src/nvidia-modeset/src"))
.args(*extra)
.arg("-c")
.arg(source.join(file))
.arg("-o")
.arg(&artifact);
capture(&mut command)?;
commands.push(format!("{command:?}"));
objects.push(artifact);
}
let heap = output.join("libactual-heap.a");
let mut rust = Command::new(tools::which("rustc").context("install rustc")?);
rust.args([
"--edition=2024",
"--crate-name=stela_nvkms_lut_heap",
"--crate-type=staticlib",
"-C",
"panic=abort",
"-C",
"opt-level=2",
])
.arg(source.join("port/tests/lut_heap.rs"))
.arg("-o")
.arg(&heap);
capture(&mut rust)?;
commands.push(format!("{rust:?}"));
let binary = output.join("cpu-model");
let mut link = Command::new(clang);
link.args(&objects)
.arg(&heap)
.arg(if cfg!(target_os = "macos") {
"-Wl,-dead_strip"
} else {
"-Wl,--gc-sections"
})
.arg("-o")
.arg(&binary);
capture(&mut link)?;
commands.push(format!("{link:?}"));
capture(&mut Command::new(&binary))?;
Ok(
json!({"binary":tools::binding(&binary)?,"heap":tools::binding(&heap)?,
"shared_heap_source":tools::binding(&tools::root().join("crates/stela-boot-core/src/heap.rs"))?,
"metadata_adapter":tools::binding(&source.port.join("memory.rs"))?,
"fixture_sources":sources.iter().map(|(file,_)| tools::binding(&source.join(file))).collect::<Result<Vec<_>>>()?,
"excluded_only_for_host_CPU_fixture":excluded,"commands":commands,"executed":true}),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg_attr(not(feature = "fetched-sources"), ignore = "feature: fetched-sources")]
#[test]
fn lut_upload_uses_header_prefix_and_common_heap() {
let output = tempfile::tempdir().unwrap();
verify(
&tools::which("clang").unwrap(),
&Sources::new(),
output.path(),
)
.unwrap();
}
}
-89
View File
@@ -1,89 +0,0 @@
//! Exercise the C adapter's allocator-refusal ABI in a separate process.
#[cfg(test)]
use super::capture;
use super::{Sources, lut, tools};
use anyhow::Result;
use serde_json::json;
#[cfg(test)]
use std::process::Command;
use std::{fs, path::Path};
#[cfg(test)]
#[cfg_attr(not(feature = "fetched-sources"), ignore = "feature: fetched-sources")]
#[test]
fn nvlink_preserves_full_lengths_and_refuses_common_heap_failures() {
let output = tempfile::tempdir().unwrap();
let source = Sources::new();
let binary = output.path().join("nvlink-memory");
let mut compiler = Command::new(tools::which("clang").unwrap());
compiler.args(["-std=gnu11", "-DNV_BSD", "-Wall", "-Wextra", "-Werror"]);
for include in [
"port",
"src/common/nvlink/interface",
"src/common/sdk/nvidia/inc",
"src/common/inc",
] {
compiler.arg("-I").arg(source.join(include));
}
super::freebsd_headers(&mut compiler);
compiler
.arg(source.join("port/stela_nvlink_memory.c"))
.arg(source.join("port/tests/nvlink_memory.c"))
.arg("-o")
.arg(&binary);
capture(&mut compiler).unwrap();
capture(&mut Command::new(binary)).unwrap();
}
/// Replay the original realloc and real common-heap failure boundary separately
/// from the test runner's allocator. No fixture provider enters native archives.
pub(super) fn verify(clang: &Path, source: &Sources, output: &Path) -> Result<()> {
fs::create_dir_all(output)?;
let flags = lut::flags(clang, source, output)?;
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
let cpu = Some(lut::cpu_model(lut::CpuModelOptions {
clang,
source,
output,
flags: &flags,
sources: &[
("port/tests/nvkms_memory.c", &[]),
(
"port/stela_nvkms_memory.c",
&[
"-Dstela_nvidia_alloc=stela_nvkms_model_alloc",
"-Dstela_nvidia_free=stela_nvkms_model_free",
"-Dnvkms_memset=stela_nvkms_model_zero",
],
),
("port/stela_nvkms_primitives.c", &[]),
],
})?);
#[cfg(not(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux"))))]
let cpu: Option<serde_json::Value> = None;
fs::write(
output.join("receipt.json"),
serde_json::to_vec_pretty(&json!({
"scope":"Actual metadata backend, original sized-prefix/realloc and common heap in a separate CPU process; no production context, final driver link or GPU execution",
"task":tools::binding(&tools::root().join(file!()))?,
"original_utils":tools::binding(&source.join("src/nvidia-modeset/src/nvkms-utils.c"))?,
"makefile":tools::binding(&source.join("src/nvidia-modeset/Makefile"))?,
"common_flags":flags.common,"c_flags":flags.c,
"hosted_CPU_access":cpu,
}))?,
)?;
Ok(())
}
#[cfg(test)]
#[cfg_attr(not(feature = "fetched-sources"), ignore = "feature: fetched-sources")]
#[test]
fn nvkms_original_realloc_preserves_ownership_on_heap_denial() {
let output = tempfile::tempdir().unwrap();
verify(
&tools::which("clang").unwrap(),
&Sources::new(),
output.path(),
)
.unwrap();
}
-127
View File
@@ -1,127 +0,0 @@
//! Inspect the upstream ordering hook's machine code without executing it.
use super::{NATIVE_TARGET, Sources, capture, tools};
use anyhow::{Context, Result, ensure};
use object::{Architecture, Object, ObjectSection, ObjectSymbol};
use serde_json::json;
use std::{fs, path::Path, process::Command};
pub(super) fn verify(clang: &Path, source: &Sources, output: &Path) -> Result<()> {
fs::create_dir_all(output)?;
let objdump = tools::which("llvm-objdump")
.or_else(tools::toolchain_objdump)
.context("original ordering inspection requires llvm-objdump")?;
let fixture = source.join("port/tests/ordering.c");
let mut profiles = Vec::new();
for target in [NATIVE_TARGET, "x86_64-apple-macosx"] {
let artifact = output.join(format!("{target}.o"));
let mut command = Command::new(clang);
command.args([
"-target",
target,
"-DNV_BSD",
"-DNV_KERNEL_INTERFACE_LAYER",
"-ffreestanding",
"-fno-stack-protector",
"-fomit-frame-pointer",
"-mno-red-zone",
"-mgeneral-regs-only",
"-std=gnu11",
"-O2",
"-Werror",
]);
for include in [
"port",
"src/common/sdk/nvidia/inc",
"src/nvidia/arch/nvalloc/unix/include",
"src/common/inc",
"src/nvidia/inc/kernel",
"src/common/unix/common/inc",
] {
command.arg("-I").arg(source.join(include));
}
super::freebsd_headers(&mut command);
let ir = output.join(format!("{target}.ll"));
let mut ir_command = Command::new(clang);
ir_command
.args(command.get_args())
.arg(&fixture)
.args(["-S", "-emit-llvm", "-o"])
.arg(&ir);
command.arg(&fixture).arg("-c").arg("-o").arg(&artifact);
capture(&mut command)?;
let bytes = fs::read(&artifact)?;
let object = object::File::parse(bytes.as_slice())?;
ensure!(
object.architecture() == Architecture::X86_64,
"wrong ordering ABI"
);
ensure!(
!object
.symbols()
.any(|s| s.is_undefined() && s.name().is_ok_and(|n| !n.is_empty())),
"ordering hook has unresolved imports"
);
let hook = object
.symbols()
.find(|s| {
s.name()
.is_ok_and(|n| n.trim_start_matches('_') == "os_flush_cpu_write_combine_buffer")
})
.context("missing actual ordering hook")?;
let text =
object.section_by_index(hook.section_index().context("ordering hook section")?)?;
ensure!(
text.data_range(hook.address(), 4)? == Some(&[0x0f, 0xae, 0xf8, 0xc3]),
"ordering hook is not exactly SFENCE and return"
);
let disassembly = capture(Command::new(&objdump).arg("-d").arg(&artifact))?;
ensure!(
disassembly
.lines()
.filter(|l| l.contains("\tsfence"))
.count()
== 2,
"hook/probe must each contain one SFENCE"
);
ensure!(
!disassembly
.split_whitespace()
.any(|t| ["%xmm", "%ymm", "%zmm"].iter().any(|r| t.starts_with(r))),
"ordering hook/probe uses SIMD registers"
);
let dump = output.join(format!("{target}.disassembly"));
fs::write(&dump, disassembly)?;
capture(&mut ir_command)?;
let text = fs::read_to_string(&ir)?;
ensure!(
text.lines()
.filter(|l| l.contains("asm sideeffect \"sfence\"") && l.contains("~{memory}"))
.count()
== 2,
"original volatile SFENCE memory clobber was lost"
);
profiles.push(json!({"target":target,"command":format!("{command:?}"),"ir_command":format!("{ir_command:?}"),
"object":tools::binding(&artifact)?,"disassembly":tools::binding(&dump)?,"ir":tools::binding(&ir)?}));
}
fs::write(
output.join("receipt.json"),
serde_json::to_vec_pretty(&json!({
"scope":"Three ABI compile/IR/actual emitted-binary inspection only; no hardware or fence execution",
"adapter":tools::binding(&source.join("port/stela_ordering.c"))?,
"fixture":tools::binding(&fixture)?,"objdump":tools::binding(&objdump)?,"profiles":profiles,
}))?,
)?;
Ok(())
}
#[cfg_attr(not(feature = "fetched-sources"), ignore = "feature: fetched-sources")]
#[test]
fn ordering_hook_preserves_fences_across_native_abis() {
let output = tempfile::tempdir().unwrap();
verify(
&tools::which("clang").unwrap(),
&Sources::new(),
output.path(),
)
.unwrap();
}
-121
View File
@@ -1,121 +0,0 @@
//! Upstream RM page accessors over the native one-time publisher.
use super::{Sources, capture, tools};
use anyhow::{Context, Result, ensure};
use serde_json::json;
use std::{fs, path::Path, process::Command};
pub(super) fn verify(clang: &Path, source: &Sources, output: &Path) -> Result<()> {
fs::create_dir_all(output)?;
let original = source.join("src/nvidia/arch/nvalloc/unix/src/os.c");
let text = fs::read_to_string(&original)?;
let declarations = source.join("src/nvidia/generated/g_os_nvoc.h");
let declarations_text = fs::read_to_string(&declarations)?;
let mut accessors = text
.split_once("#include")
.context("missing original OS source notices")?
.0
.to_owned();
for (result, name) in [
("NvU64", "osGetPageSize"),
("NvU64", "osGetSupportedSysmemPageSizeMask"),
("NvU8", "osGetPageShift"),
] {
let signature = format!("{name}(void);");
let prototypes: Vec<_> = declarations_text
.lines()
.filter(|line| line.split_whitespace().eq([result, signature.as_str()]))
.collect();
ensure!(prototypes.len() == 1, "changed original {name} declaration");
accessors.push_str(prototypes[0]);
accessors.push('\n');
let marker = format!("{result}\n{name}(void)\n{{\n");
ensure!(
text.matches(&marker).count() == 1,
"changed original {name}"
);
let start = text.find(&marker).unwrap();
let end = text[start..]
.find("\n}\n")
.context("missing original accessor body")?;
accessors.push_str(&text[start..start + end + 3]);
accessors.push('\n');
}
let header = output.join("page_geometry_accessors.h");
fs::write(&header, accessors)?;
let adapter = source.join("port/stela_page_geometry.c");
let fixture = source.join("port/tests/page_geometry.c");
let mut processes = Vec::new();
for sanitized in [false, true] {
let binary = output.join(if sanitized { "sanitized" } else { "normal" });
let mut compiler = Command::new(clang);
compiler.args([
"-DNV_BSD",
"-std=c11",
"-ffreestanding",
"-fno-builtin",
"-Wall",
"-Wextra",
"-Werror",
"-Wmissing-prototypes",
"-O2",
]);
for include in [
"port",
"src/common/sdk/nvidia/inc",
"src/nvidia/arch/nvalloc/unix/include",
"src/nvidia/inc/kernel",
"src/common/inc",
"src/common/unix/common/inc",
] {
compiler.arg("-I").arg(source.join(include));
}
super::freebsd_headers(&mut compiler);
if sanitized {
compiler.args(["-fsanitize=address,undefined", "-fno-omit-frame-pointer"]);
}
compiler
.arg("-I")
.arg(output)
.arg(&adapter)
.arg(&fixture)
.arg("-o")
.arg(&binary);
capture(&mut compiler)?;
for (base, max) in [(12, 12), (14, 14), (12, 14), (12, 21), (62, 62)] {
let mut command = Command::new(&binary);
command.args([base.to_string(), max.to_string()]);
let log = output.join(format!("{sanitized}-{base}-{max}.log"));
fs::write(&log, capture(&mut command)?)?;
processes.push(json!({
"sanitized":sanitized,"base_shift":base,"max_shift":max,
"compiler":format!("{compiler:?}"),"command":format!("{command:?}"),
"binary":tools::binding(&binary)?,"output":tools::binding(&log)?,
}));
}
}
fs::write(
output.join("receipt.json"),
serde_json::to_vec_pretty(&json!({
"scope":"Ten hosted original accessor/publisher processes; broad granules refused before publication; no physical RAM support or RM activation",
"task":tools::binding(&tools::root().join(file!()))?,
"original":tools::binding(&original)?,"accessors":tools::binding(&header)?,
"original_declarations":tools::binding(&declarations)?,
"adapter":tools::binding(&adapter)?,"fixture":tools::binding(&fixture)?,
"processes":processes,
}))?,
)?;
Ok(())
}
#[cfg(test)]
#[cfg_attr(not(feature = "fetched-sources"), ignore = "feature: fetched-sources")]
#[test]
fn page_accessors_require_supported_native_geometry() {
let output = tempfile::tempdir().unwrap();
verify(
&tools::which("clang").unwrap(),
&Sources::new(),
output.path(),
)
.unwrap();
}
-107
View File
@@ -1,107 +0,0 @@
//! Original CPU wrappers and separate full-width observation providers.
use super::{Sources, capture, tools};
use anyhow::Result;
use serde_json::json;
use std::{fs, path::Path, process::Command};
pub(super) fn verify(clang: &Path, source: &Sources, output: &Path) -> Result<()> {
fs::create_dir_all(output)?;
let adapter = source.join("port/stela_nvswitch_primitives.c");
let fixture = source.join("port/tests/nvswitch_primitives.c");
let mut models = Vec::new();
for sanitize in [false, true] {
for forward in [false, true] {
let name = format!(
"{}-{}",
if sanitize { "sanitized" } else { "normal" },
if forward { "forward" } else { "bytes" }
);
let mut objects = Vec::new();
let mut commands = Vec::new();
for (index, input) in [&adapter, &fixture].iter().enumerate() {
let artifact = output.join(format!("{name}-{index}.o"));
let mut command = Command::new(clang);
command.args([
"-DNV_BSD",
"-ffreestanding",
"-fno-builtin",
"-std=c11",
"-Wall",
"-Wextra",
"-Werror",
"-Wmissing-prototypes",
"-O2",
]);
for include in [
"port",
"src/common/sdk/nvidia/inc",
"src/nvidia/arch/nvalloc/unix/include",
"src/nvidia/inc/kernel",
"src/common/inc",
"src/common/nvlink/interface",
"src/common/nvswitch/interface",
"src/common/unix/common/inc",
] {
command.arg("-I").arg(source.join(include));
}
super::freebsd_headers(&mut command);
if sanitize {
command.args(["-fsanitize=address,undefined", "-fno-omit-frame-pointer"]);
}
if forward {
if index == 0 {
// Only the adapter object observes providers; these
// symbols never enter any production archive.
command.args([
"-Dmemcpy=stela_nvswitch_test_memcpy",
"-Dmemset=stela_nvswitch_test_memset",
"-Dstrlen=stela_nvswitch_test_strlen",
]);
} else {
command.arg("-DSTELA_NVSWITCH_FORWARD_TEST");
}
}
command.arg("-c").arg(input).arg("-o").arg(&artifact);
capture(&mut command)?;
commands.push(format!("{command:?}"));
objects.push(artifact);
}
let binary = output.join(&name);
let mut link = Command::new(clang);
link.args(&objects).arg("-o").arg(&binary);
if sanitize {
link.args(["-fsanitize=address,undefined", "-fno-omit-frame-pointer"]);
}
capture(&mut link)?;
commands.push(format!("{link:?}"));
let log = output.join(format!("{name}.log"));
fs::write(&log, capture(&mut Command::new(&binary))?)?;
models.push(json!({"sanitized":sanitize,"forwarding_only":forward,"commands":commands,"binary":tools::binding(&binary)?,"output":tools::binding(&log)?}));
}
}
fs::write(
output.join("receipt.json"),
serde_json::to_vec_pretty(&json!({
"scope":"Actual original wrappers in four hosted CPU byte/forwarding processes; no native EFI/GPU execution or production observer provider",
"task":tools::binding(&tools::root().join(file!()))?,"adapter":tools::binding(&adapter)?,"fixture":tools::binding(&fixture)?,
"original_header":tools::binding(&source.join("src/common/nvswitch/interface/export_nvswitch.h"))?,"models":models,
}))?,
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg_attr(not(feature = "fetched-sources"), ignore = "feature: fetched-sources")]
#[test]
fn nvswitch_wrappers_preserve_bytes_and_lengths() {
let output = tempfile::tempdir().unwrap();
verify(
&tools::which("clang").unwrap(),
&Sources::new(),
output.path(),
)
.unwrap();
}
}
+1 -1
View File
@@ -4,9 +4,9 @@
//! they find is true of the image, and no build host chooses its contents.
use super::{
llvm,
nvidia::Toolchain,
nvk::{LIBC, LIBC_TEST_FLAGS, REGEX, Unit, compile, resource_directory},
support::{gpu, slashed, third_party},
toolchain::Toolchain,
};
use anyhow::Result;
use std::{
+45 -1
View File
@@ -1,10 +1,15 @@
//! The pinned tools the GPU builds run, installed under `.tools/gpu`: Meson,
//! Ninja and Mesa's Python generator modules in a virtual environment, and the
//! Rust binding generators NAK's build calls.
use super::support::capture;
use crate::tools::{self, exec};
use anyhow::{Context, Result, bail, ensure};
use sha2::{Digest, Sha256};
use std::{fs, path::PathBuf, process::Command};
use std::{
fs,
path::{Path, PathBuf},
process::Command,
};
/// Mesa 26.2 needs Python 3.10 or newer for its generators.
const PYTHON_MINOR: u32 = 10;
@@ -187,3 +192,42 @@ fn standalone_python() -> Result<PathBuf> {
ensure!(python.is_file(), "{name} has no bin/python3");
Ok(python)
}
/// The host's Clang and the active Rust toolchain's LLVM linker and archiver.
pub(super) struct Toolchain {
pub(super) clang: PathBuf,
pub(super) clangxx: PathBuf,
pub(super) linker: PathBuf,
pub(super) archiver: PathBuf,
}
impl Toolchain {
pub(super) fn discover() -> Result<Self> {
let rustc = tools::which("rustc").context("rustc is not in PATH")?;
let sysroot = capture(Command::new(&rustc).args(["--print", "sysroot"]))?;
let version = capture(Command::new(&rustc).arg("-vV"))?;
let host = version
.lines()
.find_map(|line| line.strip_prefix("host: "))
.context("rustc did not report its host target")?;
let directory = Path::new(sysroot.trim())
.join("lib/rustlib")
.join(host)
.join("bin");
let tool = |name: &str| directory.join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
let toolchain = Self {
clang: tools::which("clang").context("install Clang")?,
clangxx: tools::which("clang++").context("install Clang's C++ compiler")?,
linker: tool("gcc-ld/ld.lld"),
archiver: tool("llvm-ar"),
};
for path in [&toolchain.linker, &toolchain.archiver] {
ensure!(
path.is_file(),
"{} is missing; install llvm-tools-preview for the active Rust toolchain",
path.display()
);
}
Ok(toolchain)
}
}
-42
View File
@@ -147,46 +147,4 @@ mod tests {
entry.values.push("STELA_INPUT".into());
assert!(crate::oracles::validate(&[entry]).is_err());
}
#[test]
fn feature_gates_name_their_enabling_feature() {
let files = crate::oracles::git(&[
"grep",
"-l",
"cfg_attr",
"--",
"crates/**/*.rs",
"xtask/**/*.rs",
])
.unwrap();
let mut inspected = 0;
for file in files.lines() {
let text = std::fs::read_to_string(crate::tools::root().join(file)).unwrap();
let marker = concat!("#[", "cfg_attr(");
for (offset, _) in text.match_indices(marker) {
let tail = &text[offset + marker.len()..];
let attribute = &tail[..tail.find(")]").expect("conditional attribute terminator")];
let ignored = attribute.rsplit(',').find(|part| {
let part = part.trim();
part == "ignore" || part.starts_with("ignore =")
});
if let Some(ignored) = ignored {
assert_eq!(
ignored.trim(),
"ignore = \"feature: fetched-sources\"",
"{file}"
);
assert_eq!(
attribute.trim().split_once(',').unwrap().0,
"not(feature = \"fetched-sources\")",
"{file}"
);
inspected += 1;
}
}
}
assert!(
inspected > 0,
"feature-gated source checks must remain represented"
);
}
}
-5
View File
@@ -55,11 +55,6 @@ pub fn which(name: impl AsRef<OsStr>) -> Option<PathBuf> {
.find(|path| path.is_file())
}
/// `llvm-objdump` from the Rust toolchain's `llvm-tools`.
pub fn toolchain_objdump() -> Option<PathBuf> {
toolchain_llvm_tool("llvm-objdump")
}
/// Locate a tool bundled with the active Rust toolchain.
pub fn toolchain_llvm_tool(name: &str) -> Option<PathBuf> {
let output = Command::new(env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()))