Files
nvdriver/docs/pascal-validation-2026-12-03/pascal-userd-upstream-9d327bf.patch
2026-12-03 06:19:52 +00:00

1850 lines
74 KiB
Diff
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

diff --git a/kernel-open/nvidia/pci_driver.c b/kernel-open/nvidia/pci_driver.c
index eabd394f..899c48e7 100644
--- a/kernel-open/nvidia/pci_driver.c
+++ b/kernel-open/nvidia/pci_driver.c
@@ -169,8 +169,10 @@ static int nv_rs_pm_do_suspend(struct device *dev, u32 action)
nv_rs_modeset_notify_suspend(gpu_id);
if (nv_rs_gpu_pm_verify_alive(gpu) == 0)
nv_rs_gpu_owner_runtime_stop(owner);
- else
+ else {
+ nv_rs_rmapi_revoke_runtime_userd(gpu_id);
dev_warn(dev, "GPU appears lost during PM suspend; skipping engine teardown\n");
+ }
pci_save_state(pdev);
pci_disable_device(pdev);
diff --git a/kernel-open/nvidia/rmapi_node.c b/kernel-open/nvidia/rmapi_node.c
index 235820f2..23906edf 100644
--- a/kernel-open/nvidia/rmapi_node.c
+++ b/kernel-open/nvidia/rmapi_node.c
@@ -191,6 +191,14 @@ struct nv_rs_rmapi_file {
* must not count for a later GPU that reuses the minor number. */
unsigned int generation;
struct file *control;
+ struct file *file;
+ struct file *userd_control;
+ unsigned long userd_pgoff;
+ u32 userd_gpu_id;
+ u32 userd_block;
+ /* One reference per successful RM map, protected by the USERD lock. */
+ u32 userd_map_refs;
+ struct list_head userd_link;
wait_queue_head_t wait;
/* bit 0 = a dataless OS event was posted to this file (nv_rs_rmapi_file_post) */
unsigned long events;
@@ -200,6 +208,7 @@ struct nv_rs_rmapi_gpu_node {
char name[32];
char bdf[32];
bool live;
+ bool pascal_userd_gpu;
unsigned int generation;
/* Register access of the GPU (nv_rs_rmapi_node_gpu_reader); NULL without one. */
int (*read32)(void *cookie, u64 offset, u32 *value);
@@ -225,16 +234,22 @@ static DECLARE_WAIT_QUEUE_HEAD(nv_rs_rmapi_owner_wq);
static struct nv_rs_rmapi_gpu_node nv_rs_rmapi_gpu_nodes[NV_RS_RMAPI_MAX_GPUS];
static DEFINE_SPINLOCK(nv_rs_rmapi_gpu_dev_lock);
static DEFINE_MUTEX(nv_rs_rmapi_alloc_lock);
+/* Order: RM lock (if held) -> USERD lock -> allocation lock. Faults never take the RM lock. */
+static DEFINE_MUTEX(nv_rs_rmapi_userd_lock);
+static LIST_HEAD(nv_rs_rmapi_userd_files);
+static unsigned long nv_rs_rmapi_userd_last_pgoff;
static const struct file_operations nv_rs_rmapi_operations;
static const struct file_operations nv_rs_rmapi_gpu_operations;
-static struct nv_rs_rmapi_file *nv_rs_rmapi_context(int gpu)
+static struct nv_rs_rmapi_file *nv_rs_rmapi_context(struct file *file, int gpu)
{
struct nv_rs_rmapi_file *context = kzalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return NULL;
context->owner = (u64)(unsigned long)context;
context->gpu = gpu;
+ context->file = file;
+ INIT_LIST_HEAD(&context->userd_link);
init_waitqueue_head(&context->wait);
return context;
}
@@ -762,6 +777,10 @@ u32 nv_rs_rmapi_os_kernel_map(u64 token, u64 size);
void nv_rs_rmapi_os_kernel_unmap(u64 token);
u32 nv_rs_rmapi_os_user_map(u64 token, u64 page_index, u32 page_offset, u64 *address);
u32 nv_rs_rmapi_os_match_offset(u64 token, u64 address, u64 *page_index);
+u32 nv_rs_rmapi_os_map_pascal_userd(u32 gpu_id, u64 offset, u64 length, s32 descriptor,
+ u64 owner, u32 block, u64 *address, u64 *cookie);
+void nv_rs_rmapi_os_unmap_pascal_userd(u64 cookie);
+bool nv_rs_rmapi_userd_block_available(u32 gpu_id, u32 block, u64 owner);
u32 nv_rs_rmapi_os_add_context(s32 descriptor, u32 protection, u64 token, u64 page_index,
u32 caching);
u32 nv_rs_rmapi_os_map_register(u32 gpu_id, u64 offset, u64 length, bool write_only,
@@ -1379,6 +1398,9 @@ u32 nv_rs_rmapi_os_map_video(u32 gpu_id, u64 offset, u64 length, s32 descriptor,
status = NV_RS_STATUS_INVALID_ARGUMENT;
} else if (!nv_rs_rmapi_context_on_gpu(context, gpu_id)) {
status = NV_RS_STATUS_INVALID_ARGUMENT;
+ } else if (nv_rs_rmapi_gpu_nodes[context->gpu].pascal_userd_gpu && nv_rs_runtime_engines()) {
+ /* Do not create an identity-window mapping before or after BAR1 takeover. */
+ status = 0x56; /* NV_ERR_NOT_SUPPORTED */
} else if (!nv_rs_gpu_slot_validate_bar1((u32)context->gpu, context->generation,
aligned_off, aligned_len, offset,
&io_phys, &user_addr)) {
@@ -1399,6 +1421,153 @@ u32 nv_rs_rmapi_os_map_video(u32 gpu_id, u64 offset, u64 length, s32 descriptor,
return status;
}
+static bool nv_rs_userd_block_available_locked(u32 gpu_id, u32 block, u64 owner)
+{
+ const struct nv_rs_rmapi_file *context;
+
+ list_for_each_entry(context, &nv_rs_rmapi_userd_files, userd_link) {
+ if (context->userd_gpu_id == gpu_id && context->userd_block == block &&
+ (u64)(unsigned long)context->userd_control->private_data != owner)
+ return false;
+ }
+ return true;
+}
+
+bool nv_rs_rmapi_userd_block_available(u32 gpu_id, u32 block, u64 owner)
+{
+ bool available;
+
+ mutex_lock(&nv_rs_rmapi_userd_lock);
+ available = nv_rs_userd_block_available_locked(gpu_id, block, owner);
+ mutex_unlock(&nv_rs_rmapi_userd_lock);
+ return available;
+}
+
+u32 nv_rs_rmapi_os_map_pascal_userd(u32 gpu_id, u64 offset, u64 length, s32 descriptor,
+ u64 owner, u32 block, u64 *address, u64 *cookie)
+{
+ struct nv_rs_rmapi_file *source = (struct nv_rs_rmapi_file *)(unsigned long)owner;
+ struct nv_rs_rmapi_file *context;
+ struct file *target;
+ u64 io_phys, user_addr;
+ u32 status = NV_RS_STATUS_INVALID_ARGUMENT;
+
+ if (!source || source->gpu != -1 || PAGE_SIZE != 4096 || !address || !cookie ||
+ !length || length > 0x200 - (offset & 0x1ff) ||
+ (offset & PAGE_MASK) != 0x200000ULL + (u64)block * PAGE_SIZE)
+ return status;
+ target = fget(descriptor);
+ if (!target)
+ return status;
+ if (target->f_op != &nv_rs_rmapi_gpu_operations)
+ goto put;
+ context = target->private_data;
+ /* Libcuda can open a dedicated GPU file without REGISTER_FD. Pin its
+ * verified RM owner only after validating the GPU, generation and BAR1. */
+ if (!context || (context->control && context->control != source->file) ||
+ !nv_rs_rmapi_context_on_gpu(context, gpu_id) ||
+ !nv_rs_gpu_slot_validate_bar1((u32)context->gpu, context->generation,
+ offset & PAGE_MASK, PAGE_SIZE, offset,
+ &io_phys, &user_addr) ||
+ !IS_ALIGNED(io_phys, PAGE_SIZE))
+ goto put;
+
+ mutex_lock(&nv_rs_rmapi_userd_lock);
+ if (context->userd_pgoff) {
+ /* The same file and live generation were validated above. The whole
+ * page is shared, so the pinned owner and block must also match.
+ * A fully revoked file stays retired for any old, faultable VMAs. */
+ if (!context->userd_map_refs || context->userd_map_refs == U32_MAX ||
+ context->userd_control != source->file ||
+ context->userd_gpu_id != gpu_id || context->userd_block != block) {
+ goto unlock;
+ } else {
+ context->userd_map_refs++;
+ *address = user_addr;
+ *cookie = context->userd_pgoff;
+ status = 0;
+ }
+ } else if (nv_rs_rmapi_userd_last_pgoff < (MAX_LFS_FILESIZE >> PAGE_SHIFT) - 1 &&
+ nv_rs_userd_block_available_locked(gpu_id, block, owner)) {
+ int rc;
+
+ mutex_lock(&nv_rs_rmapi_alloc_lock);
+ rc = nv_rs_file_map_insert_io(context->owner, io_phys, PAGE_SIZE, 3, 2);
+ if (!rc) {
+ /* The GPU file survives all its VMAs. Keep the owner token unique
+ * until that file goes away, even if its descriptor was closed. */
+ context->userd_control = get_file(source->file);
+ context->userd_gpu_id = gpu_id;
+ context->userd_block = block;
+ context->userd_map_refs = 1;
+ context->userd_pgoff = ++nv_rs_rmapi_userd_last_pgoff;
+ list_add_tail(&context->userd_link, &nv_rs_rmapi_userd_files);
+ *address = user_addr;
+ *cookie = context->userd_pgoff;
+ status = 0;
+ }
+ mutex_unlock(&nv_rs_rmapi_alloc_lock);
+ }
+unlock:
+ mutex_unlock(&nv_rs_rmapi_userd_lock);
+put:
+ fput(target);
+ return status;
+}
+
+/* PFNs are faulted in only after VMA insertion. Holding the same lock here
+ * prevents a fault from reinstalling a PFN after the zap. The internal page
+ * offset is unique even when GPU files share the same inode. */
+static void nv_rs_rmapi_revoke_userd_locked(struct nv_rs_rmapi_file *context)
+{
+ unmap_mapping_range(context->file->f_mapping,
+ (loff_t)context->userd_pgoff << PAGE_SHIFT, PAGE_SIZE, 1);
+ list_del_init(&context->userd_link);
+ context->userd_map_refs = 0;
+ fput(context->userd_control);
+ context->userd_control = NULL;
+}
+
+void nv_rs_rmapi_os_unmap_pascal_userd(u64 cookie)
+{
+ struct nv_rs_rmapi_file *context;
+
+ mutex_lock(&nv_rs_rmapi_userd_lock);
+ list_for_each_entry(context, &nv_rs_rmapi_userd_files, userd_link) {
+ if (context->userd_pgoff == cookie) {
+ if (--context->userd_map_refs == 0)
+ nv_rs_rmapi_revoke_userd_locked(context);
+ break;
+ }
+ }
+ mutex_unlock(&nv_rs_rmapi_userd_lock);
+}
+
+static void nv_rs_rmapi_revoke_gpu_userd(int minor, u32 generation)
+{
+ struct nv_rs_rmapi_file *context, *next;
+
+ mutex_lock(&nv_rs_rmapi_userd_lock);
+ list_for_each_entry_safe(context, next, &nv_rs_rmapi_userd_files, userd_link) {
+ if (context->gpu == minor && context->generation == generation)
+ nv_rs_rmapi_revoke_userd_locked(context);
+ }
+ mutex_unlock(&nv_rs_rmapi_userd_lock);
+}
+
+/* Runtime stop can leave the PCI node registered (for example during suspend). */
+void nv_rs_rmapi_revoke_runtime_userd(u32 gpu_id)
+{
+ struct nv_rs_rmapi_file *context, *next;
+
+ mutex_lock(&nv_rs_rmapi_userd_lock);
+ list_for_each_entry_safe(context, next, &nv_rs_rmapi_userd_files, userd_link) {
+ if (context->userd_gpu_id == gpu_id)
+ nv_rs_rmapi_revoke_userd_locked(context);
+ }
+ mutex_unlock(&nv_rs_rmapi_userd_lock);
+}
+
/* The release of GPU-cacheable system memory. The original writes 1 to the BAR0
* registers 0x70000, 0x70010 and 0x70004 and polls each; that needs the GPU's register
* mapping, which these nodes do not have. Counted, nothing else. */
@@ -1429,7 +1598,7 @@ u64 nv_rs_rmapi_os_ctl_fd_owner(s32 descriptor)
static int nv_rs_rmapi_open(struct inode *inode, struct file *file)
{
- struct nv_rs_rmapi_file *context = nv_rs_rmapi_context(-1);
+ struct nv_rs_rmapi_file *context = nv_rs_rmapi_context(file, -1);
if (!context)
return -ENOMEM;
file->private_data = context;
@@ -1466,7 +1635,7 @@ static int nv_rs_rmapi_gpu_open_file(struct inode *inode, struct file *file)
struct nv_rs_rmapi_gpu_node *node =
container_of(file->private_data, struct nv_rs_rmapi_gpu_node, misc);
int gpu = (int)(node - nv_rs_rmapi_gpu_nodes);
- struct nv_rs_rmapi_file *context = nv_rs_rmapi_context(gpu);
+ struct nv_rs_rmapi_file *context = nv_rs_rmapi_context(file, gpu);
struct nv_rs_gpu_owner *owner = NULL;
int result;
if (!context)
@@ -1514,6 +1683,9 @@ static int nv_rs_rmapi_release(struct inode *inode, struct file *file)
nv_rs_gpu_slot_is_live_gen((u32)context->gpu, context->generation))
nv_rs_rmapi_gpu_release(nv_rs_rmapi_state, context->gpu);
/* No mapping of this file is left (a mapping holds the file): its context goes. */
+ mutex_lock(&nv_rs_rmapi_userd_lock);
+ list_del_init(&context->userd_link);
+ mutex_unlock(&nv_rs_rmapi_userd_lock);
mutex_lock(&nv_rs_rmapi_alloc_lock);
mapped_alloc = nv_rs_file_map_remove(context->owner);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
@@ -1522,6 +1694,8 @@ static int nv_rs_rmapi_release(struct inode *inode, struct file *file)
mutex_unlock(&nv_rs_rmapi_lock);
if (context->control)
fput(context->control);
+ if (context->userd_control)
+ fput(context->userd_control);
kfree(context);
/* Return pooled system pages to the OS after client teardown (both control-fd
* and per-GPU device-fd closes run through here), outside nv_rs_rmapi_lock. */
@@ -1576,9 +1750,13 @@ static int nv_rs_rmapi_register(struct file *file, const u8 *top, size_t size)
if (target && target->f_op == &nv_rs_rmapi_operations)
target_context = target->private_data;
mutex_lock(&nv_rs_rmapi_lock);
- status = nv_rs_rmapi_register_fd(context->control != NULL, target_context != NULL,
+ mutex_lock(&nv_rs_rmapi_userd_lock);
+ status = nv_rs_rmapi_register_fd(context->control != NULL ||
+ (context->userd_control && context->userd_control != target),
+ target_context != NULL,
target_context && target_context->control != NULL,
target == file);
+ mutex_unlock(&nv_rs_rmapi_userd_lock);
if (!status) {
context->control = target;
target = NULL;
@@ -1671,6 +1849,9 @@ static int nv_rs_rmapi_export_dmabuf(struct file *file, u8 *top, size_t size)
}
}
}
+ /* A raw export could outlive a reprogramming of the aperture. */
+ if (pdev && nv_rs_rmapi_gpu_nodes[gpu].pascal_userd_gpu && nv_rs_runtime_engines())
+ pdev = NULL;
if (pdev)
pci_dev_get(pdev);
mutex_unlock(&nv_rs_rmapi_lock);
@@ -1919,6 +2100,50 @@ static inline void nv_rs_vm_flags_clear(struct vm_area_struct *vma, vm_flags_t f
#endif
}
+static bool nv_rs_rmapi_userd_live_locked(struct nv_rs_rmapi_file *context)
+{
+ struct nv_rs_rmapi_gpu_node *node;
+ unsigned long flags;
+ bool live;
+
+ if (list_empty(&context->userd_link))
+ return false;
+ node = &nv_rs_rmapi_gpu_nodes[context->gpu];
+ spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
+ live = node->live && node->generation == context->generation &&
+ node->gpu_id == context->userd_gpu_id && (node->owner || node->pdev);
+ spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
+ return live;
+}
+
+static vm_fault_t nv_rs_rmapi_userd_fault(struct vm_fault *vmf)
+{
+ struct vm_area_struct *vma = vmf->vma;
+ struct nv_rs_rmapi_file *context = vma->vm_file->private_data;
+ struct nv_rs_file_map_record mapping;
+ vm_fault_t result = VM_FAULT_SIGBUS;
+ bool found;
+
+ /* A revoker holds this mutex while waiting for mmap_lock. Faults already
+ * hold mmap_lock, so fail closed on contention instead of deadlocking. */
+ if (!mutex_trylock(&nv_rs_rmapi_userd_lock))
+ return VM_FAULT_SIGBUS;
+ if (vmf->pgoff == context->userd_pgoff && nv_rs_rmapi_userd_live_locked(context)) {
+ mutex_lock(&nv_rs_rmapi_alloc_lock);
+ found = nv_rs_file_map_get(context->owner, &mapping);
+ mutex_unlock(&nv_rs_rmapi_alloc_lock);
+ if (found && mapping.is_io && mapping.io_bytes == PAGE_SIZE)
+ result = vmf_insert_pfn_prot(vma, vmf->address, mapping.io_phys >> PAGE_SHIFT,
+ vma->vm_page_prot);
+ }
+ mutex_unlock(&nv_rs_rmapi_userd_lock);
+ return result;
+}
+
+static const struct vm_operations_struct nv_rs_rmapi_userd_vm_operations = {
+ .fault = nv_rs_rmapi_userd_fault,
+};
+
static int nv_rs_rmapi_mmap(struct file *file, struct vm_area_struct *vma)
{
struct nv_rs_rmapi_file *context = file->private_data;
@@ -1930,18 +2155,39 @@ static int nv_rs_rmapi_mmap(struct file *file, struct vm_area_struct *vma)
mutex_lock(&nv_rs_rmapi_alloc_lock);
has_map = nv_rs_file_map_get(context->owner, &mapping);
mutex_unlock(&nv_rs_rmapi_alloc_lock);
- if (!has_map)
+ if (!has_map) {
+
return -EINVAL;
- if (vma->vm_pgoff != 0 || !(vma->vm_flags & VM_SHARED))
+ }
+ if (vma->vm_pgoff != 0 || !(vma->vm_flags & VM_SHARED)) {
+
return -EINVAL;
+ }
if (mapping.is_io) {
unsigned long size = vma->vm_end - vma->vm_start;
struct nv_rs_pci *pci = NULL;
struct pci_dev *pdev = NULL;
unsigned long flags;
int rc;
- if (!size || size > mapping.io_bytes)
+ if (!size || size > mapping.io_bytes) {
+
return -ERANGE;
+ }
+ /* The USERD key is immutable once published with the allocation record. */
+ if (READ_ONCE(context->userd_pgoff)) {
+ mutex_lock(&nv_rs_rmapi_userd_lock);
+ if (!nv_rs_rmapi_userd_live_locked(context)) {
+ mutex_unlock(&nv_rs_rmapi_userd_lock);
+
+ return -ENODEV;
+ }
+ vma->vm_pgoff = context->userd_pgoff;
+ mutex_unlock(&nv_rs_rmapi_userd_lock);
+ vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
+ nv_rs_vm_flags_set(vma, VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP);
+ vma->vm_ops = &nv_rs_rmapi_userd_vm_operations;
+ return 0;
+ }
if (context->gpu < 0 || context->gpu >= NV_RS_RMAPI_MAX_GPUS)
return -ENODEV;
spin_lock_irqsave(&nv_rs_rmapi_gpu_dev_lock, flags);
@@ -2133,6 +2379,9 @@ int nv_rs_rmapi_node_gpu_add(struct pci_dev *pdev, u32 boot0)
atomic64_set(&node->idle_pstate_total_secs, 0);
atomic64_set(&node->power_cap_mw, 0);
atomic_set(&node->tensor_fp32_rate, 0);
+ /* GP100/GP104 use a dedicated BAR1 root in the opt-in legacy runtime. */
+ node->pascal_userd_gpu = (boot0 >> 20 & 0x1ff) == 0x130 ||
+ (boot0 >> 20 & 0x1ff) == 0x134;
node->live = true;
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
}
@@ -2273,6 +2522,7 @@ void nv_rs_rmapi_node_gpu_remove(struct pci_dev *pdev)
void (*release)(void *cookie) = NULL;
void *cookie = NULL;
struct nv_rs_gpu_owner *owner = NULL;
+ u32 generation = 0;
int minor;
if (!nv_rs_rmapi_state)
return;
@@ -2289,6 +2539,7 @@ void nv_rs_rmapi_node_gpu_remove(struct pci_dev *pdev)
owner = nv_rs_rmapi_gpu_nodes[minor].owner;
nv_rs_rmapi_gpu_nodes[minor].owner = NULL;
spin_unlock_irqrestore(&nv_rs_rmapi_gpu_dev_lock, flags);
+ generation = nv_rs_rmapi_gpu_nodes[minor].generation;
nv_rs_rmapi_gpu_nodes[minor].generation = nv_rs_gpu_slot_deactivate((u32)minor);
release = nv_rs_rmapi_gpu_nodes[minor].release;
cookie = nv_rs_rmapi_gpu_nodes[minor].cookie;
@@ -2299,8 +2550,10 @@ void nv_rs_rmapi_node_gpu_remove(struct pci_dev *pdev)
minor = -1;
}
mutex_unlock(&nv_rs_rmapi_lock);
- if (minor >= 0)
+ if (minor >= 0) {
+ nv_rs_rmapi_revoke_gpu_userd(minor, generation);
wait_event(nv_rs_rmapi_owner_wq, nv_rs_rmapi_node_start_idle(minor));
+ }
if (owner)
nv_rs_gpu_owner_runtime_stop(owner);
nv_rs_rmapi_allocs_unmap_dev(&pdev->dev);
diff --git a/kernel-open/nvidia/rmapi_node.h b/kernel-open/nvidia/rmapi_node.h
index a9e05fb3..7de5bf6c 100644
--- a/kernel-open/nvidia/rmapi_node.h
+++ b/kernel-open/nvidia/rmapi_node.h
@@ -24,6 +24,7 @@ int nv_rs_rmapi_node_gpu_reader(struct pci_dev *pdev,
void (*release)(void *cookie), void *cookie);
int nv_rs_rmapi_node_gpu_runtime(struct pci_dev *pdev, struct nv_rs_gpu_owner *owner);
void nv_rs_rmapi_node_gpu_remove(struct pci_dev *pdev);
+void nv_rs_rmapi_revoke_runtime_userd(u32 gpu_id);
struct device *nv_rs_rmapi_gpu_device_get(u32 gpu_id);
void nv_rs_rmapi_file_post(u64 owner);
void nv_rs_rmapi_gpu_negotiate_dma(u32 gpu_id, unsigned int bits);
diff --git a/src/nvidia/kernel/adapter_start.rs b/src/nvidia/kernel/adapter_start.rs
index 5ef0cc68..25cbff78 100644
--- a/src/nvidia/kernel/adapter_start.rs
+++ b/src/nvidia/kernel/adapter_start.rs
@@ -1944,9 +1944,9 @@ fn boot_maxwell_pascal_pre_gsp(
} else {
nv_rs_core::gpu::chip_arch::ArchFamily::Maxwell2
};
- let raw_vram_bytes =
- nv_rs_core::mmu::vram::read_vram_bytes_for_family(family, |reg| guard.read(reg).ok())
- .unwrap_or(16 * 1024 * 1024 * 1024);
+ let probed_vram_bytes =
+ nv_rs_core::mmu::vram::read_vram_bytes_for_family(family, |reg| guard.read(reg).ok());
+ let raw_vram_bytes = probed_vram_bytes.unwrap_or(16 * 1024 * 1024 * 1024);
let vram_bytes =
nv_rs_core::mmu::vram::clamp_vram_bytes(raw_vram_bytes, unsafe { nv_rs_vram_limit_mb() });
// Opt-in PCIe link-speed override (Gen1->Gen2/Gen3 for P104-100/P106-100/CMP 100-100, #168).
@@ -2115,7 +2115,13 @@ fn boot_maxwell_pascal_pre_gsp(
// deactivate, as the GV100 path (`ApiGuard`) and `ga10x::open` do. Without
// it this thread exits holding the lock and the next remove deadlocks.
let _api = ApiGuard::acquire();
- crate::rmapi_node::activate_legacy_runtime(pci, profile, main_ctx_size, vram_bytes);
+ crate::rmapi_node::activate_legacy_runtime(
+ pci,
+ profile,
+ main_ctx_size,
+ vram_bytes,
+ probed_vram_bytes.is_some() && vram_bytes >= 256 * 1024 * 1024,
+ )?;
crate::rmapi_node::update_live_telemetry(pci, 0, None, None, None);
nv_rs_bringup_note(pci, NOTE_LEGACY_STAGE, 3);
loop {
diff --git a/src/nvidia/kernel/rmapi_engine.rs b/src/nvidia/kernel/rmapi_engine.rs
index f6e4c56f..48f6fb76 100644
--- a/src/nvidia/kernel/rmapi_engine.rs
+++ b/src/nvidia/kernel/rmapi_engine.rs
@@ -41,6 +41,11 @@ unsafe extern "C" {
fn nv_rs_pci_write32(pci: *mut c_void, offset: u64, value: u32) -> i32;
fn nv_rs_pci_read32_irq(pci: *mut c_void, offset: u64, value: *mut u32) -> i32;
fn nv_rs_pci_write32_irq(pci: *mut c_void, offset: u64, value: u32) -> i32;
+ fn nv_rs_pci_bar1_map(pci: *mut c_void, offset: u64, bytes: u64) -> i32;
+ fn nv_rs_pci_bar1_unmap(pci: *mut c_void);
+ fn nv_rs_pci_bar1_read32(pci: *mut c_void, offset: u64, value: *mut u32) -> i32;
+ fn nv_rs_pci_bar1_write32(pci: *mut c_void, offset: u64, value: u32) -> i32;
+ fn nv_rs_rmapi_userd_block_available(gpu_id: u32, block: u32, owner: u64) -> bool;
fn nv_rs_pci_bar1_bytes(pci: *mut c_void, bytes: *mut u64) -> i32;
fn nv_rs_bringup_note(pci: *mut c_void, code: u32, value: u32);
fn nv_rs_os_busy_us(microseconds: u32);
@@ -432,6 +437,17 @@ pub(crate) const fn gv100_vram_window(vram_usable: u64) -> (u64, u64, u64) {
(cursor, floor, floor - 1)
}
+#[derive(Clone, Copy)]
+struct PascalUserdBar1 {
+ data: u64,
+ bytes: u64,
+ previous_block: u32,
+ previous_userd: u32,
+ programmed_block: u32,
+ programmed_userd: u32,
+ ready: bool,
+}
+
/// Live hardware state of one initialized GPU behind the RM API node.
pub struct LiveEngine {
pub active: bool,
@@ -439,6 +455,7 @@ pub struct LiveEngine {
pub pci: *mut c_void,
pub arch_mode: EngineArchMode,
pub bar1_identity_base: u64,
+ pascal_userd_bar1: Option<PascalUserdBar1>,
pub num_channels: u32,
/// Top-down internal VRAM allocator (instance blocks, dummy page, runlists).
pub vram_cursor: u64,
@@ -522,6 +539,7 @@ impl LiveEngine {
pci: core::ptr::null_mut(),
arch_mode: EngineArchMode::VoltaGv100,
bar1_identity_base: 0,
+ pascal_userd_bar1: None,
num_channels: 0x1000,
vram_cursor: 0x7_fd00_0000,
vram_floor: 0x7_e000_0000,
@@ -2693,6 +2711,10 @@ impl LiveEngine {
self.used_runlists = 0;
self.clear_and_free();
self.clear_pfifo_pbdma_intrs();
+ if let Err(error) = self.restore_pascal_userd_bar1() {
+ unsafe { nv_rs_bringup_note(self.pci, 0x4c47_0076, error as u32) };
+ }
+ self.pascal_userd_bar1 = None;
self.active = false;
self.gr_ctx_vram = 0;
self.bundle_cb_phys = 0;
@@ -2845,6 +2867,328 @@ impl LiveEngine {
self.last_throttle = ThermalThrottleLevel::Nominal;
}
+ fn wait_pascal_bar1_bind(&self) -> bool {
+ use nv_rs_core::mmu::bar1_setup::BIND_STATUS;
+
+ for _ in 0..1000 {
+ let word = self.rd32(u64::from(BIND_STATUS));
+ if word == u32::MAX || word >> 20 == 0xbad {
+ return false;
+ }
+ if word & 3 == 0 {
+ return true;
+ }
+ unsafe { nv_rs_os_busy_us(1) };
+ }
+ false
+ }
+
+ fn restore_pascal_userd_bar1(&mut self) -> Result<(), i32> {
+ use nv_rs_core::{fifo::load::BAR1_USERD_BASE, mmu::bar1_setup::BAR1_BLOCK};
+
+ let Some(binding) = self.pascal_userd_bar1 else {
+ return Ok(());
+ };
+ let userd = u64::from(BAR1_USERD_BASE);
+ let block = u64::from(BAR1_BLOCK);
+ self.wr32(userd, binding.previous_userd);
+ self.wr32(block, binding.previous_block);
+ if !self.wait_pascal_bar1_bind()
+ || self.rd32(block) != binding.previous_block
+ || self.rd32(userd) != binding.previous_userd
+ {
+ return Err(-5);
+ }
+ self.flush_bus();
+ self.pascal_userd_bar1 = None;
+ Ok(())
+ }
+
+ fn read_pascal_register(&self, reg: u32) -> Option<u32> {
+ let mut value = 0;
+ if self.pci.is_null()
+ || unsafe { nv_rs_pci_read32(self.pci, u64::from(reg), &mut value) } != 0
+ || value == u32::MAX
+ || value >> 20 == 0xbad
+ {
+ return None;
+ }
+ Some(value)
+ }
+
+ /// Wait for usable MMU register state and bounded queue progress.
+ fn wait_pascal_mmu(&self, mask: u32) -> Result<(), i32> {
+ for _ in 0..10_000 {
+ let state = self
+ .read_pascal_register(mmu_v2_pascal::NV_PFB_PRI_MMU_CTRL)
+ .ok_or(-5)?;
+ if state & mask != 0 {
+ return Ok(());
+ }
+ unsafe { nv_rs_os_busy_us(1) };
+ }
+ Err(-110)
+ }
+
+ /// Publish this BAR's new, VRAM-backed root to the HUB TLB before CPU access.
+ #[inline(never)]
+ fn invalidate_pascal_bar1(&self, table: u64) -> Result<(), i32> {
+ self.wait_pascal_mmu(0x00ff_0000)?;
+ let ops = mmu_v2_pascal::encode_tlb_invalidate_mmio(mmu_v2_pascal::TlbInvalidateParams {
+ pdb_phys: table,
+ pdb_is_sysmem: false,
+ all_va: true,
+ all_pdb: false,
+ replay_mode: 0,
+ sys_membar: true,
+ ack_type: 1,
+ cache_level: 0,
+ });
+ for op in &ops[..3] {
+ let MmioOp::Write32 { reg, mut val } = *op else {
+ return Err(-22);
+ };
+ if reg == mmu_v2_pascal::NV_PFB_PRI_MMU_INVALIDATE {
+ val |= 1 << 2; // HUB_ONLY (BAR address space)
+ }
+ let rc = unsafe { nv_rs_pci_write32(self.pci, u64::from(reg), val) };
+ if rc != 0 {
+ return Err(rc);
+ }
+ }
+ self.wait_pascal_mmu(1 << 15)?;
+ self.flush_bus();
+ Ok(())
+ }
+
+ /// Verify the reserved pool before making a BAR1 USERD base visible to PFIFO.
+ #[inline(never)]
+ fn bind_pascal_userd_bar1(&mut self, data: u64, bytes: u64) -> Result<(), i32> {
+ use nv_rs_core::gpu::legacy_hal::mmu_v2_pascal::Bar1VramSpan as Span;
+ use nv_rs_core::mmu::{bar1_setup::BAR1_BLOCK, ramin};
+
+ let reg = u64::from(BAR1_BLOCK);
+ let previous = self.rd32(reg);
+ let userd_reg = u64::from(nv_rs_core::fifo::load::BAR1_USERD_BASE);
+ let previous_userd = self.rd32(userd_reg);
+ if self.pascal_userd_bar1.is_some()
+ || previous == u32::MAX
+ || previous >> 20 == 0xbad
+ || previous & (1 << 31) != 0
+ || previous_userd == u32::MAX
+ || previous_userd >> 20 == 0xbad
+ || previous_userd & (1 << 28) != 0
+ || !self.wait_pascal_bar1_bind()
+ {
+ return Err(-16);
+ }
+ let mut aperture = 0;
+ if unsafe { nv_rs_pci_bar1_bytes(self.pci, &mut aperture) } != 0
+ || Span::VA + bytes > aperture
+ {
+ return Err(-22);
+ }
+ let table = self
+ .alloc_vram(Span::TABLE_BYTES + Span::PAGE, Span::PAGE)
+ .ok_or(-12)?;
+ let layout = Span::new(table, data, bytes).ok_or(-22)?;
+ let instance = table + Span::TABLE_BYTES;
+ let pdb = ramin::encode_pdb(
+ Some(ramin::RootDescriptor {
+ dma_address: table,
+ aperture: ramin::Aperture::Video,
+ volatile: false,
+ }),
+ ramin::Target::Base,
+ false,
+ ramin::BaseFeatures {
+ version2: true,
+ big_page_64k: true,
+ },
+ )
+ .map_err(|_| -22)?;
+ self.pramin_zero(table, Span::TABLE_BYTES + Span::PAGE);
+ for (offset, word) in layout.directories() {
+ self.pramin_write64(table + offset, word);
+ }
+ for page in 0..(bytes / Span::PAGE) as u16 {
+ let (offset, word) = layout.pte(page).ok_or(-22)?;
+ self.pramin_write64(table + offset, word);
+ }
+ self.pramin_write32(instance + u64::from(pdb.low.offset), pdb.low.value);
+ self.pramin_write32(instance + u64::from(pdb.high.offset), pdb.high.value);
+ self.pramin_write64(instance + 0x208, Span::VA + bytes - 1);
+ let samples = [(0x400, 0x73c1_0001), (bytes - 4, 0x73c1_0002)];
+ for (off, value) in samples {
+ self.pramin_write32(data + off, value);
+ }
+ self.flush_bus();
+ let valid = self.pramin_read32(instance + u64::from(pdb.low.offset)) == pdb.low.value
+ && self.pramin_read32(instance + u64::from(pdb.high.offset)) == pdb.high.value
+ && self.pascal_bar1_tables_match(&layout, table, bytes)
+ && samples
+ .iter()
+ .all(|&(off, expected)| self.pramin_read32(data + off) == expected);
+ unsafe { nv_rs_bringup_note(self.pci, 0x4c47_007a, u32::from(valid)) };
+ let mapped = if valid {
+ unsafe { nv_rs_pci_bar1_map(self.pci, Span::VA, bytes) }
+ } else {
+ -5
+ };
+ if mapped != 0 {
+ for (off, _) in samples {
+ self.pramin_write32(data + off, 0);
+ }
+ self.flush_bus();
+ return Err(mapped);
+ }
+
+ let bind = (1 << 31) | (instance >> 12) as u32;
+ let userd = (1 << 28) | (Span::VA >> 12) as u32;
+ self.pascal_userd_bar1 = Some(PascalUserdBar1 {
+ data,
+ bytes,
+ previous_block: previous,
+ previous_userd,
+ programmed_block: bind,
+ programmed_userd: userd,
+ ready: false,
+ });
+ self.wr32(reg, bind);
+ let result = (|| {
+ if !self.wait_pascal_bar1_bind() || self.rd32(reg) != bind {
+ return Err(-5);
+ }
+ let invalidate = self.invalidate_pascal_bar1(table);
+ unsafe {
+ nv_rs_bringup_note(self.pci, 0x4c47_007b, invalidate.err().unwrap_or(0) as u32)
+ };
+ invalidate?;
+ for (off, expected) in samples {
+ let mut value = 0;
+ let rc = unsafe { nv_rs_pci_bar1_read32(self.pci, off, &mut value) };
+ unsafe { nv_rs_bringup_note(self.pci, 0x4c47_0072, value) };
+ if rc != 0 || value != expected {
+ return Err(-5);
+ }
+ let rc = unsafe { nv_rs_pci_bar1_write32(self.pci, off, !expected) };
+ if rc != 0 {
+ return Err(rc);
+ }
+ }
+ self.flush_bus();
+ for (off, expected) in samples {
+ let observed = self.pramin_read32(data + off);
+ unsafe { nv_rs_bringup_note(self.pci, 0x4c47_0073, observed) };
+ if observed != !expected {
+ return Err(-5);
+ }
+ }
+ Ok(())
+ })();
+ unsafe { nv_rs_pci_bar1_unmap(self.pci) };
+ for (off, _) in samples {
+ self.pramin_write32(data + off, 0);
+ }
+ self.flush_bus();
+ if let Err(error) = result {
+ self.restore_pascal_userd_bar1()?;
+ return Err(error);
+ }
+ self.wr32(userd_reg, userd);
+ if self.rd32(userd_reg) != userd {
+ self.restore_pascal_userd_bar1()?;
+ return Err(-5);
+ }
+ if let Some(binding) = &mut self.pascal_userd_bar1 {
+ binding.ready = true;
+ }
+ unsafe { nv_rs_bringup_note(self.pci, 0x4c47_0075, userd) };
+ Ok(())
+ }
+
+ #[inline(never)]
+ fn pascal_bar1_tables_match(
+ &self,
+ layout: &mmu_v2_pascal::Bar1VramSpan,
+ table: u64,
+ bytes: u64,
+ ) -> bool {
+ use mmu_v2_pascal::Bar1VramSpan as Span;
+
+ let matches = |offset, word: u64| {
+ self.pramin_read32(table + offset) == word as u32
+ && self.pramin_read32(table + offset + 4) == (word >> 32) as u32
+ };
+ layout
+ .directories()
+ .into_iter()
+ .all(|(offset, word)| matches(offset, word))
+ && (0..(bytes / Span::PAGE) as u16).all(|page| {
+ layout
+ .pte(page)
+ .is_some_and(|(offset, word)| matches(offset, word))
+ })
+ }
+
+ pub(crate) fn has_pascal_userd_bar1(&self) -> bool {
+ self.pascal_userd_bar1.is_some()
+ }
+
+ fn live_pascal_userd(&self) -> Option<PascalUserdBar1> {
+ use nv_rs_core::{fifo::load::BAR1_USERD_BASE, mmu::bar1_setup::BAR1_BLOCK};
+
+ let binding = self.pascal_userd_bar1?;
+ (self.active
+ && binding.ready
+ && self.rd32(u64::from(BAR1_BLOCK)) == binding.programmed_block
+ && self.rd32(u64::from(BAR1_USERD_BASE)) == binding.programmed_userd)
+ .then_some(binding)
+ }
+
+ pub(crate) fn pascal_userd_offset(&self, address: u64, length: u64, block: u32) -> Option<u64> {
+ use nv_rs_core::gpu::legacy_hal::mmu_v2_pascal::Bar1VramSpan as Span;
+
+ let binding = self.live_pascal_userd()?;
+ let delta = address.checked_sub(binding.data)?;
+ let slot_bytes = nv_rs_core::fifo::USERD_BYTES as u64;
+ let pool_bytes = u64::from(self.num_channels) * slot_bytes;
+ (length != 0
+ && delta < pool_bytes
+ && delta / Span::PAGE == u64::from(block)
+ && length <= slot_bytes - delta % slot_bytes
+ && length <= pool_bytes - delta)
+ .then_some(Span::VA + delta)
+ }
+
+ #[inline(never)]
+ fn init_pascal_userd_bar1(&mut self, chip: ChipId) -> Result<(), i32> {
+ use nv_rs_core::gpu::mc_load::PMC_ENABLE;
+ const PMC_ENABLE_PFIFO: u32 = 1 << 8;
+ const PFIFO_INTR: u32 = 0x2100;
+ use mmu_v2_pascal::Bar1VramSpan as Span;
+
+ if !matches!(chip, ChipId::Gp100 | ChipId::Gp104) {
+ return Ok(());
+ }
+ let pmc = self.read_pascal_register(PMC_ENABLE).ok_or(-5)?;
+ if pmc & PMC_ENABLE_PFIFO == 0 || self.read_pascal_register(PFIFO_INTR).is_none() {
+ return Err(-95);
+ }
+ let bytes = (u64::from(self.num_channels) * nv_rs_core::fifo::USERD_BYTES as u64)
+ .next_multiple_of(Span::PAGE);
+ if bytes == 0 || bytes > Span::VA {
+ return Err(-22);
+ }
+ let cursor = self.vram_cursor;
+ let data = self.alloc_vram(bytes, Span::PAGE).ok_or(-12)?;
+ let result = self.bind_pascal_userd_bar1(data, bytes);
+ if result.is_err() && self.pascal_userd_bar1.is_none() {
+ self.vram_cursor = cursor;
+ }
+ result
+ }
+
/// Activates the live engine for a Maxwell (`GM107`–`GM206`) or Pascal (`GP100`–`GP108`)
/// GPU using `nv_rs_core::gpu::legacy_hal`.
#[inline(never)]
@@ -2855,7 +3199,8 @@ impl LiveEngine {
profile: &'static LegacyChipProfile,
main_ctx_size: u64,
vram_bytes: u64,
- ) {
+ vram_probed: bool,
+ ) -> Result<(), i32> {
self.gpu_id = gpu_id;
self.pci = pci;
self.arch_mode = if profile.id.is_maxwell() {
@@ -2872,6 +3217,19 @@ impl LiveEngine {
let reserved = (total / 8).min(512 * 1024 * 1024);
self.vram_floor = total.saturating_sub(reserved);
self.vram_cursor = total.saturating_sub(48 * 1024 * 1024);
+ if vram_probed {
+ if let Err(error) = self.init_pascal_userd_bar1(profile.id) {
+ unsafe { nv_rs_bringup_note(pci, 0x4c47_0074, error as u32) };
+ // On an uncertain rollback, abort before publishing the engine.
+ if self.has_pascal_userd_bar1() {
+ let _ = self.restore_pascal_userd_bar1();
+ self.pascal_userd_bar1 = None;
+ self.pci = core::ptr::null_mut();
+ self.gpu_id = 0;
+ return Err(error);
+ }
+ }
+ }
self.reset_mig_and_pmu_defaults(true);
self.used_runlists = 0;
self.tracked_tsgs.clear_and_free();
@@ -2907,6 +3265,7 @@ impl LiveEngine {
self.gr_ctx_vram = ctx_vram;
}
self.active = true;
+ Ok(())
}
/// Configures MIG hardware capability based on GPU architecture family:
@@ -3555,9 +3914,52 @@ impl Engine for LiveEngine {
status::OK
}
+ fn pascal_userd_slot(&self, _gpu: u32, channel: u32) -> Result<Option<(u64, u64)>, NvStatus> {
+ let binding = self.live_pascal_userd().ok_or(status::NOT_SUPPORTED)?;
+ let offset = u64::from(channel) * nv_rs_core::fifo::USERD_BYTES as u64;
+ if channel >= self.num_channels || offset >= binding.bytes {
+ return Err(status::INVALID_ADDRESS);
+ }
+ Ok(Some((binding.data, binding.data + offset)))
+ }
+
+ #[inline(never)]
+ fn clear_pascal_userd_block(&mut self, _gpu: u32, userd: u64) -> NvStatus {
+ use mmu_v2_pascal::Bar1VramSpan as Span;
+
+ let Some(binding) = self.live_pascal_userd() else {
+ return status::INVALID_STATE;
+ };
+ let page = userd & !(Span::PAGE - 1);
+ if page < binding.data || page - binding.data >= binding.bytes {
+ return status::INVALID_ADDRESS;
+ }
+ self.pramin_zero(page, Span::PAGE);
+ self.flush_bus();
+ for offset in (0..Span::PAGE).step_by(4) {
+ if self.pramin_read32(page + offset) != 0 {
+ return status::INVALID_STATE;
+ }
+ }
+ status::OK
+ }
+
fn userd_clear(&mut self, _gpu: u32, address: u64, bytes: u32) -> NvStatus {
+ let slot_bytes = nv_rs_core::fifo::USERD_BYTES as u64;
+ let internal = self
+ .pascal_userd_bar1
+ .is_some_and(|binding| (binding.data..binding.data + binding.bytes).contains(&address));
+ if internal && (u64::from(bytes) != slot_bytes || address % slot_bytes != 0) {
+ return status::INVALID_ARGUMENT;
+ }
self.pramin_zero(address, u64::from(bytes));
self.flush_bus();
+ if internal
+ && (self.pramin_read32(address) != 0
+ || self.pramin_read32(address + slot_bytes - 4) != 0)
+ {
+ return status::INVALID_STATE;
+ }
status::OK
}
@@ -4107,15 +4509,13 @@ impl LiveEnginePool {
profile: &'static LegacyChipProfile,
main_ctx_size: u64,
vram_bytes: u64,
- ) {
- let slot = self
- .engines
- .iter()
- .position(|e| e.active && e.gpu_id == gpu_id)
- .or_else(|| self.engines.iter().position(|e| !e.active));
- if let Some(idx) = slot {
- self.engines[idx].activate_legacy(gpu_id, pci, profile, main_ctx_size, vram_bytes);
+ vram_probed: bool,
+ ) -> Result<(), i32> {
+ if self.by_gpu(gpu_id).is_some() {
+ return Ok(());
}
+ let engine = self.engines.iter_mut().find(|e| !e.active).ok_or(-28)?;
+ engine.activate_legacy(gpu_id, pci, profile, main_ctx_size, vram_bytes, vram_probed)
}
/// Runs one dynamic PMU thermal/fan/power/P-state control tick across all active GPUs.
@@ -5083,6 +5483,26 @@ impl Engine for LiveEnginePool {
}
}
+ fn userd_block_available(&self, gpu: u32, block: u32, owner: u64) -> bool {
+ self.by_gpu(gpu).is_none_or(|engine| {
+ !engine.has_pascal_userd_bar1()
+ || unsafe { nv_rs_rmapi_userd_block_available(gpu, block, owner) }
+ })
+ }
+
+ fn pascal_userd_slot(&self, gpu: u32, channel: u32) -> Result<Option<(u64, u64)>, NvStatus> {
+ self.by_gpu(gpu)
+ .ok_or(status::NOT_SUPPORTED)?
+ .pascal_userd_slot(gpu, channel)
+ }
+
+ fn clear_pascal_userd_block(&mut self, gpu: u32, userd: u64) -> NvStatus {
+ self.by_gpu_mut(gpu)
+ .map_or(status::INVALID_STATE, |engine| {
+ engine.clear_pascal_userd_block(gpu, userd)
+ })
+ }
+
fn userd_clear(&mut self, gpu: u32, address: u64, bytes: u32) -> NvStatus {
match self.by_gpu_mut(gpu) {
Some(e) => e.userd_clear(gpu, address, bytes),
diff --git a/src/nvidia/kernel/rmapi_memory.rs b/src/nvidia/kernel/rmapi_memory.rs
index a21c9b68..07ae3c3f 100644
--- a/src/nvidia/kernel/rmapi_memory.rs
+++ b/src/nvidia/kernel/rmapi_memory.rs
@@ -68,6 +68,19 @@ unsafe extern "C" {
descriptor: i32,
address: *mut u64,
) -> u32;
+ #[cfg(not(nv_rs_edu_guest))]
+ fn nv_rs_rmapi_os_map_pascal_userd(
+ gpu_id: u32,
+ offset: u64,
+ length: u64,
+ descriptor: i32,
+ owner: u64,
+ block: u32,
+ address: *mut u64,
+ cookie: *mut u64,
+ ) -> u32;
+ #[cfg(not(nv_rs_edu_guest))]
+ fn nv_rs_rmapi_os_unmap_pascal_userd(cookie: u64);
fn nv_rs_rmapi_os_kernel_write(token: u64, offset: u64, bytes: *const u8, length: usize)
-> u32;
fn nv_rs_rmapi_os_page_dma(gpu_id: u32, token: u64, page_index: u64, dma_out: *mut u64) -> u32;
@@ -212,7 +225,14 @@ impl OsMemory for KernelOs {
) -> Result<u64, NvStatus> {
let mut address = 0u64;
#[cfg(not(nv_rs_edu_guest))]
- let bar1_offset = offset.wrapping_add(super::bar1_identity_base(gpu));
+ if super::pascal_userd_bar1_active(gpu) {
+ // The dedicated root has no general framebuffer identity mapping.
+ return Err(status::NOT_SUPPORTED);
+ }
+ #[cfg(not(nv_rs_edu_guest))]
+ let bar1_offset = offset
+ .checked_add(super::bar1_identity_base(gpu))
+ .ok_or(status::INVALID_ADDRESS)?;
#[cfg(nv_rs_edu_guest)]
let bar1_offset = offset;
// SAFETY: out pointer is a live local; node mutex is held. The C side refuses a
@@ -224,6 +244,42 @@ impl OsMemory for KernelOs {
error => Err(NvStatus(error)),
}
}
+ #[cfg(not(nv_rs_edu_guest))]
+ fn map_pascal_userd(
+ &mut self,
+ gpu: u32,
+ address: u64,
+ length: u64,
+ descriptor: i32,
+ owner: u64,
+ block: u32,
+ ) -> Result<(u64, u64), NvStatus> {
+ let offset = super::pascal_userd_offset(gpu, address, length, block).ok_or(status::INVALID_ADDRESS)?;
+ let mut address = 0;
+ let mut cookie = 0;
+ // The RM node mutex protects the engine and caller's owner token.
+ match unsafe {
+ nv_rs_rmapi_os_map_pascal_userd(
+ gpu,
+ offset,
+ length,
+ descriptor,
+ owner,
+ block,
+ &mut address,
+ &mut cookie,
+ )
+ } {
+ 0 => Ok((address, cookie)),
+ error => Err(NvStatus(error)),
+ }
+ }
+
+ #[cfg(not(nv_rs_edu_guest))]
+ fn unmap_pascal_userd(&mut self, cookie: u64) {
+ unsafe { nv_rs_rmapi_os_unmap_pascal_userd(cookie) };
+ }
+
fn unmap_video(&mut self, _: u32, _: u64) {}
/// BAR0 register-window mapping (`0xc361` usermode doorbell, `0x90e6` PMC page).
fn map_register(
diff --git a/src/nvidia/kernel/rmapi_node.rs b/src/nvidia/kernel/rmapi_node.rs
index 7f9b0355..f23e10b0 100644
--- a/src/nvidia/kernel/rmapi_node.rs
+++ b/src/nvidia/kernel/rmapi_node.rs
@@ -368,6 +368,29 @@ pub(crate) fn bar1_identity_bytes(gpu_id: u32) -> u64 {
}
}
+#[cfg(not(nv_rs_edu_guest))]
+pub(crate) fn pascal_userd_bar1_active(gpu_id: u32) -> bool {
+ unsafe {
+ (&*ptr::addr_of!(LIVE_ENGINES))
+ .by_gpu(gpu_id)
+ .is_some_and(|engine| engine.has_pascal_userd_bar1())
+ }
+}
+
+#[cfg(not(nv_rs_edu_guest))]
+pub(crate) fn pascal_userd_offset(
+ gpu_id: u32,
+ address: u64,
+ length: u64,
+ block: u32,
+) -> Option<u64> {
+ unsafe {
+ (&*ptr::addr_of!(LIVE_ENGINES))
+ .by_gpu(gpu_id)?
+ .pascal_userd_offset(address, length, block)
+ }
+}
+
#[cfg(not(nv_rs_edu_guest))]
pub(crate) fn bar1_identity_base(gpu_id: u32) -> u64 {
unsafe {
@@ -1184,7 +1207,8 @@ pub(crate) unsafe fn activate_legacy_runtime(
profile: &'static nv_rs_core::gpu::legacy_hal::chip::ChipProfile,
main_ctx_size: u64,
vram_bytes: u64,
-) {
+ vram_probed: bool,
+) -> Result<(), i32> {
unsafe {
unsafe extern "C" {
fn nv_rs_pci_gpu_id(pci: *mut core::ffi::c_void) -> u32;
@@ -1192,13 +1216,21 @@ pub(crate) unsafe fn activate_legacy_runtime(
}
let node_ptr = RMAPI_NODE_PTR;
if node_ptr.is_null() {
- return;
+ return Err(-19);
}
let node = &mut *node_ptr;
let gpu_id = nv_rs_pci_gpu_id(pci);
if gpu_id == u32::MAX {
- return;
+ return Err(-19);
}
+ (&mut *ptr::addr_of_mut!(LIVE_ENGINES)).activate_legacy(
+ gpu_id,
+ pci,
+ profile,
+ main_ctx_size,
+ vram_bytes,
+ vram_probed,
+ )?;
let total_vram = if vram_bytes >= 256 * 1024 * 1024 {
vram_bytes
} else {
@@ -1244,13 +1276,6 @@ pub(crate) unsafe fn activate_legacy_runtime(
if let Some(instance) = node.gpus.instance_of(gpu_id) {
node.cache.flush(instance as u8);
}
- (&mut *ptr::addr_of_mut!(LIVE_ENGINES)).activate_legacy(
- gpu_id,
- pci,
- profile,
- main_ctx_size,
- total_vram,
- );
crate::uvm_interface_ffi::register_live_gv100(
gpu_id,
legacy_uuid,
@@ -1263,6 +1288,7 @@ pub(crate) unsafe fn activate_legacy_runtime(
);
crate::modeset_ffi::register_live_gpu(gpu_id);
}
+ Ok(())
}
/// Deactivates the live GV100/legacy/GSP-RM engine before teardown.
@@ -1274,6 +1300,10 @@ pub(crate) unsafe fn deactivate_runtime(pci: *mut core::ffi::c_void) {
}
let gpu_id = nv_rs_pci_gpu_id(pci);
if gpu_id != u32::MAX {
+ unsafe extern "C" {
+ fn nv_rs_rmapi_revoke_runtime_userd(gpu_id: u32);
+ }
+ nv_rs_rmapi_revoke_runtime_userd(gpu_id);
if crate::gsp_bringup::has_active_session(gpu_id) {
crate::gsp_bringup::teardown_gsp_rm(gpu_id);
}
diff --git a/src/nvidia/src/gpu/legacy_hal.rs b/src/nvidia/src/gpu/legacy_hal.rs
index 0e038e26..95ebbf6d 100644
--- a/src/nvidia/src/gpu/legacy_hal.rs
+++ b/src/nvidia/src/gpu/legacy_hal.rs
@@ -779,6 +779,91 @@ pub mod mmu_v2_pascal {
pub is_page_table: bool,
}
+ /// One 2 MiB Pascal BAR1 page-table span backed by owned VRAM.
+ ///
+ /// The caller must zero all five table pages before writing the returned
+ /// entries. Unused directory slots and PTEs must remain invalid.
+ pub struct Bar1VramSpan {
+ table: u64,
+ data: u64,
+ pages: u16,
+ }
+
+ impl Bar1VramSpan {
+ pub const PAGE: u64 = 0x1000;
+ pub const VA: u64 = 0x20_0000;
+ pub const TABLE_BYTES: u64 = 5 * Self::PAGE;
+
+ pub fn new(table: u64, data: u64, bytes: u64) -> Option<Self> {
+ if table == 0
+ || data == 0
+ || bytes == 0
+ || bytes > Self::VA
+ || (table | data | bytes) & (Self::PAGE - 1) != 0
+ {
+ return None;
+ }
+ let table_end = table.checked_add(Self::TABLE_BYTES)?;
+ let data_end = data.checked_add(bytes)?;
+ if table_end > 1 << 37 || data_end > 1 << 37 || (table < data_end && data < table_end) {
+ return None;
+ }
+ Some(Self {
+ table,
+ data,
+ pages: (bytes / Self::PAGE) as u16,
+ })
+ }
+
+ pub fn directories(&self) -> [(u64, u64); 4] {
+ let single = |page| {
+ encode_pde_single(PdeSingleParams {
+ aperture: Aperture::VideoMemory,
+ volatile: false,
+ addr: self.table + page * Self::PAGE,
+ })
+ };
+ let dual = encode_pde_multi(PdeMultiParams {
+ aperture_big: Aperture::Invalid,
+ vol_big: false,
+ addr_big: 0,
+ aperture_small: Aperture::VideoMemory,
+ vol_small: false,
+ addr_small: self.table + 4 * Self::PAGE,
+ });
+ // VA = 2 MiB uses PDE0 index 1 and zero for the upper indices.
+ [
+ (0, single(1)),
+ (Self::PAGE, single(2)),
+ (2 * Self::PAGE, single(3)),
+ (3 * Self::PAGE + 16 + 8, dual[1]),
+ ]
+ }
+
+ pub fn pte(&self, index: u16) -> Option<(u64, u64)> {
+ if index >= self.pages {
+ return None;
+ }
+ let page = u64::from(index);
+ let word = encode_pte(PteParams {
+ valid: true,
+ aperture: Aperture::VideoMemory,
+ volatile: false,
+ encrypted: false,
+ privilege: false,
+ read_only: false,
+ atomic_disable: true,
+ phys_addr: self.data + page * Self::PAGE,
+ peer_id: 0,
+ comptagline: 0,
+ kind: 0,
+ });
+ // GP100 PTE aperture 0 selects VRAM; its PDE aperture is 1.
+ // See Nouveau's gp100_vmm_valid and gf100_vmm_aper.
+ Some((4 * Self::PAGE + 8 * page, word & !(3 << 1)))
+ }
+ }
+
/// Exact `_nv040762rm` (`gmmuFmtInitLevels_GP10X`): 6 levels covering 49-bit VA.
pub const fn init_levels_gp10x() -> [LevelFmt; 6] {
[
@@ -1923,6 +2008,41 @@ mod tests {
);
}
+ #[test]
+ fn pascal_bar1_vram_span_has_distinct_userd_pages() {
+ use mmu_v2_pascal::Bar1VramSpan as Span;
+ let table = 0x3fcd_fa000;
+ let data = 0x3fce_00000;
+ let span = Span::new(table, data, Span::VA).unwrap();
+ for index in 0..512 {
+ let (offset, pte) = span.pte(index).unwrap();
+ assert_eq!(offset, 4 * Span::PAGE + 8 * u64::from(index));
+ assert_eq!(pte & 7, 1); // Valid with a VRAM aperture.
+ assert_eq!(
+ ((pte >> 8) & 0x01ff_ffff) << 12,
+ data + u64::from(index) * Span::PAGE
+ );
+ }
+ assert!(span.pte(512).is_none());
+ assert!(Span::new(data, data, Span::PAGE).is_none());
+ assert!(Span::new(table, data, Span::VA + Span::PAGE).is_none());
+ assert_eq!(
+ span.directories(),
+ [
+ (0, 0x3fcdfb02),
+ (0x1000, 0x3fcdfc02),
+ (0x2000, 0x3fcdfd02),
+ (0x3018, 0x3fcdfe02),
+ ],
+ );
+ assert_eq!(span.pte(0), Some((0x4000, 0x3fce0081)));
+ assert_eq!(span.pte(511), Some((0x4ff8, 0x3fcfff81)));
+ let limit = 1u64 << 37;
+ assert!(Span::new(table, limit - Span::PAGE, Span::PAGE).is_some());
+ assert!(Span::new(table, limit, Span::PAGE).is_none());
+ assert!(Span::new(table, data + 1, Span::PAGE).is_none());
+ }
+
#[test]
fn pascal_mmu_v2_levels_pde_pte_tlb_and_fault_buffer_match_rea() {
assert!(!mmu_v2_pascal::is_version_supported(1));
diff --git a/src/nvidia/src/rmapi/channel.rs b/src/nvidia/src/rmapi/channel.rs
index cdba2d6b..a616cc8f 100644
--- a/src/nvidia/src/rmapi/channel.rs
+++ b/src/nvidia/src/rmapi/channel.rs
@@ -330,6 +330,21 @@ pub trait Engine {
set: u32,
) -> NvStatus;
+ /// A page containing eight CHIDs may still be mapped by another RM owner.
+ fn userd_block_available(&self, _gpu: u32, _block: u32, _owner: u64) -> bool {
+ true
+ }
+
+ /// The reserved VRAM pool and the slot's framebuffer address, if backed.
+ fn pascal_userd_slot(&self, _gpu: u32, _channel: u32) -> Result<Option<(u64, u64)>, NvStatus> {
+ Ok(None)
+ }
+
+ /// Scrub every slot before a free USERD page can be assigned to a new owner.
+ fn clear_pascal_userd_block(&mut self, _gpu: u32, _userd: u64) -> NvStatus {
+ status::NOT_SUPPORTED
+ }
+
/// `kfifoSetupUserD_GM107` `_nv040419rm`: `memmgrMemSet(userd, 0, 0x200)` on the
/// channel's USERD inside the client's video memory, at framebuffer physical address
/// `address`. The original takes transfer type PROCESSOR (`_nv044036rm` ->
@@ -857,6 +872,10 @@ pub struct Channel {
/// keeps the frames, as the original's descriptor reference does), the framebuffer
/// offset of that allocation, and the framebuffer address of the 512 bytes.
pub userd_memory: u32,
+ /// Driver-assigned USERD, including synthetic slots on non-hardware providers.
+ pub internal_userd: bool,
+ /// This channel's slot was allocated from the bound Pascal BAR1 VRAM pool.
+ pub pascal_bar1_userd: bool,
pub userd_base: u64,
pub userd: u64,
pub userd_aperture: Aperture,
@@ -1111,11 +1130,13 @@ impl<A: RmAlloc> Table<A> {
owner: u64,
kernel: &KernelIds,
owner_of: &dyn Fn(u32) -> Option<u64>,
+ engine: &dyn Engine,
) -> Option<u32> {
let mut id = 0;
while id < kernel.channels {
let block = id / CHID_BLOCK;
- let foreign = (block < 64 && kernel.channel_blocks >> block & 1 != 0)
+ let foreign = !engine.userd_block_available(gpu, block, owner)
+ || (block < 64 && kernel.channel_blocks >> block & 1 != 0)
|| self.channels.iter().flatten().any(|channel| {
channel.gpu == gpu
&& channel.id / CHID_BLOCK == block
@@ -1619,7 +1640,8 @@ impl<A: RmAlloc> Table<A> {
};
// kchannelAllocHwID.
let kernel = engine.kernel_ids(request.gpu);
- let Some(id) = self.allocate_channel_id(request.gpu, request.owner, &kernel, owner_of)
+ let Some(id) =
+ self.allocate_channel_id(request.gpu, request.owner, &kernel, owner_of, engine)
else {
cleanup_rm_group(self, engine);
return status::NO_MEMORY;
@@ -1628,12 +1650,28 @@ impl<A: RmAlloc> Table<A> {
// Maxwell/Pascal allocate 512-byte BAR1 USERD slots internally when hUserdMemory == 0).
let userd_memory = word(request.params, 0x20);
let userd_offset = quad(request.params, 0x40);
+ let mut pascal_bar1_userd = false;
let (base, userd, userd_aperture, userd_memory, userd_pages, userd_sysmem) = if userd_memory
== 0
{
if matches!(request.class, CLASS_CHANNEL_MAXWELL | CLASS_CHANNEL_PASCAL) {
let slot_off = u64::from(id) * (fifo::USERD_BYTES as u64);
- (slot_off, slot_off, Aperture::Video, 0, 0, None)
+ let (base, userd) = if request.class == CLASS_CHANNEL_PASCAL {
+ match engine.pascal_userd_slot(request.gpu, id) {
+ Ok(Some(slot)) => {
+ pascal_bar1_userd = true;
+ slot
+ }
+ Ok(None) => (slot_off, slot_off),
+ Err(error) => {
+ cleanup_rm_group(self, engine);
+ return error;
+ }
+ }
+ } else {
+ (slot_off, slot_off)
+ };
+ (base, userd, Aperture::Video, 0, 0, None)
} else {
cleanup_rm_group(self, engine);
return status::NOT_SUPPORTED;
@@ -1704,6 +1742,17 @@ impl<A: RmAlloc> Table<A> {
}
}
};
+ if pascal_bar1_userd
+ && !self.channels.iter().flatten().any(|channel| {
+ channel.gpu == request.gpu && channel.id / CHID_BLOCK == id / CHID_BLOCK
+ })
+ {
+ let cleared = engine.clear_pascal_userd_block(request.gpu, userd);
+ if cleared != status::OK {
+ cleanup_rm_group(self, engine);
+ return cleared;
+ }
+ }
let Ok(userd_words) = fifo::userd_words(userd & !0x1ff, userd_aperture) else {
cleanup_rm_group(self, engine);
return status::INVALID_ADDRESS;
@@ -1797,6 +1846,8 @@ impl<A: RmAlloc> Table<A> {
notifier,
token_notif_index: NOTIFY_WORK_SUBMIT_TOKEN,
userd_memory,
+ internal_userd: userd_memory == 0,
+ pascal_bar1_userd,
userd_base: base,
userd,
userd_aperture,
@@ -3211,6 +3262,7 @@ impl<A: RmAlloc> Table<A> {
self.channels.iter().flatten().any(|channel| {
channel.gpu == gpu
&& channel.userd_aperture == Aperture::Video
+ && !channel.internal_userd
&& channel.userd_memory == 0
&& channel.userd_base == base
})
@@ -3547,6 +3599,8 @@ mod unit_tests {
userd: 0,
userd_aperture: Aperture::Video,
userd_pages: 0,
+ internal_userd: false,
+ pascal_bar1_userd: false,
gpfifo: 0,
entries: 16,
notifier: None,
diff --git a/src/nvidia/src/rmapi/channel_tests.rs b/src/nvidia/src/rmapi/channel_tests.rs
index 15ce38d1..57a41daf 100644
--- a/src/nvidia/src/rmapi/channel_tests.rs
+++ b/src/nvidia/src/rmapi/channel_tests.rs
@@ -60,6 +60,8 @@ pub(super) struct RecordingEngine {
pub scrub_rebuild_runlist: Option<u32>,
pub timeslice: Option<(u8, u8)>,
pub dummy: Option<u64>,
+ pascal_pool: Option<u64>,
+ unavailable_userd_block: Option<u32>,
instances: u64,
}
@@ -85,6 +87,8 @@ impl Default for RecordingEngine {
scrub_rebuild_runlist: None,
timeslice: None,
dummy: None,
+ pascal_pool: None,
+ unavailable_userd_block: None,
instances: 0,
}
}
@@ -224,6 +228,21 @@ impl Engine for RecordingEngine {
*word = *word & !clear | set;
self.result("modify")
}
+ fn userd_block_available(&self, _: u32, block: u32, _: u64) -> bool {
+ self.unavailable_userd_block != Some(block)
+ }
+
+ fn pascal_userd_slot(&self, _: u32, id: u32) -> Result<Option<(u64, u64)>, NvStatus> {
+ Ok(self
+ .pascal_pool
+ .map(|base| (base, base + u64::from(id) * 0x200)))
+ }
+
+ fn clear_pascal_userd_block(&mut self, _: u32, address: u64) -> NvStatus {
+ self.log.push(format!("userd-scrub {address:x}"));
+ self.result("userd-scrub")
+ }
+
fn userd_clear(&mut self, _: u32, address: u64, bytes: u32) -> NvStatus {
self.log.push(format!("userd-clear {address:x} {bytes:x}"));
self.result("userd-clear")
@@ -354,6 +373,7 @@ pub(super) struct TestOs {
tokens: u64,
pub stored: BTreeMap<(OsToken, u64), Vec<u8>>,
pub freed: Vec<OsToken>,
+ userd_calls: Vec<String>,
}
impl OsMemory for TestOs {
@@ -410,6 +430,25 @@ impl OsMemory for TestOs {
fn map_video(&mut self, _: u32, _: u64, _: u64, _: i32) -> Result<u64, NvStatus> {
Err(status::NO_MEMORY)
}
+ fn map_pascal_userd(
+ &mut self,
+ gpu: u32,
+ address: u64,
+ length: u64,
+ fd: i32,
+ owner: u64,
+ block: u32,
+ ) -> Result<(u64, u64), NvStatus> {
+ self.userd_calls.push(format!(
+ "map {gpu:x} {address:x} {length:x} {fd} {owner:x} {block}"
+ ));
+ Ok((0xbe20_0000 + (address & 0xfff), 1))
+ }
+
+ fn unmap_pascal_userd(&mut self, cookie: u64) {
+ self.userd_calls.push(format!("revoke {cookie}"));
+ }
+
fn unmap_video(&mut self, _: u32, _: u64) {}
fn map_register(
&mut self,
@@ -3537,6 +3576,104 @@ fn pascal_channel_reports_framebuffer_userd_address_space() {
);
}
+#[test]
+fn pascal_userd_map_requires_owned_backing_and_revokes_the_mapping_cookie() {
+ for boot0 in [0x1300_00a1, 0x1340_00a1] {
+ let mut world = World::bare();
+ let mut facts = GpuFacts::new(boot0, 0x15f8_10de, 0x0000_10de, 0xa1);
+ facts.video = v100().facts.unwrap().video;
+ world.node.gpus.set_facts(GPU, facts).unwrap();
+ let client = world.client;
+ let who = world.who;
+ world.populate(client);
+ world.compute_group(TSG, SHARE);
+ let mut params = ChannelParams::workload(0, NOTIFIER, SHARE);
+ params.userd = 0;
+ params.userd_offset = 0;
+ let allocate = |world: &mut World| {
+ world
+ .alloc(TSG, CH0, channel::CLASS_CHANNEL_PASCAL, &params.bytes())
+ .0
+ };
+
+ let mut map = [0u8; 0x38];
+ put(&mut map, 0, client);
+ put(&mut map, 4, DEVICE);
+ put(&mut map, 8, CH0);
+ put(&mut map, 24, 0x200);
+ put(&mut map, 48, 17);
+ let map_userd = |world: &mut World, map: &[u8]| {
+ let (rc, reply, _) = world.call(&who, escape::RM_MAP_MEMORY, true, map, &[], &mut []);
+ assert_eq!(rc, 0);
+ word(&reply, 40)
+ };
+
+ world.engine.unavailable_userd_block = Some(0);
+ assert_eq!(allocate(&mut world), 0);
+ assert_eq!(map_userd(&mut world, &map), status::NOT_SUPPORTED.0);
+ assert!(world.os.userd_calls.is_empty());
+ assert_eq!(world.free(CH0), 0);
+
+ world.engine.pascal_pool = Some(0x3_fce0_0000);
+ assert_eq!(allocate(&mut world), 0);
+ let channel = world.node.classes.channels.channel(client, CH0).unwrap();
+ assert_eq!(channel.id, channel::CHID_BLOCK);
+ assert_eq!(channel.userd, 0x3_fce0_1000);
+ assert!(world
+ .engine
+ .log
+ .iter()
+ .any(|entry| entry == "userd-scrub 3fce01000"));
+ put(&mut map, 16, 1);
+ assert_ne!(map_userd(&mut world, &map), 0);
+ assert!(world.os.userd_calls.is_empty());
+ put(&mut map, 16, 0);
+ let mut foreign = who;
+ foreign.owner += 1;
+ let (rc, reply, _) = world.call(&foreign, escape::RM_MAP_MEMORY, true, &map, &[], &mut []);
+ assert_eq!((rc, word(&reply, 40)), (0, status::INVALID_CLIENT.0));
+ assert!(world.os.userd_calls.is_empty());
+ assert_eq!(map_userd(&mut world, &map), 0);
+ assert_eq!(
+ world.os.userd_calls,
+ [format!("map {GPU:x} 3fce01000 200 17 1000 1")]
+ );
+
+ let mut unmap = [0u8; 0x20];
+ put(&mut unmap, 0, client);
+ put(&mut unmap, 4, DEVICE);
+ put(&mut unmap, 8, CH0);
+ put(&mut unmap, 16, 0xbe20_0000);
+ let (rc, reply, _) = world.call(&who, escape::RM_UNMAP_MEMORY, true, &unmap, &[], &mut []);
+ assert_eq!((rc, word(&reply, 24)), (0, 0));
+ assert_eq!(world.os.userd_calls.last().unwrap(), "revoke 1");
+
+ // Eight distinct channel handles on a single page and GPU fd. The OS
+ // returns one page cookie with a different address for each slot.
+ for slot in 0..channel::CHID_BLOCK {
+ let handle = CH0 + slot;
+ if slot != 0 {
+ assert_eq!(
+ world.alloc(TSG, handle, channel::CLASS_CHANNEL_PASCAL, &params.bytes()).0,
+ 0
+ );
+ }
+ put(&mut map, 8, handle);
+ assert_eq!(map_userd(&mut world, &map), 0);
+ }
+ let release_start = world.os.userd_calls.len();
+ // One explicit unmap, including the slot's nonzero page displacement.
+ put(&mut unmap, 8, CH0 + 1);
+ put(&mut unmap, 16, 0xbe20_0200);
+ let (rc, reply, _) = world.call(&who, escape::RM_UNMAP_MEMORY, true, &unmap, &[], &mut []);
+ assert_eq!((rc, word(&reply, 24)), (0, 0));
+ for slot in 0..channel::CHID_BLOCK {
+ assert_eq!(world.free(CH0 + slot), 0);
+ }
+ assert_eq!(&world.os.userd_calls[release_start..], ["revoke 1"; 8]);
+ }
+}
+
#[test]
fn register_windows_usermode_and_subdevice_master() {
let mut world = World::new();
diff --git a/src/nvidia/src/rmapi/gpu.rs b/src/nvidia/src/rmapi/gpu.rs
index 730ca13c..6e2942db 100644
--- a/src/nvidia/src/rmapi/gpu.rs
+++ b/src/nvidia/src/rmapi/gpu.rs
@@ -5564,6 +5564,14 @@ impl<const N: usize, A: RmAlloc> Objects for Bound<'_, N, A> {
}
Some(Kind::Channel) => {
let channel = self.classes.channels.channel(object.client, object.handle);
+ if channel.is_some_and(|channel| channel.pascal_bar1_userd) {
+ let os = &mut *self.os;
+ self.classes
+ .memory
+ .drop_mappings(object.client, object.handle, |mapping| {
+ os.unmap_pascal_userd(mapping.userd_cookie);
+ });
+ }
self.classes
.channels
.channel_free(&mut *self.engine, object.client, object.handle);
@@ -5572,7 +5580,7 @@ impl<const N: usize, A: RmAlloc> Objects for Bound<'_, N, A> {
// such channel.
if let Some(channel) = channel {
match channel.userd_aperture {
- Aperture::Video if channel.userd_memory == 0 => {
+ Aperture::Video if !channel.internal_userd && channel.userd_memory == 0 => {
if !self
.classes
.channels
diff --git a/src/nvidia/src/rmapi/memory.rs b/src/nvidia/src/rmapi/memory.rs
index b10a2f6b..f70abab0 100644
--- a/src/nvidia/src/rmapi/memory.rs
+++ b/src/nvidia/src/rmapi/memory.rs
@@ -1526,6 +1526,18 @@ pub trait OsMemory {
descriptor: i32,
) -> Result<u64, NvStatus>;
/// Hardware: the end of such a mapping.
+ fn map_pascal_userd(
+ &mut self,
+ _gpu: u32,
+ _address: u64,
+ _length: u64,
+ _descriptor: i32,
+ _owner: u64,
+ _block: u32,
+ ) -> Result<(u64, u64), NvStatus> {
+ Err(status::NOT_SUPPORTED)
+ }
+ fn unmap_pascal_userd(&mut self, _cookie: u64) {}
fn unmap_video(&mut self, gpu: u32, address: u64);
/// Hardware: a CPU mapping of a BAR0 register window (`0xc361` usermode doorbell or
/// `0x90e6` PMC page); returns the physical address (`BAR0 + offset`) and attaches an
@@ -1691,6 +1703,8 @@ pub struct Mapping {
/// The address the request returned; `NV_ESC_RM_UNMAP_MEMORY` names the mapping by it.
pub address: u64,
pub video: bool,
+ /// GPU file's unique USERD VMA key; zero for other mappings.
+ pub userd_cookie: u64,
}
pub const OBJECTS: usize = 2560;
diff --git a/src/nvidia/src/rmapi/node.rs b/src/nvidia/src/rmapi/node.rs
index 05f21608..36e0e158 100644
--- a/src/nvidia/src/rmapi/node.rs
+++ b/src/nvidia/src/rmapi/node.rs
@@ -934,6 +934,7 @@ impl<const C: usize, const R: usize, A: RmAlloc> ControlNode<C, R, A> {
if !matches!(parent.kind, Kind::Device | Kind::Subdevice) {
return status::INVALID_OBJECT_PARENT;
}
+ let mut userd_block = None;
let object = match target.kind {
Kind::Memory => match self.classes.memory.find(client, handle) {
Some(object) => object,
@@ -941,24 +942,44 @@ impl<const C: usize, const R: usize, A: RmAlloc> ControlNode<C, R, A> {
},
// Maxwell (`0xb06f`) / Pascal (`0xc06f`) pre-Volta CUDA maps the channel handle
// directly via NV_ESC_RM_MAP_MEMORY to get its BAR1 USERD doorbell page.
- Kind::Channel => match self.classes.channels.channel_userd(client, handle) {
- Some((gpu, userd, Aperture::Video)) if userd != 0 => memory::Object {
+ Kind::Channel => {
+ let Some(channel) = self.classes.channels.channel(client, handle) else {
+ return status::NOT_SUPPORTED;
+ };
+ if channel.gpu != parent.gpu_id {
+ return status::INVALID_OBJECT_PARENT;
+ }
+ let size = if channel.pascal_bar1_userd {
+ userd_block = Some(channel.id / channel::CHID_BLOCK);
+ crate::fifo::USERD_BYTES as u64
+ } else {
+ if channel.userd_aperture != Aperture::Video
+ || channel.userd == 0
+ || self.gpus.facts(channel.gpu).is_some_and(|gpu| {
+ matches!(gpu.arch(), [0x130, 0 | 4, _])
+ })
+ {
+ // Only the driver-owned Pascal pool has an established BAR1 route.
+ return status::NOT_SUPPORTED;
+ }
+ 0x1000
+ };
+ memory::Object {
client,
handle,
- gpu,
- size: 0x1000,
+ gpu: channel.gpu,
+ size,
backing: Backing::Video {
- offset: userd & !0x1ff,
- bytes: 0x1000,
+ offset: channel.userd & !0x1ff,
+ bytes: size,
page: 0x1000,
pte_kind: 0,
scatter_id: 0,
},
p2p: 0,
duped: false,
- },
- _ => return status::NOT_SUPPORTED,
- },
+ }
+ }
Kind::Device | Kind::Subdevice => return status::INVALID_OBJECT_PARENT,
// A class without a CPU mapping.
_ => return status::NOT_SUPPORTED,
@@ -1025,6 +1046,7 @@ impl<const C: usize, const R: usize, A: RmAlloc> ControlNode<C, R, A> {
memory: handle,
address,
video: false,
+ userd_cookie: 0,
});
status::OK
}
@@ -1036,20 +1058,32 @@ impl<const C: usize, const R: usize, A: RmAlloc> ControlNode<C, R, A> {
if seg_avail < length {
return status::NOT_SUPPORTED;
}
- let address = match os.map_video(object.gpu, phys, length, descriptor) {
- Ok(address) => address,
+ let result = if let Some(block) = userd_block {
+ os.map_pascal_userd(object.gpu, phys, length, descriptor, caller.owner, block)
+ } else {
+ os.map_video(object.gpu, phys, length, descriptor)
+ .map(|address| (address, 0))
+ };
+ let (address, userd_cookie) = match result {
+ Ok(values) => values,
Err(status) => return status,
};
top[32..40].copy_from_slice(&address.to_le_bytes());
// A BAR1 mapping is reflected and write-combined (observed on the original:
// the workload's request 0xc0000 comes back as 0x010d0000).
set_word(top, 44, flags & !(7 << 23) & !(3 << 15) | 2 << 23 | 2 << 15);
- let _ = self.classes.memory.add_mapping(memory::Mapping {
+ if let Err(error) = self.classes.memory.add_mapping(memory::Mapping {
client,
memory: handle,
address,
video: true,
- });
+ userd_cookie,
+ }) {
+ if userd_cookie != 0 {
+ os.unmap_pascal_userd(userd_cookie);
+ }
+ return error;
+ }
status::OK
}
Backing::Register {
@@ -1076,6 +1110,7 @@ impl<const C: usize, const R: usize, A: RmAlloc> ControlNode<C, R, A> {
memory: handle,
address,
video: false,
+ userd_cookie: 0,
});
status::OK
}
@@ -1093,6 +1128,10 @@ impl<const C: usize, const R: usize, A: RmAlloc> ControlNode<C, R, A> {
let Some(mapping) = self.classes.memory.take_mapping(client, handle, address) else {
return status::OBJECT_NOT_FOUND;
};
+ if mapping.userd_cookie != 0 {
+ os.unmap_pascal_userd(mapping.userd_cookie);
+ return status::OK;
+ }
match self
.classes
.memory
@@ -1731,6 +1770,7 @@ impl<const C: usize, const R: usize, A: RmAlloc> ControlNode<C, R, A> {
memory: new,
address,
video: false,
+ userd_cookie: 0,
});
status::OK
}