Skip to content

Improve Thunderbolt eGPU detection and stability - #981

Closed
roger-pmta wants to merge 3 commits into
NVIDIA:mainfrom
roger-pmta:gh-979
Closed

roger-pmta wants to merge 3 commits into
NVIDIA:mainfrom
roger-pmta:gh-979

Conversation

@roger-pmta

@roger-pmta roger-pmta commented Dec 6, 2025 •

Copy link
Copy Markdown

Summary

This PR adds/improves support for external GPUs (eGPUs) connected via Thunderbolt 4, Thunderbolt 5, and USB4 interfaces. The official driver only recognizes Thunderbolt 3 bridges, causing TB4/TB5/USB4 eGPUs to be (potentially) treated as internal GPUs with inappropriate timeout values and no hotplug handling, resulting in system hard-locks during CUDA operations.

Relates to: #979, #894

Changes

  1. Add NV2080_CTRL_INTERNAL_EGPU_BUS_TYPE_TB5 and _USB4 bus type constants
  2. Detect Thunderbolt eGPUs via kernel's is_thunderbolt flag (vendor-agnostic)
  3. 4x timeout multiplier for external GPUs
  4. Preemption points in GSP/FSP spin loops (call osSchedule() every 256 iterations)
  5. Automatic BAR validation retry with exponential backoff on cold boot

Tested Hardware

  • GPU: NVIDIA RTX 5080 (GB203, Blackwell)
  • Enclosure: Sonnet Breakaway Box 850T5 (Intel JHL9480 TB5 bridge, device ID: 0x5786)
  • Host: Intel Raptor Lake-P with Thunderbolt 4 (device IDs: 0xa76e, 0xa72f)
  • OS: Rocky Linux with kernel 6.x

Files Modified

File Change
src/common/sdk/nvidia/inc/ctrl/ctrl2080/ctrl2080internal.h Add TB5/USB4 bus type constants
src/nvidia/arch/nvalloc/unix/src/osinit.c eGPU detection via is_thunderbolt flag
src/nvidia/arch/nvalloc/unix/src/os.c 4x timeout multiplier for external GPUs
src/nvidia/src/kernel/gpu/gsp/kernel_gsp.c Preemption points in GSP polling loops
src/nvidia/src/kernel/gpu/gsp/arch/hopper/kernel_gsp_gh100.c Preemption points in Hopper GSP
src/nvidia/src/kernel/gpu/fsp/kern_fsp.c Preemption points in FSP polling loops
kernel-open/nvidia/nv-pci.c Thunderbolt detection, BAR retry logic

Build and Install

# Build with debug symbols
make modules -j$(nproc) DEBUG=1

# Install
sudo make modules_install -j$(nproc)

# Remove official modules if installed (they take precedence in /lib/modules/$(uname -r)/extra)
sudo rm -f /lib/modules/$(uname -r)/extra/nvidia*.ko*

sudo depmod -a
sudo dracut --force

Technical Details

Why the Official Driver Fails

The driver only recognizes Thunderbolt 3 bridges as eGPU connections:

// osinit.c - only TB3 is recognized
if (params.iseGPUBridge &&
    params.approvedBusType == NV2080_CTRL_INTERNAL_EGPU_BUS_TYPE_TB3)
{
    bTb3Bridge = NV_TRUE;
}

Intel TB4/TB5 device IDs are not in the approved list, and no TB4, TB5, or USB4 bus type exists. Without external GPU recognition:

  1. PDB_PROP_GPU_IS_EXTERNAL_GPU is not set
  2. Default timeouts used (4s init, 30s compute) - too short for TB latency
  3. No special hotplug or removal handling

Hard-Locks

GSP polling loops spin without yielding:

for (nRetries = 0; ; nRetries++)
{
    nRet = msgqRxLink(...);
    if (nRet == 0) return NV_OK;
    // No preemption point - CPU spins here
}

Thunderbolt adds latency. These loops spin long enough to trigger soft-lockup detection or freeze the system entirely.

How nvidia-persistenced Interacts

nvidia-persistenced uses libnvidia-cfg.so.1 to manage devices:

// nvidia-persistenced.c:386-390
success = nv_cfg_api.open_pci_device(device->pci_info.domain,
                                     device->pci_info.bus,
                                     device->pci_info.slot,
                                     device->pci_info.function,
                                     &device->nv_cfg_handle);

On TB5 eGPU hotplug:

  1. udev creates /dev/nvidia* device files
  2. nvidia-persistenced calls nvCfgOpenPciDevice()
  3. This triggers kernel driver initialization (RmInitAdapter)

With these patches, the kernel detects the external GPU via the kernel's is_thunderbolt flag, automatically retries BAR validation if the Thunderbolt tunnel isn't ready, uses 4x timeouts for GSP communication, and yields the CPU during spin loops. nvidia-persistenced works unchanged.

Diagnostic Evidence

From nvidia-bug-report.log:

NVRM: gpuHandleSanityCheckRegReadError_GH100: Possible bad register read:
      addr: 0x110094, regvalue: 0xbadf2100, error code: Unknown SYS_PRI_ERROR_CODE

0xBADF21 is a FECS PRI error not defined in the Blackwell error table. The function name _GH100 (Hopper) being called for GB203 (Blackwell) shows inherited code paths. Register read failures point to PCIe link instability.


User Configuration

Required: Kernel Parameters

sudo grubby --update-kernel=ALL --args="iommu=pt pcie_ports=native pcie_aspm=off pci=noaer pcie_port_pm=off"

intel_iommu=off breaks Thunderbolt PCIe tunneling. Use iommu=pt instead.

Required: Module Options

cat <<'EOF' | sudo tee /etc/modprobe.d/nvidia-egpu.conf
options nvidia NVreg_DynamicPowerManagement=0x00
EOF
sudo dracut --force

Recommended: Power Limiting via udev

cat <<'EOF' | sudo tee /etc/udev/rules.d/99-nvidia-egpu-power.rules
SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x030000", DRIVER=="nvidia", RUN+="/usr/local/bin/nvidia-egpu-power-init.sh"
EOF

cat <<'EOF' | sudo tee /usr/local/bin/nvidia-egpu-power-init.sh
#!/bin/bash
sleep 5
if nvidia-smi -pl 325; then
    logger "nvidia-egpu-power-init: Set power limit to 325W"
else
    logger "nvidia-egpu-power-init: Failed to set power limit"
fi
EOF

sudo chmod +x /usr/local/bin/nvidia-egpu-power-init.sh
sudo udevadm control --reload-rules

Power limits require a running driver. The udev rule fires when the driver binds, before anything else can run the GPU at full TDP.

Optional: Compute-Only Mode

cat <<'EOF' | sudo tee -a /etc/modprobe.d/nvidia-egpu.conf
blacklist nvidia_drm
blacklist nvidia_modeset
EOF
sudo dracut --force

Usage

Recommended: Hotplug

  1. Boot with enclosure powered off
  2. Power on enclosure after login
  3. Driver loads automatically, udev applies power limits
  4. Run CUDA workloads

Cold Boot (enclosure already on)

If the enclosure is powered on during boot, the driver will automatically retry BAR validation with exponential backoff (up to 1 second per PCIe spec 6.6.1) while the Thunderbolt tunnel initializes. If this fails:

echo 1 | sudo tee /sys/bus/pci/rescan
sudo modprobe nvidia

Verification

# Check GPU detected
nvidia-smi

# Quick CUDA test
python3 -c "import torch; x = torch.randn(10000, 10000, device='cuda'); y = torch.mm(x, x); print('Success:', y.shape)"

# Sustained load test
python3 -c "
import torch
for i in range(10):
    x = torch.randn(10000, 10000, device='cuda')
    y = torch.mm(x, x)
    print(f'Iteration {i+1} complete')
"

Ollama with qwen3:4b in Docker also works without issues.

What Didn't Work

  • intel_iommu=off - Breaks Thunderbolt PCIe tunnel creation
  • Full TDP (360W) - Link instability under sustained load
  • Cold boot with enclosure connected - Display stack issues
  • Official driver - No TB4/TB5 recognition, wrong timeouts, spin-locks

Bug Report Log

Bug report with the GPU working is attached.

nvidia-bug-report.log-1.gz

@CLAassistant

CLAassistant commented Dec 6, 2025 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@roger-pmta

This comment was marked as outdated.

@morgwai

morgwai commented Dec 6, 2025 •

Copy link
Copy Markdown

For about a year now I've been running LLM workloads on multi-eGPU setups that include an USB4 3090 eGPU (ASM2464PDX based ADT UT4G with Gigabyte RTX-3090 GAMING OC 24G) connected to both TB4 and USB4 hosts (Latitude 7430, TongFang X4) running Debian-13 with DC Nvidia drivers. I have never experienced CUDA op freezes nor crashes on unplug (as long as the eGPU being unplugged is properly unbound from the driver beforehand that is).

I do experience occasional problems when booting with this USB4 eGPU connected to the X4 laptop: it seems like PCIe tunneling is not properly initialized on some attempts (20-30%, 2 red leds on the UT4G indicating a lack of a connection are active then). Re-plugging afterwards, when the boot sequence is completed, always resolves the issue.

I will also add however, that when previously I was using a TH3P4G3 (JHL7540 based) 1080ti eGPU on an XPS13-9360 with the driver v535 from the Debian repos, no unbinding was necessary: it was sufficient if no processes were reported by nvidia-smi to cleanly unplug the eGPU without any crashes. (It is also possible that this was the case of UT4G 3090 + Latitude 7430 when using driver v535, but I honestly don't remember exactly anymore)

I've tried this patch today and it has almost no effect on my setup: generally everything works as before, but booting with the USB4 eGPU connected to the X4 has not worked even once since then: I needed to re-plug afterwards every time when using this patch. Unplugging when using this patch still requires unbinding from the driver, otherwise terrible crashes occur (so no change comparing to the vanilla v590).

If this patch is a make-or-break for TB5 eGPUs, then I guess it is ok to merge it, but if we could at least try to bring the success rate of booting with USB4 eGPUs somewhere close to the old values, it would be really cool ;-) I will probably be able to help with some testing and debugging.

@roger-pmta

Copy link
Copy Markdown
Author

Thanks for the feedback and testing @morgwai! Let me check where these delays are happening and I'll do more testing with hardware today. Ideally I'd love cold boot to work myself, perhaps the eGPU delay I added is happening too late the initialization process (waiting for PCIe link vs. GSP firmware?) If cold boot was working for you before on TB3 and it isn't now, that's concerning.

For folks who find this, @morgwai and I have been chatting in the thread at https://egpu.io/forums/thunderbolt-linux-setup/rtx-5080-via-thunderbolt-5-egpu-hard-lock-on-cuda-operations-nvidia-smi-works-at-idle/ too.

@roger-pmta

This comment was marked as outdated.

@roger-pmta

roger-pmta commented Dec 7, 2025 •

Copy link
Copy Markdown
Author

I found that nvidia-persistenced wasn't helping things; I disabled it entirely. It seems to quietly reset the power limit to 360W, overriding my udev rule/script. The script I have to limit power on module load needed to be adjusted: increased timeout, then set the power limit. gpu_burn (https://github.com/wilicc/gpu-burn) is running successfully, the GPU is pulling 325-326W at its new power limit, and at that level is sustaining 11.47-11.48 TFLOP/s (significantly less than ideal, but the point is that it's working and seems relatively stable). Still getting a lot of slow RPC responses from GSP in the dmesg output though.

cat <<'EOF' | sudo tee /usr/local/bin/nvidia-egpu-power-init.sh
#!/bin/bash
sleep 5
if nvidia-smi -pl 325; then
    logger "nvidia-egpu-power-init: Set power limit to 325W"
else
    logger "nvidia-egpu-power-init: Failed to set power limit"
fi
EOF

gpu_burn, PyTorch, and Ollama are all working.

See latest nvidia-bug-report.log attached. This is the absolute closest I've gotten to getting this working properly, and probably the cleanest log yet. Ran with --extra-system-data.

nvidia-bug-report.log-3.gz

Add periodic osSchedule() calls to spin loops that wait for firmware
responses. This prevents soft lockups when response times are elevated,
particularly for external GPUs over Thunderbolt where latency is higher.

Modified functions:
  - kfspWaitForResponse: FSP command response polling
  - kgspIssueNotifyOp_GH100: GSP lockless operation polling
  - ksec2PollForCanSend_IMPL: SEC2 command queue polling
  - _kgspRpcRecvPoll: GSP RPC response polling
  - timeoutCondWait: condition wait polling

Each loop yields every 256 iterations to allow other kernel threads
to run while waiting.
Extend external GPU support to work reliably with Thunderbolt 4/5 and
USB4, and improve stability for all Thunderbolt connections.

Detection:
  - Use kernel's is_thunderbolt flag (Linux 4.10+) for vendor-agnostic
    detection instead of Intel-specific device IDs
  - Set is_external_gpu early in nv_pci_probe(), before RM initialization
  - Add TB4, TB5, USB4 bus type constants for GSP communication
  - Accept either HotPlug+ or Surprise+ slot capability, as some TB5
    bridges report only the latter

Timeouts:
  - Extend GPU timeouts 4x for external GPUs to accommodate tunneling
    latency
  - Retry with exponential backoff (up to 1 second) in osHandleGpuLost()
    before declaring GPU lost, per PCIe Base Spec sec 6.6.1

Cold boot:
  - Retry BAR validation with exponential backoff when initial validation
    fails on Thunderbolt devices (tunnel may not be ready on cold boot)

Debug:
  - Add logging for GSP RPC, PRI errors, AER errors on external GPUs
@roger-pmta roger-pmta changed the title (gh-979) Thunderbolt 4/5 and USB4 eGPU Support (gh-979) Improve Thunderbolt eGPU detection and stability Dec 7, 2025
@roger-pmta roger-pmta changed the title (gh-979) Improve Thunderbolt eGPU detection and stability Improve Thunderbolt eGPU detection and stability Dec 7, 2025
@roger-pmta

Copy link
Copy Markdown
Author

@morgwai I cleaned up this PR and removed the need to set any driver params. The udev rule is for my own odd power situation that I mentioned on the forum. I had success with cold booting my enclosure (came up, nvidia-smi worked, but failed under CUDA workloads). I think that could be power related though. If you have time, I'm curious to see if your setup works with this branch now 🤞

#define NV2080_CTRL_INTERNAL_EGPU_BUS_TYPE_TB3 (0x00000003)
#define NV2080_CTRL_INTERNAL_EGPU_BUS_TYPE_TB4 (0x00000004)
#define NV2080_CTRL_INTERNAL_EGPU_BUS_TYPE_TB5 (0x00000005)
#define NV2080_CTRL_INTERNAL_EGPU_BUS_TYPE_USB4 (0x00000006)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At first I thought these values were arbitrary, but the code never assigns them to any vars, only compares them with what it receives from RM_API::Control in osinit.c, meaning the values of these constants come from somewhere else, like some spec or a header file that cannot be included here: could we please add a comment where exactly these values come from?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, and good catch! This is leftover from when I was hacking around with TB vendor IDs. This file is automatically generated by an NVIDIA-internal tool, therefore I need to undo this.

//
// This file was generated with FINN, an NVIDIA coding tool.
// Source file:      ctrl/ctrl2080/ctrl2080internal.finn
//

@morgwai morgwai Dec 8, 2025 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we file a separate bug regarding this? Does the module really treats TB4/TB5/USB4 eGPUs as dGPUs or maybe the vars/constant/comments just refer to all these cases as something-TB3-something due to historical reasons?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That, I'm not sure. I don't have any insight into how that file is being generated... perhaps something proprietary to NVIDIA, or the GSP firmware? 🤔

Cannot add arbitrary constants to generated files. The TB4/TB5/USB4 bus type
constants must come from NVIDIA when they update the FINN source.

Revert osinit.c to original TB3 legacy detection logic:
  - Use bTb3Bridge variable name (matches original)
  - Require both HotPlug+ AND Surprise+ (TB3 sets both)
  - Keep early-out for is_thunderbolt detection
  - Keep diagnostic logging for TB3 path
@roger-pmta

Copy link
Copy Markdown
Author

The more I think about this, I don't think I'm on the right path here. By playing around with IOMMU and PCIe kernel arguments I've gotten further, which makes me think this driver patch may be unnecessary. Disabling DMA Protection in BIOS causes panics at a different point in the boot cycle. I'm not sure why yet, but it leads me to believe it's IOMMU/DMA related. I'm going to close this PR for now and will update #979 with any new findings or patches, and see if I can grab a dump in the process. Whatever is going on though seems to be happening on both 580 and 590 on kernel 6.12.x.

@roger-pmta roger-pmta closed this Dec 8, 2025
@roger-pmta

Copy link
Copy Markdown
Author

I found that patching 590 wasn't consistent. I downgraded to 575 and am working on a patch, will post to #979 when it's done and I can run some stress tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants