Repository navigation
Harden the macOS SMC fan speed and CPU voltage paths - #3545
Conversation
The temperature work in #3531, #3535 and #3536 left behind a generic key index scanner, a plausibility guard idiom and a config override pattern. The fan and voltage paths were never revisited and still read single hardcoded keys with no discovery, no plausibility guard and no test coverage. This applies that machinery to both. Fan speeds came from FNum alone: read the count, then format F%dAc for each index. That is a latent bug for a count of eleven or more, because String.format("F%dAc", 10) produces the five-character "F10Ac" and smcReadKey passes the key through ParseUtil.strToLong(key, 4), which reads only the first four bytes. "F10Ac" and "F10A" both encode to 0x46313041, so a corrupt or spoofed FNum makes OSHI read a different key and report its value as a fan speed, with no exception and no log. Keys are now discovered from the sorted key index, as the GPU keys are, and reconciled against FNum: discovery is authoritative where it found anything, a positive FNum still implies the conventionally named keys where it did not, and MAX_FANS bounds the synthesis so every key stays four characters. The count is scanned rather than probed directly because smcGetDataType returns an empty string for both "absent" and "read failed", and findKeys already distinguishes those. CPU voltage read VP0C, then VC0C/1000 if that returned zero, with the divisor tied to the key rather than to its encoding. It is now scaled from the key's SMC data type and held to a plausibility floor. fpe2 is fourteen integer and two fractional bits, so it resolves to a quarter of a unit: read as volts a 1.2 V core rail could only be expressed as 1.00 or 1.25, while read as millivolts it resolves to 0.25 mV over 0 to 16.4 V. Millivolts is the only self-consistent reading, so the existing divisor is kept, now derived from the type so a key whose encoding differs from the one expected still reads correctly. The floor makes the choice fail safe either way: a wrongly divided reading lands near 0.0012 V and is rejected as unavailable rather than returned as a believable wrong number. Voltage keys are deliberately not discovered, unlike the fan and GPU keys. Tg is a semantic prefix, where every match is a GPU cluster sensor; V is not. An M3 Pro's V block mixes a 0.75 V core voltage from VP0C with a 20.2 V supply rail from VD0R and a 0.86 V VPsC, under no naming rule that separates them, so a prefix scan could report a rail voltage as the CPU's. That is worse than reporting nothing, so the two named keys stay and oshi.os.mac.sensors.cpuvoltage.keys is the escape hatch, handing the guess to the user rather than making it in OSHI. A test asserts the defaults are unchanged so the pattern is not "completed" later. New in oshi-common, so both backends share it and it is testable off a Mac: SmcKeyIndex gains isFanSpeedKey, MAX_FANS, fanSpeedKeys and reconcileFanKeys, and a new SmcSensorValues holds toRpm, the voltage floor and scaleVoltage. toRpm preserves a zero reading rather than discarding it. iSMC drops readings below 0.005, which applied here would drop both fans on an idle M3 Pro, where F0Ac and F1Ac read 0.0 while F0Mn and F0Mx report 1350 and 5349: the fans are present and readable but not spinning. Sensors documents an empty array as "no fans detected" and a zero entry as "a fan reading zero or unmeasurable", so dropping them would turn two stopped fans into no fans. Also removes the per-instance numFans field. The key list in SmcUtil is now the single process-wide cache, matching gpuTemperatureKeys, and queryFanSpeeds resolves it before opening a connection because discovery opens its own. No CHANGELOG: on testable hardware nothing changes. The FNum truncation is only reachable through a corrupt or spoofed fan count, and the voltage scaling is unchanged for every data type observed. Verified on an M3 Pro (Mac15,7, macOS 26.5.2): FNum reads 2, getFanSpeeds returns [0, 0] before and after, and getCpuVoltage reads a plausible core voltage on both backends. The Intel fpe2 branch and every non-M3-Pro fan topology are untested for want of hardware. The two new properties are documented in oshi.properties. New tests: eight fan cases in SmcKeyIndexTest including both null-versus-empty rows of reconcileFanKeys and a case pinning every synthesized key at four characters, a new SmcSensorValuesTest, eight matching cases in each of the MacSensorsPlausibility twins, and a fanSpeedKeys comparison in NativeComparisonTest. That last one compares the two backends' discovered key lists, which is sharper than comparing rpm; the fan readings themselves are only compared when both are nonzero, since a fan spinning up between the sequential JNA and FFM reads would otherwise fail assertWithinRatio's one-value-zero branch.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📜 Recent review details⏰ Context from checks skipped due to timeout. (7)
📝 WalkthroughWalkthroughmacOS SMC sensor handling now discovers and caches fan keys, normalizes fan RPM values, selects configurable CPU-voltage keys, scales readings by datatype, and filters implausible voltages across JNA and FFM backends. Shared utilities, configuration, hardware tests, and backend comparison tests were added or updated. ChangesmacOS SMC sensor handling
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant MacSensorsFFM
participant SmcUtilFFM
participant SmcKeyIndex
participant SMC
MacSensorsFFM->>SmcUtilFFM: getFanSpeedKeys()
SmcUtilFFM->>SMC: discover SMC keys and FNum
SmcUtilFFM->>SmcKeyIndex: reconcile fan keys
SmcKeyIndex-->>SmcUtilFFM: ordered key list
SmcUtilFFM-->>MacSensorsFFM: cached fan keys
MacSensorsFFM->>SMC: read fan values
MacSensorsFFM-->>MacSensorsFFM: convert values to RPM
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #3545 +/- ##
============================================
- Coverage 79.07% 79.04% -0.04%
Complexity 76 76
============================================
Files 702 703 +1
Lines 24238 24265 +27
Branches 4033 4038 +5
============================================
+ Hits 19167 19181 +14
- Misses 2878 2890 +12
- Partials 2193 2194 +1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java`:
- Around line 228-248: Update the fan-limit checks in
MacSensorsPlausibilityFFMTest.testFanSpeedsAreWithinTheHardwareLimits and
MacSensorsPlausibilityTest to derive each F%dMx lookup digit from the
corresponding discovered key in getFanSpeedKeys(), rather than the loop index;
apply the analogous change at
oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java:228-248
and
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java:230-250.
🪄 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 Plus
Run ID: d5637676-6f22-481a-ad03-a8a8d2583c35
📒 Files selected for processing (13)
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-common/src/main/java/oshi/util/GlobalConfig.javaoshi-common/src/main/java/oshi/util/common/platform/mac/SmcKeyIndex.javaoshi-common/src/main/java/oshi/util/common/platform/mac/SmcSensorValues.javaoshi-common/src/main/resources/oshi.propertiesoshi-common/src/test/java/oshi/util/common/platform/mac/SmcKeyIndexTest.javaoshi-common/src/test/java/oshi/util/common/platform/mac/SmcSensorValuesTest.javaoshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.javaoshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.javaoshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.javaoshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java
📜 Review details
⏰ Context from checks skipped due to timeout. (6)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (3)
📚 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/util/GlobalConfig.javaoshi-common/src/main/java/oshi/util/common/platform/mac/SmcSensorValues.javaoshi-common/src/main/java/oshi/util/common/platform/mac/SmcKeyIndex.java
📚 Learning: 2026-07-06T19:25:59.225Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3432
File: oshi-common/src/main/java/oshi/util/ExceptionUtil.java:26-56
Timestamp: 2026-07-06T19:25:59.225Z
Learning: In this repo’s SLF4J 1.x-compatible logging code, do not flag cases where a logger call uses SLF4J 1.6+ implicit-cause handling—e.g., `log.error("...{}", value, t)` (or similar with a single `{}` placeholder) where `t` is passed as the final/trailing argument. SLF4J will attach `t` as the log event’s cause with the full stack trace; this is equivalent to SLF4J 2.x’s fluent `atLevel(...).setCause(t).log(...)` and is intentionally used to preserve SLF4J 1.x runtime compatibility.
Applied to files:
oshi-common/src/main/java/oshi/util/GlobalConfig.javaoshi-common/src/main/java/oshi/util/common/platform/mac/SmcSensorValues.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.javaoshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.javaoshi-common/src/main/java/oshi/util/common/platform/mac/SmcKeyIndex.javaoshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
📚 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/mac/MacSensorsJNA.java
🔇 Additional comments (14)
oshi-common/src/main/java/oshi/util/GlobalConfig.java (1)
166-181: LGTM!oshi-common/src/main/java/oshi/util/common/platform/mac/SmcSensorValues.java (2)
1-68: LGTM!
70-87: 🎯 Functional CorrectnessVerify
fpe2-only scaling covers real Intel VC0C encodings.
scaleVoltagetreats every non-fpe2datatype as already-in-volts. A community SMC dump from an Intel Mac showsVC0Creported with datatypefp2e(2 integer + 14 fractional bits) rather thanfpe2(14 integer + 2 fractional) — a different, non-interchangeable fixed-point encoding.smcGetFloatdoesn't decodefp2eat all, so on such hardware the CPU voltage read would silently fail (return 0d) rather than misreport — a safe but incomplete outcome, consistent with the PR's own note that Intel behavior is untested. Worth confirming VC0C's datatype on a broader/more current set of Intel Macs before relying on this path there.oshi-common/src/test/java/oshi/util/common/platform/mac/SmcSensorValuesTest.java (1)
1-95: LGTM!oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java (1)
54-54: LGTM!Also applies to: 115-129, 142-147, 393-455, 457-511
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java (1)
35-35: LGTM!Also applies to: 100-114, 127-133, 366-405, 407-427, 429-444, 446-460, 462-482
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java (1)
10-23: LGTM!Also applies to: 50-61, 76-76
oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.java (1)
10-17: LGTM!Also applies to: 25-26, 52-63, 78-78
oshi-common/src/main/resources/oshi.properties (1)
312-325: LGTM!oshi-common/src/main/java/oshi/util/common/platform/mac/SmcKeyIndex.java (1)
11-11: LGTM!Also applies to: 48-72, 219-246, 248-281
oshi-common/src/test/java/oshi/util/common/platform/mac/SmcKeyIndexTest.java (1)
197-278: LGTM!oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java (1)
193-227: LGTM!Also applies to: 250-292
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java (1)
195-229: LGTM!Also applies to: 252-293
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)
221-246: LGTM!
Both MacSensorsPlausibility twins built the F%dMx hardware-maximum key from the loop index, which assumes fan numbering is contiguous from F0Ac. Discovery returns keys in index order, so a machine numbering its fans non-contiguously would have been compared against a different fan's maximum. Take the digit from the discovered key itself instead. Test-only; no production behavior change. Reported by CodeRabbit on #3545.
* Share the SMC key resolution between the two backends The sensor work in #3531, #3535, #3536 and #3545 grew SmcUtil and SmcUtilFFM in parallel, and Sonar reported 253 duplicated lines between them. All of it was in key-list management rather than the native calls. Both backends had the same three-step resolution twice over, once for GPU temperature and once for fan speeds: a configuration property naming the keys outright, then discovery from the key index, then a fallback that must not be cached so a later call retries. That is four copies of the same double-checked-locking skeleton, four volatile fields and four S3077 suppressions. It is now one SmcKeyCache in oshi-common, so each backend supplies only the discovery, and three of those suppressions are gone. smcGetFirstTemperature and smcGetFirstVoltage were both first-plausible scans over a key list, differing only in how a reading is obtained: the voltage path needs a second read for the key's data type in order to scale it. Moving the scan to SmcKeyIndex.firstPlausible, symmetric with the maxPlausible already there, leaves each backend with just the read. SmcUtil drops from 596 to 518 lines and SmcUtilFFM from 622 to 545, with no change to the public surface of either. Adding a test to oshi.util.common.platform.mac needed an opens line in module-info.test, which the package had never had. That is why the two existing tests there were public and carried S5786 suppressions claiming JPMS required it. With the package opened that is no longer true, so both are now package-private and both suppressions are removed. * Stop the voltage test attributing a missing key to Intel The assumption skipped with "VP0C unavailable (Intel)", inferring the chip from the key's absence. That inference is wrong: VP0C reads 0.75 V on an M3 Pro but is absent on an M2 Max, so the test skips on Apple Silicon while reporting Intel, which is what hid that getCpuVoltage returns 0 on that machine. The skip itself is right, since there is nothing to assert when the key does not exist. Only the stated reason changes, to name the absent key rather than guess the hardware. A sweep of all 53 V keys on the M2 Max found no identified core voltage, so 0 may well be the correct answer there; that is worth its own investigation rather than a key added on one machine's evidence.
What this changes
PRs #3531, #3535 and #3536 fixed macOS temperature reporting and left behind reusable machinery: a generic key-index scanner (
SmcKeyIndex), a plausibility-guard idiom, and a config-override pattern. The fan and voltage paths inMacSensors*were never revisited and still read single hardcoded keys with no discovery, no plausibility guard, and no test coverage. This applies that machinery to both.Fans — discover the keys instead of synthesizing them from
FNumFan speeds came from
FNumalone: read the count, then formatF%dAcfor each index. That is a latent bug for a count of eleven or more.String.format("F%dAc", 10)produces the five-character"F10Ac", andsmcReadKeypasses the key throughParseUtil.strToLong(key, 4), which reads only the first four bytes. Verified empirically:So a corrupt or spoofed
FNummakes OSHI read a different key and report its value as a fan speed — no exception, no log. Keys are now discovered from the sorted key index (as the GPU keys are) and reconciled againstFNum:FNumnull/emptyMAX_FANS— no regression vs. todaynullnull— can't distinguish "no fans" from "couldn't read", so don't cacheScanned rather than probing
F0Ac…F9Acdirectly becausesmcGetDataTypereturns""for both "absent" and "read failed";findKeys'readFailedtracker already distinguishes those.Voltage — scale by data type, and hold to a floor
Voltage read
VP0C, thenVC0C / 1000if that returned zero, with the divisor tied to the key rather than to its encoding. It is now scaled from the SMC data type and held to a plausibility floor.fpe2is 14 integer + 2 fractional bits, so it resolves to a quarter of a unit. Read as volts, a 1.2 V core rail could only be expressed as 1.00 or 1.25; read as millivolts it resolves to 0.25 mV over 0–16.4 V. Millivolts is the only self-consistent reading, so the existing divisor is kept — now derived from the type, so a key whose encoding differs from the one expected still reads correctly. The floor makes the choice fail safe either way: a wrongly divided reading lands near 0.0012 V and is rejected as unavailable rather than returned as a believable wrong number.Voltage keys are deliberately not discovered — an asymmetry with fans and GPU that I'd rather document than have re-litigated.
Tgis a semantic prefix, where every match is a GPU cluster sensor;Vis not. This M3 Pro's 37V*keys mix a 0.75 V core voltage (VP0C) with a 20.2 V supply rail (VD0R) and a 0.86 VVPsC, under no naming rule that separates them, so a prefix scan could report a rail voltage as the CPU's — worse than reporting nothing. The two named keys stay, andoshi.os.mac.sensors.cpuvoltage.keysis the escape hatch, handing the guess to the user rather than making it in OSHI.testVoltageKeysAreNotDiscoveredasserts the defaults so the pattern isn't "completed" later.A stopped fan reads zero, and must stay zero
iSMC drops readings below 0.005. Applied here that would drop both fans on an idle M3 Pro, where
F0Ac/F1Acread 0.0 whileF0Mn/F0Mxreport 1350/5349 — the fans are present and readable, just not spinning.Sensors#getFanSpeedsdocuments an empty array as "no fans detected" and a zero entry as "a fan reading zero or unmeasurable", so dropping them would turn two stopped fans into no fans. Commented so nobody adds it later.Structure
New logic goes in oshi-common, so both backends share it and it is testable off a Mac:
SmcKeyIndexgainsisFanSpeedKey(^F\dAc$— the fourth char is fixed here, unlike the GPU mask),MAX_FANS,fanSpeedKeys,reconcileFanKeysSmcSensorValuesholdstoRpm, the voltage floor, andscaleVoltageBoth
SmcUtiltwins gaingetFanSpeedKeys/discoverFanSpeedKeys/getCpuVoltageKeys/smcGetFirstVoltage, following the existinggetGpuTemperatureKeysshape exactly (including the "deliberately not aMemoizer" caching, so a transient SMC failure can't disable the sensor for the JVM lifetime).Also removes the per-instance
numFansfield — the key list inSmcUtilis now the single process-wide cache, matchinggpuTemperatureKeys, andqueryFanSpeedsresolves it before opening a connection because discovery opens its own. Re: #3442, which moved memoized suppliers to instance fields: this list is small, bounded and hardware-invariant, the same character asgpuTemperatureKeys.Verification
No CHANGELOG entry: on testable hardware nothing changes. The
FNumtruncation is only reachable through a corrupt or spoofed fan count, and the voltage scaling is unchanged for every data type observed. This is hardening plus missing test coverage, not a user-facing fix.Verified on an M3 Pro (Mac15,7, macOS 26.5.2, JDK 26):
FNum(ui8, viasmcGetLong)F0Ac/F1Ac(flt)F0Mn/F0MxgetFanSpeeds()[0, 0]— unchanged before and afterVP0C(flt)VC0C""), as expected on Apple SiliconSuites: oshi-common 1219, oshi-core 104 (+8), oshi-core-ffm 89 (+8), all 0 failed.
-Pnative-comparison41 including the newfanSpeedKeys(). Spotless + Checkstyle clean.Untested for want of hardware: the Intel
fpe2branch and every non-M3-Pro fan topology. I'd like to file a follow-up asking an Intel Mac owner forVC0C's data type and raw value to confirm the millivolts reasoning empirically.The iSMC corpus does not support a cross-machine key-variation argument here the way it did for temperature: its
internal/reports/*.txt(23 machines) holds 6052 keys, every one starting withT. Its voltage list is Intel-era and lacksVP0Centirely, and its README states Apple Silicon voltage is read over a HID sensor hub rather than SMC — an approach deliberately rejected in #3535. What it does confirm:F%dAcis the right current-speed key, and a fan-count clamp is warranted.Tests
Eight fan cases in
SmcKeyIndexTestincluding bothnull-versus-empty rows ofreconcileFanKeysand a case pinning every synthesized key at four characters (the defect above); a newSmcSensorValuesTest; eight matching cases in eachMacSensorsPlausibilitytwin (identical method names, as the existing ten are); and afanSpeedKeys()comparison inNativeComparisonTest.That last one compares the two backends' discovered key lists, which is sharper than comparing rpm. The fan readings themselves are only compared when both are nonzero — a fan spinning up between the sequential JNA and FFM reads would otherwise fail
assertWithinRatio's one-value-zero branch, which asserts the nonzero value is<= ratio.Deliberately out of scope
smcReadKey/smcGetKeyInfo/smcCallvisibility asymmetry (public inSmcUtil, private inSmcUtilFFM). Narrowing JNA breaksoshi-demo'sSmcDump; widening FFM would putMemorySegment/Arenainto an exported public API for a cosmetic win. Flagging it so the asymmetry reads as deliberate.MIN_PLAUSIBLE_TEMPERATUREinto oshi-common alongside the new voltage floor. It's still duplicated across bothSmcUtiltwins; defining it once is the better shape, but that's a separate change.fpe2behavior, pending the data above.Summary by CodeRabbit