diff --git a/dkms.conf b/dkms.conf index abb6a30e..e7f2be7c 100644 --- a/dkms.conf +++ b/dkms.conf @@ -1,10 +1,22 @@ PACKAGE_NAME="nvdriver" -PACKAGE_VERSION="0.1.0" +PACKAGE_VERSION="0.2.0" BUILT_MODULE_NAME[0]="nvidia_rs" BUILT_MODULE_LOCATION[0]="kernel-open" DEST_MODULE_LOCATION[0]="/updates/nvdriver" -MAKE[0]="make KDIR=${kernel_source_dir} modules" +BUILT_MODULE_NAME[1]="nvidia_rs_modeset" +BUILT_MODULE_LOCATION[1]="kernel-open" +DEST_MODULE_LOCATION[1]="/updates/nvdriver" + +BUILT_MODULE_NAME[2]="nvidia_rs_drm" +BUILT_MODULE_LOCATION[2]="kernel-open" +DEST_MODULE_LOCATION[2]="/updates/nvdriver" + +BUILT_MODULE_NAME[3]="nvidia_rs_peermem" +BUILT_MODULE_LOCATION[3]="kernel-open" +DEST_MODULE_LOCATION[3]="/updates/nvdriver" + +MAKE[0]="make KERNEL_UNAME=${kernelver} KERNEL_SOURCES=${kernel_source_dir} modules" CLEAN="make clean" AUTOINSTALL="yes" diff --git a/install.sh b/install.sh index 7c0954fd..10175834 100755 --- a/install.sh +++ b/install.sh @@ -8,7 +8,7 @@ set -euo pipefail cd "$(dirname "$(readlink -f "$0")")" -KREL=$(uname -r) +KREL=${KREL:-$(uname -r)} SIGN_FILE=/lib/modules/$KREL/build/scripts/sign-file MOK_PRIV=${MOK_PRIV:-/var/lib/shim-signed/mok/MOK.priv} MOK_DER=${MOK_DER:-/var/lib/shim-signed/mok/MOK.der} @@ -115,6 +115,9 @@ install_volta_forever() { echo "== build ==" make modules KO_FILES=(kernel-open/nvidia_rs.ko) +for opt_ko in kernel-open/nvidia_rs_modeset.ko kernel-open/nvidia_rs_drm.ko kernel-open/nvidia_rs_peermem.ko; do + [ -f "$opt_ko" ] && KO_FILES+=("$opt_ko") +done if [ "$BUILD_BRIDGES" = "1" ]; then make uvm-bridge make modeset-bridge @@ -149,12 +152,12 @@ for f in /dev/nvidia[0-9]* /dev/nvidiactl /dev/nvidia-uvm /dev/nvidia-modeset; d if mountpoint -q "$f" 2>/dev/null; then sudo umount "$f" 2>/dev/null || true; fi done if [ -d /sys/bus/pci/drivers/nvidia_rs ]; then - for dev in /sys/bus/pci/drivers/nvidia_rs/0000:*; do + for dev in /sys/bus/pci/drivers/nvidia_rs/[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:*; do [ -e "$dev" ] || continue echo "$(basename "$dev")" | sudo tee /sys/bus/pci/drivers/nvidia_rs/unbind >/dev/null 2>&1 || true done fi -for m in nvidia_drm nvidia_modeset nvidia_rs_modeset_bridge nvidia_uvm nvidia_rs_uvm_bridge nvidia_rs; do +for m in nvidia_drm nvidia_modeset nvidia_rs_drm nvidia_rs_modeset nvidia_rs_peermem nvidia_rs_modeset_bridge nvidia_uvm nvidia_rs_uvm_bridge nvidia_rs; do if lsmod | grep -q "^$m "; then sudo rmmod "$m"; fi done if lsmod | grep -q '^nvidia_rs '; then diff --git a/kernel-open/Kbuild b/kernel-open/Kbuild index a1c45280..5deabe26 100644 --- a/kernel-open/Kbuild +++ b/kernel-open/Kbuild @@ -5,7 +5,21 @@ NV_RS_PCI_H := $(srctree)/include/linux/pci.h ifeq ($(shell grep -A2 -E 'pci_resize_resource' $(NV_RS_PCI_H) 2>/dev/null | grep -q exclude_bars && echo y),y) ccflags-y += -DNV_RS_PCI_RESIZE_EXCLUDE_BARS endif -obj-m += nvidia_rs.o nvidia_rs_modeset.o nvidia_rs_drm.o nvidia_rs_peermem.o +NV_RS_TIMER_H := $(srctree)/include/linux/timer.h +ifeq ($(shell grep -q 'timer_delete_sync' $(NV_RS_TIMER_H) 2>/dev/null && echo y),y) +ccflags-y += -DNV_RS_HAVE_TIMER_DELETE_SYNC +endif +NV_RS_MM_H := $(srctree)/include/linux/mm.h +ifeq ($(shell grep -q 'vm_flags_set' $(NV_RS_MM_H) 2>/dev/null && echo y),y) +ccflags-y += -DNV_RS_HAVE_VM_FLAGS_SET +endif +ifeq ($(shell grep -q 'vma_flags_set_word' $(NV_RS_MM_H) 2>/dev/null && echo y),y) +ccflags-y += -DNV_RS_HAVE_VMA_FLAGS_SET_WORD +endif +obj-m += nvidia_rs.o nvidia_rs_modeset.o nvidia_rs_peermem.o +ifneq ($(CONFIG_DRM),) +obj-m += nvidia_rs_drm.o +endif nvidia_rs_modeset-y := nvidia-modeset/nvidia_rs_modeset.o nvidia_rs_drm-y := nvidia-drm/nvidia_rs_drm.o nvidia_rs_peermem-y := nvidia-peermem/nvidia_rs_peermem.o diff --git a/kernel-open/nvidia/dma_adapter.c b/kernel-open/nvidia/dma_adapter.c index ed4a9b18..f1ddc9ed 100644 --- a/kernel-open/nvidia/dma_adapter.c +++ b/kernel-open/nvidia/dma_adapter.c @@ -261,9 +261,8 @@ int nv_rs_dma_read(struct nv_rs_dma_context *ctx, const struct nv_rs_dma_backing mutex_lock(&ctx->lock); s = lookup(ctx, b); if (!s || end > s->bytes) { mutex_unlock(&ctx->lock); return -EINVAL; } if (bytes) { -#if defined(CONFIG_ARM64) && !defined(NV_RS_DMA_HOST_FIXTURE) - dma_sync_single_for_cpu(ctx->device, s->dma + offset, (size_t)bytes, DMA_FROM_DEVICE); -#endif + /* Coherent DMA allocations are already mapped non-cacheable/coherent on + * non-coherent ARM64; only memory barriers are valid (never dma_sync_single_*). */ dma_rmb(); memcpy(destination, (char *)s->cpu + offset, (size_t)bytes); } @@ -281,9 +280,6 @@ int nv_rs_dma_write(struct nv_rs_dma_context *ctx, const struct nv_rs_dma_backin if (bytes) { memcpy((char *)s->cpu + offset, source, (size_t)bytes); dma_wmb(); -#if defined(CONFIG_ARM64) && !defined(NV_RS_DMA_HOST_FIXTURE) - dma_sync_single_for_device(ctx->device, s->dma + offset, (size_t)bytes, DMA_TO_DEVICE); -#endif } mutex_unlock(&ctx->lock); return 0; } @@ -321,11 +317,8 @@ int nv_rs_dma_flush_sysmem(struct nv_rs_dma_context *ctx, const struct nv_rs_dma if (!ctx) return -EINVAL; mutex_lock(&ctx->lock); s = lookup(ctx, b); if (!s || !s->mapped) { mutex_unlock(&ctx->lock); return -EINVAL; } - /* Exact580 SYSTEM_MEMORY kbusFlushSingle path: full CPU fence, plus explicit - * cache clean on non-coherent ARM64 SBCs (e.g. RK3588). */ + /* Exact580 SYSTEM_MEMORY kbusFlushSingle path: full CPU fence. Coherent DMA + * allocations are already non-cacheable/coherent on ARM64. */ mb(); -#if defined(CONFIG_ARM64) && !defined(NV_RS_DMA_HOST_FIXTURE) - dma_sync_single_for_device(ctx->device, s->dma, (size_t)s->bytes, DMA_BIDIRECTIONAL); -#endif mutex_unlock(&ctx->lock); return 0; } diff --git a/kernel-open/nvidia/ga10x_adapter.c b/kernel-open/nvidia/ga10x_adapter.c index d6b1e89f..ceb12c8b 100644 --- a/kernel-open/nvidia/ga10x_adapter.c +++ b/kernel-open/nvidia/ga10x_adapter.c @@ -151,18 +151,7 @@ int nv_rs_ga10x_cfg_write32(struct nv_rs_pci *pci, u32 offset, u32 value) int nv_rs_ga10x_bar0_fill32(struct nv_rs_pci *pci, u64 offset, u32 value, u32 count); int nv_rs_ga10x_bar0_fill32(struct nv_rs_pci *pci, u64 offset, u32 value, u32 count) { - u64 mapped, physical, bytes; - void __iomem *p; - u32 i; - - if (nv_rs_pci_bar0_info(pci, &mapped, &physical, &bytes)) - return -ENODEV; - if ((offset & 3) || offset > bytes || (u64)count * 4 > bytes - offset) - return -ERANGE; - p = (void __iomem *)(unsigned long)mapped + offset; - for (i = 0; i < count; i++) - writel(value, p + 4 * i); - return 0; + return nv_rs_pci_bar0_fill32(pci, offset, value, count); } bool nv_rs_os_capable_admin(void); diff --git a/kernel-open/nvidia/nano_timer_adapter.c b/kernel-open/nvidia/nano_timer_adapter.c index bd2730fe..0d6cdd92 100644 --- a/kernel-open/nvidia/nano_timer_adapter.c +++ b/kernel-open/nvidia/nano_timer_adapter.c @@ -21,6 +21,14 @@ struct nv_rs_nano_timer { void *payload; bool stopping,closed; }; +static inline int nv_rs_timer_delete_sync(struct timer_list *t) +{ +#if defined(NV_RS_HAVE_TIMER_DELETE_SYNC) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 2, 0) + return timer_delete_sync(t); +#else + return del_timer_sync(t); +#endif +} static bool process_context(void) { return !in_interrupt() && !irqs_disabled() && !in_atomic(); } void *nv_rs_nano_payload_alloc(size_t bytes) @@ -97,7 +105,7 @@ int nv_rs_nano_cancel(struct nv_rs_nano_timer *owner,u32 *was_active) } owner->stopping=true; spin_unlock_irqrestore(&owner->state_lock,flags); - active=owner->jiffy?timer_delete_sync(&owner->jiffy_timer):hrtimer_cancel(&owner->timer); + active=owner->jiffy?nv_rs_timer_delete_sync(&owner->jiffy_timer):hrtimer_cancel(&owner->timer); spin_lock_irqsave(&owner->state_lock,flags); owner->stopping=false; spin_unlock_irqrestore(&owner->state_lock,flags); @@ -115,7 +123,7 @@ int nv_rs_nano_destroy(struct nv_rs_nano_timer *owner) spin_lock_irqsave(&owner->state_lock,flags); owner->closed=true;owner->stopping=true; spin_unlock_irqrestore(&owner->state_lock,flags); - if(owner->jiffy)timer_delete_sync(&owner->jiffy_timer);else hrtimer_cancel(&owner->timer); + if(owner->jiffy)nv_rs_timer_delete_sync(&owner->jiffy_timer);else hrtimer_cancel(&owner->timer); mutex_unlock(&owner->stop_lock); kfree(owner);return 0; } diff --git a/kernel-open/nvidia/pci_adapter.c b/kernel-open/nvidia/pci_adapter.c index fef738e1..59ac1d1a 100644 --- a/kernel-open/nvidia/pci_adapter.c +++ b/kernel-open/nvidia/pci_adapter.c @@ -170,7 +170,7 @@ int nv_rs_pci_open(struct pci_dev *pdev, struct nv_rs_pci **out) pci_release_resource(pdev, bar1); pci_release_resource(pdev, bar3); for (;;) { -#if defined(NV_RS_PCI_RESIZE_EXCLUDE_BARS) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 19, 0) || defined(UTS_UBUNTU_RELEASE_ABI) +#if defined(NV_RS_PCI_RESIZE_EXCLUDE_BARS) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 19, 0) r = pci_resize_resource(pdev, bar1, requested, 0); #else r = pci_resize_resource(pdev, bar1, requested); @@ -190,7 +190,7 @@ int nv_rs_pci_open(struct pci_dev *pdev, struct nv_rs_pci **out) if ((pci_resource_flags(pdev, bar1) & IORESOURCE_UNSET) || (pci_resource_flags(pdev, bar3) & IORESOURCE_UNSET)) { if (requested != old_size) { -#if defined(NV_RS_PCI_RESIZE_EXCLUDE_BARS) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 19, 0) || defined(UTS_UBUNTU_RELEASE_ABI) +#if defined(NV_RS_PCI_RESIZE_EXCLUDE_BARS) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 19, 0) (void)pci_resize_resource(pdev, bar1, old_size, 0); #else (void)pci_resize_resource(pdev, bar1, old_size); @@ -509,6 +509,24 @@ int nv_rs_pci_write32(struct nv_rs_pci *p, u64 offset, u32 value) { return nv_rs_pci_access(p, offset, &value, true); } +int nv_rs_pci_bar0_fill32(struct nv_rs_pci *p, u64 offset, u32 value, u32 count) +{ + u32 i; + int error = 0; + if (!p || (offset & 3)) return -EINVAL; + mutex_lock(&p->access); + if (nv_rs_pci_is_removed(p) || !p->bar0) + error = -ENODEV; + else if (offset > p->length || (u64)count * 4 > p->length - offset) + error = -ERANGE; + else { + char __iomem *dst = (char __iomem *)p->bar0 + offset; + for (i = 0; i < count; i++) + writel(value, dst + 4 * i); + } + mutex_unlock(&p->access); + return error; +} /* Explicit readback for a caller-selected safe register, never unconditional * offset-zero reads after writes: register side effects are chip-specific. */ int nv_rs_pci_flush32(struct nv_rs_pci *p, u64 offset, u32 *value) diff --git a/kernel-open/nvidia/pci_adapter.h b/kernel-open/nvidia/pci_adapter.h index d307903e..10f5309e 100644 --- a/kernel-open/nvidia/pci_adapter.h +++ b/kernel-open/nvidia/pci_adapter.h @@ -45,6 +45,7 @@ int nv_rs_pci_bar1_read32(struct nv_rs_pci *pci, u64 offset, u32 *value); int nv_rs_pci_bar1_write32(struct nv_rs_pci *pci, u64 offset, u32 value); int nv_rs_pci_read32(struct nv_rs_pci *pci, u64 offset, u32 *value); int nv_rs_pci_write32(struct nv_rs_pci *pci, u64 offset, u32 value); +int nv_rs_pci_bar0_fill32(struct nv_rs_pci *pci, u64 offset, u32 value, u32 count); /* Hardirq callers hold a PCI lease; close/synchronize IRQs before remove. * No sleeping or register-RMW serialization is provided by these primitives. */ int nv_rs_pci_read32_irq(struct nv_rs_pci *pci, u64 offset, u32 *value); diff --git a/kernel-open/nvidia/pci_driver.c b/kernel-open/nvidia/pci_driver.c index e91d0bb1..0e6e625e 100644 --- a/kernel-open/nvidia/pci_driver.c +++ b/kernel-open/nvidia/pci_driver.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MIT /* Opt-in ownership path. A bound PCI device is not a CUDA-ready GPU. */ #include +#include #include #include #include @@ -324,6 +325,50 @@ static const struct dev_pm_ops nv_rs_pm_ops = { }; #endif /* CONFIG_PM */ +/* Match stock 580.178.04 nv_pci_shutdown (nvidia/nv-pci.c:786-816): quiesce + * runtime engines and clear Bus Master Enable so kexec/reboot cannot observe + * stray GPU DMA writes into host memory. */ +static void nv_rs_shutdown(struct pci_dev *pdev) +{ + struct nv_rs_gpu_owner *owner = pci_get_drvdata(pdev); + if (owner) + nv_rs_gpu_owner_runtime_stop(owner); + pci_clear_master(pdev); + udelay(1); +} + +static pci_ers_result_t nv_rs_aer_error_detected(struct pci_dev *pdev, + pci_channel_state_t state) +{ + struct nv_rs_gpu_owner *owner = pci_get_drvdata(pdev); + dev_err(&pdev->dev, "nvidia_rs: PCIe AER error detected (state=%d)\n", state); + if (owner) + nv_rs_gpu_owner_runtime_stop(owner); + pci_clear_master(pdev); + if (state == pci_channel_io_perm_failure) + return PCI_ERS_RESULT_DISCONNECT; + return PCI_ERS_RESULT_NEED_RESET; +} + +static pci_ers_result_t nv_rs_aer_slot_reset(struct pci_dev *pdev) +{ + if (pci_enable_device_mem(pdev)) + return PCI_ERS_RESULT_DISCONNECT; + pci_set_master(pdev); + return PCI_ERS_RESULT_RECOVERED; +} + +static void nv_rs_aer_resume(struct pci_dev *pdev) +{ + dev_info(&pdev->dev, "nvidia_rs: PCIe AER resume complete\n"); +} + +static const struct pci_error_handlers nv_rs_err_handlers = { + .error_detected = nv_rs_aer_error_detected, + .slot_reset = nv_rs_aer_slot_reset, + .resume = nv_rs_aer_resume, +}; + static const struct pci_device_id nv_rs_ids[] = { { .vendor = 0x10de, .device = PCI_ANY_ID, .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, .class = PCI_BASE_CLASS_DISPLAY << 16, @@ -334,6 +379,8 @@ static const struct pci_device_id nv_rs_ids[] = { static struct pci_driver nv_rs_driver = { .name = "nvidia_rs", .id_table = nv_rs_ids, .probe = nv_rs_probe, .remove = nv_rs_remove, + .shutdown = nv_rs_shutdown, + .err_handler = &nv_rs_err_handlers, #ifdef CONFIG_PM .driver.pm = &nv_rs_pm_ops, #endif diff --git a/kernel-open/nvidia/rmapi_node.c b/kernel-open/nvidia/rmapi_node.c index 01aaa84e..11821e26 100644 --- a/kernel-open/nvidia/rmapi_node.c +++ b/kernel-open/nvidia/rmapi_node.c @@ -236,6 +236,7 @@ struct nv_rs_rmapi_alloc { unsigned int users; bool user_pinned; bool writable; + bool freed; void *kernel; struct page *pages[]; }; @@ -618,7 +619,7 @@ static struct nv_rs_rmapi_alloc *nv_rs_rmapi_alloc_find(u64 token) { struct nv_rs_rmapi_alloc *alloc; list_for_each_entry(alloc, &nv_rs_rmapi_allocs, link) - if (alloc->token == token) + if (!alloc->freed && alloc->token == token) return alloc; return NULL; } @@ -630,12 +631,16 @@ static void nv_rs_rmapi_alloc_unmap(struct nv_rs_rmapi_alloc *alloc) alloc->kernel = NULL; } -/* Drops one use; the last one frees the record and the allocator's page references. */ +/* Drops one use; the last one unlinks, frees the record, and releases page references. */ static void nv_rs_rmapi_alloc_put(struct nv_rs_rmapi_alloc *alloc) { u64 index; if (--alloc->users) return; + mutex_lock(&nv_rs_rmapi_alloc_lock); + if (!list_empty(&alloc->link)) + list_del_init(&alloc->link); + mutex_unlock(&nv_rs_rmapi_alloc_lock); nv_rs_rmapi_alloc_unmap_dma(alloc); nv_rs_rmapi_alloc_unmap(alloc); if (alloc->user_pinned) { @@ -775,14 +780,16 @@ u32 nv_rs_rmapi_os_alloc_pages(u64 count, u64 page, bool contiguous, u32 cache, return 0; } -/* nv_free_pages: the RM object is gone; the token names nothing from here on. */ +/* nv_free_pages: the RM object is gone; the token names nothing from here on, + * while remaining on nv_rs_rmapi_allocs until users == 0 so hot-unplug DMA + * teardown never misses a record still held by a file mapping context. */ void nv_rs_rmapi_os_free_pages(u64 token) { struct nv_rs_rmapi_alloc *alloc; mutex_lock(&nv_rs_rmapi_alloc_lock); alloc = nv_rs_rmapi_alloc_find(token); if (alloc) - list_del(&alloc->link); + alloc->freed = true; mutex_unlock(&nv_rs_rmapi_alloc_lock); if (!alloc) return; @@ -1525,6 +1532,28 @@ static const struct vm_operations_struct nv_rs_rmapi_vm_operations = { * * The context is immutable once valid and holds a use of the allocation until the file is * released, so nothing is locked here. */ +static inline void nv_rs_vm_flags_set(struct vm_area_struct *vma, vm_flags_t flags) +{ +#if defined(NV_RS_HAVE_VMA_FLAGS_SET_WORD) + vma_flags_set_word(&vma->flags, flags); +#elif defined(NV_RS_HAVE_VM_FLAGS_SET) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0) + vm_flags_set(vma, flags); +#else + vma->vm_flags |= flags; +#endif +} + +static inline void nv_rs_vm_flags_clear(struct vm_area_struct *vma, vm_flags_t flags) +{ +#if defined(NV_RS_HAVE_VMA_FLAGS_SET_WORD) + vma_flags_clear_word(&vma->flags, flags); +#elif defined(NV_RS_HAVE_VM_FLAGS_SET) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0) + vm_flags_clear(vma, flags); +#else + vma->vm_flags &= ~flags; +#endif +} + static int nv_rs_rmapi_mmap(struct file *file, struct vm_area_struct *vma) { struct nv_rs_rmapi_file *context = file->private_data; @@ -1540,40 +1569,24 @@ static int nv_rs_rmapi_mmap(struct file *file, struct vm_area_struct *vma) if (!size || size > mapping->io_bytes) return -ERANGE; if (!(mapping->protection & 2)) { -#if defined(RHEL_RELEASE_CODE) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0) - vm_flags_clear(vma, VM_WRITE | VM_MAYWRITE); -#else - vma->vm_flags &= ~(VM_WRITE | VM_MAYWRITE); -#endif + nv_rs_vm_flags_clear(vma, VM_WRITE | VM_MAYWRITE); vma->vm_page_prot = vm_get_page_prot(vma->vm_flags); } if (mapping->caching == 2) vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); else vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); -#if defined(RHEL_RELEASE_CODE) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0) - vm_flags_set(vma, VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP); -#else - vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP; -#endif + nv_rs_vm_flags_set(vma, VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP); return remap_pfn_range(vma, vma->vm_start, mapping->io_phys >> PAGE_SHIFT, size, vma->vm_page_prot); } if (mapping->page_index + pages > mapping->alloc->count) return -ERANGE; if (!(mapping->protection & 2)) { -#if defined(RHEL_RELEASE_CODE) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0) - vm_flags_clear(vma, VM_WRITE | VM_MAYWRITE); -#else - vma->vm_flags &= ~(VM_WRITE | VM_MAYWRITE); -#endif + nv_rs_vm_flags_clear(vma, VM_WRITE | VM_MAYWRITE); vma->vm_page_prot = vm_get_page_prot(vma->vm_flags); } -#if defined(RHEL_RELEASE_CODE) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0) - vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP); -#else - vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP; -#endif + nv_rs_vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP); vma->vm_ops = &nv_rs_rmapi_vm_operations; for (index = mapping->page_index; index < mapping->page_index + pages; index++) { /* On failure the caller removes the area and with it the pages inserted so far. */ diff --git a/kernel-open/nvidia/rom_fw_adapter.c b/kernel-open/nvidia/rom_fw_adapter.c index 7b0a4420..dc6cff57 100644 --- a/kernel-open/nvidia/rom_fw_adapter.c +++ b/kernel-open/nvidia/rom_fw_adapter.c @@ -11,7 +11,9 @@ #include #include #include +#if defined(CONFIG_X86) #include +#endif #include #include "pci_adapter.h" #endif @@ -78,7 +80,12 @@ static int restore_pages_wb(unsigned long address, unsigned int pages) #ifdef NV_RS_ROM_FW_VM_FIXTURE if (vm_wb_failures) { vm_wb_failures--; return -EIO; } #endif +#if defined(CONFIG_X86) || defined(NV_RS_ROM_FW_HOST_FIXTURE) return set_memory_wb(address,pages); +#else + (void)address; (void)pages; + return 0; +#endif } static atomic64_t rom_fw_next_token = ATOMIC64_INIT(1); static u64 next_token(void) @@ -98,7 +105,7 @@ static int verify_pages(struct rom_fw_descriptor *d, u32 cache) { #ifdef NV_RS_ROM_FW_HOST_FIXTURE return rom_fw_mock_verify_pages(d->page, d->cpu, d->allocated, cache); -#else +#elif defined(CONFIG_X86) unsigned long i, base = page_to_pfn(d->page); unsigned long expected = cachemode2protval(cache ? _PAGE_CACHE_MODE_UC_MINUS : _PAGE_CACHE_MODE_WB) & _PAGE_CACHE_MASK; for (i = 0; i < d->allocated / PAGE_SIZE; i++) { @@ -113,6 +120,9 @@ static int verify_pages(struct rom_fw_descriptor *d, u32 cache) if ((value & _PAGE_CACHE_MASK) != expected) return -EIO; } return 0; +#else + (void)d; (void)cache; + return 0; #endif } int nv_rs_rom_fw_create(struct nv_rs_pci *pci, u32 bits, u64 alignment, struct nv_rs_rom_fw **out) @@ -203,7 +213,11 @@ int nv_rs_rom_fw_allocate(struct nv_rs_rom_fw *c, u64 token) /* Failure may have changed a prefix. Retain all pages until WB restore * succeeds; neither DMA failure nor removal may free UC pages. */ d->restore_wb = true; +#if defined(CONFIG_X86) || defined(NV_RS_ROM_FW_HOST_FIXTURE) error = set_memory_uc((unsigned long)d->cpu, d->allocated >> PAGE_SHIFT); +#else + error = 0; +#endif if (error) { mutex_unlock(&c->lock); return error; } } error = verify_pages(d, d->spec.cpu_cache); diff --git a/kernel-open/nvidia/uvm_node.c b/kernel-open/nvidia/uvm_node.c index 74bc21d1..cb4b0a84 100644 --- a/kernel-open/nvidia/uvm_node.c +++ b/kernel-open/nvidia/uvm_node.c @@ -556,7 +556,9 @@ static int nv_rs_uvm_mmap(struct file *file, struct vm_area_struct *vma) return -EBADFD; shared_rw = (vma->vm_flags & (VM_SHARED | VM_READ | VM_WRITE)) == (VM_SHARED | VM_READ | VM_WRITE); -#if defined(RHEL_RELEASE_CODE) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0) +#if defined(NV_RS_HAVE_VMA_FLAGS_SET_WORD) + vma_flags_set_word(&vma->flags, VM_MIXEDMAP | VM_DONTEXPAND | VM_DONTCOPY); +#elif defined(NV_RS_HAVE_VM_FLAGS_SET) || LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0) vm_flags_set(vma, VM_MIXEDMAP | VM_DONTEXPAND | VM_DONTCOPY); #else vma->vm_flags |= VM_MIXEDMAP | VM_DONTEXPAND | VM_DONTCOPY; @@ -600,6 +602,29 @@ int nv_rs_uvm_node_init(void) return misc_register(&nv_rs_uvm_device); } +static void nv_rs_uvm_drain_cpu_dma_ht(void) +{ + unsigned long flags; + struct nv_rs_uvm_cpu_dma_entry *e; + struct hlist_node *tmp; + HLIST_HEAD(dead); + unsigned int bkt; + + spin_lock_irqsave(&nv_rs_uvm_cpu_dma_lock, flags); + hash_for_each_safe(nv_rs_uvm_cpu_dma_ht, bkt, tmp, e, node) { + hash_del(&e->node); + hlist_add_head(&e->node, &dead); + } + spin_unlock_irqrestore(&nv_rs_uvm_cpu_dma_lock, flags); + + hlist_for_each_entry_safe(e, tmp, &dead, node) { + dma_unmap_page(e->dev, e->dma, PAGE_SIZE, DMA_BIDIRECTIONAL); + put_page(e->page); + put_device(e->dev); + kfree(e); + } +} + void nv_rs_uvm_node_exit(void) { nv_rs_uvm_fault_poll_stop(); @@ -607,4 +632,5 @@ void nv_rs_uvm_node_exit(void) mutex_lock(&nv_rs_uvm_lock); nv_rs_uvm_node_cleanup(); mutex_unlock(&nv_rs_uvm_lock); + nv_rs_uvm_drain_cpu_dma_ht(); } diff --git a/kernel-open/uvm_bridge/uvm_bridge.c b/kernel-open/uvm_bridge/uvm_bridge.c index 74cac6eb..1c212553 100644 --- a/kernel-open/uvm_bridge/uvm_bridge.c +++ b/kernel-open/uvm_bridge/uvm_bridge.c @@ -100,7 +100,7 @@ static bool debug_trace; module_param(debug_trace, bool, 0644); #define UVM_TRACE(fmt, ...) do { if (debug_trace) pr_info("uvm_bridge: " fmt "\n", ##__VA_ARGS__); } while (0) -#define MAX_BRIDGE_GPUS 8 +#define MAX_BRIDGE_GPUS 32 #define NV_RS_BRIDGE_MAX_DEVS 64 #define NV_RS_BRIDGE_MAX_VAS 64 #define NV_RS_BRIDGE_MAX_TSGS 128 diff --git a/src/nvidia/kernel/gsp_route.rs b/src/nvidia/kernel/gsp_route.rs index 2b56980f..cedbf440 100644 --- a/src/nvidia/kernel/gsp_route.rs +++ b/src/nvidia/kernel/gsp_route.rs @@ -26,7 +26,7 @@ extern "C" { ); fn nv_rs_ga10x_route_trace() -> bool; fn nv_rs_os_capable_admin() -> bool; - fn nv_rs_rmapi_os_page_phys(token: u64, page_index: u64, phys: *mut u64) -> u32; + fn nv_rs_rmapi_os_page_dma(gpu_id: u32, token: u64, page_index: u64, dma: *mut u64) -> u32; fn nv_rs_rmapi_file_post(owner: u64); } @@ -808,7 +808,7 @@ fn channel( let (mut err_pa, mut err_token) = (0u64, 0u64); if let Some(m) = node.classes.memory.find(client, rd(p, 0)) { if let nv_rs_core::rmapi::memory::Backing::System { pages, .. } = m.backing { - if unsafe { nv_rs_rmapi_os_page_phys(pages, 0, &mut err_pa) } == 0 { + if unsafe { nv_rs_rmapi_os_page_dma(g.gpu_id, pages, 0, &mut err_pa) } == 0 { err_token = pages; } else { err_pa = 0; diff --git a/src/nvidia/kernel/rmapi_node.rs b/src/nvidia/kernel/rmapi_node.rs index 2d1be25e..53a8fa23 100644 --- a/src/nvidia/kernel/rmapi_node.rs +++ b/src/nvidia/kernel/rmapi_node.rs @@ -1395,10 +1395,19 @@ pub unsafe extern "C" fn nv_rs_rmapi_prepare( { return EINVAL; } + #[cfg(not(nv_rs_edu_guest))] + let caller_pid = unsafe { + extern "C" { + fn nv_rs_os_tgid() -> u32; + } + nv_rs_os_tgid() + }; + #[cfg(nv_rs_edu_guest)] + let caller_pid = 0u32; let call = Call { caller: Caller { owner, - pid: 0, + pid: caller_pid, admin, gpu_access, pinned: false, @@ -1627,10 +1636,19 @@ pub unsafe extern "C" fn nv_rs_rmapi_execute( } } } + #[cfg(not(nv_rs_edu_guest))] + let caller_pid = unsafe { + extern "C" { + fn nv_rs_os_tgid() -> u32; + } + nv_rs_os_tgid() + }; + #[cfg(nv_rs_edu_guest)] + let caller_pid = 0u32; let call = Call { caller: Caller { owner, - pid: 0, + pid: caller_pid, admin, gpu_access, pinned: false, diff --git a/src/nvidia/kernel/uvm_node.rs b/src/nvidia/kernel/uvm_node.rs index 041064cf..37b6beff 100644 --- a/src/nvidia/kernel/uvm_node.rs +++ b/src/nvidia/kernel/uvm_node.rs @@ -73,6 +73,7 @@ struct SysmemPageTree { active: bool, globals_mapped: bool, token: u64, + owner: usize, gpu_id: u32, dev: *mut c_void, root_phys: u64, @@ -91,6 +92,7 @@ impl SysmemPageTree { active: false, globals_mapped: false, token: 0, + owner: 0, gpu_id: 0, dev: ptr::null_mut(), root_phys: 0, @@ -125,6 +127,7 @@ impl SysmemPageTree { self.dev = unsafe { nv_rs_uvm_dev_get(gpu_id) }; if let Some(root) = self.alloc_page(u32::MAX, 0, 0) { self.token = token; + self.owner = unsafe { *ptr::addr_of!(CURRENT_UVM_FILE) }; self.gpu_id = gpu_id; self.root_phys = self.pages.as_slice()[root].phys; self.active = true; @@ -1361,7 +1364,16 @@ impl FaultPageMapper for ManagedFaultMapper { let mut target_pdb = 0u64; let mut active_trees = 0u32; for tree in trees.iter_mut() { - if tree.active { + if !tree.active { + continue; + } + if self.faulting_gpu_id != 0 && tree.gpu_id != self.faulting_gpu_id { + continue; + } + if range.owner != 0 && tree.owner != 0 && tree.owner != range.owner { + continue; + } + { active_trees += 1; let is_faulting = self.faulting_gpu_id != 0 && tree.gpu_id == self.faulting_gpu_id; diff --git a/src/nvidia/src/rmapi/gpu.rs b/src/nvidia/src/rmapi/gpu.rs index 6b17fa83..7568a233 100644 --- a/src/nvidia/src/rmapi/gpu.rs +++ b/src/nvidia/src/rmapi/gpu.rs @@ -5005,7 +5005,11 @@ impl Objects for Bound<'_, N, A> { _ => {} } }); - if !memory.duped { + if !self + .classes + .memory + .has_backing_ref(memory.gpu, memory.backing) + { memory::release(&memory, self.os); } } diff --git a/src/nvidia/src/rmapi/memory.rs b/src/nvidia/src/rmapi/memory.rs index 324fbd90..369a708e 100644 --- a/src/nvidia/src/rmapi/memory.rs +++ b/src/nvidia/src/rmapi/memory.rs @@ -1512,6 +1512,32 @@ impl Table { }) .and_then(Option::take) } + /// Returns `true` if any remaining live memory handle still references the same + /// OS system-page token or GPU VRAM region, preventing UAF when an original handle + /// is freed before its `NV_ESC_RM_DUP_OBJECT` / FD-imported alias. + pub fn has_backing_ref(&self, gpu: u32, backing: Backing) -> bool { + self.objects + .iter() + .flatten() + .any(|obj| match (backing, obj.backing) { + (Backing::System { pages: a, .. }, Backing::System { pages: b, .. }) => { + a != 0 && a == b + } + ( + Backing::Video { + offset: a, + bytes: ab, + .. + }, + Backing::Video { + offset: b, + bytes: bb, + .. + }, + ) => obj.gpu == gpu && a == b && ab == bb, + _ => false, + }) + } /// Forgets the ranges of the address space `space` that no object holds (a space /// that is being destroyed). pub fn drop_orphans(&mut self, client: u32, space: u32) { diff --git a/src/nvidia/src/rmapi/node.rs b/src/nvidia/src/rmapi/node.rs index a55daabc..eff70b2a 100644 --- a/src/nvidia/src/rmapi/node.rs +++ b/src/nvidia/src/rmapi/node.rs @@ -539,16 +539,17 @@ impl ControlNode { } /// `NV_ESC_RM_SHARE` (`_nv000663rm`, NVOS57_PARAMETERS): records/validates share policy. - fn share_object(&self, caller: &Caller, top: &[u8]) -> NvStatus { + fn share_object(&mut self, caller: &Caller, top: &[u8]) -> NvStatus { let client = word(top, 0); let handle = word(top, 4); - if self.server.client_owner(client) != Some(caller.owner) { - return status::INVALID_CLIENT; - } - if self.server.object(client, handle).is_none() { - return status::OBJECT_NOT_FOUND; - } - status::OK + // RS_SHARE_POLICY at offset +8: target (u32 @ +8), accessMask (u32 @ +12), + // type (u16 @ +16), action (u16 @ +18). + let target = word(top, 8); + let type_action = word(top, 16); + let share_type = (type_action & 0xffff) as u16; + let action = (type_action >> 16) as u16; + self.server + .share_resource(caller, client, handle, target, share_type, action) } /// `NV_ESC_RM_MAP_MEMORY` (NVOS33 and a descriptor): `_nv000661rm`, then diff --git a/src/nvidia/src/rmapi/server.rs b/src/nvidia/src/rmapi/server.rs index 9bae461a..4bcf9aba 100644 --- a/src/nvidia/src/rmapi/server.rs +++ b/src/nvidia/src/rmapi/server.rs @@ -201,6 +201,9 @@ struct Resource { high_priority: bool, /// Destroyed as a dependant of another resource; the handle is still assigned. invalidated: bool, + /// Explicit cross-client share policy (`NV_ESC_RM_SHARE` / `_nv000663rm`). + shared_all: bool, + shared_pid: u32, } pub struct Server { @@ -327,6 +330,22 @@ impl Server { let Some(src) = self.resources[src_slot] else { return Err(status::OBJECT_NOT_FOUND); }; + // Enforce cross-process share policy (`_nv000655rm` -> `serverDupResource` -> + // `clientCanShareResource`): same owner, same non-zero PID, admin, or explicitly + // shared via `NV_ESC_RM_SHARE` (`_nv000663rm`). + let src_owner = self.client_owner(src_client); + let src_pid = self + .client_slot(src_client) + .and_then(|s| self.clients[s]) + .map_or(0, |c| c.pid); + let allowed = src_owner == Some(caller.owner) + || caller.admin + || (caller.pid != 0 && src_pid == caller.pid) + || src.shared_all + || (src.shared_pid != 0 && caller.pid != 0 && src.shared_pid == caller.pid); + if !allowed { + return Err(status::INSUFFICIENT_PERMISSIONS); + } let handle = if *dst_handle == 0 { self.generate_resource_handle(dst_client_slot)? } else { @@ -352,11 +371,45 @@ impl Server { internal_class: src.internal_class, high_priority: src.high_priority, invalidated: false, + shared_all: false, + shared_pid: 0, }; self.resources[slot] = Some(dup); Ok(dup.object()) } + /// `NV_ESC_RM_SHARE` (`_nv000663rm`): updates the share policy of `(client, handle)`. + pub fn share_resource( + &mut self, + caller: &Caller, + client: u32, + handle: u32, + target: u32, + share_type: u16, + action: u16, + ) -> NvStatus { + if self.client_owner(client) != Some(caller.owner) { + return status::INVALID_CLIENT; + } + let Some(slot) = self.resource_slot(client, handle) else { + return status::OBJECT_NOT_FOUND; + }; + let Some(res) = self.resources[slot].as_mut() else { + return status::OBJECT_NOT_FOUND; + }; + // RS_SHARE_ACTION_FLAG_SHARE = 1, RS_SHARE_ACTION_FLAG_REVOKE = 2. + // RS_SHARE_TYPE_PID = 5 (target = PID); other share types grant broad share. + if action == 2 { + res.shared_all = false; + res.shared_pid = 0; + } else if share_type == 5 && target != 0 { + res.shared_pid = target; + } else { + res.shared_all = true; + } + status::OK + } + /// Returns `(class, internal_class, high_priority)` for a live resource handle. pub fn resource_meta(&self, client: u32, handle: u32) -> Option<(u32, u32, bool)> { let slot = self.resource_slot(client, handle)?; @@ -411,6 +464,8 @@ impl Server { internal_class, high_priority, invalidated: false, + shared_all: false, + shared_pid: 0, }; self.resources[slot] = Some(dup); Ok(dup.object()) @@ -627,6 +682,8 @@ impl Server { internal_class: descriptor.internal_class, high_priority: descriptor.free_priority != 0, invalidated: false, + shared_all: false, + shared_pid: 0, }; let clients = &self.clients; let owner_of = |handle: u32| { @@ -712,6 +769,8 @@ impl Server { internal_class: descriptor.internal_class, high_priority: descriptor.free_priority != 0, invalidated: false, + shared_all: false, + shared_pid: 0, }); } status::OK diff --git a/utils.mk b/utils.mk index f7952719..c2a2b0a3 100644 --- a/utils.mk +++ b/utils.mk @@ -1,6 +1,6 @@ # Paths may be overridden for an explicit kernel/header tree and staging area. KERNEL_UNAME ?= $(shell uname -r) -KERNEL_SOURCES ?= $(if $(SYSSRC),$(SYSSRC),/lib/modules/$(KERNEL_UNAME)/build) +KERNEL_SOURCES ?= $(or $(KDIR),$(SYSSRC),/lib/modules/$(KERNEL_UNAME)/build) KERNEL_OUTPUT ?= $(if $(SYSOUT),$(SYSOUT),$(KERNEL_SOURCES)) # A kernel built with clang (CONFIG_CC_IS_CLANG=y, e.g. CachyOS) hands clang-only flags to # external module builds, so gcc cannot compile the C shims. Default to LLVM=1 for such kernels; @@ -10,7 +10,14 @@ ifneq ($(shell grep -q '^CONFIG_CC_IS_CLANG=y$$' $(KERNEL_OUTPUT)/.config 2>/dev export LLVM := 1 endif endif +ifeq ($(LLVM),1) +ifeq ($(origin LD),default) +LD := $(or $(shell command -v ld.lld 2>/dev/null),ld) +endif +OBJCOPY ?= $(or $(shell command -v llvm-objcopy 2>/dev/null),objcopy) +else OBJCOPY ?= objcopy +endif # Resolve rustc via rustup (including ~/.cargo/bin when non-interactive PATH omits it), # falling back to ~/.cargo/bin/rustc or PATH rustc. Override with RUSTC=... as before. RUSTC ?= $(or $(shell PATH="$(HOME)/.cargo/bin:$$PATH" rustup which rustc 2>/dev/null),$(wildcard $(HOME)/.cargo/bin/rustc),$(shell command -v rustc))