From 6435d651122b323b8282f26d7204f74f3de34e53 Mon Sep 17 00:00:00 2001 From: morebrackets Date: Fri, 4 Dec 2026 19:48:23 -0800 Subject: [PATCH] fix(rmapi/modeset): rmmod refcnt leak (#491), modeset RM ops (#466), runtime logs/fw warning (#501) (#513) * fix(ga10x/rmapi/modeset): R620 control translation, rmmod refcnt, modeset RM ops (#504, #491, #466, #501) * chore(pr513): drop gsp_route R620 hunk in favor of live-verified #514 * fix(gpu_owner): balance get_task_struct with put_task_struct after kthread_stop * fix(gpu_owner/irq): wait for runtime worker join & pin/teardown failed runtime IRQ close Addresses CodeRabbit review findings on PR #513 (and #491/#528): - gpu_owner.c: Wait for runtime_stopped in a 10s warning loop and always join via kthread_stop() + put_task_struct() so an unpinned runtime worker can never outlive module text during PCI removal / rmmod. - irq_adapter.c: When nv_rs_irq_close() fails to quiesce an unpinned runtime-kthread IRQ owner, acquire THIS_MODULE before returning the error (or force-disable/synchronize/free handlers if the module is already unloading so no callback can outlive module text). - ga10x_events.rs: Check nv_rs_irq_close() status in stop() and restore e.irq on failure instead of discarding the handle. - tests/irq-mock: Cover both live-pin and unloading-force-teardown paths. * fix(pci,irq): disable PCI INTx on forced IRQ close and bound AER/shutdown runtime stop Address follow-up review findings on #513: - In nv_rs_irq_close() forced teardown (unpinned runtime worker after mask failure), call pci_intx(owner->pdev, 0) for legacy INTx mode so the device stops asserting its level-triggered line without disabling a shared IRQ line for other devices, and add an irq-mock regression test. - Add nv_rs_gpu_owner_runtime_stop_bounded(owner, timeout_ms) preserving runtime_task and runtime_stopping on timeout (preventing restart races and allowing a later nv_rs_remove() stop to complete the join). - In nv_rs_shutdown() and nv_rs_aer_error_detected(), call pci_clear_master() first for immediate DMA containment, then use a bounded runtime stop so shutdown and PCIe AER callbacks never wedge indefinitely. * fix(pci,pm): bound runtime_lock wait, reclaim retired worker on start/AER, and reassert BME clear Address follow-up review findings on #513: - Include runtime_lock acquisition inside nv_rs_gpu_owner_runtime_stop_bounded()'s deadline via bounded mutex_trylock() polling so shutdown/AER cannot hang when startup holds runtime_lock waiting for runtime_ready. - Reclaim a retired worker in nv_rs_gpu_owner_runtime_start() via nv_rs_gpu_owner_runtime_reclaim_locked() and in nv_rs_aer_resume() so a timed-out bounded stop never strands runtime engines unavailable after recovery. - Reassert pci_clear_master(pdev) after the serialized stop attempt in nv_rs_shutdown() and nv_rs_aer_error_detected() so in-flight GPU bring-up cannot leave Bus Master enabled. - Use nv_rs_gpu_owner_runtime_stop_bounded() in PM suspend/runtime_suspend with full state rollback on timeout so suspend cannot wedge indefinitely while nv_rs_remove() keeps the unconditional join required before module unload. * fix(pci): keep Bus Master enabled during bounded GSP unload on shutdown Address final review comment on #513: - In nv_rs_shutdown(), invoke nv_rs_gpu_owner_runtime_stop_bounded(owner, 10000) before pci_clear_master(pdev) so an active GSP session can complete its DMA unload RPC during clean shutdown, then clear Bus Master Enable once the stop finishes or hits its bounded deadline. * fix(pci,pm): return DISCONNECT on AER stop timeout and keep full PM suspend stop Address review findings on #513: - In nv_rs_aer_error_detected(), return PCI_ERS_RESULT_DISCONNECT rather than PCI_ERS_RESULT_NEED_RESET if nv_rs_gpu_owner_runtime_stop_bounded() times out, preventing a PCIe slot reset while a live runtime worker could still issue MMIO or re-enable Bus Master. - In nv_rs_pm_do_suspend() and nv_rs_pmops_runtime_suspend(), wait for worker retirement via nv_rs_gpu_owner_runtime_stop() before entering D3hot rather than half-aborting after modeset suspend and USERD VMA revocation. --------- Co-authored-by: morebrackets <19673572+morebrackets@users.noreply.github.com> --- install.sh | 11 ++ .../nvidia-modeset/nvidia_rs_modeset.c | 24 +++- kernel-open/nvidia/diagnostic.c | 4 +- kernel-open/nvidia/gpu_owner.c | 128 ++++++++++++++++-- kernel-open/nvidia/gpu_owner.h | 2 + kernel-open/nvidia/irq_adapter.c | 46 ++++++- kernel-open/nvidia/pci_driver.c | 39 +++++- src/nvidia/kernel/ga10x_events.rs | 54 +++++--- src/nvidia/kernel/gpu.rs | 18 ++- src/nvidia/kernel/thread_state.rs | 18 ++- tests/device-software/thread.c | 1 + tests/dma-mock/ffi.c | 1 + tests/irq-mock/irq_mock.h | 5 +- tests/irq-mock/test.c | 43 +++++- tests/thread-state/ffi.c | 1 + 15 files changed, 336 insertions(+), 59 deletions(-) diff --git a/install.sh b/install.sh index af6ed878..8b6fa9a6 100755 --- a/install.sh +++ b/install.sh @@ -256,6 +256,17 @@ for fwdir in /usr/src/nvidia*/firmware; do fi done done +# Warn early when a host has non-580 stock GSP firmware (e.g. 595/620) but lacks the +# 580.178.04 / 580.196.07 GSP-RM blobs required by default ga10x_gsp=1 (#501). +if [ ! -f /lib/firmware/nvidia/580.178.04/gsp_ga10x.bin ] && \ + [ ! -f /lib/firmware/nvidia/580.196.07/gsp_ga10x.bin ]; then + other_gsp=$(ls /lib/firmware/nvidia/*/gsp_ga10x.bin 2>/dev/null | head -n 1 || true) + if [ -n "$other_gsp" ]; then + echo "WARN: /lib/firmware/nvidia/580.178.04/gsp_ga10x.bin not found (only found $other_gsp)." >&2 + echo " Do NOT copy a 595/620 blob into 580.178.04/; extract genuine 580.178.04 gsp_ga10x.bin" >&2 + echo " (or gsp_tu10x.bin for Turing/GA100) from NVIDIA-Linux-x86_64-580.178.04.run." >&2 + fi +fi sudo install -d -m 0755 "$INSTALL_DIR" for ko in "${KO_FILES[@]}"; do sudo install -m 0644 "$ko" "$INSTALL_DIR/" diff --git a/kernel-open/nvidia-modeset/nvidia_rs_modeset.c b/kernel-open/nvidia-modeset/nvidia_rs_modeset.c index a1071e55..18e5f373 100644 --- a/kernel-open/nvidia-modeset/nvidia_rs_modeset.c +++ b/kernel-open/nvidia-modeset/nvidia_rs_modeset.c @@ -4620,12 +4620,32 @@ static struct miscdevice nv_rs_modeset_compat_misc = { static bool nv_rs_modeset_compat_registered; +struct nv_rs_modeset_rm_ops_layout { + unsigned long version_string; + u8 system_info[8]; + unsigned long alloc_stack; + unsigned long free_stack; + unsigned long enumerate_gpus; + unsigned long open_gpu; + unsigned long close_gpu; + unsigned long op; + unsigned long set_callbacks; +}; + +static const char nv_rs_modeset_version[] = "580.178.04"; +static struct nv_rs_modeset_rm_ops_layout nv_rs_rm_ops; + static int __init nv_rs_modeset_init(void) { int ret; + u32 ops_st; - /* Verify linkage with nvidia_rs.ko & register hotplug/PM callbacks. */ - (void)nv_rs_modeset_get_rm_ops; + /* Verify RM ops handshake with nvidia_rs.ko & register hotplug/PM callbacks (#466). */ + memset(&nv_rs_rm_ops, 0, sizeof(nv_rs_rm_ops)); + nv_rs_rm_ops.version_string = (unsigned long)nv_rs_modeset_version; + ops_st = nv_rs_modeset_get_rm_ops(&nv_rs_rm_ops); + if (ops_st != 0) + pr_warn("nvidia_rs_modeset: nv_rs_modeset_get_rm_ops returned 0x%x\n", ops_st); nv_rs_kms_wq = alloc_workqueue("nv_rs_kms_wq", WQ_HIGHPRI | WQ_UNBOUND, 0); if (!nv_rs_kms_wq) return -ENOMEM; diff --git a/kernel-open/nvidia/diagnostic.c b/kernel-open/nvidia/diagnostic.c index 7050e4c3..77a4908e 100644 --- a/kernel-open/nvidia/diagnostic.c +++ b/kernel-open/nvidia/diagnostic.c @@ -15,6 +15,7 @@ #endif #include "ioctl_policy.h" #include "pci_driver.h" +#include "gpu_owner.h" #include "file_cleanup.h" #include "event_work_adapter.h" #include "rmapi_node.h" @@ -240,7 +241,8 @@ static int __init nvidia_rs_init(void) /* Publish fops only after every owning subsystem is initialized. */ status=misc_register(&nv_rs_control); if (status) { nv_rs_pci_driver_unregister(); nv_rs_uvm_node_exit(); nv_rs_rmapi_node_exit(); goto fail_software_manager; } - pr_info("nvidia_rs: /dev/nvidia-rsctl protocol %u; GPU/CUDA unsupported\n", protocol_version); + pr_info("nvidia_rs: /dev/nvidia-rsctl protocol %u (runtime_engines=%u)\n", + protocol_version, nv_rs_runtime_engines() ? 1u : 0u); return 0; fail_software_manager: drain_software_manager(); diff --git a/kernel-open/nvidia/gpu_owner.c b/kernel-open/nvidia/gpu_owner.c index bc8bd21f..4e69b47c 100644 --- a/kernel-open/nvidia/gpu_owner.c +++ b/kernel-open/nvidia/gpu_owner.c @@ -7,7 +7,10 @@ #include #include #include +#include #include +#include +#include #include #include #include @@ -566,6 +569,17 @@ void nv_rs_nvlink_hshub_log(u32 gpu_id, u32 peer_id, u32 link_mask, u32 cfg0, u3 #define NV_RS_MAX_RUNTIME_OWNERS 32 static DEFINE_MUTEX(runtime_owner_lock); static struct nv_rs_gpu_owner *nv_rs_runtime_owners[NV_RS_MAX_RUNTIME_OWNERS]; +static struct task_struct *nv_rs_runtime_tasks[NV_RS_MAX_RUNTIME_OWNERS]; + +bool nv_rs_is_runtime_kthread(void) +{ + int i; + for (i = 0; i < NV_RS_MAX_RUNTIME_OWNERS; i++) { + if (READ_ONCE(nv_rs_runtime_tasks[i]) == current) + return true; + } + return false; +} u32 nv_rs_pci_gpu_id(struct nv_rs_pci *pci) { @@ -614,11 +628,11 @@ static int runtime_kthread_fn(void *data) for (i = 0; i < NV_RS_MAX_RUNTIME_OWNERS; i++) { if (nv_rs_runtime_owners[i] == owner) { nv_rs_runtime_owners[i] = NULL; + WRITE_ONCE(nv_rs_runtime_tasks[i], NULL); break; } } mutex_unlock(&runtime_owner_lock); - WRITE_ONCE(owner->runtime_task, NULL); complete(&owner->runtime_stopped); return 0; } @@ -749,6 +763,27 @@ int nv_rs_runtime_request_gr_reset(struct nv_rs_pci *pci) return owner->runtime_gr_reset_rc; } +/* Must be called with owner->runtime_lock held. If a previously timed-out + * bounded stop left a retired worker pending join, finish kthread_stop() + * and clear runtime_task / runtime_stopping so startup can proceed. */ +static bool nv_rs_gpu_owner_runtime_reclaim_locked(struct nv_rs_gpu_owner *owner) +{ + struct task_struct *task = READ_ONCE(owner->runtime_task); + + if (!task && !smp_load_acquire(&owner->runtime_stopping)) + return true; + if (!try_wait_for_completion(&owner->runtime_stopped)) + return false; + if (task) { + kthread_stop(task); + put_task_struct(task); + WRITE_ONCE(owner->runtime_task, NULL); + } + owner->runtime_parked = false; + smp_store_release(&owner->runtime_stopping, false); + return true; +} + int nv_rs_gpu_owner_runtime_start(struct nv_rs_gpu_owner *owner) { struct nv_rs_pci *pci; @@ -777,6 +812,12 @@ int nv_rs_gpu_owner_runtime_start(struct nv_rs_gpu_owner *owner) nv_rs_pci_put(pci); return err; } + if (!nv_rs_gpu_owner_runtime_reclaim_locked(owner)) { + mutex_unlock(&owner->runtime_lock); + nv_rs_pci_power_put(pci); + nv_rs_pci_put(pci); + return -EBUSY; + } atomic_inc(&owner->runtime_starting); smp_mb__after_atomic(); init_completion(&owner->runtime_ready); @@ -825,12 +866,19 @@ int nv_rs_gpu_owner_runtime_start(struct nv_rs_gpu_owner *owner) nv_rs_pci_put(pci); return err; } + get_task_struct(task); + mutex_lock(&runtime_owner_lock); + WRITE_ONCE(nv_rs_runtime_tasks[slot], task); + mutex_unlock(&runtime_owner_lock); WRITE_ONCE(owner->runtime_task, task); wake_up_process(task); wait_for_completion(&owner->runtime_ready); err = owner->runtime_error; if (err) { wait_for_completion(&owner->runtime_stopped); + kthread_stop(task); + put_task_struct(task); + WRITE_ONCE(owner->runtime_task, NULL); } else { smp_store_release(&owner->runtime_started, true); } @@ -848,16 +896,34 @@ bool nv_rs_gpu_owner_runtime_active(struct nv_rs_gpu_owner *owner) /* Lockless read so PM runtime suspend callbacks never block on runtime_lock * while startup holds it waiting for the worker's power reference. */ return smp_load_acquire(&owner->runtime_started) || - atomic_read(&owner->runtime_starting) > 0; + atomic_read(&owner->runtime_starting) > 0 || + smp_load_acquire(&owner->runtime_stopping); } -void nv_rs_gpu_owner_runtime_stop(struct nv_rs_gpu_owner *owner) +static bool nv_rs_gpu_owner_runtime_stop_impl(struct nv_rs_gpu_owner *owner, + unsigned int timeout_ms, bool wait_forever) { + bool retired = true; + unsigned long deadline = 0; + if (!owner) - return; - mutex_lock(&owner->runtime_lock); - if (READ_ONCE(owner->runtime_started)) { - bool stopped; + return true; + if (wait_forever) { + mutex_lock(&owner->runtime_lock); + } else { + deadline = jiffies + msecs_to_jiffies(timeout_ms); + while (!mutex_trylock(&owner->runtime_lock)) { + if (time_after_eq(jiffies, deadline)) { + dev_warn(nv_rs_pci_device(owner->pci), + "nvidia_rs: bounded runtime stop timed out after %ums waiting for runtime_lock\n", + timeout_ms); + return false; + } + msleep(10); + } + } + if (READ_ONCE(owner->runtime_started) || READ_ONCE(owner->runtime_task)) { + struct task_struct *task = READ_ONCE(owner->runtime_task); /* Mark teardown in progress and drop runtime_started before waking the * worker so concurrent diagnostic open_gpu calls see -EBUSY rather than @@ -867,18 +933,50 @@ void nv_rs_gpu_owner_runtime_stop(struct nv_rs_gpu_owner *owner) WRITE_ONCE(owner->runtime_stop_req, true); wake_up(&owner->runtime_wq); complete(&owner->runtime_stop); - stopped = wait_for_completion_timeout(&owner->runtime_stopped, - msecs_to_jiffies(10000)) != 0; - if (!stopped) { - dev_warn(nv_rs_pci_device(owner->pci), - "nvidia_rs: runtime stop timed out after 10s; continuing teardown\n"); + if (wait_forever) { + /* The runtime worker does not pin THIS_MODULE (to avoid the #491/#528 + * rmmod self-pin deadlock), so PCI removal / module exit must wait + * until it retires and join via kthread_stop() before returning. */ + while (!wait_for_completion_timeout(&owner->runtime_stopped, + msecs_to_jiffies(10000))) { + dev_warn(nv_rs_pci_device(owner->pci), + "nvidia_rs: runtime stop still waiting for worker exit\n"); + } + } else { + unsigned long rem = time_before(jiffies, deadline) ? (deadline - jiffies) : 0; + retired = rem ? (wait_for_completion_timeout(&owner->runtime_stopped, rem) != 0) + : try_wait_for_completion(&owner->runtime_stopped); + if (!retired) { + /* Preserve runtime_task and runtime_stopping so a later + * nv_rs_gpu_owner_runtime_stop() on removal or reclaim on + * restart/AER resume still finishes the join safely. */ + dev_warn(nv_rs_pci_device(owner->pci), + "nvidia_rs: bounded runtime stop timed out after %ums; deferring worker join\n", + timeout_ms); + } } - owner->runtime_parked = false; - /* Only lift the admission veto once the worker has actually retired. */ - if (stopped) + if (retired) { + if (task) { + kthread_stop(task); + put_task_struct(task); + WRITE_ONCE(owner->runtime_task, NULL); + } + owner->runtime_parked = false; smp_store_release(&owner->runtime_stopping, false); + } } mutex_unlock(&owner->runtime_lock); + return retired; +} + +void nv_rs_gpu_owner_runtime_stop(struct nv_rs_gpu_owner *owner) +{ + (void)nv_rs_gpu_owner_runtime_stop_impl(owner, 0, true); +} + +bool nv_rs_gpu_owner_runtime_stop_bounded(struct nv_rs_gpu_owner *owner, unsigned int timeout_ms) +{ + return nv_rs_gpu_owner_runtime_stop_impl(owner, timeout_ms, false); } void nv_rs_gpu_owner_set_aer_recovering(struct nv_rs_gpu_owner *owner, bool recovering) diff --git a/kernel-open/nvidia/gpu_owner.h b/kernel-open/nvidia/gpu_owner.h index 1fdbf8dc..c26dee90 100644 --- a/kernel-open/nvidia/gpu_owner.h +++ b/kernel-open/nvidia/gpu_owner.h @@ -8,6 +8,7 @@ struct nv_rs_gpu_owner; * callback code alive through the return after module_put. */ bool nv_rs_gpu_module_get(void); void nv_rs_gpu_module_put(void); +bool nv_rs_is_runtime_kthread(void); int nv_rs_gpu_owner_queue_init(void); /* Stop new owner creation first. Waits retained cleanup owners/timers, then * joins workers. Persistent cleanup errors deliberately prevent teardown. */ @@ -68,6 +69,7 @@ void nv_rs_nvlink_link_log(u32 gpu_a, u32 link_a, u32 gpu_b, u32 link_b, u32 sta void nv_rs_nvlink_hshub_log(u32 gpu_id, u32 peer_id, u32 link_mask, u32 cfg0, u32 cfg1, u32 cfg2); int nv_rs_gpu_owner_runtime_start(struct nv_rs_gpu_owner *owner); void nv_rs_gpu_owner_runtime_stop(struct nv_rs_gpu_owner *owner); +bool nv_rs_gpu_owner_runtime_stop_bounded(struct nv_rs_gpu_owner *owner, unsigned int timeout_ms); bool nv_rs_gpu_owner_runtime_active(struct nv_rs_gpu_owner *owner); void nv_rs_gpu_owner_set_aer_recovering(struct nv_rs_gpu_owner *owner, bool recovering); void nv_rs_runtime_park(struct nv_rs_pci *pci); diff --git a/kernel-open/nvidia/irq_adapter.c b/kernel-open/nvidia/irq_adapter.c index 93f55c3d..a37e9631 100644 --- a/kernel-open/nvidia/irq_adapter.c +++ b/kernel-open/nvidia/irq_adapter.c @@ -9,6 +9,7 @@ #include #include #include +#include "gpu_owner.h" #endif #include "pci_adapter.h" #include "irq_adapter.h" @@ -27,7 +28,7 @@ struct nv_rs_irq { struct nv_rs_irq_ops ops; void *context; unsigned int count, mode; - bool armed, lines_enabled; + bool armed, lines_enabled, pinned_module; struct nv_rs_irq_vector vectors[]; }; static irqreturn_t nv_rs_irq_top(int number, void *cookie) @@ -97,6 +98,7 @@ static int nv_rs_irq_prepare_internal(struct nv_rs_pci *pci, unsigned int allowe { struct nv_rs_irq *owner; unsigned int i, flags = 0; + bool pin_module; int error; if (!out) return -EINVAL; *out = NULL; @@ -104,9 +106,11 @@ static int nv_rs_irq_prepare_internal(struct nv_rs_pci *pci, unsigned int allowe !max_vectors || max_vectors > NV_RS_IRQ_MAX_VECTORS || !allowed || (allowed & ~7U)) return -EINVAL; if (!nv_rs_pci_get(pci)) return -ENODEV; if (nv_rs_pci_is_removed(pci)) { error = -ENODEV; goto fail_lease; } - if (!try_module_get(THIS_MODULE)) { error = -ENODEV; goto fail_lease; } + pin_module = !nv_rs_is_runtime_kthread(); + if (pin_module && !try_module_get(THIS_MODULE)) { error = -ENODEV; goto fail_lease; } owner = kzalloc(sizeof(*owner) + max_vectors * sizeof(owner->vectors[0]), GFP_KERNEL); if (!owner) { error = -ENOMEM; goto fail_module; } + owner->pinned_module = pin_module; owner->pci = pci; owner->pdev = to_pci_dev(nv_rs_pci_device(pci)); mutex_init(&owner->transition); @@ -148,7 +152,8 @@ fail_vectors: fail_owner: kfree(owner); fail_module: - module_put(THIS_MODULE); + if (pin_module) + module_put(THIS_MODULE); fail_lease: nv_rs_pci_put(pci); return error; @@ -311,14 +316,45 @@ done: int nv_rs_irq_close(struct nv_rs_irq *owner) { int error; + bool pinned_module; if (!owner) return -EINVAL; error = nv_rs_irq_quiesce(owner); - if (error) return error; + if (error) { + bool forced_teardown = false; + mutex_lock(&owner->transition); + if (!owner->pinned_module) { + if (try_module_get(THIS_MODULE)) { + owner->pinned_module = true; + } else { + /* Module is already unloading so a pin cannot be acquired; + * silence the device and free handlers so no callback can + * outlive module text. For shared INTx, disable INTx at the + * PCI device command register without touching the shared line. */ + unsigned int i; + WRITE_ONCE(owner->armed, false); + if (owner->mode == NV_RS_IRQ_INTX) { + pci_intx(owner->pdev, 0); + } else if (owner->lines_enabled) { + for (i = 0; i < owner->count; i++) + disable_irq(owner->vectors[i].linux_irq); + owner->lines_enabled = false; + } + for (i = 0; i < owner->count; i++) + synchronize_irq(owner->vectors[i].linux_irq); + forced_teardown = true; + } + } + mutex_unlock(&owner->transition); + if (!forced_teardown) + return error; + } + pinned_module = owner->pinned_module; nv_rs_irq_free_handlers(owner); pci_free_irq_vectors(owner->pdev); nv_rs_pci_put(owner->pci); kfree(owner); - module_put(THIS_MODULE); + if (pinned_module) + module_put(THIS_MODULE); return 0; } unsigned int nv_rs_irq_vectors(const struct nv_rs_irq *owner) { return owner ? owner->count : 0; } diff --git a/kernel-open/nvidia/pci_driver.c b/kernel-open/nvidia/pci_driver.c index 9d062f60..63939704 100644 --- a/kernel-open/nvidia/pci_driver.c +++ b/kernel-open/nvidia/pci_driver.c @@ -121,7 +121,10 @@ static int nv_rs_probe(struct pci_dev *pdev, const struct pci_device_id *id) } if (nv_rs_hwmon_register(pdev) < 0) dev_warn(&pdev->dev, "failed to register /sys/class/hwmon sensor node\n"); - dev_info(&pdev->dev, "Rust PCI/DMA preparation complete; engine initialization and CUDA unavailable\n"); + dev_info(&pdev->dev, + nv_rs_runtime_engines() + ? "Rust PCI/DMA preparation complete; runtime engines armed for first open\n" + : "Rust PCI/DMA preparation complete; runtime_engines=0 (engine initialization and CUDA disabled)\n"); return 0; fail_lease: nv_rs_pci_mark_removed(lease); @@ -172,6 +175,10 @@ static int nv_rs_pm_do_suspend(struct device *dev, u32 action) lost = nv_rs_gpu_pm_verify_alive(gpu) != 0; nv_rs_rmapi_revoke_runtime_userd(gpu_id, lost); if (!lost) + /* Wait for worker retirement before disabling PCI / entering D3hot: + * modeset suspend and USERD VMA revocation have already occurred, so + * entering D3hot with a live worker is unsafe and mid-teardown cannot + * be rolled back without first retiring the worker. */ nv_rs_gpu_owner_runtime_stop(owner); else dev_warn(dev, "GPU appears lost during PM suspend; skipping engine teardown\n"); @@ -359,14 +366,15 @@ 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. */ +/* Match stock 580.178.04 nv_pci_shutdown (nvidia/nv-pci.c:786-816): keep Bus + * Master enabled while the bounded runtime-worker stop cleanly unloads any + * active GSP session (which requires DMA for the unload RPC), then clear Bus + * Master Enable once the stop completes or its deadline expires. */ 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); + (void)nv_rs_gpu_owner_runtime_stop_bounded(owner, 10000); pci_clear_master(pdev); udelay(1); } @@ -375,14 +383,27 @@ 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); + bool worker_stopped = true; dev_err(&pdev->dev, "nvidia_rs: PCIe AER error detected (state=%d)\n", state); + /* Contain DMA immediately before waiting on the runtime worker, bound the + * wait so PCIe AER receives the recovery decision promptly, and reassert + * Bus Master clear afterward in case an in-flight bring-up re-enabled it. */ + pci_clear_master(pdev); if (owner) { nv_rs_gpu_owner_set_aer_recovering(owner, true); - nv_rs_gpu_owner_runtime_stop(owner); + worker_stopped = nv_rs_gpu_owner_runtime_stop_bounded(owner, 10000); } pci_clear_master(pdev); if (state == pci_channel_io_perm_failure) return PCI_ERS_RESULT_DISCONNECT; + /* Refuse slot reset if the runtime worker did not retire before the + * deadline so the PCI core never resets the device while the worker can + * still issue MMIO or re-enable Bus Master. */ + if (!worker_stopped) { + dev_err(&pdev->dev, + "nvidia_rs: runtime worker did not retire during AER; disconnecting device\n"); + return PCI_ERS_RESULT_DISCONNECT; + } return PCI_ERS_RESULT_NEED_RESET; } @@ -397,8 +418,12 @@ static pci_ers_result_t nv_rs_aer_slot_reset(struct pci_dev *pdev) static void nv_rs_aer_resume(struct pci_dev *pdev) { struct nv_rs_gpu_owner *owner = pci_get_drvdata(pdev); - if (owner) + if (owner) { + /* Reclaim any runtime worker whose stop timed out during error_detected + * and retired while the PCIe slot was being reset. */ + (void)nv_rs_gpu_owner_runtime_stop_bounded(owner, 10000); nv_rs_gpu_owner_set_aer_recovering(owner, false); + } dev_info(&pdev->dev, "nvidia_rs: PCIe AER resume complete\n"); } diff --git a/src/nvidia/kernel/ga10x_events.rs b/src/nvidia/kernel/ga10x_events.rs index a7fcb57c..1aab3c84 100644 --- a/src/nvidia/kernel/ga10x_events.rs +++ b/src/nvidia/kernel/ga10x_events.rs @@ -883,25 +883,41 @@ pub(crate) fn stop(g: &mut Ga10xGpu) { e.on.store(false, Ordering::Release); e.kcb_stopped.store(true, Ordering::Release); e.pending.store(0, Ordering::Release); + let mut closed = true; let irq = e.irq.swap(core::ptr::null_mut(), Ordering::AcqRel); if !irq.is_null() { - unsafe { nv_rs_irq_close(irq) }; - ga10x_gsp::note( - g.pci, - b"events: stopped (interrupts, GR0 seen, posts, busy retries)\0", - e.irqs.load(Ordering::Relaxed), - e.seen[0].load(Ordering::Relaxed), - e.posts.load(Ordering::Relaxed), - e.busy.load(Ordering::Relaxed), - ); - ga10x_gsp::note( - g.pci, - b"events: stopped (GSP seen, DISP seen, unhandled GSP, unhandled DISP)\0", - e.seen[SLOT_GSP].load(Ordering::Relaxed), - e.seen[SLOT_DISP].load(Ordering::Relaxed), - u64::from(e.unhandled_gsp.load(Ordering::Relaxed)), - u64::from(e.unhandled_disp.load(Ordering::Relaxed)), - ); + let close_rc = unsafe { nv_rs_irq_close(irq) }; + if close_rc != 0 { + // Preserve the handle so a subsequent stop/teardown can retry instead of leaking + // a registered IRQ owner. + e.irq.store(irq, Ordering::Release); + closed = false; + ga10x_gsp::note( + g.pci, + b"events: irq close failed (rc, GPU)\0", + close_rc as u64, + u64::from(g.gpu_id), + 0, + 0, + ); + } else { + ga10x_gsp::note( + g.pci, + b"events: stopped (interrupts, GR0 seen, posts, busy retries)\0", + e.irqs.load(Ordering::Relaxed), + e.seen[0].load(Ordering::Relaxed), + e.posts.load(Ordering::Relaxed), + e.busy.load(Ordering::Relaxed), + ); + ga10x_gsp::note( + g.pci, + b"events: stopped (GSP seen, DISP seen, unhandled GSP, unhandled DISP)\0", + e.seen[SLOT_GSP].load(Ordering::Relaxed), + e.seen[SLOT_DISP].load(Ordering::Relaxed), + u64::from(e.unhandled_gsp.load(Ordering::Relaxed)), + u64::from(e.unhandled_disp.load(Ordering::Relaxed)), + ); + } } e.lock_kcb(); let tail = e.kcb_tail.load(Ordering::Relaxed); @@ -910,7 +926,9 @@ pub(crate) fn stop(g: &mut Ga10xGpu) { while e.kcb_draining.load(Ordering::Acquire) || e.kcb_exec_active.load(Ordering::Acquire) { core::hint::spin_loop(); } - e.armed.store(false, Ordering::Release); + if closed { + e.armed.store(false, Ordering::Release); + } } /// Enables or disables hardware head VBLANK timing interrupts (`NV_PDISP_FE_EVT_EN_HEAD_TIMING`, diff --git a/src/nvidia/kernel/gpu.rs b/src/nvidia/kernel/gpu.rs index bd5ff997..e1b8ea73 100644 --- a/src/nvidia/kernel/gpu.rs +++ b/src/nvidia/kernel/gpu.rs @@ -15,6 +15,7 @@ unsafe extern "C" { fn nv_rs_pci_power_put(pci: *mut c_void); fn nv_rs_gpu_module_get() -> bool; fn nv_rs_gpu_module_put(); + fn nv_rs_is_runtime_kthread() -> bool; fn nv_rs_pci_read32(pci: *mut c_void, offset: u64, value: *mut u32) -> i32; fn nv_rs_pci_write32(pci: *mut c_void, offset: u64, value: u32) -> i32; fn nv_rs_pci_dsn(pci: *mut c_void) -> u64; @@ -345,6 +346,7 @@ struct Operation { /// or a worker joined by module exit. !Send alone does not establish that rule. pub struct GpuLease { raw: NonNull, + pinned_module: bool, } impl GpuLease { /// # Safety @@ -512,7 +514,8 @@ impl GpuLease { if !valid(storage) { return Err(-22); } - if !nv_rs_gpu_module_get() { + let pin_module = !nv_rs_is_runtime_kthread(); + if pin_module && !nv_rs_gpu_module_get() { return Err(-19); } let counter = &*ptr::addr_of!((*storage).lifetime); @@ -527,7 +530,9 @@ impl GpuLease { } }); if let Err(state) = acquired { - nv_rs_gpu_module_put(); + if pin_module { + nv_rs_gpu_module_put(); + } return Err( if state & (REMOVED | CLOSED) != 0 || state & REFERENCES == 0 { -19 @@ -538,11 +543,14 @@ impl GpuLease { } if (*storage).cleanup.is_none() { release(storage); - nv_rs_gpu_module_put(); + if pin_module { + nv_rs_gpu_module_put(); + } return Err(-95); } Ok(Self { raw: NonNull::new_unchecked(storage), + pinned_module: pin_module, }) } } @@ -787,7 +795,9 @@ impl Drop for GpuLease { fn drop(&mut self) { unsafe { release(self.raw.as_ptr()); - nv_rs_gpu_module_put(); + if self.pinned_module { + nv_rs_gpu_module_put(); + } } } } diff --git a/src/nvidia/kernel/thread_state.rs b/src/nvidia/kernel/thread_state.rs index 99227c72..52978986 100644 --- a/src/nvidia/kernel/thread_state.rs +++ b/src/nvidia/kernel/thread_state.rs @@ -28,6 +28,7 @@ unsafe extern "C" { fn nv_rs_thread_process_context() -> bool; fn nv_rs_gpu_module_get() -> bool; fn nv_rs_gpu_module_put(); + fn nv_rs_is_runtime_kthread() -> bool; } const INVALID_STATE: NvStatus = NvStatus(0x40); const NO_MEMORY: NvStatus = NvStatus(0x51); @@ -191,14 +192,17 @@ impl Registry { if database.setup_flags & thread_timeout::ENABLED == 0 { return Ok(None); } - if !nv_rs_gpu_module_get() { + let pin_module = !nv_rs_is_runtime_kthread(); + if pin_module && !nv_rs_gpu_module_get() { return Err(INVALID_STATE); } let mut process_flags = 0; let task = match NonNull::new(nv_rs_thread_task_get(&mut process_flags)) { Some(task) => task, None => { - nv_rs_gpu_module_put(); + if pin_module { + nv_rs_gpu_module_put(); + } return Err(INVALID_STATE); } }; @@ -206,7 +210,9 @@ impl Registry { Some(value) => value.cast::(), None => { nv_rs_thread_task_put(task.as_ptr()); - nv_rs_gpu_module_put(); + if pin_module { + nv_rs_gpu_module_put(); + } return Err(NO_MEMORY); } }; @@ -214,6 +220,7 @@ impl Registry { registry: self, pointer, published: false, + pinned_module: pin_module, _task: PhantomData, }; ptr::write( @@ -324,6 +331,7 @@ pub struct Entry<'a> { registry: &'a Registry, pointer: NonNull, published: bool, + pinned_module: bool, _task: PhantomData<*mut ()>, } impl Entry<'_> { @@ -494,7 +502,9 @@ impl Drop for Entry<'_> { ptr::drop_in_place(self.pointer.as_ptr()); nv_rs_thread_storage_free(self.pointer.as_ptr().cast()); nv_rs_thread_task_put(task.as_ptr()); - nv_rs_gpu_module_put(); + if self.pinned_module { + nv_rs_gpu_module_put(); + } } } } diff --git a/tests/device-software/thread.c b/tests/device-software/thread.c index 20419056..57091716 100644 --- a/tests/device-software/thread.c +++ b/tests/device-software/thread.c @@ -1,3 +1,4 @@ #define nv_rs_gpu_module_get thread_only_module_get #define nv_rs_gpu_module_put thread_only_module_put +#define nv_rs_is_runtime_kthread thread_only_is_runtime_kthread #include "../thread-state/ffi.c" diff --git a/tests/dma-mock/ffi.c b/tests/dma-mock/ffi.c index a9e499c7..5c2865d3 100644 --- a/tests/dma-mock/ffi.c +++ b/tests/dma-mock/ffi.c @@ -28,6 +28,7 @@ bool nv_rs_gpu_module_get(void) atomic_fetch_add(&fixture_module_references,1);return true; } void nv_rs_gpu_module_put(void){atomic_fetch_sub(&fixture_module_references,1);} +bool nv_rs_is_runtime_kthread(void){return false;} unsigned fixture_module_pins(void){return atomic_load(&fixture_module_references);} void fixture_fail_module_gets(unsigned n){atomic_store(&fixture_failed_module_gets,n);} void *fixture_pci_create(void){struct nv_rs_pci*p=calloc(1,sizeof(*p));if(!p)return NULL;p->refs=1;p->mask=DMA_BIT_MASK(40);p->dev.dma_mask=&p->mask;p->dev.coherent_dma_mask=p->mask;mock_pci=p;return p;} diff --git a/tests/irq-mock/irq_mock.h b/tests/irq-mock/irq_mock.h index 966d8170..13c71d07 100644 --- a/tests/irq-mock/irq_mock.h +++ b/tests/irq-mock/irq_mock.h @@ -34,12 +34,15 @@ struct device {int unused;}; struct pci_dev {struct device dev;bool msix_enabled,msi_enabled;}; struct nv_rs_pci {struct pci_dev pdev;bool removed;int refs;}; static struct pci_dev*to_pci_dev(struct device*d){return (struct pci_dev*)d;} -static int module_refs,allocated_vectors,requested_handlers,syncs,enables,disables; +static int module_refs,allocated_vectors,requested_handlers,syncs,enables,disables,intx_disabled; static int fail_alloc,fail_request=-1,vector_result=2,choose_mode=PCI_IRQ_MSIX,module_available=1; +static bool runtime_kthread; struct handler {irqreturn_t(*top)(int,void*);irqreturn_t(*thread)(int,void*);void*cookie;unsigned long flags;bool used;}; static struct handler handlers[32]; static bool try_module_get(void*m){(void)m;if(!module_available)return false;module_refs++;return true;} static void module_put(void*m){(void)m;module_refs--;assert(module_refs>=0);} +static bool nv_rs_is_runtime_kthread(void){return runtime_kthread;} +static void pci_intx(struct pci_dev*p,int enable){(void)p;if(!enable)intx_disabled++;} static void*kzalloc(size_t n,int f){(void)f;return calloc(1,n);} static void kfree(void*p){free(p);} static unsigned int rejected_modes, attempt_count; diff --git a/tests/irq-mock/test.c b/tests/irq-mock/test.c index 2cdfa38f..2bfc743a 100644 --- a/tests/irq-mock/test.c +++ b/tests/irq-mock/test.c @@ -11,7 +11,7 @@ static int unmask(void*x){struct ctx*c=x;c->unmasks++;assert(requested_handlers> static unsigned int top(void*x,unsigned int i){struct ctx*c=x;(void)i;c->tops++;return c->top_result;} static void thread(void*x,unsigned int i){struct ctx*c=x;(void)i;c->threads++;} static const struct nv_rs_irq_ops ops={mask,unmask,top,thread}; -static void reset(void){assert(module_refs==0&&allocated_vectors==0&&requested_handlers==0);memset(handlers,0,sizeof(handlers));syncs=enables=disables=0;attempt_count=rejected_modes=0;fail_alloc=0;fail_request=-1;vector_result=2;choose_mode=PCI_IRQ_MSIX;module_available=1;} +static void reset(void){assert(module_refs==0&&allocated_vectors==0&&requested_handlers==0);memset(handlers,0,sizeof(handlers));syncs=enables=disables=intx_disabled=0;attempt_count=rejected_modes=0;fail_alloc=0;fail_request=-1;vector_result=2;choose_mode=PCI_IRQ_MSIX;module_available=1;runtime_kthread=false;} int main(void){unsigned tests=0;struct nv_rs_pci pci={.refs=1};struct ctx c={.top_result=NV_RS_IRQ_WAKE_THREAD};struct nv_rs_irq*irq=NULL; reset();assert(!nv_rs_irq_prepare(&pci,7,4,&ops,&c,&irq));assert(c.masks==1&&pci.refs==2&&module_refs==1);assert(nv_rs_irq_vectors(irq)==2&&nv_rs_irq_mode(irq)==1);assert(handlers[0].top(100,handlers[0].cookie)==IRQ_NONE&&c.tops==0);assert(!nv_rs_irq_arm(irq)&&enables==2);assert(handlers[0].top(100,handlers[0].cookie)==IRQ_WAKE_THREAD);assert(handlers[0].thread(100,handlers[0].cookie)==IRQ_HANDLED&&c.threads==1);assert(nv_rs_irq_arm(irq)==-EBUSY);assert(!nv_rs_irq_close(irq)&&pci.refs==1&&disables==2);tests++; reset();fail_alloc=1;assert(nv_rs_irq_prepare(&pci,7,4,&ops,&c,&irq)==-ENOSPC&&!irq&&pci.refs==1);tests++; @@ -95,5 +95,44 @@ int main(void){unsigned tests=0;struct nv_rs_pci pci={.refs=1};struct ctx c={.to tests++; reset(); - return tests == 20 ? 0 : 1; + runtime_kthread = true; + choose_mode = PCI_IRQ_MSI; + vector_result = 1; + assert(!nv_rs_irq_prepare(&pci, 7, 4, &ops, &c, &irq)); + assert(module_refs == 0 && pci.refs == 2 && requested_handlers == 1); + assert(!nv_rs_irq_arm(irq)); + c.mask_error = -EIO; + assert(nv_rs_irq_close(irq) == -EIO && module_refs == 1 && requested_handlers == 1); + c.mask_error = 0; + assert(!nv_rs_irq_close(irq) && module_refs == 0 && pci.refs == 1 && requested_handlers == 0); + tests++; + + reset(); + runtime_kthread = true; + choose_mode = PCI_IRQ_MSI; + vector_result = 1; + assert(!nv_rs_irq_prepare(&pci, 7, 4, &ops, &c, &irq)); + assert(module_refs == 0 && pci.refs == 2 && requested_handlers == 1); + assert(!nv_rs_irq_arm(irq)); + c.mask_error = -EIO; + module_available = 0; + assert(!nv_rs_irq_close(irq) && module_refs == 0 && pci.refs == 1 && requested_handlers == 0 && allocated_vectors == 0); + c.mask_error = 0; + tests++; + + reset(); + runtime_kthread = true; + choose_mode = PCI_IRQ_LEGACY; + vector_result = 1; + assert(!nv_rs_irq_prepare(&pci, 7, 4, &ops, &c, &irq)); + assert(module_refs == 0 && pci.refs == 2 && requested_handlers == 1); + assert(!nv_rs_irq_arm(irq)); + c.mask_error = -EIO; + module_available = 0; + assert(!nv_rs_irq_close(irq) && module_refs == 0 && pci.refs == 1 && requested_handlers == 0 && allocated_vectors == 0 && intx_disabled == 1 && disables == 0); + c.mask_error = 0; + tests++; + + reset(); + return tests == 23 ? 0 : 1; } diff --git a/tests/thread-state/ffi.c b/tests/thread-state/ffi.c index ba46d0c7..c9aa6433 100644 --- a/tests/thread-state/ffi.c +++ b/tests/thread-state/ffi.c @@ -52,3 +52,4 @@ int nv_rs_thread_current(struct snapshot *out) bool nv_rs_gpu_module_get(void) { if(module_fail)return false; atomic_fetch_add(&modules,1); return true; } void nv_rs_gpu_module_put(void) { atomic_fetch_sub(&modules,1); } +bool nv_rs_is_runtime_kthread(void) { return false; }