Skip to content

Add more GPU metrics and implement NVML and ADL support - #3089

Merged
dbwiddis merged 5 commits into
oshi:masterfrom
dbwiddis:gpu-phase-2
Mar 12, 2026
Merged

dbwiddis merged 5 commits into
oshi:masterfrom
dbwiddis:gpu-phase-2

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Mar 11, 2026 •

Copy link
Copy Markdown
Member

Extends the GraphicsCard interface with five new dynamic metric methods and implements them across
all platform backends, with optional hardware vendor library integration (NVML for NVIDIA, ADL for
AMD on Windows). Phase 2 described in #2112 (comment).

New interface methods (GraphicsCard)

  • getTemperature() — GPU temperature in °C, or -1 if unavailable
  • getPowerDraw() — power draw in watts, or -1 if unavailable
  • getCoreClockMhz() — core clock in MHz, or -1 if unavailable
  • getMemoryClockMhz() — memory clock in MHz, or -1 if unavailable
  • getFanSpeedPercent() — fan speed as 0–100%, or -1 if unavailable

Default implementations returning -1 are provided in AbstractGraphicsCard. toString() is
extended to include each metric when its value is ≥ 0.

New JNA bindings

  • oshi.jna.common.Nvml — cross-platform JNA interface and structures for the NVIDIA Management
    Library (NVML), covering both Windows (nvml.dll) and Linux (libnvidia-ml.so.1). Placed in the
    new oshi.jna.common package for bindings that are not platform-specific.
  • oshi.jna.platform.windows.Adl — JNA interface and structures for the AMD Display Library (ADL),
    Windows only. Overdrive N (RX 400 series and newer) only.

New utility classes (oshi.util.gpu)

  • NvmlUtil — optional runtime binding to NVML. Loads the library once via the holder pattern;
    device handles are enumerated lazily on first use and cached. Each metric call pairs
    nvmlInit_v2/nvmlShutdown in a try/finally to correctly manage NVML's internal reference count
    without interfering with other NVML users in the same process — the same pattern
    WmiQueryHandler uses for COM.
  • AdlUtil — optional runtime binding to ADL. Same paired ADL2_Main_Control_Create/
    ADL2_Main_Control_Destroy lifecycle pattern. Adapter indices are enumerated lazily and cached.

Platform implementations

Windows (WindowsGraphicsCard): NVML → ADL → LibreHardwareMonitor (LHM) priority for all five
metrics. NVML correlation uses PCI bus ID when available, falling back to GPU name matching. ADL
correlation uses PCI bus number from DXGI. LHM is queried via the existing WMI sensor
infrastructure.

Linux (LinuxGraphicsCard): NVML → sysfs hwmon priority. hwmon is located via
drmDevicePath/hwmon/hwmonN. AMD-specific sysfs files (gpu_busy_percent, mem_info_vram_used,
pp_dpm_sclk, pp_dpm_mclk, fan1_input/fan1_max, pwm1, power1_average, freq1_input,
freq2_input) are used as fallback. Intel GT frequency files used for core clock.

macOS (MacGraphicsCard): getTemperature() reads "Temperature(C)" from IOKit
PerformanceStatistics on Intel Macs. Other metrics inherit the -1 defaults — not reliably
available through public IOKit APIs.

Notable design decisions

  • Paired init/uninit lifecycle: NVML and ADL both use internal reference-counted initialization.
    OSHI always decrements the same counter it incremented (similar to how COM is handled), ensuring no permanent reference is held that could interfere with user code managing these libraries independently. (TODO: similar user-controlled wrapper like we do with COM)
  • Sentinel values: -1d (double) or -1L (long) consistently indicate unavailability.
    toString() only appends a metric when its value is ≥ 0.
  • Windows PCI bus number: Not reliably derivable from the registry MatchingDeviceId on
    Windows. pciBusNumber stays -1; ADL correlation is unavailable on Windows; NVML falls back to
    name-based matching.
  • Linux getLongFromFile returns 0 on missing file: All sysfs checks use > 0 rather than
    >= 0 to avoid false positives.
  • ADL clock units: iCoreClock/iMemoryClock are in 10 kHz units; divided by 100 to produce
    MHz.
  • ADL temperature: Uses ADL_OVERDRIVE_TEMPERATURE_EDGE for the edge/GPU sensor; result is in
    millidegrees C, divided by 1000 to produce °C.

Summary by CodeRabbit

  • New Features
    • GPU health & performance metrics added (temperature, power draw, core & memory clocks, fan speed) with vendor integrations (NVML, ADL) and multi-source fallbacks plus improved device/PCI correlation.
  • Documentation
    • Reformatted changelog entry and added package-level notes describing optional GPU utilities and native bindings.
  • Tests
    • New/updated tests validating GPU metrics, metric string rendering, and PCI parsing/ID construction.

@coderabbitai

coderabbitai Bot commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds Phase‑2 GPU metrics (temperature, power draw, core/memory clocks, fan speed) to the GraphicsCard API and implementations; introduces NVML and ADL JNA bindings and runtime utilities; propagates PCI bus correlation across Linux, Windows, and macOS; adds hwmon/sysfs and ADL fallbacks and tests.

Changes

Cohort / File(s) Summary
Core interface & abstraction
CHANGELOG.md, oshi-core/src/main/java/oshi/hardware/GraphicsCard.java, oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java
Added five new GraphicsCard getters: getTemperature(), getPowerDraw(), getCoreClockMhz(), getMemoryClockMhz(), getFanSpeedPercent(). AbstractGraphicsCard supplies -1 defaults and updates toString() to include these fields when non‑sentinel.
Linux implementation & NVML
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java, oshi-core/src/main/java/oshi/jna/common/Nvml.java, oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java, oshi-core/src/main/java/oshi/jna/common/package-info.java
LinuxGraphicsCard gains pciBusId, drm parsing now returns PCI id; adds NVML-first metric retrieval with hwmon/sysfs fallbacks. Adds NVML JNA bindings and NvmlUtil runtime wrapper.
Windows implementation, ADL & LHM
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java, oshi-core/src/main/java/oshi/jna/platform/windows/Adl.java, oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java
WindowsGraphicsCard adds pciBusNumber/pciBusId, updated constructor and LOCATION_INFORMATION; implements NVML→ADL→LHM metric resolution with PCI correlation and parsing helpers. Adds ADL JNA bindings and AdlUtil wrapper.
macOS implementation
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
Adds getTemperature() reading IOAccelerator PerformanceStatistics ("Temperature(C)"); other Phase‑2 metrics remain default -1.
GPU util package metadata
oshi-core/src/main/java/oshi/util/gpu/package-info.java
Added package-info for oshi.util.gpu describing optional vendor GPU library integration (NVML, ADL).
Tests & module opens
oshi-core/src/test/java/oshi/hardware/GraphicsCardTest.java, oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java, oshi-core/src/test/java/oshi/hardware/platform/windows/WindowsGraphicsCardTest.java, oshi-core-java11/src/test/java/module-info.test, oshi-core-java25/src/test/java/module-info.test
Updated GraphicsCardTest to assert new metrics or -1; added AbstractGraphicsCardTest (toString/sentinel coverage) and WindowsGraphicsCardTest (PCI parsing); added --add-opens test JVM flags.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant GCard as GraphicsCard (platform impl)
    participant NVML as NvmlUtil
    participant ADL as AdlUtil
    participant HWMON as hwmon/sysfs
    participant IOA as IOAccelerator

    App->>GCard: getTemperature()
    alt Platform is Linux
        GCard->>NVML: findDevice(pciBusId) / nvmlDeviceGetTemperature()
        alt NVML success
            NVML-->>GCard: temperature
        else
            GCard->>HWMON: read hwmon/sysfs temp
            HWMON-->>GCard: temperature
        end
    else Platform is Windows
        GCard->>NVML: findDevice(pciBusId)
        alt NVML success
            NVML-->>GCard: temperature
        else
            GCard->>ADL: findAdapterIndex(pciBusNumber) / ADL temp query
            ADL-->>GCard: temperature
        end
    else Platform is macOS
        GCard->>IOA: queryPerfStats() -> "Temperature(C)"
        IOA-->>GCard: temperature (or -1)
    end
    GCard-->>App: temperature (double or -1)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I hop through PCI lanes at night,
NVML hums a gentle light.
ADL counts clocks and fans,
hwmon whispers from the lands,
I nibble metrics — bytes delight.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 39.10% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the primary change: adding five new GPU metrics (getTemperature, getPowerDraw, getCoreClockMhz, getMemoryClockMhz, getFanSpeedPercent) and implementing NVML/ADL support across platforms.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan for PR comments
  • Generate coding plan

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 and usage tips.

@codecov

codecov Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 6.92521% with 336 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.03%. Comparing base (a51a5e1) to head (7c71d63).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...shi-core/src/main/java/oshi/util/gpu/NvmlUtil.java 5.23% 198 Missing and 1 partial ⚠️
oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java 9.27% 137 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           master    #3089       +/-   ##
===========================================
- Coverage   84.64%   70.03%   -14.61%     
===========================================
  Files          33       35        +2     
  Lines        1478     1839      +361     
  Branches      217      297       +80     
===========================================
+ Hits         1251     1288       +37     
- Misses        132      453      +321     
- Partials       95       98        +3     

☔ View full report in Codecov by Sentry.
📢 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 9

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@CHANGELOG.md`:
- Around line 5-6: Update the changelog line to explicitly call out the public
API expansion: state that the GraphicsCard interface has gained five new getter
methods (add a parenthetical listing the exact new method names if available)
and note that downstream code that implements GraphicsCard must update their
implementations to include these new getters; keep the rest of the entry intact
but add this single-sentence warning about required changes for custom
implementations.

In `@oshi-core/src/main/java/oshi/hardware/GraphicsCard.java`:
- Around line 87-121: The interface GraphicsCard added new abstract methods
which breaks source compatibility; change getTemperature, getPowerDraw,
getCoreClockMhz, getMemoryClockMhz, and getFanSpeedPercent to default methods
that return the same sentinel values used in AbstractGraphicsCard (e.g., -1.0
for double methods and -1L for long methods) so existing external
implementations continue to compile without modification.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`:
- Around line 166-169: The code is calling findDrmInfo(null) for each lshw GPU
which returns the first DRM device and can incorrectly attach the same
drmDevicePath/pciBusId to multiple LinuxGraphicsCard instances; instead extract
the "bus info" value from the lshw entry and pass that PCI bus identifier into
findDrmInfo (e.g., findDrmInfo(pciBusId)) to correlate DRM info per-device, and
if the lshw entry has no bus info or mapping is ambiguous, set the
drmDevicePath/pciBusId fields empty for that LinuxGraphicsCard; reference the
findDrmInfo method, the LinuxGraphicsCard constructor call that uses
drmInfo.getA()/getB()/getC(), and the drmDevicePath/pciBusId fields when making
the change.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 187-196: The PCI correlation fields pciBusNumber and pciBusId are
left unset, so findAdlIndex() cannot correlate ADL devices; when a
DxgiAdapterInfo (dxgiMatch) is found in WindowsGraphicsCard creation (and in the
analogous block around lines 313-320) populate pciBusId from dxgiMatch (e.g.,
use dxgiMatch.getMatchingDeviceId() or other identifier available on
DxgiAdapterInfo) and derive pciBusNumber by parsing the bus number out of that
ID (or by querying the same DXGI/registry source) before calling
buildLuidPrefix()/constructing the card so findAdlIndex() can use those fields
for ADL correlation. Ensure both the dxgiMatch path and the other dxgi-available
creation path set pciBusNumber and pciBusId.

In `@oshi-core/src/main/java/oshi/jna/platform/windows/Adl.java`:
- Around line 26-29: Replace the AdlMallocCallback's base interface from
Callback to StdCallLibrary.StdCallCallback to match ADL's __stdcall ABI; update
imports to include com.sun.jna.win32.StdCallLibrary and change "interface
AdlMallocCallback extends Callback" to "interface AdlMallocCallback extends
StdCallLibrary.StdCallCallback" so the callback uses the stdcall convention
(retain the method signature Pointer invoke(int size)).
- Around line 56-69: AdapterInfo, ADLODNPerformanceStatus, and ADLODNFanControl
structure definitions do not match the official ADL SDK layout causing
buffer/offset corruption; update the classes (and their `@FieldOrder` annotations)
to exactly match the ADL spec: for AdapterInfo add strUDID (byte[64? per spec]),
strDriverPath, strDriverPathExt, strPNPString and iOSDisplayIndex in the correct
order so ADL2_Adapter_AdapterInfo_Get uses the right buffer size (also ensure
AdlUtil.enumerateAdapters() uses Structure.size() after the fix); for
ADLODNPerformanceStatus reorder fields to start with iCoreClock and add the
missing ints iDCEFClock, iGFXClock, iUVDClock, iVCEClock,
iCurrentDCEFPerformanceLevel, iCurrentGFXPerformanceLevel, iUVDPerformanceLevel,
iVDDCI and remove the phantom iReserved; for ADLODNFanControl rename
iFanControlFlag to iFanControlMode, add iCurrentFanSpeedMode and iMinFanLimit
and remove the phantom iThrottlingRPM so ADL2_OverdriveN_PerformanceStatus_Get
and ADL2_OverdriveN_FanControl_Get read/write correct native offsets.

In `@oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java`:
- Around line 55-57: The MALLOC_CB AdlMallocCallback currently returns pointers
to newly created Memory objects that become unreachable and may be freed by JNA;
retain those Memory instances for the ADL context lifetime by storing them in a
static collection (e.g., a List or Map) referenced from AdlUtil so they are not
GC-collected until ADL frees them, and ensure the free callback removes and
explicitly frees the corresponding Memory; apply the same change to the lambda
callback defined around the AdlMallocCallback declaration so every Memory
allocated in the callback is added to that retention collection and removed when
ADL explicitly frees it.

In `@oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java`:
- Around line 111-117: The code currently sets devicesEnumerated=true
unconditionally, which caches a failed NVML enumeration; change
ensureDevicesEnumerated()/enumerateDevices() so that enumerateDevices signals
success vs failure (e.g., return Optional<Map> or throw on NVML errors from
nvmlDeviceGetCount_v2()), and only set devicesEnumerated = true and assign
devices when enumerateDevices indicates success (even if the result is an empty
map due to zero GPUs); do not flip devicesEnumerated on transient NVML failures
so later name-based fallbacks can retry.
- Around line 170-188: The findDevice method currently returns an nvmlDevice_t
Pointer and then calls nvmlUninit(), which invalidates that handle across
init/shutdown cycles; instead, change the method (and the related devices cache
populated by ensureDevicesEnumerated) to store and return a stable identifier
such as the device PCI bus ID or GPU UUID (strings) rather than Pointer; update
callers/metric getters to, inside an nvmlInit() scope, re-acquire a fresh
nvmlDevice_t handle via nvmlDeviceGetHandleByPciBusId_v2() or
nvmlDeviceGetHandleByUUID() before reading metrics, and remove any logic that
reuses stored Pointer values after nvmlUninit() (refer to findDevice,
ensureDevicesEnumerated, devices map, nvmlInit, nvmlUninit,
nvmlDeviceGetHandleByPciBusId_v2, nvmlDeviceGetHandleByUUID).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 820d209b-effe-4049-8023-3c8797c719ad

📥 Commits

Reviewing files that changed from the base of the PR and between a51a5e1 and a31e10f.

📒 Files selected for processing (12)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/hardware/GraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/main/java/oshi/jna/common/Nvml.java
  • oshi-core/src/main/java/oshi/jna/common/package-info.java
  • oshi-core/src/main/java/oshi/jna/platform/windows/Adl.java
  • oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java
  • oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java
  • oshi-core/src/main/java/oshi/util/gpu/package-info.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Analyze (java)

Comment thread CHANGELOG.md Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

315-329: ⚠️ Potential issue | 🟡 Minor

WMI fallback path does not populate PCI correlation fields.

The getGraphicsCardsFromWmi() method sets pciBusNumber = -1 and pciBusId = "" unconditionally, even when a DXGI match is found. This disables ADL correlation for cards discovered via the WMI fallback path.

Consider parsing LocationInformation in the WMI path as well, similar to the registry path.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 315 - 329, In getGraphicsCardsFromWmi(), the PCI correlation fields
pciBusNumber and pciBusId are left as default (-1, "") even for WMI-discovered
cards; update the WMI path to parse LocationInformation (same way the registry
path does) and populate pciBusNumber and pciBusId before constructing the
WindowsGraphicsCard; locate the WMI branch in getGraphicsCardsFromWmi(),
extract/parse the LocationInformation string to derive the bus number and PCI ID
(reusing the registry parsing logic or helper method if available), and pass the
populated values into the WindowsGraphicsCard(...) constructor instead of the
hardcoded defaults.
♻️ Duplicate comments (3)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)

324-343: ⚠️ Potential issue | 🔴 Critical

NVML handle obtained by findNvmlDevice() may be stale.

findNvmlDevice() calls NvmlUtil.findDevice() which returns a handle from a now-closed NVML session. The handle is then passed to NvmlUtil.getTemperature() which opens a new session—but the old handle is invalid. This is a downstream effect of the issue in NvmlUtil.java.

Once NvmlUtil is fixed to return stable identifiers (e.g., PCI bus ID strings) instead of raw handles, this code will need updating to pass the identifier rather than a Pointer.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`
around lines 324 - 343, The NVML handle returned by findNvmlDevice() is stale;
update this method and its usages to work with stable identifiers (PCI bus ID
strings) returned by NvmlUtil.findDevice() instead of native Pointer handles:
change the local variable in getTemperature() from Pointer nvmlDevice to String
nvmlBusId (or similar), call the updated NvmlUtil.getTemperature(String busId)
(or add a new overload that accepts the bus ID) and update
findNvmlDevice()/NvmlUtil.findDevice() signatures accordingly; keep the existing
hwmon temp1_input fallback logic unchanged and return -1d only if both methods
fail.
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

701-712: ⚠️ Potential issue | 🔴 Critical

findNvmlDevice() uses a stale handle from NvmlUtil.findDevice().

Same issue as in LinuxGraphicsCard: the Pointer returned by NvmlUtil.findDevice() was obtained in a now-closed NVML session and is invalid. Once NvmlUtil is fixed to return stable identifiers, this method will need updating.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 701 - 712, findNvmlDevice() currently returns a Pointer from
NvmlUtil.findDevice(), which may be a stale NVML handle from a closed session;
change the logic to use a stable identifier instead of returning/propagating a
Pointer: update this method to fetch a stable device id (e.g., PCI bus id or a
unique device index returned by a fixed NvmlUtil API) via
NvmlUtil.findDevice()/findDeviceByName() and then resolve that stable id to a
valid Pointer only within the active NVML session (e.g., call a new
NvmlUtil.getHandleForStableId(stableId) or similar) so you no longer store or
return a Pointer obtained from a prior session; references: findNvmlDevice(),
NvmlUtil.findDevice(), NvmlUtil.findDeviceByName(), pciBusId, getName().
oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java (1)

246-260: ⚠️ Potential issue | 🔴 Critical

findDevice() returns a stale handle; callers cannot use it.

The findDevice() method acquires a device handle inside an nvmlInit/nvmlUninit scope, then returns that handle after calling nvmlUninit(). According to NVML documentation, nvmlDevice_t handles become invalid after nvmlShutdown(). Callers (e.g., LinuxGraphicsCard.findNvmlDevice(), WindowsGraphicsCard.findNvmlDevice()) then pass this stale handle to metric getters like getTemperature(Pointer device), which call nvmlInit() again—but the handle from the previous session is no longer valid.

The design should either:

  1. Return the PCI bus ID string (stable identifier) from findDevice(), and have metric getters accept the bus ID and reacquire the handle internally, or
  2. Combine device lookup and metric query into single methods that keep the handle within one init/shutdown scope.
Proposed approach: return bus ID instead of handle
-    public static Pointer findDevice(String pciBusId) {
+    public static String findDeviceBusId(String pciBusId) {
         if (!Holder.LIBRARY_LOADED || pciBusId == null || pciBusId.isEmpty()) {
             return null;
         }
         boolean init = nvmlInit();
         if (!init) {
             return null;
         }
         try {
             ensureDevicesEnumerated();
-            return acquireHandleByBusId(pciBusId);
+            // Return the matched bus ID string from cache, or null
+            String needle = pciBusId.toLowerCase(Locale.ROOT);
+            for (String id : deviceBusIds) {
+                if (id.contains(needle) || needle.contains(id)) {
+                    return id;
+                }
+            }
+            return null;
         } finally {
             nvmlUninit();
         }
     }

Then metric getters accept a bus ID and reacquire the handle:

public static double getTemperature(String pciBusId) {
    if (pciBusId == null || pciBusId.isEmpty()) {
        return -1d;
    }
    boolean init = nvmlInit();
    if (!init) {
        return -1d;
    }
    try {
        Pointer device = acquireHandleByBusId(pciBusId);
        if (device == null) {
            return -1d;
        }
        IntByReference temp = new IntByReference();
        if (Holder.LIB.nvmlDeviceGetTemperature(device, Nvml.NVML_TEMPERATURE_GPU, temp) == Nvml.NVML_SUCCESS) {
            return temp.getValue();
        }
        return -1d;
    } finally {
        nvmlUninit();
    }
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java` around lines 246 - 260,
findDevice currently returns an nvmlDevice handle that becomes invalid after
nvmlUninit; change its contract to return the stable PCI bus ID string instead
(or null on failure) and update all callers (e.g.,
LinuxGraphicsCard.findNvmlDevice, WindowsGraphicsCard.findNvmlDevice) to store
that bus ID; then change metric getters (e.g., getTemperature) to accept a
pciBusId, call nvmlInit(), use acquireHandleByBusId(pciBusId) inside that init
scope to get a fresh device Pointer, perform the metric query, and finally
nvmlUninit() before returning the result so no stale handles are used.
🧹 Nitpick comments (1)
oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java (1)

77-119: Add a zero-value boundary case for the new sentinel contract.

These cases cover -1 and positive values, but not 0. Since toString() includes metrics when the getter is >= 0, a regression to > 0 would slip through here. One all-zero case would lock that boundary down.

📏 Suggested boundary test
+    `@Test`
+    void testToStringIncludesZeroValuedPhase2Metrics() {
+        String s = new StubGraphicsCard(0d, 0d, 0L, 0L, 0d).toString();
+        assertThat(s, containsString("temp=0.0°C"));
+        assertThat(s, containsString("power=0.0W"));
+        assertThat(s, containsString("coreClock=0MHz"));
+        assertThat(s, containsString("memClock=0MHz"));
+        assertThat(s, containsString("fan=0.0%"));
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java`
around lines 77 - 119, Add a boundary test in AbstractGraphicsCardTest that
constructs a StubGraphicsCard with all phase‑2 metrics set to 0 (new
StubGraphicsCard(0d, 0d, 0L, 0L, 0d)) and asserts that toString() includes
"temp=0.0°C", "power=0.0W", "coreClock=0MHz", "memClock=0MHz", and "fan=0.0%";
this ensures the toString() inclusion predicate treats 0 as valid (>= 0) and
guards against regressions to a > 0 check.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 188-197: The pciBusId local remains empty causing NVML correlation
to fall back to name matching; populate pciBusId after you obtain location info
or a DxgiAdapterInfo match: extract domain, device and function (or build from
dxgiMatch PCI fields) and set pciBusId to the standard
"domain:bus:device.function" format (zero-pad hex as needed) in the
WindowsGraphicsCard constructor where pciBusNumber is set (near variables
pciBusNumber, pciBusId, locationInfo, DxgiAdapterInfo dxgiMatch and
buildLuidPrefix). Add small helpers parsePciDevice() and parsePciFunction()
(mirror parsePciBusNumber) to parse those parts from LocationInformation or use
dxgiMatch getters if available, then ensure findNvmlDevice can use pciBusId for
direct NVML matching instead of falling back to name matching.

In `@oshi-core/src/main/java/oshi/jna/platform/windows/Adl.java`:
- Around line 56-75: The AdapterInfo Structure field order is wrong and must
match the AMD ADL SDK layout so native writes (via ADL2_Adapter_AdapterInfo_Get)
map to correct offsets; update the `@FieldOrder` on class AdapterInfo and reorder
its fields to: iSize, iAdapterIndex, strUDID, iBusNumber, iDeviceNumber,
iFunctionNumber, iVendorID, strAdapterName, strDisplayName, iPresent, iExist,
strDriverPath, strDriverPathExt, strPNPString, iOSDisplayIndex (and ensure the
corresponding public fields in AdapterInfo follow that same sequence and sizes)
so iBusNumber and other fields are read correctly.
- Around line 101-112: The ADLODNFanControl `@FieldOrder` is incorrect: swap
iMinPerformanceClock and iMinFanLimit so the annotation matches the AMD ADL SDK
(iMinPerformanceClock comes before iMinFanLimit) to ensure fields in class
ADLODNFanControl map to the correct native offsets; update the `@FieldOrder` on
ADLODNFanControl (and verify the declared field names iMinFanLimit and
iMinPerformanceClock remain the same) so AdlUtil.getFanSpeedPercent() reads
iCurrentFanSpeed from the correct offset.
- Around line 77-99: The ADLODNPerformanceStatus Structure is missing the
iVCEPerformanceLevel field causing downstream offset corruption; update the
FieldOrder annotation for ADLODNPerformanceStatus to include
"iVCEPerformanceLevel" after "iUVDPerformanceLevel" and add a corresponding
public int iVCEPerformanceLevel field in the ADLODNPerformanceStatus class (so
the class defines all 18 fields in the correct order).

In `@oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java`:
- Around line 140-147: enumerateAdapters() can return null on ADL API failures
but ensureAdaptersEnumerated currently treats any return as success; change
ensureAdaptersEnumerated to call enumerateAdapters(context) and if it returns
non-null assign busToIndex, set adaptersEnumerated = true and log the adapter
count, but if it returns null do not set adaptersEnumerated and log an error
(including context) so failures are not cached as "zero adapters"; reference
ensureAdaptersEnumerated, enumerateAdapters, busToIndex, adaptersEnumerated and
the ADL calls ADL2_Adapter_NumberOfAdapters_Get/ADL2_Adapter_AdapterInfo_Get
when implementing.

In `@oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java`:
- Around line 40-63: The test overrides every getter in StubGraphicsCard causing
AbstractGraphicsCard's default -1 sentinel values never to be exercised; to fix,
add a second minimal stub (e.g., MinimalStubGraphicsCard) that extends
AbstractGraphicsCard and only implements getGpuTicks(), then change
testDefaultSentinelValues() to instantiate this minimal stub so all other
getters come from AbstractGraphicsCard and return -1 while keeping the existing
StubGraphicsCard for the formatting/value tests (also apply the same pattern for
the similar block around the other referenced region).

---

Outside diff comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 315-329: In getGraphicsCardsFromWmi(), the PCI correlation fields
pciBusNumber and pciBusId are left as default (-1, "") even for WMI-discovered
cards; update the WMI path to parse LocationInformation (same way the registry
path does) and populate pciBusNumber and pciBusId before constructing the
WindowsGraphicsCard; locate the WMI branch in getGraphicsCardsFromWmi(),
extract/parse the LocationInformation string to derive the bus number and PCI ID
(reusing the registry parsing logic or helper method if available), and pass the
populated values into the WindowsGraphicsCard(...) constructor instead of the
hardcoded defaults.

---

Duplicate comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`:
- Around line 324-343: The NVML handle returned by findNvmlDevice() is stale;
update this method and its usages to work with stable identifiers (PCI bus ID
strings) returned by NvmlUtil.findDevice() instead of native Pointer handles:
change the local variable in getTemperature() from Pointer nvmlDevice to String
nvmlBusId (or similar), call the updated NvmlUtil.getTemperature(String busId)
(or add a new overload that accepts the bus ID) and update
findNvmlDevice()/NvmlUtil.findDevice() signatures accordingly; keep the existing
hwmon temp1_input fallback logic unchanged and return -1d only if both methods
fail.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 701-712: findNvmlDevice() currently returns a Pointer from
NvmlUtil.findDevice(), which may be a stale NVML handle from a closed session;
change the logic to use a stable identifier instead of returning/propagating a
Pointer: update this method to fetch a stable device id (e.g., PCI bus id or a
unique device index returned by a fixed NvmlUtil API) via
NvmlUtil.findDevice()/findDeviceByName() and then resolve that stable id to a
valid Pointer only within the active NVML session (e.g., call a new
NvmlUtil.getHandleForStableId(stableId) or similar) so you no longer store or
return a Pointer obtained from a prior session; references: findNvmlDevice(),
NvmlUtil.findDevice(), NvmlUtil.findDeviceByName(), pciBusId, getName().

In `@oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java`:
- Around line 246-260: findDevice currently returns an nvmlDevice handle that
becomes invalid after nvmlUninit; change its contract to return the stable PCI
bus ID string instead (or null on failure) and update all callers (e.g.,
LinuxGraphicsCard.findNvmlDevice, WindowsGraphicsCard.findNvmlDevice) to store
that bus ID; then change metric getters (e.g., getTemperature) to accept a
pciBusId, call nvmlInit(), use acquireHandleByBusId(pciBusId) inside that init
scope to get a fresh device Pointer, perform the metric query, and finally
nvmlUninit() before returning the result so no stale handles are used.

---

Nitpick comments:
In `@oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java`:
- Around line 77-119: Add a boundary test in AbstractGraphicsCardTest that
constructs a StubGraphicsCard with all phase‑2 metrics set to 0 (new
StubGraphicsCard(0d, 0d, 0L, 0L, 0d)) and asserts that toString() includes
"temp=0.0°C", "power=0.0W", "coreClock=0MHz", "memClock=0MHz", and "fan=0.0%";
this ensures the toString() inclusion predicate treats 0 as valid (>= 0) and
guards against regressions to a > 0 check.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 33f3f1ec-8570-478d-88f3-080aed0e5abb

📥 Commits

Reviewing files that changed from the base of the PR and between a31e10f and b5e1632.

📒 Files selected for processing (10)
  • oshi-core-java11/src/test/java/module-info.test
  • oshi-core-java25/src/test/java/module-info.test
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/main/java/oshi/jna/platform/windows/Adl.java
  • oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java
  • oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java
  • oshi-core/src/test/java/oshi/hardware/GraphicsCardTest.java
  • oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java
  • oshi-core/src/test/java/oshi/hardware/platform/windows/WindowsGraphicsCardTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (10)
oshi-core-java11/src/test/java/module-info.test (1)

5-8: Looks correct.

These --add-opens entries line up with the new test packages in oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java:1-30 and oshi-core/src/test/java/oshi/hardware/platform/windows/WindowsGraphicsCardTest.java:1-20, so JUnit can keep reflecting into those package-private tests under JPMS.

oshi-core-java25/src/test/java/module-info.test (1)

5-8: Good parity with the Java 11 test config.

Opening these two packages to org.junit.platform.commons is consistent with the new test coverage and avoids JPMS-only test failures on the Java 25 path.

oshi-core/src/test/java/oshi/hardware/GraphicsCardTest.java (2)

2-2: LGTM!

Copyright year updated appropriately for the 2026 additions.


37-43: LGTM!

The assertions correctly validate the API contract: each metric must return either a valid reading (≥ 0) or the sentinel value (-1). The type handling is correct with -1d for double metrics and -1L for long metrics, and the failure messages are clear. This approach ensures tests pass across different environments regardless of GPU sensor availability.

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

1-77: LGTM on library loading and state management.

The holder pattern for lazy library loading and the volatile state variables for device enumeration are well-designed. The fix to cache bus ID strings instead of Pointer handles addresses the previous review concern about handle validity across shutdown cycles.

oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (2)

211-234: LGTM on DRM info discovery with PCI slot correlation.

The findDrmInfo() method now correctly matches DRM cards to PCI slots using the uevent file, addressing the previous review concern about assigning the same DRM device to all GPUs. The fallback to the first card with a driver is appropriate when no PCI slot is provided.


427-452: Fan speed calculation edge case: divide-by-zero is avoided but returns -1 unnecessarily.

When fanMax is 0 (some drivers report this), the fanRpm > 0 && fanMax > 0 check correctly skips division. The PWM fallback handles this case. Implementation looks correct.

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

54-90: Memory retention approach is reasonable given ADL constraints.

The design to retain Memory objects indefinitely in ADL_ALLOCATIONS is a pragmatic solution. Since ADL calls free() directly on the native pointer and doesn't provide a deallocation callback, keeping the Memory objects alive prevents JNA from double-freeing. The tradeoff (native memory remains allocated until process exit) is acceptable for the small number of ADL allocations.

oshi-core/src/test/java/oshi/hardware/platform/windows/WindowsGraphicsCardTest.java (1)

1-56: LGTM - comprehensive test coverage for PCI bus number parsing.

The test cases cover typical formats, boundary values (bus 0, bus 255), case insensitivity, and error conditions (null, empty, unrecognized format, non-numeric). The @EnabledOnOs(OS.WINDOWS) annotation appropriately restricts execution to Windows.

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

374-395: LGTM - PCI bus number parsing is correct and well-tested.

The parsePciBusNumber() implementation correctly handles the "PCI bus N, device N, function N" format with case-insensitive matching. The accompanying unit tests in WindowsGraphicsCardTest provide good coverage.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

316-330: WMI fallback path does not populate PCI correlation fields.

Unlike the main registry path (lines 188-198) which parses LocationInformation to populate pciBusNumber and pciBusId, the WMI fallback path initializes these fields to -1 and "" without attempting to retrieve location data. This means ADL correlation will be unavailable for cards discovered via the WMI fallback, even if the hardware is present and LocationInformation is available in the registry.

Consider querying LocationInformation from the registry using PNPDeviceID to enable ADL correlation in the WMI path as well.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 316 - 330, The WMI fallback currently leaves pciBusNumber and
pciBusId unset, breaking ADL correlation; in the block using
WmiUtil.getUint32asLong(...) and constructing new WindowsGraphicsCard(...),
lookup the registry LocationInformation using the card's PNPDeviceID (from the
WMI result) similar to the registry path parsing: retrieve LocationInformation,
parse it to extract the PCI bus number and PCI bus ID, and assign those to
pciBusNumber and pciBusId before creating the WindowsGraphicsCard instance (keep
the same parsing logic used for the registry path so
lhmParentMap/WindowsDxgi.normalizeName and ADL correlation remain consistent).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 316-330: The WMI fallback currently leaves pciBusNumber and
pciBusId unset, breaking ADL correlation; in the block using
WmiUtil.getUint32asLong(...) and constructing new WindowsGraphicsCard(...),
lookup the registry LocationInformation using the card's PNPDeviceID (from the
WMI result) similar to the registry path parsing: retrieve LocationInformation,
parse it to extract the PCI bus number and PCI bus ID, and assign those to
pciBusNumber and pciBusId before creating the WindowsGraphicsCard instance (keep
the same parsing logic used for the registry path so
lhmParentMap/WindowsDxgi.normalizeName and ADL correlation remain consistent).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: de32f8ac-1bba-45c9-8958-0eb5efebb5f5

📥 Commits

Reviewing files that changed from the base of the PR and between b5e1632 and 5ef9243.

📒 Files selected for processing (5)
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/main/java/oshi/jna/platform/windows/Adl.java
  • oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java
  • oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java
  • oshi-core/src/test/java/oshi/hardware/platform/windows/WindowsGraphicsCardTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Analyze (java)
🔇 Additional comments (13)
oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java (3)

18-64: Good targeted stub for formatting coverage.

This keeps the toString() tests focused on the new Phase 2 branches without overcoupling them to unrelated implementation details.


66-90: Nice fix for the default-sentinel regression gap.

testDefaultSentinelValues() now validates AbstractGraphicsCard’s real default getters, so future changes to the sentinel contract will be caught here.


92-155: Coverage looks solid for the new toString() rules.

The tests hit the important rendering cases: omit sentinels, include available metrics, keep base fields, and treat zero as a valid reading.

oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java (3)

54-90: Memory retention and library loading properly addresses past review concerns.

The ADL_ALLOCATIONS set correctly retains Memory objects allocated by the callback to prevent GC from collecting them while ADL holds pointers. The comment accurately documents the trade-off (process-lifetime retention since ADL calls C free() directly).

The holder pattern with MALLOC_CB retention is also correct—keeping the callback reference prevents it from being collected while ADL holds a native pointer to it.


140-177: Adapter enumeration now correctly handles API failures vs. zero adapters.

The implementation correctly addresses the past review concern:

  • Returns null on ADL API failures (lines 157, 168) to allow retry
  • Returns Collections.emptyMap() for legitimate zero-adapter case (line 161)
  • Only sets adaptersEnumerated = true on non-null result (line 147)

231-401: Public metric methods are well-structured with correct unit conversions.

The methods consistently:

  • Validate adapter index before ADL operations
  • Use try/finally for proper ADL context cleanup
  • Check Overdrive N support before querying Overdrive N APIs
  • Apply documented unit conversions (millidegrees/1000, 10kHz/100, 1/256 watts)
  • Return -1 sentinel on any failure path
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (4)

375-455: PCI parsing utilities are correctly implemented.

The parsing methods properly handle:

  • Null and empty input strings (return -1 or "")
  • Case-insensitive matching via toLowerCase(Locale.ROOT)
  • Format variations (trailing content after the number)

The buildPciBusId format "0000:%02x:%02x.%x" correctly produces the standard PCI bus ID format for NVML correlation.


636-754: Metric implementations follow a consistent and robust priority pattern.

All five new metrics (temperature, power, clocks, fan speed) consistently:

  1. Try NVML first (best for NVIDIA GPUs)
  2. Fall back to ADL (for AMD GPUs)
  3. Fall back to LHM as a last resort (works across vendors if LHM is running)

The >= 0 checks before returning ensure that -1 sentinel values properly cascade to the next priority source.


761-784: Device resolution helpers are correctly implemented.

findNvmlDevice() appropriately prioritizes PCI bus ID matching over name matching—this is more reliable for multi-GPU systems with identical GPU models.

findAdlIndex() correctly guards both on AdlUtil.isAvailable() and pciBusNumber >= 0, avoiding unnecessary ADL context creation when PCI bus number is unknown.


188-198: PCI correlation fields are now properly populated in the main path.

This addresses the past review concerns. The LocationInformation registry value is now parsed to extract:

  • pciBusNumber for ADL correlation
  • pciBusId (in "0000:BB:DD.F" format) for NVML correlation

Both NVML and ADL can now use PCI-based device matching instead of relying solely on name matching.

oshi-core/src/test/java/oshi/hardware/platform/windows/WindowsGraphicsCardTest.java (1)

1-96: Comprehensive test coverage for PCI parsing utilities.

The test class provides thorough coverage including:

  • Typical format parsing
  • Boundary values (bus 0, bus 255, device 31, function 7)
  • Case-insensitive matching
  • Null and empty input handling
  • Unrecognized format rejection
  • Non-numeric value handling

The @EnabledOnOs(OS.WINDOWS) annotation appropriately restricts these tests to Windows where the parsing logic is relevant.

oshi-core/src/main/java/oshi/jna/platform/windows/Adl.java (2)

26-29: ABI choice for the allocator callback looks correct.

Using StdCallCallback for AdlMallocCallback matches AMD's published ADL typedef for the allocator callback, which is declared as __stdcall. (gpuopen-librariesandsdks.github.io)


56-113: The native struct layouts now look aligned with ADL.

AdapterInfo, ADLODNPerformanceStatus, and ADLODNFanControl match the field order documented in AMD's public headers, which is the critical requirement for AdlUtil to read bus IDs, clocks, voltages, and fan speed safely from native memory. (gpuopen-librariesandsdks.github.io)

@dbwiddis

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Mar 12, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (2)
oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java (1)

246-282: ⚠️ Potential issue | 🔴 Critical

Device handles returned by findDevice*() are invalid when used in metric getters.

The findDevice() and findDeviceByName() methods return nvmlDevice_t handles after calling nvmlUninit() in the finally block. These handles become invalid immediately upon return. When callers pass them to metric getters like getTemperature(Pointer device), which perform their own nvmlInit(), the handle from the previous session is stale and the NVML calls will fail or produce undefined behavior.

The past review flagged this issue with a recommendation to cache stable identifiers (PCI bus ID strings) and reacquire handles within each metric getter's init scope.

🐛 Suggested approach

Instead of returning Pointer handles from findDevice*(), return the PCI bus ID string (or GPU UUID). Metric getters should accept this identifier and acquire a fresh handle within their own init/uninit scope:

-public static Pointer findDevice(String pciBusId) {
+public static String findDeviceBusId(String pciBusId) {
     // ... validate and return the matched PCI bus ID string, not a handle
 }

-public static double getTemperature(Pointer device) {
+public static double getTemperature(String pciBusId) {
     boolean init = nvmlInit();
     if (!init) return -1d;
     try {
+        Pointer device = acquireHandleByBusId(pciBusId);
+        if (device == null) return -1d;
         // ... query temperature
     } finally {
         nvmlUninit();
     }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java` around lines 246 - 282,
findDevice and findDeviceByName currently return nvmlDevice_t Pointer handles
that are invalidated by nvmlUninit in their finally blocks; change both methods
to return a stable identifier (prefer PCI bus ID string or GPU UUID) instead of
Pointer — use existing logic (ensureDevicesEnumerated,
acquireHandleByBusId/acquireHandleByName) to discover the matching device but
extract and return its PCI bus id/UUID, not the Pointer. Update all callers
(e.g., metric getters like getTemperature(Pointer) — refactor to accept the
identifier) so each metric method calls nvmlInit(), ensureDevicesEnumerated(),
then reacquires a fresh Pointer with acquireHandleByBusId (or by UUID) before
using NVML and finally calls nvmlUninit(); keep acquireHandle* and
ensureDevicesEnumerated for handle resolution but never return handles from a
method that uninitializes NVML.
oshi-core/src/main/java/oshi/hardware/GraphicsCard.java (1)

87-121: ⚠️ Potential issue | 🟠 Major

Convert these new methods to default methods to maintain API compatibility.

These five methods are declared as abstract, which breaks source compatibility for any downstream GraphicsCard implementations that don't extend AbstractGraphicsCard. The past review flagged this issue with a recommendation to use default methods.

While AbstractGraphicsCard provides sentinel implementations, external implementations directly implementing the GraphicsCard interface will fail to compile.

♻️ Proposed fix for API compatibility
-    double getTemperature();
+    default double getTemperature() {
+        return -1d;
+    }

-    double getPowerDraw();
+    default double getPowerDraw() {
+        return -1d;
+    }

-    long getCoreClockMhz();
+    default long getCoreClockMhz() {
+        return -1L;
+    }

-    long getMemoryClockMhz();
+    default long getMemoryClockMhz() {
+        return -1L;
+    }

-    double getFanSpeedPercent();
+    default double getFanSpeedPercent() {
+        return -1d;
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/GraphicsCard.java` around lines 87 -
121, The five newly added abstract accessors (getTemperature, getPowerDraw,
getCoreClockMhz, getMemoryClockMhz, getFanSpeedPercent) must be converted to
default interface methods to preserve source compatibility; change each
declaration in GraphicsCard to a default method returning the same
sentinel/unavailable values (e.g., -1.0 for doubles, -1L for longs) so external
classes that implement GraphicsCard continue to compile without forcing them to
implement these new members.
🧹 Nitpick comments (2)
oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java (1)

140-152: Minor: Potential benign race condition in ensureAdaptersEnumerated.

Two threads could simultaneously see adaptersEnumerated == false and both call enumerateAdapters(). While this is harmless (both would get the same result and the second assignment is idempotent), consider using double-checked locking with synchronization if you want to avoid redundant enumeration work.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java` around lines 140 - 152,
The method ensureAdaptersEnumerated currently allows a race where multiple
threads may call enumerateAdapters() concurrently; to prevent redundant work use
double-checked locking: first check adaptersEnumerated, then synchronize on a
shared lock (or the class) and check adaptersEnumerated again before calling
enumerateAdapters(), and only assign busToIndex and set adaptersEnumerated =
true inside the synchronized block (references: ensureAdaptersEnumerated,
adaptersEnumerated, enumerateAdapters, busToIndex).
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

316-330: WMI fallback path does not populate PCI correlation fields.

In the WMI fallback path (getGraphicsCardsFromWmi), pciBusNumber and pciBusId remain at their default values (-1 and ""). This means NVML and ADL correlation will fall back to name matching for cards created via WMI, which is less reliable on multi-GPU systems with identical models.

Consider querying Win32_PnPEntity or parsing the PNPDeviceID to extract PCI location when possible.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 316 - 330, The WMI fallback in getGraphicsCardsFromWmi leaves
pciBusNumber and pciBusId unset, causing unreliable NVML/ADL correlation; update
the WMI path to attempt extracting PCI location from the WMI card data (e.g.,
query Win32_PnPEntity or read/parse the PNPDeviceID from the cards result) and
set pciBusNumber and pciBusId before constructing the WindowsGraphicsCard;
specifically, locate where pciBusNumber/pciBusId are declared and the creation
of new WindowsGraphicsCard(...) and add logic to parse the PNPDeviceID (or
related Win32_PnPEntity properties) for PCI segment/bus/device/function and
populate those variables so the WindowsGraphicsCard(...) call receives real PCI
correlation values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@oshi-core/src/main/java/oshi/hardware/GraphicsCard.java`:
- Around line 87-121: The five newly added abstract accessors (getTemperature,
getPowerDraw, getCoreClockMhz, getMemoryClockMhz, getFanSpeedPercent) must be
converted to default interface methods to preserve source compatibility; change
each declaration in GraphicsCard to a default method returning the same
sentinel/unavailable values (e.g., -1.0 for doubles, -1L for longs) so external
classes that implement GraphicsCard continue to compile without forcing them to
implement these new members.

In `@oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java`:
- Around line 246-282: findDevice and findDeviceByName currently return
nvmlDevice_t Pointer handles that are invalidated by nvmlUninit in their finally
blocks; change both methods to return a stable identifier (prefer PCI bus ID
string or GPU UUID) instead of Pointer — use existing logic
(ensureDevicesEnumerated, acquireHandleByBusId/acquireHandleByName) to discover
the matching device but extract and return its PCI bus id/UUID, not the Pointer.
Update all callers (e.g., metric getters like getTemperature(Pointer) — refactor
to accept the identifier) so each metric method calls nvmlInit(),
ensureDevicesEnumerated(), then reacquires a fresh Pointer with
acquireHandleByBusId (or by UUID) before using NVML and finally calls
nvmlUninit(); keep acquireHandle* and ensureDevicesEnumerated for handle
resolution but never return handles from a method that uninitializes NVML.

---

Nitpick comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 316-330: The WMI fallback in getGraphicsCardsFromWmi leaves
pciBusNumber and pciBusId unset, causing unreliable NVML/ADL correlation; update
the WMI path to attempt extracting PCI location from the WMI card data (e.g.,
query Win32_PnPEntity or read/parse the PNPDeviceID from the cards result) and
set pciBusNumber and pciBusId before constructing the WindowsGraphicsCard;
specifically, locate where pciBusNumber/pciBusId are declared and the creation
of new WindowsGraphicsCard(...) and add logic to parse the PNPDeviceID (or
related Win32_PnPEntity properties) for PCI segment/bus/device/function and
populate those variables so the WindowsGraphicsCard(...) call receives real PCI
correlation values.

In `@oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java`:
- Around line 140-152: The method ensureAdaptersEnumerated currently allows a
race where multiple threads may call enumerateAdapters() concurrently; to
prevent redundant work use double-checked locking: first check
adaptersEnumerated, then synchronize on a shared lock (or the class) and check
adaptersEnumerated again before calling enumerateAdapters(), and only assign
busToIndex and set adaptersEnumerated = true inside the synchronized block
(references: ensureAdaptersEnumerated, adaptersEnumerated, enumerateAdapters,
busToIndex).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5803a8c9-f747-4dcf-b254-a4c994e4acda

📥 Commits

Reviewing files that changed from the base of the PR and between a51a5e1 and 5ef9243.

📒 Files selected for processing (17)
  • CHANGELOG.md
  • oshi-core-java11/src/test/java/module-info.test
  • oshi-core-java25/src/test/java/module-info.test
  • oshi-core/src/main/java/oshi/hardware/GraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/main/java/oshi/jna/common/Nvml.java
  • oshi-core/src/main/java/oshi/jna/common/package-info.java
  • oshi-core/src/main/java/oshi/jna/platform/windows/Adl.java
  • oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java
  • oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java
  • oshi-core/src/main/java/oshi/util/gpu/package-info.java
  • oshi-core/src/test/java/oshi/hardware/GraphicsCardTest.java
  • oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java
  • oshi-core/src/test/java/oshi/hardware/platform/windows/WindowsGraphicsCardTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (29)
oshi-core-java11/src/test/java/module-info.test (1)

5-8: LGTM!

The new --add-opens directives for oshi.hardware.common and oshi.hardware.platform.windows are correctly added and consistent with the java25 variant. These are required for JUnit Platform to access package-private members in AbstractGraphicsCardTest and WindowsGraphicsCardTest via reflection.

CHANGELOG.md (1)

5-6: Consider calling out the public API expansion explicitly.

This entry doesn't mention that GraphicsCard gains five new interface methods (getTemperature(), getPowerDraw(), getCoreClockMhz(), getMemoryClockMhz(), getFanSpeedPercent()). Downstream users implementing GraphicsCard directly should be aware of required changes.

oshi-core/src/main/java/oshi/jna/common/package-info.java (1)

1-9: LGTM!

The package documentation appropriately warns that these JNA bindings are non-API and may be removed, setting correct expectations for external consumers.

oshi-core-java25/src/test/java/module-info.test (1)

5-8: LGTM!

The --add-opens additions mirror the java11 variant correctly, ensuring consistent test behavior across both module configurations.

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

1-8: LGTM!

Clear package documentation describing the purpose of this new namespace for optional vendor GPU library integrations.

oshi-core/src/main/java/oshi/jna/common/Nvml.java (1)

1-75: LGTM!

The NVML JNA bindings are well-structured with appropriate constants, library interface methods, and structure definitions. The @FieldOrder annotations correctly specify field ordering for JNA memory mapping. The non-API disclaimer appropriately warns about potential removal.

oshi-core/src/main/java/oshi/jna/platform/windows/Adl.java (2)

56-75: LGTM! Structure field orders now match AMD ADL SDK.

The AdapterInfo structure field order has been corrected to match the AMD ADL SDK specification with strUDID at position 3 and iBusNumber at position 4. The StdCallCallback is also correctly used for the malloc callback.


77-113: LGTM! Performance and fan control structures are correctly defined.

Both ADLODNPerformanceStatus (with all 18 fields including iVCEPerformanceLevel) and ADLODNFanControl (with iMinPerformanceClock before iMinFanLimit) now match the AMD ADL SDK specification. Previous review issues have been addressed.

oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java (3)

54-90: LGTM! Memory retention pattern correctly addresses callback lifetime.

The ADL_ALLOCATIONS set properly retains Memory objects to prevent premature GC while ADL holds native pointers. The comment correctly explains that ADL frees memory via the C runtime, so these objects are kept alive for the process lifetime. The MALLOC_CB reference is also retained to prevent the callback from being GC'd.


140-152: LGTM! Null handling for adapter enumeration is correct.

The ensureAdaptersEnumerated method now properly distinguishes between ADL errors (null return, allows retry) and legitimate zero-adapter results (empty map, cached). This addresses the previous review concern.


272-276: Correct use of perf.read() after native call.

The explicit read() call properly synchronizes native memory to Java fields after ADL2_OverdriveN_PerformanceStatus_Get populates the structure. This pattern is correctly applied throughout the file.

oshi-core/src/test/java/oshi/hardware/GraphicsCardTest.java (1)

37-43: LGTM!

The Phase 2 metric assertions correctly validate that each dynamic metric returns either a valid reading or the sentinel value -1. The assertions align with the API contract defined in GraphicsCard.

oshi-core/src/test/java/oshi/hardware/platform/windows/WindowsGraphicsCardTest.java (1)

1-96: LGTM!

Comprehensive test coverage for the PCI parsing utilities. Good edge case handling including null, empty strings, case-insensitive matching, boundary values (bus 255, device 31, function 7), and unrecognized formats.

oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java (1)

173-199: LGTM!

The getTemperature() implementation correctly follows the existing pattern used by getGpuUtilization() and getVramUsed():

  • Properly manages CoreFoundation resources (CFStringRef released after use, dictionary released in finally)
  • Returns sentinel -1d when unavailable
  • Comment at lines 197-199 appropriately documents that other Phase 2 metrics inherit the default -1 behavior
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (4)

42-62: LGTM!

The pciBusId field and constructor update correctly integrate PCI bus identification for NVML correlation. The field is properly documented and follows the same pattern as existing fields.


161-194: LGTM!

The lshw parsing path now correctly extracts the bus info field and strips the pci@ prefix to obtain the PCI slot address for per-device DRM correlation. This properly addresses the multi-GPU correlation concern.


323-452: LGTM!

The Phase 2 metric implementations follow a consistent pattern:

  1. NVML first (via findNvmlDevice())
  2. Hwmon/sysfs fallbacks with appropriate driver checks (AMD: amdgpu, Intel: i915/xe)
  3. Proper unit conversions (millidegrees → °C, microwatts → watts, Hz → MHz)
  4. Sentinel -1 returns when unavailable

499-510: LGTM!

findNvmlDevice() correctly prioritizes PCI bus ID matching over name-based fallback, which improves reliability on multi-GPU systems with identical models.

oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java (2)

93-119: LGTM!

The toString() extension correctly:

  • Guards each Phase 2 metric with >= 0 check before appending
  • Uses Locale.ROOT for consistent decimal formatting across locales
  • Follows consistent formatting patterns (temperature with °C, power with W, clocks with MHz suffix, fan with %)

146-169: LGTM!

The default implementations correctly return sentinel values (-1d for double, -1L for long), ensuring all subclasses have a working baseline without requiring overrides.

oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java (2)

50-67: LGTM!

The holder pattern correctly:

  • Loads the native library once at class initialization
  • Handles platform-specific library names (nvml on Windows, nvidia-ml on Linux)
  • Gracefully handles UnsatisfiedLinkError and NoClassDefFoundError

113-158: LGTM!

The device enumeration logic correctly addresses the past review concern:

  • enumerateDeviceBusIds() returns null on NVML error (distinguishing failure from empty result)
  • ensureDevicesEnumerated() only sets devicesEnumerated = true on success, allowing retry on transient failures
  • Stores PCI bus ID strings (stable identifiers) rather than handles
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (4)

102-127: LGTM!

The new PCI correlation fields (pciBusNumber for ADL, pciBusId for NVML) are well-documented and properly integrated into the constructor. This enables device-to-metric correlation for multi-GPU systems.


188-198: LGTM!

PCI correlation fields are now properly populated from LocationInformation when a DXGI match is found. This addresses the previous review concern about empty PCI fields preventing ADL/NVML correlation.


375-455: LGTM!

The PCI parsing helpers are well-implemented:

  • Handle null/empty inputs gracefully (return -1 or "")
  • Case-insensitive matching for format variations
  • buildPciBusId correctly formats the standard 0000:BB:DD.F PCI bus ID format with hex zero-padding
  • Comprehensive test coverage in WindowsGraphicsCardTest

636-754: LGTM!

The Phase 2 metric implementations follow a consistent fallback chain (NVML → ADL → LHM) with proper sentinel returns. The helper methods findNvmlDevice(), findAdlIndex(), and lhmFloatSensor() encapsulate the correlation logic cleanly.

Note: The findNvmlDevice() usage is affected by the handle invalidation issue identified in NvmlUtil - once that's fixed, this code will work correctly.

oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java (3)

66-90: LGTM! Past review concern properly addressed.

The MinimalStubGraphicsCard stub correctly exercises AbstractGraphicsCard's default sentinel implementations without overriding them. The testDefaultSentinelValues() test now validates the actual base-class defaults rather than overridden values, which was the concern raised in the previous review.


146-155: Good edge-case coverage for zero values.

This test correctly validates that zero is treated as a valid reading (≥ 0) rather than a sentinel. This is an important boundary case since the sentinel value is -1, and zero could easily be mishandled in conditional checks like value >= 0 vs value > 0.


81-144: Test suite is comprehensive and well-structured.

The tests cover:

  • Default sentinel values from the base class
  • Conditional toString() behavior for each Phase 2 metric
  • Combination scenarios (all sentinel, all available, mixed)
  • Base field presence regardless of Phase 2 state

The use of Hamcrest matchers provides clear, readable assertions.

@mprins mprins left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

👍🏽

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (2)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)

159-185: ⚠️ Potential issue | 🟠 Major

lshw PCI matching still collapses to the first DRM device.

lshw reports bus info values like pci@0000:01:00.0, but split(":") breaks that field into more than two tokens, so the bus info branch never runs and busInfo stays null. findDrmInfo(null) then falls back to firstWithDriver, so the lshw path can still attach the first DRM/NVML mapping to every GPU.

Possible fix
-            String[] split = line.trim().split(":");
+            String[] split = line.trim().split(":", 2);
...
-        Triplet<String, String, String> firstWithDriver = null;
         for (File card : cards) {
             String devicePath = card.getAbsolutePath() + "/device";
             String driver = readDriverName(devicePath + "/driver");
             if (driver.isEmpty()) {
                 continue;
             }
             String slotName = readUeventValue(devicePath + "/uevent", "PCI_SLOT_NAME");
-            if (firstWithDriver == null) {
-                firstWithDriver = new Triplet<>(devicePath, driver, slotName);
-            }
             // Attempt PCI slot match via uevent
-            if (pciSlot != null && slotName.endsWith(pciSlot)) {
+            if (pciSlot != null && !pciSlot.isEmpty() && slotName.endsWith(pciSlot)) {
                 return new Triplet<>(devicePath, driver, slotName);
             }
         }
-        // Fall back to first card with a driver symlink
-        return firstWithDriver != null ? firstWithDriver : new Triplet<>("", "", "");
+        return new Triplet<>("", "", "");

Also applies to: 209-232

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`
around lines 159 - 185, The lshw parser in LinuxGraphicsCard is incorrectly
using line.trim().split(":") which splits the "bus info" value (e.g.,
"pci@0000:01:00.0") into multiple tokens so the bus info branch never executes;
update the parsing logic used in the loop that builds cardList (the section
referencing busInfo, versionInfoList, name, vendor, vram) to only split into two
parts (or otherwise locate the first ':' and treat the remainder as the value)
so that prefix detection like prefix.equals("bus info") works and busInfo is set
(affecting findDrmInfo calls); apply the same fix to the duplicate parsing block
later (lines handling the same fields around the second occurrence noted) so
both lshw parsing sites handle colon-containing values correctly.
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

187-197: ⚠️ Potential issue | 🟠 Major

Fallback card construction still drops PCI correlation.

pciBusNumber/pciBusId are only filled in the registry path when dxgiMatch != null, and the WMI path never fills them at all. That leaves findAdlIndex() dead and forces findNvmlDevice() back to name matching whenever DXGI discovery is unavailable or getGraphicsCardsFromWmi(...) is used, which is unsafe on same-model multi-GPU systems.

Also applies to: 315-329

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 187 - 197, The PCI correlation fields pciBusNumber and pciBusId are
only set when WindowsDxgi.findMatch returns non-null, causing loss of PCI
mapping for the WMI/fallback path; change the logic so locationInfo is read and
parsed (using parsePciBusNumber and buildPciBusId) regardless of dxgiMatch
presence (i.e., move or duplicate the parsePciBusNumber(locationInfo) and
buildPciBusId(locationInfo) calls out of the dxgiMatch-only block), and ensure
buildLuidPrefix remains conditional on dxgiMatch while pciBusNumber/pciBusId are
always populated for use by findAdlIndex and findNvmlDevice (apply same fix to
the analogous block around the 315-329 region and any getGraphicsCardsFromWmi
fallback).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`:
- Around line 159-185: The lshw parser in LinuxGraphicsCard is incorrectly using
line.trim().split(":") which splits the "bus info" value (e.g.,
"pci@0000:01:00.0") into multiple tokens so the bus info branch never executes;
update the parsing logic used in the loop that builds cardList (the section
referencing busInfo, versionInfoList, name, vendor, vram) to only split into two
parts (or otherwise locate the first ':' and treat the remainder as the value)
so that prefix detection like prefix.equals("bus info") works and busInfo is set
(affecting findDrmInfo calls); apply the same fix to the duplicate parsing block
later (lines handling the same fields around the second occurrence noted) so
both lshw parsing sites handle colon-containing values correctly.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 187-197: The PCI correlation fields pciBusNumber and pciBusId are
only set when WindowsDxgi.findMatch returns non-null, causing loss of PCI
mapping for the WMI/fallback path; change the logic so locationInfo is read and
parsed (using parsePciBusNumber and buildPciBusId) regardless of dxgiMatch
presence (i.e., move or duplicate the parsePciBusNumber(locationInfo) and
buildPciBusId(locationInfo) calls out of the dxgiMatch-only block), and ensure
buildLuidPrefix remains conditional on dxgiMatch while pciBusNumber/pciBusId are
always populated for use by findAdlIndex and findNvmlDevice (apply same fix to
the analogous block around the 315-329 region and any getGraphicsCardsFromWmi
fallback).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cca54191-0d31-49d3-968e-42bff5d05af3

📥 Commits

Reviewing files that changed from the base of the PR and between 5ef9243 and 23e64d8.

📒 Files selected for processing (3)
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Analyze (java)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java (1)

256-307: Consider batching performance status queries.

The methods getGpuUtilization(), getCoreClockMhz(), and getMemoryClockMhz() all call ADL2_OverdriveN_PerformanceStatus_Get and extract different fields from the same ADLODNPerformanceStatus structure. If these metrics are frequently queried together, consider adding a combined method that returns all three values from a single ADL call to reduce overhead.

This is a nice-to-have optimization for performance-sensitive use cases.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java` around lines 256 - 307,
Current methods getGpuUtilization, getCoreClockMhz, and getMemoryClockMhz each
call ADL2_OverdriveN_PerformanceStatus_Get separately; create a single batched
helper (e.g., getOverdriveNPerformance(adapterIndex) or getPerformanceStatus)
that calls adlInit(), checks supportsOverdriveN(ctx, adapterIndex), invokes
Holder.LIB.ADL2_OverdriveN_PerformanceStatus_Get once to populate an
ADLODNPerformanceStatus, reads it, and returns a small struct/POJO with
iGPUActivityPercent, iCoreClock/100, and iMemoryClock/100; update
getGpuUtilization/getCoreClockMhz/getMemoryClockMhz to call this helper and
extract the respective field, ensuring adlUninit(ctx) is still called in finally
and error paths return -1 consistent with existing behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java`:
- Around line 256-307: Current methods getGpuUtilization, getCoreClockMhz, and
getMemoryClockMhz each call ADL2_OverdriveN_PerformanceStatus_Get separately;
create a single batched helper (e.g., getOverdriveNPerformance(adapterIndex) or
getPerformanceStatus) that calls adlInit(), checks supportsOverdriveN(ctx,
adapterIndex), invokes Holder.LIB.ADL2_OverdriveN_PerformanceStatus_Get once to
populate an ADLODNPerformanceStatus, reads it, and returns a small struct/POJO
with iGPUActivityPercent, iCoreClock/100, and iMemoryClock/100; update
getGpuUtilization/getCoreClockMhz/getMemoryClockMhz to call this helper and
extract the respective field, ensuring adlUninit(ctx) is still called in finally
and error paths return -1 consistent with existing behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2e3f1926-aaf4-4f3f-acf9-d1a1c5c87be6

📥 Commits

Reviewing files that changed from the base of the PR and between 23e64d8 and 7c71d63.

📒 Files selected for processing (1)
  • oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Analyze (java)
🔇 Additional comments (7)
oshi-core/src/main/java/oshi/util/gpu/AdlUtil.java (7)

1-46: LGTM!

Clean imports, well-documented class with clear explanation of the ADL lifecycle pattern, sentinel values, and Overdrive N requirements.


51-86: LGTM!

The holder pattern correctly manages library loading with appropriate fallback. The malloc callback properly uses Native.malloc() with raw Pointer instead of Memory objects, avoiding the double-free issue since ADL owns and frees these allocations directly.


91-93: LGTM!

The volatile fields provide visibility guarantees. The check-then-act in ensureAdaptersEnumerated has a benign race where multiple threads may enumerate concurrently, but since enumeration is idempotent and the result is an unmodifiable map, this is safe and consistent with the @ThreadSafe annotation.


99-128: LGTM!

The init/uninit helpers correctly implement the paired ADL2 lifecycle pattern. The Javadoc clearly documents the reference-counting semantics. All call sites properly use try-finally to ensure cleanup.


136-173: LGTM!

The enumeration logic correctly distinguishes between ADL API failures (returns null, allows retry) and legitimate zero-adapter results (returns empty map, caches). This addresses the prior review concern about caching failures as "no adapters."


175-183: LGTM!

Correct check for Overdrive N support using the version from ADL2_Overdrive_Caps.


373-397: LGTM!

The fan speed method correctly handles the mode distinction—returning the percentage only when iFanControlMode == ADL_FAN_SPEED_MODE_PERCENT and returning -1 for RPM mode where percentage cannot be calculated. This matches the documented API contract.

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.

2 participants