Repository navigation
Add more GPU metrics and implement NVML and ADL support - #3089
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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
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)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
📝 Coding Plan for PR comments
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. Comment |
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
📒 Files selected for processing (12)
CHANGELOG.mdoshi-core/src/main/java/oshi/hardware/GraphicsCard.javaoshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.javaoshi-core/src/main/java/oshi/jna/common/Nvml.javaoshi-core/src/main/java/oshi/jna/common/package-info.javaoshi-core/src/main/java/oshi/jna/platform/windows/Adl.javaoshi-core/src/main/java/oshi/util/gpu/AdlUtil.javaoshi-core/src/main/java/oshi/util/gpu/NvmlUtil.javaoshi-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)
There was a problem hiding this comment.
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 | 🟡 MinorWMI fallback path does not populate PCI correlation fields.
The
getGraphicsCardsFromWmi()method setspciBusNumber = -1andpciBusId = ""unconditionally, even when a DXGI match is found. This disables ADL correlation for cards discovered via the WMI fallback path.Consider parsing
LocationInformationin 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 | 🔴 CriticalNVML handle obtained by
findNvmlDevice()may be stale.
findNvmlDevice()callsNvmlUtil.findDevice()which returns a handle from a now-closed NVML session. The handle is then passed toNvmlUtil.getTemperature()which opens a new session—but the old handle is invalid. This is a downstream effect of the issue inNvmlUtil.java.Once
NvmlUtilis 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 aPointer.🤖 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 fromNvmlUtil.findDevice().Same issue as in
LinuxGraphicsCard: thePointerreturned byNvmlUtil.findDevice()was obtained in a now-closed NVML session and is invalid. OnceNvmlUtilis 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 annvmlInit/nvmlUninitscope, then returns that handle after callingnvmlUninit(). According to NVML documentation,nvmlDevice_thandles become invalid afternvmlShutdown(). Callers (e.g.,LinuxGraphicsCard.findNvmlDevice(),WindowsGraphicsCard.findNvmlDevice()) then pass this stale handle to metric getters likegetTemperature(Pointer device), which callnvmlInit()again—but the handle from the previous session is no longer valid.The design should either:
- Return the PCI bus ID string (stable identifier) from
findDevice(), and have metric getters accept the bus ID and reacquire the handle internally, or- 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
-1and positive values, but not0. SincetoString()includes metrics when the getter is>= 0, a regression to> 0would 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
📒 Files selected for processing (10)
oshi-core-java11/src/test/java/module-info.testoshi-core-java25/src/test/java/module-info.testoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.javaoshi-core/src/main/java/oshi/jna/platform/windows/Adl.javaoshi-core/src/main/java/oshi/util/gpu/AdlUtil.javaoshi-core/src/main/java/oshi/util/gpu/NvmlUtil.javaoshi-core/src/test/java/oshi/hardware/GraphicsCardTest.javaoshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.javaoshi-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-opensentries line up with the new test packages inoshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java:1-30andoshi-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.commonsis 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
-1dfor double metrics and-1Lfor 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
fanMaxis 0 (some drivers report this), thefanRpm > 0 && fanMax > 0check 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
Memoryobjects indefinitely inADL_ALLOCATIONSis a pragmatic solution. Since ADL callsfree()directly on the native pointer and doesn't provide a deallocation callback, keeping theMemoryobjects 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 inWindowsGraphicsCardTestprovide good coverage.
There was a problem hiding this comment.
🧹 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
LocationInformationto populatepciBusNumberandpciBusId, the WMI fallback path initializes these fields to-1and""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
LocationInformationfrom the registry usingPNPDeviceIDto 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
📒 Files selected for processing (5)
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.javaoshi-core/src/main/java/oshi/jna/platform/windows/Adl.javaoshi-core/src/main/java/oshi/util/gpu/AdlUtil.javaoshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.javaoshi-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 validatesAbstractGraphicsCard’s real default getters, so future changes to the sentinel contract will be caught here.
92-155: Coverage looks solid for the newtoString()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_ALLOCATIONSset correctly retainsMemoryobjects 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 Cfree()directly).The holder pattern with
MALLOC_CBretention 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
nullon ADL API failures (lines 157, 168) to allow retry- Returns
Collections.emptyMap()for legitimate zero-adapter case (line 161)- Only sets
adaptersEnumerated = trueon 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
-1sentinel on any failure pathoshi-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
buildPciBusIdformat"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:
- Try NVML first (best for NVIDIA GPUs)
- Fall back to ADL (for AMD GPUs)
- Fall back to LHM as a last resort (works across vendors if LHM is running)
The
>= 0checks before returning ensure that-1sentinel 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 onAdlUtil.isAvailable()andpciBusNumber >= 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
LocationInformationregistry value is now parsed to extract:
pciBusNumberfor ADL correlationpciBusId(in"0000:BB:DD.F"format) for NVML correlationBoth 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
StdCallCallbackforAdlMallocCallbackmatches 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, andADLODNFanControlmatch the field order documented in AMD's public headers, which is the critical requirement forAdlUtilto read bus IDs, clocks, voltages, and fan speed safely from native memory. (gpuopen-librariesandsdks.github.io)
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
♻️ Duplicate comments (2)
oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java (1)
246-282:⚠️ Potential issue | 🔴 CriticalDevice handles returned by
findDevice*()are invalid when used in metric getters.The
findDevice()andfindDeviceByName()methods returnnvmlDevice_thandles after callingnvmlUninit()in thefinallyblock. These handles become invalid immediately upon return. When callers pass them to metric getters likegetTemperature(Pointer device), which perform their ownnvmlInit(), 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
Pointerhandles fromfindDevice*(), 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 | 🟠 MajorConvert these new methods to
defaultmethods to maintain API compatibility.These five methods are declared as abstract, which breaks source compatibility for any downstream
GraphicsCardimplementations that don't extendAbstractGraphicsCard. The past review flagged this issue with a recommendation to usedefaultmethods.While
AbstractGraphicsCardprovides sentinel implementations, external implementations directly implementing theGraphicsCardinterface 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 inensureAdaptersEnumerated.Two threads could simultaneously see
adaptersEnumerated == falseand both callenumerateAdapters(). 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),pciBusNumberandpciBusIdremain at their default values (-1and""). 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_PnPEntityor parsing thePNPDeviceIDto 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
📒 Files selected for processing (17)
CHANGELOG.mdoshi-core-java11/src/test/java/module-info.testoshi-core-java25/src/test/java/module-info.testoshi-core/src/main/java/oshi/hardware/GraphicsCard.javaoshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.javaoshi-core/src/main/java/oshi/jna/common/Nvml.javaoshi-core/src/main/java/oshi/jna/common/package-info.javaoshi-core/src/main/java/oshi/jna/platform/windows/Adl.javaoshi-core/src/main/java/oshi/util/gpu/AdlUtil.javaoshi-core/src/main/java/oshi/util/gpu/NvmlUtil.javaoshi-core/src/main/java/oshi/util/gpu/package-info.javaoshi-core/src/test/java/oshi/hardware/GraphicsCardTest.javaoshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.javaoshi-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-opensdirectives foroshi.hardware.commonandoshi.hardware.platform.windowsare correctly added and consistent with the java25 variant. These are required for JUnit Platform to access package-private members inAbstractGraphicsCardTestandWindowsGraphicsCardTestvia reflection.CHANGELOG.md (1)
5-6: Consider calling out the public API expansion explicitly.This entry doesn't mention that
GraphicsCardgains five new interface methods (getTemperature(),getPowerDraw(),getCoreClockMhz(),getMemoryClockMhz(),getFanSpeedPercent()). Downstream users implementingGraphicsCarddirectly 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-opensadditions 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
@FieldOrderannotations 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
AdapterInfostructure field order has been corrected to match the AMD ADL SDK specification withstrUDIDat position 3 andiBusNumberat position 4. TheStdCallCallbackis also correctly used for the malloc callback.
77-113: LGTM! Performance and fan control structures are correctly defined.Both
ADLODNPerformanceStatus(with all 18 fields includingiVCEPerformanceLevel) andADLODNFanControl(withiMinPerformanceClockbeforeiMinFanLimit) 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_ALLOCATIONSset properly retainsMemoryobjects 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. TheMALLOC_CBreference is also retained to prevent the callback from being GC'd.
140-152: LGTM! Null handling for adapter enumeration is correct.The
ensureAdaptersEnumeratedmethod 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 ofperf.read()after native call.The explicit
read()call properly synchronizes native memory to Java fields afterADL2_OverdriveN_PerformanceStatus_Getpopulates 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 inGraphicsCard.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 bygetGpuUtilization()andgetVramUsed():
- Properly manages CoreFoundation resources (CFStringRef released after use, dictionary released in finally)
- Returns sentinel
-1dwhen unavailable- Comment at lines 197-199 appropriately documents that other Phase 2 metrics inherit the default
-1behavioroshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (4)
42-62: LGTM!The
pciBusIdfield 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
lshwparsing path now correctly extracts thebus infofield and strips thepci@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:
- NVML first (via
findNvmlDevice())- Hwmon/sysfs fallbacks with appropriate driver checks (AMD:
amdgpu, Intel:i915/xe)- Proper unit conversions (millidegrees → °C, microwatts → watts, Hz → MHz)
- Sentinel
-1returns 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
>= 0check before appending- Uses
Locale.ROOTfor 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 (
-1dfor double,-1Lfor 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 (
nvmlon Windows,nvidia-mlon Linux)- Gracefully handles
UnsatisfiedLinkErrorandNoClassDefFoundError
113-158: LGTM!The device enumeration logic correctly addresses the past review concern:
enumerateDeviceBusIds()returnsnullon NVML error (distinguishing failure from empty result)ensureDevicesEnumerated()only setsdevicesEnumerated = trueon 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 (
pciBusNumberfor ADL,pciBusIdfor 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
LocationInformationwhen 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
buildPciBusIdcorrectly formats the standard0000:BB:DD.FPCI 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(), andlhmFloatSensor()encapsulate the correlation logic cleanly.Note: The
findNvmlDevice()usage is affected by the handle invalidation issue identified inNvmlUtil- 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
MinimalStubGraphicsCardstub correctly exercisesAbstractGraphicsCard's default sentinel implementations without overriding them. ThetestDefaultSentinelValues()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 >= 0vsvalue > 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.
There was a problem hiding this comment.
♻️ Duplicate comments (2)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)
159-185:⚠️ Potential issue | 🟠 Major
lshwPCI matching still collapses to the first DRM device.
lshwreportsbus infovalues likepci@0000:01:00.0, butsplit(":")breaks that field into more than two tokens, so thebus infobranch never runs andbusInfostaysnull.findDrmInfo(null)then falls back tofirstWithDriver, so thelshwpath 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 | 🟠 MajorFallback card construction still drops PCI correlation.
pciBusNumber/pciBusIdare only filled in the registry path whendxgiMatch != null, and the WMI path never fills them at all. That leavesfindAdlIndex()dead and forcesfindNvmlDevice()back to name matching whenever DXGI discovery is unavailable orgetGraphicsCardsFromWmi(...)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
📒 Files selected for processing (3)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.javaoshi-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)
There was a problem hiding this comment.
🧹 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(), andgetMemoryClockMhz()all callADL2_OverdriveN_PerformanceStatus_Getand extract different fields from the sameADLODNPerformanceStatusstructure. 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
📒 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 rawPointerinstead ofMemoryobjects, 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
ensureAdaptersEnumeratedhas 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@ThreadSafeannotation.
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_PERCENTand returning -1 for RPM mode where percentage cannot be calculated. This matches the documented API contract.
Extends the
GraphicsCardinterface with five new dynamic metric methods and implements them acrossall 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-1if unavailablegetPowerDraw()— power draw in watts, or-1if unavailablegetCoreClockMhz()— core clock in MHz, or-1if unavailablegetMemoryClockMhz()— memory clock in MHz, or-1if unavailablegetFanSpeedPercent()— fan speed as 0–100%, or-1if unavailableDefault implementations returning
-1are provided inAbstractGraphicsCard.toString()isextended 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 ManagementLibrary (NVML), covering both Windows (
nvml.dll) and Linux (libnvidia-ml.so.1). Placed in thenew
oshi.jna.commonpackage 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/nvmlShutdownin a try/finally to correctly manage NVML's internal reference countwithout interfering with other NVML users in the same process — the same pattern
WmiQueryHandleruses for COM.AdlUtil— optional runtime binding to ADL. Same pairedADL2_Main_Control_Create/ADL2_Main_Control_Destroylifecycle pattern. Adapter indices are enumerated lazily and cached.Platform implementations
Windows (
WindowsGraphicsCard): NVML → ADL → LibreHardwareMonitor (LHM) priority for all fivemetrics. 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 viadrmDevicePath/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 IOKitPerformanceStatisticson Intel Macs. Other metrics inherit the-1defaults — not reliablyavailable through public IOKit APIs.
Notable design decisions
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)
-1d(double) or-1L(long) consistently indicate unavailability.toString()only appends a metric when its value is ≥ 0.MatchingDeviceIdonWindows.
pciBusNumberstays-1; ADL correlation is unavailable on Windows; NVML falls back toname-based matching.
getLongFromFilereturns 0 on missing file: All sysfs checks use> 0rather than>= 0to avoid false positives.iCoreClock/iMemoryClockare in 10 kHz units; divided by 100 to produceMHz.
ADL_OVERDRIVE_TEMPERATURE_EDGEfor the edge/GPU sensor; result is inmillidegrees C, divided by 1000 to produce °C.
Summary by CodeRabbit