Skip to content

Read GPU utilization from NVML and ADL on Windows - #3686

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:fix/windows-gpu-utilization-vendor-api
Aug 22, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:fix/windows-gpu-utilization-vendor-api

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 22, 2026 •

Copy link
Copy Markdown
Member

Fixes #3682.

WindowsGpuStats.getGpuUtilization() consulted no vendor API. It ran LibreHardwareMonitor and then a PDH engine-tick delta, while its five sibling metrics all run NVML, then ADL, then LHM:

metric NVML ADL LHM PDH ticks
getTemperature 1st 2nd 3rd —
getPowerDraw 1st 2nd 3rd —
getCoreClockMhz 1st 2nd 3rd —
getMemoryClockMhz 1st 2nd 3rd —
getFanSpeedPercent 1st 2nd 3rd —
getGpuUtilization (before) never never 1st 2nd
getGpuUtilization (after) 1st 2nd 3rd 4th

LHM is a third-party application that must be installed and running with its WMI provider, so for most users the only live path was the tick delta, which needs two samples and therefore returns the -1 sentinel on the first call. This is the same root cause as #3681 on Linux, and less severe: it is not -1 forever.

The tick delta stays as the last resort. It is vendor-neutral, covers Intel iGPUs, and sums all engines rather than just kernel execution.

The AMD half

NvmlUtil{JNA,FFM}.getGpuUtilization already existed and simply had no caller on Windows. ADL had no equivalent — but the value was already being fetched and discarded: iGPUActivityPercent is mapped in Adl.java, and the clock getters already pull that exact struct through ADL2_OverdriveN_PerformanceStatus_Get.

So both twins split their performance-status reader into a raw field read plus the clock's unit conversion, leaving the new getter as one more field of the same struct. The FFM offset of 24 is the 7th of the struct's 18 ints, consistent with the existing 72-byte allocation. JNA also picks up the ADL_ODN_CLOCK_UNITS_PER_MHZ constant its twin already had, in place of a bare division.

The LHM block inside getGpuUtilization was a duplicate of the existing lhmFloatSensor helper and now calls it.

Tests

WindowsGpuStats had no test at all, despite being the most source-complex of the three GpuStats implementations (20 dispatch points, four-deep priority chains) and despite both siblings having one. This PR adds WindowsGpuStatsTest, 23 tests stubbing every dispatch point. Three of them set NVML, ADL, LHM and the PDH counters to four different values at once and assert which one answers, so the tests pin source priority and not merely that some source responds.

That gap applied to Linux too: every NVML assertion in LinuxGpuStatsTest used an empty drmDevicePath, so dropping an NVML branch from a getter that also has a sysfs fallback would not have failed. Two tests close it — one reads a fully populated amdgpu tree behind a working NVML stub, the other reads the same fixture with NVML silent so the first cannot pass vacuously.

Both were mutation-checked: removing the NVML and ADL branches from the Windows chain, and the NVML branch from Linux getTemperature, fails 5 tests.

Verification

Full gate from a clean root — spotless:apply sortpom:sort checkstyle:check install forbiddenapis:check javadoc:javadoc -Paggregate-coverage — plus -Perror-prone for NullAway. Green.

Not verified on hardware. The NVML path mirrors the Linux one the reporter confirmed on a real NVIDIA card in #3681; the ADL path is untested against an AMD card, and its struct offset is derived from the header layout rather than measured.

Summary by CodeRabbit

  • New Features

    • Improved GPU utilization reporting across Linux and Windows.
    • NVIDIA GPUs now use NVML metrics where available.
    • Windows AMD GPUs now use ADL metrics where available.
    • Added consistent fallback support through existing hardware monitoring sources when vendor-specific metrics are unavailable.
    • Improved GPU memory and utilization metric sourcing for more reliable results.
  • Bug Fixes

    • Corrected GPU utilization reporting and source-priority behavior across supported platforms.

WindowsGpuStats.getGpuUtilization() consulted no vendor API. It ran
LibreHardwareMonitor and then a PDH engine-tick delta, while its five
sibling metrics all run NVML, then ADL, then LHM. LHM is a third-party
application that must be installed and running with its WMI provider, so
for most users the only live path was the tick delta, which needs two
samples and therefore returns the -1 sentinel on the first call.

Adds nvmlGetGpuUtilization and adlGetGpuUtilization as dispatch methods
and inserts them ahead of LHM. The tick delta stays as the last resort:
it is vendor-neutral, covers Intel iGPUs, and sums all engines rather
than just kernel execution.

NvmlUtil{JNA,FFM}.getGpuUtilization already existed and had no caller on
Windows. ADL had no equivalent, but iGPUActivityPercent was already
mapped in Adl.java and already fetched and discarded by the clock
getters, so both twins split their performance-status reader into a raw
field read plus the clock's unit conversion, leaving the new getter as
one more field of the same struct. The FFM offset 24 is the 7th of the
struct's 18 ints, consistent with the existing 72-byte allocation. JNA
picks up the ADL_ODN_CLOCK_UNITS_PER_MHZ constant its twin already had,
in place of a bare division.

The LHM block in getGpuUtilization was a duplicate of the existing
lhmFloatSensor helper and now calls it.

Adds WindowsGpuStatsTest. The class had no test at all despite being the
most source-complex of the three GpuStats implementations, and its
sibling tests exist. Also tightens LinuxGpuStatsTest: no test anywhere
pinned source priority, only source presence, so dropping an NVML branch
from a getter that also has a sysfs fallback would not have failed.

The ADL path is unverified against hardware; the offset is derived from
the struct layout rather than measured on an AMD card.

Fixes #3682
@coderabbitai

coderabbitai Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 46e5ed32-e4de-430f-9733-19924fac8762

📥 Commits

Reviewing files that changed from the base of the PR and between c411183 and af4b3f0.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsGpuStats.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxGpuStatsTest.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsGpuStatsTest.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/AdlUtilFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsJNA.java
  • oshi-core/src/main/java/oshi/util/gpu/AdlUtilJNA.java

Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review.

📜 Recent review details
⏰ Context from checks skipped due to timeout. (8)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Error Prone
  • GitHub Check: Test JDK 25, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle)
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (ForbiddenAPIs, Javadoc, SLF4J)
🧰 Additional context used
📓 Path-based instructions (5)
oshi-core-ffm/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

oshi-core-ffm may not reference com.sun.jna.**.

Files:

  • oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/AdlUtilFFM.java
**/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

**/src/main/java/**/*.java: Every public and protected type and method needs javadoc.
Do not use fully-qualified class names in
code or in javadoc — including inside {@link ...}. Import the type and link the simple name.
New files get a current-year-only
header (Copyright 2026 The OSHI Project Contributors / SPDX-License-Identifier: MIT), even when
copied from an older file; spotless maintains end years on existing files.
Normalize with ParseUtil.getStringValueOrUnknown / getStringValueOrEmpty rather than an
inline ternary.
Do not reach for @Nullable to make a null return legal: the convention is a sentinel, not a
null
— Constants.UNKNOWN or "" for strings, an empty collection or array, and 0/-1/NaN
for numbers, whichever is outside the value's real range.

Files:

  • oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsJNA.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/AdlUtilFFM.java
  • oshi-core/src/main/java/oshi/util/gpu/AdlUtilJNA.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsGpuStats.java
oshi-common/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

oshi-common/**/*.java: Before writing any parsing helper, check whether ParseUtil already has one.
oshi-common may not reference com.sun.jna.**, java.lang.foreign.**, or any
System.load/loadLibrary. It must stay pure JDK.

Files:

  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxGpuStatsTest.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsGpuStatsTest.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsGpuStats.java
**/*Test.java

📄 CodeRabbit inference engine (AGENTS.md)

Test files are named *Test.java.

Files:

  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxGpuStatsTest.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsGpuStatsTest.java
**/src/test/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

**/src/test/java/**/*.java: Tests must pass there and on real hardware.
Assert on invariants (non-null, correct type, ordering, a plausible range), not on specific values.
Zero and empty collections are legitimate results almost everywhere.
Any oshi-core test that allocates JNA needs
@DisabledIfSystemProperty(named = "os.name", matches = "(?i).*netbsd.*"); the NetBSD CI runner
has no libjnidispatch.

Files:

  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxGpuStatsTest.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsGpuStatsTest.java
🧠 Learnings (3)
📚 Learning: 2026-04-11T05:51:49.185Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3139
File: oshi-core-java25/src/main/java/oshi/hardware/platform/linux/LinuxGpuStatsFFM.java:36-58
Timestamp: 2026-04-11T05:51:49.185Z
Learning: For OSHI Linux GPU stats implementations (e.g., LinuxGpuStats and its LinuxGpuStatsJNA/LinuxGpuStatsFFM subclasses), treat NVML "nvml*" methods (such as nvmlGetVramUsed, nvmlGetCoreClockMhz, nvmlGetMemoryClockMhz, nvmlGetTemperature, nvmlGetPowerDraw, nvmlGetFanSpeedPercent) as having a documented failure sentinel: they are contractually expected to return -1 (long/double) on failure. The base class/implementations should use guards like `if (val >= 0)` before consuming NVML results and should fall back to sysfs/hwmon paths when the value is negative. In review, do not flag subclass pass-through of the -1 sentinel as a missing clamp/contract violation; only flag issues if the -1 sentinel is altered or NVML failure results are used without the expected `>= 0` guard or fallback behavior.

Applied to files:

  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxGpuStatsTest.java
📚 Learning: 2026-08-02T23:56:23.866Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3565
File: oshi-core-ffm/src/main/java/oshi/ffm/platform/unix/PosixLibcFunctions.java:51-56
Timestamp: 2026-08-02T23:56:23.866Z
Learning: For Java FFM bindings in the oshi-core-ffm module, assume a 64-bit JVM and 64-bit operating system. Do not flag 32-bit native ABI or memory-layout compatibility concerns, consistent with the project's JDK 25 support policy, unless that policy changes.

Applied to files:

  • oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/AdlUtilFFM.java
📚 Learning: 2026-08-15T15:43:29.296Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3628
File: oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java:108-108
Timestamp: 2026-08-15T15:43:29.296Z
Learning: In the OSHI Java codebase, use the sentinel-over-null convention at public API boundaries. Private helpers may return an explicitly JSpecify-annotated nullable value when the caller handles the missing result clearly and locally; callers must check for null before accessing the result. For example, methods such as lookupAccountBySid(String) may return String Nullable [] when queryUserSessions() performs the required null check.

Applied to files:

  • oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/AdlUtilFFM.java
🔇 Additional comments (8)
oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsGpuStats.java (1)

27-33: LGTM!

Also applies to: 119-126, 182-189, 286-305

CHANGELOG.md (1)

24-25: LGTM!

oshi-core/src/main/java/oshi/util/gpu/AdlUtilJNA.java (1)

50-52: LGTM!

Also applies to: 286-314, 316-326, 328-337

oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/AdlUtilFFM.java (1)

66-67: LGTM!

Also applies to: 378-401, 410-433

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsJNA.java (1)

64-68: LGTM!

Also applies to: 104-108

oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java (1)

64-68: LGTM!

Also applies to: 104-108

oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxGpuStatsTest.java (1)

541-566: LGTM!

Also applies to: 568-593

oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsGpuStatsTest.java (1)

1-566: LGTM!


📝 Walkthrough

Walkthrough

Windows GPU utilization now checks NVML and ADL before LHM and PDH fallbacks. JNA and FFM ADL utilities expose GPU activity values. Linux and Windows tests cover source precedence and fallback behavior.

Changes

GPU utilization sourcing

Layer / File(s) Summary
Windows source priority
oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsGpuStats.java, CHANGELOG.md
Windows utilization now queries NVML, ADL, LHM, and PDH in priority order. The changelog records the new vendor sources.
ADL activity retrieval
oshi-core/src/main/java/oshi/util/gpu/AdlUtilJNA.java, oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/AdlUtilFFM.java
ADL utilities read GPU activity from OverdriveN performance status. Clock reads retain MHz conversion.
Native backend dispatch
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsJNA.java, oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java
JNA and FFM Windows implementations delegate NVML and ADL utilization calls to their utility classes.
Source priority and fallback validation
oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxGpuStatsTest.java, oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsGpuStatsTest.java
Tests cover vendor precedence, fallback sources, PDH tick calculations, metric resolution, sentinel values, and closed-session behavior.

Estimated code review effort: 4 (Complex) | ~45 minutes

Merge Risk: ⚪ Minimal · up to af4b3

The change adds Windows GPU utilization through the existing vendor APIs while preserving fallback behavior, and no actionable merge-blocking risk remains after normal checks and review.

Sequence Diagram(s)

sequenceDiagram
  participant WindowsGpuStats
  participant NVML
  participant ADL
  participant LHM
  participant PDH
  WindowsGpuStats->>NVML: Query utilization
  NVML-->>WindowsGpuStats: Return value or unavailable
  WindowsGpuStats->>ADL: Query adapter utilization
  ADL-->>WindowsGpuStats: Return value or unavailable
  WindowsGpuStats->>LHM: Read GPU Core load
  LHM-->>WindowsGpuStats: Return load or unavailable
  WindowsGpuStats->>PDH: Calculate engine tick delta
  PDH-->>WindowsGpuStats: Return utilization or sentinel
Loading

Poem

I’m a rabbit with metrics to spare,
NVML and ADL now hop through the air.
LHM waits, PDH keeps time,
Tests guard each fallback line.
GPU numbers bloom everywhere!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.66% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 93 functions across 7 files. (1 skipped: 1 unsupported.) Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: adding NVML and ADL GPU utilization sources on Windows.
Linked Issues check ✅ Passed The changes satisfy #3682 by adding NVML and ADL dispatch before LHM and PDH, exposing ADL utilization, and adding priority tests.
Out of Scope Changes check ✅ Passed All code, tests, and changelog changes support the linked issue objectives, including the requested Linux priority coverage.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Aug 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.25%. Comparing base (c411183) to head (af4b3f0).

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3686      +/-   ##
============================================
- Coverage     80.30%   80.25%   -0.05%     
  Complexity     4307     4307              
============================================
  Files           707      707              
  Lines         25520    25520              
  Branches       4305     4305              
============================================
- Hits          20494    20482      -12     
- Misses         2809     2819      +10     
- Partials       2217     2219       +2     
Flag Coverage Δ
linux 39.55% <ø> (+0.06%) ⬆️
macos 40.38% <ø> (+0.03%) ⬆️
windows 46.77% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@dbwiddis
dbwiddis merged commit d9ef514 into oshi:master Aug 22, 2026
18 of 19 checks passed
@dbwiddis
dbwiddis deleted the fix/windows-gpu-utilization-vendor-api branch August 22, 2026 16:48
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.

Windows GpuStats.getGpuUtilization() never consults NVML or ADL, unlike every other metric on the class

1 participant