Repository navigation
Read Apple Silicon CPU temp from SMC die-aggregate keys - #3535
Conversation
|
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 (7)
🚧 Files skipped from review as they are similar to previous changes (7)
📜 Recent review details⏰ Context from checks skipped due to timeout. (6)
📝 WalkthroughWalkthroughApple Silicon CPU temperature detection now probes firmware-computed aggregate CPU-die SMC keys before existing per-core keys in both JNA and FFM implementations. New macOS tests cover plausibility and key precedence, and the changelog records the fix. ChangesApple Silicon CPU temperature
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant SystemInfo
participant MacSensors
participant SMC
SystemInfo->>MacSensors: queryCpuTemperature()
MacSensors->>SMC: read TCMb, then TCMz
SMC-->>MacSensors: aggregate CPU-die temperature
MacSensors->>SMC: read per-core keys if aggregate value is non-positive
SMC-->>MacSensors: fallback temperature or unavailable
MacSensors-->>SystemInfo: plausible temperature or unavailable
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 #3535 +/- ##
============================================
- Coverage 78.86% 78.82% -0.04%
- Complexity 76 3836 +3760
============================================
Files 698 698
Lines 24008 24008
Branches 3963 3963
============================================
- Hits 18934 18925 -9
- Misses 2886 2893 +7
- Partials 2188 2190 +2
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
🧹 Nitpick comments (1)
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java (1)
100-105: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftExercise query selection, not just constant ordering.
These assertions pass even if either
queryCpuTemperature()stops using aggregate keys or probes per-core keys first. Add deterministic SMC-read test seams that verifyTCMbwins overTCMzand per-core values, and that unavailable aggregate readings fall back correctly.
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java#L100-L105: test JNA aggregate-first selection and fallback behavior.oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java#L100-L106: add the equivalent FFM behavior test.🤖 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-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java` around lines 100 - 105, The current tests only verify aggregate-key ordering, not query selection. In oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java:100-105, add deterministic SMC-read seams covering queryCpuTemperature() so TCMb is selected before TCMz and per-core values, with unavailable aggregate readings falling back correctly; in oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java:100-106, add the equivalent FFM behavior test. Preserve the existing key-order and distinctness assertions.
🤖 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 `@CHANGELOG.md`:
- Line 8: Update the CHANGELOG entry describing Sensors#getCpuTemperature to
state that the firmware-computed die average key TCMb is preferred when
available, while TCMz or a per-core value may be returned when the average is
unavailable or implausible; do not imply TCMb is always returned.
---
Nitpick comments:
In
`@oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java`:
- Around line 100-105: The current tests only verify aggregate-key ordering, not
query selection. In
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java:100-105,
add deterministic SMC-read seams covering queryCpuTemperature() so TCMb is
selected before TCMz and per-core values, with unavailable aggregate readings
falling back correctly; in
oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java:100-106,
add the equivalent FFM behavior test. Preserve the existing key-order and
distinctness assertions.
🪄 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: e837ec80-1a1c-4461-b70c-2f85de5444da
📒 Files selected for processing (7)
CHANGELOG.mdoshi-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. (3)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Analyze (java)
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
🧰 Additional context used
🧠 Learnings (2)
📚 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-core/src/main/java/oshi/util/platform/mac/SmcUtil.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.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 (6)
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java (1)
65-73: LGTM!oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java (1)
79-86: LGTM!oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.java (1)
7-7: LGTM!Also applies to: 38-43
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java (1)
7-7: LGTM!Also applies to: 36-41
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java (1)
1-92: LGTM!oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java (1)
8-8: LGTM!
OSHI read the macOS CPU temperature from five hardcoded per-core SMC FourCC keys (Tp09, Tp0T, Tp01, Tp05, Tp0D). These are chip-specific and all five are absent on the M3 Pro, so getCpuTemperature() returned 0. Prefer the chip-independent, firmware-computed CPU-die aggregate keys TCMb (die average) then TCMz (die max) before the per-core keys. Both are flt type and decode through the existing smcGetFirstTemperature path, which already applies the 15C plausibility floor from #3531 - no new native binding or private API. TCMb is preferred so the reported value stays close to the historical single-core reading (verified on an M3 Pro: getCpuTemperature() == TCMb, both JNA and FFM backends). Changed in lockstep across the JNA (oshi-core) and FFM (oshi-core-ffm) backends so NativeComparisonTest.sensors() stays green. Adds a JNA twin of the FFM plausibility test and an aggregate-keys-average-first contract test to both.
0de069d to
d487a85
Compare
|
Verified on M2 Max (Mac14,6, macOS 15, JDK 25). Works, and it does more here than fix the M3 case. The aggregate keys stay live exactly where the per-core keys parkThis is the machine where #3529/#3531 was diagnosed, so it has the idle-gating behaviour. At genuine deep idle the per-core keys are parked at their sentinels, but
This also recovers the idle behaviour #3531 had to give up. Before this PR an idle M2 Max reported unavailable, correctly, because every per-core key was parked. Now it reports a real ~41 °C. So the aggregate keys are not merely chip-independent — on this hardware they are immune to the cluster gating that caused the original bug. Both backends agree exactly
One small correction to the descriptionThe rationale says IOHID reads "~20-30 °C lower". On M2 Max, measured at the same moment, it is a smaller gap: So ~6-12 °C here rather than 20-30. The direction is right and the conclusion is unaffected — the SMC path needs no private-API bindings and works on every chip in the dataset — but the magnitude may be M3-specific and might be worth softening to "reads lower" rather than a specific range. LGTM otherwise. |
* Harden the macOS SMC fan speed and CPU voltage paths 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. * Derive the fan max key from the discovered key, not the loop index 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.
Summary
Fixes #3534. OSHI read the macOS CPU temperature from five hardcoded per-core SMC FourCC keys (
Tp09, Tp0T, Tp01, Tp05, Tp0D). These are chip-specific, and all five are absent on the M3 Pro (which exposes a different set:Tp06/Tp0E…,Te0…,Tp3P/Tp3X/Tp3T), soSensors#getCpuTemperature()returned 0.This reads the chip-independent, firmware-computed CPU-die aggregate keys that the SMC already exposes:
TCMb— CPU die average, preferred as primaryTCMz— CPU die max, secondaryBoth are
flttype and decode through the existingsmcGetFirstTemperaturepath, which already applies the 15 °C plausibility floor from #3531 — no new native binding and no private API. This supersedes the IOHID-fallback idea explored in the issue: across every chip in the iSMC hardware dataset (M1→M5, A18, Intel T2) a usable SMC CPU key is always present — even the M3 Pro, which lacks the per-core keys, still exposesTCMb/TCMz— so IOHID would only have defended a case that does not occur, at the cost of undocumented private-API bindings reading a different (die-diode) sensor ~20-30 °C lower.TCMbis preferred so the reported value stays close to the historical single-core reading rather than jumping ~20 °C to the die max.New query order in
queryCpuTemperature(both backends):TCMbthenTCMz(plausibility-guarded)SMC_KEYS_CPU_TEMP_AS) — unchangedTC0P— unchanged, plausibility-guardedScope: CPU temperature only. GPU is deferred to a follow-up — it has no analogous
TGM*die aggregate, andMacGpuStats.getTemperature()already has a key-independent IOAccelerator fallback.Changes
Changed in lockstep across the JNA (
oshi-core) and FFM (oshi-core-ffm) backends soNativeComparisonTest.sensors()stays green:SmcUtil/SmcUtilFFM— addSMC_KEYS_CPU_TEMP_AGGREGATE_AS = [TCMb, TCMz]MacSensorsJNA/MacSensorsFFM— try the aggregate keys before the per-core keysMacSensorsPlausibilityTest(twin of the existing FFM test) + an aggregate-keys-average-first contract test in bothVerification
mvn -pl oshi-core -am clean test— 1127 passedmvn -pl oshi-core-ffm -am clean test— 1127 passedmvn test -pl oshi-benchmark -Pnative-comparison—NativeComparisonTest.sensors()passes (FFM within 25% of JNA)getCpuTemperature()went from 0 → theTCMbvalue on both backends (paired same-JVM read: JNATCMb=72.117 →getCpuTemperature()=72.117; FFMTCMb=73.521 →getCpuTemperature()=73.521), confirming it tracks the die average and notTCMzor 0.Summary by CodeRabbit
Sensors#getCpuTemperatureno longer incorrectly returns0for chips with differing SMC CPU-die keys.