Skip to content

Extract Solaris PowerSource common base (JNA/FFM parity, part 3) - #3369

Merged
dbwiddis merged 2 commits into
oshi:masterfrom
dbwiddis:solaris-powersource-common-base
Jun 11, 2026
Merged

dbwiddis merged 2 commits into
oshi:masterfrom
dbwiddis:solaris-powersource-common-base

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jun 11, 2026 •

Copy link
Copy Markdown
Member

Part 3 of 3 — the final piece of the Solaris JNA/FFM parity cleanup, after #3367 (software.os) and #3368 (hardware). PowerSource was held back from #3368 because it's static-factory/value-object shaped, but the battery math turns out to be cleanly shareable.

What changed

  • New abstract SolarisPowerSource base in oshi-common holding the default values and the bif/bst battery math.
  • The native battery/acpi_drv kstat read stays in SolarisPowerSourceJNA / SolarisPowerSourceFFM, which populate a BatteryReadings POJO (raw kstat values + per-block validity flags) and hand it to the shared buildPowerSources builder via a factory.
  • Each subclass keeps its kstat-module detection (KSTAT_BATT_IDX) and the queryPowerSources/getPowerSources entry points; the JNA HAL points at the renamed SolarisPowerSourceJNA.

This brings PowerSource in line with the rest of the Solaris classes (base in oshi-common + …JNA/…FFM concretes), completing the parity work.

Incidental JNA bug fix

The JNA side compared the battery "unknown capacity" sentinel against 0xffffffff written as an int (so -1L), which can never match the unsigned 32-bit 4294967295L that dataLookupLong returns (both JNA and FFM read UINT32 via FormatUtil.getUnsignedInt). So the JNA code silently never recognized the sentinel and could report a bogus max capacity / power rate. The shared math uses 0xFFFFFFFFL, matching the FFM behavior.

Full clean reactor build plus spotless/checkstyle/forbiddenapis/javadoc all pass locally.

Summary by CodeRabbit

  • New Features
    • Improved Solaris power-source reporting: broader device coverage and more accurate battery metrics (capacity units, current/max capacity, charging/discharging state, estimated time remaining, voltage and amperage).
  • Chore
    • Consolidated and refactored Solaris power-source logic for cleaner, maintainable platform implementations.

Move the battery default values and the bif/bst math into an abstract
SolarisPowerSource base in oshi-common. The native battery/acpi_drv kstat
read stays in the JNA and FFM subclasses, which populate a BatteryReadings
POJO and hand it to the shared builder; each subclass keeps its kstat-module
detection and the queryPowerSources/getPowerSources entry points. The JNA
HAL points at the renamed SolarisPowerSourceJNA.

Also fixes a pre-existing JNA bug: the "unknown capacity" sentinel was
compared against 0xffffffff as an int (-1L), which never matched the
unsigned 32-bit value (4294967295L) that dataLookupLong returns, so the JNA
side never recognized the sentinel. The shared math uses 0xFFFFFFFFL,
matching the FFM behavior.
@coderabbitai

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 177c1885-150c-4833-b688-b89bca12b02b

📥 Commits

Reviewing files that changed from the base of the PR and between 6cad468 and 68ee7c5.

📒 Files selected for processing (1)
  • oshi-common/src/main/java/oshi/hardware/common/platform/unix/solaris/SolarisPowerSource.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-common/src/main/java/oshi/hardware/common/platform/unix/solaris/SolarisPowerSource.java
📜 Recent 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). (15)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)

📝 Walkthrough

Walkthrough

Refactors Solaris power-source handling: a new common SolarisPowerSource base maps raw kstat BIF/BST readings into normalized PowerSource fields; platform implementations (JNA and FFM) read raw kstat values into BatteryReadings and delegate object construction to the common builder.

Changes

Solaris Power Source Abstraction Refactor

Layer / File(s) Summary
Shared base abstraction and battery reading contract
oshi-common/src/main/java/oshi/hardware/common/platform/unix/solaris/SolarisPowerSource.java
Introduces BatteryReadings container for raw BIF/BST kstat fields and validity flags, PowerSourceFactory functional interface for platform-specific instantiation, and buildPowerSources() method that maps validated battery readings into normalized power source properties: capacity units, max/current capacity with sentinel handling, charging/discharging state from bstState flags, remaining time estimation, and voltage/amperage conversion.
JNA-backed Solaris power source implementation
oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSourceJNA.java
New class extending the base abstraction with static kstat module discovery (battery vs. acpi_drv) at class load. getPowerSources() invokes readBattery() to open kstat chains and read BIF0/BST0 records into BatteryReadings, then delegates to buildPowerSources() for normalization and factory instantiation.
FFM implementation refactored to use base class
oshi-core-ffm/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSourceFFM.java
Updated to extend the new SolarisPowerSource base class and use buildPowerSources() instead of inline computation. Introduces readBattery() to extract BIF0/BST0 kstat values into BatteryReadings rather than deriving power values inline.
HAL wiring and configuration updates
oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisHardwareAbstractionLayerJNA.java, config/checkstyle-suppressions.xml
getPowerSources() delegated to SolarisPowerSourceJNA.getPowerSources(). Checkstyle VisibilityModifier suppression expanded to include the new SolarisPowerSource base class pattern.

Sequence Diagram(s)

sequenceDiagram
  participant SolarisPowerSourceJNA
  participant KstatUtil
  participant BatteryReadings
  participant SolarisPowerSource
  SolarisPowerSourceJNA->>SolarisPowerSourceJNA: getPowerSources()
  SolarisPowerSourceJNA->>SolarisPowerSourceJNA: readBattery()
  SolarisPowerSourceJNA->>KstatUtil: openChain()
  KstatUtil-->>SolarisPowerSourceJNA: kstat chain
  SolarisPowerSourceJNA->>KstatUtil: lookup(BIF0)
  KstatUtil-->>BatteryReadings: bif_* fields
  SolarisPowerSourceJNA->>KstatUtil: lookup(BST0)
  KstatUtil-->>BatteryReadings: bst_* fields
  SolarisPowerSourceJNA->>SolarisPowerSource: buildPowerSources("BAT0", BatteryReadings, factory)
  SolarisPowerSource-->>SolarisPowerSourceJNA: List~PowerSource~
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • oshi/oshi#3125: Prior refactor introducing queryPowerSources() dispatch and earlier Solaris power-source rework.

Poem

I nibble kstat crumbs at break of day,
BIF and BST in tidy array,
JNA and FFM hand me the read,
One shared rabbit path to build the feed,
Hopping batteries into fields of play 🐇🔋

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: extracting a common Solaris PowerSource base class to achieve JNA/FFM parity.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

❤️ Share

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

@codecov

codecov Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 75.09%. Comparing base (49441fd) to head (68ee7c5).

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3369      +/-   ##
============================================
- Coverage     75.12%   75.09%   -0.03%     
  Complexity       76       76              
============================================
  Files           564      564              
  Lines         22374    22374              
  Branches       3681     3681              
============================================
- Hits          16808    16802       -6     
- Misses         3499     3500       +1     
- Partials       2067     2072       +5     
Flag Coverage Δ
freebsd 26.20% <0.00%> (-0.01%) ⬇️
linux 29.61% <0.00%> (ø)
macos 30.29% <0.00%> (ø)
openbsd 25.64% <0.00%> (+0.01%) ⬆️
solaris 26.76% <100.00%> (+0.01%) ⬆️
windows 38.02% <0.00%> (-0.05%) ⬇️

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

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

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

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@oshi-common/src/main/java/oshi/hardware/common/platform/unix/solaris/SolarisPowerSource.java`:
- Around line 126-129: The current assignment of psCurrentCapacity from
readings.bstRemCap in SolarisPowerSource.java can incorrectly accept the unknown
sentinel 0xFFFFFFFFL (4294967295) as a valid value; update the condition around
readings.bstRemCap (used to compute psCurrentCapacity) to explicitly reject the
UNKNOWN_CAP sentinel (0xFFFFFFFFL / 4294967295) in addition to checking
non‑negativity so psCurrentCapacity is only set for genuine values (e.g.,
require energyNow >= 0 AND energyNow != UNKNOWN_CAP) and leave psCurrentCapacity
untouched when the sentinel is present.
- Around line 84-96: psRemainingCapacityPercent is left at 1d and never computed
from capacities; update SolarisPowerSource initialization logic to compute
psRemainingCapacityPercent = (psMaxCapacity > 0) ? (double)psCurrentCapacity /
psMaxCapacity : 1.0 and assign psDesignCapacity from readings.bifDesignCap (or
equivalent source) instead of leaving it as 1; ensure psCapacityUnits remains
correct and clamp/handle divide-by-zero or negative values per existing
conventions so the reported percentage reflects psCurrentCapacity/psMaxCapacity.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: bbe09a14-0d36-420f-8645-a801846e4af9

📥 Commits

Reviewing files that changed from the base of the PR and between 49441fd and 6cad468.

📒 Files selected for processing (6)
  • config/checkstyle-suppressions.xml
  • oshi-common/src/main/java/oshi/hardware/common/platform/unix/solaris/SolarisPowerSource.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSourceFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisHardwareAbstractionLayerJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSourceJNA.java
💤 Files with no reviewable changes (1)
  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.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). (16)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).

Applied to files:

  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisHardwareAbstractionLayerJNA.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSourceJNA.java
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/unix/solaris/SolarisPowerSource.java
🔇 Additional comments (11)
oshi-common/src/main/java/oshi/hardware/common/platform/unix/solaris/SolarisPowerSource.java (3)

31-46: LGTM!


48-69: LGTM!


136-153: LGTM!

Also applies to: 155-159

oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSourceJNA.java (3)

24-39: LGTM!


41-65: LGTM!


67-95: LGTM!

oshi-core-ffm/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSourceFFM.java (3)

15-21: LGTM!


56-63: LGTM!


65-92: LGTM!

oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisHardwareAbstractionLayerJNA.java (1)

57-60: LGTM!

config/checkstyle-suppressions.xml (1)

65-67: LGTM!

Comment on lines +84 to +96
double psRemainingCapacityPercent = 1d;
double psTimeRemainingEstimated = -1d; // -1 = unknown, -2 = unlimited
double psTimeRemainingInstant = 0d;
double psPowerUsageRate = 0d;
double psVoltage = -1d;
double psAmperage = 0d;
boolean psPowerOnLine = false;
boolean psCharging = false;
boolean psDischarging = false;
CapacityUnits psCapacityUnits = CapacityUnits.RELATIVE;
int psCurrentCapacity = 0;
int psMaxCapacity = 1;
int psDesignCapacity = 1;

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

psRemainingCapacityPercent is never computed from capacity values.

The remaining capacity percentage is initialized to 1d (100%) but never updated based on psCurrentCapacity and psMaxCapacity. This means the battery will always report 100% charge regardless of actual state.

Additionally, psDesignCapacity is initialized to 1 but never assigned from readings.bifDesignCap.

🐛 Proposed fix
         if (readings.bifValid) {
             // Predicted battery capacity when fully charged.
             long energyFull = readings.bifLastCap;
             if (energyFull == UNKNOWN_CAP || energyFull <= 0) {
                 energyFull = readings.bifDesignCap;
             }
             if (energyFull != UNKNOWN_CAP && energyFull > 0) {
                 psMaxCapacity = (int) energyFull;
             }
+            if (readings.bifDesignCap != UNKNOWN_CAP && readings.bifDesignCap > 0) {
+                psDesignCapacity = (int) readings.bifDesignCap;
+            }
             if (readings.bifUnit == 0) {
                 psCapacityUnits = CapacityUnits.MWH;
             } else if (readings.bifUnit == 1) {
                 psCapacityUnits = CapacityUnits.MAH;
             }
             psDeviceName = readings.bifModel;
             psSerialNumber = readings.bifSerial;
             psChemistry = readings.bifType;
             psManufacturer = readings.bifOemInfo;
         }

         if (readings.bstValid) {
             // estimated remaining battery capacity
             long energyNow = readings.bstRemCap;
             if (energyNow >= 0) {
                 psCurrentCapacity = (int) energyNow;
             }
             // ... existing code ...
         }
+
+        // Compute remaining capacity percentage from current/max
+        if (psMaxCapacity > 0) {
+            psRemainingCapacityPercent = Math.min(1d, (double) psCurrentCapacity / psMaxCapacity);
+        }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@oshi-common/src/main/java/oshi/hardware/common/platform/unix/solaris/SolarisPowerSource.java`
around lines 84 - 96, psRemainingCapacityPercent is left at 1d and never
computed from capacities; update SolarisPowerSource initialization logic to
compute psRemainingCapacityPercent = (psMaxCapacity > 0) ?
(double)psCurrentCapacity / psMaxCapacity : 1.0 and assign psDesignCapacity from
readings.bifDesignCap (or equivalent source) instead of leaving it as 1; ensure
psCapacityUnits remains correct and clamp/handle divide-by-zero or negative
values per existing conventions so the reported percentage reflects
psCurrentCapacity/psMaxCapacity.

bst_rem_cap can return the 0xFFFFFFFF "unknown" sentinel, which previously
passed the >= 0 check and cast to -1. Reject it like the adjacent bst_rate
sentinel so an unknown remaining capacity leaves the default rather than
reporting a garbage value.
@dbwiddis
dbwiddis merged commit 67a4a27 into oshi:master Jun 11, 2026
22 checks passed
@dbwiddis
dbwiddis deleted the solaris-powersource-common-base branch June 11, 2026 03:51
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.

1 participant