Files
nvdriver/src/nvidia/kernel/uvm_interface_ffi.rs
Eric Hartford 9c5d74c469 uvm/kernel: HMM/timeline/allocator fixes (#222) and modeset/UVM FFI safety (#239)
- Rebased #222 (HMM ReadDuplicated OR + Host slot recycling preserving #220's
  NvStatus(0x1a), sync_timeline waiter overflow, CBC/NVLS/SRIOV watermark reclaim).
- Rebased #239 (modeset_ffi refcount/arch/lock fixes, UVM FFI null/bounds/checked-
  arithmetic adapted onto #294's visit_video_range split, raw-pointer CSL AES-GCM
  avoiding aliasing UB).

Verified with 32/32 offline/build/QEMU/gate checks (1,093 unit tests).

Co-authored-by: morebrackets <morebrackets@users.noreply.github.com>
2026-12-02 19:06:24 +00:00

3103 lines
99 KiB
Rust

//! Kernel C-ABI FFI bridge for RM-side `nvUvmInterface*` entry points (580.178.04).
//!
//! Backs the `nv_rs_uvm_iface_*` symbols with the zero-allocation, no-std
//! `nv_rs_core::uvm::interface_dispatch::UvmInterfaceRegistry` (76/76 handlers,
//! 18/18 C-ABI structs verified against `/usr/src/nvidia-srv-580.178.04/common/inc/nv_uvm_types.h`).
//!
//! Symbol names are prefixed `nv_rs_uvm_iface_*` so `nvidia_rs.ko` can load
//! side-by-side with stock `nvidia.ko` during Dual-GPU Parity runs without
//! colliding on Linux's global `EXPORT_SYMBOL(nvUvmInterface*)` namespace.
//! A standalone build without stock `nvidia.ko` can alias `nvUvmInterface*`
//! directly to these entry points.
use core::{ptr, slice};
use nv_rs_abi::NvStatus;
use nv_rs_core::gpu::multi_gpu::{PeerLink, INVALID_PEER_ID};
use nv_rs_core::uvm::interface_abi::{
UvmGpuAccessCntrConfig, UvmGpuAccessCntrInfo, UvmGpuAddressSpaceInfo, UvmGpuAllocInfo,
UvmGpuCaps, UvmGpuChannelAllocParams, UvmGpuClientInfo, UvmGpuCopyEnginesCaps, UvmGpuEccInfo,
UvmGpuFbInfo, UvmGpuInfo, UvmGpuNvlinkInfo, UvmGpuP2PCapsParams,
UvmGpuPagingChannelAllocParams, UvmGpuTsgAllocParams, UvmLinkType, UvmPlatformInfo,
};
use nv_rs_core::uvm::interface_dispatch::{
UvmGpuDescriptor, UvmGpuPlatformInfo, UvmInterfaceRegistry, NV_ERR_NOT_SUPPORTED,
};
unsafe extern "C" {
fn nv_rs_rm_api_lock();
fn nv_rs_rm_api_unlock();
fn nv_rs_uvm_fault_poll_stop();
#[cfg(not(nv_rs_edu_guest))]
fn nv_rs_rmapi_os_page_dma(gpu_id: u32, token: u64, page_index: u64, dma_out: *mut u64) -> u32;
}
static mut UVM_IFACE: UvmInterfaceRegistry = UvmInterfaceRegistry::new(false, false);
static mut UVM_RUNLIST_SCRATCH: [(u16, u16, u64, u64); 32] = [(0, 0, 0, 0); 32];
struct LockGuard;
impl LockGuard {
#[inline(always)]
unsafe fn acquire() -> Self {
unsafe {
nv_rs_rm_api_lock();
Self
}
}
}
impl Drop for LockGuard {
#[inline(always)]
fn drop(&mut self) {
unsafe { nv_rs_rm_api_unlock() };
}
}
#[inline(always)]
unsafe fn iface_mut() -> &'static mut UvmInterfaceRegistry {
unsafe { &mut *ptr::addr_of_mut!(UVM_IFACE) }
}
/// Registers a live GV100 Tesla V100 GPU UUID (16 GiB or 32 GiB) in the RM↔UVM interface table.
///
/// # Safety
/// Must be called while `nv_rs_rm_api_lock` is already held (e.g., from `activate_runtime`
/// on `nvidia_rs_rt` while the opener thread holds `nv_rs_rm_api_lock`). Re-acquiring the
/// lock here would self-deadlock.
#[inline(never)]
#[allow(clippy::too_many_arguments)]
pub(crate) unsafe fn register_live_gv100(
gpu_id: u32,
uuid: [u8; 16],
pci_device_id: u32,
fb_size_bytes: u64,
pci_dev_cookie: usize,
bar0_vaddr: usize,
fault_ring_cpu: usize,
fault_ring_size: u32,
) {
unsafe {
let mut desc = UvmGpuDescriptor::tesla_v100(uuid, pci_device_id, fb_size_bytes);
desc.gpu_id = gpu_id;
desc.pci_dev_cookie = pci_dev_cookie;
desc.bar0_vaddr = bar0_vaddr;
desc.fault_ring_cpu = fault_ring_cpu;
desc.fault_ring_size = fault_ring_size;
let pma_base = (desc.fb_size_bytes / 2) & !0x1f_ffff;
let iface = iface_mut();
let _ = iface.add_probed_gpu(desc);
iface.set_gpu_pma_base(&uuid, pma_base);
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_register_uvm_callbacks(ops_cookie: usize) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().register_uvm_callbacks(ops_cookie).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_deregister_uvm_ops() {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().deregister_uvm_ops();
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_register_gpu(
uuid: *const [u8; 16],
out_info: *mut UvmGpuPlatformInfo,
) -> u32 {
unsafe {
if uuid.is_null() || out_info.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().register_gpu(&*uuid) {
Ok(info) => {
*out_info = info;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_unregister_gpu(uuid: *const [u8; 16]) {
unsafe {
if uuid.is_null() {
return;
}
let _guard = LockGuard::acquire();
iface_mut().unregister_gpu(&*uuid);
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_session_create(
session_out: *mut u64,
platform_out: *mut UvmPlatformInfo,
) -> u32 {
unsafe {
if session_out.is_null() || platform_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().session_create() {
Ok((handle, plat)) => {
*session_out = handle;
*platform_out = plat;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[inline(never)]
unsafe fn teardown_p2p_devices(iface: &UvmInterfaceRegistry, dev1: u64, dev2: u64) {
if let (Some((g1, _)), Some((g2, _))) = (iface.device_hw_ids(dev1), iface.device_hw_ids(dev2)) {
if g1 != 0 && g2 != 0 && g1 != g2 {
unsafe {
crate::rmapi_node::teardown_p2p_mailbox_pair(g1, g2);
}
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_session_destroy(session: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
let iface = iface_mut();
while let Some(ch) = iface.next_channel_in_session(session) {
let st = destroy_channel_hw(iface, ch);
if st != NvStatus::OK.0 {
return st;
}
}
while let Some((dev1, dev2)) = iface.take_p2p_object_for_session(session) {
teardown_p2p_devices(iface, dev1, dev2);
}
iface.session_destroy(session).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_device_create(
session: u64,
uuid: *const [u8; 16],
device_out: *mut u64,
) -> u32 {
unsafe {
if uuid.is_null() || device_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().device_create(session, &*uuid) {
Ok(handle) => {
*device_out = handle;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_device_destroy(device: u64) {
unsafe {
let _guard = LockGuard::acquire();
let iface = iface_mut();
while let Some(ch) = iface.next_channel_in_device(device) {
if destroy_channel_hw(iface, ch) != NvStatus::OK.0 {
return;
}
}
while let Some((dev1, dev2)) = iface.take_p2p_object_for_device(device) {
teardown_p2p_devices(iface, dev1, dev2);
}
iface.device_destroy(device);
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_get_gpu_info(
uuid: *const [u8; 16],
client_info: *const UvmGpuClientInfo,
out_info: *mut UvmGpuInfo,
) -> u32 {
unsafe {
if uuid.is_null() || client_info.is_null() || out_info.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().get_gpu_info(&*uuid, *client_info) {
Ok(info) => {
*out_info = info;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_get_fb_info(
device: u64,
out_info: *mut UvmGpuFbInfo,
) -> u32 {
unsafe {
if out_info.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().get_fb_info(device) {
Ok(info) => {
*out_info = info;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_get_ecc_info(
device: u64,
out_info: *mut UvmGpuEccInfo,
) -> u32 {
unsafe {
if out_info.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().get_ecc_info(device) {
Ok(mut info) => {
#[cfg(not(test))]
{
unsafe extern "C" {
fn nv_rs_disable_ecc() -> bool;
}
if nv_rs_disable_ecc() {
info.b_ecc_enabled = 0;
}
}
*out_info = info;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_get_nvlink_info(
device: u64,
out_info: *mut UvmGpuNvlinkInfo,
) -> u32 {
unsafe {
if out_info.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().get_nvlink_info(device) {
Ok(info) => {
*out_info = info;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_query_caps(device: u64, out_caps: *mut UvmGpuCaps) -> u32 {
unsafe {
if out_caps.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().query_caps(device) {
Ok(caps) => {
*out_caps = caps;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_query_copy_engines_caps(
device: u64,
out_caps: *mut UvmGpuCopyEnginesCaps,
) -> u32 {
unsafe {
if out_caps.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
iface_mut()
.query_copy_engines_caps_into(device, &mut *out_caps)
.0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_memory_alloc_fb(
va_space: u64,
length: u64,
gpu_va_out: *mut u64,
alloc_info: *mut UvmGpuAllocInfo,
) -> u32 {
unsafe {
if gpu_va_out.is_null() || alloc_info.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().memory_alloc_fb(va_space, length, &mut *alloc_info) {
Ok(va) => {
*gpu_va_out = va;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_memory_alloc_sys(
va_space: u64,
length: u64,
page_phys_list: *const u64,
page_count: u64,
gpu_va_out: *mut u64,
alloc_info: *mut UvmGpuAllocInfo,
) -> u32 {
unsafe {
if gpu_va_out.is_null() || alloc_info.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
if page_count > 0 && page_phys_list.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let page_count_usize = match usize::try_from(page_count) {
Ok(n) if n <= (isize::MAX as usize) / core::mem::size_of::<u64>() => n,
_ => return NvStatus::INVALID_ARGUMENT.0,
};
let _guard = LockGuard::acquire();
let iface = iface_mut();
match iface.memory_alloc_sys(va_space, length, &mut *alloc_info) {
Ok(va) => {
if !page_phys_list.is_null() && page_count_usize > 0 {
if let Some((gpu_id, _bar0, pde3, pde0)) = iface.vas_hw_info(va_space) {
if gpu_id != 0 && pde3 != 0 && pde0 != 0 {
let pages =
core::slice::from_raw_parts(page_phys_list, page_count_usize);
let _ =
crate::rmapi_node::uvm_hw_map_pages(gpu_id, pde3, pde0, va, pages);
}
}
}
*gpu_va_out = va;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_memory_free(va_space: u64, gpu_va: u64) {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().memory_free(va_space, gpu_va);
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_service_device_interrupts_rm(device: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().service_device_interrupts_rm(device).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_own_page_fault_intr(device: u64, own: bool) -> u32 {
unsafe {
if own {
// Yield hardware replayable fault buffer polling to stock nvidia-uvm.ko.
nv_rs_uvm_fault_poll_stop();
}
let _guard = LockGuard::acquire();
iface_mut().own_page_fault_intr(device, own).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_address_space_create(
device: u64,
va_base: u64,
va_size: u64,
enable_ats: bool,
va_space_out: *mut u64,
info_out: *mut UvmGpuAddressSpaceInfo,
) -> u32 {
unsafe {
if va_space_out.is_null() || info_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
match iface.address_space_create(device, va_base, va_size, enable_ats) {
Ok((handle, info)) => {
if let Some((gpu_id, _bar0)) = iface.device_hw_ids(device) {
if gpu_id != 0 {
if let Some((pde3, pde0)) = crate::rmapi_node::uvm_hw_create_vas(gpu_id) {
iface.set_vas_hw_pdb(handle, pde3, pde0);
}
}
}
*va_space_out = handle;
*info_out = info;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_address_space_destroy(va_space: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
let iface = iface_mut();
while let Some(ch) = iface.next_channel_in_va_space(va_space) {
let st = destroy_channel_hw(iface, ch);
if st != NvStatus::OK.0 {
return st;
}
}
iface.address_space_destroy(va_space).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_set_page_directory(
va_space: u64,
phys_address: u64,
num_entries: u32,
vidmem_aperture: bool,
pasid: u32,
dma_addr_out: *mut u64,
) -> u32 {
unsafe {
static mut UVM_INST_SCRATCH: [u64; 32] = [0; 32];
if dma_addr_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
let prev_hw = iface.vas_hw_info(va_space);
let user_vas = iface.vas_user_handles(va_space);
match iface.set_page_directory(va_space, phys_address, num_entries, vidmem_aperture, pasid)
{
Ok(addr) => {
if let Some((user_client, user_va_space)) = user_vas {
let _ = crate::rmapi_node::set_vaspace_page_directory_full(
user_client,
user_va_space,
Some(phys_address),
num_entries,
!vidmem_aperture,
);
if vidmem_aperture {
iface.set_vas_hw_pde3(va_space, phys_address);
}
#[cfg(not(nv_rs_edu_guest))]
if let Some((gpu_id, _, _, _)) = prev_hw {
if gpu_id != 0 {
crate::rmapi_node::flush_gpu_tlb(gpu_id, phys_address);
}
}
} else if let Some((gpu_id, _bar0, old_pde3, _pde0)) = prev_hw {
if gpu_id != 0 && old_pde3 != 0 && phys_address != 0 {
let scratch = &mut *ptr::addr_of_mut!(UVM_INST_SCRATCH);
let n = iface.collect_vas_channel_insts(va_space, scratch);
crate::rmapi_node::uvm_hw_set_page_directory(
gpu_id,
old_pde3,
phys_address,
vidmem_aperture,
&scratch[..n],
);
if vidmem_aperture {
iface.set_vas_hw_pde3(va_space, phys_address);
}
}
}
*dma_addr_out = addr;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_unset_page_directory(va_space: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
let iface = iface_mut();
if let Some((user_client, user_va_space)) = iface.vas_user_handles(va_space) {
let _ = crate::rmapi_node::set_vaspace_page_directory_full(
user_client,
user_va_space,
None,
0,
false,
);
}
iface.unset_page_directory(va_space).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_p2p_object_create(
dev1: u64,
dev2: u64,
p2p_handle_out: *mut u32,
) -> u32 {
unsafe {
if p2p_handle_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
let hw_pair = match (iface.device_hw_ids(dev1), iface.device_hw_ids(dev2)) {
(Some((g1, _)), Some((g2, _))) if g1 != 0 && g2 != 0 && g1 != g2 => Some((g1, g2)),
_ => None,
};
if let Some((g1, g2)) = hw_pair {
if crate::rmapi_node::setup_p2p_mailbox_pair(g1, g2).is_none() {
return NV_ERR_NOT_SUPPORTED.0;
}
}
match iface.p2p_object_create(dev1, dev2) {
Ok(h) => {
*p2p_handle_out = h;
NvStatus::OK.0
}
Err(st) => {
if let Some((g1, g2)) = hw_pair {
crate::rmapi_node::teardown_p2p_mailbox_pair(g1, g2);
}
st.0
}
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_p2p_object_destroy(session: u64, p2p_handle: u32) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
let iface = iface_mut();
if let Some((dev1, dev2)) = iface.p2p_object_devices(session, p2p_handle) {
teardown_p2p_devices(iface, dev1, dev2);
}
iface.p2p_object_destroy(session, p2p_handle).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_tsg_allocate(
va_space: u64,
params: *const UvmGpuTsgAllocParams,
tsg_out: *mut u64,
) -> u32 {
unsafe {
if params.is_null() || tsg_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().tsg_allocate(va_space, *params) {
Ok(h) => {
*tsg_out = h;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_tsg_destroy(tsg: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
let iface = iface_mut();
while let Some(ch) = iface.next_channel_in_tsg(tsg) {
let st = destroy_channel_hw(iface, ch);
if st != NvStatus::OK.0 {
return st;
}
}
iface.tsg_destroy(tsg).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_channel_allocate(
tsg: u64,
params: *const UvmGpuChannelAllocParams,
userd_phys: u64,
gpfifo_phys: u64,
gpfifo_bytes: u64,
channel_out: *mut u64,
hw_runlist_out: *mut u32,
hw_chid_out: *mut u32,
bar0_vaddr_out: *mut u64,
) -> u32 {
unsafe {
if params.is_null()
|| channel_out.is_null()
|| hw_runlist_out.is_null()
|| hw_chid_out.is_null()
|| bar0_vaddr_out.is_null()
{
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
let p = *params;
match iface.channel_allocate(tsg, p) {
Ok(h) => {
let mut out_runlist = 1u32;
let mut out_chid = (h & 0xfff) as u32;
let mut out_bar0 = 0u64;
if userd_phys != 0 && gpfifo_phys != 0 && gpfifo_bytes != 0 {
if let Some((_vas, gpu_id, bar0, pde3, pde0, runlist, hw_tsg_id)) =
iface.tsg_hw_info(tsg)
{
if gpu_id != 0 && pde3 != 0 && pde0 != 0 {
if let (Some(gpfifo_va), Some(hw_chid)) = (
iface.alloc_internal_gpu_va(gpfifo_bytes, 0x1000),
iface.channel_hw_chid(h),
) {
let _ = crate::rmapi_node::uvm_hw_map_range(
gpu_id,
pde3,
pde0,
gpfifo_va,
gpfifo_phys,
gpfifo_bytes,
false,
);
if let Some(inst_phys) = crate::rmapi_node::uvm_hw_bind_ce_channel(
gpu_id,
u32::from(hw_chid),
pde3,
gpfifo_va,
p.num_gp_fifo_entries,
userd_phys,
) {
let _ = iface.channel_set_hw(
h, gpu_id, runlist, hw_tsg_id, inst_phys, userd_phys,
);
let scratch = &mut *ptr::addr_of_mut!(UVM_RUNLIST_SCRATCH);
let n =
iface.collect_runlist_channels(gpu_id, runlist, scratch);
let _ = crate::rmapi_node::uvm_hw_submit_ce_runlist(
gpu_id,
runlist,
&scratch[..n],
);
out_runlist = runlist;
out_chid = u32::from(hw_chid);
out_bar0 = bar0 as u64;
}
}
}
}
}
*channel_out = h;
*hw_runlist_out = out_runlist;
*hw_chid_out = out_chid;
*bar0_vaddr_out = out_bar0;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[inline(never)]
unsafe fn destroy_channel_hw(iface: &mut UvmInterfaceRegistry, channel: u64) -> u32 {
unsafe {
if let Some((gpu_id, runlist, hw_tsg_id, hw_chid)) = iface.channel_hw_info(channel) {
let st = crate::rmapi_node::uvm_hw_disable_preempt_ce_channel(
gpu_id,
u32::from(hw_tsg_id),
u32::from(hw_chid),
);
if st != NvStatus::OK {
return st.0;
}
let scratch = &mut *ptr::addr_of_mut!(UVM_RUNLIST_SCRATCH);
let n = iface.collect_runlist_channels_excluding(gpu_id, runlist, channel, scratch);
let st = crate::rmapi_node::uvm_hw_submit_ce_runlist(gpu_id, runlist, &scratch[..n]);
if st != NvStatus::OK {
return st.0;
}
let st = crate::rmapi_node::uvm_hw_finish_unbind_ce_channel(gpu_id, u32::from(hw_chid));
if st != NvStatus::OK {
return st.0;
}
}
iface.channel_destroy(channel).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_channel_destroy(channel: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
destroy_channel_hw(iface_mut(), channel)
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_paging_channel_allocate(
device: u64,
params: *const UvmGpuPagingChannelAllocParams,
channel_out: *mut u64,
) -> u32 {
unsafe {
if params.is_null() || channel_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().paging_channel_allocate(device, *params) {
Ok(h) => {
*channel_out = h;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_paging_channel_destroy(channel: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().paging_channel_destroy(channel).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_toggle_prefetch_faults(device: u64, enable: bool) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().toggle_prefetch_faults(device, enable).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_report_fatal_error(error: u32) {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().report_fatal_error(NvStatus(error));
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_init_access_cntr_info(
device: u64,
out_info: *mut UvmGpuAccessCntrInfo,
) -> u32 {
unsafe {
if out_info.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().init_access_cntr_info(device) {
Ok(info) => {
*out_info = info;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_destroy_access_cntr_info(device: u64, handle: u32) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().destroy_access_cntr_info(device, handle).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_enable_access_cntr(
device: u64,
handle: u32,
config: *const UvmGpuAccessCntrConfig,
) -> u32 {
unsafe {
if config.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
iface_mut().enable_access_cntr(device, handle, *config).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_disable_access_cntr(device: u64, handle: u32) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().disable_access_cntr(device, handle).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_flush_replayable_fault_buffer(device: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().flush_replayable_fault_buffer(device).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_has_pending_non_replayable_faults(
device: u64,
out_pending: *mut bool,
) -> u32 {
unsafe {
if out_pending.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().has_pending_non_replayable_faults(device) {
Ok(p) => {
*out_pending = p;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_dup_address_space(
device: u64,
user_client: u32,
user_va_space: u32,
va_space_out: *mut u64,
info_out: *mut UvmGpuAddressSpaceInfo,
) -> u32 {
unsafe {
if va_space_out.is_null() || info_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().dup_address_space(device, user_client, user_va_space) {
Ok((h, info)) => {
*va_space_out = h;
*info_out = info;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_dup_allocation(
src_va_space: u64,
src_address: u64,
dst_va_space: u64,
dst_va_alignment: u64,
dst_address_out: *mut u64,
) -> u32 {
unsafe {
if dst_address_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().dup_allocation(src_va_space, src_address, dst_va_space, dst_va_alignment)
{
Ok(addr) => {
*dst_address_out = addr;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_dup_memory(
device: u64,
user_client: u32,
user_memory: u32,
duped_handle_out: *mut u32,
kind_out: *mut u32,
sysmem_out: *mut u8,
dev_desc_out: *mut u8,
contig_out: *mut u8,
page_size_out: *mut u64,
phys_addr_out: *mut u64,
size_out: *mut u64,
uuid_out: *mut u8,
) -> u32 {
unsafe {
if duped_handle_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
#[cfg(not(nv_rs_edu_guest))]
let mem_lookup = crate::rmapi_node::lookup_memory(user_client, user_memory);
#[cfg(nv_rs_edu_guest)]
let mem_lookup: Option<(bool, u32, u64, u64, u8)> = None;
match iface.dup_memory(device, user_client, user_memory) {
Ok(h) => {
*duped_handle_out = h;
let (kind, sysmem, dev_desc, contig, page_size, phys_addr, size, uuid) =
if let Some((is_video, mem_gpu_id, token_or_vram, sz, pte_kind)) = mem_lookup {
let uuid = iface
.gpu_uuid_by_id(mem_gpu_id)
.or_else(|| iface.device_uuid(device))
.unwrap_or([0u8; 16]);
#[cfg(not(nv_rs_edu_guest))]
let contig = u8::from(
is_video
&& crate::rmapi_node::is_video_memory_contiguous(
user_client,
user_memory,
),
);
#[cfg(nv_rs_edu_guest)]
let contig = u8::from(is_video);
(
u32::from(pte_kind),
u8::from(!is_video),
1u8,
contig,
4096u64,
if is_video { token_or_vram } else { 0 },
sz,
uuid,
)
} else {
let uuid = iface.device_uuid(device).unwrap_or([0u8; 16]);
(0, 1, 1, 0, 4096, 0, 4096, uuid)
};
if !kind_out.is_null() {
*kind_out = kind;
}
if !sysmem_out.is_null() {
*sysmem_out = sysmem;
}
if !dev_desc_out.is_null() {
*dev_desc_out = dev_desc;
}
if !contig_out.is_null() {
*contig_out = contig;
}
if !page_size_out.is_null() {
*page_size_out = page_size;
}
if !phys_addr_out.is_null() {
*phys_addr_out = phys_addr;
}
if !size_out.is_null() {
*size_out = size;
}
if !uuid_out.is_null() {
for (i, &b) in uuid.iter().enumerate() {
*uuid_out.add(i) = b;
}
}
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_free_duped_handle(device: u64, duped_handle: u32) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().free_duped_handle(device, duped_handle).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_memory_cpu_map(
va_space: u64,
gpu_va: u64,
length: u64,
cpu_ptr_out: *mut u64,
) -> u32 {
unsafe {
if cpu_ptr_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().memory_cpu_map(va_space, gpu_va, length) {
Ok(p) => {
*cpu_ptr_out = p;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_memory_cpu_unmap(va_space: u64, cpu_ptr: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().memory_cpu_unmap(va_space, cpu_ptr).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_retain_channel(
va_space: u64,
user_client: u32,
user_channel: u32,
retained_out: *mut u64,
inst_base_out: *mut u64,
runlist_out: *mut u32,
chid_out: *mut u32,
tsg_id_out: *mut u32,
engine_type_out: *mut u32,
ctx_vram_out: *mut u64,
ctx_size_out: *mut u64,
uuid_out: *mut u8,
) -> u32 {
unsafe {
if retained_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
match iface.retain_channel(va_space, user_client, user_channel) {
Ok(h) => {
*retained_out = h;
#[cfg(not(nv_rs_edu_guest))]
let ch_lookup = match crate::rmapi_node::lookup_channel(user_client, user_channel) {
Ok(v) => Some(v),
Err(st) if st == NvStatus(0x65) => {
let _ = iface.release_channel(h);
*retained_out = 0;
return st.0;
}
Err(_) => None,
};
#[cfg(nv_rs_edu_guest)]
let ch_lookup: Option<(u32, u32, u32, u64, u64, u64)> = None;
let (runlist_id, group_id, chid, inst_addr, ctx_vram, ctx_size) =
ch_lookup.unwrap_or((0, 0, 0, 0, 0, 0));
let engine_type = if runlist_id == 0 { 1u32 } else { 2u32 };
if !inst_base_out.is_null() {
*inst_base_out = inst_addr;
}
if !runlist_out.is_null() {
*runlist_out = runlist_id;
}
if !chid_out.is_null() {
*chid_out = chid;
}
if !tsg_id_out.is_null() {
*tsg_id_out = group_id;
}
if !engine_type_out.is_null() {
*engine_type_out = engine_type;
}
if !ctx_vram_out.is_null() {
*ctx_vram_out = if runlist_id == 0 { ctx_vram } else { 0 };
}
if !ctx_size_out.is_null() {
*ctx_size_out = if runlist_id == 0 { ctx_size } else { 0 };
}
if !uuid_out.is_null() {
let uuid = iface
.vas_hw_info(va_space)
.and_then(|(gid, _, _, _)| iface.gpu_uuid_by_id(gid))
.unwrap_or([0u8; 16]);
for (i, &b) in uuid.iter().enumerate() {
*uuid_out.add(i) = b;
}
}
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_bind_channel_resources(
retained_channel: u64,
resource_ids: *const u32,
resource_vas: *const u64,
count: u32,
) -> u32 {
unsafe {
if count > 0 && (resource_ids.is_null() || resource_vas.is_null()) {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
let st = iface.bind_channel_resources(retained_channel, count);
if st != NvStatus::OK {
return st.0;
}
#[cfg(not(nv_rs_edu_guest))]
if let Some((va_space, user_client, user_channel)) =
iface.retained_channel_info(retained_channel)
{
let mut res_pairs = [(0u32, 0u64); 4];
let n = if !resource_ids.is_null() && !resource_vas.is_null() {
(count as usize).min(res_pairs.len())
} else {
0
};
for (i, slot) in res_pairs.iter_mut().take(n).enumerate() {
*slot = (*resource_ids.add(i), *resource_vas.add(i));
}
let (bind_st, gpu_id) =
crate::rmapi_node::bind_channel_context(user_client, user_channel, &res_pairs[..n]);
if bind_st != NvStatus::OK {
return bind_st.0;
}
if n > 0 {
if let Some((_, _, pde3, _)) = iface.vas_hw_info(va_space) {
if gpu_id != 0 && pde3 != 0 {
crate::rmapi_node::uvm_hw_map_global_ctx_in_pde3(gpu_id, pde3);
}
}
}
}
NvStatus::OK.0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_stop_channel(
retained_channel: u64,
immediate: bool,
) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
let iface = iface_mut();
#[cfg(not(nv_rs_edu_guest))]
if let Some((_va_space, user_client, user_channel)) =
iface.retained_channel_info(retained_channel)
{
crate::rmapi_node::stop_channel_context(user_client, user_channel);
}
iface.stop_channel(retained_channel, immediate).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_release_channel(retained_channel: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().release_channel(retained_channel).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_paging_channels_map(
src_va_space: u64,
src_address: u64,
device: u64,
dst_address_out: *mut u64,
) -> u32 {
unsafe {
if dst_address_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().paging_channels_map(src_va_space, src_address, device) {
Ok(addr) => {
*dst_address_out = addr;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_paging_channels_unmap(
src_va_space: u64,
device: u64,
) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().paging_channels_unmap(src_va_space, device).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_paging_channel_push_stream(
channel: u64,
method_stream: *const u8,
method_stream_size: usize,
) -> u32 {
unsafe {
if method_stream.is_null() && method_stream_size != 0 {
return NvStatus::INVALID_ARGUMENT.0;
}
let bytes = if method_stream_size == 0 {
&[]
} else {
slice::from_raw_parts(method_stream, method_stream_size)
};
let _guard = LockGuard::acquire();
iface_mut().paging_channel_push_stream(channel, bytes).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_report_non_replayable_fault(device: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().report_non_replayable_fault(device).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_get_non_replayable_faults(
device: u64,
count_out: *mut u32,
) -> u32 {
unsafe {
if count_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().get_non_replayable_faults(device) {
Ok(n) => {
*count_out = n;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_get_pma_object(device: u64, pma_out: *mut u64) -> u32 {
unsafe {
if pma_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().get_pma_object(device) {
Ok(p) => {
*pma_out = p;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_pma_register_eviction_callbacks(cookie: usize) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().pma_register_eviction_callbacks(cookie).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_pma_unregister_eviction_callbacks() {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().pma_unregister_eviction_callbacks();
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_init_fault_info(
device: u64,
replayable_sz_out: *mut u32,
non_replayable_sz_out: *mut u32,
bar0_vaddr_out: *mut u64,
ring_cpu_out: *mut u64,
handle_out: *mut u32,
) -> u32 {
unsafe {
if replayable_sz_out.is_null()
|| non_replayable_sz_out.is_null()
|| bar0_vaddr_out.is_null()
|| ring_cpu_out.is_null()
|| handle_out.is_null()
{
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
match iface.init_fault_info(device) {
Ok((r, nr)) => {
let (bar0, ring_cpu, handle) = iface.device_live_fault_backing(device).unwrap_or((
0,
0,
(device as u32) | 0x4600_0000,
));
*replayable_sz_out = r;
*non_replayable_sz_out = nr;
*bar0_vaddr_out = bar0 as u64;
*ring_cpu_out = ring_cpu as u64;
*handle_out = handle;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_destroy_fault_info(device: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().destroy_fault_info(device).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_get_external_alloc_ptes(
va_space: u64,
duped_handle: u32,
offset: u64,
size: u64,
caching_type: u32,
mapping_type: u32,
format_type: u32,
mapping_page_size: u64,
pte_buf: *mut u64,
pte_buf_bytes: u64,
num_written_out: *mut u64,
num_remaining_out: *mut u64,
) -> u32 {
unsafe {
if num_written_out.is_null() || num_remaining_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
if let Err(st) = iface.get_external_alloc_ptes(va_space, duped_handle, offset, size) {
return st.0;
}
let page_size = if mapping_page_size != 0 && mapping_page_size.is_power_of_two() {
mapping_page_size
} else {
4096
};
let total_ptes = size / page_size;
let cap_ptes = pte_buf_bytes / 8;
let to_write = if pte_buf.is_null() {
0
} else {
total_ptes.min(cap_ptes)
};
#[cfg(not(nv_rs_edu_guest))]
if to_write > 0 {
use nv_rs_core::uvm::mmu_v2;
let vas_gpu_id = iface.vas_hw_info(va_space).map_or(0, |(gid, _, _, _)| gid);
if let Some((_dev, user_client, user_obj)) = iface.duped_handle_info(duped_handle) {
if let Some((is_video, mem_gpu_id, token_or_vram, total_sz, obj_kind)) =
crate::rmapi_node::lookup_memory(user_client, user_obj)
{
if total_sz > 0 {
let Some(req_end) = offset.checked_add(size) else {
return NvStatus::INVALID_ARGUMENT.0;
};
if req_end > total_sz {
return NvStatus::INVALID_ARGUMENT.0;
}
}
let is_peer_vram =
is_video && vas_gpu_id != 0 && mem_gpu_id != 0 && vas_gpu_id != mem_gpu_id;
let peer_id = if is_peer_vram {
let Some(pid) =
crate::rmapi_node::ensure_p2p_peer_id(vas_gpu_id, mem_gpu_id)
else {
return NV_ERR_NOT_SUPPORTED.0;
};
pid
} else {
0
};
let (mut prot, mut cached) = mmu_v2::decode_external_attrs(
mapping_type,
caching_type,
is_video && !is_peer_vram,
);
if is_peer_vram {
// Peer VRAM (`NV_MMU_VER2_PTE_APERTURE_PEER_MEMORY`): uncached in local L2 (`VOL=1`).
// Preserve `ReadWriteAtomic` (`ATOMIC_DISABLE=0`) over NVLink 2.0 peers (`uvm_volta_mmu.c:178-251`),
// and downgrade to `ReadWrite` (`ATOMIC_DISABLE=1`) only for PCIe P2P peers.
cached = false;
let has_nvlink =
crate::rmapi_node::nvlink_link_count(vas_gpu_id, mem_gpu_id) > 0
&& crate::rmapi_node::nvlink_link_count(mem_gpu_id, vas_gpu_id) > 0;
prot = mmu_v2::peer_protection(prot, has_nvlink);
}
let kind = if is_peer_vram {
mmu_v2::PTE_KIND_PITCH
} else if format_type == 1 {
mmu_v2::PTE_KIND_GENERIC_16BX2
} else {
u64::from(obj_kind)
};
if is_video {
if let Some(alloc_page_size) =
crate::rmapi_node::lookup_video_page_size(user_client, user_obj)
{
if alloc_page_size != 0 && page_size > alloc_page_size {
return NvStatus::INVALID_ARGUMENT.0;
}
}
let Some(map_bytes) = to_write.checked_mul(page_size) else {
return NvStatus::INVALID_ARGUMENT.0;
};
// Preflight every segment before writing any PTE so a rejected
// segment never leaves partially written entries in `pte_buf`.
if let Err(st) = crate::rmapi_node::visit_video_range(
user_client,
user_obj,
offset,
map_bytes,
|seg_delta, seg_phys, seg_len| {
if !seg_delta.is_multiple_of(page_size)
|| !seg_len.is_multiple_of(page_size)
|| !seg_phys.is_multiple_of(page_size)
|| seg_phys.checked_add(seg_len).is_none()
{
return Err(NvStatus::INVALID_ARGUMENT);
}
Ok(())
},
) {
return st.0;
}
if let Err(st) = crate::rmapi_node::visit_video_range(
user_client,
user_obj,
offset,
map_bytes,
|seg_delta, seg_phys, seg_len| {
let start_idx = seg_delta / page_size;
let count = seg_len / page_size;
for j in 0..count {
let Some(phys) = j
.checked_mul(page_size)
.and_then(|d| seg_phys.checked_add(d))
else {
return Err(NvStatus::INVALID_ARGUMENT);
};
let pte = if is_peer_vram {
mmu_v2::make_pte_peer_4k_kind(
phys, peer_id, prot, cached, kind,
)
} else {
mmu_v2::make_pte_4k_kind(phys, true, prot, cached, kind)
};
*pte_buf.add((start_idx + j) as usize) = pte;
}
Ok(())
},
) {
return st.0;
}
} else {
for i in 0..to_write {
let Some(byte_off) =
i.checked_mul(page_size).and_then(|d| offset.checked_add(d))
else {
return NvStatus::INVALID_ARGUMENT.0;
};
let mut p = 0u64;
if nv_rs_rmapi_os_page_dma(
vas_gpu_id,
token_or_vram,
byte_off / 4096,
&mut p,
) != 0
{
return NvStatus::INVALID_ARGUMENT.0;
}
let pte = mmu_v2::make_pte_4k_kind(p, false, prot, cached, kind);
*pte_buf.add(i as usize) = pte;
}
}
}
}
}
*num_written_out = to_write;
*num_remaining_out = total_ptes.saturating_sub(to_write);
NvStatus::OK.0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_get_external_alloc_phys_addrs(
va_space: u64,
duped_handle: u32,
offset: u64,
size: u64,
mapping_page_size: u64,
phys_buf: *mut u64,
phys_buf_bytes: u64,
num_written_out: *mut u64,
num_remaining_out: *mut u64,
) -> u32 {
unsafe {
if num_written_out.is_null() || num_remaining_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
if let Err(st) = iface.get_external_alloc_phys_addrs(va_space, duped_handle, offset, size) {
return st.0;
}
let page_size = if mapping_page_size != 0 && mapping_page_size.is_power_of_two() {
mapping_page_size
} else {
4096
};
let total = size / page_size;
let cap = phys_buf_bytes / 8;
let to_write = if phys_buf.is_null() {
0
} else {
total.min(cap)
};
#[cfg(not(nv_rs_edu_guest))]
if to_write > 0 {
let vas_gpu_id = iface.vas_hw_info(va_space).map_or(0, |(gid, _, _, _)| gid);
if let Some((_dev, user_client, user_obj)) = iface.duped_handle_info(duped_handle) {
if let Some((is_video, _mem_gpu_id, token_or_vram, total_sz, _kind)) =
crate::rmapi_node::lookup_memory(user_client, user_obj)
{
if total_sz > 0 {
let Some(req_end) = offset.checked_add(size) else {
return NvStatus::INVALID_ARGUMENT.0;
};
if req_end > total_sz {
return NvStatus::INVALID_ARGUMENT.0;
}
}
if is_video {
if let Some(alloc_page_size) =
crate::rmapi_node::lookup_video_page_size(user_client, user_obj)
{
if alloc_page_size != 0 && page_size > alloc_page_size {
return NvStatus::INVALID_ARGUMENT.0;
}
}
let Some(map_bytes) = to_write.checked_mul(page_size) else {
return NvStatus::INVALID_ARGUMENT.0;
};
// Preflight every segment before writing any physical address so a
// rejected segment never leaves partial output in `phys_buf`.
if let Err(st) = crate::rmapi_node::visit_video_range(
user_client,
user_obj,
offset,
map_bytes,
|seg_delta, seg_phys, seg_len| {
if !seg_delta.is_multiple_of(page_size)
|| !seg_len.is_multiple_of(page_size)
|| !seg_phys.is_multiple_of(page_size)
|| seg_phys.checked_add(seg_len).is_none()
{
return Err(NvStatus::INVALID_ARGUMENT);
}
Ok(())
},
) {
return st.0;
}
if let Err(st) = crate::rmapi_node::visit_video_range(
user_client,
user_obj,
offset,
map_bytes,
|seg_delta, seg_phys, seg_len| {
let start_idx = seg_delta / page_size;
let count = seg_len / page_size;
for j in 0..count {
let Some(phys) = j
.checked_mul(page_size)
.and_then(|d| seg_phys.checked_add(d))
else {
return Err(NvStatus::INVALID_ARGUMENT);
};
*phys_buf.add((start_idx + j) as usize) = phys;
}
Ok(())
},
) {
return st.0;
}
} else {
for i in 0..to_write {
let Some(byte_off) =
i.checked_mul(page_size).and_then(|d| offset.checked_add(d))
else {
return NvStatus::INVALID_ARGUMENT.0;
};
let mut p = 0u64;
if nv_rs_rmapi_os_page_dma(
vas_gpu_id,
token_or_vram,
byte_off / 4096,
&mut p,
) != 0
{
return NvStatus::INVALID_ARGUMENT.0;
}
*phys_buf.add(i as usize) = p;
}
}
}
}
}
*num_written_out = to_write;
*num_remaining_out = total.saturating_sub(to_write);
NvStatus::OK.0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_get_channel_resource_ptes(
va_space: u64,
resource_descriptor: u64,
offset: u64,
size: u64,
mapping_page_size: u64,
pte_buf: *mut u64,
pte_buf_bytes: u64,
num_written_out: *mut u64,
num_remaining_out: *mut u64,
) -> u32 {
unsafe {
if num_written_out.is_null() || num_remaining_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
if let Err(st) =
iface_mut().get_channel_resource_ptes(va_space, resource_descriptor, offset, size)
{
return st.0;
}
let page_size = if mapping_page_size != 0 && mapping_page_size.is_power_of_two() {
mapping_page_size
} else {
4096
};
let total_ptes = size / page_size;
let cap_ptes = pte_buf_bytes / 8;
let to_write = if pte_buf.is_null() {
0
} else {
total_ptes.min(cap_ptes)
};
if to_write > 0 {
use nv_rs_core::uvm::mmu_v2;
use nv_rs_core::uvm::va_space::Protection;
let Some(base) = resource_descriptor.checked_add(offset) else {
return NvStatus::INVALID_ARGUMENT.0;
};
for i in 0..to_write {
let Some(phys) = i.checked_mul(page_size).and_then(|d| base.checked_add(d)) else {
return NvStatus::INVALID_ARGUMENT.0;
};
let pte = mmu_v2::make_pte_4k(phys, true, Protection::ReadWriteAtomic, true);
*pte_buf.add(i as usize) = pte;
}
}
*num_written_out = to_write;
*num_remaining_out = total_ptes.saturating_sub(to_write);
NvStatus::OK.0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_pma_alloc_pages(
pma: u64,
page_size: u64,
out_pages: *mut u64,
page_count: usize,
) -> u32 {
unsafe {
if out_pages.is_null() && page_count != 0 {
return NvStatus::INVALID_ARGUMENT.0;
}
let pages = if page_count == 0 {
&mut []
} else {
slice::from_raw_parts_mut(out_pages, page_count)
};
let _guard = LockGuard::acquire();
iface_mut().pma_alloc_pages(pma, page_size, pages).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_pma_pin_pages(
pma: u64,
pages_ptr: *const u64,
page_count: usize,
page_size: u64,
) -> u32 {
unsafe {
if pages_ptr.is_null() && page_count != 0 {
return NvStatus::INVALID_ARGUMENT.0;
}
let pages = if page_count == 0 {
&[]
} else {
slice::from_raw_parts(pages_ptr, page_count)
};
let _guard = LockGuard::acquire();
iface_mut().pma_pin_pages(pma, pages, page_size).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_pma_free_pages(
pma: u64,
pages_ptr: *const u64,
page_count: usize,
page_size: u64,
) -> u32 {
unsafe {
if pages_ptr.is_null() && page_count != 0 {
return NvStatus::INVALID_ARGUMENT.0;
}
let pages = if page_count == 0 {
&[]
} else {
slice::from_raw_parts(pages_ptr, page_count)
};
let _guard = LockGuard::acquire();
iface_mut().pma_free_pages(pma, pages, page_size).0
}
}
// ============================================================================
// Confidential Computing CSL Engine (Hopper/Blackwell, 580.178.04 REA-derived)
// Pure `#![no_std]`, zero SIMD, zero heap, bounded stack <= 1024 B.
// Matches `_nv046779rm`, `_nv046784rm`, `_nv046783rm`, `_nv046781rm`, `_nv046780rm`,
// `_nv046785rm`, `_nv046852rm`, `_nv046826rm`, `_nv046829rm`, `_nv018785rm`,
// `_nv018782rm`, `_nv018786rm`, `_nv018787rm`, `_nv018788rm`, `_nv018789rm`,
// `_nv018790rm`, `_nv018792rm`, `_nv029333rm`, `_nv042420rm`, `_nv042419rm`.
// ============================================================================
const CSL_NV_OK: u32 = 0x00;
const CSL_NV_ERR_INSUFFICIENT_RESOURCES: u32 = 0x1a;
const CSL_NV_ERR_INVALID_ARGUMENT: u32 = 0x1f;
const CSL_NV_ERR_INVALID_DATA: u32 = 0x25;
const CSL_MAX_CONTEXTS: usize = 16;
const CSL_KEY_RING_SLOTS: usize = 16;
/// SPDM 1.2 session lifecycle state for Hopper/Blackwell Confidential Computing.
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum SpdmSessionState {
Idle = 0,
VersionNegotiated = 1,
CapabilitiesExchanged = 2,
AlgorithmsNegotiated = 3,
KeyExchanged = 4,
Active = 5,
KeyRotationPending = 6,
Terminated = 7,
}
#[derive(Clone, Copy)]
struct CslKeyRingEntry {
key: [u8; 32],
iv_mask: [u8; 12],
}
impl CslKeyRingEntry {
const fn empty() -> Self {
Self {
key: [0u8; 32],
iv_mask: [0u8; 12],
}
}
}
#[derive(Clone, Copy)]
struct CslContext {
handle: u64,
channel: u64,
active: bool,
/// `0` = 32-bit IV counter (AES-256-GCM / HMAC-SHA256), `1` = 64-bit IV counter (`_nv029333rm`).
mode: u32,
spdm_state: SpdmSessionState,
key_epoch: u32,
iv_epoch: u32,
enc_key: [u8; 32],
enc_iv: [u8; 12],
enc_iv_mask: [u8; 12],
dec_key: [u8; 32],
dec_iv: [u8; 12],
dec_iv_mask: [u8; 12],
/// 32-byte signing nonce/counter (`ctx + 0x30..0x50` in `_nv018792rm`, first 24 bytes LE counter).
sign_iv: [u8; 32],
/// Stats (`ctx + 0xc0` in `_nv018788rm`).
enc_msg_count: u64,
dec_msg_count: u64,
enc_bytes: u64,
dec_bytes: u64,
/// Most recent 16-byte AES-256-GCM authentication tag.
last_tag: [u8; 16],
/// 16-slot key-rotation ring buffer (`(param_5 & 0xf) * 0x2c` in `_nv018782rm`).
key_ring_idx: u8,
key_ring: [CslKeyRingEntry; CSL_KEY_RING_SLOTS],
}
impl CslContext {
const fn empty() -> Self {
Self {
handle: 0,
channel: 0,
active: false,
mode: 0,
spdm_state: SpdmSessionState::Idle,
key_epoch: 0,
iv_epoch: 0,
enc_key: [0u8; 32],
enc_iv: [0u8; 12],
enc_iv_mask: [0u8; 12],
dec_key: [0u8; 32],
dec_iv: [0u8; 12],
dec_iv_mask: [0u8; 12],
sign_iv: [0u8; 32],
enc_msg_count: 0,
dec_msg_count: 0,
enc_bytes: 0,
dec_bytes: 0,
last_tag: [0u8; 16],
key_ring_idx: 0,
key_ring: [CslKeyRingEntry::empty(); CSL_KEY_RING_SLOTS],
}
}
}
/// Scratch buffer in `.bss` (guarded by `nv_rs_rm_api_lock()`) to keep every kernel
/// stack frame well below 1,024 bytes with zero SIMD and zero `memcpy`/`memset`.
struct CslCryptoScratch {
aes_rk: [u32; 60],
sha_w: [u32; 64],
sha_block: [u8; 64],
hmac_ipad: [u8; 64],
hmac_opad: [u8; 64],
}
impl CslCryptoScratch {
const fn new() -> Self {
Self {
aes_rk: [0u32; 60],
sha_w: [0u32; 64],
sha_block: [0u8; 64],
hmac_ipad: [0u8; 64],
hmac_opad: [0u8; 64],
}
}
}
static mut CSL_CONTEXTS: [CslContext; CSL_MAX_CONTEXTS] = [CslContext::empty(); CSL_MAX_CONTEXTS];
static mut CSL_NEXT_HANDLE: u64 = 0x4353_4c00_0000_0001; // "CSL\0..."
static mut CSL_SCRATCH: CslCryptoScratch = CslCryptoScratch::new();
// --- Pure `#![no_std]`, non-SIMD AES-256 (FIPS 197) + GHASH (NIST SP 800-38D) ---
const AES_SBOX: [u8; 256] = [
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
];
const AES_RCON: [u32; 7] = [
0x0100_0000,
0x0200_0000,
0x0400_0000,
0x0800_0000,
0x1000_0000,
0x2000_0000,
0x4000_0000,
];
#[inline(always)]
fn aes_sub_word(w: u32) -> u32 {
((AES_SBOX[((w >> 24) & 0xff) as usize] as u32) << 24)
| ((AES_SBOX[((w >> 16) & 0xff) as usize] as u32) << 16)
| ((AES_SBOX[((w >> 8) & 0xff) as usize] as u32) << 8)
| (AES_SBOX[(w & 0xff) as usize] as u32)
}
#[inline(never)]
fn aes256_expand_key(key: &[u8; 32], rk: &mut [u32; 60]) {
let mut i = 0usize;
while i < 8 {
rk[i] = u32::from_be_bytes([key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]);
i += 1;
}
while i < 60 {
let mut temp = rk[i - 1];
if (i % 8) == 0 {
temp = aes_sub_word(temp.rotate_left(8)) ^ AES_RCON[(i / 8) - 1];
} else if (i % 8) == 4 {
temp = aes_sub_word(temp);
}
rk[i] = rk[i - 8] ^ temp;
i += 1;
}
}
#[inline(always)]
fn gf_xtime(a: u8) -> u8 {
let hi = a & 0x80;
let s = a << 1;
if hi != 0 {
s ^ 0x1b
} else {
s
}
}
#[inline(never)]
fn aes256_encrypt_block(rk: &[u32; 60], input: &[u8; 16], output: &mut [u8; 16]) {
let mut s = [0u8; 16];
let mut i = 0usize;
while i < 16 {
s[i] = input[i];
i += 1;
}
// Initial AddRoundKey
let mut c = 0usize;
while c < 4 {
let w = rk[c].to_be_bytes();
s[4 * c] ^= w[0];
s[4 * c + 1] ^= w[1];
s[4 * c + 2] ^= w[2];
s[4 * c + 3] ^= w[3];
c += 1;
}
let mut round = 1usize;
while round <= 14 {
// SubBytes
let mut b = 0usize;
while b < 16 {
s[b] = AES_SBOX[s[b] as usize];
b += 1;
}
// ShiftRows (column-major state)
let t1 = s[1];
s[1] = s[5];
s[5] = s[9];
s[9] = s[13];
s[13] = t1;
let t2 = s[2];
let t6 = s[6];
s[2] = s[10];
s[6] = s[14];
s[10] = t2;
s[14] = t6;
let t15 = s[15];
s[15] = s[11];
s[11] = s[7];
s[7] = s[3];
s[3] = t15;
// MixColumns (rounds 1..=13)
if round < 14 {
let mut col = 0usize;
while col < 4 {
let idx = col * 4;
let a0 = s[idx];
let a1 = s[idx + 1];
let a2 = s[idx + 2];
let a3 = s[idx + 3];
let t = a0 ^ a1 ^ a2 ^ a3;
s[idx] ^= t ^ gf_xtime(a0 ^ a1);
s[idx + 1] ^= t ^ gf_xtime(a1 ^ a2);
s[idx + 2] ^= t ^ gf_xtime(a2 ^ a3);
s[idx + 3] ^= t ^ gf_xtime(a3 ^ a0);
col += 1;
}
}
// AddRoundKey
let mut col = 0usize;
while col < 4 {
let w = rk[round * 4 + col].to_be_bytes();
s[4 * col] ^= w[0];
s[4 * col + 1] ^= w[1];
s[4 * col + 2] ^= w[2];
s[4 * col + 3] ^= w[3];
col += 1;
}
round += 1;
}
let mut k = 0usize;
while k < 16 {
output[k] = s[k];
k += 1;
}
}
/// GF(2^128) multiplication for NIST SP 800-38D GHASH (`R = 0xe1 || 0^120`).
#[inline(never)]
fn ghash_mul(x: &mut [u8; 16], h: &[u8; 16]) {
let mut z_hi = 0u64;
let mut z_lo = 0u64;
let mut v_hi = u64::from_be_bytes([h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]]);
let mut v_lo = u64::from_be_bytes([h[8], h[9], h[10], h[11], h[12], h[13], h[14], h[15]]);
let mut byte_idx = 0usize;
while byte_idx < 16 {
let mut b = x[byte_idx];
let mut bit = 0u8;
while bit < 8 {
if (b & 0x80) != 0 {
z_hi ^= v_hi;
z_lo ^= v_lo;
}
let lsb = v_lo & 1;
v_lo = (v_lo >> 1) | ((v_hi & 1) << 63);
v_hi >>= 1;
if lsb != 0 {
v_hi ^= 0xe100_0000_0000_0000;
}
b <<= 1;
bit += 1;
}
byte_idx += 1;
}
let hi_b = z_hi.to_be_bytes();
let lo_b = z_lo.to_be_bytes();
let mut i = 0usize;
while i < 8 {
x[i] = hi_b[i];
x[8 + i] = lo_b[i];
i += 1;
}
}
#[inline(never)]
fn ghash_update(acc: &mut [u8; 16], h: &[u8; 16], data: &[u8]) {
let mut off = 0usize;
while off < data.len() {
let take = (data.len() - off).min(16);
let mut i = 0usize;
while i < take {
acc[i] ^= data[off + i];
i += 1;
}
ghash_mul(acc, h);
off += 16;
}
}
#[inline(never)]
unsafe fn ghash_update_ptr(acc: &mut [u8; 16], h: &[u8; 16], data: *const u8, len: usize) {
unsafe {
let mut off = 0usize;
while off < len {
let take = (len - off).min(16);
let mut i = 0usize;
while i < take {
acc[i] ^= *data.add(off + i);
i += 1;
}
ghash_mul(acc, h);
off += 16;
}
}
}
/// Full NIST SP 800-38D AES-256-GCM encryption/decryption (12-byte IV, 16-byte tag),
/// matching `_nv042420rm` / `_nv042419rm` bit-for-bit.
///
/// Uses raw pointers so in-place (`input == output`) calls do not create aliasing
/// `&[u8]` / `&mut [u8]` references.
#[inline(never)]
unsafe fn aes256_gcm_crypt(
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
input: *const u8,
output: *mut u8,
len: usize,
encrypt: bool,
tag_out: &mut [u8; 16],
) {
unsafe {
let scratch = &mut *ptr::addr_of_mut!(CSL_SCRATCH);
aes256_expand_key(key, &mut scratch.aes_rk);
let zero = [0u8; 16];
let mut h = [0u8; 16];
aes256_encrypt_block(&scratch.aes_rk, &zero, &mut h);
let mut j0 = [0u8; 16];
let mut i = 0usize;
while i < 12 {
j0[i] = nonce[i];
i += 1;
}
j0[15] = 1;
let mut ghash = [0u8; 16];
ghash_update(&mut ghash, &h, aad);
if !encrypt {
ghash_update_ptr(&mut ghash, &h, input, len);
}
// GCTR starting at inc32(J0) = counter 2
let mut ctr = j0;
let mut ctr_val = 2u32;
let mut off = 0usize;
let mut ks = [0u8; 16];
while off < len {
let cb = ctr_val.to_be_bytes();
ctr[12] = cb[0];
ctr[13] = cb[1];
ctr[14] = cb[2];
ctr[15] = cb[3];
aes256_encrypt_block(&scratch.aes_rk, &ctr, &mut ks);
let take = (len - off).min(16);
let mut j = 0usize;
while j < take {
*output.add(off + j) = *input.add(off + j) ^ ks[j];
j += 1;
}
off += 16;
ctr_val = ctr_val.wrapping_add(1);
}
if encrypt {
ghash_update_ptr(&mut ghash, &h, output as *const u8, len);
}
// Final length block: len(AAD)*8 || len(C)*8 (64-bit big-endian each)
let mut len_blk = [0u8; 16];
let aad_bits = ((aad.len() as u64) * 8).to_be_bytes();
let msg_bits = ((len as u64) * 8).to_be_bytes();
let mut k = 0usize;
while k < 8 {
len_blk[k] = aad_bits[k];
len_blk[8 + k] = msg_bits[k];
k += 1;
}
ghash_update(&mut ghash, &h, &len_blk);
let mut s_mask = [0u8; 16];
aes256_encrypt_block(&scratch.aes_rk, &j0, &mut s_mask);
let mut m = 0usize;
while m < 16 {
tag_out[m] = ghash[m] ^ s_mask[m];
m += 1;
}
}
}
// --- Pure `#![no_std]`, non-SIMD SHA-256 & HMAC-SHA256 (FIPS 180-4 / 198-1) ---
const SHA256_K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
struct Sha256State {
h: [u32; 8],
buf_len: usize,
total_len: u64,
}
impl Sha256State {
const fn new() -> Self {
Self {
h: [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
],
buf_len: 0,
total_len: 0,
}
}
#[inline(never)]
fn compress(&mut self, block: &[u8; 64], w: &mut [u32; 64]) {
let mut i = 0usize;
while i < 16 {
w[i] = u32::from_be_bytes([
block[4 * i],
block[4 * i + 1],
block[4 * i + 2],
block[4 * i + 3],
]);
i += 1;
}
while i < 64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
i += 1;
}
let mut a = self.h[0];
let mut b = self.h[1];
let mut c = self.h[2];
let mut d = self.h[3];
let mut e = self.h[4];
let mut f = self.h[5];
let mut g = self.h[6];
let mut h = self.h[7];
let mut r = 0usize;
while r < 64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ ((!e) & g);
let t1 = h
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(SHA256_K[r])
.wrapping_add(w[r]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let t2 = s0.wrapping_add(maj);
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
r += 1;
}
self.h[0] = self.h[0].wrapping_add(a);
self.h[1] = self.h[1].wrapping_add(b);
self.h[2] = self.h[2].wrapping_add(c);
self.h[3] = self.h[3].wrapping_add(d);
self.h[4] = self.h[4].wrapping_add(e);
self.h[5] = self.h[5].wrapping_add(f);
self.h[6] = self.h[6].wrapping_add(g);
self.h[7] = self.h[7].wrapping_add(h);
}
#[inline(never)]
fn update(&mut self, data: &[u8], blk: &mut [u8; 64], w: &mut [u32; 64]) {
self.total_len = self.total_len.wrapping_add(data.len() as u64);
let mut i = 0usize;
while i < data.len() {
blk[self.buf_len] = data[i];
self.buf_len += 1;
if self.buf_len == 64 {
self.compress(blk, w);
self.buf_len = 0;
}
i += 1;
}
}
#[inline(never)]
fn finalize(mut self, blk: &mut [u8; 64], w: &mut [u32; 64], out: &mut [u8; 32]) {
let bit_len = self.total_len.wrapping_mul(8);
blk[self.buf_len] = 0x80;
self.buf_len += 1;
if self.buf_len > 56 {
while self.buf_len < 64 {
unsafe { ptr::write_volatile(&mut blk[self.buf_len], 0) };
self.buf_len += 1;
}
self.compress(blk, w);
self.buf_len = 0;
}
while self.buf_len < 56 {
unsafe { ptr::write_volatile(&mut blk[self.buf_len], 0) };
self.buf_len += 1;
}
let lb = bit_len.to_be_bytes();
let mut j = 0usize;
while j < 8 {
blk[56 + j] = lb[j];
j += 1;
}
self.compress(blk, w);
let mut i = 0usize;
while i < 8 {
let hb = self.h[i].to_be_bytes();
out[4 * i] = hb[0];
out[4 * i + 1] = hb[1];
out[4 * i + 2] = hb[2];
out[4 * i + 3] = hb[3];
i += 1;
}
}
}
/// Computes HMAC-SHA256(key[32], msg1 || msg2) matching `_nv018792rm` (`_nv042553rm`..`_nv042551rm`).
#[inline(never)]
unsafe fn hmac_sha256_two(key: &[u8; 32], msg1: &[u8], msg2: &[u8], out: &mut [u8; 32]) {
unsafe {
let scratch = &mut *ptr::addr_of_mut!(CSL_SCRATCH);
let mut i = 0usize;
while i < 64 {
let kb = if i < 32 { key[i] } else { 0 };
scratch.hmac_ipad[i] = kb ^ 0x36;
scratch.hmac_opad[i] = kb ^ 0x5c;
i += 1;
}
let mut inner = Sha256State::new();
inner.update(
&scratch.hmac_ipad,
&mut scratch.sha_block,
&mut scratch.sha_w,
);
inner.update(msg1, &mut scratch.sha_block, &mut scratch.sha_w);
inner.update(msg2, &mut scratch.sha_block, &mut scratch.sha_w);
let mut inner_hash = [0u8; 32];
inner.finalize(&mut scratch.sha_block, &mut scratch.sha_w, &mut inner_hash);
let mut outer = Sha256State::new();
outer.update(
&scratch.hmac_opad,
&mut scratch.sha_block,
&mut scratch.sha_w,
);
outer.update(&inner_hash, &mut scratch.sha_block, &mut scratch.sha_w);
outer.finalize(&mut scratch.sha_block, &mut scratch.sha_w, out);
}
}
#[inline(never)]
unsafe fn csl_derive_material(channel: u64, epoch: u32, label: u8, out: &mut [u8; 32]) {
unsafe {
let scratch = &mut *ptr::addr_of_mut!(CSL_SCRATCH);
let mut seed = [0u8; 16];
let ch_b = channel.to_le_bytes();
let ep_b = epoch.to_le_bytes();
let mut i = 0usize;
while i < 8 {
seed[i] = ch_b[i];
i += 1;
}
seed[8] = ep_b[0];
seed[9] = ep_b[1];
seed[10] = ep_b[2];
seed[11] = ep_b[3];
seed[12] = label;
seed[13] = 0x53; // 'S'
seed[14] = 0x50; // 'P'
seed[15] = 0x44; // 'D'
let mut st = Sha256State::new();
st.update(&seed, &mut scratch.sha_block, &mut scratch.sha_w);
st.finalize(&mut scratch.sha_block, &mut scratch.sha_w, out);
}
}
#[inline(always)]
fn csl_iv_counter_and_max(mode: u32, iv: &[u8; 12]) -> (u64, u64) {
if mode == 0 {
let cur = u32::from_le_bytes([iv[0], iv[1], iv[2], iv[3]]) as u64;
(cur, 0xffff_ffffu64)
} else if mode == 1 {
let cur = u64::from_le_bytes([iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]]);
(cur, u64::MAX)
} else {
(0, 0)
}
}
/// Exact `_nv018786rm` IV increment with overflow protection.
#[inline(always)]
fn csl_increment_iv_raw(mode: u32, iv: &mut [u8; 12], increment: u64) -> Result<u64, u32> {
if mode == 0 {
if increment > 0xffff_ffff {
return Err(CSL_NV_ERR_INVALID_ARGUMENT);
}
let cur = u32::from_le_bytes([iv[0], iv[1], iv[2], iv[3]]) as u64;
if cur > 0xffff_ffffu64 - increment {
return Err(CSL_NV_ERR_INSUFFICIENT_RESOURCES);
}
let next = (cur + increment) as u32;
let b = next.to_le_bytes();
iv[0] = b[0];
iv[1] = b[1];
iv[2] = b[2];
iv[3] = b[3];
Ok(next as u64)
} else if mode == 1 {
let cur = u64::from_le_bytes([iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]]);
if cur > u64::MAX - increment {
return Err(CSL_NV_ERR_INSUFFICIENT_RESOURCES);
}
let next = cur + increment;
let b = next.to_le_bytes();
let mut i = 0usize;
while i < 8 {
iv[i] = b[i];
i += 1;
}
Ok(next)
} else {
Ok(0)
}
}
#[inline(never)]
unsafe fn csl_find_mut(handle: u64) -> Option<&'static mut CslContext> {
unsafe {
if handle == 0 {
return None;
}
let table = &mut *ptr::addr_of_mut!(CSL_CONTEXTS);
let mut i = 0usize;
while i < CSL_MAX_CONTEXTS {
if table[i].active && table[i].handle == handle {
return Some(&mut table[i]);
}
i += 1;
}
None
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_csl_init_context(
channel: u64,
csl_ctx_out: *mut u64,
) -> u32 {
unsafe {
if channel == 0 || csl_ctx_out.is_null() {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
let _guard = LockGuard::acquire();
let table = &mut *ptr::addr_of_mut!(CSL_CONTEXTS);
let mut slot = None;
let mut i = 0usize;
while i < CSL_MAX_CONTEXTS {
if !table[i].active {
slot = Some(i);
break;
}
i += 1;
}
let Some(idx) = slot else {
return CSL_NV_ERR_INSUFFICIENT_RESOURCES;
};
let handle = *ptr::addr_of!(CSL_NEXT_HANDLE);
*ptr::addr_of_mut!(CSL_NEXT_HANDLE) = handle.wrapping_add(1).max(1);
let ctx = &mut table[idx];
ctx.handle = handle;
ctx.channel = channel;
ctx.active = true;
ctx.mode = 0;
ctx.spdm_state = SpdmSessionState::Active;
ctx.key_epoch = 1;
ctx.iv_epoch = 1;
ctx.enc_msg_count = 0;
ctx.dec_msg_count = 0;
ctx.enc_bytes = 0;
ctx.dec_bytes = 0;
ctx.key_ring_idx = 0;
let mut enc_k = [0u8; 32];
let mut dec_k = [0u8; 32];
let mut iv_mat = [0u8; 32];
csl_derive_material(channel, 1, 0x01, &mut enc_k);
csl_derive_material(channel, 1, 0x02, &mut dec_k);
csl_derive_material(channel, 1, 0x03, &mut iv_mat);
let mut j = 0usize;
while j < 32 {
ctx.enc_key[j] = enc_k[j];
ctx.dec_key[j] = dec_k[j];
ctx.sign_iv[j] = 0;
j += 1;
}
let mut m = 0usize;
while m < 12 {
ctx.enc_iv[m] = 0;
ctx.dec_iv[m] = 0;
ctx.enc_iv_mask[m] = iv_mat[m];
ctx.dec_iv_mask[m] = iv_mat[12 + m];
m += 1;
}
*csl_ctx_out = handle;
CSL_NV_OK
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_deinit_csl_context(csl_ctx: u64) -> u32 {
unsafe {
if csl_ctx == 0 {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
let _guard = LockGuard::acquire();
let Some(ctx) = csl_find_mut(csl_ctx) else {
return CSL_NV_ERR_INVALID_ARGUMENT;
};
let mut i = 0usize;
while i < 32 {
ctx.enc_key[i] = 0;
ctx.dec_key[i] = 0;
ctx.sign_iv[i] = 0;
i += 1;
}
let mut j = 0usize;
while j < 12 {
ctx.enc_iv[j] = 0;
ctx.dec_iv[j] = 0;
ctx.enc_iv_mask[j] = 0;
ctx.dec_iv_mask[j] = 0;
j += 1;
}
ctx.spdm_state = SpdmSessionState::Terminated;
ctx.active = false;
ctx.handle = 0;
CSL_NV_OK
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_csl_rotate_key(
ctx_handles: *const u64,
count: usize,
) -> u32 {
unsafe {
if ctx_handles.is_null() || count == 0 {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
let handles = slice::from_raw_parts(ctx_handles, count);
let _guard = LockGuard::acquire();
// Validate all handles first (matching `_nv046784rm` pre-loop null/validity check).
let mut i = 0usize;
while i < handles.len() {
if csl_find_mut(handles[i]).is_none() {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
i += 1;
}
// Rotate in batches of up to 0x40 (64) matching `_nv046784rm`.
let mut idx = 0usize;
while idx < handles.len() {
if let Some(ctx) = csl_find_mut(handles[idx]) {
ctx.spdm_state = SpdmSessionState::KeyRotationPending;
// Archive prior decrypt key + IV mask into 16-slot ring (`param_5 & 0xf` in `_nv018782rm`).
let slot = (ctx.key_ring_idx as usize) & (CSL_KEY_RING_SLOTS - 1);
let mut k = 0usize;
while k < 32 {
ctx.key_ring[slot].key[k] = ctx.dec_key[k];
k += 1;
}
let mut m = 0usize;
while m < 12 {
ctx.key_ring[slot].iv_mask[m] = ctx.dec_iv_mask[m];
m += 1;
}
ctx.key_ring_idx = ctx.key_ring_idx.wrapping_add(1);
ctx.key_epoch = ctx.key_epoch.wrapping_add(1);
let mut enc_k = [0u8; 32];
let mut dec_k = [0u8; 32];
let mut iv_mat = [0u8; 32];
csl_derive_material(ctx.channel, ctx.key_epoch, 0x01, &mut enc_k);
csl_derive_material(ctx.channel, ctx.key_epoch, 0x02, &mut dec_k);
csl_derive_material(ctx.channel, ctx.key_epoch, 0x03, &mut iv_mat);
let mut j = 0usize;
while j < 32 {
ctx.enc_key[j] = enc_k[j];
ctx.dec_key[j] = dec_k[j];
ctx.sign_iv[j] = 0;
j += 1;
}
let mut n = 0usize;
while n < 12 {
ctx.enc_iv[n] = 0;
ctx.dec_iv[n] = 0;
ctx.enc_iv_mask[n] = iv_mat[n];
ctx.dec_iv_mask[n] = iv_mat[12 + n];
n += 1;
}
ctx.spdm_state = SpdmSessionState::Active;
}
idx += 1;
}
CSL_NV_OK
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_csl_rotate_iv(csl_ctx: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
let Some(ctx) = csl_find_mut(csl_ctx) else {
return CSL_NV_ERR_INVALID_ARGUMENT;
};
if ctx.mode != 0 {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
ctx.iv_epoch = ctx.iv_epoch.wrapping_add(1);
let mut iv_mat = [0u8; 32];
csl_derive_material(ctx.channel, ctx.key_epoch ^ ctx.iv_epoch, 0x04, &mut iv_mat);
let mut i = 0usize;
while i < 12 {
ctx.enc_iv[i] = 0;
ctx.dec_iv[i] = 0;
ctx.enc_iv_mask[i] = iv_mat[i];
ctx.dec_iv_mask[i] = iv_mat[12 + i];
i += 1;
}
CSL_NV_OK
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_csl_increment_iv(
csl_ctx: u64,
increment: u64,
new_iv_out: *mut u64,
) -> u32 {
unsafe {
if new_iv_out.is_null() {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
let _guard = LockGuard::acquire();
let Some(ctx) = csl_find_mut(csl_ctx) else {
return CSL_NV_ERR_INVALID_ARGUMENT;
};
match csl_increment_iv_raw(ctx.mode, &mut ctx.enc_iv, increment) {
Ok(v) => {
*new_iv_out = v;
CSL_NV_OK
}
Err(st) => st,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_csl_query_message_pool(
csl_ctx: u64,
remaining_out: *mut u64,
) -> u32 {
unsafe {
if remaining_out.is_null() {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
let _guard = LockGuard::acquire();
let Some(ctx) = csl_find_mut(csl_ctx) else {
return CSL_NV_ERR_INVALID_ARGUMENT;
};
let (cur, max) = csl_iv_counter_and_max(ctx.mode, &ctx.enc_iv);
*remaining_out = max.saturating_sub(cur);
CSL_NV_OK
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_csl_log_encryption(csl_ctx: u64, buffer_size: u32) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
let Some(ctx) = csl_find_mut(csl_ctx) else {
return CSL_NV_ERR_INVALID_ARGUMENT;
};
let (cur, max) = csl_iv_counter_and_max(ctx.mode, &ctx.enc_iv);
if cur == max {
return CSL_NV_ERR_INSUFFICIENT_RESOURCES;
}
ctx.enc_msg_count = ctx.enc_msg_count.wrapping_add(1);
ctx.enc_bytes = ctx.enc_bytes.wrapping_add(buffer_size as u64);
CSL_NV_OK
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_csl_encrypt(
csl_ctx: u64,
input: *const u8,
output: *mut u8,
len: usize,
) -> u32 {
unsafe {
if input.is_null() || output.is_null() || len == 0 {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
let _guard = LockGuard::acquire();
let Some(ctx) = csl_find_mut(csl_ctx) else {
return CSL_NV_ERR_INVALID_ARGUMENT;
};
if csl_increment_iv_raw(ctx.mode, &mut ctx.enc_iv, 1).is_err() {
return CSL_NV_ERR_INSUFFICIENT_RESOURCES;
}
let mut nonce = [0u8; 12];
let mut i = 0usize;
while i < 12 {
nonce[i] = ctx.enc_iv[i] ^ ctx.enc_iv_mask[i];
i += 1;
}
let mut tag = [0u8; 16];
aes256_gcm_crypt(&ctx.enc_key, &nonce, &[], input, output, len, true, &mut tag);
let mut j = 0usize;
while j < 16 {
ctx.last_tag[j] = tag[j];
j += 1;
}
ctx.enc_msg_count = ctx.enc_msg_count.wrapping_add(1);
ctx.enc_bytes = ctx.enc_bytes.wrapping_add(len as u64);
CSL_NV_OK
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_csl_decrypt(
csl_ctx: u64,
input: *const u8,
output: *mut u8,
len: usize,
) -> u32 {
unsafe {
if input.is_null() || output.is_null() || len == 0 {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
let _guard = LockGuard::acquire();
let Some(ctx) = csl_find_mut(csl_ctx) else {
return CSL_NV_ERR_INVALID_ARGUMENT;
};
if csl_increment_iv_raw(ctx.mode, &mut ctx.dec_iv, 1).is_err() {
return CSL_NV_ERR_INSUFFICIENT_RESOURCES;
}
let mut nonce = [0u8; 12];
let mut i = 0usize;
while i < 12 {
nonce[i] = ctx.dec_iv[i] ^ ctx.dec_iv_mask[i];
i += 1;
}
let mut tag = [0u8; 16];
aes256_gcm_crypt(
&ctx.dec_key,
&nonce,
&[],
input,
output,
len,
false,
&mut tag,
);
let mut j = 0usize;
while j < 16 {
ctx.last_tag[j] = tag[j];
j += 1;
}
ctx.dec_msg_count = ctx.dec_msg_count.wrapping_add(1);
ctx.dec_bytes = ctx.dec_bytes.wrapping_add(len as u64);
CSL_NV_OK
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_get_p2p_caps(
dev_a: u64,
dev_b: u64,
out_caps: *mut UvmGpuP2PCapsParams,
) -> u32 {
unsafe {
if out_caps.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
let iface = iface_mut();
let (peer_a, peer_b, nvlink_links) =
match (iface.device_hw_ids(dev_a), iface.device_hw_ids(dev_b)) {
(Some((g_a, _)), Some((g_b, _))) if g_a != 0 && g_b != 0 && g_a != g_b => {
let nvl = crate::rmapi_node::nvlink_link_count(g_a, g_b);
match crate::rmapi_node::p2p_peer_ids(g_a, g_b) {
Some((pa, pb)) => (u32::from(pa), u32::from(pb), nvl),
None => (INVALID_PEER_ID, INVALID_PEER_ID, nvl),
}
}
_ => (INVALID_PEER_ID, INVALID_PEER_ID, 0),
};
let link = PeerLink {
link_type: if nvlink_links > 0 {
UvmLinkType::NvLink2
} else {
UvmLinkType::Pcie
},
peer_id_a_to_b: peer_a,
peer_id_b_to_a: peer_b,
egm_peer_id_a_to_b: INVALID_PEER_ID,
egm_peer_id_b_to_a: INVALID_PEER_ID,
optimal_write_ce_a: 0,
optimal_write_ce_b: 0,
total_line_rate_mbps: if nvlink_links > 0 {
nvlink_links * 25_781
} else {
16_000
},
bar1_dma_addr: [0; 2],
bar1_dma_size: [0; 2],
};
match iface.get_p2p_caps(dev_a, dev_b, link) {
Ok(caps) => {
*out_caps = caps;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_csl_sign(
csl_ctx: u64,
input: *const u8,
len: usize,
auth_tag_out: *mut [u8; 16],
) -> u32 {
unsafe {
if auth_tag_out.is_null() || input.is_null() || len == 0 {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
let inp = slice::from_raw_parts(input, len);
let _guard = LockGuard::acquire();
let Some(ctx) = csl_find_mut(csl_ctx) else {
return CSL_NV_ERR_INVALID_ARGUMENT;
};
if ctx.mode != 0 {
return CSL_NV_ERR_INVALID_ARGUMENT;
}
// Exact `_nv018792rm` 24-byte LE counter check & increment (`ctx + 0x30..0x48`).
let mut all_ff = true;
let mut i = 0usize;
while i < 24 {
if ctx.sign_iv[i] != 0xff {
all_ff = false;
break;
}
i += 1;
}
if all_ff {
return CSL_NV_ERR_INSUFFICIENT_RESOURCES;
}
let mut carry = 1u8;
let mut j = 0usize;
while j < 24 {
let (v, ovf) = ctx.sign_iv[j].overflowing_add(carry);
ctx.sign_iv[j] = v;
carry = if ovf { 1 } else { 0 };
j += 1;
}
let mut mac = [0u8; 32];
hmac_sha256_two(&ctx.dec_key, inp, &ctx.sign_iv, &mut mac);
let out = &mut *auth_tag_out;
let mut k = 0usize;
while k < 16 {
out[k] = mac[k];
k += 1;
}
let _ = CSL_NV_ERR_INVALID_DATA;
CSL_NV_OK
}
}
// ---- R620 nvUvmInterface* extensions (5 new symbols) ----
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_access_bits_buf_alloc(
device: u64,
handle_out: *mut u64,
) -> u32 {
unsafe {
if handle_out.is_null() {
return NvStatus::INVALID_ARGUMENT.0;
}
let _guard = LockGuard::acquire();
match iface_mut().access_bits_buf_alloc(device) {
Ok(h) => {
*handle_out = h;
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_access_bits_buf_free(device: u64, handle: u64) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().access_bits_buf_free(device, handle).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_access_bits_buf_dump(
device: u64,
handle: u64,
count_out: *mut u32,
) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
match iface_mut().access_bits_buf_dump(device, handle) {
Ok(n) => {
if !count_out.is_null() {
*count_out = n;
}
NvStatus::OK.0
}
Err(st) => st.0,
}
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_register_uvm_events(cookie: usize) -> u32 {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().register_uvm_events(cookie).0
}
}
#[unsafe(no_mangle)]
#[inline(never)]
pub unsafe extern "C" fn nv_rs_uvm_iface_deregister_uvm_events() {
unsafe {
let _guard = LockGuard::acquire();
iface_mut().deregister_uvm_events();
}
}