From 44f623d85c0ed58e8e42b00b8c5d80eaf977b30a Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Wed, 25 Nov 2026 03:12:08 -0300 Subject: [PATCH 1/3] GPUSensors 0.9.0: GFX minimum clock in the OD8 state The kext takes a raised GFX minimum (OD8 id 1) with the rest of the OD8 state, through the same 0xa1 call and the same owner rules and way back. It is taken only inside the card's own 0x9f range for id 1 and never above the GFX maximum of the same state (the driver's FMIN <= FMAX rule); anything else is refused as GfxMinRange (12). It keeps the clock up at idle, so it is taken only while the watchdog has fresh readings, and the watchdog's 95 C and missing-readings rules hold it while it is held. Channel version stays 2: setOd8 also takes 14 scalars (the 13 of 0.7.0 still work), status flag 512, held bit 16, and OD8WriteState publishes GfxMinHeld and Takes. gpucontrol gains "gfxmin MHz" for hold and check. The app shows a GFX minimum clock section under the maximum in Settings > GPU control, only when the kext publishes Takes with the minimum, and remembers it with the rest of the OD8 state. The curve rules copy and its fixture cover the new check; the first 100 fixture lines are unchanged. Not added: the memory maximum (its 0x9f minimum is the stock 2000 MHz on the RX 6800 XT, so nothing is lower, and a memory clock change blanks the display) and the fan minimum speed and target temperature (the driver does not offer them while it offers the fan curve). --- CHANGELOG.md | 2 + GPU/CHANGELOG.md | 27 +++ GPU/README.md | 2 +- GPU/sensors/README.md | 20 +- GPU/sensors/VERSION | 2 +- GPU/sensors/kext/control_logic.hpp | 87 +++++-- GPU/sensors/kext/kern_control.cpp | 48 +++- GPU/sensors/kext/kern_control.hpp | 5 +- GPU/sensors/kext/kern_service.cpp | 29 ++- GPU/sensors/tests/controltest.cpp | 188 +++++++++++++-- GPU/sensors/tests/curve_fixturegen.cpp | 50 +++- GPU/sensors/tool/gpucontrol.cpp | 66 +++-- .../RyzenStatus/Core/DefaultsKey+App.swift | 2 + .../Core/GPUControlClockStrings.swift | 129 ++++++++-- .../Core/GPUControlPageStrings.swift | 19 +- .../Services/Metrics/FakeGPUControlKext.swift | 37 ++- .../Services/Metrics/GPUControlChannel.swift | 2 +- .../Metrics/GPUControlController.swift | 15 +- .../Metrics/GPUControlCurveRules.swift | 17 +- .../Services/Metrics/GPUControlPage.swift | 100 +++++++- .../Services/Metrics/GPUControlService.swift | 15 +- .../Services/Metrics/GPUControlWire.swift | 55 ++++- .../Metrics/GPUControlWriteProperties.swift | 23 +- .../Settings/GPUControlClockMinSection.swift | 226 ++++++++++++++++++ .../UI/Settings/GPUControlClockSection.swift | 2 + .../UI/Settings/GPUControlSettingsView.swift | 7 + Tests/Fixtures/GPUSensors/curve-cases.jsonl | 20 ++ Tests/Suites/GPUControlChannelTests.swift | 24 +- Tests/Suites/GPUControlClockTests.swift | 151 +++++++++++- Tests/Suites/GPUControlFanTests.swift | 13 +- Tests/Suites/GPUControlPageTests.swift | 2 +- 31 files changed, 1236 insertions(+), 149 deletions(-) create mode 100644 Sources/RyzenStatus/UI/Settings/GPUControlClockMinSection.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f8cb830..c0635d8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ **GPU power limit, from the optional GPUSensors.kext**: when the kext is loaded and an administrator has allowed GPU changes, Settings › GPU control and the panel can lower the RX 6800 XT's power limit in 10 W steps down to the card's own minimum (225 W on a card that starts at 240 W). The kext checks every request and goes back to the start-up limit on its own when RyzenStatus quits, stops answering or the Mac sleeps; a switch on the page asks for the same limit again after launch and wake, only while changes are allowed and never with a password. Another switch, Allow changes after restart too, asks for an administrator password once and then allows GPU changes again at every startup, so the remembered limit comes back after a restart too; turning it off asks again and removes that step. With GPUSensors.kext 0.8.0, Close Changes closes them again without a password, and on an RX 6900 XT the page shows the readings only. GPUSensors.kext is not public yet; without it, nothing changes. +**GPU minimum clock, from GPUSensors.kext 0.9.0**: Settings › GPU control has a GFX minimum clock under the maximum. It only raises the minimum, from the card's stock value up to the GFX maximum in force, and keeps the clock up at idle, so the card draws more power and runs warmer; the kext checks every request, watches the temperature while it is held, and goes back to stock in the same cases as the other GPU changes. The section shows only with GPUSensors.kext 0.9.0. The memory clock, fan minimum speed and fan target temperature stay out: on the RX 6800 XT the driver offers no lower memory clock and no fan minimum or target while it offers the fan curve. Tested with unit tests only. + **AWDL / AirDrop activity in the Network card**: with a Wi-Fi driver that publishes AWDL activity in the I/O Registry (`RTLAwdlPeers` and `RTLAwdlChannel` on the `awdl0` interface, and optionally the `RTLLed` status LED mode), the panel's Network card shows a line with the number of peers exchanging data over AWDL (AirDrop, Sidecar, Continuity) and its current channel. Settings › Monitor › Alerts adds an optional notification when AWDL goes from no peers to some; it is off by default and fires at most once a minute. The line can be hidden like the card's other blocks. With other Wi-Fi hardware nothing changes and nothing extra is read. ## [1.89.0] — 2026-11-23 — kexts 3.42.0 (No kext changes) diff --git a/GPU/CHANGELOG.md b/GPU/CHANGELOG.md index 24a1cfcd..98894a88 100644 --- a/GPU/CHANGELOG.md +++ b/GPU/CHANGELOG.md @@ -2,6 +2,33 @@ The encoding fix keeps its own history in `encode/CHANGELOG.md`. +## GPU sensors 0.9.0 (host tests only, not booted) + +- A program may now hold a raised GFX minimum clock (OD8 id 1) with the rest of the OD8 + state: `gpucontrol hold gfxmin 1500 -- `, `gpucontrol check gfxmin 1500`. It is + taken only inside the card's own range for it (the 0x9f entry: 500 to 2800 MHz on the test + RX 6800 XT, stock 500) and never above the GFX maximum of the same state (the stock one, or + the lowered one held with it): the driver's own rule (`PhwComm_OD8_SetGfxClockLimits`: both + requested, each in its range, minimum at most the maximum). Anything else is refused with + the new reason `GfxMinRange` (12), never clamped. It goes back to stock in the same cases + as the rest of OD8 (release, close, 30 s of silence, a wake), through the same stock pair. +- It is the first setting that can make the card warmer at idle, so it is taken only while + the fan watchdog has fresh readings, and the watchdog runs while it is held: 95 C, or no + readings for 10 s, puts stock back and turns writing off. The "too hot with the fan under + 90 %" rule stays with a held curve, because the stock fan climbs slowly by design. +- The read-back allows the minimum to read up to 25 MHz lower than sent, never higher, as + for the maximum. Whether the firmware ever rounds it is not known yet. +- The channel stays version 2: `setOd8` takes 14 scalars (the 14th is the minimum) as well as + the 0.7.0 form of 13, `status` sets flag 512 (`kFlagGfxMin`), `OD8WriteState` gains `Held` + bit 16, `GfxMinHeld` and `Takes` (23: what `setOd8` takes). An older kext refuses the + 14-scalar form with a wrong-count error; `gpucontrol` and the app send it only with a + minimum. +- Not added, and why (read on this card and in the 25G342 driver, 2026-11-25): the memory + maximum (id 8), whose 0x9f minimum is its stock value (2000 MHz here), so there is nothing + lower to take, and whose change blanks the display; the fan minimum speed (id 10) and fan + target temperature (id 12), which the driver does not offer while the fan curve is offered + (feature 0, and `PhwComm_OD8_SetGenericSetting` skips a setting whose feature is 0). + ## Decoders 0.3.5 (RyzenStatus 1.89.0) - The `stats` line's slow-frame count now uses the stream's own frame time. It used to count diff --git a/GPU/README.md b/GPU/README.md index 11d1d3b9..51becfeb 100644 --- a/GPU/README.md +++ b/GPU/README.md @@ -37,7 +37,7 @@ Inc. | Loader kext (`decode/loader/`) | 1.1.0 | RX 6800 XT (Tahoe 26.7.3) with AMFIPass off; not run on Sequoia | | Encoding fix kext (`encode/kext/`) | 1.3.0 (code as 1.2.6) | RX 6800 XT (Tahoe 26.7.3); 1.2.1 reported on RX 6900 XT (Sequoia 15.8.3); Navi 23 static only | | Encoding fix service (`encode/tool/`) | 1.3.0 | RX 6800 XT (Tahoe 26.7.3; FaceTime encoder part in a test process); 1.2.1 reported on RX 6900 XT (Sequoia 15.8.3); cc decoder part run with an iPhone camera on RX 6900 XT (15.8.2) | -| GPU sensors kext (`sensors/`) | 0.8.1 | 0.8.0 on RX 6800 XT (Tahoe 26.7.3) | +| GPU sensors kext (`sensors/`) | 0.9.0 | 0.8.0 on RX 6800 XT (Tahoe 26.7.3) | Full test results, dates and what has never been tried are in [docs/status.md](docs/status.md). diff --git a/GPU/sensors/README.md b/GPU/sensors/README.md index 8f1725d3..585edb8d 100644 --- a/GPU/sensors/README.md +++ b/GPU/sensors/README.md @@ -97,7 +97,7 @@ The properties of `DrogaBoxGPUSensors` are: | `OD8State` | OD8, read only (0.6.0): `read`, `read, but an entry is not as expected`, `not available: ...`, `no data: ...`, `not read: ...`, `stopped: ...`, `waiting ...` or `off: ...` | | `OD8` | once tried: `Reads`, `Tries`, `LastResult`, `LastReadAgeS`, `Caps`, `NotAllowed`, `StockOdd`, `DefaultsMoved`, `CurrentMoved`, `FanCurveStock`, `FanCurve` (five [C, %] pairs) and `Settings` by name (`Feature`, `Min`, `Max`, `Stock`, `Current`); `OddEntry` and `OddEscape` when an answer was not as expected. See [OD8, read only](#od8-read-only-060) | | `OD8Write` | OD8 writes (0.7.0): `off until restart: see WriteState`, `read only: this card can only be read (see WriteState)` (0.8.0), `waiting for a clean OD8 read (OD8State)`, `closed: sudo gpucontrol arm opens it until restart`, or `armed: ...` (OD8 at stock, a program holds a fan or clock change, going back to stock, the last call was not taken) | -| `OD8WriteState` | `Held` (1 fan curve, 2 zero RPM off, 4 GFX max, 8 not confirmed), `Changes` and `Reverts` (confirmed since boot), `LastCheck` and `LastCheckText` (why the last OD8 request was refused, 0 = none), `SentPower` (power limit sends seen during OD8 calls), `FanCurveHeld` (C × 1000 + %) and `GfxMaxHeld` while held. See [OD8 writes](#od8-writes-070) | +| `OD8WriteState` | `Held` (1 fan curve, 2 zero RPM off, 4 GFX max, 8 not confirmed, 16 GFX min since 0.9.0), `Changes` and `Reverts` (confirmed since boot), `LastCheck` and `LastCheckText` (why the last OD8 request was refused, 0 = none), `SentPower` (power limit sends seen during OD8 calls), `FanCurveHeld` (C × 1000 + %), `GfxMaxHeld` and `GfxMinHeld` (0.9.0) while held, `Takes` (0.9.0: what `setOd8` takes, in `Held` bits, 23). See [OD8 writes](#od8-writes-070) | | `Samples` | readings copied since boot | | `SampleAgeMs` | how old the last reading is; with `Sensors`, `Units` and `PMLog` it is absent once the copy is older than 5 s (the driver stopped sampling: the card is asleep, powered down, or its driver is gone) | | `Sensors` | `{ name: value }`, in the units of `Units` | @@ -242,7 +242,8 @@ itself is killed, the kext sees the connection close and goes back on its own. The channel is an IOUserClient on `DrogaBoxGPUSensors` (type 0), with scalars only: `status`, `arm`, `set(watts)`, `alive`, `release`, since 0.7.0 `setOd8`, and since 0.8.0 `disarm` (selector 6, `{version}` in, one reply out, any caller) (version 2; -0.5.0 and 0.6.0 were version 1; 0.8.0 only adds, so it stays 2). Every call passes the +0.5.0 and 0.6.0 were version 1; 0.8.0 only adds, so it stays 2; so does 0.9.0, whose +`setOd8` also takes a 14th scalar, the GFX minimum, and still takes the 13 of 0.7.0). Every call passes the version first; another version is refused. 0.8.0 adds two answers: 19 "a change is still applied or being handled" (disarm) and 20 "the card's minimum power limit is not known" (set, only below the start-up value: above it is "above the start-up limit" either way). `set` and @@ -313,9 +314,17 @@ else: refused: it reaches 100 % only at 70 C. - Zero RPM off (the fan spins at idle). - A lower GFX maximum, from 1500 MHz up to the stock one. - -Memory clock, voltage and power percent are never written; the GFX minimum is only sent -at its stock value. A request +- A raised GFX minimum (0.9.0), inside the card's own range for it (500 to 2800 MHz on the + test card, stock 500) and never above the GFX maximum of the same state. It keeps the clock + up at idle, so it is the one setting that can make the card warmer: it is taken only while + the watchdog below has a fresh PMLog copy, and the watchdog's 95 C limit and its missing + readings rule hold it as they hold a curve (not the 75 C rule, which needs a curve: the + stock fan climbs slowly by design). `gpucontrol hold gfxmin 1500 -- `. + +Memory clock, voltage and power percent are never written. The memory maximum cannot be +lowered on this card anyway: its 0x9f minimum is the stock value (2000 MHz), and a memory +clock change blanks the display. The fan minimum speed and target temperature are not +offered by the driver while it offers the curve (feature 0; the driver skips them). A request that fails a check is refused with the reason, never clamped; `gpucontrol check` runs the same checks on the published OD8 and says what would be taken. OD8 and the power limit are never held together. @@ -380,6 +389,7 @@ it. The kext does not route it. | Power limit and OD8 at once (0.7.1) | With 230 W held, an OD8 change was refused ("busy") and the 230 W stayed; with zero RPM off held, a power limit was refused. Curve + zero RPM off + GFX max 2300 in one call: all three read back, all three taken back | | OD8 across a sleep (0.7.1) | Zero RPM off, and then the curve, held while the Mac slept. The curve was still on the card right after the wake (fan 1950 RPM); 2 s later the kext had put stock back by itself (1329, then 1201 RPM), `gpucontrol hold` asked again and the curve came back; stock again at the end. The GPU log lines at sleep are the same as with nothing held | | A long load at stock (2026-11-19) | gpubench --sustain 300 at the 240 W start-up limit, stock fan, read only: 232.5 W, no compute errors; hotspot 85 C after 80 s, 88 C after 2 minutes, 90-91 C after 5 and still rising about 0.7 C a minute; edge 62 C at most; stock fan 96-100 %. 220 of the 300 s at 85 C or more, which is why the watchdog's limit went from 85 to 95 C in 0.7.2 | +| The 0.9.0 decisions | `controltest`, 371 checks on the CPU (was 336): the GFX minimum against the card's real 0x9f (500 to 2800, never above the stock or the lowered maximum, the range from the entry, not a constant), the call it builds (the pair with the minimum, memory and fan entries untouched), the shapes never sent (minimum above the maximum, the pair split, a minimum of 0), its read-back (up to 25 MHz lower, never higher), the 14- and 13-scalar wire forms and every other count, the watchdog without a curve (only 95 C and no readings count). `curve-cases.jsonl` grew by 20 GFX minimum cases, the first 100 unchanged. Four mutations of the new rules each failed the tests. Not booted | | The 0.8.0 decisions | `controltest`, 336 checks on the CPU (was 277): the floor from the card's real 0x9f (225 W at 240 W, 248 W at 264 W, Linux's integer division), no floor and every change refused when OD8 is not read, odd or its power entry is not as expected; disarm taken from any caller, administrator or not, refused while a change, its way back or an unconfirmed state is there, and closed afterwards (arm still needs an administrator); a read-only card readable, never armable or changeable, its worker started; `set` and `setOd8` answering "off" / "not armed" before any value, absurd ones included; the GFX clock refused by the card's stock maximum, not the wire; the scan's decision for one read-only card and for a mixed machine; which reason `WriteOff` keeps; a request counted as being handled only while waiting or running. Each new check was broken on purpose once and failed. Not booted | | The floor's source on this Mac (0.8.0) | `PP_PhmSoftPowerPlayTable` in ioreg, read 2026-11-20: overdrive table revision 0x81, power limit cap set, `POWERPERCENTAGE` max 9 min 6, `SocketPowerLimitAc[0]` 240; the kext's 0x9f gives -6 to 9 and the start-up read 240 W. Linux's formula read in `sienna_cichlid_ppt.c` (master, and v6.6, which had no minimum) | | The stock GFX maximum across wakes | The driver's default moves between 2354 and 2359 MHz at a wake, in both directions (seen three times); the way back sends the lower of the first read and the fresh one | diff --git a/GPU/sensors/VERSION b/GPU/sensors/VERSION index 6f4eebdf..ac39a106 100644 --- a/GPU/sensors/VERSION +++ b/GPU/sensors/VERSION @@ -1 +1 @@ -0.8.1 +0.9.0 diff --git a/GPU/sensors/kext/control_logic.hpp b/GPU/sensors/kext/control_logic.hpp index 252b2f55..74c392c9 100644 --- a/GPU/sensors/kext/control_logic.hpp +++ b/GPU/sensors/kext/control_logic.hpp @@ -681,8 +681,19 @@ inline const char* floorStateText(FloorState s) { // design-od8-b.md v3 + v3.1. Three settings, each only in the direction that // cannot make the card hotter: the fan curve (more air than stock, all ten // entries in every call), zero RPM (off only: the fan always spins), and the -// GFX maximum clock (lower only, not below 1500 MHz). Everything else goes out -// with requested 0. +// GFX maximum clock (lower only, not below 1500 MHz). 0.9.0 adds a fourth, the +// GFX minimum clock, the one setting that may go up: inside the card's own +// 0x9f range for id 1 and never above the GFX maximum of the same call (the +// driver's own rule, PhwComm_OD8_SetGfxClockLimits: both requested, each in +// its range, FMIN <= FMAX). A raised minimum keeps the GPU clock up at idle, +// so it is only taken while the watchdog has readings and the watchdog's +// 95 C limit holds it (od8DogPass). Everything else goes out with requested +// 0. Not taken, and why (2026-11-25, 25G342): the memory maximum (id 8; its +// 0x9f minimum is the stock value, 2000 MHz on the test card, so nothing is +// lower, and a memory clock change blanks the display), the fan minimum +// speed and target temperature (ids 10 and 12; the driver does not offer +// them while the fan curve is offered: feature 0, and SetGenericSetting +// skips a setting whose feature is 0). // 0xa1 OD8_SetSettings: in = header {16, 0x00C000A1, 1 = not kept for // replay, 0} + count 38 + 38 x {value, requested, reset, 0, 0} + 8 // unused (788); out = a 0xa0 answer (164), out[0] must equal 38. @@ -726,9 +737,10 @@ struct Od8Want { int32_t temp[kOd8CurvePoints], speed[kOd8CurvePoints]; bool zeroRpmOff; int32_t gfxMaxMHz; // 0 = stock + int32_t gfxMinMHz; // 0 = stock (0.9.0) }; inline bool od8IsStock(const Od8Want& w) { - return !w.curve && !w.zeroRpmOff && w.gfxMaxMHz == 0; + return !w.curve && !w.zeroRpmOff && w.gfxMaxMHz == 0 && w.gfxMinMHz == 0; } enum class Od8Check : uint32_t { @@ -743,7 +755,10 @@ enum class Od8Check : uint32_t { CurveLast, // the last point not 100 %, or above the target - the gap CurveCooling, // less air than the stock curve somewhere below the target GfxRange, // GFX max above stock, below 1500, or below the GFX min - NoReadings, // a curve, but the fan watchdog has no fresh readings + NoReadings, // a curve or a raised GFX min, but the watchdog has no + // fresh readings + GfxMinRange, // 0.9.0: GFX min outside the card's range for it, or above + // the GFX max of the same state }; inline const char* od8CheckText(uint64_t c) { switch (static_cast(c)) { @@ -772,6 +787,8 @@ inline const char* od8CheckText(uint64_t c) { return "GFX max must be between 1500 MHz and the stock maximum"; case Od8Check::NoReadings: return "the fan watchdog has no fresh hotspot and fan readings"; + case Od8Check::GfxMinRange: + return "GFX min must be in the card's range and not above GFX max"; } return "unknown"; } @@ -882,6 +899,13 @@ inline Od8Check od8CheckWant(const Od8Want& w, const Od8InitialOut& first, w.gfxMaxMHz < first.e[kOd8GfxMin].def) return Od8Check::GfxRange; } + if (w.gfxMinMHz != 0) { + // The range of id 1 is the same in both reads (od8SameLayout above). + const Od8Entry& m = fresh.e[kOd8GfxMin]; + int32_t max = w.gfxMaxMHz != 0 ? w.gfxMaxMHz : od8StockGfxMax(first, fresh); + if (w.gfxMinMHz < m.min || w.gfxMinMHz > m.max || w.gfxMinMHz > max) + return Od8Check::GfxMinRange; + } return Od8Check::Ok; } @@ -912,7 +936,8 @@ inline void od8Build(const Od8Want& w, const Od8InitialOut& first, Od8SetEntry{fresh.e[kOd8ZeroRpmStop].def, 1, 0, 0, 0}; int32_t gfx = w.gfxMaxMHz != 0 ? w.gfxMaxMHz : od8StockGfxMax(first, fresh); out->e[kOd8GfxMax] = Od8SetEntry{gfx, 1, 0, 0, 0}; - out->e[kOd8GfxMin] = Od8SetEntry{first.e[kOd8GfxMin].def, 1, 0, 0, 0}; + int32_t low = w.gfxMinMHz != 0 ? w.gfxMinMHz : first.e[kOd8GfxMin].def; + out->e[kOd8GfxMin] = Od8SetEntry{low, 1, 0, 0, 0}; } // Every call's shape, checked again where it is sent: count 38, all ten curve // entries requested 1 (never 1..9 of them), nothing outside the five @@ -937,13 +962,22 @@ inline bool od8ShapeOk(const Od8SetIn& in) { if (i == kOd8GfxMax && e.requested == 1 && e.value < kOd8GfxFloorMHz) return false; } + // The GFX pair always together, the minimum never above the maximum + // (the driver refuses the pair otherwise, and then keeps neither). + const Od8SetEntry& hi = in.e[kOd8GfxMax]; + const Od8SetEntry& lo = in.e[kOd8GfxMin]; + if (hi.requested != lo.requested || + (lo.requested == 1 && (lo.value <= 0 || lo.value > hi.value))) + return false; return curve == 10 && in.unused[0] == 0 && in.unused[1] == 0; } // The read-back after a call (design section 5): 0 = as sent, else the first // entry that is not + 1 (39 = the allowed mask moved). Requested entries -// must read what was sent (GFX max may read lower, by up to the allowance: -// the firmware rounds; never higher); the others what they read before. +// must read what was sent (GFX max and, since 0.9.0, GFX min may read lower, +// by up to the allowance: the firmware rounds; never higher); the others what +// they read before. Whether the firmware ever rounds the minimum is not known +// (not seen on a card yet): reading higher than sent fails as for the max. inline uint32_t od8VerifyAfter(const Od8SetIn& sent, const Od8CurrentOut& before, const Od8CurrentOut& after) { @@ -951,7 +985,8 @@ inline uint32_t od8VerifyAfter(const Od8SetIn& sent, int32_t a = after.cur[i]; if (sent.e[i].requested == 1) { int32_t v = sent.e[i].value; - bool ok = i == kOd8GfxMax ? (a <= v && a >= v - kOd8DriftMHz) : a == v; + bool gfx = i == kOd8GfxMax || i == kOd8GfxMin; + bool ok = gfx ? (a <= v && a >= v - kOd8DriftMHz) : a == v; if (!ok) return i + 1; } else if (a != before.cur[i]) { return i + 1; @@ -1336,15 +1371,21 @@ class Owner { // alive in {version} the owner's word, every 5 s // release in {version} the owner goes back to the start-up limit // setOd8 in {version, flags, t1..t5, s1..s5, gfxMaxMHz} (13 scalars) +// or, since 0.9.0, {..., gfxMaxMHz, gfxMinMHz} (14) // out {reply, Od8Check}; flags 1 = a fan curve, 2 = zero RPM off; -// gfxMaxMHz 0 = stock (0.7.0). The stock state is the way back. +// gfxMaxMHz 0 = stock (0.7.0); gfxMinMHz 0 = stock, and the 13 +// scalar form means a stock minimum. The stock state is the way +// back. // disarm in {version} anyone (0.8.0): closes writing again; // StillApplied while anything is applied; arm reopens it // Version 2 (0.7.0): setOd8, and status grew. A power change and an OD8 // change are never held together: the other kind answers "busy". 0.8.0 adds // disarm and two replies at the end and keeps version 2: nothing an older // program sends means anything else now. An older kext answers disarm with -// kIOReturnBadArgument (an unknown selector). +// kIOReturnBadArgument (an unknown selector). 0.9.0 adds the 14-scalar +// setOd8, one Od8Check (GfxMinRange), one held bit and one status flag +// (kFlagGfxMin) and keeps version 2 the same way; an older kext answers the +// 14-scalar setOd8 with kIOReturnBadArgument (a wrong count). // set and setOd8 answer Off (writing off, or a read-only card) and then // NotArmed (never armed since restart, or disarmed) before they look at any // value they carry (valueGate), so an absurd value still gets the real @@ -1501,12 +1542,14 @@ enum : uint64_t { kFlagMine = 64, // the program asking does kFlagReady = 128, // the PowerPlay object and the start-up limit are known kFlagOd8Ready = 256, // OD8 was read cleanly since boot: setOd8 can work + kFlagGfxMin = 512, // 0.9.0: setOd8 takes a GFX minimum (14 scalars) }; enum : uint64_t { kOd8HeldCurve = 1, kOd8HeldZeroRpmOff = 2, kOd8HeldGfx = 4, kOd8HeldUnknown = 8, // not confirmed stock (a failed or unapplied call) + kOd8HeldGfxMin = 16, // 0.9.0: a raised GFX minimum }; // setOd8's flags scalar. enum : uint64_t { @@ -1554,22 +1597,32 @@ inline Reply setWire(const Owner& o, uint64_t watts, uint32_t* out) { *out = static_cast(watts); return Reply::Ok; } -// setOd8's {version, flags, t1..t5, s1..s5, gfxMaxMHz}: the gate, then -// anything that cannot be a fan point or a clock is malformed (BadArgs). -// The clock's only wire bound is the 32-bit field (0.8.0, was 5000 MHz): its -// first real check is od8CheckWant's, against the card's stock maximum. -constexpr uint32_t kOd8WireCount = 13; +// setOd8's {version, flags, t1..t5, s1..s5, gfxMaxMHz[, gfxMinMHz]}: the +// gate, then anything that cannot be a fan point or a clock is malformed +// (BadArgs). The clocks' only wire bound is the 32-bit field (0.8.0, was 5000 +// MHz): their first real check is od8CheckWant's, against the card's range. +// count is how many scalars came: kOd8WireCount (0.9.0) or the 0.7.0 form, +// kOd8WireCountV070, whose GFX minimum is the stock one. +constexpr uint32_t kOd8WireCount = 14; +constexpr uint32_t kOd8WireCountV070 = 13; constexpr uint64_t kOd8WireMaxPoint = 200; -inline Reply od8Wire(const Owner& o, const uint64_t* in, Od8Want* want) { +inline bool od8WireCountOk(uint32_t count) { + return count == kOd8WireCount || count == kOd8WireCountV070; +} +inline Reply od8Wire(const Owner& o, const uint64_t* in, uint32_t count, + Od8Want* want) { Reply g = valueGate(o); if (g != Reply::Ok) return g; *want = Od8Want{}; + if (!od8WireCountOk(count)) return Reply::BadArgs; uint64_t flags = in[1]; + uint64_t low = count == kOd8WireCount ? in[13] : 0; bool ok = (flags & ~uint64_t(kOd8WantCurve | kOd8WantZeroRpmOff)) == 0 && - in[12] <= 0x7fffffffULL; + in[12] <= 0x7fffffffULL && low <= 0x7fffffffULL; want->curve = (flags & kOd8WantCurve) != 0; want->zeroRpmOff = (flags & kOd8WantZeroRpmOff) != 0; want->gfxMaxMHz = static_cast(in[12] <= 0x7fffffffULL ? in[12] : 0); + want->gfxMinMHz = static_cast(low <= 0x7fffffffULL ? low : 0); for (uint32_t k = 0; k < kOd8CurvePoints; k++) { uint64_t t = in[2 + k], v = in[7 + k]; if (t > kOd8WireMaxPoint || v > kOd8WireMaxPoint || diff --git a/GPU/sensors/kext/kern_control.cpp b/GPU/sensors/kext/kern_control.cpp index a97e9be9..f2904d1e 100644 --- a/GPU/sensors/kext/kern_control.cpp +++ b/GPU/sensors/kext/kern_control.cpp @@ -92,6 +92,17 @@ // and 0xa0 (0x2a and 0x6e are sent only by runSet and runRevert, 0xa1 only // by od8Commit, and none of them can run; each sender checks again). // +// 8. 0.9.0. A raised GFX minimum clock (OD8 id 1) joins the OD8 state: in +// the card's own range for it and never above the GFX maximum of the +// same state (the driver's FMIN <= FMAX rule), through the same setOd8 +// (14 scalars; the 13-scalar form still works and keeps the stock +// minimum), the same owner rules and the same way back (the stock pair). +// It is the first setting that can make the card warmer at idle, so it +// is taken only while the watchdog has fresh readings, and the watchdog +// runs while it is held: 95 C or no readings for 10 s puts stock back +// and turns writing off. The "too hot with the fan under 90 %" rule +// stays with the curve: the stock fan climbs slowly by design. +// // Only on an RX 6800 XT (73BF revision C1) or, read only, an RX 6900 XT (C0), // and only when each function starts with the bytes in control_logic.hpp. // Writing needs more: an RX 6800 XT, exactly one AMD GPU, @@ -1098,7 +1109,8 @@ Od8Result od8Commit(bool* sentPower, uint32_t* retOut) { uint64_t od8HeldFlags(const gpuctl::Od8Want& w) { return (w.curve ? gpuctl::kOd8HeldCurve : 0) | (w.zeroRpmOff ? gpuctl::kOd8HeldZeroRpmOff : 0) | - (w.gfxMaxMHz != 0 ? gpuctl::kOd8HeldGfx : 0); + (w.gfxMaxMHz != 0 ? gpuctl::kOd8HeldGfx : 0) | + (w.gfxMinMHz != 0 ? gpuctl::kOd8HeldGfxMin : 0); } // The fixed way back once (design v3.1 B). Confirmed: stock again. @@ -1171,8 +1183,10 @@ void runSetOd8(uint64_t t, uint64_t client, const gpuctl::Od8Want& want) { IOLockUnlock(gStateLock); gpuctl::Od8Check check = gpuctl::Od8Check::Ok; Od8Result p = Od8Result::Confirmed; - if (reply == gpuctl::Reply::Ok && want.curve && !od8DogSees()) { - check = gpuctl::Od8Check::NoReadings; // never a curve it cannot watch + if (reply == gpuctl::Reply::Ok && (want.curve || want.gfxMinMHz != 0) && + !od8DogSees()) { + // never a curve or a raised GFX minimum it cannot watch + check = gpuctl::Od8Check::NoReadings; p = Od8Result::Refused; reply = gpuctl::Reply::Od8Refused; } @@ -1248,8 +1262,9 @@ void runSetOd8(uint64_t t, uint64_t client, const gpuctl::Od8Want& want) { IOLockWakeup(gStateLock, &gSlot, false); IOLockUnlock(gStateLock); if (c == Od8Result::Confirmed) - SYSLOG("gpuctl", "OD8 change held: curve %d, zero RPM off %d, GFX max %d", - want.curve, want.zeroRpmOff, want.gfxMaxMHz); + SYSLOG("gpuctl", + "OD8 change held: curve %d, zero RPM off %d, GFX max %d, GFX min %d", + want.curve, want.zeroRpmOff, want.gfxMaxMHz, want.gfxMinMHz); if (c == Od8Result::Failed) SYSLOG("gpuctl", "OD8 change FAILED (ppCWDDE 0x%x, read-back %u), way back %s: " @@ -1258,14 +1273,18 @@ void runSetOd8(uint64_t t, uint64_t client, const gpuctl::Od8Want& want) { back == Od8Result::Confirmed ? "ok" : "NOT confirmed"); } -// The fan watchdog (design v3.1 F), once a second while a curve is held. +// The fan watchdog (design v3.1 F), once a second while a curve or (0.9.0) +// a raised GFX minimum is held. Without a curve the stock fan runs, which +// climbs slowly by design (75 % at 76 C, 2026-11-19), so only the 95 C limit +// and the missing readings count then: the target temperature goes in as 0. uint64_t od8DogPass() { IOLockLock(gStateLock); - bool curve = - (gOd8Held & (gpuctl::kOd8HeldCurve | gpuctl::kOd8HeldUnknown)) != 0 && - gOd8Dirty && !gTornDown && !gOwner.isOff() && !gReadOnlyCard; + bool live = gOd8Dirty && !gTornDown && !gOwner.isOff() && !gReadOnlyCard; + bool curve = live && (gOd8Held & + (gpuctl::kOd8HeldCurve | gpuctl::kOd8HeldUnknown)) != 0; + bool low = live && (gOd8Held & gpuctl::kOd8HeldGfxMin) != 0; IOLockUnlock(gStateLock); - if (!curve) return 0; + if (!curve && !low) return 0; uint64_t now = nowMs(); if (now < wDogNextMs) return wDogNextMs; wDogNextMs = now + 1000; @@ -1274,7 +1293,7 @@ uint64_t od8DogPass() { uint32_t hot = 0, fan = 0; have = have && gpusens::entry(wDogLog, 27, &hot) && gpusens::entry(wDogLog, 15, &fan); - int32_t target = wOd8First.e[gpuctl::kOd8TargetTemp].def; + int32_t target = curve ? wOd8First.e[gpuctl::kOd8TargetTemp].def : 0; gpuctl::Od8Dog d = gpuctl::od8Watchdog(&wDog, have, ageNs / 1000000, hot, fan, target, now); if (d == gpuctl::Od8Dog::Fine) return wDogNextMs; @@ -1771,6 +1790,7 @@ void GPUControl::status(uint64_t client, uint64_t out[gpuctl::kStatusCount]) { IOLockLock(gStateLock); uint64_t f = 0; if (od8ok) f |= gpuctl::kFlagOd8Ready; + f |= gpuctl::kFlagGfxMin; // 0.9.0: setOd8 takes a GFX minimum if (gOwner.isArmed()) f |= gpuctl::kFlagArmed; if (gOwner.isOff()) f |= gpuctl::kFlagOff; if (sleepingLocked()) f |= gpuctl::kFlagSleeping; @@ -2166,7 +2186,8 @@ OSDictionary* GPUControl::od8Dictionary() { // ---------------------------------------------------- OD8 writes, channel ---- gpuctl::Reply GPUControl::setOd8(uint64_t client, const uint64_t* in, - const uint32_t* closedFlag, uint32_t* check) { + uint32_t count, const uint32_t* closedFlag, + uint32_t* check) { *check = 0; gpuctl::Od8Want want{}; if (gStateLock == nullptr) return gpuctl::Reply::Off; @@ -2190,7 +2211,8 @@ gpuctl::Reply GPUControl::setOd8(uint64_t client, const uint64_t* in, r = gpuctl::Reply::BadArgs; } else if (gReadOnlyCard) { r = gpuctl::Reply::Off; - } else if ((r = gpuctl::od8Wire(gOwner, in, &want)) != gpuctl::Reply::Ok) { + } else if ((r = gpuctl::od8Wire(gOwner, in, count, &want)) != + gpuctl::Reply::Ok) { // off or not armed, before any value; then a malformed state } else if (gpuctl::od8IsStock(want)) { // The stock state is the way back, never a change. diff --git a/GPU/sensors/kext/kern_control.hpp b/GPU/sensors/kext/kern_control.hpp index d59dd9e1..6c67abb1 100644 --- a/GPU/sensors/kext/kern_control.hpp +++ b/GPU/sensors/kext/kern_control.hpp @@ -82,8 +82,9 @@ OSDictionary* od8Dictionary(); // OD8 writes (0.7.0, design-od8-b.md v3.1), for the user client. setOd8 waits // like set(); *check is the Od8Check when the reply is Od8Refused. in is the -// wire's kOd8WireCount scalars as sent, version first (gpuctl::od8Wire). -gpuctl::Reply setOd8(uint64_t client, const uint64_t* in, +// wire's scalars as sent, version first, count of them (kOd8WireCount or the +// 0.7.0 form kOd8WireCountV070; gpuctl::od8Wire). +gpuctl::Reply setOd8(uint64_t client, const uint64_t* in, uint32_t count, const uint32_t* closedFlag, uint32_t* check); const char* od8WriteText(); struct Od8WriteState { diff --git a/GPU/sensors/kext/kern_service.cpp b/GPU/sensors/kext/kern_service.cpp index 7a86bf59..0a777ab9 100644 --- a/GPU/sensors/kext/kern_service.cpp +++ b/GPU/sensors/kext/kern_service.cpp @@ -205,7 +205,7 @@ void DrogaBoxGPUSensors::publish() { setProperty("OD8Write", GPUControl::od8WriteText()); GPUControl::Od8WriteState ow; if (GPUControl::od8WriteState(&ow)) { - auto d = OSDictionary::withCapacity(10); + auto d = OSDictionary::withCapacity(12); if (d) { putNumber(d, "Held", ow.held); putNumber(d, "Changes", ow.changes); @@ -237,6 +237,14 @@ void DrogaBoxGPUSensors::publish() { } if (ow.want.gfxMaxMHz != 0) putNumber(d, "GfxMaxHeld", static_cast(ow.want.gfxMaxMHz)); + if (ow.want.gfxMinMHz != 0) + putNumber(d, "GfxMinHeld", static_cast(ow.want.gfxMinMHz)); + // 0.9.0: what setOd8 takes, in the Held bits (1 fan curve, 2 zero RPM + // off, 4 GFX max, 16 GFX min), so a program knows the GFX minimum is + // there before it sends one. + putNumber(d, "Takes", + gpuctl::kOd8HeldCurve | gpuctl::kOd8HeldZeroRpmOff | + gpuctl::kOd8HeldGfx | gpuctl::kOd8HeldGfxMin); setProperty("OD8WriteState", d); d->release(); } @@ -352,9 +360,14 @@ IOReturn DrogaBoxGPUControlClient::externalMethod( IOExternalMethodDispatch*, OSObject*, void*) { if (args == nullptr || selector >= gpuctl::kSelCount) return kIOReturnBadArgument; - uint32_t wantIn = selector == gpuctl::kSelSet ? 2 - : selector == gpuctl::kSelSetOd8 ? gpuctl::kOd8WireCount - : 1; + uint32_t wantIn = 1; + if (selector == gpuctl::kSelSet) wantIn = 2; + // setOd8 takes two counts (0.9.0): its 0.7.0 form and the one with a + // GFX minimum. The count is passed on; od8Wire reads only what came. + if (selector == gpuctl::kSelSetOd8) + wantIn = gpuctl::od8WireCountOk(args->scalarInputCount) + ? args->scalarInputCount + : gpuctl::kOd8WireCount; uint32_t wantOut = selector == gpuctl::kSelStatus ? gpuctl::kStatusCount : selector == gpuctl::kSelSetOd8 ? 2 : 1; @@ -414,10 +427,12 @@ IOReturn DrogaBoxGPUControlClient::externalMethod( r = GPUControl::release(id_); break; case gpuctl::kSelSetOd8: { - // {version, flags, t1..t5, s1..s5, gfxMaxMHz}, decoded by - // gpuctl::od8Wire after off and not armed; the kext checks the rest. + // {version, flags, t1..t5, s1..s5, gfxMaxMHz[, gfxMinMHz]}, decoded + // by gpuctl::od8Wire after off and not armed; the kext checks the + // rest. uint32_t check = 0; - r = GPUControl::setOd8(id_, args->scalarInput, &closed_, &check); + r = GPUControl::setOd8(id_, args->scalarInput, args->scalarInputCount, + &closed_, &check); out[1] = check; break; } diff --git a/GPU/sensors/tests/controltest.cpp b/GPU/sensors/tests/controltest.cpp index 28c122bc..31889935 100644 --- a/GPU/sensors/tests/controltest.cpp +++ b/GPU/sensors/tests/controltest.cpp @@ -1042,7 +1042,7 @@ static void od8Writes() { after.cur[15] = 0; after.notAllowed = 0; check(od8VerifyAfter(in, cur, after) == 39, "the allowed mask moved: 39"); - od8Build(g = Od8Want{0, {}, {}, false, 2300}, first, fresh, &in); + od8Build(g = Od8Want{0, {}, {}, false, 2300, 0}, first, fresh, &in); after = cur; after.cur[0] = 2295; check(od8VerifyAfter(in, cur, after) == 0, "GFX read back 5 MHz lower: ok"); @@ -1086,7 +1086,7 @@ static void od8Writes() { "no reading for 10 s, or none at all: blind (the kext goes back)"); bool texts = true; - for (uint32_t c = 0; c <= static_cast(Od8Check::NoReadings); c++) + for (uint32_t c = 0; c <= static_cast(Od8Check::GfxMinRange); c++) texts = texts && od8CheckText(c)[0] != '\0'; check(texts && od8CheckText(99)[0] != '\0', "every OD8 refusal has a text"); } @@ -1103,6 +1103,7 @@ static void od8Scalars(uint64_t in[kOd8WireCount], uint64_t flags, in[7 + k] = sp[k]; } in[12] = gfx; + in[13] = 0; // the GFX minimum (0.9.0): stock } static void readOnlyCard() { check(deviceReadable(0x1002, 0x73BF, 0xC0) && @@ -1195,11 +1196,11 @@ static void readOnlyCard() { const uint64_t okS[5] = {20, 36, 52, 68, 100}; Od8Want want{}; od8Scalars(in, UINT64_MAX, bigT, bigS, UINT64_MAX); - bool od8off = od8Wire(o, in, &want) == Reply::Off; + bool od8off = od8Wire(o, in, kOd8WireCount, &want) == Reply::Off; od8Scalars(in, kOd8WantCurve, okT, okS, 2300); - od8off = od8off && od8Wire(o, in, &want) == Reply::Off; + od8off = od8off && od8Wire(o, in, kOd8WireCount, &want) == Reply::Off; od8Scalars(in, 0, okT, okS, 0); - od8off = od8off && od8Wire(o, in, &want) == Reply::Off; + od8off = od8off && od8Wire(o, in, kOd8WireCount, &want) == Reply::Off; check(od8off, "setOd8 answers off for absurd, good and stock states alike"); } static void disarming() { @@ -1225,7 +1226,7 @@ static void disarming() { const uint64_t bigS[5] = {201, 0, 0, 7, 0}; Od8Want want{}; od8Scalars(in, 0xff, bigT, bigS, UINT64_MAX); - check(od8Wire(o, in, &want) == Reply::NotArmed, + check(od8Wire(o, in, kOd8WireCount, &want) == Reply::NotArmed, "and setOd8 with an absurd state answers not armed"); check(o.arm() && o.change(7, 1000) == Ask::Ok, "arm opens it again and a change is taken"); @@ -1293,36 +1294,37 @@ static void wires() { const uint64_t okS[5] = {20, 36, 52, 68, 100}; Od8Want want{}; od8Scalars(in, 4, zero, zero, 0); - bool bad = od8Wire(o, in, &want) == Reply::BadArgs; + bool bad = od8Wire(o, in, kOd8WireCount, &want) == Reply::BadArgs; od8Scalars(in, kOd8WantCurve, okT, okS, 0); in[3] = 201; - bad = bad && od8Wire(o, in, &want) == Reply::BadArgs; + bad = bad && od8Wire(o, in, kOd8WireCount, &want) == Reply::BadArgs; od8Scalars(in, 0, okT, okS, 0); - bad = bad && od8Wire(o, in, &want) == Reply::BadArgs; + bad = bad && od8Wire(o, in, kOd8WireCount, &want) == Reply::BadArgs; od8Scalars(in, 0, zero, zero, 0x80000000ULL); - bad = bad && od8Wire(o, in, &want) == Reply::BadArgs; + bad = bad && od8Wire(o, in, kOd8WireCount, &want) == Reply::BadArgs; od8Scalars(in, 0, zero, zero, 0x100000000ULL); - bad = bad && od8Wire(o, in, &want) == Reply::BadArgs; + bad = bad && od8Wire(o, in, kOd8WireCount, &want) == Reply::BadArgs; check(bad, "armed: unknown flags, a point over 200, points without a curve, a " "clock the 32-bit field cannot carry (also 2^32, never read as stock)" " are malformed"); od8Scalars(in, kOd8WantCurve | kOd8WantZeroRpmOff, okT, okS, 2300); - check(od8Wire(o, in, &want) == Reply::Ok && want.curve && want.zeroRpmOff && - want.gfxMaxMHz == 2300 && want.temp[4] == 48 && + check(od8Wire(o, in, kOd8WireCount, &want) == Reply::Ok && want.curve && + want.zeroRpmOff && want.gfxMaxMHz == 2300 && want.temp[4] == 48 && want.speed[4] == 100, "armed: a good state is decoded as sent"); // S-8: the clock's first check is the card's stock maximum (2354 here). od8Scalars(in, 0, zero, zero, 5001); - check(od8Wire(o, in, &want) == Reply::Ok && want.gfxMaxMHz == 5001 && + check(od8Wire(o, in, kOd8WireCount, &want) == Reply::Ok && + want.gfxMaxMHz == 5001 && od8CheckWant(want, first, first, cur) == Od8Check::GfxRange, "5001 MHz is no longer cut at the wire: the card's maximum refuses it"); od8Scalars(in, 0, zero, zero, 2355); - check(od8Wire(o, in, &want) == Reply::Ok && + check(od8Wire(o, in, kOd8WireCount, &want) == Reply::Ok && od8CheckWant(want, first, first, cur) == Od8Check::GfxRange, "1 MHz above the stock maximum is refused"); od8Scalars(in, 0, zero, zero, 2354); - check(od8Wire(o, in, &want) == Reply::Ok && + check(od8Wire(o, in, kOd8WireCount, &want) == Reply::Ok && od8CheckWant(want, first, first, cur) == Od8Check::Ok, "the stock maximum itself is taken"); } @@ -1403,6 +1405,159 @@ static void floors() { replyText(19)[0] != '\0' && replyText(20)[0] != '\0', "the two new replies are 19 and 20, with their texts"); } +// ----------------------------------------------------------- 0.9.0 tests -- +// The GFX minimum clock (OD8 id 1): the card's 0x9f range for it (500-2800 +// on the test card, stock 500), never above the GFX maximum of the same +// state, sent with the GFX pair, read back like the maximum. +static void gfxMin() { + Od8InitialOut first, fresh; + cardInitial(&first); + fresh = first; + Od8CurrentOut cur; + cardCurrent(first, &cur); + Od8Want m{}; + m.gfxMinMHz = 1500; + check(!od8IsStock(m), "a raised GFX minimum is a change, not stock"); + check(od8CheckWant(m, first, fresh, cur) == Od8Check::Ok, + "GFX min 1500 with the stock maximum: ok"); + m.gfxMinMHz = 2354; + check(od8CheckWant(m, first, fresh, cur) == Od8Check::Ok, + "GFX min at the stock maximum (a pinned clock): ok"); + m.gfxMinMHz = 2355; + check(od8CheckWant(m, first, fresh, cur) == Od8Check::GfxMinRange, + "GFX min 1 MHz above the stock maximum: refused"); + m.gfxMinMHz = 499; + check(od8CheckWant(m, first, fresh, cur) == Od8Check::GfxMinRange, + "GFX min under the card's 500 MHz: refused"); + m.gfxMinMHz = 2801; + check(od8CheckWant(m, first, fresh, cur) == Od8Check::GfxMinRange, + "GFX min over the card's range: refused"); + m.gfxMinMHz = 2000; + m.gfxMaxMHz = 1900; + check(od8CheckWant(m, first, fresh, cur) == Od8Check::GfxMinRange, + "GFX min above the GFX max asked in the same state: refused"); + m.gfxMaxMHz = 2000; + check(od8CheckWant(m, first, fresh, cur) == Od8Check::Ok, + "GFX min equal to the GFX max asked: ok"); + m.gfxMaxMHz = 1400; + check(od8CheckWant(m, first, fresh, cur) == Od8Check::GfxRange, + "a GFX max under 1500 is still the max's refusal"); + Od8InitialOut woke = first; + woke.e[0].def = 2340; + Od8Want top{}; + top.gfxMinMHz = 2350; + check(od8CheckWant(top, first, woke, cur) == Od8Check::GfxMinRange, + "after a wake lowered the maximum's default to 2340: 2350 refused"); + top.gfxMinMHz = 2340; + check(od8CheckWant(top, first, woke, cur) == Od8Check::Ok, + "and 2340 taken (the lower of the two reads)"); + Od8InitialOut narrow = first; + narrow.e[1].min = 600; + Od8Want lo{}; + lo.gfxMinMHz = 550; + check(od8CheckWant(lo, narrow, narrow, cur) == Od8Check::GfxMinRange, + "the range comes from the card's 0x9f entry, not a constant"); + + // The call. + Od8SetIn in; + Od8Want b{}; + b.gfxMinMHz = 1500; + od8Build(b, first, fresh, &in); + check(od8ShapeOk(in) && in.e[1].value == 1500 && in.e[1].requested == 1 && + in.e[1].reset == 0 && in.e[0].value == 2354 && + in.e[0].requested == 1, + "GFX min 1500: the pair goes out as {2354 stock, 1500}"); + bool others = true; + const uint32_t untouched[] = {8, 9, 10, 11, 12, 13, 14, + 16, 17, 18, 29, 34, 36, 37}; + for (uint32_t i : untouched) + others = others && in.e[i].requested == 0 && in.e[i].reset == 0; + check(others, + "memory max and min, fan minimum and target, power %, voltage: " + "untouched with a GFX minimum"); + b.gfxMaxMHz = 2000; + od8Build(b, first, fresh, &in); + check(od8ShapeOk(in) && in.e[0].value == 2000 && in.e[1].value == 1500, + "GFX max and min together: both values"); + Od8SetIn bad = in; + bad.e[1].value = 2001; + check(!od8ShapeOk(bad), "a minimum above the maximum in the bytes: never"); + bad = in; + bad.e[1].requested = 0; + check(!od8ShapeOk(bad), "the pair split (only the maximum): never"); + bad = in; + bad.e[1].value = 0; + check(!od8ShapeOk(bad), "a minimum of 0 in the bytes: never"); + od8Build(Od8Want{}, first, fresh, &in); + check(od8ShapeOk(in) && in.e[1].value == 500, + "stock: the minimum goes back to the first read's 500"); + + // The read-back. + b = Od8Want{}; + b.gfxMinMHz = 1500; + od8Build(b, first, fresh, &in); + Od8CurrentOut after = cur; + after.cur[1] = 1500; + check(od8VerifyAfter(in, cur, after) == 0, "GFX min read back as sent: ok"); + after.cur[1] = 1490; + check(od8VerifyAfter(in, cur, after) == 0, + "GFX min read back 10 MHz lower: ok (as the maximum)"); + after.cur[1] = 1501; + check(od8VerifyAfter(in, cur, after) == 2, + "GFX min read back higher: entry 1 reported"); + after.cur[1] = 1474; + check(od8VerifyAfter(in, cur, after) == 2, + "GFX min read back 26 MHz lower: reported"); + after = cur; + check(od8VerifyAfter(in, cur, after) == 2, + "GFX min not taken (still 500): reported"); + + // The wire. + Owner o; + uint64_t w14[kOd8WireCount]; + const uint64_t zero[5] = {0, 0, 0, 0, 0}; + Od8Want want{}; + od8Scalars(w14, 0, zero, zero, 0); + w14[13] = 1500; + check(od8Wire(o, w14, kOd8WireCount, &want) == Reply::NotArmed, + "the 14-scalar form answers not armed before its values"); + o.arm(); + check(od8Wire(o, w14, kOd8WireCount, &want) == Reply::Ok && + want.gfxMinMHz == 1500 && want.gfxMaxMHz == 0 && !want.curve, + "14 scalars: the GFX minimum is decoded as sent"); + check(od8Wire(o, w14, kOd8WireCountV070, &want) == Reply::Ok && + want.gfxMinMHz == 0, + "13 scalars (0.7.0): the 14th is never read, the minimum is stock"); + check(od8Wire(o, w14, 12, &want) == Reply::BadArgs && + od8Wire(o, w14, 15, &want) == Reply::BadArgs && + !od8WireCountOk(12) && od8WireCountOk(13) && od8WireCountOk(14), + "any other count: malformed"); + w14[13] = 0x80000000ULL; + check(od8Wire(o, w14, kOd8WireCount, &want) == Reply::BadArgs, + "a minimum the 32-bit field cannot carry: malformed"); + Owner gone; + gone.arm(); + gone.turnOff(); + w14[13] = 1500; + check(od8Wire(gone, w14, kOd8WireCount, &want) == Reply::Off, + "writing off: off before the minimum is looked at"); + + // The watchdog while only a GFX minimum is held: target 0, so only the + // 95 C limit and the missing readings count (the stock fan climbs slowly). + Od8Watch dog; + check(od8Watchdog(&dog, true, 900, 80, 40, 0, 1000) == Od8Dog::Fine && + od8Watchdog(&dog, true, 900, 85, 40, 0, 9000) == Od8Dog::Fine, + "no curve: 80-85 C with the stock fan at 40 % for 8 s is fine"); + check(od8Watchdog(&dog, true, 900, 95, 100, 0, 10000) == Od8Dog::Trip, + "no curve: 95 C still trips"); + check(od8Watchdog(&dog, true, 11000, 50, 30, 0, 22000) == Od8Dog::Blind, + "no curve: no readings for 10 s still goes back"); + check(od8CheckText(static_cast(Od8Check::GfxMinRange))[0] != '\0' && + static_cast(Od8Check::GfxMinRange) == 12 && + kOd8HeldGfxMin == 16 && kFlagGfxMin == 512, + "GfxMinRange is 12 with a text, held bit 16, status flag 512"); +} + int main() { card(); profiles(); @@ -1428,6 +1583,7 @@ int main() { disarming(); wires(); floors(); + gfxMin(); if (failures != 0) printf("%d FAILED\n", failures); return failures == 0 ? 0 : 1; } diff --git a/GPU/sensors/tests/curve_fixturegen.cpp b/GPU/sensors/tests/curve_fixturegen.cpp index 63d08e85..4694c273 100644 --- a/GPU/sensors/tests/curve_fixturegen.cpp +++ b/GPU/sensors/tests/curve_fixturegen.cpp @@ -24,6 +24,8 @@ // 37 GfxVoltOffset 131072/881/1075/1075/1075 // All other ids (2-7, 13, 29-34): unpublished, zero. // Prints one JSON line per case: {"want":{...},"check":}. +// A GFX minimum (0.9.0) is written as "gfxMin" only when it is not stock, so +// the 100 lines from before it stay byte for byte as they were. #include #include #include @@ -123,11 +125,12 @@ static void emit(const Od8Want& w, std::initializer_list muts = {}) { Od8Check c = od8CheckWant(w, F, R, C); printf( "{\"want\":{\"curve\":%s,\"temp\":[%d,%d,%d,%d,%d]," - "\"speed\":[%d,%d,%d,%d,%d],\"zeroRpmOff\":%s,\"gfx\":%d}," - "\"muts\":[", + "\"speed\":[%d,%d,%d,%d,%d],\"zeroRpmOff\":%s,\"gfx\":%d", w.curve ? "true" : "false", w.temp[0], w.temp[1], w.temp[2], w.temp[3], w.temp[4], w.speed[0], w.speed[1], w.speed[2], w.speed[3], w.speed[4], w.zeroRpmOff ? "true" : "false", w.gfxMaxMHz); + if (w.gfxMinMHz != 0) printf(",\"gfxMin\":%d", w.gfxMinMHz); + printf("},\"muts\":["); bool sep = false; for (const Mut& m : muts) { if (sep) printf(","); @@ -361,5 +364,48 @@ int main() { emit(stock, {{"firstEntry", kOd8GfxMax, "feature", 0}}); // layout differs -> Drifted + // 0.9.0: the GFX minimum (id 1), in the card's range for it (500-2800) + // and never above the GFX maximum of the same state (2359 stock here). + for (int32_t g : {500, 501, 1500, 2000, 2358, 2359}) { + Od8Want w{}; + w.gfxMinMHz = g; + emit(w); // Ok + } + for (int32_t g : {499, 2360, 2800, 2801}) { + Od8Want w{}; + w.gfxMinMHz = g; + emit(w); // GfxMinRange + } + { + Od8Want w{}; + w.gfxMaxMHz = 2000; + w.gfxMinMHz = 2000; + emit(w); // Ok: equal to the max asked + w.gfxMinMHz = 2001; + emit(w); // GfxMinRange: above the max asked + w.gfxMaxMHz = 1400; + w.gfxMinMHz = 1000; + emit(w); // GfxRange: the max's own refusal comes first + } + { + Od8Want w = curve(new int32_t[5]{30, 40, 44, 46, 48}, + new int32_t[5]{20, 36, 52, 68, 100}, true, 2300); + w.gfxMinMHz = 1800; + emit(w); // Ok: everything at once + w.gfxMinMHz = 2301; + emit(w); // GfxMinRange + } + { + Od8Want w{}; + w.gfxMinMHz = 2350; + emit(w, {{"freshEntry", kOd8GfxMax, "def", 2340}}); // GfxMinRange + w.gfxMinMHz = 2340; + emit(w, {{"freshEntry", kOd8GfxMax, "def", 2340}}); // Ok (lower read) + w.gfxMinMHz = 550; + emit(w, {{"bothEntry", kOd8GfxMin, "min", 600}}); // GfxMinRange + emit(w, {{"bothEntry", kOd8GfxMin, "max", 540}}); // GfxMinRange + emit(w, {{"bothEntry", kOd8GfxMin, "feature", 8}}); // NoFeature first + } + return 0; } diff --git a/GPU/sensors/tool/gpucontrol.cpp b/GPU/sensors/tool/gpucontrol.cpp index 4518b961..045da136 100644 --- a/GPU/sensors/tool/gpucontrol.cpp +++ b/GPU/sensors/tool/gpucontrol.cpp @@ -5,10 +5,12 @@ // gpucontrol od8 what the kext read of OD8 (fan // curve, clock ranges); anyone // gpucontrol hold [fan C:%,C:%,C:%,C:%,C:%] [zerorpm off] [gfxmax MHz] +// [gfxmin MHz] // -- holds that fan curve / zero RPM -// off / lower GFX max while the -// command runs, then stock (0.7.0) -// gpucontrol check [fan ...] [zerorpm off] [gfxmax MHz] +// off / lower GFX max / raised GFX +// min (0.9.0) while the command +// runs, then stock (0.7.0) +// gpucontrol check [fan ...] [zerorpm off] [gfxmax MHz] [gfxmin MHz] // says whether the kext would take // it, and why not; sends nothing // sudo gpucontrol arm opens writing until restart @@ -62,9 +64,10 @@ const char* kUsage = " gpucontrol disarm\n" " gpucontrol hold power -- [args...]\n" " gpucontrol hold [fan C:%,C:%,C:%,C:%,C:%] [zerorpm off] [gfxmax " - "MHz]" + "MHz] [gfxmin MHz]" " -- [args...]\n" - " gpucontrol check [fan C:%,...] [zerorpm off] [gfxmax MHz]\n"; + " gpucontrol check [fan C:%,...] [zerorpm off] [gfxmax MHz] [gfxmin " + "MHz]\n"; volatile sig_atomic_t gSignal = 0; // A SIGTERM has its own flag: a later Ctrl-C or hangup overwrites gSignal, and @@ -189,9 +192,11 @@ int doStatus() { else if (h == 0) printf(" OD8 at stock\n"); else - printf(" OD8 %s%s%s%s\n", (h & kOd8HeldCurve) ? "fan curve " : "", + printf(" OD8 %s%s%s%s%s\n", + (h & kOd8HeldCurve) ? "fan curve " : "", (h & kOd8HeldZeroRpmOff) ? "zero RPM off " : "", (h & kOd8HeldGfx) ? "GFX max lowered " : "", + (h & kOd8HeldGfxMin) ? "GFX min raised " : "", (h & kOd8HeldUnknown) ? "not confirmed, going back to stock" : ""); if (f & kFlagOwned) printf(" held by a program\n"); if (f & kFlagReverting) printf(" going back to the start-up limit\n"); @@ -313,12 +318,21 @@ bool parseCurve(const char* text, Od8Want* w) { w->curve = true; return true; } -// The OD8 options: fan CURVE, zerorpm off, gfxmax MHz, in any order, each -// once. argv ends at the first "--" or at the end. Returns how many words -// it took, 0 on a mistake. +// A clock in MHz: any the 32-bit field carries; the kext checks it against +// the card's range. +bool parseMHz(const char* s, int32_t* out) { + char* end = nullptr; + long m = strtol(s, &end, 10); + if (end == s || *end != '\0' || m <= 0 || m > 0x7fffffffL) return false; + *out = static_cast(m); + return true; +} +// The OD8 options: fan CURVE, zerorpm off, gfxmax MHz, gfxmin MHz (0.9.0), +// in any order, each once. argv ends at the first "--" or at the end. +// Returns how many words it took, 0 on a mistake. int parseOd8(char** argv, int argc, Od8Want* w) { int i = 0; - bool fan = false, zero = false, gfx = false; + bool fan = false, zero = false, gfx = false, low = false; while (i < argc && strcmp(argv[i], "--") != 0) { if (strcmp(argv[i], "fan") == 0 && i + 1 < argc && !fan) { if (!parseCurve(argv[i + 1], w)) { @@ -333,20 +347,17 @@ int parseOd8(char** argv, int argc, Od8Want* w) { w->zeroRpmOff = true; zero = true; } else if (strcmp(argv[i], "gfxmax") == 0 && i + 1 < argc && !gfx) { - char* end = nullptr; - long m = strtol(argv[i + 1], &end, 10); - // Any clock the 32-bit field carries; the kext checks it against the - // card's stock maximum. - if (end == argv[i + 1] || *end != '\0' || m <= 0 || m > 0x7fffffffL) - return 0; - w->gfxMaxMHz = static_cast(m); + if (!parseMHz(argv[i + 1], &w->gfxMaxMHz)) return 0; gfx = true; + } else if (strcmp(argv[i], "gfxmin") == 0 && i + 1 < argc && !low) { + if (!parseMHz(argv[i + 1], &w->gfxMinMHz)) return 0; + low = true; } else { return 0; } i += 2; } - return (fan || zero || gfx) ? i : 0; + return (fan || zero || gfx || low) ? i : 0; } void describe(const HoldReq& q, char* out, size_t n) { if (!q.od8) { @@ -364,14 +375,17 @@ void describe(const HoldReq& q, char* out, size_t n) { if (q.want.zeroRpmOff && used < n) used += snprintf(out + used, n - used, "%szero RPM off", used ? "; " : ""); if (q.want.gfxMaxMHz != 0 && used < n) - snprintf(out + used, n - used, "%sGFX max %d MHz", used ? "; " : "", - q.want.gfxMaxMHz); + used += snprintf(out + used, n - used, "%sGFX max %d MHz", used ? "; " : "", + q.want.gfxMaxMHz); + if (q.want.gfxMinMHz != 0 && used < n) + snprintf(out + used, n - used, "%sGFX min %d MHz", used ? "; " : "", + q.want.gfxMinMHz); } // Sends the request once. *check: why an OD8 state was refused. Reply sendReq(Channel& ch, const HoldReq& q, uint64_t* check) { *check = 0; if (!q.od8) return ch.call(kSelSet, q.watts, true); - uint64_t in[13] = {kChannelVersion}; + uint64_t in[kOd8WireCount] = {kChannelVersion}; in[1] = (q.want.curve ? kOd8WantCurve : 0) | (q.want.zeroRpmOff ? kOd8WantZeroRpmOff : 0); for (uint32_t k = 0; k < kOd8CurvePoints; k++) { @@ -379,10 +393,18 @@ Reply sendReq(Channel& ch, const HoldReq& q, uint64_t* check) { in[7 + k] = q.want.curve ? static_cast(q.want.speed[k]) : 0; } in[12] = static_cast(q.want.gfxMaxMHz); + in[13] = static_cast(q.want.gfxMinMHz); + // The 0.7.0 form unless a GFX minimum is asked: a 0.7.x or 0.8.x kext + // takes only 13 scalars (and refuses 14 with kIOReturnBadArgument). + uint32_t count = q.want.gfxMinMHz != 0 ? kOd8WireCount : kOd8WireCountV070; uint64_t out[2] = {0, 0}; uint32_t outCount = 2; kern_return_t kr = - IOConnectCallScalarMethod(ch.conn, kSelSetOd8, in, 13, out, &outCount); + IOConnectCallScalarMethod(ch.conn, kSelSetOd8, in, count, out, &outCount); + if (kr == kIOReturnBadArgument && count == kOd8WireCount) + fprintf(stderr, + "gpucontrol: this GPUSensors takes no GFX minimum (0.9.0 or " + "newer does)\n"); if (kr != KERN_SUCCESS || outCount < 2) return Reply::BadArgs; *check = out[1]; return static_cast(out[0]); diff --git a/Sources/RyzenStatus/Core/DefaultsKey+App.swift b/Sources/RyzenStatus/Core/DefaultsKey+App.swift index ca3b6311..c46bb0e9 100644 --- a/Sources/RyzenStatus/Core/DefaultsKey+App.swift +++ b/Sources/RyzenStatus/Core/DefaultsKey+App.swift @@ -1102,4 +1102,6 @@ extension DefaultsKey { static let gpuControlRememberedCurve = "gpuControlRememberedCurve" // [C, %] x 5, flat static let gpuControlRememberedZeroRpmOff = "gpuControlRememberedZeroRpmOff" static let gpuControlRememberedGfxMHz = "gpuControlRememberedGfxMHz" + /// A raised GFX minimum (GPUSensors 0.9.0), in MHz. + static let gpuControlRememberedGfxMinMHz = "gpuControlRememberedGfxMinMHz" } diff --git a/Sources/RyzenStatus/Core/GPUControlClockStrings.swift b/Sources/RyzenStatus/Core/GPUControlClockStrings.swift index 6a0fba87..53edf16b 100644 --- a/Sources/RyzenStatus/Core/GPUControlClockStrings.swift +++ b/Sources/RyzenStatus/Core/GPUControlClockStrings.swift @@ -26,9 +26,24 @@ struct GPUControlClockStrings { /// %2$d = the stock maximum, both in MHz. let sliderHelpFormat: String + // The GFX minimum clock section (GPUSensors 0.9.0). Its stock caption, + // range note, power note and wait reuse the texts above. + /// The section's header, and the slider's VoiceOver label. + let minSection: String + /// VoiceOver: the MHz field. + let minFieldLabel: String + /// VoiceOver: the stepper; %d = its step in MHz. + let minStepperFormat: String + let minToggle: String + let minFooter: String + /// The slider's VoiceOver help: %1$d = the stock minimum, %2$d = the top + /// (the GFX maximum in force), both in MHz. + let minSliderHelpFormat: String + var all: [String] { [section, toggle, stockFormat, footer, notePowerHeld, noteClockHeld, switching, outOfRangeFormat, - fieldLabel, stepperFormat, sliderHelpFormat] + fieldLabel, stepperFormat, sliderHelpFormat, + minSection, minFieldLabel, minStepperFormat, minToggle, minFooter, minSliderHelpFormat] } } @@ -65,7 +80,13 @@ extension GPUControlClockStrings { noteClockHeld: "A clock setting is held. Choosing a power limit first returns the clock to stock: the kext never holds both.", switching: "Returning the power limit to its start-up value first…", outOfRangeFormat: "Choose a value from %d to %d MHz.", - sliderHelpFormat: "From %1$d MHz to the stock maximum, %2$d MHz. Only lowers the maximum; the value is sent when you stop moving it.") + sliderHelpFormat: "From %1$d MHz to the stock maximum, %2$d MHz. Only lowers the maximum; the value is sent when you stop moving it.", + minSection: "GFX minimum clock", + minFieldLabel: "GFX minimum clock in MHz", + minStepperFormat: "GFX minimum clock, steps of %d MHz", + minToggle: "Raise the minimum clock", + minFooter: "Only higher than stock and never above the GFX maximum; the kext checks every request. A higher minimum keeps the clock up at idle, so the card draws more power and runs warmer; the kext goes back to stock if the GPU gets too hot.", + minSliderHelpFormat: "From the stock minimum, %1$d MHz, to %2$d MHz. Only raises the minimum; the value is sent when you stop moving it.") static let es = GPUControlClockStrings( section: "Reloj máximo de GFX", @@ -78,7 +99,13 @@ extension GPUControlClockStrings { noteClockHeld: "Hay un reloj máximo puesto. Al elegir un límite de potencia, primero el reloj vuelve a los valores de fábrica: el kext nunca mantiene las dos cosas.", switching: "Primero el límite de potencia vuelve a su valor de arranque…", outOfRangeFormat: "Elige un valor entre %d y %d MHz.", - sliderHelpFormat: "De %1$d MHz al máximo de fábrica, %2$d MHz. Solo baja el máximo; el valor se manda cuando dejas de moverlo.") + sliderHelpFormat: "De %1$d MHz al máximo de fábrica, %2$d MHz. Solo baja el máximo; el valor se manda cuando dejas de moverlo.", + minSection: "Reloj mínimo de GFX", + minFieldLabel: "Reloj mínimo de GFX en MHz", + minStepperFormat: "Reloj mínimo de GFX, pasos de %d MHz", + minToggle: "Subir el reloj mínimo", + minFooter: "Solo por encima del de fábrica y nunca sobre el máximo de GFX; el kext revisa cada pedido. Un mínimo más alto mantiene el reloj arriba en reposo, así que la tarjeta consume más y se calienta más; el kext vuelve a los valores de fábrica si la GPU se calienta demasiado.", + minSliderHelpFormat: "Del mínimo de fábrica, %1$d MHz, a %2$d MHz. Solo sube el mínimo; el valor se manda cuando dejas de moverlo.") static let ptBR = GPUControlClockStrings( section: "Clock máximo da GFX", @@ -91,7 +118,13 @@ extension GPUControlClockStrings { noteClockHeld: "Há um clock máximo mantido. Ao escolher um limite de energia, primeiro o clock volta ao padrão: o kext nunca mantém os dois.", switching: "Primeiro o limite de energia volta ao valor de inicialização…", outOfRangeFormat: "Escolha um valor entre %d e %d MHz.", - sliderHelpFormat: "De %1$d MHz até o máximo de fábrica, %2$d MHz. Só reduz o máximo; o valor é enviado quando você para de movê-lo.") + sliderHelpFormat: "De %1$d MHz até o máximo de fábrica, %2$d MHz. Só reduz o máximo; o valor é enviado quando você para de movê-lo.", + minSection: "Clock mínimo da GFX", + minFieldLabel: "Clock mínimo da GFX em MHz", + minStepperFormat: "Clock mínimo da GFX, passos de %d MHz", + minToggle: "Aumentar o clock mínimo", + minFooter: "Só acima do padrão e nunca acima do máximo da GFX; o kext verifica cada pedido. Um mínimo mais alto mantém o clock alto em repouso, então a placa consome mais e esquenta mais; o kext volta ao padrão se a GPU esquentar demais.", + minSliderHelpFormat: "Do mínimo de fábrica, %1$d MHz, até %2$d MHz. Só aumenta o mínimo; o valor é enviado quando você para de movê-lo.") static let tr = GPUControlClockStrings( section: "Maks. GFX saat hızı", @@ -104,7 +137,13 @@ extension GPUControlClockStrings { noteClockHeld: "Bir maks. saat hızı tutuluyor. Güç sınırı seçmek önce saat hızını fabrika değerine döndürür: kext ikisini birlikte tutmaz.", switching: "Önce güç sınırı başlangıç değerine dönüyor…", outOfRangeFormat: "%d ile %d MHz arasında bir değer seçin.", - sliderHelpFormat: "%1$d MHz'den fabrika maksimumu %2$d MHz'e kadar. Yalnızca maksimumu düşürür; değer, hareket ettirmeyi bıraktığınızda gönderilir.") + sliderHelpFormat: "%1$d MHz'den fabrika maksimumu %2$d MHz'e kadar. Yalnızca maksimumu düşürür; değer, hareket ettirmeyi bıraktığınızda gönderilir.", + minSection: "Min. GFX saat hızı", + minFieldLabel: "Min. GFX saat hızı (MHz)", + minStepperFormat: "Min. GFX saat hızı, %d MHz'lik adımlar", + minToggle: "Min. saat hızını yükselt", + minFooter: "Yalnızca fabrika değerinin üstünde ve asla maks. GFX saat hızının üstünde değil; kext her isteği denetler. Daha yüksek bir minimum, saat hızını boştayken de yüksek tutar; kart daha çok güç çeker ve daha çok ısınır. GPU fazla ısınırsa kext fabrika değerine döner.", + minSliderHelpFormat: "Fabrika minimumu %1$d MHz'den %2$d MHz'e kadar. Yalnızca minimumu yükseltir; değer, hareket ettirmeyi bıraktığınızda gönderilir.") static let ru = GPUControlClockStrings( section: "Макс. частота GFX", @@ -117,7 +156,13 @@ extension GPUControlClockStrings { noteClockHeld: "Удерживается макс. частота. Выбор лимита мощности сначала вернёт частоту к заводской: kext никогда не удерживает оба.", switching: "Сначала лимит мощности возвращается к значению загрузки…", outOfRangeFormat: "Выберите значение от %d до %d МГц.", - sliderHelpFormat: "От %1$d МГц до заводского максимума, %2$d МГц. Только снижает максимум; значение отправляется, когда вы перестаёте его двигать.") + sliderHelpFormat: "От %1$d МГц до заводского максимума, %2$d МГц. Только снижает максимум; значение отправляется, когда вы перестаёте его двигать.", + minSection: "Мин. частота GFX", + minFieldLabel: "Мин. частота GFX в МГц", + minStepperFormat: "Мин. частота GFX, шаг %d МГц", + minToggle: "Повысить минимальную частоту", + minFooter: "Только выше заводской и никогда не выше макс. частоты GFX; kext проверяет каждый запрос. Более высокий минимум держит частоту поднятой в простое, поэтому карта потребляет больше и сильнее греется; kext возвращает заводские значения, если GPU перегревается.", + minSliderHelpFormat: "От заводского минимума, %1$d МГц, до %2$d МГц. Только повышает минимум; значение отправляется, когда вы перестаёте его двигать.") static let sk = GPUControlClockStrings( section: "Maximálny takt GFX", @@ -130,7 +175,13 @@ extension GPUControlClockStrings { noteClockHeld: "Drží sa maximálny takt. Výber limitu príkonu najprv vráti takt na továrenskú hodnotu: kext nikdy nedrží oboje.", switching: "Najprv sa limit príkonu vracia na štartovaciu hodnotu…", outOfRangeFormat: "Vyberte hodnotu od %d do %d MHz.", - sliderHelpFormat: "Od %1$d MHz po továrenské maximum, %2$d MHz. Maximum iba znižuje; hodnota sa odošle, keď ním prestanete hýbať.") + sliderHelpFormat: "Od %1$d MHz po továrenské maximum, %2$d MHz. Maximum iba znižuje; hodnota sa odošle, keď ním prestanete hýbať.", + minSection: "Minimálny takt GFX", + minFieldLabel: "Minimálny takt GFX v MHz", + minStepperFormat: "Minimálny takt GFX, kroky po %d MHz", + minToggle: "Zvýšiť minimálny takt", + minFooter: "Iba nad továrenskú hodnotu a nikdy nad maximálny takt GFX; kext kontroluje každú požiadavku. Vyššie minimum drží takt hore aj v nečinnosti, takže karta viac berie a viac sa zahrieva; ak sa GPU príliš zahreje, kext vráti továrenské hodnoty.", + minSliderHelpFormat: "Od továrenského minima, %1$d MHz, po %2$d MHz. Minimum iba zvyšuje; hodnota sa odošle, keď ním prestanete hýbať.") static let de = GPUControlClockStrings( section: "Maximaler GFX-Takt", @@ -143,7 +194,13 @@ extension GPUControlClockStrings { noteClockHeld: "Ein maximaler Takt wird gehalten. Beim Wählen eines Leistungslimits geht der Takt zuerst auf den Werkswert zurück: Der Kext hält nie beides.", switching: "Das Leistungslimit geht zuerst auf seinen Startwert zurück…", outOfRangeFormat: "Wählen Sie einen Wert von %d bis %d MHz.", - sliderHelpFormat: "Von %1$d MHz bis zum Werksmaximum, %2$d MHz. Senkt nur das Maximum; der Wert wird gesendet, wenn Sie ihn nicht mehr bewegen.") + sliderHelpFormat: "Von %1$d MHz bis zum Werksmaximum, %2$d MHz. Senkt nur das Maximum; der Wert wird gesendet, wenn Sie ihn nicht mehr bewegen.", + minSection: "Minimaler GFX-Takt", + minFieldLabel: "Minimaler GFX-Takt in MHz", + minStepperFormat: "Minimaler GFX-Takt, Schritte von %d MHz", + minToggle: "Minimalen Takt anheben", + minFooter: "Nur über den Werkswert und nie über den maximalen GFX-Takt; der Kext prüft jede Anfrage. Ein höheres Minimum hält den Takt auch im Leerlauf oben, die Karte braucht also mehr Strom und wird wärmer; wird die GPU zu heiß, geht der Kext auf die Werkswerte zurück.", + minSliderHelpFormat: "Vom Werksminimum, %1$d MHz, bis %2$d MHz. Hebt nur das Minimum an; der Wert wird gesendet, wenn Sie ihn nicht mehr bewegen.") static let fr = GPUControlClockStrings( section: "Fréquence GFX maximale", @@ -156,7 +213,13 @@ extension GPUControlClockStrings { noteClockHeld: "Une fréquence maximale est maintenue. Choisir une limite de puissance remet d’abord la fréquence à sa valeur d’usine : le kext ne maintient jamais les deux.", switching: "La limite de puissance revient d’abord à sa valeur de démarrage…", outOfRangeFormat: "Choisissez une valeur de %d à %d MHz.", - sliderHelpFormat: "De %1$d MHz au maximum d’usine, %2$d MHz. Abaisse seulement le maximum ; la valeur est envoyée quand vous arrêtez de la déplacer.") + sliderHelpFormat: "De %1$d MHz au maximum d’usine, %2$d MHz. Abaisse seulement le maximum ; la valeur est envoyée quand vous arrêtez de la déplacer.", + minSection: "Fréquence GFX minimale", + minFieldLabel: "Fréquence GFX minimale en MHz", + minStepperFormat: "Fréquence GFX minimale, pas de %d MHz", + minToggle: "Relever la fréquence minimale", + minFooter: "Seulement au-dessus de la valeur d’usine et jamais au-dessus de la fréquence GFX maximale ; le kext vérifie chaque demande. Un minimum plus haut garde la fréquence haute au repos : la carte consomme et chauffe davantage ; le kext revient aux valeurs d’usine si le GPU chauffe trop.", + minSliderHelpFormat: "Du minimum d’usine, %1$d MHz, à %2$d MHz. Relève seulement le minimum ; la valeur est envoyée quand vous arrêtez de la déplacer.") static let it = GPUControlClockStrings( section: "Clock GFX massimo", @@ -169,7 +232,13 @@ extension GPUControlClockStrings { noteClockHeld: "È mantenuto un clock massimo. Scegliendo un limite di potenza, prima il clock torna al valore di fabbrica: il kext non mantiene mai entrambi.", switching: "Prima il limite di potenza torna al valore di avvio…", outOfRangeFormat: "Scegli un valore tra %d e %d MHz.", - sliderHelpFormat: "Da %1$d MHz al massimo di fabbrica, %2$d MHz. Abbassa solo il massimo; il valore viene inviato quando smetti di muoverlo.") + sliderHelpFormat: "Da %1$d MHz al massimo di fabbrica, %2$d MHz. Abbassa solo il massimo; il valore viene inviato quando smetti di muoverlo.", + minSection: "Clock GFX minimo", + minFieldLabel: "Clock GFX minimo in MHz", + minStepperFormat: "Clock GFX minimo, passi da %d MHz", + minToggle: "Alza il clock minimo", + minFooter: "Solo sopra il valore di fabbrica e mai sopra il clock GFX massimo; il kext controlla ogni richiesta. Un minimo più alto tiene il clock alto anche a riposo, quindi la scheda consuma e scalda di più; il kext torna ai valori di fabbrica se la GPU scalda troppo.", + minSliderHelpFormat: "Dal minimo di fabbrica, %1$d MHz, a %2$d MHz. Alza solo il minimo; il valore viene inviato quando smetti di muoverlo.") static let ja = GPUControlClockStrings( section: "GFX 最大クロック", @@ -182,7 +251,13 @@ extension GPUControlClockStrings { noteClockHeld: "最大クロックが保持されています。電力制限を選ぶと、先にクロックが純正に戻ります。kext は両方を同時に保持しません。", switching: "先に電力制限を起動時の値に戻しています…", outOfRangeFormat: "%d から %d MHz の値を選んでください。", - sliderHelpFormat: "%1$d MHz から純正の最大値 %2$d MHz まで。最大値を下げるだけです。動かすのをやめると値が送られます。") + sliderHelpFormat: "%1$d MHz から純正の最大値 %2$d MHz まで。最大値を下げるだけです。動かすのをやめると値が送られます。", + minSection: "GFX 最小クロック", + minFieldLabel: "GFX 最小クロック(MHz)", + minStepperFormat: "GFX 最小クロック、%d MHz 刻み", + minToggle: "最小クロックを上げる", + minFooter: "純正より高く、GFX 最大クロック以下の値のみです。kext はすべての要求を確認します。最小値を上げるとアイドル時もクロックが高いままになり、消費電力と温度が上がります。GPU が熱くなりすぎると kext は純正に戻します。", + minSliderHelpFormat: "純正の最小値 %1$d MHz から %2$d MHz まで。最小値を上げるだけです。動かすのをやめると値が送られます。") static let ko = GPUControlClockStrings( section: "최대 GFX 클록", @@ -195,7 +270,13 @@ extension GPUControlClockStrings { noteClockHeld: "최대 클록이 유지되고 있습니다. 전력 한도를 선택하면 먼저 클록이 기본값으로 돌아갑니다. kext는 둘을 함께 유지하지 않습니다.", switching: "먼저 전력 한도를 시동 값으로 돌리는 중…", outOfRangeFormat: "%d에서 %d MHz 사이의 값을 선택하십시오.", - sliderHelpFormat: "%1$d MHz부터 기본 최대값 %2$d MHz까지. 최대값을 낮추기만 하며, 움직임을 멈추면 값이 전송됩니다.") + sliderHelpFormat: "%1$d MHz부터 기본 최대값 %2$d MHz까지. 최대값을 낮추기만 하며, 움직임을 멈추면 값이 전송됩니다.", + minSection: "최소 GFX 클록", + minFieldLabel: "최소 GFX 클록(MHz)", + minStepperFormat: "최소 GFX 클록, %d MHz 단위", + minToggle: "최소 클록 높이기", + minFooter: "기본값보다 높게, 최대 GFX 클록을 넘지 않게만 설정할 수 있으며, kext가 모든 요청을 확인합니다. 최소값을 높이면 유휴 상태에서도 클록이 높게 유지되어 전력 소모와 발열이 늘어납니다. GPU가 너무 뜨거워지면 kext가 기본값으로 되돌립니다.", + minSliderHelpFormat: "기본 최소값 %1$d MHz부터 %2$d MHz까지. 최소값을 높이기만 하며, 움직임을 멈추면 값이 전송됩니다.") static let zhHans = GPUControlClockStrings( section: "GFX 最大时钟频率", @@ -208,7 +289,13 @@ extension GPUControlClockStrings { noteClockHeld: "正在维持最大时钟频率。选择功率上限会先使时钟频率返回出厂值:kext 绝不会同时维持两者。", switching: "正在先使功率上限返回启动值…", outOfRangeFormat: "请选择 %d 到 %d MHz 之间的值。", - sliderHelpFormat: "从 %1$d MHz 到出厂最大值 %2$d MHz。只会降低最大值;停止移动后发送该值。") + sliderHelpFormat: "从 %1$d MHz 到出厂最大值 %2$d MHz。只会降低最大值;停止移动后发送该值。", + minSection: "GFX 最小时钟频率", + minFieldLabel: "GFX 最小时钟频率(MHz)", + minStepperFormat: "GFX 最小时钟频率,步长 %d MHz", + minToggle: "提高最小时钟频率", + minFooter: "只能高于出厂值,且不超过 GFX 最大时钟频率;kext 会检查每个请求。提高最小值会让时钟在空闲时也保持较高,显卡功耗和温度都会上升;GPU 过热时 kext 会恢复出厂值。", + minSliderHelpFormat: "从出厂最小值 %1$d MHz 到 %2$d MHz。只会提高最小值;停止移动后发送该值。") static let zhTW = GPUControlClockStrings( section: "GFX 最大時脈", @@ -221,7 +308,13 @@ extension GPUControlClockStrings { noteClockHeld: "正在維持最大時脈。選擇功率上限會先使時脈回到原廠值:kext 絕不會同時維持兩者。", switching: "正在先使功率上限回到啟動值…", outOfRangeFormat: "請選擇 %d 到 %d MHz 之間的值。", - sliderHelpFormat: "從 %1$d MHz 到原廠最大值 %2$d MHz。只會降低最大值;停止移動後傳送該值。") + sliderHelpFormat: "從 %1$d MHz 到原廠最大值 %2$d MHz。只會降低最大值;停止移動後傳送該值。", + minSection: "GFX 最小時脈", + minFieldLabel: "GFX 最小時脈(MHz)", + minStepperFormat: "GFX 最小時脈,間距 %d MHz", + minToggle: "提高最小時脈", + minFooter: "只能高於原廠值,且不超過 GFX 最大時脈;kext 會檢查每個要求。提高最小值會讓時脈在閒置時也保持較高,顯示卡耗電與溫度都會上升;GPU 過熱時 kext 會恢復原廠值。", + minSliderHelpFormat: "從原廠最小值 %1$d MHz 到 %2$d MHz。只會提高最小值;停止移動後傳送該值。") static let uk = GPUControlClockStrings( section: "Макс. частота GFX", @@ -234,5 +327,11 @@ extension GPUControlClockStrings { noteClockHeld: "Утримується макс. частота. Вибір ліміту потужності спершу поверне частоту до заводської: kext ніколи не утримує обидва.", switching: "Спершу ліміт потужності повертається до значення завантаження…", outOfRangeFormat: "Виберіть значення від %d до %d МГц.", - sliderHelpFormat: "Від %1$d МГц до заводського максимуму, %2$d МГц. Лише знижує максимум; значення надсилається, коли ви перестаєте його рухати.") + sliderHelpFormat: "Від %1$d МГц до заводського максимуму, %2$d МГц. Лише знижує максимум; значення надсилається, коли ви перестаєте його рухати.", + minSection: "Мін. частота GFX", + minFieldLabel: "Мін. частота GFX у МГц", + minStepperFormat: "Мін. частота GFX, крок %d МГц", + minToggle: "Підвищити мінімальну частоту", + minFooter: "Лише вище заводської і ніколи не вище макс. частоти GFX; kext перевіряє кожен запит. Вищий мінімум тримає частоту піднятою в простої, тож карта споживає більше й сильніше гріється; kext повертає заводські значення, якщо GPU перегрівається.", + minSliderHelpFormat: "Від заводського мінімуму, %1$d МГц, до %2$d МГц. Лише підвищує мінімум; значення надсилається, коли ви перестаєте його рухати.") } diff --git a/Sources/RyzenStatus/Core/GPUControlPageStrings.swift b/Sources/RyzenStatus/Core/GPUControlPageStrings.swift index eea3c887..68345ea1 100644 --- a/Sources/RyzenStatus/Core/GPUControlPageStrings.swift +++ b/Sources/RyzenStatus/Core/GPUControlPageStrings.swift @@ -129,6 +129,8 @@ struct GPUControlPageStrings { let zeroRpmItem: String /// %d = MHz. let gfxItemFormat: String + /// A raised GFX minimum in the held sentence (GPUSensors 0.9.0); %d = MHz. + let gfxMinItemFormat: String /// Between the held settings, and before the last one: "a, b and c". let listSeparator: String let listLastSeparator: String @@ -165,6 +167,7 @@ struct GPUControlPageStrings { if want.curve != nil { items.append(fanCurveItem) } if want.zeroRpmOff { items.append(zeroRpmItem) } if let mhz = want.gfxMaxMHz { items.append(String(format: gfxItemFormat, mhz)) } + if let mhz = want.gfxMinMHz { items.append(String(format: gfxMinItemFormat, mhz)) } // An empty hold would leave "RyzenStatus is holding " with nothing // after it: say the short form instead. guard !items.isEmpty else { return heldOD8Short } @@ -208,7 +211,7 @@ struct GPUControlPageStrings { kextVersion, channel, panelLabel, notAllowed, busy, notReady, off, closedGroup, needsAdministrator, otherVersion, unconfirmed, notOwner, settingMissing, offNotAsExpected, offChangeUnconfirmed, offDriverStopped, offWatchdog, gaveUpFormat, timedOut, notConfirmed, backToStartUp, alreadyAtStartUp, - unsafeNotPlain, unsafeNotRoot, unsafeWritable, unsafeACL, unsafeUnreadable, unsafeSignature, unsafeOtherProgram, heldOD8Format, fanCurveItem, zeroRpmItem, gfxItemFormat, + unsafeNotPlain, unsafeNotRoot, unsafeWritable, unsafeACL, unsafeUnreadable, unsafeSignature, unsafeOtherProgram, heldOD8Format, fanCurveItem, zeroRpmItem, gfxItemFormat, gfxMinItemFormat, listSeparator, listLastSeparator, unsafeSetID, heldOD8Short, closeChanges, closeChangesHelp, closedAgain, closeRefused, closeNotSupported, closedByOther, readOnlyTitle, readOnlyDetail, cardRangeFormat, floorUnknown, nothingToLower, otherProgramChanged, powerHint, openWritingHint, kextSaysFormat, noReading] @@ -325,6 +328,7 @@ extension GPUControlPageStrings { fanCurveItem: "a fan curve", zeroRpmItem: "the fan always running", gfxItemFormat: "a GFX maximum of %d MHz", + gfxMinItemFormat: "a GFX minimum of %d MHz", listSeparator: ", ", listLastSeparator: " and ", heldOD8Short: "RyzenStatus is holding OD8 settings", @@ -421,6 +425,7 @@ extension GPUControlPageStrings { fanCurveItem: "una curva de ventilador", zeroRpmItem: "el ventilador siempre girando", gfxItemFormat: "un reloj máximo de GFX de %d MHz", + gfxMinItemFormat: "un reloj mínimo de GFX de %d MHz", listSeparator: ", ", listLastSeparator: " y ", heldOD8Short: "RyzenStatus mantiene ajustes OD8", @@ -517,6 +522,7 @@ extension GPUControlPageStrings { fanCurveItem: "uma curva de ventoinha", zeroRpmItem: "a ventoinha sempre girando", gfxItemFormat: "um clock GFX máximo de %d MHz", + gfxMinItemFormat: "um clock GFX mínimo de %d MHz", listSeparator: ", ", listLastSeparator: " e ", heldOD8Short: "O RyzenStatus está mantendo ajustes OD8", @@ -613,6 +619,7 @@ extension GPUControlPageStrings { fanCurveItem: "bir fan eğrisi", zeroRpmItem: "her zaman dönen fan", gfxItemFormat: "maks. GFX saat hızı %d MHz", + gfxMinItemFormat: "min. GFX saat hızı %d MHz", listSeparator: ", ", listLastSeparator: " ve ", heldOD8Short: "RyzenStatus OD8 ayarlarını tutuyor", @@ -709,6 +716,7 @@ extension GPUControlPageStrings { fanCurveItem: "кривую вентилятора", zeroRpmItem: "постоянное вращение вентилятора", gfxItemFormat: "макс. частоту GFX %d МГц", + gfxMinItemFormat: "мин. частоту GFX %d МГц", listSeparator: ", ", listLastSeparator: " и ", heldOD8Short: "RyzenStatus удерживает настройки OD8", @@ -805,6 +813,7 @@ extension GPUControlPageStrings { fanCurveItem: "krivku ventilátora", zeroRpmItem: "ventilátor stále v chode", gfxItemFormat: "maximálny takt GFX %d MHz", + gfxMinItemFormat: "minimálny takt GFX %d MHz", listSeparator: ", ", listLastSeparator: " a ", heldOD8Short: "RyzenStatus drží nastavenia OD8", @@ -901,6 +910,7 @@ extension GPUControlPageStrings { fanCurveItem: "eine Lüfterkurve", zeroRpmItem: "den Lüfter im Dauerbetrieb", gfxItemFormat: "einen maximalen GFX-Takt von %d MHz", + gfxMinItemFormat: "einen minimalen GFX-Takt von %d MHz", listSeparator: ", ", listLastSeparator: " und ", heldOD8Short: "RyzenStatus hält OD8-Einstellungen", @@ -997,6 +1007,7 @@ extension GPUControlPageStrings { fanCurveItem: "une courbe de ventilateur", zeroRpmItem: "le ventilateur toujours en marche", gfxItemFormat: "une fréquence GFX max de %d MHz", + gfxMinItemFormat: "une fréquence GFX min de %d MHz", listSeparator: ", ", listLastSeparator: " et ", heldOD8Short: "RyzenStatus maintient des réglages OD8", @@ -1093,6 +1104,7 @@ extension GPUControlPageStrings { fanCurveItem: "una curva della ventola", zeroRpmItem: "la ventola sempre in rotazione", gfxItemFormat: "un clock GFX massimo di %d MHz", + gfxMinItemFormat: "un clock GFX minimo di %d MHz", listSeparator: ", ", listLastSeparator: " e ", heldOD8Short: "RyzenStatus mantiene impostazioni OD8", @@ -1189,6 +1201,7 @@ extension GPUControlPageStrings { fanCurveItem: "ファンカーブ", zeroRpmItem: "常に回るファン", gfxItemFormat: "GFX 最大クロック %d MHz", + gfxMinItemFormat: "GFX 最小クロック %d MHz", listSeparator: "、", listLastSeparator: "と", heldOD8Short: "RyzenStatus が OD8 設定を保持中", @@ -1285,6 +1298,7 @@ extension GPUControlPageStrings { fanCurveItem: "팬 곡선", zeroRpmItem: "항상 도는 팬", gfxItemFormat: "최대 GFX 클록 %d MHz", + gfxMinItemFormat: "최소 GFX 클록 %d MHz", listSeparator: ", ", listLastSeparator: " 및 ", heldOD8Short: "RyzenStatus가 OD8 설정을 유지 중", @@ -1381,6 +1395,7 @@ extension GPUControlPageStrings { fanCurveItem: "风扇曲线", zeroRpmItem: "始终转动的风扇", gfxItemFormat: "GFX 最大时钟频率 %d MHz", + gfxMinItemFormat: "GFX 最小时钟频率 %d MHz", listSeparator: "、", listLastSeparator: "和", heldOD8Short: "RyzenStatus 正在维持 OD8 设置", @@ -1477,6 +1492,7 @@ extension GPUControlPageStrings { fanCurveItem: "風扇曲線", zeroRpmItem: "始終轉動的風扇", gfxItemFormat: "GFX 最大時脈 %d MHz", + gfxMinItemFormat: "GFX 最小時脈 %d MHz", listSeparator: "、", listLastSeparator: "和", heldOD8Short: "RyzenStatus 正在維持 OD8 設定", @@ -1573,6 +1589,7 @@ extension GPUControlPageStrings { fanCurveItem: "криву вентилятора", zeroRpmItem: "постійне обертання вентилятора", gfxItemFormat: "макс. частоту GFX %d МГц", + gfxMinItemFormat: "мін. частоту GFX %d МГц", listSeparator: ", ", listLastSeparator: " і ", heldOD8Short: "RyzenStatus утримує налаштування OD8", diff --git a/Sources/RyzenStatus/Services/Metrics/FakeGPUControlKext.swift b/Sources/RyzenStatus/Services/Metrics/FakeGPUControlKext.swift index 378c4a3c..eceb2f28 100644 --- a/Sources/RyzenStatus/Services/Metrics/FakeGPUControlKext.swift +++ b/Sources/RyzenStatus/Services/Metrics/FakeGPUControlKext.swift @@ -77,6 +77,11 @@ final class FakeGPUControlKext: @unchecked Sendable { var od8Ready = true var stockGfxMaxMHz = 2_359 var gfxMinMHz = 500 + /// GPUSensors 0.9.0: `setOD8` also takes 14 scalars with a GFX minimum, + /// `OD8WriteState` has `Takes`, and `status` the `gfxMin` flag. The + /// minimum's range is `gfxMinMHz...gfxMinTopMHz` (500-2800 on the card). + var takesGfxMin = false + var gfxMinTopMHz = 2_800 /// The stock fan target; the last curve point must be at 100 % at or /// below this minus 22 C. var fanTargetC = 70 @@ -230,10 +235,13 @@ final class FakeGPUControlKext: @unchecked Sendable { /// The fan watchdog trips (95 C, or 75 C with the fan under 90 % for 5 s, /// or 10 s without readings): stock fan once, writing off until restart. + /// Since 0.9.0 it also watches a raised GFX minimum (95 C or no + /// readings). func tripFanWatchdog() { locked { - let curve = (od8Held & (GPUControlOD8Held.curve.rawValue | GPUControlOD8Held.unknown.rawValue)) != 0 - guard curve, od8Dirty, !tornDown, !owner.isOff else { return } + let watched = GPUControlOD8Held.curve.rawValue | GPUControlOD8Held.unknown.rawValue + | GPUControlOD8Held.gfxMin.rawValue + guard od8Held & watched != 0, od8Dirty, !tornDown, !owner.isOff else { return } if inSleep { // After the wake Owner goes back, and writing goes off then. od8OffAfterWayBack = true @@ -279,6 +287,11 @@ final class FakeGPUControlKext: @unchecked Sendable { od8State["FanCurveHeld"] = curve.map { NSNumber(value: $0.temperatureC * 1_000 + $0.speedPercent) } } if od8Dirty, let gfx = od8HeldWant.gfxMaxMHz { od8State["GfxMaxHeld"] = NSNumber(value: gfx) } + if takesGfxMin { + if od8Dirty, let low = od8HeldWant.gfxMinMHz { od8State["GfxMinHeld"] = NSNumber(value: low) } + let takes: GPUControlOD8Held = [.curve, .zeroRpmOff, .gfxMax, .gfxMin] + od8State["Takes"] = NSNumber(value: takes.rawValue) + } var all: [String: Any] = [ "Write": writeText(), "WriteState": [ @@ -358,7 +371,9 @@ final class FakeGPUControlKext: @unchecked Sendable { out[0] = GPUControlReply.badVersion.rawValue return out } - guard input.count == selector.inputCount, outputCount >= selector.outputCount else { return nil } + let countTaken = selector == .setOD8 && takesGfxMin ? selector.takes(inputCount: input.count) + : input.count == selector.inputCount + guard countTaken, outputCount >= selector.outputCount else { return nil } if var forced = forcedReplies[selector], !forced.isEmpty { let reply = forced.removeFirst() forcedReplies[selector] = forced @@ -399,11 +414,14 @@ final class FakeGPUControlKext: @unchecked Sendable { } } - /// The dispatcher's reading of `setOD8`'s 13 scalars; nil is malformed. - /// The clock's wire bound: 5000 MHz in 0.7.2, the 32-bit field in 0.8.0. + /// The dispatcher's reading of `setOD8`'s 13 scalars (or 14 with a GFX + /// minimum, 0.9.0); nil is malformed. The clock's wire bound: 5000 MHz in + /// 0.7.2, the 32-bit field in 0.8.0. private static func want(from input: [UInt64], maxGfxMHz: UInt64) -> GPUControlOD8Want? { let flags = input[1] - guard flags & ~(GPUControlWire.wantCurve | GPUControlWire.wantZeroRpmOff) == 0, input[12] <= maxGfxMHz else { + let low = input.count > 13 ? input[13] : 0 + guard flags & ~(GPUControlWire.wantCurve | GPUControlWire.wantZeroRpmOff) == 0, input[12] <= maxGfxMHz, + low <= 0x7FFF_FFFF else { return nil } let curve = flags & GPUControlWire.wantCurve != 0 @@ -415,7 +433,8 @@ final class FakeGPUControlKext: @unchecked Sendable { } return GPUControlOD8Want(curve: curve ? points : nil, zeroRpmOff: flags & GPUControlWire.wantZeroRpmOff != 0, - gfxMaxMHz: input[12] == 0 ? nil : Int(input[12])) + gfxMaxMHz: input[12] == 0 ? nil : Int(input[12]), + gfxMinMHz: low == 0 ? nil : Int(low)) } // MARK: The kext's calls @@ -597,6 +616,9 @@ final class FakeGPUControlKext: @unchecked Sendable { if let gfx = want.gfxMaxMHz, gfx < GPUControlWire.gfxFloorMHz || gfx > stockGfxMaxMHz || gfx < gfxMinMHz { return .gfxRange } + if let low = want.gfxMinMHz, low < gfxMinMHz || low > gfxMinTopMHz || low > (want.gfxMaxMHz ?? stockGfxMaxMHz) { + return .gfxMinRange + } return .ok } @@ -618,6 +640,7 @@ final class FakeGPUControlKext: @unchecked Sendable { private func statusScalars(client: UInt64) -> [UInt64] { var flags: GPUControlFlags = [] if od8Ready { flags.insert(.od8Ready) } + if takesGfxMin { flags.insert(.gfxMin) } if owner.isArmed { flags.insert(.armed) } if owner.isOff || owner.isReadOnly { flags.insert(.off) } if sleepingLocked { flags.insert(.sleeping) } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlChannel.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlChannel.swift index 59c5b66c..1d3844d5 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlChannel.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlChannel.swift @@ -117,7 +117,7 @@ final class KextGPUControlChannel: GPUControlChannel, @unchecked Sendable { func call(_ selector: GPUControlWire.Selector, input: [UInt64], outputCount: Int) -> [UInt64]? { // The kext refuses a wrong count anyway; refusing it here keeps a // mistake in this app from reaching the kernel at all. - guard input.count == selector.inputCount else { return nil } + guard selector.takes(inputCount: input.count) else { return nil } state.lock() guard connection != 0, outputCount > 0 else { state.unlock() diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift index 4ce0bfa8..ba9823c7 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift @@ -242,8 +242,17 @@ final class GPUControlEngine { chooseOD8(want) } - /// The whole OD8 state with the fan changed: the GFX maximum that is held - /// or asked for goes with it. + /// The whole OD8 state with the GFX minimum changed (GPUSensors 0.9.0): + /// the fan state and the GFX maximum that are held or asked for go with + /// it. + func chooseGfxMin(_ mhz: Int?) { + var want = od8Basis + want.gfxMinMHz = mhz + chooseOD8(want) + } + + /// The whole OD8 state with the fan changed: the GFX clocks that are held + /// or asked for go with it. func chooseFan(curve: [GPUControlFanPoint]?, zeroRpmOff: Bool) { var want = od8Basis want.curve = curve @@ -839,6 +848,8 @@ final class GPUControlController: @unchecked Sendable { func chooseGfxMax(_ mhz: Int?) { queue.async { [self] in engine.chooseGfxMax(mhz); run() } } + func chooseGfxMin(_ mhz: Int?) { queue.async { [self] in engine.chooseGfxMin(mhz); run() } } + func chooseFan(curve: [GPUControlFanPoint]?, zeroRpmOff: Bool) { queue.async { [self] in engine.chooseFan(curve: curve, zeroRpmOff: zeroRpmOff); run() } } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift index a64c534e..6273b2d2 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift @@ -43,8 +43,11 @@ enum GPUControlCurveRules { /// source. GPUSensors 0.8.0 ("080"): its `od8CheckWant` gives the same /// answers as 0.7.2's for every line of `curve-cases.jsonl`, and its /// source is GPU/sensors/kext in this repository. GPUSensors 0.8.1 - /// ("081") leaves these checks as they were in 0.8.0. - static let checkedReleases: Set = ["080", "081"] + /// ("081") leaves these checks as they were in 0.8.0. GPUSensors 0.9.0 + /// ("090") adds the GFX minimum (`GfxMinRange`) and gives the same + /// answers as 0.8.0 for the first 100 lines of `curve-cases.jsonl`; the + /// lines after them are its GFX minimum cases. + static let checkedReleases: Set = ["080", "081", "090"] /// The kext build is one this copy was checked against. Neither the /// editor nor a remembered fan state sends anything to another build. @@ -223,6 +226,14 @@ enum GPUControlCurveRules { let top = Swift.min(s.first[gfxMax].def, s.fresh[gfxMax].def) if mhz < gfxFloorMHz || mhz > top || mhz < s.first[gfxMin].def { return Result(check: .gfxRange) } } + // GPUSensors 0.9.0: the minimum in the card's range for id 1 (the + // same in both reads, checked above) and never above the maximum of + // the same state. + if let low = want.gfxMinMHz { + let range = s.fresh[gfxMin] + let top = want.gfxMaxMHz ?? Swift.min(s.first[gfxMax].def, s.fresh[gfxMax].def) + if low < range.min || low > range.max || low > top { return Result(check: .gfxMinRange) } + } return .ok } } @@ -297,6 +308,6 @@ struct GPUControlFanDraft: Equatable, Sendable { /// the start-up values): it is the stock fan over a held fan state, with /// no clock held. func givesBack(_ held: GPUControlOD8Want) -> Bool { - want.isStock && (held.curve != nil || held.zeroRpmOff) && held.gfxMaxMHz == nil + want.isStock && (held.curve != nil || held.zeroRpmOff) && held.gfxMaxMHz == nil && held.gfxMinMHz == nil } } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift index 129c25b6..2771fdcd 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift @@ -424,6 +424,8 @@ enum GPUControlRemembered: Equatable, Sendable { var want = GPUControlOD8Want(zeroRpmOff: defaults.bool(forKey: DefaultsKey.gpuControlRememberedZeroRpmOff)) let mhz = defaults.integer(forKey: DefaultsKey.gpuControlRememberedGfxMHz) if mhz > 0 { want.gfxMaxMHz = mhz } + let low = defaults.integer(forKey: DefaultsKey.gpuControlRememberedGfxMinMHz) + if low > 0 { want.gfxMinMHz = low } if let flat = defaults.array(forKey: DefaultsKey.gpuControlRememberedCurve) as? [Int] { guard flat.count == 2 * GPUControlWire.fanCurvePoints else { return .nothing } want.curve = stride(from: 0, to: flat.count, by: 2).map { @@ -441,6 +443,7 @@ enum GPUControlRemembered: Equatable, Sendable { defaults.removeObject(forKey: DefaultsKey.gpuControlRememberedCurve) defaults.removeObject(forKey: DefaultsKey.gpuControlRememberedZeroRpmOff) defaults.removeObject(forKey: DefaultsKey.gpuControlRememberedGfxMHz) + defaults.removeObject(forKey: DefaultsKey.gpuControlRememberedGfxMinMHz) switch self { case .nothing: defaults.set("none", forKey: DefaultsKey.gpuControlRememberedKind) @@ -455,6 +458,7 @@ enum GPUControlRemembered: Equatable, Sendable { } defaults.set(want.zeroRpmOff, forKey: DefaultsKey.gpuControlRememberedZeroRpmOff) if let mhz = want.gfxMaxMHz { defaults.set(mhz, forKey: DefaultsKey.gpuControlRememberedGfxMHz) } + if let low = want.gfxMinMHz { defaults.set(low, forKey: DefaultsKey.gpuControlRememberedGfxMinMHz) } } } } @@ -488,9 +492,13 @@ enum GPUControlRememberPolicy { /// RPM) goes out only to a build the curve rules were checked against, as /// with "Apply curve" (none given: no fan state). A clock alone does not /// depend on them, as on the page. + /// `gfxMin`: the GFX minimum the kext takes now (`GPUControlClockMinLogic + /// .limits`), nil when it takes none (a kext before 0.9.0): a remembered + /// minimum outside it is left out of the request, like the maximum. static func request(remembered: GPUControlRemembered, active: Bool, facts: GPUControlFacts?, stopped: GPUControlStop?, - stockGfxMaxMHz: Int? = nil, kextVersion: String? = nil) -> GPUControlRequest? { + stockGfxMaxMHz: Int? = nil, kextVersion: String? = nil, + gfxMin: GPUControlClockMinLogic.Limits? = nil) -> GPUControlRequest? { guard active, stopped == nil, let facts, facts.armed, !facts.off, facts.writeOffCode == 0, !(facts.owned && !facts.mine) else { return nil } switch remembered { @@ -510,6 +518,7 @@ enum GPUControlRememberPolicy { if let mhz = want.gfxMaxMHz, !GPUControlClockLogic.lowers(mhz, stockGfxMaxMHz: stockGfxMaxMHz) { want.gfxMaxMHz = nil } + want = GPUControlClockMinLogic.checked(want, limits: gfxMin, stockGfxMaxMHz: stockGfxMaxMHz) return want.isStock ? nil : .od8(want) } } @@ -575,13 +584,94 @@ enum GPUControlClockLogic { } } +// MARK: - The GFX minimum clock (GPUSensors 0.9.0) + +/// The minimum clock control's numbers. The range is the card's stock +/// minimum (OD8 id 1, 500 MHz on the test card; the way back, never a hold) +/// up to the GFX maximum of the same state: the lowered maximum held or +/// asked for, else the stock maximum, and never past the card's own top for +/// id 1. The kext takes the same and nothing else (`GfxMinRange`). Only +/// offered when the kext publishes `Takes` with the GFX minimum. +enum GPUControlClockMinLogic { + static let step = 10 + static let tickStepMHz = 100 + + /// The card's range for the minimum, and its stock value. + struct Limits: Equatable, Sendable { + var min: Int + var max: Int + var stock: Int + } + + /// Nil when the kext takes no minimum (before 0.9.0), OD8 is not read + /// cleanly, or the table has no usable GFX pair. + static func limits(writing: GPUControlStatus.Writing?, od8Ready: Bool) -> Limits? { + guard od8Ready, writing?.od8State?.takesGfxMin == true, let m = writing?.od8?.gfxMin else { return nil } + return Limits(min: m.min, max: m.max, stock: m.stock) + } + + /// The control's range: stock up to the GFX maximum in force. Nil when + /// there is nothing above stock to choose. + static func range(limits: Limits?, gfxMaxMHz: Int?) -> ClosedRange? { + guard let limits, let gfxMaxMHz else { return nil } + let top = Swift.min(gfxMaxMHz, limits.max) + let bottom = Swift.max(limits.stock, limits.min) + guard top > bottom else { return nil } + return bottom...top + } + + /// A value the control may send as a hold: above stock, inside the range. + static func raises(_ mhz: Int, range: ClosedRange?) -> Bool { + guard let range else { return false } + return mhz > range.lowerBound && mhz <= range.upperBound + } + + /// What choosing `mhz` asks for: nil (the stock minimum, the way back) at + /// or below the stock value, else the value. + static func request(_ mhz: Int, stockMHz: Int) -> Int? { + mhz <= stockMHz ? nil : mhz + } + + /// A slider position as a value: 10 MHz steps from the stock minimum, + /// the top of the range when it is not on a step. + static func snapped(_ raw: Double, range: ClosedRange) -> Int { + let floor = range.lowerBound + let value = floor + Int(((raw - Double(floor)) / Double(step)).rounded()) * step + if value >= range.upperBound - step / 2 { return range.upperBound } + return Swift.max(floor, value) + } + + /// The slider's tick marks, one every 100 MHz from the stock minimum. + static func tickCount(range: ClosedRange) -> Int { + (range.upperBound - range.lowerBound) / tickStepMHz + 1 + } + + /// A state with its minimum checked against what the kext takes now: + /// left out when the kext takes none, or when it is not above stock or + /// passes the GFX maximum of the state (the lowered one, else the stock + /// maximum of the moment). The rest of the state is kept. + static func checked(_ want: GPUControlOD8Want, limits: Limits?, stockGfxMaxMHz: Int?) -> GPUControlOD8Want { + guard let low = want.gfxMinMHz else { return want } + var want = want + let range = range(limits: limits, gfxMaxMHz: want.gfxMaxMHz ?? stockGfxMaxMHz) + if !raises(low, range: range) { want.gfxMinMHz = nil } + return want + } +} + extension GPUControlRememberPolicy { /// A remembered request again, right before it goes out: a clock that no /// longer lowers the stock maximum of the moment is left out (the rest - /// of the fan state still goes). Nil when nothing is left to ask. - static func checkedAgain(_ request: GPUControlRequest, stockGfxMaxMHz: Int?) -> GPUControlRequest? { - guard case .od8(var want) = request, let mhz = want.gfxMaxMHz else { return request } - if !GPUControlClockLogic.lowers(mhz, stockGfxMaxMHz: stockGfxMaxMHz) { want.gfxMaxMHz = nil } + /// of the fan state still goes), and so is a minimum the kext does not + /// take now (`gfxMin` nil: a kext before 0.9.0, or no clean OD8 read). + /// Nil when nothing is left to ask. + static func checkedAgain(_ request: GPUControlRequest, stockGfxMaxMHz: Int?, + gfxMin: GPUControlClockMinLogic.Limits? = nil) -> GPUControlRequest? { + guard case .od8(var want) = request else { return request } + if let mhz = want.gfxMaxMHz, !GPUControlClockLogic.lowers(mhz, stockGfxMaxMHz: stockGfxMaxMHz) { + want.gfxMaxMHz = nil + } + want = GPUControlClockMinLogic.checked(want, limits: gfxMin, stockGfxMaxMHz: stockGfxMaxMHz) return want.isStock ? nil : .od8(want) } } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift index e22e1d8d..8217b4e5 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift @@ -125,7 +125,10 @@ final class GPUControlService: ObservableObject { let model = fake controller.setReaskFilter { request in let control = model.flatMap(GPUControlService.fakeControl) ?? GPUSensorsService.shared.currentControl() - return GPUControlRememberPolicy.checkedAgain(request, stockGfxMaxMHz: control?.writing?.od8?.stockGfxMaxMHz) + let od8Ready = control?.writing?.od8Read == .read + return GPUControlRememberPolicy.checkedAgain( + request, stockGfxMaxMHz: control?.writing?.od8?.stockGfxMaxMHz, + gfxMin: GPUControlClockMinLogic.limits(writing: control?.writing, od8Ready: od8Ready)) } controller.start() self.controller = controller @@ -171,6 +174,12 @@ final class GPUControlService: ObservableObject { controller?.chooseGfxMax(mhz) } + /// The minimum clock control (GPUSensors 0.9.0): a raised GFX minimum, + /// or nil for the stock one. The rest of a held OD8 state goes with it. + func chooseGfxMin(_ mhz: Int?) { + controller?.chooseGfxMin(mhz) + } + func backToStartUp() { controller?.choose(.startUp) } @@ -416,7 +425,9 @@ final class GPUControlService: ObservableObject { if let request = GPUControlRememberPolicy.request(remembered: remembered, active: rememberActive, facts: facts, stopped: snapshot?.stopped, stockGfxMaxMHz: control?.writing?.od8?.stockGfxMaxMHz, - kextVersion: control?.writing?.kextVersion) { + kextVersion: control?.writing?.kextVersion, + gfxMin: GPUControlClockMinLogic.limits( + writing: control?.writing, od8Ready: facts.od8Ready)) { controller.choose(request, origin: .remembered) } } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlWire.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlWire.swift index 4dc6b4a9..07a585b2 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlWire.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlWire.swift @@ -9,8 +9,9 @@ import Foundation /// (selectors, replies, the status layout, its flags) and `kern_service.cpp` /// (the counts each call takes). 0.8.0 keeps version 2 and only adds: the /// `disarm` selector, two replies, one `WriteOff` reason and the card's own -/// power range (`PowerRange`, read from the properties). Nothing here talks -/// to the kext. +/// power range (`PowerRange`, read from the properties). 0.9.0 keeps it too +/// and adds the GFX minimum clock: a 14-scalar `setOD8`, one OD8 refusal, +/// one held bit and one status flag. Nothing here talks to the kext. enum GPUControlWire { /// The first scalar of every call. A kext that speaks another version /// answers `badVersion` and nothing else. @@ -29,7 +30,7 @@ enum GPUControlWire { /// still needs `arm`. A 0.7.x kext does not know it: the call fails. case disarm = 6 - /// Scalars in, the version included. + /// Scalars in, the version included; for `setOD8` its 0.7.0 form. var inputCount: Int { switch self { case .set: return 2 @@ -38,6 +39,13 @@ enum GPUControlWire { } } + /// Whether the kext takes this many scalars: `setOD8` also takes the + /// 14 of kext 0.9.0, which carry a GFX minimum. + func takes(inputCount count: Int) -> Bool { + self == .setOD8 ? count == GPUControlWire.setOD8InputCount + || count == GPUControlWire.setOD8InputCountGfxMin : count == inputCount + } + /// Scalars out, the reply first. var outputCount: Int { switch self { @@ -51,6 +59,9 @@ enum GPUControlWire { static let statusCount = 13 /// `{version, flags, t1..t5, s1..s5, gfxMaxMHz}`. static let setOD8InputCount = 13 + /// The same and `gfxMinMHz` (kext 0.9.0). Sent only with a GFX minimum: + /// an older kext refuses this count. + static let setOD8InputCountGfxMin = 14 static let fanCurvePoints = 5 /// `set` and `setOD8` wait this long for the kext's worker. @@ -155,6 +166,9 @@ enum GPUControlOD8Check: UInt64, CaseIterable, Sendable { case curveCooling = 9 case gfxRange = 10 case noReadings = 11 + /// 0.9.0: the GFX minimum is outside the card's range for it, or above + /// the GFX maximum of the same state. + case gfxMinRange = 12 /// `od8CheckText`. var kextText: String { @@ -171,6 +185,7 @@ enum GPUControlOD8Check: UInt64, CaseIterable, Sendable { case .curveCooling: return "the curve gives less air than stock somewhere" case .gfxRange: return "GFX max must be between 1500 MHz and the stock maximum" case .noReadings: return "the fan watchdog has no fresh hotspot and fan readings" + case .gfxMinRange: return "GFX min must be in the card's range and not above GFX max" } } } @@ -241,6 +256,8 @@ struct GPUControlFlags: OptionSet, Hashable, Sendable { static let ready = GPUControlFlags(rawValue: 128) /// OD8 was read cleanly since boot: `setOD8` can work. static let od8Ready = GPUControlFlags(rawValue: 256) + /// `setOD8` takes a GFX minimum (kext 0.9.0). + static let gfxMin = GPUControlFlags(rawValue: 512) } /// What the confirmed OD8 state changes (`kOd8Held*`). @@ -252,6 +269,8 @@ struct GPUControlOD8Held: OptionSet, Hashable, Sendable { static let gfxMax = GPUControlOD8Held(rawValue: 4) /// Not confirmed at stock: a failed call, or one the GPU did not take. static let unknown = GPUControlOD8Held(rawValue: 8) + /// A raised GFX minimum (kext 0.9.0). + static let gfxMin = GPUControlOD8Held(rawValue: 16) } /// The 13 scalars `status` returns, in the kext's order (`StatusField`). @@ -343,7 +362,7 @@ struct GPUControlFanPoint: Equatable, Hashable, Sendable { } /// The whole OD8 state a program wants, never one setting: the kext takes -/// the fan curve, zero RPM and the GFX maximum clock together in every call, +/// the fan curve, zero RPM and the GFX clock pair together in every call, /// so a request that left one out would put that one back to stock. struct GPUControlOD8Want: Equatable, Hashable, Sendable { /// Five points, or nil for the stock fan. @@ -352,11 +371,13 @@ struct GPUControlOD8Want: Equatable, Hashable, Sendable { var zeroRpmOff = false /// A lower GFX maximum clock in MHz, or nil for stock. var gfxMaxMHz: Int? + /// A raised GFX minimum clock in MHz, or nil for stock (kext 0.9.0). + var gfxMinMHz: Int? static let stock = GPUControlOD8Want() /// The stock state is the way back, never a change (`od8IsStock`). - var isStock: Bool { curve == nil && !zeroRpmOff && gfxMaxMHz == nil } + var isStock: Bool { curve == nil && !zeroRpmOff && gfxMaxMHz == nil && gfxMinMHz == nil } /// What `status` reports while this state is held (`od8HeldFlags`). var heldFlags: GPUControlOD8Held { @@ -364,17 +385,20 @@ struct GPUControlOD8Want: Equatable, Hashable, Sendable { if curve != nil { held.insert(.curve) } if zeroRpmOff { held.insert(.zeroRpmOff) } if gfxMaxMHz != nil { held.insert(.gfxMax) } + if gfxMinMHz != nil { held.insert(.gfxMin) } return held } - /// The 13 scalars of `setOD8` for this state, as `gpucontrol` builds - /// them: without a curve its ten entries are 0, and a stock clock is 0. - /// Nil when the state cannot be written as scalars at all (a curve that - /// is not five points, a negative number, a clock of 0 that would read as - /// "stock"). Every other value goes out unchanged: the kext decides, and - /// the app never clamps. + /// The scalars of `setOD8` for this state, as `gpucontrol` builds them: + /// 13, or 14 with a GFX minimum (kext 0.9.0); without a curve its ten + /// entries are 0, and a stock clock is 0. Nil when the state cannot be + /// written as scalars at all (a curve that is not five points, a + /// negative number, a clock of 0 that would read as "stock"). Every + /// other value goes out unchanged: the kext decides, and the app never + /// clamps. func scalars() -> [UInt64]? { - var input = [UInt64](repeating: 0, count: GPUControlWire.setOD8InputCount) + let count = gfxMinMHz == nil ? GPUControlWire.setOD8InputCount : GPUControlWire.setOD8InputCountGfxMin + var input = [UInt64](repeating: 0, count: count) input[0] = GPUControlWire.channelVersion input[1] = (curve != nil ? GPUControlWire.wantCurve : 0) | (zeroRpmOff ? GPUControlWire.wantZeroRpmOff : 0) if let curve { @@ -389,6 +413,10 @@ struct GPUControlOD8Want: Equatable, Hashable, Sendable { guard gfxMaxMHz > 0 else { return nil } input[12] = UInt64(gfxMaxMHz) } + if let gfxMinMHz { + guard gfxMinMHz > 0 else { return nil } + input[13] = UInt64(gfxMinMHz) + } return input } } @@ -462,7 +490,8 @@ enum GPUControlTextGroup: CaseIterable, Sendable { case .ok: return nil case .notRead, .drifted, .memoryMoved: return .notReady case .noFeature, .noReadings: return .settingMissing - case .curveRange, .curveOrder, .curveFirst, .curveLast, .curveCooling, .gfxRange: return .notAllowed + case .curveRange, .curveOrder, .curveFirst, .curveLast, .curveCooling, .gfxRange, .gfxMinRange: + return .notAllowed } } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlWriteProperties.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlWriteProperties.swift index fad60293..c72ba462 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlWriteProperties.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlWriteProperties.swift @@ -67,6 +67,14 @@ extension GPUControlStatus { var fanCurveHeld: [GPUControlFanPoint]? /// The GFX maximum held now in MHz, nil at stock. var gfxMaxHeld: Int? + /// The GFX minimum held now in MHz, nil at stock (kext 0.9.0). + var gfxMinHeld: Int? = nil + /// `Takes`: what `setOD8` takes, in held bits (kext 0.9.0); nil + /// from an older kext, which takes no GFX minimum. + var takes: GPUControlOD8Held? = nil + + /// The kext takes a GFX minimum (0.9.0 publishes `Takes`). + var takesGfxMin: Bool { takes?.contains(.gfxMin) == true } } /// `OD8State`: whether the kext read OD8 since boot. @@ -120,6 +128,17 @@ extension GPUControlStatus { guard let setting = settings["GfxMaxMHz"], setting.feature == 0x1 else { return nil } return Swift.min(setting.stock, setting.defaultNow) } + + /// The GFX minimum's range and stock value (OD8 id 1), from the + /// card's own table: the kext takes a minimum in `min...max`, + /// never above the GFX maximum of the same state. Nil unless both + /// GFX entries have feature 0x1 (the kext refuses every OD8 call + /// otherwise). + var gfxMin: (min: Int, max: Int, stock: Int)? { + guard stockGfxMaxMHz != nil, let setting = settings["GfxMinMHz"], setting.feature == 0x1, + setting.min <= setting.max else { return nil } + return (setting.min, setting.max, setting.stock) + } } /// `Write`, as the kext wrote it. @@ -254,7 +273,9 @@ extension GPUControlStatus.Writing.OD8State { changes: c("Changes"), reverts: c("Reverts"), lastCheck: n("LastCheck"), lastCheckText: GPUControlStatus.text(dict["LastCheckText"]), sentPower: c("SentPower"), fanCurveHeld: GPUControlStatus.fanCurvePacked(dict["FanCurveHeld"]), - gfxMaxHeld: n("GfxMaxHeld").flatMap { $0 > 0 ? $0 : nil }) + gfxMaxHeld: n("GfxMaxHeld").flatMap { $0 > 0 ? $0 : nil }, + gfxMinHeld: n("GfxMinHeld").flatMap { $0 > 0 ? $0 : nil }, + takes: n("Takes").map { GPUControlOD8Held(rawValue: UInt64($0)) }) } } diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlClockMinSection.swift b/Sources/RyzenStatus/UI/Settings/GPUControlClockMinSection.swift new file mode 100644 index 00000000..cc902b55 --- /dev/null +++ b/Sources/RyzenStatus/UI/Settings/GPUControlClockMinSection.swift @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 RyzenStatus + +import AppKit +import SwiftUI + +/// The GFX minimum clock section of Settings > GPU control (GPUSensors +/// 0.9.0), built like the maximum's (`GPUControlClockSection`): a switch, +/// then a slider from the stock minimum to the GFX maximum in force, with a +/// field and a stepper. Only ever higher than stock and never above the +/// maximum; the page shows it only when the kext takes a minimum. +struct GPUControlClockMinSection: View { + let input: GPUControlPageInput + let strings: GPUControlPageStrings + let clock: GPUControlClockStrings + /// The section that asked last, so a refusal shows next to its control. + @Binding var lastOD8Source: GPUControlOD8Source + let choose: (Int?) -> Void + + @State private var on: Bool + @State private var draft: Int + @State private var fieldText = "" + @State private var outOfRange = false + + init(input: GPUControlPageInput, strings: GPUControlPageStrings, clock: GPUControlClockStrings, + lastOD8Source: Binding, choose: @escaping (Int?) -> Void) { + self.input = input + self.strings = strings + self.clock = clock + _lastOD8Source = lastOD8Source + self.choose = choose + let held = Self.heldMHz(input) + _on = State(initialValue: held != nil) + _draft = State(initialValue: held ?? Self.limits(input)?.stock ?? 0) + } + + private static func heldMHz(_ input: GPUControlPageInput) -> Int? { + if case .heldByApp(.od8(let want))? = input.state { return want.gfxMinMHz } + return nil + } + + private static func limits(_ input: GPUControlPageInput) -> GPUControlClockMinLogic.Limits? { + GPUControlClockMinLogic.limits(writing: input.writing, od8Ready: input.facts?.od8Ready == true) + } + + /// The page shows this section only when the kext takes a minimum. + static func shows(_ input: GPUControlPageInput) -> Bool { limits(input) != nil } + + /// The GFX maximum in force: the lowered one the app holds, else stock. + static func topMHz(_ input: GPUControlPageInput) -> Int? { + if case .heldByApp(.od8(let want))? = input.state, let mhz = want.gfxMaxMHz { return mhz } + return input.writing?.od8?.stockGfxMaxMHz + } + + private var range: ClosedRange? { + GPUControlClockMinLogic.range(limits: Self.limits(input), gfxMaxMHz: Self.topMHz(input)) + } + private var stock: Int? { Self.limits(input)?.stock } + + private var enabled: Bool { usable && !input.isPending } + + /// As the maximum's: the slider stays usable while its own request + /// waits (a11y A3). + private var usable: Bool { + range != nil && input.canChoose && (input.state?.acceptsChoices ?? false) + } + + var body: some View { + Section { + Toggle(clock.minToggle, isOn: Binding(get: { on }, set: { switched($0) })) + .toggleStyle(.switch) + .controlSize(.regular) + .disabled(!enabled) + if range == nil { + Label(strings.od8NotRead, systemImage: "info.circle") + .foregroundStyle(.secondary) + } else if on, let range, let stock { + clockRow(range: range, stock: stock) + } + if case .heldByApp(.power)? = input.state { + Label(clock.notePowerHeld, systemImage: "info.circle") + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + if lastOD8Source == .clockMin, case .switching(.od8)? = input.snapshot?.activity { + Label(clock.switching, systemImage: "clock") + .foregroundStyle(.secondary) + } + if outOfRange, let range { + GPUControlProblemLabel(text: String(format: clock.outOfRangeFormat, range.lowerBound, range.upperBound), + isProblem: true) + } + if let note = refusal { + VStack(alignment: .leading, spacing: 2) { + GPUControlProblemLabel(text: note.sentence, isProblem: true) + if let kext = note.kextText { + Text(String(format: strings.kextSaysFormat, kext)) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + } + } header: { + Text(clock.minSection) + } footer: { + Text(clock.minFooter) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .onChange(of: draft) { _, value in fieldText = "\(value)" } + // What is held changed on its own: the switch and the value follow + // it, unless a request still waits. + .onChange(of: Self.heldMHz(input)) { _, held in + guard !input.isPending else { return } + on = held != nil + draft = held ?? stock ?? draft + } + .onAppear { fieldText = "\(draft)" } + } + + private var refusal: GPUControlPageNote? { + guard lastOD8Source == .clockMin, case .refused(let request, _)? = input.snapshot?.outcome, + request.isOD8 else { return nil } + return GPUControlPageNote.make(input.snapshot, strings) + } + + // MARK: The row + + /// VoiceOver's names for the row's three controls, each its own + /// ("VoiceOver": alternative labels for all key interface elements). + static func accessibilityNames(_ clock: GPUControlClockStrings) -> (slider: String, field: String, stepper: String) { + (clock.minSection, clock.minFieldLabel, String(format: clock.minStepperFormat, GPUControlClockMinLogic.step)) + } + + private func clockRow(range: ClosedRange, stock: Int) -> some View { + let names = Self.accessibilityNames(clock) + let reason = GPUControlPageContent.disabledReason(input, strings) + let slider = GPUControlTickSlider(value: draft, range: range, + ticks: GPUControlClockMinLogic.tickCount(range: range), + label: names.slider, + help: Self.sliderHelp(clock, range: range), + valueDescription: GPUControlPageContent.accessibilityValue( + "\(draft) MHz", reason: usable ? nil : reason, strings), + onChange: { draft = GPUControlClockMinLogic.snapped($0, range: range) }, + onRelease: { send(draft, stock: stock) }) + let entry = HStack(spacing: 8) { + TextField(names.field, text: $fieldText) + .labelsHidden() + .multilineTextAlignment(.trailing) + .frame(minWidth: 56) + .fixedSize(horizontal: true, vertical: false) + .onSubmit { commitField(range: range, stock: stock) } + .accessibilityLabel(names.field) + Stepper(names.stepper, value: Binding(get: { draft }, set: { value in + draft = Swift.min(Swift.max(value, range.lowerBound), range.upperBound) + send(draft, stock: stock) + }), in: range, step: GPUControlClockMinLogic.step) + .labelsHidden() + .accessibilityLabel(names.stepper) + .accessibilityValue(GPUControlPageContent.accessibilityValue( + "\(draft) MHz", reason: enabled ? nil : reason, strings)) + Text("MHz").foregroundStyle(.secondary) + } + .disabled(!enabled) + return VStack(alignment: .leading, spacing: 4) { + ViewThatFits(in: .horizontal) { + HStack(spacing: 8) { + slider.frame(minWidth: GPUControlClockSection.sliderMinWidth).disabled(!usable) + entry + } + VStack(alignment: .trailing, spacing: 4) { + slider.disabled(!usable) + entry + } + } + // Stock at the leading end, where the slider starts. + HStack { + Text(String(format: clock.stockFormat, range.lowerBound)) + Spacer() + Text(verbatim: "\(range.upperBound) MHz") + } + .font(.caption) + .foregroundStyle(.secondary) + } + } + + /// The slider's help: its two ends, as written under it, and what + /// moving it does. + static func sliderHelp(_ clock: GPUControlClockStrings, range: ClosedRange) -> String { + String(format: clock.minSliderHelpFormat, range.lowerBound, range.upperBound) + } + + // MARK: Sending + + private func switched(_ value: Bool) { + on = value + outOfRange = false + // Turning it on shows the control and sends nothing: the stock + // minimum is not a hold. Turning it off puts the stock minimum back, + // keeping the rest of a held OD8 state in the same request. + if !value { + lastOD8Source = .clockMin + choose(nil) + if let stock { draft = stock } + } + } + + private func commitField(range: ClosedRange, stock: Int) { + // Outside the range: not sent and not clamped; the field says what + // it takes. + guard let value = Int(fieldText.trimmingCharacters(in: .whitespaces)), range.contains(value) else { + outOfRange = true + return + } + draft = value + send(value, stock: stock) + } + + private func send(_ value: Int, stock: Int) { + outOfRange = false + lastOD8Source = .clockMin + choose(GPUControlClockMinLogic.request(value, stockMHz: stock)) + } +} diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlClockSection.swift b/Sources/RyzenStatus/UI/Settings/GPUControlClockSection.swift index 90587736..a765b948 100644 --- a/Sources/RyzenStatus/UI/Settings/GPUControlClockSection.swift +++ b/Sources/RyzenStatus/UI/Settings/GPUControlClockSection.swift @@ -239,6 +239,8 @@ struct GPUControlClockSection: View { enum GPUControlOD8Source: Equatable { case fan case clock + /// The GFX minimum (GPUSensors 0.9.0). + case clockMin } /// A native slider with tick marks (SwiftUI's has none on macOS) that diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift b/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift index c0acd903..c48155fb 100644 --- a/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift +++ b/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift @@ -32,6 +32,7 @@ struct GPUControlSettingsView: View { }, applyFan: { service.applyFan($0) }, chooseGfxMax: { service.chooseGfxMax($0) }, + chooseGfxMin: { service.chooseGfxMin($0) }, closeChanges: { service.closeChanges() })) // Reads once a second only while the page is on screen. .settingsPageActivity(.gpuControl, @@ -98,6 +99,7 @@ struct GPUControlPageActions { var setBootArm: (Bool) -> Void = { _ in } var applyFan: (GPUControlFanDraft) -> Void = { _ in } var chooseGfxMax: (Int?) -> Void = { _ in } + var chooseGfxMin: (Int?) -> Void = { _ in } var closeChanges: () -> Void = {} } @@ -243,6 +245,11 @@ struct GPUControlPageContent: View { GPUControlClockSection(input: input, strings: strings, clock: clock, lastOD8Source: $lastOD8Source, choose: actions.chooseGfxMax) } + // Right under the maximum: the two ends of the same clock range. + if showsPower, GPUControlClockMinSection.shows(input) { + GPUControlClockMinSection(input: input, strings: strings, clock: clock, + lastOD8Source: $lastOD8Source, choose: actions.chooseGfxMin) + } if case .closed? = input.state { armSection } if Self.showsBootArm(input) { bootArmSection } rememberSection diff --git a/Tests/Fixtures/GPUSensors/curve-cases.jsonl b/Tests/Fixtures/GPUSensors/curve-cases.jsonl index 74ba7346..b8d5e09f 100644 --- a/Tests/Fixtures/GPUSensors/curve-cases.jsonl +++ b/Tests/Fixtures/GPUSensors/curve-cases.jsonl @@ -98,3 +98,23 @@ {"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0},"muts":[{"kind":"bothEntry","id":12,"field":"def","value":40}],"check":0} {"want":{"curve":true,"temp":[30,40,44,46,48],"speed":[20,36,52,68,100],"zeroRpmOff":false,"gfx":0},"muts":[{"kind":"bothEntry","id":0,"field":"feature","value":0}],"check":4} {"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0},"muts":[{"kind":"firstEntry","id":0,"field":"feature","value":0}],"check":2} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":500},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":501},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":1500},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":2000},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":2358},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":2359},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":499},"muts":[],"check":12} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":2360},"muts":[],"check":12} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":2800},"muts":[],"check":12} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":2801},"muts":[],"check":12} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2000,"gfxMin":2000},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2000,"gfxMin":2001},"muts":[],"check":12} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":1400,"gfxMin":1000},"muts":[],"check":10} +{"want":{"curve":true,"temp":[30,40,44,46,48],"speed":[20,36,52,68,100],"zeroRpmOff":true,"gfx":2300,"gfxMin":1800},"muts":[],"check":0} +{"want":{"curve":true,"temp":[30,40,44,46,48],"speed":[20,36,52,68,100],"zeroRpmOff":true,"gfx":2300,"gfxMin":2301},"muts":[],"check":12} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":2350},"muts":[{"kind":"freshEntry","id":0,"field":"def","value":2340}],"check":12} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":2340},"muts":[{"kind":"freshEntry","id":0,"field":"def","value":2340}],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":550},"muts":[{"kind":"bothEntry","id":1,"field":"min","value":600}],"check":12} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":550},"muts":[{"kind":"bothEntry","id":1,"field":"max","value":540}],"check":12} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":550},"muts":[{"kind":"bothEntry","id":1,"field":"feature","value":8}],"check":4} diff --git a/Tests/Suites/GPUControlChannelTests.swift b/Tests/Suites/GPUControlChannelTests.swift index efbc64d5..7de57728 100644 --- a/Tests/Suites/GPUControlChannelTests.swift +++ b/Tests/Suites/GPUControlChannelTests.swift @@ -1289,8 +1289,9 @@ enum GPUControlChannelTests { .notRead: .notReady, .drifted: .notReady, .memoryMoved: .notReady, .noFeature: .settingMissing, .curveRange: .notAllowed, .curveOrder: .notAllowed, .curveFirst: .notAllowed, .curveLast: .notAllowed, .curveCooling: .notAllowed, .gfxRange: .notAllowed, .noReadings: .settingMissing, + .gfxMinRange: .notAllowed, ] - suite.expect(checks.count == 11, "11 OD8 reasons besides ok") + suite.expect(checks.count == 12, "12 OD8 reasons besides ok") for check in GPUControlOD8Check.allCases { suite.expect(G.forOD8Check(check.rawValue) == checks[check], "OD8 check \(check.rawValue) \(check): its group") if check != .ok { @@ -1298,8 +1299,8 @@ enum GPUControlChannelTests { "OD8 refused for \(check): the reason's group") } } - suite.expect(G.forOD8Check(12) == nil, "an unknown OD8 reason has no group") - suite.expect(G.forReply(GPUControlReply.od8Refused.rawValue, check: 12) == .notAllowed, + suite.expect(G.forOD8Check(13) == nil, "an unknown OD8 reason has no group") + suite.expect(G.forReply(GPUControlReply.od8Refused.rawValue, check: 13) == .notAllowed, "refused for an unknown reason: not allowed") let offs: [GPUControlWriteOff: G] = [ .ctlOff: .offNotAsExpected, .notOneCard: .offNotAsExpected, .otherAmdGpu: .offNotAsExpected, @@ -1344,10 +1345,19 @@ enum GPUControlChannelTests { let checks: [(GPUControlOD8Check, UInt64)] = [ (.ok, 0), (.notRead, 1), (.drifted, 2), (.memoryMoved, 3), (.noFeature, 4), (.curveRange, 5), (.curveOrder, 6), (.curveFirst, 7), (.curveLast, 8), (.curveCooling, 9), (.gfxRange, 10), - (.noReadings, 11), + (.noReadings, 11), (.gfxMinRange, 12), ] - suite.expect(checks.allSatisfy { $0.0.rawValue == $0.1 } && GPUControlOD8Check.allCases.count == 12, - "OD8 checks: ok 0 ... noReadings 11, as gpuctl::Od8Check") + suite.expect(checks.allSatisfy { $0.0.rawValue == $0.1 } && GPUControlOD8Check.allCases.count == 13, + "OD8 checks: ok 0 ... gfxMinRange 12, as gpuctl::Od8Check") + suite.expect(GPUControlOD8Held.gfxMin.rawValue == 16 && GPUControlFlags.gfxMin.rawValue == 512, + "0.9.0: the GFX minimum's held bit 16 and status flag 512, as kOd8HeldGfxMin and kFlagGfxMin") + suite.expect(GPUControlWire.Selector.setOD8.takes(inputCount: 13) + && GPUControlWire.Selector.setOD8.takes(inputCount: 14) + && !GPUControlWire.Selector.setOD8.takes(inputCount: 12) + && !GPUControlWire.Selector.setOD8.takes(inputCount: 15) + && GPUControlWire.Selector.set.takes(inputCount: 2) + && !GPUControlWire.Selector.set.takes(inputCount: 14), + "setOD8 takes 13 or 14 scalars (od8WireCountOk), every other call its one count") let offs: [(GPUControlWriteOff, UInt64)] = [ (.none, 0), (.ctlOff, 1), (.notOneCard, 2), (.otherAmdGpu, 3), (.library, 4), (.routes, 5), (.cwdde, 6), (.secondObject, 7), (.bootImplausible, 8), (.start, 9), (.sendFailed, 10), @@ -1378,6 +1388,8 @@ enum GPUControlChannelTests { ("kWakeReadyMarginMs", GPUControlWire.wakeReadyMarginMs), ("kSetWaitMs", GPUControlWire.setWaitMs), ("kMaxPowerPercentDown", UInt64(GPUControlPowerRange.maxPercentDown)), + ("kOd8WireCount", UInt64(GPUControlWire.setOD8InputCountGfxMin)), + ("kOd8WireCountV070", UInt64(GPUControlWire.setOD8InputCount)), ] let kext = constants(in: source) for (name, app) in mirrored { diff --git a/Tests/Suites/GPUControlClockTests.swift b/Tests/Suites/GPUControlClockTests.swift index 3247ce47..e7b4d18f 100644 --- a/Tests/Suites/GPUControlClockTests.swift +++ b/Tests/Suites/GPUControlClockTests.swift @@ -14,6 +14,7 @@ enum GPUControlClockTests { controller(suite) strings(suite) reviewFixes(suite) + gfxMin(suite) } private typealias Logic = GPUControlClockLogic @@ -193,7 +194,7 @@ enum GPUControlClockTests { .filter { $0 != "%%" } ?? [] } let english = GPUControlClockStrings.enUS.all - suite.expect(english.count == 11, "11 texts") + suite.expect(english.count == 17, "17 texts (6 for the GFX minimum)") for language in AppLanguage.allCases { let clock = FeatureStrings.gpuControlClock(language) let table = clock.all @@ -205,6 +206,10 @@ enum GPUControlClockTests { suite.expect(Set([names.slider, names.field, names.stepper]).count == 3 && names.stepper.contains("\(GPUControlClockLogic.step)"), "\(language.rawValue): the clock row's three controls have their own names") + let low = GPUControlClockMinSection.accessibilityNames(clock) + suite.expect(Set([low.slider, low.field, low.stepper, names.slider, names.field, names.stepper]).count == 6 + && low.stepper.contains("\(GPUControlClockMinLogic.step)"), + "\(language.rawValue): the minimum's three controls have their own names, not the maximum's") // No watts written into a text (S-2): the clock footer's 200 W is gone. suite.expect(!table.contains { $0.contains("200 W") || $0.contains("200 Вт") || $0.contains("200 W'") }, "\(language.rawValue): no fixed watts in the clock texts") @@ -224,6 +229,150 @@ enum GPUControlClockTests { suite.expect(GPUControlClockSection.sliderMinWidth > 0, "the row keeps the slider at least this wide on one line") } + /// The GFX minimum clock (GPUSensors 0.9.0): its range from the card's + /// table up to the maximum in force, the 14 scalars, `Takes`, the + /// controller against the model, remembering it, its words. + private static func gfxMin(_ suite: TestSuite) { + typealias Min = GPUControlClockMinLogic + let limits = Min.Limits(min: 500, max: 2_800, stock: 500) + suite.expect(Min.range(limits: limits, gfxMaxMHz: 2_359) == 500...2_359, + "the minimum: from the stock 500 MHz to the stock maximum") + suite.expect(Min.range(limits: limits, gfxMaxMHz: 2_000) == 500...2_000, "up to a lowered maximum") + suite.expect(Min.range(limits: nil, gfxMaxMHz: 2_359) == nil && Min.range(limits: limits, gfxMaxMHz: nil) == nil + && Min.range(limits: limits, gfxMaxMHz: 500) == nil, + "no minimum taken, no maximum known, or nothing above stock: no control") + suite.expect(Min.range(limits: Min.Limits(min: 500, max: 2_000, stock: 500), gfxMaxMHz: 2_359) == 500...2_000, + "never past the card's own top for the minimum") + let r = 500...2_359 + suite.expect(Min.raises(1_500, range: r) && Min.raises(2_359, range: r), + "1500 MHz and the maximum itself raise the minimum") + suite.expect(!Min.raises(500, range: r) && !Min.raises(2_360, range: r) && !Min.raises(1_500, range: nil), + "stock, above the maximum, or no range: never a hold") + suite.expect(Min.request(500, stockMHz: 500) == nil && Min.request(1_500, stockMHz: 500) == 1_500, + "choosing the stock minimum is the way back; a higher value is asked for") + suite.expect(Min.snapped(1_504, range: r) == 1_500 && Min.snapped(2_356, range: r) == 2_359 + && Min.snapped(400, range: r) == 500, "10 MHz steps, the top on its own, never below stock") + suite.expect(Min.tickCount(range: r) == 19, "a tick every 100 MHz: 500 to 2300") + let low = GPUControlOD8Want(gfxMinMHz: 2_100) + suite.expect(Min.checked(low, limits: limits, stockGfxMaxMHz: 2_359) == low, "2100 MHz is kept") + suite.expect(Min.checked(low, limits: nil, stockGfxMaxMHz: 2_359).gfxMinMHz == nil, + "a kext that takes no minimum: left out") + suite.expect(Min.checked(GPUControlOD8Want(gfxMaxMHz: 2_000, gfxMinMHz: 2_100), limits: limits, stockGfxMaxMHz: 2_359) + == GPUControlOD8Want(gfxMaxMHz: 2_000), "above the lowered maximum: left out, the maximum stays") + + // The scalars. + suite.expect(GPUControlOD8Want(gfxMinMHz: 1_500).scalars() == [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1_500], + "a minimum: 14 scalars, the 14th in MHz") + suite.expect(GPUControlOD8Want(gfxMaxMHz: 2_300).scalars()?.count == 13, + "no minimum: the 13 every kext since 0.7.0 takes") + suite.expect(GPUControlOD8Want(gfxMinMHz: 0).scalars() == nil, "a minimum of 0 would read as stock: not sent") + suite.expect(!GPUControlOD8Want(gfxMinMHz: 1_500).isStock && GPUControlOD8Want(gfxMinMHz: 1_500).heldFlags == .gfxMin, + "a raised minimum is a hold, held bit 16") + + // The table, and whether the kext takes it. + let path = FileManager.default.currentDirectoryPath + "/Tests/Fixtures/GPUSensors/ioreg-0.7.2-2026-11-20.plist" + if let data = FileManager.default.contents(atPath: path), + let dict = (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [String: Any], + var writing = GPUControlStatus.parse(dict)?.writing { + suite.expect(writing.od8?.gfxMin.map { [$0.min, $0.max, $0.stock] } == [500, 2_800, 500], + "the card's minimum: 500 to 2800 MHz, stock 500") + suite.expect(Min.limits(writing: writing, od8Ready: true) == nil, + "0.7.2 publishes no Takes: no minimum control") + writing.od8State?.takes = [.curve, .zeroRpmOff, .gfxMax, .gfxMin] + suite.expect(Min.limits(writing: writing, od8Ready: true) == limits + && Min.limits(writing: writing, od8Ready: false) == nil, + "with Takes 23 and a clean read: the card's limits") + } else { + suite.expect(false, "the 0.7.2 fixture loads") + } + do { + let fake = FakeGPUControlKext() + fake.takesGfxMin = true + fake.arm() + let c = fake.connection() + _ = c.open() + let answer = c.setOD8(GPUControlOD8Want(gfxMinMHz: 1_500)) + let writing = GPUControlService.fakeControl(fake)?.writing + suite.expect(answer?.reply == .ok && writing?.od8State?.gfxMinHeld == 1_500 + && writing?.od8State?.held == .gfxMin && writing?.od8State?.takesGfxMin == true + && c.status()?.flags.contains(.gfxMin) == true, + "0.9.0 model: GfxMinHeld 1500, Takes, the status flag") + } + + // The controller against the 0.9.0 model. + do { + let h = Harness { $0.takesGfxMin = true } + h.engine.chooseGfxMax(2_000) + h.run(ms: 3_000) + h.engine.chooseGfxMin(1_500) + h.run(ms: 0) + suite.expect(h.calls(.setOD8).last?.input == [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2_000, 1_500] + && h.engine.snapshot.held == .od8(GPUControlOD8Want(gfxMaxMHz: 2_000, gfxMinMHz: 1_500)), + "the minimum goes with the held maximum, and is held") + h.run(ms: 3_000) + h.engine.chooseGfxMin(nil) + h.run(ms: 0) + suite.expect(h.calls(.setOD8).last?.input == [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2_000] + && h.engine.snapshot.held == .od8(GPUControlOD8Want(gfxMaxMHz: 2_000)), + "turning the minimum off keeps the maximum, in the 13-scalar form") + } + do { + let h = Harness { $0.takesGfxMin = true } + h.engine.chooseGfxMin(2_400) + h.run(ms: 0) + if case .refused(_, let answer)? = h.engine.snapshot.outcome { + suite.expect(answer.check == .gfxMinRange && h.calls(.setOD8).last?.input[13] == 2_400 + && h.engine.snapshot.held == nil + && GPUControlTextGroup.forReply(answer.replyCode, check: answer.checkCode) == .notAllowed, + "above the stock maximum: sent unchanged, refused (GFX min range), nothing held") + } else { + suite.expect(false, "a minimum above the maximum: refused") + } + } + do { + let h = Harness { $0.takesGfxMin = true } + h.engine.chooseGfxMin(1_500) + h.run(ms: 0) + h.fake.tripFanWatchdog() + h.run(ms: 5_000) + suite.expect(h.engine.snapshot.stopped == .writingOff(GPUControlWriteOff.od8Watchdog.rawValue), + "a raised minimum is watched: the watchdog stops it") + } + + // Remembering it. + let suiteName = "ryzenstatus.tests.gpucontrol.clockmin.\(getpid())" + if let defaults = UserDefaults(suiteName: suiteName) { + let both = GPUControlOD8Want(gfxMaxMHz: 2_000, gfxMinMHz: 1_500) + GPUControlRemembered.od8(both).save(defaults) + suite.expect(defaults.integer(forKey: DefaultsKey.gpuControlRememberedGfxMinMHz) == 1_500 + && GPUControlRemembered.load(defaults) == .od8(both), "a minimum round-trips with the maximum") + GPUControlRemembered.power(watts: 220).save(defaults) + suite.expect(defaults.object(forKey: DefaultsKey.gpuControlRememberedGfxMinMHz) == nil, + "saving power clears the minimum") + defaults.removePersistentDomain(forName: suiteName) + } + var facts = GPUControlFacts(source: .properties) + facts.ready = true + facts.armed = true + facts.bootW = 240 + facts.od8Ready = true + typealias Policy = GPUControlRememberPolicy + let both = GPUControlOD8Want(gfxMaxMHz: 2_000, gfxMinMHz: 1_500) + suite.expect(Policy.request(remembered: .od8(both), active: true, facts: facts, stopped: nil, + stockGfxMaxMHz: 2_359, gfxMin: limits) == .od8(both), + "a remembered minimum is asked for again with a kext that takes it") + suite.expect(Policy.request(remembered: .od8(both), active: true, facts: facts, stopped: nil, + stockGfxMaxMHz: 2_359) == .od8(GPUControlOD8Want(gfxMaxMHz: 2_000)), + "a kext that takes no minimum: only the maximum is asked for") + suite.expect(Policy.checkedAgain(.od8(GPUControlOD8Want(gfxMinMHz: 1_500)), stockGfxMaxMHz: 2_359) == nil, + "after a wake, no minimum taken: nothing left to ask") + suite.expect(Policy.checkedAgain(.od8(GPUControlOD8Want(gfxMinMHz: 1_500)), stockGfxMaxMHz: 2_359, gfxMin: limits) + == .od8(GPUControlOD8Want(gfxMinMHz: 1_500)), "and with it: asked again") + suite.expect(GPUControlPageStrings.enUS.od8Held(both) + == "RyzenStatus is holding a GFX maximum of 2000 MHz and a GFX minimum of 1500 MHz", + "both clocks held, in one sentence") + } + /// The review of phases 3 and 4 (F1 to F6). private static func reviewFixes(_ suite: TestSuite) { let curve = GPUControlFanDraft.testedCurve diff --git a/Tests/Suites/GPUControlFanTests.swift b/Tests/Suites/GPUControlFanTests.swift index 2e95c690..535f09de 100644 --- a/Tests/Suites/GPUControlFanTests.swift +++ b/Tests/Suites/GPUControlFanTests.swift @@ -83,7 +83,7 @@ enum GPUControlFanTests { return } let lines = text.split(separator: "\n") - suite.expect(lines.count == 100, "100 cases") + suite.expect(lines.count == 120, "120 cases (100 from 0.7.2, 20 for the GFX minimum of 0.9.0)") var seen: [UInt64: Int] = [:] for (index, line) in lines.enumerated() { guard let object = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any], @@ -104,7 +104,7 @@ enum GPUControlFanTests { "case \(index + 1): never a code od8CheckWant does not give") seen[expected, default: 0] += 1 } - suite.expect(seen == [0: 33, 2: 14, 3: 5, 4: 12, 5: 9, 6: 4, 7: 3, 8: 6, 9: 6, 10: 8], + suite.expect(seen == [0: 42, 2: 14, 3: 5, 4: 13, 5: 9, 6: 4, 7: 3, 8: 6, 9: 6, 10: 9, 12: 9], "every code od8CheckWant gives is in the file: \(seen)") // The GFX drift boundary, by hand: +25 MHz is taken, +26 is not. var drift = base @@ -120,8 +120,10 @@ enum GPUControlFanTests { let curve = (dict["curve"] as? Bool) == true ? zip(temps, speeds).map { GPUControlFanPoint(temperatureC: $0, speedPercent: $1) } : nil let gfx = (dict["gfx"] as? Int) ?? 0 + // GPUSensors 0.9.0: written only when it is not stock. + let low = (dict["gfxMin"] as? Int) ?? 0 return GPUControlOD8Want(curve: curve, zeroRpmOff: (dict["zeroRpmOff"] as? Bool) == true, - gfxMaxMHz: gfx == 0 ? nil : gfx) + gfxMaxMHz: gfx == 0 ? nil : gfx, gfxMinMHz: low == 0 ? nil : low) } private static func apply(_ mutation: [String: Any], to state: inout Rules.State) { @@ -189,10 +191,11 @@ enum GPUControlFanTests { suite.expect(GPUControlCurvePreview.make(want: tested, writing: other) == .notChecked, "no build name: not checked") // GPUSensors 0.8.0 and 0.8.1: the build date follows the package // build, so any date of a release build is the same checked source. - for build in ["REL-080-2026-11-21", "REL-080-2026-11-20", "REL-080-2027-01-05", "REL-081-2026-11-22"] { + for build in ["REL-080-2026-11-21", "REL-080-2026-11-20", "REL-080-2027-01-05", "REL-081-2026-11-22", + "REL-090-2026-11-25"] { other.kextVersion = build suite.expect(GPUControlCurvePreview.make(want: tested, writing: other) == .accepted, - "\(build): GPUSensors 0.8.0 or 0.8.1, checked") + "\(build): GPUSensors 0.8.0, 0.8.1 or 0.9.0, checked") } for build in ["DBG-080-2026-11-21", "REL-082-2026-11-21", "REL-080", "REL-080-2026-11", "REL-080-2026-11-21x", "REL-080-2026-11-21-1", "REL-08-2026-11-21", "REL-072-2026-11-20", "rel-080-2026-11-21", ""] { diff --git a/Tests/Suites/GPUControlPageTests.swift b/Tests/Suites/GPUControlPageTests.swift index 44e35baa..230b51da 100644 --- a/Tests/Suites/GPUControlPageTests.swift +++ b/Tests/Suites/GPUControlPageTests.swift @@ -853,7 +853,7 @@ enum GPUControlPageTests { return pattern?.matches(in: text, range: range).compactMap { Range($0.range, in: text).map { String(text[$0]) } } ?? [] } let english = GPUControlPageStrings.enUS.all - suite.expect(english.count == 94, "94 texts") + suite.expect(english.count == 95, "95 texts") for language in AppLanguage.allCases { let table = FeatureStrings.gpuControlPage(language).all suite.expect(table.count == english.count && table.allSatisfy { !$0.trimmingCharacters(in: .whitespaces).isEmpty }, From 122aa73de084fecfaccb52516b46472c8a5f1ed4 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Wed, 25 Nov 2026 08:36:06 -0300 Subject: [PATCH 2/3] GPUSensors 0.9.0: GFX voltage, overclock and a raised power limit The OD8 state now also takes a lower GFX voltage (OD8 id 37, the firmware's VddGfxOffset). Read end to end in the 25G342 driver: it is offered with PP_OD8VoltageSliderSupport (the Navi 21 default) as a range from the card's minimum to its stock value (881 to 1075 mV on the test RX 6800 XT), the driver writes value minus the top as the offset of the whole voltage curve and reads back top plus offset. The kext takes it lower only, in 25 mV steps from stock, reads it back exactly, and sends the stock value in every other call so no way back leaves an offset. Two raises, only when the request asks for them and only inside the card's own OverDrive range: a GFX maximum above stock up to the 0x9f maximum (setOd8 flag 4), and a power limit above the start-up one up to the start-up limit plus the card's power percent, cut at +15 % (set's new 3-scalar form; 261 W on the test card). One step past either maximum is refused. Each raise needs fresh watchdog readings and is held under the watchdog: 95 C or 10 s without readings puts stock back and turns writing off (new WriteOff 16 for the power limit). Not added: the memory clock and fast memory timings. Both start with an IRI call (0x110018) that Apple's display glue does not implement, so the driver cannot apply them on macOS. Channel version stays 2: setOd8 takes 15 scalars too, set takes 3, replies 21 and 22, Od8Check 13, status flags 1024 and 2048, held bits 32 and 64, VoltHeld, Takes 119, PowerRange CeilW. gpucontrol gains "volt mV", "overclock" and "hold power W raise". The app adds a GFX voltage section (it suggests stock minus 25 mV as a starting point and never applies it by itself) and an Overclock section, off by default, with no suggested values. A voltage or a raise is never sent again by itself at launch. docs/GPU_CONTROL.md describes every control, its range and its risks. Tested on the host only: controltest 432 checks, the curve rules fixture grew to 149 cases (the first 120 unchanged), ./build.sh --test. Not booted. --- CHANGELOG.md | 2 + GPU/CHANGELOG.md | 40 +- GPU/sensors/README.md | 33 +- GPU/sensors/kext/control_logic.hpp | 267 +++++++++-- GPU/sensors/kext/kern_control.cpp | 129 ++++-- GPU/sensors/kext/kern_control.hpp | 9 +- GPU/sensors/kext/kern_service.cpp | 46 +- GPU/sensors/tests/controltest.cpp | 315 ++++++++++++- GPU/sensors/tests/curve_fixturegen.cpp | 61 ++- GPU/sensors/tool/gpucontrol.cpp | 113 +++-- README.md | 2 +- .../RyzenStatus/Core/DefaultsKey+App.swift | 10 + .../Core/GPUControlOverclockStrings.swift | 420 ++++++++++++++++++ .../Core/GPUControlPageStrings.swift | 39 +- .../Services/Metrics/FakeGPUControlKext.swift | 127 +++++- .../Services/Metrics/GPUControlChannel.swift | 8 +- .../Metrics/GPUControlController.swift | 67 ++- .../Metrics/GPUControlCurveRules.swift | 26 +- .../Services/Metrics/GPUControlPage.swift | 228 +++++++++- .../Services/Metrics/GPUControlService.swift | 27 +- .../Services/Metrics/GPUControlWire.swift | 139 +++++- .../Metrics/GPUControlWriteProperties.swift | 46 +- .../UI/Settings/GPUControlClockSection.swift | 8 +- .../Settings/GPUControlOverclockSection.swift | 259 +++++++++++ .../UI/Settings/GPUControlSettingsView.swift | 37 +- .../UI/Settings/GPUControlVoltSection.swift | 267 +++++++++++ Tests/Fixtures/GPUSensors/README.md | 36 +- Tests/Fixtures/GPUSensors/curve-cases.jsonl | 29 ++ Tests/MetricsTests.swift | 1 + Tests/Suites/GPUControlChannelTests.swift | 67 ++- Tests/Suites/GPUControlFanTests.swift | 14 +- Tests/Suites/GPUControlOverclockTests.swift | 416 +++++++++++++++++ Tests/Suites/GPUControlPageTests.swift | 2 +- docs/GPU_CONTROL.md | 136 ++++++ 34 files changed, 3157 insertions(+), 269 deletions(-) create mode 100644 Sources/RyzenStatus/Core/GPUControlOverclockStrings.swift create mode 100644 Sources/RyzenStatus/UI/Settings/GPUControlOverclockSection.swift create mode 100644 Sources/RyzenStatus/UI/Settings/GPUControlVoltSection.swift create mode 100644 Tests/Suites/GPUControlOverclockTests.swift create mode 100644 docs/GPU_CONTROL.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c0635d8d..c6b48720 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ **GPU minimum clock, from GPUSensors.kext 0.9.0**: Settings › GPU control has a GFX minimum clock under the maximum. It only raises the minimum, from the card's stock value up to the GFX maximum in force, and keeps the clock up at idle, so the card draws more power and runs warmer; the kext checks every request, watches the temperature while it is held, and goes back to stock in the same cases as the other GPU changes. The section shows only with GPUSensors.kext 0.9.0. The memory clock, fan minimum speed and fan target temperature stay out: on the RX 6800 XT the driver offers no lower memory clock and no fan minimum or target while it offers the fan curve. Tested with unit tests only. +**GPU voltage and Overclock, from GPUSensors.kext 0.9.0**: Settings › GPU control has a GFX voltage section that only lowers the voltage, from the card's stock value down to its own minimum in 25 mV steps (an undervolt: the whole voltage curve moves down, so the card runs cooler). It suggests stock minus 25 mV as a starting point to test and never applies it by itself. A separate Overclock section, off by default, raises the GFX maximum clock up to the card's own maximum and the power limit up to the card's own power percent (never more than +15 %); it has no suggested values. Every value stays inside the limits the card publishes, the kext refuses anything else, holds every raise under its temperature watchdog and goes back to stock in the same cases as the other GPU changes; a voltage or a raise is never sent again by itself at launch. Memory clock and fast memory timings are not offered: on macOS the driver cannot apply them. Only the RX 6800 XT writes; the RX 6900 XT shows readings only. All of it is in [docs/GPU_CONTROL.md](docs/GPU_CONTROL.md). Tested with unit tests only. + **AWDL / AirDrop activity in the Network card**: with a Wi-Fi driver that publishes AWDL activity in the I/O Registry (`RTLAwdlPeers` and `RTLAwdlChannel` on the `awdl0` interface, and optionally the `RTLLed` status LED mode), the panel's Network card shows a line with the number of peers exchanging data over AWDL (AirDrop, Sidecar, Continuity) and its current channel. Settings › Monitor › Alerts adds an optional notification when AWDL goes from no peers to some; it is off by default and fires at most once a minute. The line can be hidden like the card's other blocks. With other Wi-Fi hardware nothing changes and nothing extra is read. ## [1.89.0] — 2026-11-23 — kexts 3.42.0 (No kext changes) diff --git a/GPU/CHANGELOG.md b/GPU/CHANGELOG.md index 98894a88..2363a3fe 100644 --- a/GPU/CHANGELOG.md +++ b/GPU/CHANGELOG.md @@ -23,10 +23,42 @@ The encoding fix keeps its own history in `encode/CHANGELOG.md`. bit 16, `GfxMinHeld` and `Takes` (23: what `setOd8` takes). An older kext refuses the 14-scalar form with a wrong-count error; `gpucontrol` and the app send it only with a minimum. -- Not added, and why (read on this card and in the 25G342 driver, 2026-11-25): the memory - maximum (id 8), whose 0x9f minimum is its stock value (2000 MHz here), so there is nothing - lower to take, and whose change blanks the display; the fan minimum speed (id 10) and fan - target temperature (id 12), which the driver does not offer while the fan curve is offered +- A lower GFX voltage (OD8 id 37, the firmware's `VddGfxOffset`): `gpucontrol hold volt 1050 + -- `. Read end to end in HWLibs 25G342: the driver offers it with + `PP_OD8VoltageSliderSupport` (the Navi 21 default, 1) as a range from swsmu+328 to swsmu+332 + (881 to 1075 mV on the test card, stock 1075), stages value minus the top as the OD table's + `VddGfxOffset` (int16 mV, written whole to the firmware) and reads it back as top plus + offset. So it is a millivolt cap that moves the whole voltage curve down, and it cannot go + above the top. Linux writes the same field and needs SMU firmware 58.41.0 or later (the + test card: 58.76.0). The kext takes it lower only (at or below stock, at or above the card's + minimum) in 25 mV steps from stock, reads it back exactly, and sends the stock value in + every other call so a way back never leaves an offset behind. Refused: `VoltRange` (13); + not offered or not allowed now: `NoFeature`. +- Raises, only when the request asks for them and only inside the card's own OverDrive + range: a GFX maximum above stock up to the 0x9f maximum (2800 MHz here) with `setOd8` flag + 4, `gpucontrol hold gfxmax 2500 overclock -- `; and a power limit above the + start-up one with `set`'s new 3-scalar form (flag 1), `gpucontrol hold power 260 raise -- + `, up to `PowerRange.CeilW` = start-up limit x (100 + the 0x9f power percent) / + 100, the way Linux takes `power1_cap_max`, the percent cut at +15 (261 W on the test card, + +9 %). The driver's 0x6e path has no ceiling of its own (it sends SMU message 0x32 with the + watts as given), so this is the only one. One step past either maximum is refused + (`GfxRange`; the new reply 21 `AboveCeiling`). Each raise is taken only while the watchdog + has fresh readings (new reply 22 `NoReadings` for `set`) and is held under it: 95 C or no + readings for 10 s puts stock back and turns writing off (new `WriteOff` 16 + `PowerWatchdog` for the power limit). +- The channel stays version 2: `setOd8` also takes 15 scalars (the 15th is the voltage), + `set` also takes 3, `status` sets flags 1024 (`kFlagVolt`) and 2048 (`kFlagRaise`), + `OD8WriteState` gains `Held` bits 32 (voltage) and 64 (GFX maximum above stock), `VoltHeld`, + and `Takes` 119; `PowerRange` gains `CeilW`. An older kext refuses the new counts. +- Not added, and why (read in the 25G342 driver, 2026-11-25): the memory maximum (id 8) and + fast memory timings (id 14, AC timing). Both start with `PhwComm_OD8_StartMemoryOverclock` + -> `PECI_StartGPUMemoryOverclock`, an IRI call 0x110018 to the display driver, and on macOS + that interface is `AtiAppleDalServices::dalIriFunction`, which has no case for 0x110018 (nor + 0x110019, the end) and answers status 1, so the start fails. A memory maximum then makes + `PhwComm_OD8_ApplySettings` return before the OD table is written (the whole call fails + and the new clock stays staged), and fast timings are recorded but never programmed + (nothing could be read back). Also not added: the fan minimum speed (id 10) and fan target + temperature (id 12), which the driver does not offer while the fan curve is offered (feature 0, and `PhwComm_OD8_SetGenericSetting` skips a setting whose feature is 0). ## Decoders 0.3.5 (RyzenStatus 1.89.0) diff --git a/GPU/sensors/README.md b/GPU/sensors/README.md index 585edb8d..92c213c6 100644 --- a/GPU/sensors/README.md +++ b/GPU/sensors/README.md @@ -93,11 +93,11 @@ The properties of `DrogaBoxGPUSensors` are: | `Write` | the power limit write path (0.5.0): `off until restart: see WriteState`, `read only: this card can only be read (see WriteState)` (0.8.0, an RX 6900 XT), `waiting for ...`, `closed: sudo gpucontrol arm opens it until restart`, or `armed: ...` (nothing held, a program holds a lower limit, a program holds a fan or clock change (see `OD8Write`), a program is setting a limit, going back, between sleep and wake) | | `WriteState` | `WriteOff` and `WriteOffText` (why writing is off, 0 and empty when it is not; 15 = `ReadOnlyCard` since 0.8.0), `Armed`, `Owned`, `HeldW` (the limit now: the start-up one when nothing is held), `Changes` and `Reverts` (confirmed since boot), `LastReply` (the last `set`'s answer, numbered as in `control_logic.hpp`) | | `PowerRangeState` | the card's power range (0.8.0): `from the card: start-up limit less its OD8 power percent`, `not known yet: waiting for a clean OD8 read`, `not known: ...` (the start-up limit is not read or not believable, or the OD8 power entry is not as expected), `the card offers no lower power limit: only the start-up limit`, `waiting for the driver's library` or `off...` | -| `PowerRange` | (0.8.0) `Known` (1 once the floor is known), `FloorW` and `MaxW` (the lowest and highest limit `set` takes, W; only when known; equal when the card offers nothing lower), `StepW` (10), `PercentMin` and `PercentMax` (the card's OD8 power percent, signed 32-bit like the OD8 settings: -6 and 9 on the test RX 6800 XT; once OD8 was read). Published on a read-only card too (its own floor, for reading only: nothing is taken there). See [The power limit](#the-power-limit-050) | +| `PowerRange` | (0.8.0) `Known` (1 once the floor is known), `FloorW` and `MaxW` (the lowest and highest limit `set` takes, W; only when known; equal when the card offers nothing lower), `CeilW` (0.9.0: the highest limit `set`'s raise form takes; `MaxW` when the card offers nothing higher; 261 on the test card), `StepW` (10), `PercentMin` and `PercentMax` (the card's OD8 power percent, signed 32-bit like the OD8 settings: -6 and 9 on the test RX 6800 XT; once OD8 was read). Published on a read-only card too (its own floor, for reading only: nothing is taken there). See [The power limit](#the-power-limit-050) | | `OD8State` | OD8, read only (0.6.0): `read`, `read, but an entry is not as expected`, `not available: ...`, `no data: ...`, `not read: ...`, `stopped: ...`, `waiting ...` or `off: ...` | | `OD8` | once tried: `Reads`, `Tries`, `LastResult`, `LastReadAgeS`, `Caps`, `NotAllowed`, `StockOdd`, `DefaultsMoved`, `CurrentMoved`, `FanCurveStock`, `FanCurve` (five [C, %] pairs) and `Settings` by name (`Feature`, `Min`, `Max`, `Stock`, `Current`); `OddEntry` and `OddEscape` when an answer was not as expected. See [OD8, read only](#od8-read-only-060) | | `OD8Write` | OD8 writes (0.7.0): `off until restart: see WriteState`, `read only: this card can only be read (see WriteState)` (0.8.0), `waiting for a clean OD8 read (OD8State)`, `closed: sudo gpucontrol arm opens it until restart`, or `armed: ...` (OD8 at stock, a program holds a fan or clock change, going back to stock, the last call was not taken) | -| `OD8WriteState` | `Held` (1 fan curve, 2 zero RPM off, 4 GFX max, 8 not confirmed, 16 GFX min since 0.9.0), `Changes` and `Reverts` (confirmed since boot), `LastCheck` and `LastCheckText` (why the last OD8 request was refused, 0 = none), `SentPower` (power limit sends seen during OD8 calls), `FanCurveHeld` (C × 1000 + %), `GfxMaxHeld` and `GfxMinHeld` (0.9.0) while held, `Takes` (0.9.0: what `setOd8` takes, in `Held` bits, 23). See [OD8 writes](#od8-writes-070) | +| `OD8WriteState` | `Held` (1 fan curve, 2 zero RPM off, 4 GFX max, 8 not confirmed, 16 GFX min, 32 GFX voltage, 64 GFX max above stock, the last three since 0.9.0), `Changes` and `Reverts` (confirmed since boot), `LastCheck` and `LastCheckText` (why the last OD8 request was refused, 0 = none), `SentPower` (power limit sends seen during OD8 calls), `FanCurveHeld` (C × 1000 + %), `GfxMaxHeld`, `GfxMinHeld` and `VoltHeld` (0.9.0) while held, `Takes` (0.9.0: what `setOd8` takes, in `Held` bits: 119 = also 32 GFX voltage and 64 GFX maximum above stock). See [OD8 writes](#od8-writes-070) | | `Samples` | readings copied since boot | | `SampleAgeMs` | how old the last reading is; with `Sensors`, `Units` and `PMLog` it is absent once the copy is older than 5 s (the driver stopped sampling: the card is asleep, powered down, or its driver is gone) | | `Sensors` | `{ name: value }`, in the units of `Units` | @@ -243,7 +243,7 @@ The channel is an IOUserClient on `DrogaBoxGPUSensors` (type 0), with scalars on `status`, `arm`, `set(watts)`, `alive`, `release`, since 0.7.0 `setOd8`, and since 0.8.0 `disarm` (selector 6, `{version}` in, one reply out, any caller) (version 2; 0.5.0 and 0.6.0 were version 1; 0.8.0 only adds, so it stays 2; so does 0.9.0, whose -`setOd8` also takes a 14th scalar, the GFX minimum, and still takes the 13 of 0.7.0). Every call passes the +`setOd8` also takes a 14th scalar, the GFX minimum, and a 15th, the GFX voltage, and still takes the 13 of 0.7.0; `set` also takes a third, the raise flag). Every call passes the version first; another version is refused. 0.8.0 adds two answers: 19 "a change is still applied or being handled" (disarm) and 20 "the card's minimum power limit is not known" (set, only below the start-up value: above it is "above the start-up limit" either way). `set` and @@ -321,10 +321,27 @@ else: readings rule hold it as they hold a curve (not the 75 C rule, which needs a curve: the stock fan climbs slowly by design). `gpucontrol hold gfxmin 1500 -- `. -Memory clock, voltage and power percent are never written. The memory maximum cannot be -lowered on this card anyway: its 0x9f minimum is the stock value (2000 MHz), and a memory -clock change blanks the display. The fan minimum speed and target temperature are not -offered by the driver while it offers the curve (feature 0; the driver skips them). A request +- A lower GFX voltage (0.9.0, OD8 id 37, the firmware's `VddGfxOffset`): from the card's + stock value down to its own minimum (1075 to 881 mV on the test card), in 25 mV steps from + stock, never above stock. The driver turns it into an offset that moves the whole voltage + curve down and reads back top + offset, which the kext compares exactly. Every other call + carries the stock value, so no way back leaves an offset behind. `gpucontrol hold volt 1050 + -- `. +- Raises (0.9.0), only when the request asks for them, only inside the card's own OverDrive + range, each held under the watchdog (95 C or 10 s without readings: stock back, writing + off) and taken only while it has fresh readings: a GFX maximum above stock up to the 0x9f + maximum (2800 MHz here, `gpucontrol hold gfxmax 2500 overclock -- `), and a power + limit above the start-up one up to `PowerRange.CeilW`, the start-up limit plus the card's + own power percent cut at +15 % (261 W here; `gpucontrol hold power 260 raise -- + `). One step past either maximum is refused. + +Memory clock, fast memory timings and power percent are never written. On macOS the driver +cannot apply the first two: both start with an IRI call (0x110018, "start memory overclock") +that Apple's display glue (`AtiAppleDalServices::dalIriFunction`) does not implement, so a +memory clock makes the whole call fail with the clock left staged, and fast timings are +recorded but never programmed (25G342, read 2026-11-25). The fan minimum speed and target +temperature are not offered by the driver while it offers the curve (feature 0; the driver +skips them). A request that fails a check is refused with the reason, never clamped; `gpucontrol check` runs the same checks on the published OD8 and says what would be taken. OD8 and the power limit are never held together. @@ -389,7 +406,7 @@ it. The kext does not route it. | Power limit and OD8 at once (0.7.1) | With 230 W held, an OD8 change was refused ("busy") and the 230 W stayed; with zero RPM off held, a power limit was refused. Curve + zero RPM off + GFX max 2300 in one call: all three read back, all three taken back | | OD8 across a sleep (0.7.1) | Zero RPM off, and then the curve, held while the Mac slept. The curve was still on the card right after the wake (fan 1950 RPM); 2 s later the kext had put stock back by itself (1329, then 1201 RPM), `gpucontrol hold` asked again and the curve came back; stock again at the end. The GPU log lines at sleep are the same as with nothing held | | A long load at stock (2026-11-19) | gpubench --sustain 300 at the 240 W start-up limit, stock fan, read only: 232.5 W, no compute errors; hotspot 85 C after 80 s, 88 C after 2 minutes, 90-91 C after 5 and still rising about 0.7 C a minute; edge 62 C at most; stock fan 96-100 %. 220 of the 300 s at 85 C or more, which is why the watchdog's limit went from 85 to 95 C in 0.7.2 | -| The 0.9.0 decisions | `controltest`, 371 checks on the CPU (was 336): the GFX minimum against the card's real 0x9f (500 to 2800, never above the stock or the lowered maximum, the range from the entry, not a constant), the call it builds (the pair with the minimum, memory and fan entries untouched), the shapes never sent (minimum above the maximum, the pair split, a minimum of 0), its read-back (up to 25 MHz lower, never higher), the 14- and 13-scalar wire forms and every other count, the watchdog without a curve (only 95 C and no readings count). `curve-cases.jsonl` grew by 20 GFX minimum cases, the first 100 unchanged. Four mutations of the new rules each failed the tests. Not booted | +| The 0.9.0 decisions | `controltest`, 371 checks on the CPU (was 336): the GFX minimum against the card's real 0x9f (500 to 2800, never above the stock or the lowered maximum, the range from the entry, not a constant), the call it builds (the pair with the minimum, memory and fan entries untouched), the shapes never sent (minimum above the maximum, the pair split, a minimum of 0), its read-back (up to 25 MHz lower, never higher), the 14- and 13-scalar wire forms and every other count, the watchdog without a curve (only 95 C and no readings count). `curve-cases.jsonl` grew by 20 GFX minimum cases, the first 100 unchanged. Four mutations of the new rules each failed the tests. Then the GFX voltage and the raises, also 0.9.0: 432 checks (the voltage against the card's real 881-1075 mV entry, stock+1, min-1 and a step that is not 25 mV refused, the stock value in every call, an exact read-back; the GFX maximum up to 2800 only with the overclock flag and 2801 refused; the 261 W ceiling from the +9 % entry, 262 and 270 W refused, a +20 % table cut at +15; the 15- and 3-scalar wire forms); `curve-cases.jsonl` grew to 149 lines, the first 120 unchanged; four more mutations each failed the tests. Not booted | | The 0.8.0 decisions | `controltest`, 336 checks on the CPU (was 277): the floor from the card's real 0x9f (225 W at 240 W, 248 W at 264 W, Linux's integer division), no floor and every change refused when OD8 is not read, odd or its power entry is not as expected; disarm taken from any caller, administrator or not, refused while a change, its way back or an unconfirmed state is there, and closed afterwards (arm still needs an administrator); a read-only card readable, never armable or changeable, its worker started; `set` and `setOd8` answering "off" / "not armed" before any value, absurd ones included; the GFX clock refused by the card's stock maximum, not the wire; the scan's decision for one read-only card and for a mixed machine; which reason `WriteOff` keeps; a request counted as being handled only while waiting or running. Each new check was broken on purpose once and failed. Not booted | | The floor's source on this Mac (0.8.0) | `PP_PhmSoftPowerPlayTable` in ioreg, read 2026-11-20: overdrive table revision 0x81, power limit cap set, `POWERPERCENTAGE` max 9 min 6, `SocketPowerLimitAc[0]` 240; the kext's 0x9f gives -6 to 9 and the start-up read 240 W. Linux's formula read in `sienna_cichlid_ppt.c` (master, and v6.6, which had no minimum) | | The stock GFX maximum across wakes | The driver's default moves between 2354 and 2359 MHz at a wake, in both directions (seen three times); the way back sends the lower of the first read and the fresh one | diff --git a/GPU/sensors/kext/control_logic.hpp b/GPU/sensors/kext/control_logic.hpp index 74c392c9..c880a33d 100644 --- a/GPU/sensors/kext/control_logic.hpp +++ b/GPU/sensors/kext/control_logic.hpp @@ -2,9 +2,12 @@ // control_logic.hpp - every decision GPUSensors' GPU control takes, with no // kernel headers, so the tests build it as ordinary C++. // -// The control only lowers or limits, always within the values the card had -// when the Mac started (the power table on the EFI: 240 W on the owner's RX -// 6800 XT, 264 W on a stock one). It never raises a clock, a voltage or a +// The control lowers or limits within the values the card had when the Mac +// started (the power table on the EFI: 240 W on the owner's RX 6800 XT, 264 W +// on a stock one). Since 0.9.0 it may also raise the GFX maximum clock and +// the power limit, only when the request says so (the overclock flag), and +// never past the card's own OverDrive range (the 0x9f maximum; for power, +// the 0x9f power percent, at most +15 %). It never raises a voltage or a // temperature limit. Nothing here talks to the GPU: the kext asks these // functions first and only acts on a yes. // @@ -193,9 +196,11 @@ enum class PowerCheck : uint32_t { Ok = 0, NoBootValue, // the start-up limit was never read, or is not believable BelowFloor, // below the card's own minimum (PowerRange) - AboveBoot, + AboveBoot, // above the start-up value without the raise flag, or the + // card offers no higher limit (ceilW not above it) NotAStep, NoFloor, // the card's minimum is not known (OD8 not read cleanly): no change + AboveCeiling, // 0.9.0: raise flag, but above the card's own ceiling }; inline bool bootValuePlausible(uint32_t bootW) { @@ -206,12 +211,21 @@ inline bool bootValuePlausible(uint32_t bootW) { // in 10 W steps. The start-up value itself is always taken (it is how the // control goes back, floor known or not), even when it is not a multiple of // 10 (264 W). floorW 0 = not known: nothing below the start-up value is -// taken (NoFloor); above it is AboveBoot either way. -inline PowerCheck checkPower(uint32_t bootW, uint32_t floorW, - uint32_t requestW) { +// taken (NoFloor). Above it (0.9.0): only when the caller passes the card's +// ceiling (PowerRange::ceilW, given only for a request with the raise flag), +// up to that ceiling, in 10 W steps or the ceiling itself; ceilW 0, or not +// above the start-up value, is AboveBoot as before. +inline PowerCheck checkPower(uint32_t bootW, uint32_t floorW, uint32_t requestW, + uint32_t ceilW = 0) { if (!bootValuePlausible(bootW)) return PowerCheck::NoBootValue; if (requestW == bootW) return PowerCheck::Ok; - if (requestW > bootW) return PowerCheck::AboveBoot; // floor known or not + if (requestW > bootW) { + if (ceilW <= bootW) return PowerCheck::AboveBoot; // floor known or not + if (requestW > ceilW) return PowerCheck::AboveCeiling; + if (requestW != ceilW && requestW % kStepW != 0) + return PowerCheck::NotAStep; + return PowerCheck::Ok; + } if (floorW == 0 || floorW > bootW) return PowerCheck::NoFloor; if (requestW < floorW) return PowerCheck::BelowFloor; if (requestW % kStepW != 0) return PowerCheck::NotAStep; @@ -221,8 +235,9 @@ inline PowerCheck checkPower(uint32_t bootW, uint32_t floorW, // A program's set(watts): refused (outside the range), the start-up value // (that is going back: Owner::release, never a change), or a change. enum class SetRoute : uint32_t { Refuse, Release, Change }; -inline SetRoute routeSet(uint32_t bootW, uint32_t floorW, uint32_t requestW) { - if (checkPower(bootW, floorW, requestW) != PowerCheck::Ok) +inline SetRoute routeSet(uint32_t bootW, uint32_t floorW, uint32_t requestW, + uint32_t ceilW = 0) { + if (checkPower(bootW, floorW, requestW, ceilW) != PowerCheck::Ok) return SetRoute::Refuse; return requestW == bootW ? SetRoute::Release : SetRoute::Change; } @@ -263,8 +278,9 @@ inline AccessOut accessAnswer() { return AccessOut{sizeof(AccessOut), 0, 0}; } // The 0x6e request, built only for a value checkPower takes: the range is // checked again where the bytes are made, whatever the caller checked. inline bool makeSetLimit(uint32_t bootW, uint32_t floorW, uint32_t watts, - SetLimitIn* out) { - if (out == nullptr || checkPower(bootW, floorW, watts) != PowerCheck::Ok) + SetLimitIn* out, uint32_t ceilW = 0) { + if (out == nullptr || + checkPower(bootW, floorW, watts, ceilW) != PowerCheck::Ok) return false; *out = SetLimitIn{EscapeHeader{kEscapeHeaderSize, @@ -616,6 +632,17 @@ constexpr uint32_t kOd8PowerFeature = 0x8; // A lower bound further down than this is taken as a broken read (refused), // never as a floor. Tables seen: -6 (the owner's RX 6800 XT). constexpr int32_t kMaxPowerPercentDown = 50; +// The ceiling (0.9.0), the other side of the same entry, the way Linux takes +// power1_cap_max on a Navi 21 (sienna_cichlid_init_ppt_limits): +// max = SocketPowerLimitAc * (100 + overdrive_table.max[POWERPERCENTAGE]) +// / 100 +// with the start-up value standing for SocketPowerLimitAc as for the floor. +// AMD's own tool stops at +15 % on these cards (Adrenalin, RX 6800 XT): a +// table that offers more is cut there, never past it. +9 on the owner's card +// (240 W -> 261 W). The driver's 0x6e path has no ceiling of its own +// (PEM_CWDDEPM_SetPackagePowerLimit -> smu_11_0_7_set_power_limit sends SMU +// message 0x32 with the watts as given, 25G342): this is the only one. +constexpr int32_t kMaxPowerPercentUp = 15; enum class FloorState : uint32_t { Known = 0, NoBootValue, // the start-up limit is not read yet, or not believable @@ -628,10 +655,22 @@ struct PowerRange { uint32_t floorW; // 0 unless the floor is known uint32_t maxW; // the start-up limit (never raised); 0 until believable int32_t percentMin, percentMax; // the card's PowerPercent, when read + // 0.9.0: the highest limit a request with the raise flag may take; 0 + // unless the floor is known (state Known), and equal to maxW when the card + // offers nothing higher (percentMax 0 or less, or NotOffered: then 0 too). + uint32_t ceilW{0}; }; +// The ceiling for a known entry: the start-up value plus its percent, the +// percent cut at +15. Not above the start-up value when nothing is offered. +inline uint32_t powerCeiling(uint32_t bootW, int32_t percentMax) { + if (percentMax <= 0) return bootW; + int32_t up = + percentMax < kMaxPowerPercentUp ? percentMax : kMaxPowerPercentUp; + return bootW * static_cast(100 + up) / 100; +} inline PowerRange powerRange(uint32_t bootW, bool haveStock, bool stockOdd, const Od8InitialOut& stock) { - PowerRange r{FloorState::NoBootValue, 0, 0, 0, 0}; + PowerRange r{FloorState::NoBootValue, 0, 0, 0, 0, 0}; if (!bootValuePlausible(bootW)) return r; r.maxW = bootW; if (!haveStock) { @@ -657,6 +696,7 @@ inline PowerRange powerRange(uint32_t bootW, bool haveStock, bool stockOdd, } r.state = FloorState::Known; r.floorW = bootW * static_cast(100 + e.min) / 100; + r.ceilW = powerCeiling(bootW, e.max); return r; } inline const char* floorStateText(FloorState s) { @@ -687,22 +727,34 @@ inline const char* floorStateText(FloorState s) { // driver's own rule, PhwComm_OD8_SetGfxClockLimits: both requested, each in // its range, FMIN <= FMAX). A raised minimum keeps the GPU clock up at idle, // so it is only taken while the watchdog has readings and the watchdog's -// 95 C limit holds it (od8DogPass). Everything else goes out with requested -// 0. Not taken, and why (2026-11-25, 25G342): the memory maximum (id 8; its -// 0x9f minimum is the stock value, 2000 MHz on the test card, so nothing is -// lower, and a memory clock change blanks the display), the fan minimum -// speed and target temperature (ids 10 and 12; the driver does not offer -// them while the fan curve is offered: feature 0, and SetGenericSetting -// skips a setting whose feature is 0). +// 95 C limit holds it (od8DogPass). 0.9.0 also adds two: the GFX voltage (id +// 37, the driver's VddGfxOffset; lower only, see kOd8GfxVolt) and, with the +// overclock flag, a GFX maximum above stock up to the card's own 0x9f maximum +// (held under the watchdog like the minimum). Everything else goes out with +// requested 0. Not taken, and why (2026-11-25, 25G342): the memory maximum +// (id 8) and fast memory timings (id 14, AC timing). Both go through +// PhwComm_OD8_StartMemoryOverclock -> PECI_StartGPUMemoryOverclock, an IRI +// call 0x110018 to the display driver, and on macOS that interface is +// AtiAppleDalServices::dalIriFunction, which has no case for 0x110018 (nor +// 0x110019, the end): it answers status 1, so the start fails. A memory +// maximum then makes PhwComm_OD8_ApplySettings return before the OD table is +// written (the whole call fails, the new UCLK stays staged and blocks every +// later commit until a call stages the old one again); fast timings record +// the new value and never program the timings (nothing to read back). Also +// not taken: the fan minimum speed and target temperature (ids 10 and 12; the +// driver does not offer them while the fan curve is offered: feature 0, and +// SetGenericSetting skips a setting whose feature is 0). // 0xa1 OD8_SetSettings: in = header {16, 0x00C000A1, 1 = not kept for // replay, 0} + count 38 + 38 x {value, requested, reset, 0, 0} + 8 // unused (788); out = a 0xa0 answer (164), out[0] must equal 38. // Every call carries all ten fan curve entries requested 1: the wanted curve, // or the all-ten reset (FanMode 0, the points back to the driver's defaults). // So the driver's legacy branch for a partial curve (which caps the fan's -// maximum RPM from entry 28) can never run. Every call also carries zero RPM -// and the GFX pair explicitly: the result does not depend on what was staged -// before (a failed call leaves its change staged in the driver). +// maximum RPM from entry 28) can never run. Every call also carries zero RPM, +// the GFX pair and (0.9.0, when the card offers it) the GFX voltage +// explicitly: the result does not depend on what was staged before (a failed +// call leaves its change staged in the driver; a voltage left out of a call +// would keep the staged offset). constexpr uint32_t kEscapeOd8Set = 0xa1; struct Od8SetEntry { int32_t value; @@ -720,6 +772,23 @@ static_assert(sizeof(Od8SetIn) == 16 + 772, "0xa1 request 788 bytes"); constexpr uint32_t kOd8GfxMax = 0, kOd8GfxMin = 1, kOd8MemMax = 8, kOd8TargetTemp = 12, kOd8ZeroRpm = 15, kOd8ZeroRpmStop = 35; constexpr int32_t kOd8GfxFloorMHz = 1500; +// The GFX voltage (0.9.0), id 37, feature 0x20000. Read in HWLibs 25G342: +// PhwComm_OD8_InitializeDefaultSettings offers it when +// PP_OD8VoltageSliderSupport is 1 (the Navi 21 default) with min = swsmu+328, +// max = default = swsmu+332 (881..1075 mV, stock 1075, on the test card); +// PhwComm_OD8_ApplySettings stages value - max (only when min <= value <= +// max, else it keeps the old one) as the OD table's VddGfxOffset (int16 mV, +// smu_11_0_7_set_od_table +46), written whole to the firmware; and +// PhwComm_OD8_UpdateInternalSettings reads the table back and sets current = +// max + VddGfxOffset. So the value is a millivolt cap from which the whole +// GFX voltage curve is offset down; it can never go above max. Linux writes +// the same field (sienna_cichlid_od_edit_dpm_table, PP_OD_EDIT_VDDGFX_OFFSET) +// and only for SMU firmware 58.41.0 or later (the test card: 58.76.0). The +// kext takes it lower only (at or below the card's stock value, at or above +// its minimum), in 25 mV steps from stock, and reads it back exactly. +constexpr uint32_t kOd8GfxVolt = 37; +constexpr uint32_t kOd8VoltFeature = 0x20000; +constexpr int32_t kOd8VoltStepMV = 25; // Factory defaults move a little across a wake (GfxMax 2354 -> 2359 MHz, // 2026-11-19): this much is accepted for the GFX pair, nothing for the rest. constexpr int32_t kOd8DriftMHz = 25; @@ -738,9 +807,13 @@ struct Od8Want { bool zeroRpmOff; int32_t gfxMaxMHz; // 0 = stock int32_t gfxMinMHz; // 0 = stock (0.9.0) + int32_t voltMV; // 0 = stock (0.9.0): the GFX voltage, lower only + bool overclock; // 0.9.0: gfxMaxMHz may be above stock, up to the + // card's 0x9f maximum (a permission, not a setting) }; inline bool od8IsStock(const Od8Want& w) { - return !w.curve && !w.zeroRpmOff && w.gfxMaxMHz == 0 && w.gfxMinMHz == 0; + return !w.curve && !w.zeroRpmOff && w.gfxMaxMHz == 0 && w.gfxMinMHz == 0 && + w.voltMV == 0; } enum class Od8Check : uint32_t { @@ -759,6 +832,8 @@ enum class Od8Check : uint32_t { // fresh readings GfxMinRange, // 0.9.0: GFX min outside the card's range for it, or above // the GFX max of the same state + VoltRange, // 0.9.0: GFX voltage above stock, below the card's minimum, + // or not a 25 mV step from stock }; inline const char* od8CheckText(uint64_t c) { switch (static_cast(c)) { @@ -784,11 +859,15 @@ inline const char* od8CheckText(uint64_t c) { case Od8Check::CurveCooling: return "the curve gives less air than stock somewhere"; case Od8Check::GfxRange: - return "GFX max must be between 1500 MHz and the stock maximum"; + return "GFX max must be between 1500 MHz and the stock maximum (with " + "overclock: the card's own maximum)"; case Od8Check::NoReadings: return "the fan watchdog has no fresh hotspot and fan readings"; case Od8Check::GfxMinRange: return "GFX min must be in the card's range and not above GFX max"; + case Od8Check::VoltRange: + return "GFX voltage must be at or below stock, in the card's range, in " + "25 mV steps from stock"; } return "unknown"; } @@ -894,7 +973,12 @@ inline Od8Check od8CheckWant(const Od8Want& w, const Od8InitialOut& first, } } if (w.gfxMaxMHz != 0) { - int32_t top = od8StockGfxMax(first, fresh); + // Without the overclock flag, the stock maximum; with it (0.9.0), the + // card's own 0x9f maximum for id 0 (the same in both reads, + // od8SameLayout above), the driver's own upper bound for the pair + // (PhwComm_OD8_SetGfxClockLimits: each in its range, FMIN <= FMAX). + int32_t top = + w.overclock ? fresh.e[kOd8GfxMax].max : od8StockGfxMax(first, fresh); if (w.gfxMaxMHz < kOd8GfxFloorMHz || w.gfxMaxMHz > top || w.gfxMaxMHz < first.e[kOd8GfxMin].def) return Od8Check::GfxRange; @@ -906,8 +990,26 @@ inline Od8Check od8CheckWant(const Od8Want& w, const Od8InitialOut& first, if (w.gfxMinMHz < m.min || w.gfxMinMHz > m.max || w.gfxMinMHz > max) return Od8Check::GfxMinRange; } + if (w.voltMV != 0) { + // Offered as at boot, and allowed now (a call that changes a feature the + // driver does not allow is refused whole, PP 7). + const Od8Entry& v = first.e[kOd8GfxVolt]; + if (v.feature != kOd8VoltFeature || (cur.notAllowed & kOd8VoltFeature) != 0) + return Od8Check::NoFeature; + // Lower only: stock is the top; the defaults are the same in both reads + // (the drift check above allows no change outside the GFX pair). + if (w.voltMV < v.min || w.voltMV > v.max || w.voltMV > v.def || + (v.def - w.voltMV) % kOd8VoltStepMV != 0) + return Od8Check::VoltRange; + } return Od8Check::Ok; } +// Whether a held state raises anything above stock (0.9.0): a GFX maximum +// above the stock one. Held under the watchdog like a raised minimum. +inline bool od8RaisesGfxMax(const Od8Want& w, const Od8InitialOut& first, + const Od8InitialOut& fresh) { + return w.overclock && w.gfxMaxMHz > od8StockGfxMax(first, fresh); +} // The whole 0xa1 for a state. With the stock state this is the one fixed way // back (design v3.1 B): the all-ten curve reset, zero RPM at its stock value, @@ -938,10 +1040,18 @@ inline void od8Build(const Od8Want& w, const Od8InitialOut& first, out->e[kOd8GfxMax] = Od8SetEntry{gfx, 1, 0, 0, 0}; int32_t low = w.gfxMinMHz != 0 ? w.gfxMinMHz : first.e[kOd8GfxMin].def; out->e[kOd8GfxMin] = Od8SetEntry{low, 1, 0, 0, 0}; + // The GFX voltage (0.9.0) in every call when the card offers it: the + // wanted value or the fresh stock one, so a held offset never survives a + // way back. Not offered: requested 0 (od8CheckWant refused any voltage). + if (first.e[kOd8GfxVolt].feature == kOd8VoltFeature) { + int32_t mv = w.voltMV != 0 ? w.voltMV : fresh.e[kOd8GfxVolt].def; + out->e[kOd8GfxVolt] = Od8SetEntry{mv, 1, 0, 0, 0}; + } } // Every call's shape, checked again where it is sent: count 38, all ten curve -// entries requested 1 (never 1..9 of them), nothing outside the five -// settings requested, no reset outside the curve. +// entries requested 1 (never 1..9 of them), nothing outside the six +// settings requested (the GFX voltage since 0.9.0), no reset outside the +// curve. inline bool od8ShapeOk(const Od8SetIn& in) { if (in.count != kOd8Count || in.header.code != (kEscapeCode | kEscapeOd8Set) || @@ -952,7 +1062,7 @@ inline bool od8ShapeOk(const Od8SetIn& in) { const Od8SetEntry& e = in.e[i]; bool isCurve = i >= 19 && i <= 28; bool allowed = isCurve || i == kOd8GfxMax || i == kOd8GfxMin || - i == kOd8ZeroRpm || i == kOd8ZeroRpmStop; + i == kOd8ZeroRpm || i == kOd8ZeroRpmStop || i == kOd8GfxVolt; if (e.zero0 != 0 || e.zero1 != 0 || e.requested > 1 || e.reset > 1) return false; if (!allowed && (e.requested != 0 || e.reset != 0)) return false; @@ -961,6 +1071,7 @@ inline bool od8ShapeOk(const Od8SetIn& in) { if (isCurve && e.value <= 0) return false; if (i == kOd8GfxMax && e.requested == 1 && e.value < kOd8GfxFloorMHz) return false; + if (i == kOd8GfxVolt && e.requested == 1 && e.value <= 0) return false; } // The GFX pair always together, the minimum never above the maximum // (the driver refuses the pair otherwise, and then keeps neither). @@ -1064,6 +1175,8 @@ enum class WriteOff : uint32_t { Od8Watchdog, // the fan watchdog took the curve back ReadOnlyCard, // 0.8.0: a card the kext reads but never writes (73BF // rev C0, the RX 6900 XT); the reads run as on the C1 + PowerWatchdog, // 0.9.0: the watchdog put the start-up limit back over + // a raised one (95 C, or no readings) }; struct WritePrereqs { bool ctlOff; @@ -1161,6 +1274,9 @@ inline const char* writeOffText(WriteOff w) { case WriteOff::ReadOnlyCard: return "this card can only be read (RX 6900 XT, 73BF rev C0): writing " "never opens on it"; + case WriteOff::PowerWatchdog: + return "the watchdog put the start-up power limit back over a raised " + "one"; } return "unknown"; } @@ -1371,21 +1487,29 @@ class Owner { // alive in {version} the owner's word, every 5 s // release in {version} the owner goes back to the start-up limit // setOd8 in {version, flags, t1..t5, s1..s5, gfxMaxMHz} (13 scalars) -// or, since 0.9.0, {..., gfxMaxMHz, gfxMinMHz} (14) -// out {reply, Od8Check}; flags 1 = a fan curve, 2 = zero RPM off; -// gfxMaxMHz 0 = stock (0.7.0); gfxMinMHz 0 = stock, and the 13 -// scalar form means a stock minimum. The stock state is the way -// back. +// or, since 0.9.0, {..., gfxMaxMHz, gfxMinMHz} (14) or +// {..., gfxMaxMHz, gfxMinMHz, voltMV} (15) +// out {reply, Od8Check}; flags 1 = a fan curve, 2 = zero RPM off, +// 4 = overclock (0.9.0: gfxMaxMHz may be above stock, up to the +// card's own maximum); gfxMaxMHz 0 = stock (0.7.0); gfxMinMHz 0 +// = stock, and the 13 scalar form means a stock minimum; voltMV 0 +// = stock, and the 13 and 14 scalar forms mean a stock voltage. +// The stock state is the way back. +// set also, since 0.9.0, {version, watts, flags} (3): flags 1 = +// raise (watts may be above the start-up limit, up to the card's +// ceiling, PowerRange::ceilW); the 2-scalar form never raises. // disarm in {version} anyone (0.8.0): closes writing again; // StillApplied while anything is applied; arm reopens it // Version 2 (0.7.0): setOd8, and status grew. A power change and an OD8 // change are never held together: the other kind answers "busy". 0.8.0 adds // disarm and two replies at the end and keeps version 2: nothing an older // program sends means anything else now. An older kext answers disarm with -// kIOReturnBadArgument (an unknown selector). 0.9.0 adds the 14-scalar -// setOd8, one Od8Check (GfxMinRange), one held bit and one status flag -// (kFlagGfxMin) and keeps version 2 the same way; an older kext answers the -// 14-scalar setOd8 with kIOReturnBadArgument (a wrong count). +// kIOReturnBadArgument (an unknown selector). 0.9.0 adds the 14- and +// 15-scalar setOd8 and the 3-scalar set, three Od8Checks' worth of +// refusals (GfxMinRange, VoltRange), two replies (AboveCeiling, NoReadings), +// four held bits, three status flags (kFlagGfxMin, kFlagVolt, kFlagRaise) and +// one WriteOff (PowerWatchdog), and keeps version 2: an older kext answers +// the new counts with kIOReturnBadArgument (a wrong count). // set and setOd8 answer Off (writing off, or a read-only card) and then // NotArmed (never armed since restart, or disarmed) before they look at any // value they carry (valueGate), so an absurd value still gets the real @@ -1425,6 +1549,9 @@ enum class Reply : uint32_t { // being handled; go back to the start-up values first NoFloor, // 0.8.0, set: the card's minimum power limit is not known // (PowerRangeState says why): only the start-up value + AboveCeiling, // 0.9.0, set with the raise flag: above the card's ceiling + NoReadings, // 0.9.0, set with the raise flag: the watchdog has no fresh + // hotspot readings, so nothing above the start-up value }; constexpr uint64_t kSetWaitMs = 5000; inline Reply replyFor(Ask a) { @@ -1460,6 +1587,8 @@ inline Reply replyFor(PowerCheck c) { return Reply::NotAStep; case PowerCheck::NoFloor: return Reply::NoFloor; + case PowerCheck::AboveCeiling: + return Reply::AboveCeiling; } return Reply::BadArgs; } @@ -1512,6 +1641,11 @@ inline const char* replyText(uint64_t r) { case Reply::NoFloor: return "refused: the card's minimum power limit is not known " "(PowerRangeState)"; + case Reply::AboveCeiling: + return "refused: above the card's own power ceiling (PowerRange CeilW)"; + case Reply::NoReadings: + return "refused: no fresh hotspot readings for the watchdog, so no " + "raised limit"; } return "unknown answer"; } @@ -1543,6 +1677,9 @@ enum : uint64_t { kFlagReady = 128, // the PowerPlay object and the start-up limit are known kFlagOd8Ready = 256, // OD8 was read cleanly since boot: setOd8 can work kFlagGfxMin = 512, // 0.9.0: setOd8 takes a GFX minimum (14 scalars) + kFlagVolt = 1024, // 0.9.0: setOd8 takes a GFX voltage (15 scalars) + kFlagRaise = 2048, // 0.9.0: setOd8 takes the overclock flag and set + // the raise form (3 scalars) }; enum : uint64_t { kOd8HeldCurve = 1, @@ -1550,11 +1687,18 @@ enum : uint64_t { kOd8HeldGfx = 4, kOd8HeldUnknown = 8, // not confirmed stock (a failed or unapplied call) kOd8HeldGfxMin = 16, // 0.9.0: a raised GFX minimum + kOd8HeldVolt = 32, // 0.9.0: a lowered GFX voltage + kOd8HeldGfxUp = 64, // 0.9.0: a GFX maximum above stock (overclock) }; // setOd8's flags scalar. enum : uint64_t { kOd8WantCurve = 1, kOd8WantZeroRpmOff = 2, + kOd8WantOverclock = 4, // 0.9.0 +}; +// set's flags scalar (0.9.0, the 3-scalar form). +enum : uint64_t { + kSetWantRaise = 1, }; // ------------------------------------------------ what a call answers first -- // @@ -1597,17 +1741,37 @@ inline Reply setWire(const Owner& o, uint64_t watts, uint32_t* out) { *out = static_cast(watts); return Reply::Ok; } -// setOd8's {version, flags, t1..t5, s1..s5, gfxMaxMHz[, gfxMinMHz]}: the -// gate, then anything that cannot be a fan point or a clock is malformed -// (BadArgs). The clocks' only wire bound is the 32-bit field (0.8.0, was 5000 -// MHz): their first real check is od8CheckWant's, against the card's range. -// count is how many scalars came: kOd8WireCount (0.9.0) or the 0.7.0 form, -// kOd8WireCountV070, whose GFX minimum is the stock one. -constexpr uint32_t kOd8WireCount = 14; +// set's 3-scalar form (0.9.0), {version, watts, flags}: the same, then a +// flag the kext does not know is malformed. +constexpr uint32_t kSetWireCount = 2; +constexpr uint32_t kSetWireCountRaise = 3; +inline bool setWireCountOk(uint32_t count) { + return count == kSetWireCount || count == kSetWireCountRaise; +} +inline Reply setWireRaise(const Owner& o, uint64_t watts, uint64_t flags, + uint32_t* out, bool* raise) { + *raise = false; + Reply g = setWire(o, watts, out); + if (g != Reply::Ok) return g; + if ((flags & ~uint64_t(kSetWantRaise)) != 0) return Reply::BadArgs; + *raise = (flags & kSetWantRaise) != 0; + return Reply::Ok; +} +// setOd8's {version, flags, t1..t5, s1..s5, gfxMaxMHz[, gfxMinMHz[, +// voltMV]]}: the gate, then anything that cannot be a fan point, a clock or +// a voltage is malformed (BadArgs). The clocks' and the voltage's only wire +// bound is the 32-bit field (0.8.0, was 5000 MHz): their first real check is +// od8CheckWant's, against the card's range. count is how many scalars came: +// kOd8WireCount (with the voltage), kOd8WireCountV090 (stock voltage) or the +// 0.7.0 form kOd8WireCountV070 (stock minimum and voltage). The overclock +// flag is taken in every form. +constexpr uint32_t kOd8WireCount = 15; +constexpr uint32_t kOd8WireCountV090 = 14; constexpr uint32_t kOd8WireCountV070 = 13; constexpr uint64_t kOd8WireMaxPoint = 200; inline bool od8WireCountOk(uint32_t count) { - return count == kOd8WireCount || count == kOd8WireCountV070; + return count == kOd8WireCount || count == kOd8WireCountV090 || + count == kOd8WireCountV070; } inline Reply od8Wire(const Owner& o, const uint64_t* in, uint32_t count, Od8Want* want) { @@ -1616,13 +1780,18 @@ inline Reply od8Wire(const Owner& o, const uint64_t* in, uint32_t count, *want = Od8Want{}; if (!od8WireCountOk(count)) return Reply::BadArgs; uint64_t flags = in[1]; - uint64_t low = count == kOd8WireCount ? in[13] : 0; - bool ok = (flags & ~uint64_t(kOd8WantCurve | kOd8WantZeroRpmOff)) == 0 && - in[12] <= 0x7fffffffULL && low <= 0x7fffffffULL; + uint64_t low = count >= kOd8WireCountV090 ? in[13] : 0; + uint64_t mv = count >= kOd8WireCount ? in[14] : 0; + bool ok = (flags & ~uint64_t(kOd8WantCurve | kOd8WantZeroRpmOff | + kOd8WantOverclock)) == 0 && + in[12] <= 0x7fffffffULL && low <= 0x7fffffffULL && + mv <= 0x7fffffffULL; want->curve = (flags & kOd8WantCurve) != 0; want->zeroRpmOff = (flags & kOd8WantZeroRpmOff) != 0; + want->overclock = (flags & kOd8WantOverclock) != 0; want->gfxMaxMHz = static_cast(in[12] <= 0x7fffffffULL ? in[12] : 0); want->gfxMinMHz = static_cast(low <= 0x7fffffffULL ? low : 0); + want->voltMV = static_cast(mv <= 0x7fffffffULL ? mv : 0); for (uint32_t k = 0; k < kOd8CurvePoints; k++) { uint64_t t = in[2 + k], v = in[7 + k]; if (t > kOd8WireMaxPoint || v > kOd8WireMaxPoint || diff --git a/GPU/sensors/kext/kern_control.cpp b/GPU/sensors/kext/kern_control.cpp index f2904d1e..e164bdf7 100644 --- a/GPU/sensors/kext/kern_control.cpp +++ b/GPU/sensors/kext/kern_control.cpp @@ -103,6 +103,20 @@ // and turns writing off. The "too hot with the fan under 90 %" rule // stays with the curve: the stock fan climbs slowly by design. // +// 9. 0.9.0 also. Three more, all inside the card's own OverDrive range (the +// 0x9f read, the same limits AMD's own tool offers) and never past it: +// a lower GFX voltage (OD8 id 37, VddGfxOffset; lower only, 25 mV steps, +// read back exactly, and carried in every call so a way back always puts +// the stock offset back), and two raises that a request must ask for +// with its own flag: a GFX maximum above stock up to the 0x9f maximum +// (setOd8 flag 4), and a power limit above the start-up one up to the +// 0x9f power percent (at most +15 %; set's 3-scalar form). A raise is +// taken only while the watchdog has fresh readings and is held under it +// (95 C or no readings for 10 s: stock back, writing off). Memory clock +// and fast memory timings stay out: on macOS the driver's memory +// overclock start (IRI 0x110018) is not implemented by Apple's DAL glue, +// so the driver never applies them (control_logic.hpp, OD8 writes). +// // Only on an RX 6800 XT (73BF revision C1) or, read only, an RX 6900 XT (C0), // and only when each function starts with the bytes in control_logic.hpp. // Writing needs more: an RX 6800 XT, exactly one AMD GPU, @@ -236,7 +250,11 @@ gpuctl::Od8Check gOd8LastCheck{gpuctl::Od8Check::Ok}; uint64_t gOd8SentPower{0}; // 0xa1 calls during which a power limit went out bool gOd8OffAfterWayBack{false}; // the watchdog tripped: off once stock uint32_t gSlotKind{0}; // 0 power, 1 OD8: what the slot's request is +bool gSlotRaise{false}; // 0.9.0: the power request carries the raise flag gpuctl::Od8Want gSlotWant{}; +// 0.9.0: the watchdog took a raised limit back; off once the start-up one is +// confirmed (runRevert). +bool gPowerOffAfterWayBack{false}; uint32_t gSlotCheck{0}; // the worker's Od8Check for a refused setOd8 const char* gStatus{"waiting for the driver's library"}; @@ -623,10 +641,13 @@ gpuctl::Access askAccess() { return gpuctl::Access::No; return gpuctl::classifyAccess(ret, outSize, out); } -gpuctl::Sent sendLimit(uint32_t boot, uint32_t floor, uint32_t watts) { +// ceil: the card's ceiling for a request with the raise flag (0.9.0), 0 for +// everything else (then nothing above the start-up value is built). +gpuctl::Sent sendLimit(uint32_t boot, uint32_t floor, uint32_t watts, + uint32_t ceil = 0) { if (gReadOnlyCard) return gpuctl::Sent::NotSent; // never on a read-only card gpuctl::SetLimitIn in; - if (!gpuctl::makeSetLimit(boot, floor, watts, &in)) + if (!gpuctl::makeSetLimit(boot, floor, watts, &in, ceil)) return gpuctl::Sent::Failed; __atomic_store_n(&gTagCount, 0, __ATOMIC_RELAXED); __atomic_store_n(&gTagW, 0, __ATOMIC_RELAXED); @@ -766,6 +787,10 @@ void runRevert() { } else { if (!gOwner.isChanged()) gHeldW = 0; gReverts++; + // The watchdog took a raised limit back (0.9.0): off once the + // start-up limit is confirmed. + if (gPowerOffAfterWayBack) + turnOffLocked(gpuctl::WriteOff::PowerWatchdog); } } } else if (next == gpuctl::Next::GiveUp) { @@ -795,6 +820,8 @@ void runRevert() { } } +bool od8DogSees(); + void runSet() { uint64_t t = 0, client = 0; uint32_t watts = 0; @@ -802,8 +829,10 @@ void runSet() { bool have = gSlot.take(&t, &client, &watts); bool off = have && gOwner.isOff(); bool od8 = have && gSlotKind == 1; + bool raise = have && gSlotKind == 0 && gSlotRaise; gpuctl::Od8Want want = gSlotWant; gSlotKind = 0; + gSlotRaise = false; if (off) { // off: answered at once, nothing is asked of the driver gSlot.finish(t, gpuctl::Reply::Off); gLastReply = gpuctl::Reply::Off; @@ -816,9 +845,14 @@ void runSet() { return; } uint32_t boot = bootW(); - uint32_t floor = rangeNow().floorW; // fixed once known; 0 = not known + gpuctl::PowerRange range = rangeNow(); + uint32_t floor = range.floorW; // fixed once known; 0 = not known + // The ceiling only for a request that asked to raise (0.9.0). + uint32_t ceil = raise ? range.ceilW : 0; + // A raised limit is held under the watchdog: never one it cannot watch. + bool blind = raise && watts > boot && !od8DogSees(); // 0x2a first: a GPU that is not up changes nothing, not even Owner. - gpuctl::Access access = askAccess(); + gpuctl::Access access = blind ? gpuctl::Access::No : askAccess(); IOLockLock(gStateLock); gpuctl::Reply reply = gpuctl::Reply::Ok; bool go = false; @@ -826,11 +860,14 @@ void runSet() { reply = gpuctl::Reply::Cancelled; else if (sleepingLocked()) reply = gpuctl::Reply::Sleeping; + else if (blind) + reply = gpuctl::Reply::NoReadings; else if (access != gpuctl::Access::Yes) reply = gpuctl::Reply::NotReady; else if (gOd8Dirty) reply = gpuctl::Reply::Busy; // an OD8 change is held: never both - else if (gpuctl::routeSet(boot, floor, watts) != gpuctl::SetRoute::Change) + else if (gpuctl::routeSet(boot, floor, watts, ceil) != + gpuctl::SetRoute::Change) reply = gpuctl::Reply::BadArgs; // the client routed it already else { reply = gpuctl::replyFor(gOwner.change(client, nowMs())); @@ -845,7 +882,7 @@ void runSet() { } IOLockUnlock(gStateLock); - gpuctl::Sent sent = sendLimit(boot, floor, watts); + gpuctl::Sent sent = sendLimit(boot, floor, watts, ceil); IOLockLock(gStateLock); if (sent == gpuctl::Sent::Failed) { @@ -1106,11 +1143,14 @@ Od8Result od8Commit(bool* sentPower, uint32_t* retOut) { return Od8Result::Confirmed; } -uint64_t od8HeldFlags(const gpuctl::Od8Want& w) { +// raised: the GFX maximum is above stock (od8RaisesGfxMax, 0.9.0). +uint64_t od8HeldFlags(const gpuctl::Od8Want& w, bool raised) { return (w.curve ? gpuctl::kOd8HeldCurve : 0) | (w.zeroRpmOff ? gpuctl::kOd8HeldZeroRpmOff : 0) | (w.gfxMaxMHz != 0 ? gpuctl::kOd8HeldGfx : 0) | - (w.gfxMinMHz != 0 ? gpuctl::kOd8HeldGfxMin : 0); + (w.gfxMinMHz != 0 ? gpuctl::kOd8HeldGfxMin : 0) | + (w.voltMV != 0 ? gpuctl::kOd8HeldVolt : 0) | + (raised ? gpuctl::kOd8HeldGfxUp : 0); } // The fixed way back once (design v3.1 B). Confirmed: stock again. @@ -1183,9 +1223,10 @@ void runSetOd8(uint64_t t, uint64_t client, const gpuctl::Od8Want& want) { IOLockUnlock(gStateLock); gpuctl::Od8Check check = gpuctl::Od8Check::Ok; Od8Result p = Od8Result::Confirmed; - if (reply == gpuctl::Reply::Ok && (want.curve || want.gfxMinMHz != 0) && - !od8DogSees()) { - // never a curve or a raised GFX minimum it cannot watch + if (reply == gpuctl::Reply::Ok && + (want.curve || want.gfxMinMHz != 0 || want.overclock) && !od8DogSees()) { + // never a curve, a raised GFX minimum or (0.9.0) an overclock it cannot + // watch check = gpuctl::Od8Check::NoReadings; p = Od8Result::Refused; reply = gpuctl::Reply::Od8Refused; @@ -1227,10 +1268,12 @@ void runSetOd8(uint64_t t, uint64_t client, const gpuctl::Od8Want& want) { Od8Result back = Od8Result::Confirmed; if (c == Od8Result::Failed) back = od8WayBackOnce(); // stock over it + // wOd8First / wOd8Fresh are the reads od8Prepare checked the state against. + bool raised = gpuctl::od8RaisesGfxMax(want, wOd8First, wOd8Fresh); IOLockLock(gStateLock); if (sentPower) gOd8SentPower++; if (c == Od8Result::Confirmed) { - gOd8Held = od8HeldFlags(want); + gOd8Held = od8HeldFlags(want, raised); gOd8HeldWant = want; gOd8Changes++; gOd8LastCheck = gpuctl::Od8Check::Ok; @@ -1263,8 +1306,10 @@ void runSetOd8(uint64_t t, uint64_t client, const gpuctl::Od8Want& want) { IOLockUnlock(gStateLock); if (c == Od8Result::Confirmed) SYSLOG("gpuctl", - "OD8 change held: curve %d, zero RPM off %d, GFX max %d, GFX min %d", - want.curve, want.zeroRpmOff, want.gfxMaxMHz, want.gfxMinMHz); + "OD8 change held: curve %d, zero RPM off %d, GFX max %d%s, GFX " + "min %d, GFX voltage %d mV", + want.curve, want.zeroRpmOff, want.gfxMaxMHz, + raised ? " (above stock)" : "", want.gfxMinMHz, want.voltMV); if (c == Od8Result::Failed) SYSLOG("gpuctl", "OD8 change FAILED (ppCWDDE 0x%x, read-back %u), way back %s: " @@ -1278,13 +1323,19 @@ void runSetOd8(uint64_t t, uint64_t client, const gpuctl::Od8Want& want) { // climbs slowly by design (75 % at 76 C, 2026-11-19), so only the 95 C limit // and the missing readings count then: the target temperature goes in as 0. uint64_t od8DogPass() { + uint32_t boot = bootW(); IOLockLock(gStateLock); - bool live = gOd8Dirty && !gTornDown && !gOwner.isOff() && !gReadOnlyCard; + bool on = !gTornDown && !gOwner.isOff() && !gReadOnlyCard; + bool live = gOd8Dirty && on; bool curve = live && (gOd8Held & (gpuctl::kOd8HeldCurve | gpuctl::kOd8HeldUnknown)) != 0; - bool low = live && (gOd8Held & gpuctl::kOd8HeldGfxMin) != 0; + // A raised GFX minimum, or (0.9.0) a GFX maximum above stock. + bool low = live && + (gOd8Held & (gpuctl::kOd8HeldGfxMin | gpuctl::kOd8HeldGfxUp)) != 0; + // 0.9.0: a power limit above the start-up one (never with OD8 held). + bool power = on && !gOd8Dirty && gHeldW > boot && !gPowerOffAfterWayBack; IOLockUnlock(gStateLock); - if (!curve && !low) return 0; + if (!curve && !low && !power) return 0; uint64_t now = nowMs(); if (now < wDogNextMs) return wDogNextMs; wDogNextMs = now + 1000; @@ -1297,6 +1348,19 @@ uint64_t od8DogPass() { gpuctl::Od8Dog d = gpuctl::od8Watchdog(&wDog, have, ageNs / 1000000, hot, fan, target, now); if (d == gpuctl::Od8Dog::Fine) return wDogNextMs; + if (power) { + // The start-up limit goes back through runRevert (its 3 tries, and after + // a wake if a sleep comes first); writing goes off once it is confirmed. + SYSLOG("gpuctl", "watchdog: %s (hotspot %u C): start-up power limit", + d == gpuctl::Od8Dog::Trip ? "too hot" : "no readings", hot); + IOLockLock(gStateLock); + gPowerOffAfterWayBack = true; + uint64_t id = gOwner.release(gOwner.owner()); + if (id != 0) gPendingRevert = id; + IOLockUnlock(gStateLock); + signalWorker(); + return 0; + } SYSLOG("gpuctl", "OD8 watchdog: %s (hotspot %u C, fan %u %%): stock fan", d == gpuctl::Od8Dog::Trip ? "too hot" : "no readings", hot, fan); // One try here; if it is not confirmed, writing goes off and the @@ -1791,6 +1855,8 @@ void GPUControl::status(uint64_t client, uint64_t out[gpuctl::kStatusCount]) { uint64_t f = 0; if (od8ok) f |= gpuctl::kFlagOd8Ready; f |= gpuctl::kFlagGfxMin; // 0.9.0: setOd8 takes a GFX minimum + f |= gpuctl::kFlagVolt; // 0.9.0: setOd8 takes a GFX voltage + f |= gpuctl::kFlagRaise; // 0.9.0: the overclock flag and set's raise form if (gOwner.isArmed()) f |= gpuctl::kFlagArmed; if (gOwner.isOff()) f |= gpuctl::kFlagOff; if (sleepingLocked()) f |= gpuctl::kFlagSleeping; @@ -1849,13 +1915,15 @@ gpuctl::Reply GPUControl::disarm(bool administrator) { } gpuctl::Reply GPUControl::set(uint64_t client, uint64_t rawWatts, - const uint32_t* closedFlag) { + uint64_t rawFlags, const uint32_t* closedFlag) { if (gStateLock == nullptr) return gpuctl::Reply::Off; checkRuntime(); uint32_t boot = bootW(); // Before gStateLock (it takes gOd8Lock); fixed once known. - uint32_t floor = rangeNow().floorW; + gpuctl::PowerRange range = rangeNow(); + uint32_t floor = range.floorW; uint32_t watts = 0; + bool raise = false; IOLockLock(gStateLock); // The connection's own flag, set by closed() under this lock: a set that // got past externalMethod's check while the connection closed stops here. @@ -1876,13 +1944,16 @@ gpuctl::Reply GPUControl::set(uint64_t client, uint64_t rawWatts, r = gpuctl::Reply::BadArgs; } else if (gReadOnlyCard) { r = gpuctl::Reply::Off; - } else if ((r = gpuctl::setWire(gOwner, rawWatts, &watts)) != - gpuctl::Reply::Ok) { - // off or not armed, before the value; then a value that is no watts + } else if ((r = gpuctl::setWireRaise(gOwner, rawWatts, rawFlags, &watts, + &raise)) != gpuctl::Reply::Ok) { + // off or not armed, before the value; then a value that is no watts, or + // a flag the kext does not know } else { - switch (gpuctl::routeSet(boot, floor, watts)) { + // The card's ceiling only when the request asked to raise (0.9.0). + uint32_t ceil = raise ? range.ceilW : 0; + switch (gpuctl::routeSet(boot, floor, watts, ceil)) { case gpuctl::SetRoute::Refuse: - r = gpuctl::replyFor(gpuctl::checkPower(boot, floor, watts)); + r = gpuctl::replyFor(gpuctl::checkPower(boot, floor, watts, ceil)); break; case gpuctl::SetRoute::Release: // The start-up value is going back, never a change. @@ -1902,10 +1973,12 @@ gpuctl::Reply GPUControl::set(uint64_t client, uint64_t rawWatts, r = gpuctl::Reply::Busy; // an OD8 change is held: never both if (r == gpuctl::Reply::Ok) { ticket = gSlot.post(client, watts); - if (ticket == 0) + if (ticket == 0) { r = gpuctl::Reply::Busy; - else + } else { gSlotKind = 0; + gSlotRaise = raise; + } } break; } @@ -2011,6 +2084,8 @@ const char* GPUControl::writeText() { text = "armed: going back to the start-up limit"; // One program holds one thing at a time, the power limit or an OD8 change, // and Owner marks both as changed: say which one it is. + else if (gOwner.owner() != 0 && gOwner.isChanged() && gHeldW > bootW()) + text = "armed: a program holds a raised limit (watchdog on)"; else if (gOwner.owner() != 0 && gOwner.isChanged() && gHeldW != 0) text = "armed: a program holds a lower limit"; else if (gOwner.owner() != 0 && gOwner.isChanged() && gOd8Dirty) @@ -2291,7 +2366,7 @@ const char* GPUControl::od8WriteText() { else if ((gOd8Held & gpuctl::kOd8HeldUnknown) != 0) text = "armed: the last OD8 call was not taken; going back to stock"; else if (gOd8Dirty && gOd8Held != 0) - text = "armed: a program holds a fan or clock change"; + text = "armed: a program holds a fan, clock or voltage change"; else if (gOd8Dirty) text = "armed: going back to stock"; else diff --git a/GPU/sensors/kext/kern_control.hpp b/GPU/sensors/kext/kern_control.hpp index 6c67abb1..99ba48d6 100644 --- a/GPU/sensors/kext/kern_control.hpp +++ b/GPU/sensors/kext/kern_control.hpp @@ -57,8 +57,10 @@ gpuctl::Reply disarm(bool administrator); // closedFlag is the connection's own "closed" word: closed() sets it under // the state lock and set() reads it there, so no set lands after a close. // watts is the wire's scalar as sent: Off and NotArmed come before it is -// looked at (gpuctl::setWire). -gpuctl::Reply set(uint64_t client, uint64_t watts, const uint32_t* closedFlag); +// looked at (gpuctl::setWire). flags: the 3-scalar form's (0.9.0, +// kSetWantRaise), 0 for the 2-scalar form. +gpuctl::Reply set(uint64_t client, uint64_t watts, uint64_t flags, + const uint32_t* closedFlag); gpuctl::Reply alive(uint64_t client); gpuctl::Reply release(uint64_t client); // The connection closed or its program died. True the first time only. @@ -83,7 +85,8 @@ OSDictionary* od8Dictionary(); // OD8 writes (0.7.0, design-od8-b.md v3.1), for the user client. setOd8 waits // like set(); *check is the Od8Check when the reply is Od8Refused. in is the // wire's scalars as sent, version first, count of them (kOd8WireCount or the -// 0.7.0 form kOd8WireCountV070; gpuctl::od8Wire). +// 0.9.0 and 0.7.0 forms kOd8WireCountV090 and kOd8WireCountV070; +// gpuctl::od8Wire). gpuctl::Reply setOd8(uint64_t client, const uint64_t* in, uint32_t count, const uint32_t* closedFlag, uint32_t* check); const char* od8WriteText(); diff --git a/GPU/sensors/kext/kern_service.cpp b/GPU/sensors/kext/kern_service.cpp index 0a777ab9..e67894ff 100644 --- a/GPU/sensors/kext/kern_service.cpp +++ b/GPU/sensors/kext/kern_service.cpp @@ -28,11 +28,13 @@ // HeldW, Changes, Reverts, LastReply } // PowerRangeState the card's power range (0.8.0): where the // floor comes from, or why it is not known -// PowerRange { FloorW, MaxW, StepW, PercentMin, -// PercentMax, Known }: the lowest and highest -// limit set takes; Known 1 with FloorW and -// MaxW once the floor is known (FloorW = MaxW -// when the card offers nothing lower); +// PowerRange { FloorW, MaxW, CeilW, StepW, +// PercentMin, PercentMax, Known }: the lowest +// and highest limit set takes; Known 1 with +// FloorW and MaxW once the floor is known +// (FloorW = MaxW when the card offers nothing +// lower); CeilW (0.9.0) the highest with the +// raise flag (= MaxW when nothing higher); // PercentMin/Max once OD8 was read // OD8State OD8 (0.6.0, read only): waiting, read, // not available, or why not @@ -187,6 +189,9 @@ void DrogaBoxGPUSensors::publish() { if (floorKnown) { putNumber(d, "FloorW", pr.floorW); putNumber(d, "MaxW", pr.maxW); + // 0.9.0: the highest limit set's raise form takes (MaxW when the + // card offers nothing higher). + putNumber(d, "CeilW", pr.ceilW > pr.maxW ? pr.ceilW : pr.maxW); } putNumber(d, "StepW", gpuctl::kStepW); if (pr.state != gpuctl::FloorState::NoBootValue && @@ -239,12 +244,17 @@ void DrogaBoxGPUSensors::publish() { putNumber(d, "GfxMaxHeld", static_cast(ow.want.gfxMaxMHz)); if (ow.want.gfxMinMHz != 0) putNumber(d, "GfxMinHeld", static_cast(ow.want.gfxMinMHz)); + if (ow.want.voltMV != 0) + putNumber(d, "VoltHeld", static_cast(ow.want.voltMV)); // 0.9.0: what setOd8 takes, in the Held bits (1 fan curve, 2 zero RPM - // off, 4 GFX max, 16 GFX min), so a program knows the GFX minimum is - // there before it sends one. + // off, 4 GFX max, 16 GFX min; 0.9.0: 32 GFX voltage, 64 GFX max above + // stock with the overclock flag), so a program knows a setting is + // there before it sends one. The card must still offer it (OD8 + // Settings, Feature not 0). putNumber(d, "Takes", gpuctl::kOd8HeldCurve | gpuctl::kOd8HeldZeroRpmOff | - gpuctl::kOd8HeldGfx | gpuctl::kOd8HeldGfxMin); + gpuctl::kOd8HeldGfx | gpuctl::kOd8HeldGfxMin | + gpuctl::kOd8HeldVolt | gpuctl::kOd8HeldGfxUp); setProperty("OD8WriteState", d); d->release(); } @@ -361,9 +371,14 @@ IOReturn DrogaBoxGPUControlClient::externalMethod( if (args == nullptr || selector >= gpuctl::kSelCount) return kIOReturnBadArgument; uint32_t wantIn = 1; - if (selector == gpuctl::kSelSet) wantIn = 2; - // setOd8 takes two counts (0.9.0): its 0.7.0 form and the one with a - // GFX minimum. The count is passed on; od8Wire reads only what came. + // set takes two counts (0.9.0): {version, watts} and the raise form. + if (selector == gpuctl::kSelSet) + wantIn = gpuctl::setWireCountOk(args->scalarInputCount) + ? args->scalarInputCount + : gpuctl::kSetWireCount; + // setOd8 takes three counts: its 0.7.0 form, the one with a GFX minimum + // (0.9.0) and the one with a GFX voltage (0.9.0). The count is passed on; + // od8Wire reads only what came. if (selector == gpuctl::kSelSetOd8) wantIn = gpuctl::od8WireCountOk(args->scalarInputCount) ? args->scalarInputCount @@ -418,7 +433,11 @@ IOReturn DrogaBoxGPUControlClient::externalMethod( break; case gpuctl::kSelSet: // The value is looked at only after off and not armed (setWire). - r = GPUControl::set(id_, args->scalarInput[1], &closed_); + r = GPUControl::set(id_, args->scalarInput[1], + args->scalarInputCount == gpuctl::kSetWireCountRaise + ? args->scalarInput[2] + : 0, + &closed_); break; case gpuctl::kSelAlive: r = GPUControl::alive(id_); @@ -427,7 +446,8 @@ IOReturn DrogaBoxGPUControlClient::externalMethod( r = GPUControl::release(id_); break; case gpuctl::kSelSetOd8: { - // {version, flags, t1..t5, s1..s5, gfxMaxMHz[, gfxMinMHz]}, decoded + // {version, flags, t1..t5, s1..s5, gfxMaxMHz[, gfxMinMHz[, voltMV]]}, + // decoded // by gpuctl::od8Wire after off and not armed; the kext checks the // rest. uint32_t check = 0; diff --git a/GPU/sensors/tests/controltest.cpp b/GPU/sensors/tests/controltest.cpp index 31889935..bba4c6a7 100644 --- a/GPU/sensors/tests/controltest.cpp +++ b/GPU/sensors/tests/controltest.cpp @@ -871,11 +871,14 @@ static void od8Writes() { in.e[0].reset == 0 && in.e[1].reset == 0, "stock: the GFX pair as explicit stock values, no reset flags"); bool others = true; - const uint32_t untouched[] = {8, 9, 10, 11, 12, 13, 14, - 16, 17, 18, 29, 36, 37}; + const uint32_t untouched[] = {8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 29, 36}; for (uint32_t i : untouched) others = others && in.e[i].requested == 0 && in.e[i].reset == 0; - check(others, "memory, power %, voltage, power mode, auto OC/UV: untouched"); + check(others, "memory, power %, power mode, auto OC/UV: untouched"); + check( + in.e[37].requested == 1 && in.e[37].reset == 0 && in.e[37].value == 1075, + "stock (0.9.0): the GFX voltage as its explicit stock value, so a " + "held offset never survives the way back"); Od8InitialOut woke = first; woke.e[0].def = 2359; od8Build(stock, first, woke, &in); @@ -1042,7 +1045,7 @@ static void od8Writes() { after.cur[15] = 0; after.notAllowed = 0; check(od8VerifyAfter(in, cur, after) == 39, "the allowed mask moved: 39"); - od8Build(g = Od8Want{0, {}, {}, false, 2300, 0}, first, fresh, &in); + od8Build(g = Od8Want{0, {}, {}, false, 2300, 0, 0, false}, first, fresh, &in); after = cur; after.cur[0] = 2295; check(od8VerifyAfter(in, cur, after) == 0, "GFX read back 5 MHz lower: ok"); @@ -1104,6 +1107,7 @@ static void od8Scalars(uint64_t in[kOd8WireCount], uint64_t flags, } in[12] = gfx; in[13] = 0; // the GFX minimum (0.9.0): stock + in[14] = 0; // the GFX voltage (0.9.0): stock } static void readOnlyCard() { check(deviceReadable(0x1002, 0x73BF, 0xC0) && @@ -1293,7 +1297,7 @@ static void wires() { const uint64_t okT[5] = {30, 40, 44, 46, 48}; const uint64_t okS[5] = {20, 36, 52, 68, 100}; Od8Want want{}; - od8Scalars(in, 4, zero, zero, 0); + od8Scalars(in, 8, zero, zero, 0); // 4 is the overclock flag since 0.9.0 bool bad = od8Wire(o, in, kOd8WireCount, &want) == Reply::BadArgs; od8Scalars(in, kOd8WantCurve, okT, okS, 0); in[3] = 201; @@ -1469,12 +1473,12 @@ static void gfxMin() { "GFX min 1500: the pair goes out as {2354 stock, 1500}"); bool others = true; const uint32_t untouched[] = {8, 9, 10, 11, 12, 13, 14, - 16, 17, 18, 29, 34, 36, 37}; + 16, 17, 18, 29, 34, 36}; for (uint32_t i : untouched) others = others && in.e[i].requested == 0 && in.e[i].reset == 0; - check(others, - "memory max and min, fan minimum and target, power %, voltage: " - "untouched with a GFX minimum"); + check(others && in.e[37].requested == 1 && in.e[37].value == 1075, + "memory max and min, fan minimum and target, power %: untouched " + "with a GFX minimum; the voltage at its stock 1075 mV (0.9.0)"); b.gfxMaxMHz = 2000; od8Build(b, first, fresh, &in); check(od8ShapeOk(in) && in.e[0].value == 2000 && in.e[1].value == 1500, @@ -1519,27 +1523,28 @@ static void gfxMin() { Od8Want want{}; od8Scalars(w14, 0, zero, zero, 0); w14[13] = 1500; - check(od8Wire(o, w14, kOd8WireCount, &want) == Reply::NotArmed, + check(od8Wire(o, w14, kOd8WireCountV090, &want) == Reply::NotArmed, "the 14-scalar form answers not armed before its values"); o.arm(); - check(od8Wire(o, w14, kOd8WireCount, &want) == Reply::Ok && + check(od8Wire(o, w14, kOd8WireCountV090, &want) == Reply::Ok && want.gfxMinMHz == 1500 && want.gfxMaxMHz == 0 && !want.curve, "14 scalars: the GFX minimum is decoded as sent"); check(od8Wire(o, w14, kOd8WireCountV070, &want) == Reply::Ok && want.gfxMinMHz == 0, "13 scalars (0.7.0): the 14th is never read, the minimum is stock"); check(od8Wire(o, w14, 12, &want) == Reply::BadArgs && - od8Wire(o, w14, 15, &want) == Reply::BadArgs && - !od8WireCountOk(12) && od8WireCountOk(13) && od8WireCountOk(14), - "any other count: malformed"); + od8Wire(o, w14, 16, &want) == Reply::BadArgs && + !od8WireCountOk(12) && od8WireCountOk(13) && od8WireCountOk(14) && + od8WireCountOk(15) && !od8WireCountOk(16), + "any other count: malformed (15, the 0.9.0 form, is taken)"); w14[13] = 0x80000000ULL; - check(od8Wire(o, w14, kOd8WireCount, &want) == Reply::BadArgs, + check(od8Wire(o, w14, kOd8WireCountV090, &want) == Reply::BadArgs, "a minimum the 32-bit field cannot carry: malformed"); Owner gone; gone.arm(); gone.turnOff(); w14[13] = 1500; - check(od8Wire(gone, w14, kOd8WireCount, &want) == Reply::Off, + check(od8Wire(gone, w14, kOd8WireCountV090, &want) == Reply::Off, "writing off: off before the minimum is looked at"); // The watchdog while only a GFX minimum is held: target 0, so only the @@ -1558,6 +1563,281 @@ static void gfxMin() { "GfxMinRange is 12 with a text, held bit 16, status flag 512"); } +// ------------------------------------ 0.9.0 tests: voltage and raises -- +// The GFX voltage (OD8 id 37): lower only, inside the card's 0x9f range +// (881-1075 mV on the test card, stock 1075), 25 mV steps from stock, carried +// in every call, read back exactly. +static void gfxVolt() { + Od8InitialOut first, fresh; + cardInitial(&first); + fresh = first; + Od8CurrentOut cur; + cardCurrent(first, &cur); + Od8Want v{}; + v.voltMV = 1050; + check(!od8IsStock(v), "a GFX voltage is not the stock state"); + check(od8CheckWant(v, first, fresh, cur) == Od8Check::Ok, + "1050 mV (stock 1075 - 25): taken"); + v.voltMV = 900; + check(od8CheckWant(v, first, fresh, cur) == Od8Check::Ok, + "900 mV (stock - 175, the lowest 25 mV step above the 881 minimum): " + "taken"); + v.voltMV = 1075; + check(od8CheckWant(v, first, fresh, cur) == Od8Check::Ok, + "the stock 1075 mV itself: taken"); + v.voltMV = 1076; + bool refused = od8CheckWant(v, first, fresh, cur) == Od8Check::VoltRange; + v.voltMV = 1100; + refused = + refused && od8CheckWant(v, first, fresh, cur) == Od8Check::VoltRange; + check(refused, "1 mV or 25 mV above stock: refused (lower only)"); + v.voltMV = 875; + refused = od8CheckWant(v, first, fresh, cur) == Od8Check::VoltRange; + v.voltMV = 880; + refused = + refused && od8CheckWant(v, first, fresh, cur) == Od8Check::VoltRange; + check(refused, "below the card's 881 mV minimum: refused, never clamped"); + v.voltMV = 1060; + check(od8CheckWant(v, first, fresh, cur) == Od8Check::VoltRange, + "1060 mV, not a 25 mV step from stock: refused"); + Od8InitialOut nv = first; + nv.e[37] = Od8Entry{}; + v.voltMV = 1050; + check(od8CheckWant(v, nv, nv, cur) == Od8Check::NoFeature, + "a card that does not offer the voltage: refused as not offered"); + Od8CurrentOut na = cur; + na.notAllowed |= kOd8VoltFeature; + check(od8CheckWant(v, first, fresh, na) == Od8Check::NoFeature, + "offered but not allowed now: refused (the driver would refuse the " + "whole call)"); + Od8InitialOut low = first; + low.e[37] = Od8Entry{0x20000, 881, 1150, 1100, 0, 0}; + v.voltMV = 1125; + bool fromStock = od8CheckWant(v, low, low, cur) == Od8Check::VoltRange; + v.voltMV = 1075; + fromStock = fromStock && od8CheckWant(v, low, low, cur) == Od8Check::Ok; + check(fromStock, + "the top is the card's stock value, not its maximum (another card: " + "1100 stock, 1150 max)"); + + Od8SetIn in; + v.voltMV = 1050; + od8Build(v, first, fresh, &in); + check(od8ShapeOk(in) && in.e[37].value == 1050 && in.e[37].requested == 1 && + in.e[37].reset == 0 && in.e[0].value == 2354 && + in.e[1].value == 500 && in.e[8].requested == 0 && + in.e[14].requested == 0 && in.e[19].reset == 1, + "1050 mV: entry 37 = 1050 requested, the GFX pair at stock, memory " + "and AC timing untouched, the curve as the reset"); + od8Build(Od8Want{}, first, fresh, &in); + check(in.e[37].value == 1075 && in.e[37].requested == 1, + "the way back sends the stock 1075 mV over a held offset"); + od8Build(Od8Want{}, nv, nv, &in); + check(in.e[37].requested == 0 && od8ShapeOk(in), + "not offered: entry 37 never requested"); + od8Build(v, first, fresh, &in); + in.e[37].value = 0; + check(!od8ShapeOk(in), "a shape with a voltage of 0 is never sent"); + od8Build(v, first, fresh, &in); + in.e[37].reset = 1; + check(!od8ShapeOk(in), "nor one with a voltage reset flag"); + od8Build(v, first, fresh, &in); + in.e[14].requested = 1; + check(!od8ShapeOk(in), "nor one that asks for fast memory timings"); + od8Build(v, first, fresh, &in); + in.e[8].requested = 1; + check(!od8ShapeOk(in), "nor one that asks for a memory clock"); + + // The read-back: exact, the driver reads max + VddGfxOffset back. + od8Build(v, first, fresh, &in); + Od8CurrentOut after = cur; + after.cur[37] = 1050; + check(od8VerifyAfter(in, cur, after) == 0, "1050 mV read back: ok"); + after.cur[37] = 1049; + check(od8VerifyAfter(in, cur, after) == 38, "1 mV off: entry 37 reported"); + after.cur[37] = 1075; + check(od8VerifyAfter(in, cur, after) == 38, + "not taken (still 1075): reported"); + + // The wire: the 15th scalar. + Owner o; + uint64_t w15[kOd8WireCount]; + const uint64_t zero[5] = {0, 0, 0, 0, 0}; + od8Scalars(w15, 0, zero, zero, 0); + w15[14] = 1050; + Od8Want want{}; + check(od8Wire(o, w15, kOd8WireCount, &want) == Reply::NotArmed, + "15 scalars: not armed before the voltage is looked at"); + o.arm(); + check(od8Wire(o, w15, kOd8WireCount, &want) == Reply::Ok && + want.voltMV == 1050 && want.gfxMinMHz == 0 && !want.overclock, + "15 scalars: the voltage is decoded as sent"); + check(od8Wire(o, w15, kOd8WireCountV090, &want) == Reply::Ok && + want.voltMV == 0, + "14 scalars: the 15th is never read, the voltage is stock"); + w15[14] = 0x80000000ULL; + check(od8Wire(o, w15, kOd8WireCount, &want) == Reply::BadArgs, + "a voltage the 32-bit field cannot carry: malformed"); + check(static_cast(Od8Check::VoltRange) == 13 && + od8CheckText(13)[0] != '\0' && kOd8HeldVolt == 32 && + kFlagVolt == 1024 && kOd8GfxVolt == 37 && + od8Feature(kOd8GfxVolt) == kOd8VoltFeature, + "VoltRange is 13 with a text, held bit 32, status flag 1024"); +} + +// The GFX maximum above stock (0.9.0): only with the overclock flag, up to +// the card's own 0x9f maximum (2800 on the test card), never past it. +static void gfxOverclock() { + Od8InitialOut first, fresh; + cardInitial(&first); + fresh = first; + Od8CurrentOut cur; + cardCurrent(first, &cur); + Od8Want g{}; + g.gfxMaxMHz = 2500; + check(od8CheckWant(g, first, fresh, cur) == Od8Check::GfxRange, + "2500 MHz without the overclock flag: refused as before"); + g.overclock = true; + check(od8CheckWant(g, first, fresh, cur) == Od8Check::Ok && + od8RaisesGfxMax(g, first, fresh), + "2500 MHz with the flag: taken, and it raises above stock"); + g.gfxMaxMHz = 2800; + check(od8CheckWant(g, first, fresh, cur) == Od8Check::Ok, + "the card's own 2800 MHz maximum: taken"); + g.gfxMaxMHz = 2801; + check(od8CheckWant(g, first, fresh, cur) == Od8Check::GfxRange, + "one step above the 0x9f maximum (2801): refused"); + g.gfxMaxMHz = 2825; + check(od8CheckWant(g, first, fresh, cur) == Od8Check::GfxRange, + "2825 (25 MHz past the maximum): refused"); + g.gfxMaxMHz = 2300; + check(od8CheckWant(g, first, fresh, cur) == Od8Check::Ok && + !od8RaisesGfxMax(g, first, fresh), + "a lower maximum with the flag: taken, not a raise"); + g.gfxMaxMHz = 1400; + check(od8CheckWant(g, first, fresh, cur) == Od8Check::GfxRange, + "the 1500 MHz floor holds with the flag too"); + Od8Want stockFlag{}; + stockFlag.overclock = true; + check(od8IsStock(stockFlag) && + od8CheckWant(stockFlag, first, fresh, cur) == Od8Check::Ok && + !od8RaisesGfxMax(stockFlag, first, fresh), + "the flag alone is the stock state: a permission, not a setting"); + g.gfxMaxMHz = 2600; + g.gfxMinMHz = 2600; + check(od8CheckWant(g, first, fresh, cur) == Od8Check::Ok, + "a minimum up to a raised maximum: taken (FMIN <= FMAX)"); + g.gfxMinMHz = 2601; + check(od8CheckWant(g, first, fresh, cur) == Od8Check::GfxMinRange, + "a minimum above the raised maximum: refused"); + Od8SetIn in; + g.gfxMinMHz = 0; + g.gfxMaxMHz = 2500; + od8Build(g, first, fresh, &in); + check(od8ShapeOk(in) && in.e[0].value == 2500 && in.e[1].value == 500 && + in.e[0].requested == 1 && in.e[1].requested == 1, + "2500 MHz: the pair goes out as {2500, 500 stock}"); + Od8CurrentOut after = cur; + after.cur[0] = 2500; + check(od8VerifyAfter(in, cur, after) == 0, "2500 read back: ok"); + after.cur[0] = 2480; + check(od8VerifyAfter(in, cur, after) == 0, + "20 MHz lower (the firmware rounds): ok, as for a lower maximum"); + after.cur[0] = 2354; + check(od8VerifyAfter(in, cur, after) == 1, + "the firmware kept stock: reported (no silent overclock claim)"); + Owner o; + o.arm(); + uint64_t w[kOd8WireCount]; + const uint64_t zero[5] = {0, 0, 0, 0, 0}; + od8Scalars(w, kOd8WantOverclock, zero, zero, 2500); + Od8Want want{}; + check(od8Wire(o, w, kOd8WireCountV070, &want) == Reply::Ok && + want.overclock && want.gfxMaxMHz == 2500, + "the overclock flag is taken in the 13-scalar form too"); + check(kOd8WantOverclock == 4 && kOd8HeldGfxUp == 64 && kFlagRaise == 2048, + "overclock flag 4, held bit 64, status flag 2048"); +} + +// The power limit above the start-up one (0.9.0): only with the raise flag, +// up to the start-up value plus the card's 0x9f power percent (at most 15). +static void powerRaise() { + Od8InitialOut t; + cardInitial(&t); + PowerRange r = powerRange(240, true, false, t); + check(r.ceilW == 261, + "the owner's card: 240 W plus its +9 % is a 261 W ceiling (Linux's " + "power1_cap_max, rounded down)"); + check(checkPower(240, r.floorW, 250) == PowerCheck::AboveBoot && + routeSet(240, r.floorW, 250) == SetRoute::Refuse, + "250 W without the raise flag: above the start-up limit, as before"); + check(checkPower(240, r.floorW, 250, r.ceilW) == PowerCheck::Ok && + checkPower(240, r.floorW, 260, r.ceilW) == PowerCheck::Ok && + routeSet(240, r.floorW, 260, r.ceilW) == SetRoute::Change, + "250 and 260 W with the flag: a change"); + check(checkPower(240, r.floorW, 261, r.ceilW) == PowerCheck::Ok, + "the ceiling itself (261, not a 10 W step): taken"); + check( + checkPower(240, r.floorW, 262, r.ceilW) == PowerCheck::AboveCeiling && + checkPower(240, r.floorW, 270, r.ceilW) == PowerCheck::AboveCeiling && + replyFor(PowerCheck::AboveCeiling) == Reply::AboveCeiling, + "1 W or one 10 W step above the ceiling: refused"); + check(checkPower(240, r.floorW, 255, r.ceilW) == PowerCheck::NotAStep, + "255 W: not a 10 W step"); + check(checkPower(240, r.floorW, 230, r.ceilW) == PowerCheck::Ok && + checkPower(240, r.floorW, 220, r.ceilW) == PowerCheck::BelowFloor && + checkPower(240, r.floorW, 240, r.ceilW) == PowerCheck::Ok, + "the flag changes nothing below the start-up limit"); + SetLimitIn in{}; + check(makeSetLimit(240, r.floorW, 260, &in, r.ceilW) && in.watts == 260 && + !makeSetLimit(240, r.floorW, 260, &in) && + !makeSetLimit(240, r.floorW, 270, &in, r.ceilW), + "the 0x6e bytes are built only with the ceiling and inside it"); + Od8InitialOut x = t; + x.e[kOd8PowerPercent].max = 20; + check(powerRange(264, true, false, x).ceilW == 303, + "a table offering +20 %: cut at AMD's +15 (264 W -> 303 W)"); + x.e[kOd8PowerPercent].max = 15; + check(powerRange(264, true, false, x).ceilW == 303, "+15 %: 303 W"); + x.e[kOd8PowerPercent].max = 0; + PowerRange flat = powerRange(240, true, false, x); + check(flat.ceilW == 240 && checkPower(240, flat.floorW, 250, flat.ceilW) == + PowerCheck::AboveBoot, + "no percent up: the ceiling is the start-up limit, nothing higher"); + x = t; + x.e[kOd8PowerPercent] = Od8Entry{0, -6, 9, 0, 0, 0}; + check(powerRange(240, true, false, x).ceilW == 0, + "no power limit feature: no ceiling"); + check(powerRange(240, false, false, Od8InitialOut{}).ceilW == 0 && + powerRange(240, true, true, t).ceilW == 0, + "OD8 not read, or its first read odd: no ceiling"); + + // The wire: {version, watts, flags}. + Owner o; + uint32_t w = 0; + bool raise = true; + check(setWireRaise(o, 250, kSetWantRaise, &w, &raise) == Reply::NotArmed && + !raise, + "the raise form answers not armed before its values"); + o.arm(); + check(setWireRaise(o, 250, kSetWantRaise, &w, &raise) == Reply::Ok && raise && + w == 250, + "armed: the raise flag is decoded"); + check(setWireRaise(o, 250, 0, &w, &raise) == Reply::Ok && !raise, + "flags 0: no raise"); + check(setWireRaise(o, 250, 2, &w, &raise) == Reply::BadArgs && !raise, + "an unknown flag: malformed"); + check(setWireCountOk(2) && setWireCountOk(3) && !setWireCountOk(1) && + !setWireCountOk(4), + "set takes 2 or 3 scalars"); + check(static_cast(Reply::AboveCeiling) == 21 && + static_cast(Reply::NoReadings) == 22 && + replyText(21)[0] != '\0' && replyText(22)[0] != '\0' && + static_cast(WriteOff::PowerWatchdog) == 16 && + writeOffText(WriteOff::PowerWatchdog)[0] != '\0', + "replies 21 and 22, WriteOff 16, with their texts"); +} + int main() { card(); profiles(); @@ -1584,6 +1864,9 @@ int main() { wires(); floors(); gfxMin(); + gfxVolt(); + gfxOverclock(); + powerRaise(); if (failures != 0) printf("%d FAILED\n", failures); return failures == 0 ? 0 : 1; } diff --git a/GPU/sensors/tests/curve_fixturegen.cpp b/GPU/sensors/tests/curve_fixturegen.cpp index 4694c273..c69d83b7 100644 --- a/GPU/sensors/tests/curve_fixturegen.cpp +++ b/GPU/sensors/tests/curve_fixturegen.cpp @@ -25,7 +25,9 @@ // All other ids (2-7, 13, 29-34): unpublished, zero. // Prints one JSON line per case: {"want":{...},"check":}. // A GFX minimum (0.9.0) is written as "gfxMin" only when it is not stock, so -// the 100 lines from before it stay byte for byte as they were. +// the 100 lines from before it stay byte for byte as they were; the same for +// the GFX voltage ("volt") and the overclock flag ("overclock": true), added +// later in 0.9.0, so the first 120 lines stay as they were too. #include #include #include @@ -50,9 +52,10 @@ static void loadReal() { first.count = fresh.count = cur.count = kOd8Count; first.caps = fresh.caps = caps; // cur.notAllowed: doCheck does (uint32)cfInt(d,"NotAllowed"); the dump - // prints 18446744073709338866, which cfInt (SInt32) reads as -22750. - // od8CheckWant never reads notAllowed, so the value cannot affect output. - cur.notAllowed = static_cast(-22750); + // prints 18446744073709338866 = 2^64 - 212750, which is 0xfffcc0f2 as 32 + // bits (the app's bits("NotAllowed") reads the same). od8CheckWant reads it + // only for a GFX voltage, so the first 120 lines do not depend on it. + cur.notAllowed = 0xfffcc0f2u; setEntry(kOd8GfxMax, 1, 500, 2800, 2359, 2359, 2359); setEntry(kOd8GfxMin, 1, 500, 2800, 500, 500, 500); setEntry(kOd8MemMax, 4, 2000, 2150, 2000, 2000, 2000); @@ -80,7 +83,8 @@ static void loadReal() { // A state mutation, so cases can exercise Drifted / MemoryMoved / NoFeature // which the real dump (first == fresh == cur, all features present) cannot // reach. Serialised into the JSONL so main.swift replays the same mutation. -// kind: freshCaps | firstCaps | freshEntry | firstEntry | bothEntry | cur +// kind: freshCaps | firstCaps | freshEntry | firstEntry | bothEntry | cur | +// notAllowed (the 0xa0 mask, value only) // (bothEntry = same field on first and fresh, so od8SameLayout still passes). struct Mut { const char* kind; @@ -113,6 +117,8 @@ static void applyMut(Od8InitialOut& F, Od8InitialOut& R, Od8CurrentOut& C, } else if (std::strcmp(m.kind, "bothEntry") == 0) { applyEntry(F.e[m.id], m.field, m.value); applyEntry(R.e[m.id], m.field, m.value); + } else if (std::strcmp(m.kind, "notAllowed") == 0) { + C.notAllowed = static_cast(m.value); } else { // cur C.cur[m.id] = static_cast(m.value); } @@ -130,6 +136,8 @@ static void emit(const Od8Want& w, std::initializer_list muts = {}) { w.temp[4], w.speed[0], w.speed[1], w.speed[2], w.speed[3], w.speed[4], w.zeroRpmOff ? "true" : "false", w.gfxMaxMHz); if (w.gfxMinMHz != 0) printf(",\"gfxMin\":%d", w.gfxMinMHz); + if (w.voltMV != 0) printf(",\"volt\":%d", w.voltMV); + if (w.overclock) printf(",\"overclock\":true"); printf("},\"muts\":["); bool sep = false; for (const Mut& m : muts) { @@ -138,7 +146,7 @@ static void emit(const Od8Want& w, std::initializer_list muts = {}) { if (m.field != nullptr) printf("{\"kind\":\"%s\",\"id\":%u,\"field\":\"%s\",\"value\":%lld}", m.kind, m.id, m.field, static_cast(m.value)); - else if (m.kind[0] == 'f') // freshCaps / firstCaps + else if (m.kind[0] == 'f' || m.kind[0] == 'n') // caps, notAllowed printf("{\"kind\":\"%s\",\"value\":%lld}", m.kind, static_cast(m.value)); else // cur @@ -406,6 +414,47 @@ int main() { emit(w, {{"bothEntry", kOd8GfxMin, "max", 540}}); // GfxMinRange emit(w, {{"bothEntry", kOd8GfxMin, "feature", 8}}); // NoFeature first } + // 0.9.0, the GFX voltage (id 37): lower only, 25 mV steps from stock. + { + Od8Want w{}; + for (int32_t mv : + {1075, 1050, 1025, 1000, 900, 1076, 1100, 880, 875, 1060, 1049}) + w.voltMV = mv, emit(w); + w.voltMV = 1050; + emit(w, {{"bothEntry", kOd8GfxVolt, "feature", 0}}); // NoFeature + emit(w, {{"notAllowed", 0, nullptr, 0xfffec0f2}}); // NoFeature + emit(w, {{"bothEntry", kOd8GfxVolt, "def", 1100}, + {"bothEntry", kOd8GfxVolt, "max", 1150}}); // Ok + w.voltMV = 1125; + emit(w, {{"bothEntry", kOd8GfxVolt, "def", 1100}, + {"bothEntry", kOd8GfxVolt, "max", 1150}}); // VoltRange + w.voltMV = 1050; + emit(w, {{"freshEntry", kOd8GfxVolt, "def", 1050}}); // Drifted + Od8Want c = curve(new int32_t[5]{30, 40, 44, 46, 48}, + new int32_t[5]{20, 36, 52, 68, 100}, true, 2300); + c.gfxMinMHz = 1800; + c.voltMV = 1050; + emit(c); // Ok: everything at once + } + // 0.9.0, the overclock flag: the GFX maximum up to the card's 2800. + { + Od8Want w{}; + w.overclock = true; + emit(w); // Ok: the flag alone is stock + for (int32_t mhz : {2359, 2360, 2500, 2800, 2801, 2825, 1400}) + w.gfxMaxMHz = mhz, emit(w); + w.gfxMaxMHz = 2600; + w.gfxMinMHz = 2600; + emit(w); // Ok: FMIN <= FMAX with a raised max + w.gfxMinMHz = 2601; + emit(w); // GfxMinRange + w.gfxMinMHz = 0; + w.gfxMaxMHz = 2700; + emit(w, {{"bothEntry", kOd8GfxMax, "max", 2600}}); // GfxRange: its own max + w.overclock = false; + w.gfxMaxMHz = 2500; + emit(w); // GfxRange: no flag + } return 0; } diff --git a/GPU/sensors/tool/gpucontrol.cpp b/GPU/sensors/tool/gpucontrol.cpp index 045da136..e1bf3399 100644 --- a/GPU/sensors/tool/gpucontrol.cpp +++ b/GPU/sensors/tool/gpucontrol.cpp @@ -5,25 +5,33 @@ // gpucontrol od8 what the kext read of OD8 (fan // curve, clock ranges); anyone // gpucontrol hold [fan C:%,C:%,C:%,C:%,C:%] [zerorpm off] [gfxmax MHz] -// [gfxmin MHz] +// [gfxmin MHz] [volt mV] [overclock] // -- holds that fan curve / zero RPM // off / lower GFX max / raised GFX -// min (0.9.0) while the command -// runs, then stock (0.7.0) +// min (0.9.0) / lower GFX voltage +// (0.9.0) while the command runs, +// then stock (0.7.0); overclock +// (0.9.0) lets gfxmax go above +// stock, up to the card's maximum // gpucontrol check [fan ...] [zerorpm off] [gfxmax MHz] [gfxmin MHz] +// [volt mV] [overclock] // says whether the kext would take // it, and why not; sends nothing // sudo gpucontrol arm opens writing until restart // gpucontrol disarm closes it again (0.8.0), anyone; // refused while a change is applied -// gpucontrol hold power -- lowers the limit to W watts while +// gpucontrol hold power [raise] -- +// lowers the limit to W watts while // the command runs, then puts the -// start-up limit back +// start-up limit back; with raise +// (0.9.0) W may be above the +// start-up limit, up to the card's +// ceiling (PowerRange CeilW) // // The kext only takes the card's own minimum (PowerRange, 0.8.0) up to the -// limit the card started with, in 10 W steps, from one program at a time, and -// only after `arm`. It refuses anything else; this command does not clamp or -// retry a refused value. +// limit the card started with (or, with raise, its ceiling), in 10 W steps, +// from one program at a time, and only after `arm`. It refuses anything else; +// this command does not clamp or retry a refused value. // // hold always releases: when the command ends, on Ctrl-C, SIGTERM (passed on // to the command) or SIGHUP, and if this command is killed the kext sees the @@ -62,12 +70,12 @@ const char* kUsage = " gpucontrol od8\n" " sudo gpucontrol arm\n" " gpucontrol disarm\n" - " gpucontrol hold power -- [args...]\n" + " gpucontrol hold power [raise] -- [args...]\n" " gpucontrol hold [fan C:%,C:%,C:%,C:%,C:%] [zerorpm off] [gfxmax " - "MHz] [gfxmin MHz]" + "MHz] [gfxmin MHz] [volt mV] [overclock]" " -- [args...]\n" " gpucontrol check [fan C:%,...] [zerorpm off] [gfxmax MHz] [gfxmin " - "MHz]\n"; + "MHz] [volt mV] [overclock]\n"; volatile sig_atomic_t gSignal = 0; // A SIGTERM has its own flag: a later Ctrl-C or hangup overwrites gSignal, and @@ -136,7 +144,7 @@ struct Channel { }; const char* writeOffName(uint64_t w) { - if (w > static_cast(WriteOff::ReadOnlyCard)) + if (w > static_cast(WriteOff::PowerWatchdog)) return "unknown reason"; return writeOffText(static_cast(w)); } @@ -293,6 +301,7 @@ void releaseAndReport(Channel& ch, bool od8) { struct HoldReq { bool od8 = false; uint32_t watts = 0; + bool raise = false; // 0.9.0: watts may be above the start-up limit Od8Want want{}; }; @@ -328,12 +337,18 @@ bool parseMHz(const char* s, int32_t* out) { return true; } // The OD8 options: fan CURVE, zerorpm off, gfxmax MHz, gfxmin MHz (0.9.0), -// in any order, each once. argv ends at the first "--" or at the end. -// Returns how many words it took, 0 on a mistake. +// volt mV and overclock (0.9.0, one word), in any order, each once. argv +// ends at the first "--" or at the end. Returns how many words it took, 0 on +// a mistake. int parseOd8(char** argv, int argc, Od8Want* w) { int i = 0; - bool fan = false, zero = false, gfx = false, low = false; + bool fan = false, zero = false, gfx = false, low = false, volt = false; while (i < argc && strcmp(argv[i], "--") != 0) { + if (strcmp(argv[i], "overclock") == 0 && !w->overclock) { + w->overclock = true; + i += 1; + continue; + } if (strcmp(argv[i], "fan") == 0 && i + 1 < argc && !fan) { if (!parseCurve(argv[i + 1], w)) { fprintf(stderr, @@ -352,16 +367,20 @@ int parseOd8(char** argv, int argc, Od8Want* w) { } else if (strcmp(argv[i], "gfxmin") == 0 && i + 1 < argc && !low) { if (!parseMHz(argv[i + 1], &w->gfxMinMHz)) return 0; low = true; + } else if (strcmp(argv[i], "volt") == 0 && i + 1 < argc && !volt) { + if (!parseMHz(argv[i + 1], &w->voltMV)) return 0; // same bounds + volt = true; } else { return 0; } i += 2; } - return (fan || zero || gfx || low) ? i : 0; + // overclock alone changes nothing: it only lets gfxmax go above stock. + return (fan || zero || gfx || low || volt) ? i : 0; } void describe(const HoldReq& q, char* out, size_t n) { if (!q.od8) { - snprintf(out, n, "limit %u W", q.watts); + snprintf(out, n, "limit %u W%s", q.watts, q.raise ? " (raise)" : ""); return; } size_t used = 0; @@ -378,30 +397,58 @@ void describe(const HoldReq& q, char* out, size_t n) { used += snprintf(out + used, n - used, "%sGFX max %d MHz", used ? "; " : "", q.want.gfxMaxMHz); if (q.want.gfxMinMHz != 0 && used < n) - snprintf(out + used, n - used, "%sGFX min %d MHz", used ? "; " : "", - q.want.gfxMinMHz); + used += snprintf(out + used, n - used, "%sGFX min %d MHz", used ? "; " : "", + q.want.gfxMinMHz); + if (q.want.voltMV != 0 && used < n) + used += snprintf(out + used, n - used, "%sGFX voltage %d mV", + used ? "; " : "", q.want.voltMV); + if (q.want.overclock && used < n) + snprintf(out + used, n - used, "%soverclock on", used ? "; " : ""); } // Sends the request once. *check: why an OD8 state was refused. Reply sendReq(Channel& ch, const HoldReq& q, uint64_t* check) { *check = 0; - if (!q.od8) return ch.call(kSelSet, q.watts, true); + if (!q.od8 && !q.raise) return ch.call(kSelSet, q.watts, true); + if (!q.od8) { + // The raise form (0.9.0): {version, watts, raise}. + uint64_t in[kSetWireCountRaise] = {kChannelVersion, q.watts, kSetWantRaise}; + uint64_t out[1] = {0}; + uint32_t outCount = 1; + kern_return_t kr = IOConnectCallScalarMethod( + ch.conn, kSelSet, in, kSetWireCountRaise, out, &outCount); + if (kr == kIOReturnBadArgument) + fprintf(stderr, + "gpucontrol: this GPUSensors takes no raised limit (0.9.0 or " + "newer does)\n"); + if (kr != KERN_SUCCESS || outCount < 1) return Reply::BadArgs; + return static_cast(out[0]); + } uint64_t in[kOd8WireCount] = {kChannelVersion}; in[1] = (q.want.curve ? kOd8WantCurve : 0) | - (q.want.zeroRpmOff ? kOd8WantZeroRpmOff : 0); + (q.want.zeroRpmOff ? kOd8WantZeroRpmOff : 0) | + (q.want.overclock ? kOd8WantOverclock : 0); for (uint32_t k = 0; k < kOd8CurvePoints; k++) { in[2 + k] = q.want.curve ? static_cast(q.want.temp[k]) : 0; in[7 + k] = q.want.curve ? static_cast(q.want.speed[k]) : 0; } in[12] = static_cast(q.want.gfxMaxMHz); in[13] = static_cast(q.want.gfxMinMHz); - // The 0.7.0 form unless a GFX minimum is asked: a 0.7.x or 0.8.x kext - // takes only 13 scalars (and refuses 14 with kIOReturnBadArgument). - uint32_t count = q.want.gfxMinMHz != 0 ? kOd8WireCount : kOd8WireCountV070; + in[14] = static_cast(q.want.voltMV); + // The shortest form that carries the request: a 0.7.x or 0.8.x kext takes + // only 13 scalars, a 0.9.x one 13 or 14 (both refuse more with + // kIOReturnBadArgument). + uint32_t count = q.want.voltMV != 0 ? kOd8WireCount + : q.want.gfxMinMHz != 0 ? kOd8WireCountV090 + : kOd8WireCountV070; uint64_t out[2] = {0, 0}; uint32_t outCount = 2; kern_return_t kr = IOConnectCallScalarMethod(ch.conn, kSelSetOd8, in, count, out, &outCount); if (kr == kIOReturnBadArgument && count == kOd8WireCount) + fprintf(stderr, + "gpucontrol: this GPUSensors takes no GFX voltage (0.9.0 or " + "newer does)\n"); + if (kr == kIOReturnBadArgument && count == kOd8WireCountV090) fprintf(stderr, "gpucontrol: this GPUSensors takes no GFX minimum (0.9.0 or " "newer does)\n"); @@ -618,18 +665,24 @@ void printRange() { if (state && CFGetTypeID(state) == CFStringGetTypeID()) CFStringGetCString(static_cast(state), text, sizeof(text), kCFStringEncodingUTF8); - bool haveFloor = false; - int64_t floorW = 0, maxW = 0; + bool haveFloor = false, haveCeil = false; + int64_t floorW = 0, maxW = 0, ceilW = 0; if (range && CFGetTypeID(range) == CFDictionaryGetTypeID()) { auto d = static_cast(range); floorW = cfInt(d, "FloorW", &haveFloor); maxW = cfInt(d, "MaxW"); + ceilW = cfInt(d, "CeilW", &haveCeil); } if (haveFloor) printf(" range %lld-%lld W in 10 W steps (%s)\n", floorW, maxW, text); else printf(" range %s\n", text); + if (haveFloor && haveCeil && ceilW > maxW) + printf( + " raise up to %lld W with hold power raise (the card's " + "own power percent)\n", + ceilW); if (state) CFRelease(state); if (range) CFRelease(range); } @@ -782,13 +835,17 @@ int main(int argc, char** argv) { if (argc == 2 && strcmp(argv[1], "disarm") == 0) return doDisarm(); if (argc == 2 && strcmp(argv[1], "od8") == 0) return doOd8(); if (argc >= 6 && strcmp(argv[1], "hold") == 0 && - strcmp(argv[2], "power") == 0 && strcmp(argv[4], "--") == 0) { + strcmp(argv[2], "power") == 0 && + (strcmp(argv[4], "--") == 0 || + (argc >= 7 && strcmp(argv[4], "raise") == 0 && + strcmp(argv[5], "--") == 0))) { HoldReq q; if (!parseWatts(argv[3], &q.watts)) { fprintf(stderr, "gpucontrol: %s is not a number of watts\n", argv[3]); return 64; } - return doHold(q, argv + 5); + q.raise = strcmp(argv[4], "raise") == 0; + return doHold(q, argv + (q.raise ? 6 : 5)); } if (argc >= 5 && strcmp(argv[1], "hold") == 0) { HoldReq q; diff --git a/README.md b/README.md index 30e837f8..540c0d8a 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ For the Radeon RX 6800, 6800 XT and 6900 XT on an OpenCore Mac (an RX 6950 XT sh - **Hardware AV1 and VP9 decoding.** Safari and Chrome play AV1 and VP9 on the GPU instead of the CPU, YouTube in 4K60 included. - **Full-speed hardware encoding.** HEVC and H.264 encoding keep the video engine's clocks up: OBS at 4K60 without repeated frames, and sizes wider than 4096 without GPU stalls. - **GPU sensors.** Edge, memory and VR temperatures, voltages, throttling, video and fabric clocks and the PCIe link, which Apple's driver already reads and keeps hidden. They show up everywhere in the app, like any other sensor. -- **GPU control.** With the GPU sensors kext, a Settings page for the power limit (from the start-up value down to the card's own minimum, worked out the way Linux does), a five-point fan curve with zero RPM and a live check of what the card will accept, and a lower maximum GFX clock. Changes are opened with your administrator password until the Mac restarts, and **Remember** can apply your last settings again at launch and after a wake. +- **GPU control.** With the GPU sensors kext, a Settings page for the power limit (from the start-up value down to the card's own minimum, worked out the way Linux does), a five-point fan curve with zero RPM and a live check of what the card will accept, a lower maximum or raised minimum GFX clock, a lower GFX voltage (undervolt), and an Overclock section, off by default, that raises the GFX clock and the power limit only inside the card's own OverDrive limits. Changes are opened with your administrator password until the Mac restarts, and **Remember** can apply your last settings again at launch and after a wake (a voltage or a raise only after a wake). Every control, its range and its risks: [GPU control](docs/GPU_CONTROL.md). - **GPU RX 6000 installer.** Checks the Mac, installs only what is needed, updates what is out of date, says when a part waits for a reboot, and removes everything again. Every part runs only on the macOS builds it was checked against and stays off on any other one. What each needs, what was run on which card, and how to build it: [GPU/README.md](GPU/README.md). diff --git a/Sources/RyzenStatus/Core/DefaultsKey+App.swift b/Sources/RyzenStatus/Core/DefaultsKey+App.swift index c46bb0e9..9219f34f 100644 --- a/Sources/RyzenStatus/Core/DefaultsKey+App.swift +++ b/Sources/RyzenStatus/Core/DefaultsKey+App.swift @@ -1104,4 +1104,14 @@ extension DefaultsKey { static let gpuControlRememberedGfxMHz = "gpuControlRememberedGfxMHz" /// A raised GFX minimum (GPUSensors 0.9.0), in MHz. static let gpuControlRememberedGfxMinMHz = "gpuControlRememberedGfxMinMHz" + /// A lowered GFX voltage (GPUSensors 0.9.0), in mV. Saved with the rest + /// of the state, never asked for again at launch. + static let gpuControlRememberedVoltMV = "gpuControlRememberedVoltMV" + /// The overclock flag of a remembered raised GFX maximum (GPUSensors + /// 0.9.0). Saved with the rest of the state, never asked for again at + /// launch. + static let gpuControlRememberedOverclock = "gpuControlRememberedOverclock" + /// The "Allow overclocking" switch of Settings > GPU control (off by + /// default). + static let gpuControlOverclock = "gpuControlOverclock" } diff --git a/Sources/RyzenStatus/Core/GPUControlOverclockStrings.swift b/Sources/RyzenStatus/Core/GPUControlOverclockStrings.swift new file mode 100644 index 00000000..7e5949ab --- /dev/null +++ b/Sources/RyzenStatus/Core/GPUControlOverclockStrings.swift @@ -0,0 +1,420 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 RyzenStatus + +import Foundation + +/// The GFX voltage and Overclock sections of Settings > GPU control +/// (GPUSensors 0.9.0). Built like `GPUControlClockStrings`; the power note +/// and the wait of a switch reuse the clock section's texts. +struct GPUControlOverclockStrings { + // The GFX voltage section. + /// The section's header, and the slider's VoiceOver label. + let voltSection: String + /// VoiceOver: the mV field. + let voltFieldLabel: String + /// VoiceOver: the stepper; %d = its step in mV. + let voltStepperFormat: String + let voltToggle: String + /// %d = the stock voltage in mV. + let voltStockFormat: String + /// The slider's VoiceOver help: %1$d = the lowest value, %2$d = stock, + /// both in mV. + let voltSliderHelpFormat: String + /// %1$d = the lowest value, %2$d = stock, %3$d = the step, all in mV. + let voltOutOfRangeFormat: String + /// %d = one step below stock, in mV. + let voltRecommendedFormat: String + /// The button that puts the starting point into the control. + let voltUseRecommended: String + /// The button that sends the value in the control. + let voltApply: String + let voltFooter: String + + // The Overclock section. + let ocSection: String + let ocToggle: String + /// Under the switch: what can and cannot happen. + let ocWarning: String + /// The raised GFX maximum's row, and its slider's VoiceOver label. + let ocGfxLabel: String + /// VoiceOver: the MHz field. + let ocGfxFieldLabel: String + /// VoiceOver: the stepper; %d = its step in MHz. + let ocGfxStepperFormat: String + /// The slider's VoiceOver help: %1$d = stock, %2$d = the card's + /// maximum, both in MHz. + let ocGfxSliderHelpFormat: String + /// %d = the card's own maximum in MHz, under the slider's top end. + let ocGfxTopFormat: String + /// The raised power limit's pop-up. + let ocPowerLabel: String + /// VoiceOver's hint on that pop-up. + let ocPowerHint: String + let ocFooter: String + + var all: [String] { + [voltSection, voltFieldLabel, voltStepperFormat, voltToggle, voltStockFormat, voltSliderHelpFormat, + voltOutOfRangeFormat, voltRecommendedFormat, voltUseRecommended, voltApply, voltFooter, + ocSection, ocToggle, ocWarning, ocGfxLabel, ocGfxFieldLabel, ocGfxStepperFormat, ocGfxSliderHelpFormat, + ocGfxTopFormat, ocPowerLabel, ocPowerHint, ocFooter] + } +} + +extension FeatureStrings { + static func gpuControlOverclock(_ language: AppLanguage) -> GPUControlOverclockStrings { + switch language { + case .enUS: return .enUS + case .ptBR: return .ptBR + case .tr: return .tr + case .ru: return .ru + case .es: return .es + case .sk: return .sk + case .de: return .de + case .fr: return .fr + case .it: return .it + case .ja: return .ja + case .ko: return .ko + case .zhHans: return .zhHans + case .zhTW, .zhHK: return .zhTW + case .uk: return .uk + } + } +} + +extension GPUControlOverclockStrings { + static let enUS = GPUControlOverclockStrings( + voltSection: "GFX voltage", + voltFieldLabel: "GFX voltage in mV", + voltStepperFormat: "GFX voltage, steps of %d mV", + voltToggle: "Lower the GFX voltage", + voltStockFormat: "Stock (%d mV)", + voltSliderHelpFormat: "From %1$d mV to the stock voltage, %2$d mV. Only lowers it; the value is sent when you stop moving it.", + voltOutOfRangeFormat: "Choose a value from %1$d to %2$d mV, in steps of %3$d mV from stock.", + voltRecommendedFormat: "Recommended starting point: %d mV. A starting point to test, not a guarantee.", + voltUseRecommended: "Use Starting Point", + voltApply: "Apply", + voltFooter: "Lowers the whole GPU voltage curve by the difference to stock: less heat and less power. If it is too low, the GPU can freeze, reset its driver or show a black screen. Go down 25 mV at a time, test with a game or a benchmark, and stay 10–20 mV above the lowest value that was stable. It goes back to stock when RyzenStatus quits, on restart and after sleep. Silicon varies from card to card.", + ocSection: "Overclock", + ocToggle: "Allow overclocking", + ocWarning: "Inside AMD’s own limits for this card nothing can burn, but a value can be unstable: the GPU can freeze or reset its driver. Everything goes back to stock when you turn this off, when RyzenStatus quits, on restart and after sleep, and the watchdog puts stock back at 95 °C.", + ocGfxLabel: "GFX maximum above stock", + ocGfxFieldLabel: "Raised GFX maximum clock in MHz", + ocGfxStepperFormat: "Raised GFX maximum clock, steps of %d MHz", + ocGfxSliderHelpFormat: "From the stock maximum, %1$d MHz, to the card’s maximum, %2$d MHz. The value is sent when you stop moving it.", + ocGfxTopFormat: "Card maximum (%d MHz)", + ocPowerLabel: "Power limit above start-up", + ocPowerHint: "Applies when chosen, up to the card’s own ceiling.", + ocFooter: "More clock usually needs more power to gain anything. The kext holds one thing at a time: a power limit and the clock, fan or voltage settings are never held together. Turning overclocking off puts back whatever it raised.") + + static let es = GPUControlOverclockStrings( + voltSection: "Voltaje de GFX", + voltFieldLabel: "Voltaje de GFX en mV", + voltStepperFormat: "Voltaje de GFX, pasos de %d mV", + voltToggle: "Bajar el voltaje de GFX", + voltStockFormat: "De fábrica (%d mV)", + voltSliderHelpFormat: "De %1$d mV al voltaje de fábrica, %2$d mV. Solo lo baja; el valor se manda cuando dejas de moverlo.", + voltOutOfRangeFormat: "Elige un valor entre %1$d y %2$d mV, en pasos de %3$d mV desde el de fábrica.", + voltRecommendedFormat: "Punto de partida recomendado: %d mV. Es un punto de partida para probar, no una garantía.", + voltUseRecommended: "Usar punto de partida", + voltApply: "Aplicar", + voltFooter: "Baja toda la curva de voltaje de la GPU en la diferencia con el de fábrica: menos calor y menos consumo. Si queda demasiado bajo, la GPU puede congelarse, reiniciar su driver o dejar la pantalla en negro. Baja 25 mV cada vez, prueba con un juego o un benchmark y quédate 10–20 mV por encima del valor más bajo que fue estable. Vuelve al de fábrica al salir de RyzenStatus, al reiniciar y después del reposo. Cada chip es distinto, aun en el mismo modelo de tarjeta.", + ocSection: "Overclock", + ocToggle: "Permitir overclock", + ocWarning: "Dentro de los límites que AMD fija para esta tarjeta nada se puede quemar, pero un valor puede ser inestable: la GPU puede congelarse o reiniciar su driver. Todo vuelve a los valores de fábrica al apagar esto, al salir de RyzenStatus, al reiniciar y después del reposo, y el vigilante vuelve a los valores de fábrica a los 95 °C.", + ocGfxLabel: "Máximo de GFX sobre el de fábrica", + ocGfxFieldLabel: "Reloj máximo de GFX subido, en MHz", + ocGfxStepperFormat: "Reloj máximo de GFX subido, pasos de %d MHz", + ocGfxSliderHelpFormat: "Del máximo de fábrica, %1$d MHz, al máximo de la tarjeta, %2$d MHz. El valor se manda cuando dejas de moverlo.", + ocGfxTopFormat: "Máximo de la tarjeta (%d MHz)", + ocPowerLabel: "Límite de potencia sobre el de arranque", + ocPowerHint: "Se aplica al elegirlo, hasta el tope de la propia tarjeta.", + ocFooter: "Para ganar algo, más reloj suele necesitar más potencia. El kext mantiene una sola cosa a la vez: un límite de potencia y los ajustes de reloj, ventilador o voltaje nunca se mantienen juntos. Al apagar el overclock vuelve todo lo que había subido.") + + static let ptBR = GPUControlOverclockStrings( + voltSection: "Tensão da GFX", + voltFieldLabel: "Tensão da GFX em mV", + voltStepperFormat: "Tensão da GFX, passos de %d mV", + voltToggle: "Reduzir a tensão da GFX", + voltStockFormat: "Padrão (%d mV)", + voltSliderHelpFormat: "De %1$d mV à tensão padrão, %2$d mV. Só reduz; o valor é enviado quando você para de movê-lo.", + voltOutOfRangeFormat: "Escolha um valor entre %1$d e %2$d mV, em passos de %3$d mV a partir do padrão.", + voltRecommendedFormat: "Ponto de partida recomendado: %d mV. Um ponto de partida para testar, não uma garantia.", + voltUseRecommended: "Usar ponto de partida", + voltApply: "Aplicar", + voltFooter: "Reduz toda a curva de tensão da GPU pela diferença em relação ao padrão: menos calor e menos consumo. Se ficar baixa demais, a GPU pode travar, reiniciar o driver ou deixar a tela preta. Desça 25 mV por vez, teste com um jogo ou benchmark e fique 10–20 mV acima do menor valor que foi estável. Volta ao padrão quando o RyzenStatus fecha, ao reiniciar e depois do repouso. Cada chip é diferente, mesmo no mesmo modelo de placa.", + ocSection: "Overclock", + ocToggle: "Permitir overclock", + ocWarning: "Dentro dos limites da própria AMD para esta placa nada pode queimar, mas um valor pode ser instável: a GPU pode travar ou reiniciar o driver. Tudo volta ao padrão ao desligar isto, quando o RyzenStatus fecha, ao reiniciar e depois do repouso, e o vigilante restaura o padrão a 95 °C.", + ocGfxLabel: "Máximo da GFX acima do padrão", + ocGfxFieldLabel: "Clock máximo da GFX elevado em MHz", + ocGfxStepperFormat: "Clock máximo da GFX elevado, passos de %d MHz", + ocGfxSliderHelpFormat: "Do máximo padrão, %1$d MHz, ao máximo da placa, %2$d MHz. O valor é enviado quando você para de movê-lo.", + ocGfxTopFormat: "Máximo da placa (%d MHz)", + ocPowerLabel: "Limite de energia acima da inicialização", + ocPowerHint: "Aplica ao escolher, até o teto da própria placa.", + ocFooter: "Mais clock costuma precisar de mais energia para ganhar algo. O kext mantém uma coisa por vez: um limite de energia e ajustes de clock, ventoinha ou tensão nunca ficam juntos. Desligar o overclock devolve o que ele elevou.") + + static let tr = GPUControlOverclockStrings( + voltSection: "GFX gerilimi", + voltFieldLabel: "mV cinsinden GFX gerilimi", + voltStepperFormat: "GFX gerilimi, %d mV adımlarla", + voltToggle: "GFX gerilimini düşür", + voltStockFormat: "Fabrika (%d mV)", + voltSliderHelpFormat: "%1$d mV ile fabrika gerilimi %2$d mV arası. Yalnızca düşürür; değer, kaydırmayı bıraktığınızda gönderilir.", + voltOutOfRangeFormat: "Fabrika değerinden %3$d mV adımlarla %1$d ile %2$d mV arasında bir değer seçin.", + voltRecommendedFormat: "Önerilen başlangıç noktası: %d mV. Denemek için bir başlangıç noktasıdır, garanti değildir.", + voltUseRecommended: "Başlangıç noktasını kullan", + voltApply: "Uygula", + voltFooter: "GPU'nun tüm gerilim eğrisini fabrika değerine olan fark kadar düşürür: daha az ısı ve daha az güç. Fazla düşükse GPU donabilir, sürücüsünü sıfırlayabilir veya siyah ekran gösterebilir. Her seferinde 25 mV düşürün, bir oyun veya benchmark ile deneyin ve kararlı kalan en düşük değerin 10–20 mV üstünde kalın. RyzenStatus kapanınca, yeniden başlatınca ve uykudan sonra fabrika değerine döner. Her çip farklıdır.", + ocSection: "Hız aşırtma", + ocToggle: "Hız aşırtmaya izin ver", + ocWarning: "AMD'nin bu kart için koyduğu sınırlar içinde hiçbir şey yanamaz, ama bir değer kararsız olabilir: GPU donabilir veya sürücüsünü sıfırlayabilir. Bunu kapattığınızda, RyzenStatus kapanınca, yeniden başlatınca ve uykudan sonra her şey fabrika değerine döner; bekçi 95 °C'de fabrika değerlerini geri getirir.", + ocGfxLabel: "Fabrika değerinin üstünde maks. GFX", + ocGfxFieldLabel: "MHz cinsinden yükseltilmiş maks. GFX saat hızı", + ocGfxStepperFormat: "Yükseltilmiş maks. GFX saat hızı, %d MHz adımlarla", + ocGfxSliderHelpFormat: "Fabrika maksimumu %1$d MHz ile kartın maksimumu %2$d MHz arası. Değer, kaydırmayı bıraktığınızda gönderilir.", + ocGfxTopFormat: "Kart maksimumu (%d MHz)", + ocPowerLabel: "Başlangıç değerinin üstünde güç sınırı", + ocPowerHint: "Seçildiğinde uygulanır, kartın kendi tavanına kadar.", + ocFooter: "Daha yüksek saat hızı, bir kazanç sağlamak için genellikle daha fazla güç ister. Kext aynı anda tek bir şey tutar: güç sınırı ile saat hızı, fan veya gerilim ayarları asla birlikte tutulmaz. Hız aşırtmayı kapatmak, yükselttiği her şeyi geri alır.") + + static let ru = GPUControlOverclockStrings( + voltSection: "Напряжение GFX", + voltFieldLabel: "Напряжение GFX в мВ", + voltStepperFormat: "Напряжение GFX, шаг %d мВ", + voltToggle: "Снизить напряжение GFX", + voltStockFormat: "Заводское (%d мВ)", + voltSliderHelpFormat: "От %1$d мВ до заводского напряжения %2$d мВ. Только снижает; значение отправляется, когда вы отпускаете ползунок.", + voltOutOfRangeFormat: "Выберите значение от %1$d до %2$d мВ с шагом %3$d мВ от заводского.", + voltRecommendedFormat: "Рекомендуемая отправная точка: %d мВ. Это точка для проверки, а не гарантия.", + voltUseRecommended: "Взять отправную точку", + voltApply: "Применить", + voltFooter: "Снижает всю кривую напряжения GPU на разницу с заводским: меньше нагрев и потребление. Если слишком низко, GPU может зависнуть, перезапустить драйвер или показать чёрный экран. Снижайте по 25 мВ, проверяйте игрой или бенчмарком и держитесь на 10–20 мВ выше самого низкого стабильного значения. Возвращается к заводскому при выходе из RyzenStatus, при перезагрузке и после сна. Каждый чип отличается.", + ocSection: "Разгон", + ocToggle: "Разрешить разгон", + ocWarning: "В пределах, которые AMD задаёт для этой карты, ничего не сгорит, но значение может быть нестабильным: GPU может зависнуть или перезапустить драйвер. Всё возвращается к заводскому, когда вы выключаете это, при выходе из RyzenStatus, при перезагрузке и после сна, а сторож возвращает заводские значения при 95 °C.", + ocGfxLabel: "Макс. частота GFX выше заводской", + ocGfxFieldLabel: "Повышенная макс. частота GFX в МГц", + ocGfxStepperFormat: "Повышенная макс. частота GFX, шаг %d МГц", + ocGfxSliderHelpFormat: "От заводского максимума %1$d МГц до максимума карты %2$d МГц. Значение отправляется, когда вы отпускаете ползунок.", + ocGfxTopFormat: "Максимум карты (%d МГц)", + ocPowerLabel: "Лимит мощности выше значения загрузки", + ocPowerHint: "Применяется при выборе, до потолка самой карты.", + ocFooter: "Чтобы что-то выиграть, большей частоте обычно нужна большая мощность. Kext удерживает только одно за раз: лимит мощности и настройки частоты, вентилятора или напряжения никогда не удерживаются вместе. Выключение разгона возвращает всё, что он поднял.") + + static let sk = GPUControlOverclockStrings( + voltSection: "Napätie GFX", + voltFieldLabel: "Napätie GFX v mV", + voltStepperFormat: "Napätie GFX, kroky po %d mV", + voltToggle: "Znížiť napätie GFX", + voltStockFormat: "Továrenské (%d mV)", + voltSliderHelpFormat: "Od %1$d mV po továrenské napätie %2$d mV. Iba znižuje; hodnota sa odošle, keď ho prestanete posúvať.", + voltOutOfRangeFormat: "Vyberte hodnotu od %1$d do %2$d mV v krokoch po %3$d mV od továrenskej.", + voltRecommendedFormat: "Odporúčaný východiskový bod: %d mV. Východiskový bod na skúšanie, nie záruka.", + voltUseRecommended: "Použiť východiskový bod", + voltApply: "Použiť", + voltFooter: "Zníži celú krivku napätia GPU o rozdiel oproti továrenskej hodnote: menej tepla a menšia spotreba. Ak je príliš nízko, GPU môže zamrznúť, reštartovať ovládač alebo ukázať čiernu obrazovku. Znižujte po 25 mV, skúšajte hrou alebo benchmarkom a zostaňte 10–20 mV nad najnižšou stabilnou hodnotou. Po ukončení RyzenStatus, reštarte a po spánku sa vráti na továrenskú hodnotu. Každý čip je iný.", + ocSection: "Pretaktovanie", + ocToggle: "Povoliť pretaktovanie", + ocWarning: "V rámci limitov, ktoré AMD určuje pre túto kartu, nič nezhorí, ale hodnota môže byť nestabilná: GPU môže zamrznúť alebo reštartovať ovládač. Všetko sa vráti na továrenské hodnoty po vypnutí tejto voľby, po ukončení RyzenStatus, po reštarte a po spánku a strážca vráti továrenské hodnoty pri 95 °C.", + ocGfxLabel: "Maximum GFX nad továrenskou hodnotou", + ocGfxFieldLabel: "Zvýšený maximálny takt GFX v MHz", + ocGfxStepperFormat: "Zvýšený maximálny takt GFX, kroky po %d MHz", + ocGfxSliderHelpFormat: "Od továrenského maxima %1$d MHz po maximum karty %2$d MHz. Hodnota sa odošle, keď ho prestanete posúvať.", + ocGfxTopFormat: "Maximum karty (%d MHz)", + ocPowerLabel: "Limit príkonu nad štartovacou hodnotou", + ocPowerHint: "Použije sa po výbere, až po strop samotnej karty.", + ocFooter: "Vyšší takt zvyčajne potrebuje viac príkonu, aby niečo priniesol. Kext drží naraz len jednu vec: limit príkonu a nastavenia taktu, ventilátora alebo napätia sa nikdy nedržia spolu. Vypnutie pretaktovania vráti všetko, čo zvýšilo.") + + static let de = GPUControlOverclockStrings( + voltSection: "GFX-Spannung", + voltFieldLabel: "GFX-Spannung in mV", + voltStepperFormat: "GFX-Spannung, Schritte von %d mV", + voltToggle: "GFX-Spannung senken", + voltStockFormat: "Werkswert (%d mV)", + voltSliderHelpFormat: "Von %1$d mV bis zur Werksspannung, %2$d mV. Nur senken; der Wert wird gesendet, wenn du ihn loslässt.", + voltOutOfRangeFormat: "Wähle einen Wert von %1$d bis %2$d mV, in Schritten von %3$d mV ab dem Werkswert.", + voltRecommendedFormat: "Empfohlener Startpunkt: %d mV. Ein Startpunkt zum Testen, keine Garantie.", + voltUseRecommended: "Startpunkt verwenden", + voltApply: "Anwenden", + voltFooter: "Senkt die ganze Spannungskurve der GPU um den Abstand zum Werkswert: weniger Wärme und weniger Verbrauch. Ist sie zu niedrig, kann die GPU einfrieren, ihren Treiber neu starten oder ein schwarzes Bild zeigen. Geh in Schritten von 25 mV nach unten, teste mit einem Spiel oder Benchmark und bleib 10–20 mV über dem niedrigsten stabilen Wert. Beim Beenden von RyzenStatus, beim Neustart und nach dem Ruhezustand geht sie auf den Werkswert zurück. Jeder Chip ist anders.", + ocSection: "Übertakten", + ocToggle: "Übertakten erlauben", + ocWarning: "Innerhalb der Grenzen, die AMD für diese Karte selbst setzt, kann nichts durchbrennen, aber ein Wert kann instabil sein: Die GPU kann einfrieren oder ihren Treiber neu starten. Alles geht auf die Werkswerte zurück, wenn du das ausschaltest, wenn RyzenStatus beendet wird, beim Neustart und nach dem Ruhezustand, und der Wächter stellt bei 95 °C die Werkswerte wieder her.", + ocGfxLabel: "GFX-Maximum über dem Werkswert", + ocGfxFieldLabel: "Erhöhter maximaler GFX-Takt in MHz", + ocGfxStepperFormat: "Erhöhter maximaler GFX-Takt, Schritte von %d MHz", + ocGfxSliderHelpFormat: "Vom Werksmaximum, %1$d MHz, bis zum Maximum der Karte, %2$d MHz. Der Wert wird gesendet, wenn du ihn loslässt.", + ocGfxTopFormat: "Kartenmaximum (%d MHz)", + ocPowerLabel: "Leistungslimit über dem Startwert", + ocPowerHint: "Gilt sofort nach der Auswahl, bis zur Obergrenze der Karte selbst.", + ocFooter: "Mehr Takt braucht meist mehr Leistung, damit er etwas bringt. Der Kext hält immer nur eines: Ein Leistungslimit und Takt-, Lüfter- oder Spannungseinstellungen werden nie gleichzeitig gehalten. Wird Übertakten ausgeschaltet, geht alles zurück, was es erhöht hat.") + + static let fr = GPUControlOverclockStrings( + voltSection: "Tension GFX", + voltFieldLabel: "Tension GFX en mV", + voltStepperFormat: "Tension GFX, pas de %d mV", + voltToggle: "Baisser la tension GFX", + voltStockFormat: "Usine (%d mV)", + voltSliderHelpFormat: "De %1$d mV à la tension d’usine, %2$d mV. Ne fait que baisser ; la valeur est envoyée quand vous arrêtez de le déplacer.", + voltOutOfRangeFormat: "Choisissez une valeur entre %1$d et %2$d mV, par pas de %3$d mV depuis la valeur d’usine.", + voltRecommendedFormat: "Point de départ recommandé : %d mV. Un point de départ à tester, pas une garantie.", + voltUseRecommended: "Utiliser le point de départ", + voltApply: "Appliquer", + voltFooter: "Baisse toute la courbe de tension du GPU de l’écart avec la valeur d’usine : moins de chaleur et moins de consommation. Trop basse, le GPU peut se figer, réinitialiser son pilote ou afficher un écran noir. Descendez de 25 mV à la fois, testez avec un jeu ou un benchmark et restez 10 à 20 mV au-dessus de la plus basse valeur restée stable. Elle revient à la valeur d’usine quand RyzenStatus quitte, au redémarrage et après la veille. Chaque puce est différente.", + ocSection: "Overclocking", + ocToggle: "Autoriser l’overclocking", + ocWarning: "Dans les limites qu’AMD fixe pour cette carte, rien ne peut griller, mais une valeur peut être instable : le GPU peut se figer ou réinitialiser son pilote. Tout revient aux valeurs d’usine quand vous désactivez ceci, quand RyzenStatus quitte, au redémarrage et après la veille, et le gardien remet les valeurs d’usine à 95 °C.", + ocGfxLabel: "Maximum GFX au-dessus de l’usine", + ocGfxFieldLabel: "Fréquence GFX maximale relevée en MHz", + ocGfxStepperFormat: "Fréquence GFX maximale relevée, pas de %d MHz", + ocGfxSliderHelpFormat: "Du maximum d’usine, %1$d MHz, au maximum de la carte, %2$d MHz. La valeur est envoyée quand vous arrêtez de le déplacer.", + ocGfxTopFormat: "Maximum de la carte (%d MHz)", + ocPowerLabel: "Limite de puissance au-dessus du démarrage", + ocPowerHint: "S’applique dès le choix, jusqu’au plafond de la carte elle-même.", + ocFooter: "Plus de fréquence demande en général plus de puissance pour gagner quelque chose. Le kext ne maintient qu’une chose à la fois : une limite de puissance et des réglages de fréquence, de ventilateur ou de tension ne sont jamais maintenus ensemble. Désactiver l’overclocking remet tout ce qu’il a relevé.") + + static let it = GPUControlOverclockStrings( + voltSection: "Tensione GFX", + voltFieldLabel: "Tensione GFX in mV", + voltStepperFormat: "Tensione GFX, passi di %d mV", + voltToggle: "Abbassa la tensione GFX", + voltStockFormat: "Di fabbrica (%d mV)", + voltSliderHelpFormat: "Da %1$d mV alla tensione di fabbrica, %2$d mV. Solo abbassa; il valore viene inviato quando smetti di muoverlo.", + voltOutOfRangeFormat: "Scegli un valore tra %1$d e %2$d mV, a passi di %3$d mV da quello di fabbrica.", + voltRecommendedFormat: "Punto di partenza consigliato: %d mV. Un punto di partenza da provare, non una garanzia.", + voltUseRecommended: "Usa punto di partenza", + voltApply: "Applica", + voltFooter: "Abbassa tutta la curva di tensione della GPU della differenza dal valore di fabbrica: meno calore e meno consumo. Se è troppo bassa, la GPU può bloccarsi, riavviare il driver o mostrare uno schermo nero. Scendi di 25 mV alla volta, prova con un gioco o un benchmark e resta 10–20 mV sopra il valore più basso rimasto stabile. Torna al valore di fabbrica quando RyzenStatus esce, al riavvio e dopo lo stop. Ogni chip è diverso.", + ocSection: "Overclock", + ocToggle: "Consenti l’overclock", + ocWarning: "Entro i limiti che AMD stessa fissa per questa scheda non può bruciarsi nulla, ma un valore può essere instabile: la GPU può bloccarsi o riavviare il driver. Tutto torna ai valori di fabbrica quando lo disattivi, quando RyzenStatus esce, al riavvio e dopo lo stop, e il supervisore rimette i valori di fabbrica a 95 °C.", + ocGfxLabel: "Massimo GFX sopra quello di fabbrica", + ocGfxFieldLabel: "Clock GFX massimo alzato in MHz", + ocGfxStepperFormat: "Clock GFX massimo alzato, passi di %d MHz", + ocGfxSliderHelpFormat: "Dal massimo di fabbrica, %1$d MHz, al massimo della scheda, %2$d MHz. Il valore viene inviato quando smetti di muoverlo.", + ocGfxTopFormat: "Massimo della scheda (%d MHz)", + ocPowerLabel: "Limite di potenza sopra quello all’avvio", + ocPowerHint: "Si applica appena scelto, fino al tetto della scheda stessa.", + ocFooter: "Più clock di solito richiede più potenza per guadagnare qualcosa. Il kext mantiene una cosa alla volta: un limite di potenza e le impostazioni di clock, ventola o tensione non sono mai mantenuti insieme. Disattivare l’overclock rimette tutto ciò che aveva alzato.") + + static let ja = GPUControlOverclockStrings( + voltSection: "GFX 電圧", + voltFieldLabel: "GFX 電圧(mV)", + voltStepperFormat: "GFX 電圧、%d mV 刻み", + voltToggle: "GFX 電圧を下げる", + voltStockFormat: "純正 (%d mV)", + voltSliderHelpFormat: "%1$d mV から純正電圧 %2$d mV まで。下げるだけです。動かすのをやめると値が送られます。", + voltOutOfRangeFormat: "%1$d〜%2$d mV の範囲で、純正から %3$d mV 刻みの値を選んでください。", + voltRecommendedFormat: "推奨の出発点: %d mV。試すための出発点であり、保証ではありません。", + voltUseRecommended: "出発点を使う", + voltApply: "適用", + voltFooter: "GPU の電圧カーブ全体を純正との差だけ下げます。発熱と消費電力が減ります。下げすぎると GPU がフリーズしたり、ドライバがリセットされたり、画面が真っ暗になったりします。25 mV ずつ下げてゲームやベンチマークで試し、安定した最低値より 10〜20 mV 上にとどめてください。RyzenStatus の終了時、再起動時、スリープ後に純正に戻ります。チップの個体差があります。", + ocSection: "オーバークロック", + ocToggle: "オーバークロックを許可", + ocWarning: "AMD がこのカードに定めた範囲内なら壊れることはありませんが、値によっては不安定になり、GPU がフリーズしたりドライバがリセットされたりします。これをオフにしたとき、RyzenStatus の終了時、再起動時、スリープ後にはすべて純正に戻り、95 °C で監視が純正に戻します。", + ocGfxLabel: "純正を超える GFX 最大クロック", + ocGfxFieldLabel: "引き上げた GFX 最大クロック(MHz)", + ocGfxStepperFormat: "引き上げた GFX 最大クロック、%d MHz 刻み", + ocGfxSliderHelpFormat: "純正の最大 %1$d MHz からカードの最大 %2$d MHz まで。動かすのをやめると値が送られます。", + ocGfxTopFormat: "カードの最大 (%d MHz)", + ocPowerLabel: "起動時を超える電力制限", + ocPowerHint: "選ぶとすぐに適用されます。カード自身の上限まで。", + ocFooter: "クロックを上げて効果を得るには、通常より多くの電力が必要です。kext は一度に1つだけ保持します。電力制限とクロック、ファン、電圧の設定を同時に保持することはありません。オーバークロックをオフにすると、引き上げたものはすべて戻ります。") + + static let ko = GPUControlOverclockStrings( + voltSection: "GFX 전압", + voltFieldLabel: "GFX 전압(mV)", + voltStepperFormat: "GFX 전압, %d mV 단위", + voltToggle: "GFX 전압 낮추기", + voltStockFormat: "기본값 (%d mV)", + voltSliderHelpFormat: "%1$d mV부터 기본 전압 %2$d mV까지. 낮추기만 합니다. 움직임을 멈추면 값이 전송됩니다.", + voltOutOfRangeFormat: "%1$d~%2$d mV 사이에서 기본값부터 %3$d mV 단위의 값을 고르세요.", + voltRecommendedFormat: "권장 시작점: %d mV. 시험해 볼 시작점이며 보장은 아닙니다.", + voltUseRecommended: "시작점 사용", + voltApply: "적용", + voltFooter: "GPU 전압 곡선 전체를 기본값과의 차이만큼 낮춥니다. 발열과 전력이 줄어듭니다. 너무 낮으면 GPU가 멈추거나, 드라이버가 재설정되거나, 화면이 검게 될 수 있습니다. 25 mV씩 낮추며 게임이나 벤치마크로 시험하고, 안정적이었던 가장 낮은 값보다 10~20 mV 위에 두세요. RyzenStatus를 종료할 때, 재시동할 때, 잠자기 후에는 기본값으로 돌아갑니다. 칩마다 차이가 있습니다.", + ocSection: "오버클럭", + ocToggle: "오버클럭 허용", + ocWarning: "AMD가 이 카드에 정한 한도 안에서는 아무것도 타지 않지만, 값이 불안정할 수 있어 GPU가 멈추거나 드라이버가 재설정될 수 있습니다. 이 옵션을 끌 때, RyzenStatus를 종료할 때, 재시동할 때, 잠자기 후에는 모두 기본값으로 돌아가며, 95 °C에서는 감시가 기본값으로 되돌립니다.", + ocGfxLabel: "기본값을 넘는 최대 GFX", + ocGfxFieldLabel: "높인 최대 GFX 클록(MHz)", + ocGfxStepperFormat: "높인 최대 GFX 클록, %d MHz 단위", + ocGfxSliderHelpFormat: "기본 최대 %1$d MHz부터 카드 최대 %2$d MHz까지. 움직임을 멈추면 값이 전송됩니다.", + ocGfxTopFormat: "카드 최대 (%d MHz)", + ocPowerLabel: "시동 값을 넘는 전력 한도", + ocPowerHint: "고르면 바로 적용되며, 카드 자체 상한까지입니다.", + ocFooter: "클록을 높여 이득을 보려면 보통 더 많은 전력이 필요합니다. kext는 한 번에 하나만 유지합니다. 전력 한도와 클록, 팬 또는 전압 설정은 함께 유지되지 않습니다. 오버클럭을 끄면 높인 것은 모두 되돌아갑니다.") + + static let zhHans = GPUControlOverclockStrings( + voltSection: "GFX 电压", + voltFieldLabel: "GFX 电压(mV)", + voltStepperFormat: "GFX 电压,步长 %d mV", + voltToggle: "降低 GFX 电压", + voltStockFormat: "出厂值(%d mV)", + voltSliderHelpFormat: "从 %1$d mV 到出厂电压 %2$d mV。只会降低;停止拖动时发送数值。", + voltOutOfRangeFormat: "请在 %1$d 到 %2$d mV 之间选择,从出厂值起以 %3$d mV 为步长。", + voltRecommendedFormat: "推荐起点:%d mV。这是用来测试的起点,并非保证。", + voltUseRecommended: "使用起点", + voltApply: "应用", + voltFooter: "将整条 GPU 电压曲线按与出厂值的差值降低:发热和功耗都会减少。过低时 GPU 可能卡死、重置驱动或黑屏。每次降低 25 mV,用游戏或基准测试检验,并保持比最低稳定值高 10–20 mV。退出 RyzenStatus、重新启动和睡眠后会恢复出厂值。每颗芯片都不一样。", + ocSection: "超频", + ocToggle: "允许超频", + ocWarning: "在 AMD 为这张显卡设定的范围内不会烧坏任何东西,但某个数值可能不稳定:GPU 可能卡死或重置驱动。关闭此项时、退出 RyzenStatus、重新启动和睡眠后一切都会恢复出厂值,监控会在 95 °C 时恢复出厂值。", + ocGfxLabel: "高于出厂值的 GFX 最大值", + ocGfxFieldLabel: "提高后的 GFX 最大时钟频率(MHz)", + ocGfxStepperFormat: "提高后的 GFX 最大时钟频率,步长 %d MHz", + ocGfxSliderHelpFormat: "从出厂最大值 %1$d MHz 到显卡最大值 %2$d MHz。停止拖动时发送数值。", + ocGfxTopFormat: "显卡最大值(%d MHz)", + ocPowerLabel: "高于启动值的功率上限", + ocPowerHint: "选择后立即应用,最高到显卡自身的上限。", + ocFooter: "提高时钟频率通常需要更多功率才能有所收获。kext 一次只维持一项:功率上限与时钟频率、风扇或电压设置绝不会同时维持。关闭超频会恢复它提高的所有设置。") + + static let zhTW = GPUControlOverclockStrings( + voltSection: "GFX 電壓", + voltFieldLabel: "GFX 電壓(mV)", + voltStepperFormat: "GFX 電壓,間隔 %d mV", + voltToggle: "降低 GFX 電壓", + voltStockFormat: "原廠值(%d mV)", + voltSliderHelpFormat: "從 %1$d mV 到原廠電壓 %2$d mV。只會降低;停止拖動時送出數值。", + voltOutOfRangeFormat: "請在 %1$d 到 %2$d mV 之間選擇,從原廠值起以 %3$d mV 為間隔。", + voltRecommendedFormat: "建議起點:%d mV。這是用來測試的起點,並非保證。", + voltUseRecommended: "使用起點", + voltApply: "套用", + voltFooter: "將整條 GPU 電壓曲線依與原廠值的差值降低:發熱與耗電都會減少。太低時 GPU 可能當機、重設驅動程式或黑畫面。每次降低 25 mV,用遊戲或基準測試檢驗,並保持比最低穩定值高 10–20 mV。結束 RyzenStatus、重新開機與睡眠後會恢復原廠值。每顆晶片都不一樣。", + ocSection: "超頻", + ocToggle: "允許超頻", + ocWarning: "在 AMD 為這張顯示卡設定的範圍內不會燒壞任何東西,但某個數值可能不穩定:GPU 可能當機或重設驅動程式。關閉此項時、結束 RyzenStatus、重新開機與睡眠後一切都會恢復原廠值,監控會在 95 °C 時恢復原廠值。", + ocGfxLabel: "高於原廠值的 GFX 最大值", + ocGfxFieldLabel: "提高後的 GFX 最大時脈(MHz)", + ocGfxStepperFormat: "提高後的 GFX 最大時脈,間隔 %d MHz", + ocGfxSliderHelpFormat: "從原廠最大值 %1$d MHz 到顯示卡最大值 %2$d MHz。停止拖動時送出數值。", + ocGfxTopFormat: "顯示卡最大值(%d MHz)", + ocPowerLabel: "高於啟動值的功率上限", + ocPowerHint: "選擇後立即套用,最高到顯示卡本身的上限。", + ocFooter: "提高時脈通常需要更多功率才會有效果。kext 一次只維持一項:功率上限與時脈、風扇或電壓設定絕不會同時維持。關閉超頻會恢復它提高的所有設定。") + + static let uk = GPUControlOverclockStrings( + voltSection: "Напруга GFX", + voltFieldLabel: "Напруга GFX у мВ", + voltStepperFormat: "Напруга GFX, крок %d мВ", + voltToggle: "Знизити напругу GFX", + voltStockFormat: "Заводська (%d мВ)", + voltSliderHelpFormat: "Від %1$d мВ до заводської напруги %2$d мВ. Лише знижує; значення надсилається, коли ви відпускаєте повзунок.", + voltOutOfRangeFormat: "Виберіть значення від %1$d до %2$d мВ із кроком %3$d мВ від заводського.", + voltRecommendedFormat: "Рекомендована відправна точка: %d мВ. Це точка для перевірки, а не гарантія.", + voltUseRecommended: "Узяти відправну точку", + voltApply: "Застосувати", + voltFooter: "Знижує всю криву напруги GPU на різницю із заводською: менше нагріву й споживання. Якщо надто низько, GPU може зависнути, перезапустити драйвер або показати чорний екран. Знижуйте по 25 мВ, перевіряйте грою чи бенчмарком і тримайтеся на 10–20 мВ вище найнижчого стабільного значення. Повертається до заводської після виходу з RyzenStatus, перезавантаження та сну. Кожен чип інший.", + ocSection: "Розгін", + ocToggle: "Дозволити розгін", + ocWarning: "У межах, які AMD задає для цієї карти, нічого не згорить, але значення може бути нестабільним: GPU може зависнути або перезапустити драйвер. Усе повертається до заводського, коли ви вимикаєте це, після виходу з RyzenStatus, перезавантаження та сну, а сторож повертає заводські значення при 95 °C.", + ocGfxLabel: "Макс. частота GFX вище заводської", + ocGfxFieldLabel: "Підвищена макс. частота GFX у МГц", + ocGfxStepperFormat: "Підвищена макс. частота GFX, крок %d МГц", + ocGfxSliderHelpFormat: "Від заводського максимуму %1$d МГц до максимуму карти %2$d МГц. Значення надсилається, коли ви відпускаєте повзунок.", + ocGfxTopFormat: "Максимум карти (%d МГц)", + ocPowerLabel: "Ліміт потужності вище значення завантаження", + ocPowerHint: "Застосовується під час вибору, до стелі самої карти.", + ocFooter: "Щоб щось виграти, більшій частоті зазвичай потрібна більша потужність. Kext утримує лише одне за раз: ліміт потужності й налаштування частоти, вентилятора чи напруги ніколи не утримуються разом. Вимкнення розгону повертає все, що він підняв.") +} diff --git a/Sources/RyzenStatus/Core/GPUControlPageStrings.swift b/Sources/RyzenStatus/Core/GPUControlPageStrings.swift index 68345ea1..5d81ef1a 100644 --- a/Sources/RyzenStatus/Core/GPUControlPageStrings.swift +++ b/Sources/RyzenStatus/Core/GPUControlPageStrings.swift @@ -105,6 +105,9 @@ struct GPUControlPageStrings { let offChangeUnconfirmed: String let offDriverStopped: String let offWatchdog: String + /// Off: the watchdog put the start-up power limit back over a raised one + /// (GPUSensors 0.9.0). + let offPowerWatchdog: String /// %@ = the group's sentence. let gaveUpFormat: String let timedOut: String @@ -131,6 +134,8 @@ struct GPUControlPageStrings { let gfxItemFormat: String /// A raised GFX minimum in the held sentence (GPUSensors 0.9.0); %d = MHz. let gfxMinItemFormat: String + /// A lowered GFX voltage in the held sentence (GPUSensors 0.9.0); %d = mV. + let voltItemFormat: String /// Between the held settings, and before the last one: "a, b and c". let listSeparator: String let listLastSeparator: String @@ -168,6 +173,7 @@ struct GPUControlPageStrings { if want.zeroRpmOff { items.append(zeroRpmItem) } if let mhz = want.gfxMaxMHz { items.append(String(format: gfxItemFormat, mhz)) } if let mhz = want.gfxMinMHz { items.append(String(format: gfxMinItemFormat, mhz)) } + if let mv = want.voltMV { items.append(String(format: voltItemFormat, mv)) } // An empty hold would leave "RyzenStatus is holding " with nothing // after it: say the short form instead. guard !items.isEmpty else { return heldOD8Short } @@ -195,6 +201,7 @@ struct GPUControlPageStrings { case .offChangeUnconfirmed: return offChangeUnconfirmed case .offDriverStopped: return offDriverStopped case .offWatchdog: return offWatchdog + case .offPowerWatchdog: return offPowerWatchdog case .stillApplied: return closeRefused case .noFloor: return floorUnknown case .readOnlyCard: return readOnlyDetail @@ -210,8 +217,8 @@ struct GPUControlPageStrings { copy, copied, notInstalled, unsafeToolFormat, armFailed, rememberToggle, rememberFooter, changes, reverts, kextVersion, channel, panelLabel, notAllowed, busy, notReady, off, closedGroup, needsAdministrator, otherVersion, unconfirmed, notOwner, settingMissing, offNotAsExpected, offChangeUnconfirmed, - offDriverStopped, offWatchdog, gaveUpFormat, timedOut, notConfirmed, backToStartUp, alreadyAtStartUp, - unsafeNotPlain, unsafeNotRoot, unsafeWritable, unsafeACL, unsafeUnreadable, unsafeSignature, unsafeOtherProgram, heldOD8Format, fanCurveItem, zeroRpmItem, gfxItemFormat, gfxMinItemFormat, + offDriverStopped, offWatchdog, offPowerWatchdog, gaveUpFormat, timedOut, notConfirmed, backToStartUp, alreadyAtStartUp, + unsafeNotPlain, unsafeNotRoot, unsafeWritable, unsafeACL, unsafeUnreadable, unsafeSignature, unsafeOtherProgram, heldOD8Format, fanCurveItem, zeroRpmItem, gfxItemFormat, gfxMinItemFormat, voltItemFormat, listSeparator, listLastSeparator, unsafeSetID, heldOD8Short, closeChanges, closeChangesHelp, closedAgain, closeRefused, closeNotSupported, closedByOther, readOnlyTitle, readOnlyDetail, cardRangeFormat, floorUnknown, nothingToLower, otherProgramChanged, powerHint, openWritingHint, kextSaysFormat, noReading] @@ -311,6 +318,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "Off: a change could not be confirmed. Restart the Mac.", offDriverStopped: "The GPU driver stopped or the Mac is shutting down.", offWatchdog: "Off: the fan watchdog put the stock fan back.", + offPowerWatchdog: "Off: the watchdog put the start-up power limit back.", gaveUpFormat: "Not taken after a minute. %@", timedOut: "No answer in 5 s; nothing is held.", notConfirmed: "The kext did not confirm the change; nothing is held.", @@ -329,6 +337,7 @@ extension GPUControlPageStrings { zeroRpmItem: "the fan always running", gfxItemFormat: "a GFX maximum of %d MHz", gfxMinItemFormat: "a GFX minimum of %d MHz", + voltItemFormat: "a GFX voltage of %d mV", listSeparator: ", ", listLastSeparator: " and ", heldOD8Short: "RyzenStatus is holding OD8 settings", @@ -408,6 +417,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "Apagada: un cambio no se pudo confirmar. Reinicia el Mac.", offDriverStopped: "El controlador de la GPU se detuvo o el Mac se está apagando.", offWatchdog: "Apagada: el vigilante del ventilador volvió al ventilador de fábrica.", + offPowerWatchdog: "Apagada: el vigilante volvió al límite de potencia de arranque.", gaveUpFormat: "No se aceptó en un minuto. %@", timedOut: "Sin respuesta en 5 s; no se mantiene nada.", notConfirmed: "El kext no confirmó el cambio; no se mantiene nada.", @@ -426,6 +436,7 @@ extension GPUControlPageStrings { zeroRpmItem: "el ventilador siempre girando", gfxItemFormat: "un reloj máximo de GFX de %d MHz", gfxMinItemFormat: "un reloj mínimo de GFX de %d MHz", + voltItemFormat: "un voltaje de GFX de %d mV", listSeparator: ", ", listLastSeparator: " y ", heldOD8Short: "RyzenStatus mantiene ajustes OD8", @@ -505,6 +516,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "Desativada: uma alteração não pôde ser confirmada. Reinicie o Mac.", offDriverStopped: "O driver da GPU parou ou o Mac está desligando.", offWatchdog: "Desativada: o vigilante da ventoinha restaurou a ventoinha de fábrica.", + offPowerWatchdog: "Desativada: o vigilante restaurou o limite de energia de inicialização.", gaveUpFormat: "Não aceito em um minuto. %@", timedOut: "Sem resposta em 5 s; nada é mantido.", notConfirmed: "O kext não confirmou a alteração; nada é mantido.", @@ -523,6 +535,7 @@ extension GPUControlPageStrings { zeroRpmItem: "a ventoinha sempre girando", gfxItemFormat: "um clock GFX máximo de %d MHz", gfxMinItemFormat: "um clock GFX mínimo de %d MHz", + voltItemFormat: "uma tensão da GFX de %d mV", listSeparator: ", ", listLastSeparator: " e ", heldOD8Short: "O RyzenStatus está mantendo ajustes OD8", @@ -602,6 +615,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "Kapalı: bir değişiklik doğrulanamadı. Mac'i yeniden başlatın.", offDriverStopped: "GPU sürücüsü durdu veya Mac kapanıyor.", offWatchdog: "Kapalı: fan bekçisi fabrika fanını geri getirdi.", + offPowerWatchdog: "Kapalı: bekçi başlangıç güç sınırını geri getirdi.", gaveUpFormat: "Bir dakikada kabul edilmedi. %@", timedOut: "5 sn içinde yanıt yok; hiçbir şey tutulmuyor.", notConfirmed: "Kext değişikliği doğrulamadı; hiçbir şey tutulmuyor.", @@ -620,6 +634,7 @@ extension GPUControlPageStrings { zeroRpmItem: "her zaman dönen fan", gfxItemFormat: "maks. GFX saat hızı %d MHz", gfxMinItemFormat: "min. GFX saat hızı %d MHz", + voltItemFormat: "GFX gerilimi %d mV", listSeparator: ", ", listLastSeparator: " ve ", heldOD8Short: "RyzenStatus OD8 ayarlarını tutuyor", @@ -699,6 +714,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "Выключено: изменение не удалось подтвердить. Перезапустите Mac.", offDriverStopped: "Драйвер GPU остановился или Mac выключается.", offWatchdog: "Выключено: сторож вентилятора вернул заводской вентилятор.", + offPowerWatchdog: "Выключено: сторож вернул лимит мощности при загрузке.", gaveUpFormat: "Не принято за минуту. %@", timedOut: "Нет ответа в течение 5 с; ничего не удерживается.", notConfirmed: "Kext не подтвердил изменение; ничего не удерживается.", @@ -717,6 +733,7 @@ extension GPUControlPageStrings { zeroRpmItem: "постоянное вращение вентилятора", gfxItemFormat: "макс. частоту GFX %d МГц", gfxMinItemFormat: "мин. частоту GFX %d МГц", + voltItemFormat: "напряжение GFX %d мВ", listSeparator: ", ", listLastSeparator: " и ", heldOD8Short: "RyzenStatus удерживает настройки OD8", @@ -796,6 +813,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "Vypnuté: zmenu sa nepodarilo potvrdiť. Reštartujte Mac.", offDriverStopped: "Ovládač GPU sa zastavil alebo sa Mac vypína.", offWatchdog: "Vypnuté: strážca ventilátora vrátil továrenský ventilátor.", + offPowerWatchdog: "Vypnuté: strážca vrátil štartovací limit príkonu.", gaveUpFormat: "Neprijaté do minúty. %@", timedOut: "Žiadna odpoveď do 5 s; nič sa nedrží.", notConfirmed: "Kext zmenu nepotvrdil; nič sa nedrží.", @@ -814,6 +832,7 @@ extension GPUControlPageStrings { zeroRpmItem: "ventilátor stále v chode", gfxItemFormat: "maximálny takt GFX %d MHz", gfxMinItemFormat: "minimálny takt GFX %d MHz", + voltItemFormat: "napätie GFX %d mV", listSeparator: ", ", listLastSeparator: " a ", heldOD8Short: "RyzenStatus drží nastavenia OD8", @@ -893,6 +912,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "Aus: Eine Änderung konnte nicht bestätigt werden. Starten Sie den Mac neu.", offDriverStopped: "Der GPU-Treiber ist gestoppt oder der Mac fährt herunter.", offWatchdog: "Aus: Der Lüfterwächter hat den Werkslüfter zurückgebracht.", + offPowerWatchdog: "Aus: Der Wächter hat das Leistungslimit auf den Startwert zurückgesetzt.", gaveUpFormat: "In einer Minute nicht angenommen. %@", timedOut: "Keine Antwort in 5 s; nichts wird gehalten.", notConfirmed: "Der Kext hat die Änderung nicht bestätigt; nichts wird gehalten.", @@ -911,6 +931,7 @@ extension GPUControlPageStrings { zeroRpmItem: "den Lüfter im Dauerbetrieb", gfxItemFormat: "einen maximalen GFX-Takt von %d MHz", gfxMinItemFormat: "einen minimalen GFX-Takt von %d MHz", + voltItemFormat: "eine GFX-Spannung von %d mV", listSeparator: ", ", listLastSeparator: " und ", heldOD8Short: "RyzenStatus hält OD8-Einstellungen", @@ -990,6 +1011,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "Désactivée : un changement n’a pas pu être confirmé. Redémarrez le Mac.", offDriverStopped: "Le pilote GPU s’est arrêté ou le Mac s’éteint.", offWatchdog: "Désactivée : le gardien du ventilateur a remis le ventilateur d’usine.", + offPowerWatchdog: "Désactivée : le gardien a remis la limite de puissance de démarrage.", gaveUpFormat: "Non accepté en une minute. %@", timedOut: "Pas de réponse en 5 s ; rien n’est maintenu.", notConfirmed: "Le kext n’a pas confirmé le changement ; rien n’est maintenu.", @@ -1008,6 +1030,7 @@ extension GPUControlPageStrings { zeroRpmItem: "le ventilateur toujours en marche", gfxItemFormat: "une fréquence GFX max de %d MHz", gfxMinItemFormat: "une fréquence GFX min de %d MHz", + voltItemFormat: "une tension GFX de %d mV", listSeparator: ", ", listLastSeparator: " et ", heldOD8Short: "RyzenStatus maintient des réglages OD8", @@ -1087,6 +1110,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "Disattivata: una modifica non è stata confermata. Riavvia il Mac.", offDriverStopped: "Il driver GPU si è fermato o il Mac si sta spegnendo.", offWatchdog: "Disattivata: il supervisore della ventola ha rimesso la ventola di fabbrica.", + offPowerWatchdog: "Disattivata: il supervisore ha rimesso il limite di potenza all’avvio.", gaveUpFormat: "Non accettato in un minuto. %@", timedOut: "Nessuna risposta in 5 s; non viene mantenuto nulla.", notConfirmed: "Il kext non ha confermato la modifica; non viene mantenuto nulla.", @@ -1105,6 +1129,7 @@ extension GPUControlPageStrings { zeroRpmItem: "la ventola sempre in rotazione", gfxItemFormat: "un clock GFX massimo di %d MHz", gfxMinItemFormat: "un clock GFX minimo di %d MHz", + voltItemFormat: "una tensione GFX di %d mV", listSeparator: ", ", listLastSeparator: " e ", heldOD8Short: "RyzenStatus mantiene impostazioni OD8", @@ -1184,6 +1209,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "オフ: 変更を確認できませんでした。Mac を再起動してください。", offDriverStopped: "GPU ドライバーが停止したか、Mac がシステム終了中です。", offWatchdog: "オフ: ファン監視が純正ファンに戻しました。", + offPowerWatchdog: "オフ: 監視が電力制限を起動時の値に戻しました。", gaveUpFormat: "1分以内に受け付けられませんでした。%@", timedOut: "5 秒以内に応答がありません。何も保持していません。", notConfirmed: "kext は変更を確認しませんでした。何も保持していません。", @@ -1202,6 +1228,7 @@ extension GPUControlPageStrings { zeroRpmItem: "常に回るファン", gfxItemFormat: "GFX 最大クロック %d MHz", gfxMinItemFormat: "GFX 最小クロック %d MHz", + voltItemFormat: "GFX 電圧 %d mV", listSeparator: "、", listLastSeparator: "と", heldOD8Short: "RyzenStatus が OD8 設定を保持中", @@ -1281,6 +1308,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "꺼짐: 변경 사항을 확인할 수 없습니다. Mac을 재시동하십시오.", offDriverStopped: "GPU 드라이버가 멈췄거나 Mac이 종료 중입니다.", offWatchdog: "꺼짐: 팬 감시가 기본 팬으로 되돌렸습니다.", + offPowerWatchdog: "꺼짐: 감시가 전력 한도를 시동 값으로 되돌렸습니다.", gaveUpFormat: "1분 안에 받아들여지지 않았습니다. %@", timedOut: "5초 안에 응답이 없습니다. 아무것도 유지하지 않습니다.", notConfirmed: "kext가 변경을 확인하지 않았습니다. 아무것도 유지하지 않습니다.", @@ -1299,6 +1327,7 @@ extension GPUControlPageStrings { zeroRpmItem: "항상 도는 팬", gfxItemFormat: "최대 GFX 클록 %d MHz", gfxMinItemFormat: "최소 GFX 클록 %d MHz", + voltItemFormat: "GFX 전압 %d mV", listSeparator: ", ", listLastSeparator: " 및 ", heldOD8Short: "RyzenStatus가 OD8 설정을 유지 중", @@ -1378,6 +1407,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "关闭:无法确认更改。请重新启动 Mac。", offDriverStopped: "GPU 驱动程序已停止,或 Mac 正在关机。", offWatchdog: "关闭:风扇监控已恢复出厂风扇。", + offPowerWatchdog: "关闭:监控已将功率上限恢复为启动值。", gaveUpFormat: "一分钟内未被接受。%@", timedOut: "5 秒内无响应;未持有任何项目。", notConfirmed: "kext 未确认更改;未持有任何项目。", @@ -1396,6 +1426,7 @@ extension GPUControlPageStrings { zeroRpmItem: "始终转动的风扇", gfxItemFormat: "GFX 最大时钟频率 %d MHz", gfxMinItemFormat: "GFX 最小时钟频率 %d MHz", + voltItemFormat: "GFX 电压 %d mV", listSeparator: "、", listLastSeparator: "和", heldOD8Short: "RyzenStatus 正在维持 OD8 设置", @@ -1475,6 +1506,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "關閉:無法確認變更。請重新啟動 Mac。", offDriverStopped: "GPU 驅動程式已停止,或 Mac 正在關機。", offWatchdog: "關閉:風扇監控已恢復原廠風扇。", + offPowerWatchdog: "關閉:監控已將功率上限恢復為啟動值。", gaveUpFormat: "一分鐘內未被接受。%@", timedOut: "5 秒內沒有回應;未持有任何項目。", notConfirmed: "kext 未確認變更;未持有任何項目。", @@ -1493,6 +1525,7 @@ extension GPUControlPageStrings { zeroRpmItem: "始終轉動的風扇", gfxItemFormat: "GFX 最大時脈 %d MHz", gfxMinItemFormat: "GFX 最小時脈 %d MHz", + voltItemFormat: "GFX 電壓 %d mV", listSeparator: "、", listLastSeparator: "和", heldOD8Short: "RyzenStatus 正在維持 OD8 設定", @@ -1572,6 +1605,7 @@ extension GPUControlPageStrings { offChangeUnconfirmed: "Вимкнено: зміну не вдалося підтвердити. Перезапустіть Mac.", offDriverStopped: "Драйвер GPU зупинився або Mac вимикається.", offWatchdog: "Вимкнено: сторож вентилятора повернув заводський вентилятор.", + offPowerWatchdog: "Вимкнено: сторож повернув ліміт потужності під час завантаження.", gaveUpFormat: "Не прийнято за хвилину. %@", timedOut: "Немає відповіді за 5 с; нічого не утримується.", notConfirmed: "Kext не підтвердив зміну; нічого не утримується.", @@ -1590,6 +1624,7 @@ extension GPUControlPageStrings { zeroRpmItem: "постійне обертання вентилятора", gfxItemFormat: "макс. частоту GFX %d МГц", gfxMinItemFormat: "мін. частоту GFX %d МГц", + voltItemFormat: "напругу GFX %d мВ", listSeparator: ", ", listLastSeparator: " і ", heldOD8Short: "RyzenStatus утримує налаштування OD8", diff --git a/Sources/RyzenStatus/Services/Metrics/FakeGPUControlKext.swift b/Sources/RyzenStatus/Services/Metrics/FakeGPUControlKext.swift index eceb2f28..0e67657b 100644 --- a/Sources/RyzenStatus/Services/Metrics/FakeGPUControlKext.swift +++ b/Sources/RyzenStatus/Services/Metrics/FakeGPUControlKext.swift @@ -82,6 +82,20 @@ final class FakeGPUControlKext: @unchecked Sendable { /// minimum's range is `gfxMinMHz...gfxMinTopMHz` (500-2800 on the card). var takesGfxMin = false var gfxMinTopMHz = 2_800 + /// GPUSensors 0.9.0, the rest of it: `setOD8` also takes 15 scalars with + /// a GFX voltage and the overclock flag (4), `set` its 3-scalar raise + /// form, `status` the `volt` and `raise` flags, `OD8WriteState` has + /// `Takes` 119 and `VoltHeld`, `PowerRange` has `CeilW`. Implies + /// `takesGfxMin`. The test card's numbers: voltage 881 to 1075 mV (stock + /// 1075), GFX maximum up to 2800 MHz, power up to the start-up limit + /// plus its +9 % (261 W at 240 W). + var takesOverclock = false { + didSet { if takesOverclock { takesGfxMin = true } } + } + var voltMinMV = 881 + var voltStockMV = 1_075 + /// The card's own top for the GFX maximum (`GfxMaxMHz.Max`). + var gfxMaxTopMHz = 2_800 /// The stock fan target; the last curve point must be at 100 % at or /// below this minus 22 C. var fanTargetC = 70 @@ -152,6 +166,8 @@ final class FakeGPUControlKext: @unchecked Sendable { private var offBackAt: UInt64? private var offBackLeft = 0 private var od8OffAfterWayBack = false + /// 0.9.0: the watchdog took a raised limit back; off once it is back. + private var powerOffAfterWayBack = false private var tornDown = false // Sleep and wake, as the worker sees them. private var inSleep = false @@ -235,12 +251,19 @@ final class FakeGPUControlKext: @unchecked Sendable { /// The fan watchdog trips (95 C, or 75 C with the fan under 90 % for 5 s, /// or 10 s without readings): stock fan once, writing off until restart. - /// Since 0.9.0 it also watches a raised GFX minimum (95 C or no - /// readings). + /// Since 0.9.0 it also watches a raised GFX minimum and a GFX maximum + /// above stock (95 C or no readings), and a power limit above the + /// start-up one: the start-up limit goes back through the ordinary way + /// back, and writing goes off once it is confirmed (`PowerWatchdog`). func tripFanWatchdog() { locked { + if !od8Dirty, heldW > bootW, !tornDown, !owner.isOff, !powerOffAfterWayBack { + powerOffAfterWayBack = true + startRevert(owner.release(owner.owner)) + return + } let watched = GPUControlOD8Held.curve.rawValue | GPUControlOD8Held.unknown.rawValue - | GPUControlOD8Held.gfxMin.rawValue + | GPUControlOD8Held.gfxMin.rawValue | GPUControlOD8Held.gfxMaxUp.rawValue guard od8Held & watched != 0, od8Dirty, !tornDown, !owner.isOff else { return } if inSleep { // After the wake Owner goes back, and writing goes off then. @@ -289,9 +312,11 @@ final class FakeGPUControlKext: @unchecked Sendable { if od8Dirty, let gfx = od8HeldWant.gfxMaxMHz { od8State["GfxMaxHeld"] = NSNumber(value: gfx) } if takesGfxMin { if od8Dirty, let low = od8HeldWant.gfxMinMHz { od8State["GfxMinHeld"] = NSNumber(value: low) } - let takes: GPUControlOD8Held = [.curve, .zeroRpmOff, .gfxMax, .gfxMin] + var takes: GPUControlOD8Held = [.curve, .zeroRpmOff, .gfxMax, .gfxMin] + if takesOverclock { takes.formUnion([.volt, .gfxMaxUp]) } od8State["Takes"] = NSNumber(value: takes.rawValue) } + if takesOverclock, od8Dirty, let mv = od8HeldWant.voltMV { od8State["VoltHeld"] = NSNumber(value: mv) } var all: [String: Any] = [ "Write": writeText(), "WriteState": [ @@ -312,6 +337,7 @@ final class FakeGPUControlKext: @unchecked Sendable { if floor != 0 { range["FloorW"] = NSNumber(value: floor) range["MaxW"] = NSNumber(value: bootW) + if takesOverclock { range["CeilW"] = NSNumber(value: Swift.max(ceilLocked, bootW)) } } if od8Ready, Self.bootPlausible(bootW) { // Signed 32-bit, as the kext publishes them. @@ -371,8 +397,18 @@ final class FakeGPUControlKext: @unchecked Sendable { out[0] = GPUControlReply.badVersion.rawValue return out } - let countTaken = selector == .setOD8 && takesGfxMin ? selector.takes(inputCount: input.count) - : input.count == selector.inputCount + // 0.9.0 takes the longer forms; an older kext only its own counts + // (the 14-scalar setOD8 since the GFX minimum). + let countTaken: Bool + switch selector { + case .setOD8 where takesOverclock, .set where takesOverclock: + countTaken = selector.takes(inputCount: input.count) + case .setOD8 where takesGfxMin: + countTaken = input.count == GPUControlWire.setOD8InputCount + || input.count == GPUControlWire.setOD8InputCountGfxMin + default: + countTaken = input.count == selector.inputCount + } guard countTaken, outputCount >= selector.outputCount else { return nil } if var forced = forcedReplies[selector], !forced.isEmpty { let reply = forced.removeFirst() @@ -395,8 +431,11 @@ final class FakeGPUControlKext: @unchecked Sendable { case .set: // 0.8.0: off and not armed come before any value (`valueGate`). if generation == .v08, let gate = valueGate() { return [record(gate).rawValue] } + // 0.9.0's raise form: a flag the kext does not know is malformed. + let flags = input.count > 2 ? input[2] : 0 + if flags & ~GPUControlWire.setWantRaise != 0 { return [record(.badArgs).rawValue] } let reply: GPUControlReply = input[1] > 0xFFFF_FFFF - ? .aboveBoot : set(client: client, watts: UInt32(input[1])) + ? .aboveBoot : set(client: client, watts: UInt32(input[1]), raise: flags != 0) return [reply.rawValue] case .alive: return [(owner.alive(client, nowMs) ? GPUControlReply.ok : .notOwner).rawValue] @@ -405,7 +444,8 @@ final class FakeGPUControlKext: @unchecked Sendable { return [GPUControlReply.ok.rawValue] case .setOD8: if generation == .v08, let gate = valueGate() { return [record(gate).rawValue, 0] } - guard let want = Self.want(from: input, maxGfxMHz: generation == .v08 ? 0x7FFF_FFFF : 5_000) else { + guard let want = Self.want(from: input, maxGfxMHz: generation == .v08 ? 0x7FFF_FFFF : 5_000, + overclock: takesOverclock) else { return [GPUControlReply.badArgs.rawValue, 0] } let (reply, check) = setOD8(client: client, want: want) @@ -415,13 +455,15 @@ final class FakeGPUControlKext: @unchecked Sendable { } /// The dispatcher's reading of `setOD8`'s 13 scalars (or 14 with a GFX - /// minimum, 0.9.0); nil is malformed. The clock's wire bound: 5000 MHz in - /// 0.7.2, the 32-bit field in 0.8.0. - private static func want(from input: [UInt64], maxGfxMHz: UInt64) -> GPUControlOD8Want? { + /// minimum, 15 with a GFX voltage, 0.9.0); nil is malformed. The clock's + /// wire bound: 5000 MHz in 0.7.2, the 32-bit field in 0.8.0. `overclock`: + /// the kext knows flag 4 (0.9.0). + private static func want(from input: [UInt64], maxGfxMHz: UInt64, overclock: Bool = false) -> GPUControlOD8Want? { let flags = input[1] let low = input.count > 13 ? input[13] : 0 - guard flags & ~(GPUControlWire.wantCurve | GPUControlWire.wantZeroRpmOff) == 0, input[12] <= maxGfxMHz, - low <= 0x7FFF_FFFF else { + let mv = input.count > 14 ? input[14] : 0 + let known = GPUControlWire.wantCurve | GPUControlWire.wantZeroRpmOff | (overclock ? GPUControlWire.wantOverclock : 0) + guard flags & ~known == 0, input[12] <= maxGfxMHz, low <= 0x7FFF_FFFF, mv <= 0x7FFF_FFFF else { return nil } let curve = flags & GPUControlWire.wantCurve != 0 @@ -434,7 +476,9 @@ final class FakeGPUControlKext: @unchecked Sendable { return GPUControlOD8Want(curve: curve ? points : nil, zeroRpmOff: flags & GPUControlWire.wantZeroRpmOff != 0, gfxMaxMHz: input[12] == 0 ? nil : Int(input[12]), - gfxMinMHz: low == 0 ? nil : Int(low)) + gfxMinMHz: low == 0 ? nil : Int(low), + voltMV: mv == 0 ? nil : Int(mv), + overclock: flags & GPUControlWire.wantOverclock != 0) } // MARK: The kext's calls @@ -476,12 +520,22 @@ final class FakeGPUControlKext: @unchecked Sendable { return bootW * UInt32(100 + powerPercentMin) / 100 } - // `GPUControl::set` and the worker's `runSet`. - private func set(client: UInt64, watts: UInt32) -> GPUControlReply { + // `powerCeiling` (0.9.0): the start-up limit plus the card's power + // percent, cut at +15; 0 while the floor is not known. + private var ceilLocked: UInt32 { + guard floorLocked != 0, powerPercentFeature == 0x8 else { return floorLocked == 0 ? 0 : bootW } + guard powerPercentMax > 0 else { return bootW } + return bootW * UInt32(100 + Swift.min(powerPercentMax, 15)) / 100 + } + + // `GPUControl::set` and the worker's `runSet`. `raise`: the 3-scalar + // form's flag (0.9.0). + private func set(client: UInt64, watts: UInt32, raise: Bool = false) -> GPUControlReply { startRevert(owner.expired(nowMs)) if owner.isOff || owner.isReadOnly { return record(.off) } let reply: GPUControlReply - switch Self.routeSet(boot: bootW, floor: floorLocked, watts: watts) { + let ceil = raise ? ceilLocked : 0 + switch Self.routeSet(boot: bootW, floor: floorLocked, watts: watts, ceil: ceil) { case .refuse(let refusal): reply = refusal case .release: @@ -494,6 +548,9 @@ final class FakeGPUControlKext: @unchecked Sendable { if pre == .ok, od8Dirty { pre = .busy } guard pre == .ok else { return record(pre) } if workerStalled { return record(timeout(client: client)) } + // A raised limit is held under the watchdog: never one it cannot + // watch (runSet, 0.9.0). + if raise, watts > bootW, !dogSees { return record(.noReadings) } reply = runSet(client: client, watts: watts) } return record(reply) @@ -555,7 +612,9 @@ final class FakeGPUControlKext: @unchecked Sendable { if sleepingLocked { return (.sleeping, .ok) } if heldW != 0 || limitUnknown { return (.busy, .ok) } var check = GPUControlOD8Check.ok - if want.curve != nil, !dogSees { check = .noReadings } + // Never a curve, a raised GFX minimum or (0.9.0) an overclock the + // watchdog cannot watch. + if want.curve != nil || want.gfxMinMHz != nil || want.overclock, !dogSees { check = .noReadings } if check == .ok, !gpuAnswers { return (.notReady, .ok) } if check == .ok { check = checkOD8(want) } if check != .ok { @@ -585,7 +644,7 @@ final class FakeGPUControlKext: @unchecked Sendable { turnOffLocked(.od8Failed) return (.failed, .ok) } - od8Held = want.heldFlags.rawValue + od8Held = want.heldFlags(stockGfxMaxMHz: stockGfxMaxMHz).rawValue od8HeldWant = want od8Changes += 1 od8LastCheck = 0 @@ -613,12 +672,19 @@ final class FakeGPUControlKext: @unchecked Sendable { if curve[0].temperatureC > 30 { return .curveFirst } if let last = curve.last, last.speedPercent != 100 || last.temperatureC > fanTargetC - 22 { return .curveLast } } - if let gfx = want.gfxMaxMHz, gfx < GPUControlWire.gfxFloorMHz || gfx > stockGfxMaxMHz || gfx < gfxMinMHz { + let top = want.overclock ? gfxMaxTopMHz : stockGfxMaxMHz + if let gfx = want.gfxMaxMHz, gfx < GPUControlWire.gfxFloorMHz || gfx > top || gfx < gfxMinMHz { return .gfxRange } if let low = want.gfxMinMHz, low < gfxMinMHz || low > gfxMinTopMHz || low > (want.gfxMaxMHz ?? stockGfxMaxMHz) { return .gfxMinRange } + if let mv = want.voltMV { + guard takesOverclock else { return .noFeature } + if mv < voltMinMV || mv > voltStockMV || (voltStockMV - mv) % GPUControlWire.voltStepMV != 0 { + return .voltRange + } + } return .ok } @@ -641,6 +707,7 @@ final class FakeGPUControlKext: @unchecked Sendable { var flags: GPUControlFlags = [] if od8Ready { flags.insert(.od8Ready) } if takesGfxMin { flags.insert(.gfxMin) } + if takesOverclock { flags.formUnion([.volt, .raise]) } if owner.isArmed { flags.insert(.armed) } if owner.isOff || owner.isReadOnly { flags.insert(.off) } if sleepingLocked { flags.insert(.sleeping) } @@ -665,6 +732,7 @@ final class FakeGPUControlKext: @unchecked Sendable { if !owner.isArmed { return "closed: sudo gpucontrol arm opens it until restart" } if sleepingLocked { return "armed: the Mac is between sleep and wake" } if owner.isReverting || pendingRevert != 0 { return "armed: going back to the start-up limit" } + if owner.owner != 0, owner.isChanged, heldW > bootW { return "armed: a program holds a raised limit (watchdog on)" } if owner.owner != 0, owner.isChanged { return "armed: a program holds a lower limit" } return "armed: nothing held" } @@ -677,7 +745,7 @@ final class FakeGPUControlKext: @unchecked Sendable { if od8Held & GPUControlOD8Held.unknown.rawValue != 0 { return "armed: the last OD8 call was not taken; going back to stock" } - if od8Dirty, od8Held != 0 { return "armed: a program holds a fan or clock change" } + if od8Dirty, od8Held != 0 { return "armed: a program holds a fan, clock or voltage change" } if od8Dirty { return "armed: going back to stock" } return "armed: OD8 at stock" } @@ -775,6 +843,10 @@ final class FakeGPUControlKext: @unchecked Sendable { } else { if !owner.isChanged { heldW = 0 } reverts += 1 + if powerOffAfterWayBack { + powerOffAfterWayBack = false + turnOffLocked(.powerWatchdog) + } } } @@ -809,11 +881,18 @@ final class FakeGPUControlKext: @unchecked Sendable { private enum Route { case refuse(GPUControlReply), release, change } // `checkPower` and `routeSet`. `floor` 0: not known (0.8.0), only the - // start-up value is taken. - private static func routeSet(boot: UInt32, floor: UInt32, watts: UInt32) -> Route { + // start-up value is taken. `ceil` (0.9.0): the card's ceiling, given only + // for a request with the raise flag; 0, or not above the start-up value, + // refuses anything above it as before. + private static func routeSet(boot: UInt32, floor: UInt32, watts: UInt32, ceil: UInt32 = 0) -> Route { if !bootPlausible(boot) { return .refuse(.noBootValue) } if watts == boot { return .release } - if watts > boot { return .refuse(.aboveBoot) } + if watts > boot { + if ceil <= boot { return .refuse(.aboveBoot) } + if watts > ceil { return .refuse(.aboveCeiling) } + if watts != ceil, watts % UInt32(GPUControlWire.powerStepW) != 0 { return .refuse(.notAStep) } + return .change + } if floor == 0 || floor > boot { return .refuse(.noFloor) } if watts < floor { return .refuse(.belowFloor) } if watts % UInt32(GPUControlWire.powerStepW) != 0 { return .refuse(.notAStep) } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlChannel.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlChannel.swift index 1d3844d5..dd6ca903 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlChannel.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlChannel.swift @@ -49,8 +49,12 @@ extension GPUControlChannel { } /// Asks for a power limit in watts. The start-up value is the way back. - func setPower(watts: UInt32) -> GPUControlAnswer? { - answer(.set, input: [GPUControlWire.channelVersion, UInt64(watts)]) + /// `raise` (kext 0.9.0): the 3-scalar form with the raise flag, for a + /// limit above the start-up one; an older kext refuses that count. + func setPower(watts: UInt32, raise: Bool = false) -> GPUControlAnswer? { + let input = raise ? [GPUControlWire.channelVersion, UInt64(watts), GPUControlWire.setWantRaise] + : [GPUControlWire.channelVersion, UInt64(watts)] + return answer(.set, input: input) } /// Asks for a whole OD8 state. Nil also when the state cannot be written diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift index ba9823c7..0b309321 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift @@ -6,9 +6,11 @@ import Foundation /// What the app asks GPUSensors.kext to hold. enum GPUControlRequest: Equatable, Hashable, Sendable { - /// A lower power limit in watts. + /// A lower power limit in watts, or (kext 0.9.0) a higher one, sent with + /// `set`'s raise form. case power(watts: UInt32) - /// The whole OD8 state: fan curve, zero RPM and GFX maximum together. + /// The whole OD8 state: fan curve, zero RPM, the GFX clocks and the GFX + /// voltage together. case od8(GPUControlOD8Want) /// Back to the start-up values: `release`, never a change. case startUp @@ -234,14 +236,56 @@ final class GPUControlEngine { snapshot.outcome = nil } - /// The whole OD8 state with the GFX maximum changed: the curve and zero - /// RPM that are held or asked for go with it. + /// The whole OD8 state with the GFX maximum lowered: the curve, zero RPM + /// and the rest that are held or asked for go with it. The stock maximum + /// (nil) gives back a lowered one only: a raised maximum belongs to the + /// overclock control, and stays. func chooseGfxMax(_ mhz: Int?) { var want = od8Basis + if mhz == nil, want.overclock { return chooseOD8(want) } want.gfxMaxMHz = mhz + want.overclock = false chooseOD8(want) } + /// The whole OD8 state with a GFX maximum above stock (GPUSensors 0.9.0, + /// the overclock flag), or nil for the stock maximum: nil gives back a + /// raised maximum only, and keeps a lowered one. + func chooseGfxMaxRaised(_ mhz: Int?) { + var want = od8Basis + if let mhz { + want.gfxMaxMHz = mhz + want.overclock = true + } else if want.overclock { + want.gfxMaxMHz = nil + want.overclock = false + } + chooseOD8(want) + } + + /// The whole OD8 state with the GFX voltage changed (GPUSensors 0.9.0): + /// a lower one in mV, or nil for stock. The rest goes with it. + func chooseVolt(_ mv: Int?) { + var want = od8Basis + want.voltMV = mv + chooseOD8(want) + } + + /// The overclock switch went off: every raise the app holds or asks for + /// goes back to stock (a power limit above the start-up one, a GFX + /// maximum above stock). Nothing else changes. + func dropRaises() { + let current = wanted ?? snapshot.held + switch current { + case .power(let watts)?: + if let boot = snapshot.status?.bootW, boot != 0, UInt64(watts) > boot { choose(.startUp) } + case .od8(let want)? where want.overclock: + chooseGfxMaxRaised(nil) + default: + break + } + } + /// The whole OD8 state with the GFX minimum changed (GPUSensors 0.9.0): /// the fan state and the GFX maximum that are held or asked for go with /// it. @@ -492,7 +536,7 @@ final class GPUControlEngine { static func matches(_ request: GPUControlRequest, _ status: GPUControlChannelStatus) -> Bool { switch request { case .power(let watts): return status.heldW == UInt64(watts) && !status.holdsOD8 - case .od8(let want): return status.od8Held == want.heldFlags && !status.holdsPower + case .od8(let want): return want.matches(held: status.od8Held) && !status.holdsPower case .startUp: return !status.holdsPower && !status.holdsOD8 } } @@ -603,7 +647,12 @@ final class GPUControlEngine { quietSince = nil let answer: GPUControlAnswer? switch request { - case .power(let watts): answer = channel.setPower(watts: watts) + case .power(let watts): + // Above the start-up limit only in the raise form, and only to a + // kext that takes it; an older one refuses the value either way. + let status = snapshot.status + let raise = status.map { $0.flags.contains(.raise) && $0.bootW != 0 && UInt64(watts) > $0.bootW } ?? false + answer = channel.setPower(watts: watts, raise: raise) case .od8(let want): guard want.scalars() != nil else { refuse(request, GPUControlAnswer(replyCode: GPUControlReply.badArgs.rawValue)) @@ -850,6 +899,12 @@ final class GPUControlController: @unchecked Sendable { func chooseGfxMin(_ mhz: Int?) { queue.async { [self] in engine.chooseGfxMin(mhz); run() } } + func chooseGfxMaxRaised(_ mhz: Int?) { queue.async { [self] in engine.chooseGfxMaxRaised(mhz); run() } } + + func chooseVolt(_ mv: Int?) { queue.async { [self] in engine.chooseVolt(mv); run() } } + + func dropRaises() { queue.async { [self] in engine.dropRaises(); run() } } + func chooseFan(curve: [GPUControlFanPoint]?, zeroRpmOff: Bool) { queue.async { [self] in engine.chooseFan(curve: curve, zeroRpmOff: zeroRpmOff); run() } } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift index 6273b2d2..41a15aca 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift @@ -21,7 +21,7 @@ import Foundation /// the curve is applied. enum GPUControlCurveRules { static let entryCount = 38 - static let gfxMax = 0, gfxMin = 1, memMax = 8, targetTemp = 12, zeroRpm = 15, zeroRpmStop = 35 + static let gfxMax = 0, gfxMin = 1, memMax = 8, targetTemp = 12, zeroRpm = 15, zeroRpmStop = 35, gfxVolt = 37 static let points = GPUControlWire.fanCurvePoints static func tempID(_ k: Int) -> Int { 19 + 2 * k } static func speedID(_ k: Int) -> Int { 20 + 2 * k } @@ -31,6 +31,9 @@ enum GPUControlCurveRules { static let driftMHz = 25 static let sensorGapC = 22 static let firstPointMaxC = 30 + // GPUSensors 0.9.0: the GFX voltage's feature bit and step. + static let voltFeature = GPUControlStatus.voltFeature + static let voltStepMV = GPUControlWire.voltStepMV /// The kext builds this copy was checked against (`VersionInfo`). With /// any other build the preview says so and does not decide. @@ -46,7 +49,8 @@ enum GPUControlCurveRules { /// ("081") leaves these checks as they were in 0.8.0. GPUSensors 0.9.0 /// ("090") adds the GFX minimum (`GfxMinRange`) and gives the same /// answers as 0.8.0 for the first 100 lines of `curve-cases.jsonl`; the - /// lines after them are its GFX minimum cases. + /// lines after them are its GFX minimum cases, then (the same 0.9.0) its + /// GFX voltage and overclock cases, after the first 120. static let checkedReleases: Set = ["080", "081", "090"] /// The kext build is one this copy was checked against. Neither the @@ -98,6 +102,9 @@ enum GPUControlCurveRules { var first = [Entry](repeating: Entry(), count: GPUControlCurveRules.entryCount) var fresh = [Entry](repeating: Entry(), count: GPUControlCurveRules.entryCount) var current = [Int](repeating: 0, count: GPUControlCurveRules.entryCount) + /// The features the driver does not allow now (the current read's + /// mask, `OD8.NotAllowed`): read only for a GFX voltage (0.9.0). + var notAllowed: UInt32 = 0 init() {} @@ -110,6 +117,7 @@ enum GPUControlCurveRules { guard let caps = table.caps else { return nil } firstCaps = caps freshCaps = caps + notAllowed = table.notAllowed ?? 0 for (id, name) in GPUControlCurveRules.names.enumerated() { guard let setting = table.settings[name] else { continue } first[id] = Entry(feature: setting.feature, min: setting.min, max: setting.max, def: setting.stock) @@ -223,7 +231,9 @@ enum GPUControlCurveRules { } } if let mhz = want.gfxMaxMHz { - let top = Swift.min(s.first[gfxMax].def, s.fresh[gfxMax].def) + // GPUSensors 0.9.0: with the overclock flag the top is the card's + // own maximum for id 0 (the same in both reads, checked above). + let top = want.overclock ? s.fresh[gfxMax].max : Swift.min(s.first[gfxMax].def, s.fresh[gfxMax].def) if mhz < gfxFloorMHz || mhz > top || mhz < s.first[gfxMin].def { return Result(check: .gfxRange) } } // GPUSensors 0.9.0: the minimum in the card's range for id 1 (the @@ -234,6 +244,15 @@ enum GPUControlCurveRules { let top = want.gfxMaxMHz ?? Swift.min(s.first[gfxMax].def, s.fresh[gfxMax].def) if low < range.min || low > range.max || low > top { return Result(check: .gfxMinRange) } } + // GPUSensors 0.9.0: the GFX voltage, offered as at boot and allowed + // now, lower only, in 25 mV steps from stock. + if let mv = want.voltMV { + let v = s.first[gfxVolt] + if v.feature != voltFeature || s.notAllowed & voltFeature != 0 { return Result(check: .noFeature) } + if mv < v.min || mv > v.max || mv > v.def || (v.def - mv) % voltStepMV != 0 { + return Result(check: .voltRange) + } + } return .ok } } @@ -309,5 +328,6 @@ struct GPUControlFanDraft: Equatable, Sendable { /// no clock held. func givesBack(_ held: GPUControlOD8Want) -> Bool { want.isStock && (held.curve != nil || held.zeroRpmOff) && held.gfxMaxMHz == nil && held.gfxMinMHz == nil + && held.voltMV == nil } } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift index 2771fdcd..d7bed525 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift @@ -48,6 +48,10 @@ struct GPUControlFacts: Equatable, Sendable { /// The kext can close writing again (`disarm`, 0.8.0): it publishes /// `PowerRangeState`, which 0.7.x does not. var canDisarm = false + /// The kext takes raises (0.9.0): the overclock flag of `setOD8` and the + /// raise form of `set` (status flag 2048; from the properties, `Takes` + /// with the bit for a GFX maximum above stock). + var takesRaise = false var writeOff: GPUControlWriteOff? { GPUControlWriteOff(rawValue: writeOffCode) } /// The read-only card (kext 0.8.0): read, never controlled. @@ -78,6 +82,7 @@ struct GPUControlFacts: Equatable, Sendable { mine = flags.contains(.mine) ready = flags.contains(.ready) od8Ready = flags.contains(.od8Ready) + takesRaise = flags.contains(.raise) bootW = status.bootW == 0 ? nil : Int(clamping: status.bootW) heldW = status.heldW == 0 ? nil : Int(clamping: status.heldW) writeOffCode = status.writeOffCode @@ -119,6 +124,7 @@ struct GPUControlFacts: Equatable, Sendable { od8Changes = writing.od8State?.changes od8Reverts = writing.od8State?.reverts od8Ready = writing.od8Read == .read + takesRaise = writing.od8State?.takesGfxMaxUp == true if case .notClean(let text)? = writing.od8Read { od8ReadText = text } changed = (heldW != nil && bootW != nil && heldW != bootW) || !od8Held.isEmpty takeRange(from: writing) @@ -426,6 +432,9 @@ enum GPUControlRemembered: Equatable, Sendable { if mhz > 0 { want.gfxMaxMHz = mhz } let low = defaults.integer(forKey: DefaultsKey.gpuControlRememberedGfxMinMHz) if low > 0 { want.gfxMinMHz = low } + let mv = defaults.integer(forKey: DefaultsKey.gpuControlRememberedVoltMV) + if mv > 0 { want.voltMV = mv } + want.overclock = defaults.bool(forKey: DefaultsKey.gpuControlRememberedOverclock) if let flat = defaults.array(forKey: DefaultsKey.gpuControlRememberedCurve) as? [Int] { guard flat.count == 2 * GPUControlWire.fanCurvePoints else { return .nothing } want.curve = stride(from: 0, to: flat.count, by: 2).map { @@ -444,6 +453,8 @@ enum GPUControlRemembered: Equatable, Sendable { defaults.removeObject(forKey: DefaultsKey.gpuControlRememberedZeroRpmOff) defaults.removeObject(forKey: DefaultsKey.gpuControlRememberedGfxMHz) defaults.removeObject(forKey: DefaultsKey.gpuControlRememberedGfxMinMHz) + defaults.removeObject(forKey: DefaultsKey.gpuControlRememberedVoltMV) + defaults.removeObject(forKey: DefaultsKey.gpuControlRememberedOverclock) switch self { case .nothing: defaults.set("none", forKey: DefaultsKey.gpuControlRememberedKind) @@ -459,6 +470,8 @@ enum GPUControlRemembered: Equatable, Sendable { defaults.set(want.zeroRpmOff, forKey: DefaultsKey.gpuControlRememberedZeroRpmOff) if let mhz = want.gfxMaxMHz { defaults.set(mhz, forKey: DefaultsKey.gpuControlRememberedGfxMHz) } if let low = want.gfxMinMHz { defaults.set(low, forKey: DefaultsKey.gpuControlRememberedGfxMinMHz) } + if let mv = want.voltMV { defaults.set(mv, forKey: DefaultsKey.gpuControlRememberedVoltMV) } + if want.overclock { defaults.set(true, forKey: DefaultsKey.gpuControlRememberedOverclock) } } } } @@ -495,6 +508,10 @@ enum GPUControlRememberPolicy { /// `gfxMin`: the GFX minimum the kext takes now (`GPUControlClockMinLogic /// .limits`), nil when it takes none (a kext before 0.9.0): a remembered /// minimum outside it is left out of the request, like the maximum. + /// This is the request at launch: a GFX voltage and every raise (a GFX + /// maximum above stock, a power limit above the start-up one) are never + /// asked for again here. A value that froze the Mac would freeze it again + /// at the next launch, and again. The rest of the state still goes. static func request(remembered: GPUControlRemembered, active: Bool, facts: GPUControlFacts?, stopped: GPUControlStop?, stockGfxMaxMHz: Int? = nil, kextVersion: String? = nil, @@ -505,8 +522,10 @@ enum GPUControlRememberPolicy { case .nothing: return nil case .power(let watts): - guard watts > 0, let boot = facts.bootW, GPUControlPageLogic.powerChoices(bootW: boot, range: facts.powerRange) - .contains(watts), watts != boot else { return nil } + // Only the lower limits the pop-up offers: never one above the + // start-up limit (a raise) at launch. + guard watts > 0, let boot = facts.bootW, watts < boot, + GPUControlPageLogic.powerChoices(bootW: boot, range: facts.powerRange).contains(watts) else { return nil } return .power(watts: UInt32(watts)) case .od8(var want): // OD8 not read cleanly: the kext could not take it. @@ -515,6 +534,7 @@ enum GPUControlRememberPolicy { // with it, and Apply is off too. Nothing goes, not even the clock: // only what was held is asked for again, never a part of it. if want.curve != nil || want.zeroRpmOff, !GPUControlCurveRules.isChecked(kextVersion) { return nil } + want = strippedAtLaunch(want) if let mhz = want.gfxMaxMHz, !GPUControlClockLogic.lowers(mhz, stockGfxMaxMHz: stockGfxMaxMHz) { want.gfxMaxMHz = nil } @@ -523,6 +543,19 @@ enum GPUControlRememberPolicy { } } + /// A remembered OD8 state without what is never asked for at launch: the + /// GFX voltage, and the overclock flag with the raised GFX maximum it + /// allowed (a lowered maximum stays). + static func strippedAtLaunch(_ want: GPUControlOD8Want) -> GPUControlOD8Want { + var want = want + want.voltMV = nil + if want.overclock { + want.overclock = false + want.gfxMaxMHz = nil + } + return want + } + /// A remembered limit the card does not take is forgotten, not kept for /// later: one saved with 0.7.x below this card's floor (200 W where the /// floor is 225 W). Only once the range is known. @@ -660,22 +693,199 @@ enum GPUControlClockMinLogic { } extension GPUControlRememberPolicy { - /// A remembered request again, right before it goes out: a clock that no - /// longer lowers the stock maximum of the moment is left out (the rest - /// of the fan state still goes), and so is a minimum the kext does not - /// take now (`gfxMin` nil: a kext before 0.9.0, or no clean OD8 read). + /// A remembered request again, right before it goes out (after a wake, + /// in the same run of the app): a clock that no longer lowers the stock + /// maximum of the moment is left out (the rest of the fan state still + /// goes), and so is a minimum the kext does not take now (`gfxMin` nil: + /// a kext before 0.9.0, or no clean OD8 read). The same for a GFX voltage + /// (`volt`) and a raised GFX maximum (`overclock`, the card's range for + /// it): kept only while the kext takes them and inside the card's range. /// Nil when nothing is left to ask. static func checkedAgain(_ request: GPUControlRequest, stockGfxMaxMHz: Int?, - gfxMin: GPUControlClockMinLogic.Limits? = nil) -> GPUControlRequest? { + gfxMin: GPUControlClockMinLogic.Limits? = nil, + volt: GPUControlVoltLogic.Limits? = nil, + overclock: GPUControlOverclockLogic.GfxLimits? = nil) -> GPUControlRequest? { guard case .od8(var want) = request else { return request } - if let mhz = want.gfxMaxMHz, !GPUControlClockLogic.lowers(mhz, stockGfxMaxMHz: stockGfxMaxMHz) { - want.gfxMaxMHz = nil + if let mhz = want.gfxMaxMHz { + let raised = want.overclock && GPUControlOverclockLogic.raises(mhz, limits: overclock) + if !raised, !GPUControlClockLogic.lowers(mhz, stockGfxMaxMHz: stockGfxMaxMHz) { want.gfxMaxMHz = nil } + } + // The flag goes only with the raise it allows. + if want.overclock, !(want.gfxMaxMHz.map { GPUControlOverclockLogic.raises($0, limits: overclock) } ?? false) { + want.overclock = false } want = GPUControlClockMinLogic.checked(want, limits: gfxMin, stockGfxMaxMHz: stockGfxMaxMHz) + want = GPUControlVoltLogic.checked(want, limits: volt) return want.isStock ? nil : .od8(want) } } +// MARK: - The GFX voltage (GPUSensors 0.9.0) + +/// The voltage control's numbers, from the card's own table +/// (`OD8.Settings.GfxVoltOffset`, the driver's VddGfxOffset: 881 to 1075 mV, +/// stock 1075, on the test card). The value is a cap in mV: the whole GFX +/// voltage curve goes down by stock minus the value. Only lower than stock, +/// at or above the card's minimum, in 25 mV steps from stock: the kext takes +/// that and nothing else (`VoltRange`). Only offered when the kext publishes +/// `Takes` with the voltage and the card offers it. +enum GPUControlVoltLogic { + static let step = GPUControlWire.voltStepMV + + /// The card's lowest value and its stock one, in mV. + struct Limits: Equatable, Sendable { + var min: Int + var stock: Int + } + + /// Nil when the kext takes no voltage (before 0.9.0), OD8 is not read + /// cleanly, the card does not offer it, or nothing is lower than stock. + static func limits(writing: GPUControlStatus.Writing?, od8Ready: Bool) -> Limits? { + guard od8Ready, writing?.od8State?.takesVolt == true, let v = writing?.od8?.gfxVolt else { return nil } + let limits = Limits(min: v.min, stock: v.stock) + return range(limits) == nil ? nil : limits + } + + /// The control's range: the lowest 25 mV step from stock at or above + /// the card's minimum, up to stock. Nil when there is no such step. + static func range(_ limits: Limits?) -> ClosedRange? { + guard let limits, limits.min < limits.stock else { return nil } + let bottom = limits.stock - (limits.stock - limits.min) / step * step + guard bottom < limits.stock else { return nil } + return bottom...limits.stock + } + + /// A value the control may send as a hold: below stock, at or above the + /// card's minimum, a whole number of steps from stock. + static func lowers(_ mv: Int, limits: Limits?) -> Bool { + guard let limits else { return false } + return mv < limits.stock && mv >= limits.min && (limits.stock - mv) % step == 0 + } + + /// What choosing `mv` asks for: nil (the stock voltage, the way back) at + /// or above stock, else the value. + static func request(_ mv: Int, stockMV: Int) -> Int? { + mv >= stockMV ? nil : mv + } + + /// A slider position as a value: 25 mV steps down from stock, never + /// below the range. + static func snapped(_ raw: Double, range: ClosedRange) -> Int { + let top = range.upperBound + let value = top - Int(((Double(top) - raw) / Double(step)).rounded()) * step + return Swift.min(top, Swift.max(range.lowerBound, value)) + } + + /// The slider's tick marks, one every step. + static func tickCount(range: ClosedRange) -> Int { + (range.upperBound - range.lowerBound) / step + 1 + } + + /// The starting point the page offers: one step below stock, from the + /// card's own table, never a fixed number. Nil when that step is below + /// the card's minimum, or the card offers no voltage. A starting point to + /// test, never applied on its own. + static func recommended(_ limits: Limits?) -> Int? { + guard let limits else { return nil } + let mv = limits.stock - step + return mv >= limits.min ? mv : nil + } + + /// A state with its voltage checked against what the kext takes now: + /// left out when the kext takes none or the value is not one it takes. + static func checked(_ want: GPUControlOD8Want, limits: Limits?) -> GPUControlOD8Want { + guard let mv = want.voltMV, !lowers(mv, limits: limits) else { return want } + var want = want + want.voltMV = nil + return want + } +} + +// MARK: - Overclock (GPUSensors 0.9.0) + +/// The overclock section's numbers: a GFX maximum above stock up to the +/// card's own maximum (`OD8.Settings.GfxMaxMHz.Max`, 2800 MHz on the test +/// card; sent with the overclock flag), and a power limit above the start-up +/// one up to the card's ceiling (`PowerRange.CeilW`, 261 W on the test card; +/// sent with `set`'s raise form). Both are inside AMD's own limits for the +/// card; the kext takes nothing else, and holds them under its watchdog. +enum GPUControlOverclockLogic { + static let step = 10 + static let tickStepMHz = 100 + + /// The stock GFX maximum and the card's own top for it. + struct GfxLimits: Equatable, Sendable { + var stock: Int + var max: Int + } + + /// Nil when the kext takes no raised maximum (`Takes` without 64), OD8 is + /// not read cleanly, or the card's top is not above stock. + static func gfxLimits(writing: GPUControlStatus.Writing?, od8Ready: Bool) -> GfxLimits? { + guard od8Ready, writing?.od8State?.takesGfxMaxUp == true, let stock = writing?.od8?.stockGfxMaxMHz, + let top = writing?.od8?.gfxMaxTopMHz, top > stock else { return nil } + return GfxLimits(stock: stock, max: top) + } + + /// The raised maximum's range: stock (the way back) to the card's top. + static func gfxRange(_ limits: GfxLimits) -> ClosedRange { limits.stock...limits.max } + + /// A value the control may send as a raise: above stock, at most the + /// card's top. + static func raises(_ mhz: Int, limits: GfxLimits?) -> Bool { + guard let limits else { return false } + return mhz > limits.stock && mhz <= limits.max + } + + /// What choosing `mhz` asks for: nil (the stock maximum) at or below + /// stock, else the value. + static func request(_ mhz: Int, stockMHz: Int) -> Int? { + mhz <= stockMHz ? nil : mhz + } + + /// A slider position as a value: 10 MHz steps from stock, the card's top + /// on its own. + static func snapped(_ raw: Double, range: ClosedRange) -> Int { + let floor = range.lowerBound + let value = floor + Int(((raw - Double(floor)) / Double(step)).rounded()) * step + if value >= range.upperBound - step / 2 { return range.upperBound } + return Swift.max(floor, value) + } + + /// The slider's tick marks, one every 100 MHz from stock. + static func tickCount(range: ClosedRange) -> Int { + (range.upperBound - range.lowerBound) / tickStepMHz + 1 + } + + /// The card's power ceiling, when the kext takes raises and the card + /// offers a limit above the start-up one (`CeilW` above `MaxW`, for this + /// start-up value). Nil otherwise. + static func ceilingW(facts: GPUControlFacts?) -> Int? { + guard let facts, facts.takesRaise, let boot = facts.bootW, let range = facts.powerRange, + range.maxW == boot, let ceil = range.ceilW, ceil > boot else { return nil } + return ceil + } + + /// The raised pop-up's values: the start-up value first (the way back), + /// then every multiple of the step above it up to the ceiling, and the + /// ceiling itself (the kext takes it even off a step: 261 W). + static func powerChoices(bootW: Int?, ceilW: Int?, stepW: Int = GPUControlWire.powerStepW) -> [Int] { + guard let boot = bootW, let ceil = ceilW, ceil > boot else { return [] } + let step = Swift.max(stepW, 1) + let firstAbove = (boot / step + 1) * step + var choices = [boot] + if firstAbove <= ceil { choices += Array(stride(from: firstAbove, through: ceil, by: step)) } + if choices.last != ceil { choices.append(ceil) } + return choices + } + + /// A limit above the start-up one: sent with the raise form. + static func raisesPower(_ watts: Int, bootW: Int?) -> Bool { + guard let boot = bootW else { return false } + return watts > boot + } +} + /// Which channel the app connects at launch (plan 11.1). enum GPUControlConnectionMode: Equatable, Sendable { case none diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift index 8217b4e5..654d09a1 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift @@ -66,6 +66,16 @@ final class GPUControlService: ObservableObject { } } + /// The "Allow overclocking" switch (GPUSensors 0.9.0; off by default). + /// Turning it off gives back every raise the app holds or asks for. + @Published var overclock: Bool { + didSet { + guard overclock != oldValue else { return } + defaults.set(overclock, forKey: DefaultsKey.gpuControlOverclock) + if !overclock { controller?.dropRaises() } + } + } + private let defaults: UserDefaults private var controller: GPUControlController? private var fake: FakeGPUControlKext? @@ -83,6 +93,7 @@ final class GPUControlService: ObservableObject { init(defaults: UserDefaults = .standard) { self.defaults = defaults remember = defaults.bool(forKey: DefaultsKey.gpuControlRemember) + overclock = defaults.bool(forKey: DefaultsKey.gpuControlOverclock) } var facts: GPUControlFacts? { GPUControlPageLogic.facts(snapshot: snapshot, control: control) } @@ -128,7 +139,9 @@ final class GPUControlService: ObservableObject { let od8Ready = control?.writing?.od8Read == .read return GPUControlRememberPolicy.checkedAgain( request, stockGfxMaxMHz: control?.writing?.od8?.stockGfxMaxMHz, - gfxMin: GPUControlClockMinLogic.limits(writing: control?.writing, od8Ready: od8Ready)) + gfxMin: GPUControlClockMinLogic.limits(writing: control?.writing, od8Ready: od8Ready), + volt: GPUControlVoltLogic.limits(writing: control?.writing, od8Ready: od8Ready), + overclock: GPUControlOverclockLogic.gfxLimits(writing: control?.writing, od8Ready: od8Ready)) } controller.start() self.controller = controller @@ -180,6 +193,18 @@ final class GPUControlService: ObservableObject { controller?.chooseGfxMin(mhz) } + /// The overclock control (GPUSensors 0.9.0): a GFX maximum above stock, + /// sent with the overclock flag, or nil for the stock maximum. + func chooseGfxMaxRaised(_ mhz: Int?) { + controller?.chooseGfxMaxRaised(mhz) + } + + /// The voltage control (GPUSensors 0.9.0): a lower GFX voltage in mV, or + /// nil for stock. The rest of a held OD8 state goes with it. + func chooseVolt(_ mv: Int?) { + controller?.chooseVolt(mv) + } + func backToStartUp() { controller?.choose(.startUp) } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlWire.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlWire.swift index 07a585b2..c079a457 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlWire.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlWire.swift @@ -11,7 +11,12 @@ import Foundation /// `disarm` selector, two replies, one `WriteOff` reason and the card's own /// power range (`PowerRange`, read from the properties). 0.9.0 keeps it too /// and adds the GFX minimum clock: a 14-scalar `setOD8`, one OD8 refusal, -/// one held bit and one status flag. Nothing here talks to the kext. +/// one held bit and one status flag; then the GFX voltage (a 15-scalar +/// `setOD8`), the overclock flag for a GFX maximum above stock, the raise +/// form of `set` (3 scalars, a limit above the start-up one up to +/// `PowerRange.CeilW`), two replies, one more OD8 refusal, one `WriteOff` +/// reason, two held bits and two status flags. Nothing here talks to the +/// kext. enum GPUControlWire { /// The first scalar of every call. A kext that speaks another version /// answers `badVersion` and nothing else. @@ -30,7 +35,8 @@ enum GPUControlWire { /// still needs `arm`. A 0.7.x kext does not know it: the call fails. case disarm = 6 - /// Scalars in, the version included; for `setOD8` its 0.7.0 form. + /// Scalars in, the version included; for `setOD8` its 0.7.0 form, for + /// `set` the form that never raises. var inputCount: Int { switch self { case .set: return 2 @@ -40,10 +46,18 @@ enum GPUControlWire { } /// Whether the kext takes this many scalars: `setOD8` also takes the - /// 14 of kext 0.9.0, which carry a GFX minimum. + /// 14 and 15 of kext 0.9.0 (a GFX minimum, a GFX voltage), and `set` + /// its 3-scalar raise form (`od8WireCountOk`, `setWireCountOk`). func takes(inputCount count: Int) -> Bool { - self == .setOD8 ? count == GPUControlWire.setOD8InputCount - || count == GPUControlWire.setOD8InputCountGfxMin : count == inputCount + switch self { + case .setOD8: + return count == GPUControlWire.setOD8InputCount || count == GPUControlWire.setOD8InputCountGfxMin + || count == GPUControlWire.setOD8InputCountVolt + case .set: + return count == inputCount || count == GPUControlWire.setInputCountRaise + default: + return count == inputCount + } } /// Scalars out, the reply first. @@ -62,6 +76,12 @@ enum GPUControlWire { /// The same and `gfxMinMHz` (kext 0.9.0). Sent only with a GFX minimum: /// an older kext refuses this count. static let setOD8InputCountGfxMin = 14 + /// The same and `voltMV` (kext 0.9.0, `kOd8WireCount`). Sent only with a + /// GFX voltage. + static let setOD8InputCountVolt = 15 + /// `set`'s raise form, `{version, watts, flags}` (kext 0.9.0, + /// `kSetWireCountRaise`). Sent only for a limit above the start-up one. + static let setInputCountRaise = 3 static let fanCurvePoints = 5 /// `set` and `setOD8` wait this long for the kext's worker. @@ -91,6 +111,14 @@ enum GPUControlWire { /// `setOD8`'s flags scalar. static let wantCurve: UInt64 = 1 static let wantZeroRpmOff: UInt64 = 2 + /// 0.9.0: the GFX maximum may be above stock, up to the card's own + /// maximum (`kOd8WantOverclock`). A permission, not a setting. + static let wantOverclock: UInt64 = 4 + /// `set`'s flags scalar in the raise form (`kSetWantRaise`): the limit + /// may be above the start-up one, up to the card's ceiling. + static let setWantRaise: UInt64 = 1 + /// The GFX voltage goes down from stock in these steps (`kOd8VoltStepMV`). + static let voltStepMV = 25 } /// A call's first scalar out (`gpuctl::Reply`). @@ -119,6 +147,12 @@ enum GPUControlReply: UInt64, CaseIterable, Sendable { /// `set` (0.8.0): the card's minimum power limit is not known /// (`PowerRangeState` says why): only the start-up value is taken. case noFloor = 20 + /// `set` with the raise flag (0.9.0): above the card's ceiling + /// (`PowerRange.CeilW`). + case aboveCeiling = 21 + /// `set` with the raise flag (0.9.0): the watchdog has no fresh hotspot + /// readings, so nothing above the start-up limit. + case noReadings = 22 /// The kext's own words (`replyText`), shown under the app's sentence. var kextText: String { @@ -147,6 +181,8 @@ enum GPUControlReply: UInt64, CaseIterable, Sendable { case .stillApplied: return "refused: a change is still applied or being handled; go back to the start-up values first" case .noFloor: return "refused: the card's minimum power limit is not known (PowerRangeState)" + case .aboveCeiling: return "refused: above the card's own power ceiling (PowerRange CeilW)" + case .noReadings: return "refused: no fresh hotspot readings for the watchdog, so no raised limit" } } } @@ -169,6 +205,9 @@ enum GPUControlOD8Check: UInt64, CaseIterable, Sendable { /// 0.9.0: the GFX minimum is outside the card's range for it, or above /// the GFX maximum of the same state. case gfxMinRange = 12 + /// 0.9.0: the GFX voltage is above stock, below the card's minimum, or + /// not a 25 mV step from stock. + case voltRange = 13 /// `od8CheckText`. var kextText: String { @@ -183,9 +222,11 @@ enum GPUControlOD8Check: UInt64, CaseIterable, Sendable { case .curveFirst: return "the first fan point must be at 30 C or below" case .curveLast: return "the last fan point must be 100 % at or below the safe top temperature" case .curveCooling: return "the curve gives less air than stock somewhere" - case .gfxRange: return "GFX max must be between 1500 MHz and the stock maximum" + case .gfxRange: + return "GFX max must be between 1500 MHz and the stock maximum (with overclock: the card's own maximum)" case .noReadings: return "the fan watchdog has no fresh hotspot and fan readings" case .gfxMinRange: return "GFX min must be in the card's range and not above GFX max" + case .voltRange: return "GFX voltage must be at or below stock, in the card's range, in 25 mV steps from stock" } } } @@ -210,6 +251,9 @@ enum GPUControlWriteOff: UInt64, CaseIterable, Sendable { /// 0.8.0: a card the kext reads but never writes (the RX 6900 XT, 73BF /// rev C0). Off from boot; the reads still run. case readOnlyCard = 15 + /// 0.9.0: the watchdog put the start-up power limit back over a raised + /// one (95 C, or no readings). + case powerWatchdog = 16 /// `writeOffText`. var kextText: String { @@ -230,6 +274,7 @@ enum GPUControlWriteOff: UInt64, CaseIterable, Sendable { case .od8Failed: return "an OD8 change did not read back as sent" case .od8Watchdog: return "the fan watchdog put the stock fan back" case .readOnlyCard: return "this card can only be read (RX 6900 XT, 73BF rev C0): writing never opens on it" + case .powerWatchdog: return "the watchdog put the start-up power limit back over a raised one" } } } @@ -258,6 +303,11 @@ struct GPUControlFlags: OptionSet, Hashable, Sendable { static let od8Ready = GPUControlFlags(rawValue: 256) /// `setOD8` takes a GFX minimum (kext 0.9.0). static let gfxMin = GPUControlFlags(rawValue: 512) + /// `setOD8` takes a GFX voltage (kext 0.9.0, 15 scalars). + static let volt = GPUControlFlags(rawValue: 1024) + /// `setOD8` takes the overclock flag and `set` its raise form (kext + /// 0.9.0). + static let raise = GPUControlFlags(rawValue: 2048) } /// What the confirmed OD8 state changes (`kOd8Held*`). @@ -271,6 +321,10 @@ struct GPUControlOD8Held: OptionSet, Hashable, Sendable { static let unknown = GPUControlOD8Held(rawValue: 8) /// A raised GFX minimum (kext 0.9.0). static let gfxMin = GPUControlOD8Held(rawValue: 16) + /// A lowered GFX voltage (kext 0.9.0). + static let volt = GPUControlOD8Held(rawValue: 32) + /// A GFX maximum above stock, with the overclock flag (kext 0.9.0). + static let gfxMaxUp = GPUControlOD8Held(rawValue: 64) } /// The 13 scalars `status` returns, in the kext's order (`StatusField`). @@ -362,45 +416,77 @@ struct GPUControlFanPoint: Equatable, Hashable, Sendable { } /// The whole OD8 state a program wants, never one setting: the kext takes -/// the fan curve, zero RPM and the GFX clock pair together in every call, -/// so a request that left one out would put that one back to stock. +/// the fan curve, zero RPM, the GFX clock pair and the GFX voltage together +/// in every call, so a request that left one out would put that one back to +/// stock. struct GPUControlOD8Want: Equatable, Hashable, Sendable { /// Five points, or nil for the stock fan. var curve: [GPUControlFanPoint]? /// True keeps the fan turning; false is the stock behaviour. var zeroRpmOff = false - /// A lower GFX maximum clock in MHz, or nil for stock. + /// A lower GFX maximum clock in MHz (or, with `overclock`, a higher + /// one), or nil for stock. var gfxMaxMHz: Int? /// A raised GFX minimum clock in MHz, or nil for stock (kext 0.9.0). var gfxMinMHz: Int? + /// A lowered GFX voltage in mV, or nil for stock (kext 0.9.0): the cap + /// the whole GFX voltage curve is offset down to. + var voltMV: Int? + /// The overclock flag (kext 0.9.0): `gfxMaxMHz` may be above stock, up + /// to the card's own maximum. A permission, not a setting: alone it is + /// still the stock state. + var overclock = false static let stock = GPUControlOD8Want() - /// The stock state is the way back, never a change (`od8IsStock`). - var isStock: Bool { curve == nil && !zeroRpmOff && gfxMaxMHz == nil && gfxMinMHz == nil } + /// The stock state is the way back, never a change (`od8IsStock`). The + /// overclock flag alone changes nothing. + var isStock: Bool { curve == nil && !zeroRpmOff && gfxMaxMHz == nil && gfxMinMHz == nil && voltMV == nil } - /// What `status` reports while this state is held (`od8HeldFlags`). + /// What `status` reports while this state is held (`od8HeldFlags`), + /// without the bit for a GFX maximum above stock (64): only the stock + /// maximum of the moment tells that (`heldFlags(stockGfxMaxMHz:)`). var heldFlags: GPUControlOD8Held { var held: GPUControlOD8Held = [] if curve != nil { held.insert(.curve) } if zeroRpmOff { held.insert(.zeroRpmOff) } if gfxMaxMHz != nil { held.insert(.gfxMax) } if gfxMinMHz != nil { held.insert(.gfxMin) } + if voltMV != nil { held.insert(.volt) } + return held + } + + /// The same with the bit for a GFX maximum above stock, as the kext + /// sets it (`od8RaisesGfxMax`: the overclock flag and a maximum above + /// the stock one). + func heldFlags(stockGfxMaxMHz: Int?) -> GPUControlOD8Held { + var held = heldFlags + if overclock, let mhz = gfxMaxMHz, let stock = stockGfxMaxMHz, mhz > stock { held.insert(.gfxMaxUp) } return held } + /// `status` shows this state: the same held bits, the bit for a raised + /// maximum only with the overclock flag (the kext sets it for nothing + /// else). + func matches(held: GPUControlOD8Held) -> Bool { + held.subtracting(.gfxMaxUp) == heldFlags && (overclock || !held.contains(.gfxMaxUp)) + } + /// The scalars of `setOD8` for this state, as `gpucontrol` builds them: - /// 13, or 14 with a GFX minimum (kext 0.9.0); without a curve its ten - /// entries are 0, and a stock clock is 0. Nil when the state cannot be - /// written as scalars at all (a curve that is not five points, a - /// negative number, a clock of 0 that would read as "stock"). Every - /// other value goes out unchanged: the kext decides, and the app never - /// clamps. + /// the shortest form that carries it: 15 with a GFX voltage, else 14 + /// with a GFX minimum (kext 0.9.0), else 13; without a curve its ten + /// entries are 0, and a stock clock or voltage is 0; the overclock flag + /// is 4 in the flags. Nil when the state cannot be written as scalars at + /// all (a curve that is not five points, a negative number, a clock or a + /// voltage of 0 that would read as "stock"). Every other value goes out + /// unchanged: the kext decides, and the app never clamps. func scalars() -> [UInt64]? { - let count = gfxMinMHz == nil ? GPUControlWire.setOD8InputCount : GPUControlWire.setOD8InputCountGfxMin + let count = voltMV != nil ? GPUControlWire.setOD8InputCountVolt + : gfxMinMHz != nil ? GPUControlWire.setOD8InputCountGfxMin : GPUControlWire.setOD8InputCount var input = [UInt64](repeating: 0, count: count) input[0] = GPUControlWire.channelVersion input[1] = (curve != nil ? GPUControlWire.wantCurve : 0) | (zeroRpmOff ? GPUControlWire.wantZeroRpmOff : 0) + | (overclock ? GPUControlWire.wantOverclock : 0) if let curve { guard curve.count == GPUControlWire.fanCurvePoints else { return nil } for (index, point) in curve.enumerated() { @@ -417,12 +503,16 @@ struct GPUControlOD8Want: Equatable, Hashable, Sendable { guard gfxMinMHz > 0 else { return nil } input[13] = UInt64(gfxMinMHz) } + if let voltMV { + guard voltMV > 0 else { return nil } + input[14] = UInt64(voltMV) + } return input } } /// The sentences the app shows for the kext's numbers. The kext answers with -/// 20 replies besides "ok", 11 OD8 refusals and 15 reasons that keep writing +/// 22 replies besides "ok", 13 OD8 refusals and 16 reasons that keep writing /// off; the app translates one sentence per group and puts the kext's own /// English text under it. A number this app does not know has no group and is /// shown as the kext wrote it. @@ -455,6 +545,9 @@ enum GPUControlTextGroup: CaseIterable, Sendable { case offDriverStopped /// Off: the fan watchdog put the stock fan back. case offWatchdog + /// Off: the watchdog put the start-up power limit back over a raised + /// one (kext 0.9.0). + case offPowerWatchdog /// `disarm` refused: something is still applied (kext 0.8.0). case stillApplied /// The card's minimum power limit is not known yet (kext 0.8.0). @@ -469,7 +562,8 @@ enum GPUControlTextGroup: CaseIterable, Sendable { switch reply { case .ok: return nil case .badVersion: return .otherVersion - case .badArgs, .belowFloor, .aboveBoot, .notAStep: return .notAllowed + case .badArgs, .belowFloor, .aboveBoot, .notAStep, .aboveCeiling: return .notAllowed + case .noReadings: return .settingMissing case .noFloor: return .noFloor case .stillApplied: return .stillApplied case .notPrivileged: return .needsAdministrator @@ -490,7 +584,7 @@ enum GPUControlTextGroup: CaseIterable, Sendable { case .ok: return nil case .notRead, .drifted, .memoryMoved: return .notReady case .noFeature, .noReadings: return .settingMissing - case .curveRange, .curveOrder, .curveFirst, .curveLast, .curveCooling, .gfxRange, .gfxMinRange: + case .curveRange, .curveOrder, .curveFirst, .curveLast, .curveCooling, .gfxRange, .gfxMinRange, .voltRange: return .notAllowed } } @@ -506,6 +600,7 @@ enum GPUControlTextGroup: CaseIterable, Sendable { case .teardown: return .offDriverStopped case .od8Watchdog: return .offWatchdog case .readOnlyCard: return .readOnlyCard + case .powerWatchdog: return .offPowerWatchdog } } } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlWriteProperties.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlWriteProperties.swift index c72ba462..3f3940ab 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlWriteProperties.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlWriteProperties.swift @@ -72,9 +72,17 @@ extension GPUControlStatus { /// `Takes`: what `setOD8` takes, in held bits (kext 0.9.0); nil /// from an older kext, which takes no GFX minimum. var takes: GPUControlOD8Held? = nil + /// `VoltHeld`: the GFX voltage held now in mV, nil at stock + /// (kext 0.9.0). + var voltHeld: Int? = nil /// The kext takes a GFX minimum (0.9.0 publishes `Takes`). var takesGfxMin: Bool { takes?.contains(.gfxMin) == true } + /// The kext takes a GFX voltage (`Takes` 32, kext 0.9.0). + var takesVolt: Bool { takes?.contains(.volt) == true } + /// The kext takes the overclock flag for a GFX maximum above + /// stock (`Takes` 64, kext 0.9.0), and with it `set`'s raise form. + var takesGfxMaxUp: Bool { takes?.contains(.gfxMaxUp) == true } } /// `OD8State`: whether the kext read OD8 since boot. @@ -139,6 +147,26 @@ extension GPUControlStatus { setting.min <= setting.max else { return nil } return (setting.min, setting.max, setting.stock) } + + /// The card's own top for the GFX maximum (`GfxMaxMHz.Max`, the + /// 0x9f maximum of id 0): what the kext takes with the overclock + /// flag. Nil unless the stock maximum is known. + var gfxMaxTopMHz: Int? { + guard stockGfxMaxMHz != nil, let setting = settings["GfxMaxMHz"] else { return nil } + return setting.max + } + + /// The GFX voltage entry (OD8 id 37, `GfxVoltOffset`, kext 0.9.0): + /// its range and stock value in mV. Nil unless the card offers it + /// (feature 0x20000), the driver allows it now (`NotAllowed` + /// without that bit) and the range holds the stock value: the + /// kext answers "no feature" otherwise. + var gfxVolt: (min: Int, max: Int, stock: Int)? { + guard let setting = settings["GfxVoltOffset"], setting.feature == GPUControlStatus.voltFeature, + (notAllowed ?? 0) & GPUControlStatus.voltFeature == 0, + setting.min <= setting.stock, setting.stock <= setting.max else { return nil } + return (setting.min, setting.max, setting.stock) + } } /// `Write`, as the kext wrote it. @@ -181,6 +209,9 @@ extension GPUControlStatus { } } + /// The GFX voltage's feature bit (`kOd8VoltFeature`). + static let voltFeature: UInt32 = 0x20000 + /// A signed 32-bit value: the kext's OD8 numbers are `int32_t` published /// as 32-bit numbers, so -6 can arrive as -6 or as 4294967290. Nil for /// anything that is not a whole number of 32 bits. @@ -275,7 +306,8 @@ extension GPUControlStatus.Writing.OD8State { fanCurveHeld: GPUControlStatus.fanCurvePacked(dict["FanCurveHeld"]), gfxMaxHeld: n("GfxMaxHeld").flatMap { $0 > 0 ? $0 : nil }, gfxMinHeld: n("GfxMinHeld").flatMap { $0 > 0 ? $0 : nil }, - takes: n("Takes").map { GPUControlOD8Held(rawValue: UInt64($0)) }) + takes: n("Takes").map { GPUControlOD8Held(rawValue: UInt64($0)) }, + voltHeld: n("VoltHeld").flatMap { $0 > 0 ? $0 : nil }) } } @@ -345,8 +377,13 @@ struct GPUControlPowerRange: Equatable, Sendable { var source: Source /// The lowest limit taken; nil while the kext does not know it. var floorW: Int? - /// The start-up limit, the highest taken; nil while the floor is not known. + /// The start-up limit, the highest taken without the raise flag; nil + /// while the floor is not known. var maxW: Int? + /// `CeilW` (kext 0.9.0): the highest limit `set`'s raise form takes, + /// equal to `maxW` when the card offers nothing higher. Nil from an + /// older kext and while the floor is not known. + var ceilW: Int? = nil var stepW: Int /// The card's OD8 power percent, once read. var percentMin: Int? @@ -366,7 +403,10 @@ struct GPUControlPowerRange: Equatable, Sendable { let step = GPUControlStatus.integer(dict["StepW"]).flatMap { $0 > 0 ? $0 : nil } ?? GPUControlWire.powerStepW var usable = false if known, let floor, let max { usable = floor > 0 && floor <= max } - return Self(source: .kext, floorW: usable ? floor : nil, maxW: usable ? max : nil, stepW: step, + // A ceiling below the start-up value is not one the kext publishes. + let ceil = GPUControlStatus.integer(dict["CeilW"]).flatMap { value in max.map { value >= $0 } == true ? value : nil } + return Self(source: .kext, floorW: usable ? floor : nil, maxW: usable ? max : nil, + ceilW: usable ? ceil : nil, stepW: step, percentMin: signed(dict["PercentMin"]), percentMax: signed(dict["PercentMax"])) } diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlClockSection.swift b/Sources/RyzenStatus/UI/Settings/GPUControlClockSection.swift index a765b948..9de9d7cc 100644 --- a/Sources/RyzenStatus/UI/Settings/GPUControlClockSection.swift +++ b/Sources/RyzenStatus/UI/Settings/GPUControlClockSection.swift @@ -32,8 +32,10 @@ struct GPUControlClockSection: View { _draft = State(initialValue: held ?? input.writing?.od8?.stockGfxMaxMHz ?? GPUControlWire.gfxFloorMHz) } + /// A lowered maximum the app holds; a raised one (the overclock flag, + /// GPUSensors 0.9.0) belongs to the Overclock section. private static func heldMHz(_ input: GPUControlPageInput) -> Int? { - if case .heldByApp(.od8(let want))? = input.state { return want.gfxMaxMHz } + if case .heldByApp(.od8(let want))? = input.state, !want.overclock { return want.gfxMaxMHz } return nil } @@ -241,6 +243,10 @@ enum GPUControlOD8Source: Equatable { case clock /// The GFX minimum (GPUSensors 0.9.0). case clockMin + /// The GFX voltage (GPUSensors 0.9.0). + case volt + /// The raised GFX maximum of the Overclock section (GPUSensors 0.9.0). + case overclock } /// A native slider with tick marks (SwiftUI's has none on macOS) that diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlOverclockSection.swift b/Sources/RyzenStatus/UI/Settings/GPUControlOverclockSection.swift new file mode 100644 index 00000000..501462c5 --- /dev/null +++ b/Sources/RyzenStatus/UI/Settings/GPUControlOverclockSection.swift @@ -0,0 +1,259 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 RyzenStatus + +import AppKit +import SwiftUI + +/// The Overclock section of Settings > GPU control (GPUSensors 0.9.0): a +/// switch, off by default, with a plain warning under it. When it is on, and +/// each only when the kext and the card offer it: a GFX maximum above stock +/// up to the card's own maximum (built like the clock sections: a slider, a +/// field and a stepper; sent with the overclock flag), and a power limit +/// above the start-up one up to the card's ceiling (a pop-up like the power +/// section's; sent with `set`'s raise form). Turning the switch off gives +/// back whatever it raised. No preset raises anything. Never on a card that +/// can only be read. +struct GPUControlOverclockSection: View { + let input: GPUControlPageInput + let strings: GPUControlPageStrings + let clock: GPUControlClockStrings + let overclock: GPUControlOverclockStrings + /// The section that asked last, so a refusal shows next to its control. + @Binding var lastOD8Source: GPUControlOD8Source + let setOn: (Bool) -> Void + let chooseGfx: (Int?) -> Void + let choosePower: (Int) -> Void + + @State private var draft: Int + @State private var fieldText = "" + @State private var outOfRange = false + + init(input: GPUControlPageInput, strings: GPUControlPageStrings, clock: GPUControlClockStrings, + overclock: GPUControlOverclockStrings, lastOD8Source: Binding, + setOn: @escaping (Bool) -> Void, chooseGfx: @escaping (Int?) -> Void, choosePower: @escaping (Int) -> Void) { + self.input = input + self.strings = strings + self.clock = clock + self.overclock = overclock + _lastOD8Source = lastOD8Source + self.setOn = setOn + self.chooseGfx = chooseGfx + self.choosePower = choosePower + _draft = State(initialValue: Self.heldMHz(input) ?? Self.gfxLimits(input)?.stock ?? 0) + } + + /// A raised GFX maximum the app holds (the overclock flag with it). + static func heldMHz(_ input: GPUControlPageInput) -> Int? { + if case .heldByApp(.od8(let want))? = input.state, want.overclock { return want.gfxMaxMHz } + return nil + } + + static func gfxLimits(_ input: GPUControlPageInput) -> GPUControlOverclockLogic.GfxLimits? { + GPUControlOverclockLogic.gfxLimits(writing: input.writing, od8Ready: input.facts?.od8Ready == true) + } + + /// The raised pop-up's values; empty when the card offers nothing above + /// the start-up limit or the kext takes no raise. + static func powerChoices(_ input: GPUControlPageInput) -> [Int] { + GPUControlOverclockLogic.powerChoices(bootW: input.facts?.bootW, + ceilW: GPUControlOverclockLogic.ceilingW(facts: input.facts), + stepW: input.facts?.powerRange?.stepW ?? GPUControlWire.powerStepW) + } + + /// The page shows this section when the kext and the card offer at + /// least one raise, and writing can open on the card. + static func shows(_ input: GPUControlPageInput) -> Bool { + if case .readOnlyCard? = input.state { return false } + return gfxLimits(input) != nil || !powerChoices(input).isEmpty + } + + private var takesChoices: Bool { input.canChoose && (input.state?.acceptsChoices ?? false) } + private var enabled: Bool { takesChoices && !input.isPending } + + var body: some View { + Section { + // "Toggles": the label says what turning it on does. Off by + // default; it can be turned off at any time. + Toggle(overclock.ocToggle, isOn: Binding(get: { input.overclock }, set: { setOn($0) })) + .toggleStyle(.switch) + .controlSize(.regular) + .disabled(!input.canChoose || (!input.overclock && !enabled)) + Text(overclock.ocWarning) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + if input.overclock { + if let limits = Self.gfxLimits(input) { + gfxRow(limits) + } + let choices = Self.powerChoices(input) + if !choices.isEmpty { powerRow(choices) } + } + if lastOD8Source == .overclock, case .switching(.od8)? = input.snapshot?.activity { + Label(clock.switching, systemImage: "clock") + .foregroundStyle(.secondary) + } + if let note = refusal { + VStack(alignment: .leading, spacing: 2) { + GPUControlProblemLabel(text: note.sentence, isProblem: true) + if let kext = note.kextText { + Text(String(format: strings.kextSaysFormat, kext)) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + } + } header: { + Text(overclock.ocSection) + } footer: { + Text(overclock.ocFooter) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .onChange(of: draft) { _, value in fieldText = "\(value)" } + .onChange(of: Self.heldMHz(input)) { _, held in + guard !input.isPending else { return } + draft = held ?? Self.gfxLimits(input)?.stock ?? draft + } + .onAppear { fieldText = "\(draft)" } + } + + /// A refusal of the raised GFX maximum (an OD8 request this section + /// sent), or of a raised power limit. + private var refusal: GPUControlPageNote? { + guard case .refused(let request, _)? = input.snapshot?.outcome else { return nil } + if request.isOD8 { + guard lastOD8Source == .overclock else { return nil } + } else if case .power(let watts) = request { + guard GPUControlOverclockLogic.raisesPower(Int(watts), bootW: input.facts?.bootW) else { return nil } + } else { + return nil + } + return GPUControlPageNote.make(input.snapshot, strings) + } + + // MARK: The GFX maximum above stock + + /// VoiceOver's names for the row's three controls, each its own. + static func accessibilityNames(_ overclock: GPUControlOverclockStrings) + -> (slider: String, field: String, stepper: String) { + (overclock.ocGfxLabel, overclock.ocGfxFieldLabel, + String(format: overclock.ocGfxStepperFormat, GPUControlOverclockLogic.step)) + } + + private func gfxRow(_ limits: GPUControlOverclockLogic.GfxLimits) -> some View { + let range = GPUControlOverclockLogic.gfxRange(limits) + let names = Self.accessibilityNames(overclock) + let reason = GPUControlPageContent.disabledReason(input, strings) + let slider = GPUControlTickSlider(value: draft, range: range, + ticks: GPUControlOverclockLogic.tickCount(range: range), + label: names.slider, + help: Self.sliderHelp(overclock, limits: limits), + valueDescription: GPUControlPageContent.accessibilityValue( + "\(draft) MHz", reason: takesChoices ? nil : reason, strings), + onChange: { draft = GPUControlOverclockLogic.snapped($0, range: range) }, + onRelease: { send(draft, limits: limits) }) + let entry = HStack(spacing: 8) { + TextField(names.field, text: $fieldText) + .labelsHidden() + .multilineTextAlignment(.trailing) + .frame(minWidth: 56) + .fixedSize(horizontal: true, vertical: false) + .onSubmit { commitField(limits: limits) } + .accessibilityLabel(names.field) + Stepper(names.stepper, value: Binding(get: { draft }, set: { value in + draft = Swift.min(Swift.max(value, range.lowerBound), range.upperBound) + send(draft, limits: limits) + }), in: range, step: GPUControlOverclockLogic.step) + .labelsHidden() + .accessibilityLabel(names.stepper) + .accessibilityValue(GPUControlPageContent.accessibilityValue( + "\(draft) MHz", reason: enabled ? nil : reason, strings)) + Text("MHz").foregroundStyle(.secondary) + } + .disabled(!enabled) + return VStack(alignment: .leading, spacing: 4) { + Text(overclock.ocGfxLabel) + ViewThatFits(in: .horizontal) { + HStack(spacing: 8) { + slider.frame(minWidth: GPUControlClockSection.sliderMinWidth).disabled(!takesChoices) + entry + } + VStack(alignment: .trailing, spacing: 4) { + slider.disabled(!takesChoices) + entry + } + } + // Stock at the leading end, where the slider starts. + HStack { + Text(String(format: clock.stockFormat, limits.stock)) + Spacer() + Text(String(format: overclock.ocGfxTopFormat, limits.max)) + } + .font(.caption) + .foregroundStyle(.secondary) + if outOfRange { + GPUControlProblemLabel(text: String(format: clock.outOfRangeFormat, range.lowerBound, range.upperBound), + isProblem: true) + } + } + } + + /// The slider's help: its two ends, as written under it, and what + /// moving it does. + static func sliderHelp(_ overclock: GPUControlOverclockStrings, + limits: GPUControlOverclockLogic.GfxLimits) -> String { + String(format: overclock.ocGfxSliderHelpFormat, limits.stock, limits.max) + } + + private func commitField(limits: GPUControlOverclockLogic.GfxLimits) { + // Outside the range: not sent and not clamped; the row says what it + // takes. + guard let value = Int(fieldText.trimmingCharacters(in: .whitespaces)), + GPUControlOverclockLogic.gfxRange(limits).contains(value) else { + outOfRange = true + return + } + draft = value + send(value, limits: limits) + } + + private func send(_ value: Int, limits: GPUControlOverclockLogic.GfxLimits) { + outOfRange = false + lastOD8Source = .overclock + chooseGfx(GPUControlOverclockLogic.request(value, stockMHz: limits.stock)) + } + + // MARK: The power limit above the start-up one + + /// "Pop-up buttons", as the power section: applies when chosen. The + /// start-up value is the way back. + private func powerRow(_ choices: [Int]) -> some View { + let shown = Self.shownWatts(input, choices: choices) + return Picker(overclock.ocPowerLabel, selection: Binding(get: { shown }, set: { choosePower($0) })) { + ForEach(choices, id: \.self) { watts in + Text(watts == choices.first ? String(format: strings.bootFormat, watts) + : String(format: strings.wattsFormat, watts)) + .tag(watts) + } + } + .pickerStyle(.menu) + .disabled(!enabled) + .accessibilityHint(overclock.ocPowerHint) + .accessibilityValue(GPUControlPageContent.accessibilityValue( + shown == choices.first ? String(format: strings.bootFormat, shown) : String(format: strings.wattsFormat, shown), + reason: enabled ? nil : GPUControlPageContent.disabledReason(input, strings), strings)) + } + + /// The pop-up's value: a raised limit asked for or held, else the + /// start-up value (a lower limit belongs to the power section). + static func shownWatts(_ input: GPUControlPageInput, choices: [Int]) -> Int { + let boot = choices.first ?? 0 + guard let facts = input.facts, + let watts = GPUControlPageLogic.shownWatts(facts: facts, snapshot: input.snapshot), + choices.contains(watts) else { return boot } + return watts + } +} diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift b/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift index c48155fb..684c4ee5 100644 --- a/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift +++ b/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift @@ -20,6 +20,7 @@ struct GPUControlSettingsView: View { fan: FeatureStrings.gpuControlFan(l10n.language), clock: FeatureStrings.gpuControlClock(l10n.language), boot: FeatureStrings.gpuControlBoot(l10n.language), + overclock: FeatureStrings.gpuControlOverclock(l10n.language), title: FeatureStrings.gpuControl(l10n.language).title, actions: GPUControlPageActions( choosePower: { service.choosePower($0) }, @@ -33,6 +34,9 @@ struct GPUControlSettingsView: View { applyFan: { service.applyFan($0) }, chooseGfxMax: { service.chooseGfxMax($0) }, chooseGfxMin: { service.chooseGfxMin($0) }, + chooseVolt: { service.chooseVolt($0) }, + chooseGfxMaxRaised: { service.chooseGfxMaxRaised($0) }, + setOverclock: { service.overclock = $0 }, closeChanges: { service.closeChanges() })) // Reads once a second only while the page is on screen. .settingsPageActivity(.gpuControl, @@ -66,6 +70,8 @@ struct GPUControlPageInput: Equatable { /// The editor's starting draft; nil starts from what is held, or from /// the tested curve. var fanDraft: GPUControlFanDraft? + /// "Allow overclocking" (GPUSensors 0.9.0), off by default. + var overclock = false init(facts: GPUControlFacts?, state: GPUControlPageState?, snapshot: GPUControlSnapshot?) { self.facts = facts @@ -88,6 +94,7 @@ struct GPUControlPageInput: Equatable { kextVersion = service.control?.writing?.kextVersion canChoose = service.mode != .none writing = service.control?.writing + overclock = service.overclock } } @@ -100,6 +107,9 @@ struct GPUControlPageActions { var applyFan: (GPUControlFanDraft) -> Void = { _ in } var chooseGfxMax: (Int?) -> Void = { _ in } var chooseGfxMin: (Int?) -> Void = { _ in } + var chooseVolt: (Int?) -> Void = { _ in } + var chooseGfxMaxRaised: (Int?) -> Void = { _ in } + var setOverclock: (Bool) -> Void = { _ in } var closeChanges: () -> Void = {} } @@ -202,6 +212,7 @@ struct GPUControlPageContent: View { let fan: GPUControlFanStrings let clock: GPUControlClockStrings let boot: GPUControlBootStrings + let overclock: GPUControlOverclockStrings let title: String let actions: GPUControlPageActions @State private var copied = false @@ -211,13 +222,15 @@ struct GPUControlPageContent: View { @State private var lastOD8Source: GPUControlOD8Source = .fan init(input: GPUControlPageInput, strings: GPUControlPageStrings, fan: GPUControlFanStrings, - clock: GPUControlClockStrings, boot: GPUControlBootStrings = .enUS, title: String, + clock: GPUControlClockStrings, boot: GPUControlBootStrings = .enUS, + overclock: GPUControlOverclockStrings = .enUS, title: String, actions: GPUControlPageActions) { self.input = input self.strings = strings self.fan = fan self.clock = clock self.boot = boot + self.overclock = overclock self.title = title self.actions = actions var held: GPUControlOD8Want? @@ -250,6 +263,18 @@ struct GPUControlPageContent: View { GPUControlClockMinSection(input: input, strings: strings, clock: clock, lastOD8Source: $lastOD8Source, choose: actions.chooseGfxMin) } + // GPUSensors 0.9.0: the voltage next to the clocks, then the + // raises on their own, off by default. Neither on a card that can + // only be read. + if showsPower, GPUControlVoltSection.shows(input) { + GPUControlVoltSection(input: input, strings: strings, clock: clock, overclock: overclock, + lastOD8Source: $lastOD8Source, choose: actions.chooseVolt) + } + if showsPower, GPUControlOverclockSection.shows(input) { + GPUControlOverclockSection(input: input, strings: strings, clock: clock, overclock: overclock, + lastOD8Source: $lastOD8Source, setOn: actions.setOverclock, + chooseGfx: actions.chooseGfxMaxRaised, choosePower: actions.choosePower) + } if case .closed? = input.state { armSection } if Self.showsBootArm(input) { bootArmSection } rememberSection @@ -463,9 +488,13 @@ struct GPUControlPageContent: View { /// offer choices instead of typing. Applies when chosen, like AMD Power /// and System Settings ("Sliders", macOS: show the result as it changes). private var powerSection: some View { - let choices = GPUControlPageLogic.powerChoices(facts: input.facts, state: input.state) + let lowerChoices = GPUControlPageLogic.powerChoices(facts: input.facts, state: input.state) let limits = GPUControlPageLogic.limits(bootW: input.facts?.bootW, range: input.facts?.powerRange) let shown = input.facts.flatMap { GPUControlPageLogic.shownWatts(facts: $0, snapshot: input.snapshot) } + // A raised limit (held from the Overclock section) is not one of the + // lower choices: listed so the menu shows what is in force. + let choices = shown.map { lowerChoices.isEmpty || lowerChoices.contains($0) ? lowerChoices : lowerChoices + [$0] } + ?? lowerChoices // While a request is out or waits, the kext has not taken it: no // second choice until it answers. let enabled = input.canChoose && (input.state?.acceptsChoices ?? false) && !input.isPending @@ -476,6 +505,10 @@ struct GPUControlPageContent: View { // A refusal of a fan request shows in the fan section instead. var note = GPUControlPageNote.make(input.snapshot, s) if case .refused(let request, _)? = input.snapshot?.outcome, request.isOD8 { note = nil } + // A refused raise shows in the overclock section instead. + if case .refused(.power(let watts), _)? = input.snapshot?.outcome, + GPUControlOverclockSection.shows(input), + GPUControlOverclockLogic.raisesPower(Int(watts), bootW: input.facts?.bootW) { note = nil } return Section { Picker(s.powerLabel, selection: Binding( get: { shown ?? choices.first ?? 0 }, diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlVoltSection.swift b/Sources/RyzenStatus/UI/Settings/GPUControlVoltSection.swift new file mode 100644 index 00000000..8af4626a --- /dev/null +++ b/Sources/RyzenStatus/UI/Settings/GPUControlVoltSection.swift @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 RyzenStatus + +import AppKit +import SwiftUI + +/// The GFX voltage section of Settings > GPU control (GPUSensors 0.9.0), +/// built like the clock sections (`GPUControlClockMinSection`): a switch, +/// then a slider from the card's lowest 25 mV step up to stock with a field +/// and a stepper. Only ever lower than stock. Under it, the recommended +/// starting point (one step below stock, from the card's own table) with a +/// button that puts it into the control and never sends it, and the button +/// that sends what the control shows. The page shows it only when the kext +/// takes a voltage and the card offers one, and never on a card that can +/// only be read. +struct GPUControlVoltSection: View { + let input: GPUControlPageInput + let strings: GPUControlPageStrings + let clock: GPUControlClockStrings + let overclock: GPUControlOverclockStrings + /// The section that asked last, so a refusal shows next to its control. + @Binding var lastOD8Source: GPUControlOD8Source + let choose: (Int?) -> Void + + @State private var on: Bool + @State private var draft: Int + @State private var fieldText = "" + @State private var outOfRange = false + + init(input: GPUControlPageInput, strings: GPUControlPageStrings, clock: GPUControlClockStrings, + overclock: GPUControlOverclockStrings, lastOD8Source: Binding, + choose: @escaping (Int?) -> Void) { + self.input = input + self.strings = strings + self.clock = clock + self.overclock = overclock + _lastOD8Source = lastOD8Source + self.choose = choose + let held = Self.heldMV(input) + _on = State(initialValue: held != nil) + _draft = State(initialValue: held ?? Self.limits(input)?.stock ?? 0) + } + + private static func heldMV(_ input: GPUControlPageInput) -> Int? { + if case .heldByApp(.od8(let want))? = input.state { return want.voltMV } + return nil + } + + private static func limits(_ input: GPUControlPageInput) -> GPUControlVoltLogic.Limits? { + GPUControlVoltLogic.limits(writing: input.writing, od8Ready: input.facts?.od8Ready == true) + } + + /// The page shows this section only when the kext takes a voltage, the + /// card offers one below stock, and writing can open on the card. + static func shows(_ input: GPUControlPageInput) -> Bool { + if case .readOnlyCard? = input.state { return false } + return limits(input) != nil + } + + /// The starting point the section offers, nil when there is none. + static func recommendedMV(_ input: GPUControlPageInput) -> Int? { + GPUControlVoltLogic.recommended(limits(input)) + } + + private var range: ClosedRange? { GPUControlVoltLogic.range(Self.limits(input)) } + private var stock: Int? { Self.limits(input)?.stock } + + private var enabled: Bool { usable && !input.isPending } + + /// As the clock sections: the slider stays usable while its own request + /// waits (a11y A3). + private var usable: Bool { + range != nil && input.canChoose && (input.state?.acceptsChoices ?? false) + } + + /// The value in force: the one held, else stock. + private var inForce: Int? { Self.heldMV(input) ?? stock } + + var body: some View { + Section { + Toggle(overclock.voltToggle, isOn: Binding(get: { on }, set: { switched($0) })) + .toggleStyle(.switch) + .controlSize(.regular) + .disabled(!enabled) + if on, let range, let stock { + voltRow(range: range, stock: stock) + } + if let recommended = Self.recommendedMV(input) { + HStack(alignment: .firstTextBaseline) { + Text(String(format: overclock.voltRecommendedFormat, recommended)) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + Spacer() + // Puts the starting point into the control; nothing is + // sent until Apply. + Button(overclock.voltUseRecommended) { useRecommended(recommended) } + .disabled(!enabled) + } + } + if on, let stock { + HStack { + Spacer() + Button(overclock.voltApply) { send(draft, stock: stock) } + .disabled(!enabled || draft == inForce) + } + } + if case .heldByApp(.power)? = input.state { + Label(clock.notePowerHeld, systemImage: "info.circle") + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + if lastOD8Source == .volt, case .switching(.od8)? = input.snapshot?.activity { + Label(clock.switching, systemImage: "clock") + .foregroundStyle(.secondary) + } + if outOfRange, let range { + GPUControlProblemLabel(text: String(format: overclock.voltOutOfRangeFormat, range.lowerBound, + range.upperBound, GPUControlVoltLogic.step), + isProblem: true) + } + if let note = refusal { + VStack(alignment: .leading, spacing: 2) { + GPUControlProblemLabel(text: note.sentence, isProblem: true) + if let kext = note.kextText { + Text(String(format: strings.kextSaysFormat, kext)) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + } + } header: { + Text(overclock.voltSection) + } footer: { + Text(overclock.voltFooter) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .onChange(of: draft) { _, value in fieldText = "\(value)" } + // What is held changed on its own: the switch and the value follow + // it, unless a request still waits. + .onChange(of: Self.heldMV(input)) { _, held in + guard !input.isPending else { return } + on = held != nil + draft = held ?? stock ?? draft + } + .onAppear { fieldText = "\(draft)" } + } + + private var refusal: GPUControlPageNote? { + guard lastOD8Source == .volt, case .refused(let request, _)? = input.snapshot?.outcome, + request.isOD8 else { return nil } + return GPUControlPageNote.make(input.snapshot, strings) + } + + // MARK: The row + + /// VoiceOver's names for the row's three controls, each its own. + static func accessibilityNames(_ overclock: GPUControlOverclockStrings) + -> (slider: String, field: String, stepper: String) { + (overclock.voltSection, overclock.voltFieldLabel, + String(format: overclock.voltStepperFormat, GPUControlVoltLogic.step)) + } + + private func voltRow(range: ClosedRange, stock: Int) -> some View { + let names = Self.accessibilityNames(overclock) + let reason = GPUControlPageContent.disabledReason(input, strings) + let slider = GPUControlTickSlider(value: draft, range: range, + ticks: GPUControlVoltLogic.tickCount(range: range), + label: names.slider, + help: Self.sliderHelp(overclock, range: range), + valueDescription: GPUControlPageContent.accessibilityValue( + "\(draft) mV", reason: usable ? nil : reason, strings), + onChange: { draft = GPUControlVoltLogic.snapped($0, range: range) }, + onRelease: { send(draft, stock: stock) }) + let entry = HStack(spacing: 8) { + TextField(names.field, text: $fieldText) + .labelsHidden() + .multilineTextAlignment(.trailing) + .frame(minWidth: 56) + .fixedSize(horizontal: true, vertical: false) + .onSubmit { commitField(stock: stock) } + .accessibilityLabel(names.field) + Stepper(names.stepper, value: Binding(get: { draft }, set: { value in + draft = Swift.min(Swift.max(value, range.lowerBound), range.upperBound) + send(draft, stock: stock) + }), in: range, step: GPUControlVoltLogic.step) + .labelsHidden() + .accessibilityLabel(names.stepper) + .accessibilityValue(GPUControlPageContent.accessibilityValue( + "\(draft) mV", reason: enabled ? nil : reason, strings)) + Text("mV").foregroundStyle(.secondary) + } + .disabled(!enabled) + return VStack(alignment: .leading, spacing: 4) { + ViewThatFits(in: .horizontal) { + HStack(spacing: 8) { + slider.frame(minWidth: GPUControlClockSection.sliderMinWidth).disabled(!usable) + entry + } + VStack(alignment: .trailing, spacing: 4) { + slider.disabled(!usable) + entry + } + } + // Stock at the trailing end, where the slider starts from, as + // the maximum clock's. + HStack { + Text(verbatim: "\(range.lowerBound) mV") + Spacer() + Text(String(format: overclock.voltStockFormat, stock)) + } + .font(.caption) + .foregroundStyle(.secondary) + } + } + + /// The slider's help: its two ends, as written under it, and what + /// moving it does. + static func sliderHelp(_ overclock: GPUControlOverclockStrings, range: ClosedRange) -> String { + String(format: overclock.voltSliderHelpFormat, range.lowerBound, range.upperBound) + } + + // MARK: Sending + + private func switched(_ value: Bool) { + on = value + outOfRange = false + // Turning it on shows the control and sends nothing: the stock + // voltage is not a hold. Turning it off puts the stock voltage back, + // keeping the rest of a held OD8 state in the same request. + if !value { + lastOD8Source = .volt + choose(nil) + if let stock { draft = stock } + } + } + + /// The starting point goes into the control only: the owner sends it + /// with Apply, the slider or the field. + private func useRecommended(_ mv: Int) { + outOfRange = false + on = true + draft = mv + fieldText = "\(mv)" + } + + private func commitField(stock: Int) { + // Outside the range or off a step: not sent and not clamped; the + // field says what it takes. + guard let value = Int(fieldText.trimmingCharacters(in: .whitespaces)), + value == stock || GPUControlVoltLogic.lowers(value, limits: Self.limits(input)) else { + outOfRange = true + return + } + draft = value + send(value, stock: stock) + } + + private func send(_ value: Int, stock: Int) { + outOfRange = false + lastOD8Source = .volt + choose(GPUControlVoltLogic.request(value, stockMV: stock)) + } +} diff --git a/Tests/Fixtures/GPUSensors/README.md b/Tests/Fixtures/GPUSensors/README.md index ae18b614..bf9208a0 100644 --- a/Tests/Fixtures/GPUSensors/README.md +++ b/Tests/Fixtures/GPUSensors/README.md @@ -15,29 +15,37 @@ arrive signed (`PowerPercent.Min` = -6, `NotAllowed` = -212750), not as the ## curve-cases.jsonl -100 OD8 states and what the kext's own `gpuctl::od8CheckWant` answers for -each, from GPUSensors.kext's `control_logic.hpp` at GPUSensors 0.7.2 -(`GPU/sensors/kext/control_logic.hpp` in this repository holds the kext's -source). The app's copy of the rules (`GPUControlCurveRules.swift`) must give -the same answer for every line (`GPUControlFanTests`). +149 OD8 states and what the kext's own `gpuctl::od8CheckWant` answers for +each, from GPUSensors.kext's `control_logic.hpp` (`GPU/sensors/kext/control_logic.hpp` +in this repository holds the kext's source; the generator is +`GPU/sensors/tests/curve_fixturegen.cpp`). The app's copy of the rules +(`GPUControlCurveRules.swift`) must give the same answer for every line +(`GPUControlFanTests`). Lines 1 to 100 come from GPUSensors 0.7.2, lines 101 +to 120 are 0.9.0's GFX minimum cases and lines 121 to 149 its GFX voltage and +overclock cases; each later group left the lines before it byte for byte as +they were. Each line is `{"want": {...}, "muts": [...], "check": N}`: -- `want`: `curve`, `temp[5]`, `speed[5]`, `zeroRpmOff`, `gfx` (0 = stock). +- `want`: `curve`, `temp[5]`, `speed[5]`, `zeroRpmOff`, `gfx` (0 = stock), + and since 0.9.0, each written only when it is not stock: `gfxMin` (MHz), + `volt` (the GFX voltage in mV) and `overclock: true` (the overclock flag, + which lets `gfx` go above stock up to the card's own maximum). - `muts`: changes to the card's real state before the check, by entry id (`od8Name` order): `freshCaps` / `firstCaps` (value), `freshEntry` / `firstEntry` / `bothEntry` (id, field `feature`/`min`/`max`/`def`, value), - `cur` (id, value). They reach the codes the real table alone cannot: - Drifted, MemoryMoved and NoFeature. -- `check`: the `Od8Check` number (33 Ok, 14 Drifted, 5 MemoryMoved, - 12 NoFeature, 9 CurveRange, 4 CurveOrder, 3 CurveFirst, 6 CurveLast, - 6 CurveCooling, 8 GfxRange). NotRead and NoReadings never come from - `od8CheckWant`. + `cur` (id, value), and since 0.9.0 `notAllowed` (value: the current read's + NotAllowed mask, as 32 bits). They reach the codes the real table alone + cannot: Drifted, MemoryMoved and NoFeature. +- `check`: the `Od8Check` number (55 Ok, 15 Drifted, 5 MemoryMoved, + 15 NoFeature, 9 CurveRange, 4 CurveOrder, 3 CurveFirst, 6 CurveLast, + 6 CurveCooling, 14 GfxRange, 10 GfxMinRange, 7 VoltRange). NotRead and + NoReadings never come from `od8CheckWant`. The base state is the card's real OD8 table as `gpucontrol check` maps it (Stock = first read, Default = fresh read, Current = current values, -Caps 212749); the same values as `ioreg-0.7.2-2026-11-20.plist`, which the -test builds the state from. +Caps 212749, NotAllowed 0xfffcc0f2); the same values as +`ioreg-0.7.2-2026-11-20.plist`, which the test builds the state from. To regenerate after a kext change, from the root of this repository: diff --git a/Tests/Fixtures/GPUSensors/curve-cases.jsonl b/Tests/Fixtures/GPUSensors/curve-cases.jsonl index b8d5e09f..9ee96107 100644 --- a/Tests/Fixtures/GPUSensors/curve-cases.jsonl +++ b/Tests/Fixtures/GPUSensors/curve-cases.jsonl @@ -118,3 +118,32 @@ {"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":550},"muts":[{"kind":"bothEntry","id":1,"field":"min","value":600}],"check":12} {"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":550},"muts":[{"kind":"bothEntry","id":1,"field":"max","value":540}],"check":12} {"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"gfxMin":550},"muts":[{"kind":"bothEntry","id":1,"field":"feature","value":8}],"check":4} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1075},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1050},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1025},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1000},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":900},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1076},"muts":[],"check":13} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1100},"muts":[],"check":13} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":880},"muts":[],"check":13} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":875},"muts":[],"check":13} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1060},"muts":[],"check":13} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1049},"muts":[],"check":13} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1050},"muts":[{"kind":"bothEntry","id":37,"field":"feature","value":0}],"check":4} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1050},"muts":[{"kind":"notAllowed","value":4294885618}],"check":4} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1050},"muts":[{"kind":"bothEntry","id":37,"field":"def","value":1100},{"kind":"bothEntry","id":37,"field":"max","value":1150}],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1125},"muts":[{"kind":"bothEntry","id":37,"field":"def","value":1100},{"kind":"bothEntry","id":37,"field":"max","value":1150}],"check":13} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"volt":1050},"muts":[{"kind":"freshEntry","id":37,"field":"def","value":1050}],"check":2} +{"want":{"curve":true,"temp":[30,40,44,46,48],"speed":[20,36,52,68,100],"zeroRpmOff":true,"gfx":2300,"gfxMin":1800,"volt":1050},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":0,"overclock":true},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2359,"overclock":true},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2360,"overclock":true},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2500,"overclock":true},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2800,"overclock":true},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2801,"overclock":true},"muts":[],"check":10} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2825,"overclock":true},"muts":[],"check":10} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":1400,"overclock":true},"muts":[],"check":10} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2600,"gfxMin":2600,"overclock":true},"muts":[],"check":0} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2600,"gfxMin":2601,"overclock":true},"muts":[],"check":12} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2700,"overclock":true},"muts":[{"kind":"bothEntry","id":0,"field":"max","value":2600}],"check":10} +{"want":{"curve":false,"temp":[0,0,0,0,0],"speed":[0,0,0,0,0],"zeroRpmOff":false,"gfx":2500},"muts":[],"check":10} diff --git a/Tests/MetricsTests.swift b/Tests/MetricsTests.swift index ea122ef6..f9d99ab8 100644 --- a/Tests/MetricsTests.swift +++ b/Tests/MetricsTests.swift @@ -14477,6 +14477,7 @@ struct MetricsTests { ("SudoersInstallTests", SudoersInstallTests.run), ("GPUControlFanTests", GPUControlFanTests.run), ("GPUControlClockTests", GPUControlClockTests.run), + ("GPUControlOverclockTests", GPUControlOverclockTests.run), ("GPUControlA11yTests", GPUControlA11yTests.run), ("GPUFolderTests", GPUFolderTests.run), ("GPUInstallerDMGTests", GPUInstallerDMGTests.run), diff --git a/Tests/Suites/GPUControlChannelTests.swift b/Tests/Suites/GPUControlChannelTests.swift index 7de57728..4b68e9d1 100644 --- a/Tests/Suites/GPUControlChannelTests.swift +++ b/Tests/Suites/GPUControlChannelTests.swift @@ -546,6 +546,15 @@ enum GPUControlChannelTests { // 0.8.0's two replies. do { let (_, c) = fresh { $0.od8Ready = false }; got(c.setPower(watts: 230), .noFloor, "the card's floor not known") } do { let (_, c) = fresh(); _ = c.setPower(watts: 230); got(c.disarm(), .stillApplied, "close while a change is held") } + // 0.9.0's two replies, for set's raise form. + do { + let (_, c) = fresh { $0.takesOverclock = true } + got(c.setPower(watts: 290, raise: true), .aboveCeiling, "290 W, above the card's ceiling") + } + do { + let (_, c) = fresh { $0.takesOverclock = true; $0.dogSees = false } + got(c.setPower(watts: 250, raise: true), .noReadings, "a raise the watchdog cannot watch") + } suite.expect(seen == Set(GPUControlReply.allCases.map(\.rawValue)), "the model gives every reply of the kext") // Every reason writing goes off, with the off-back for OD8. @@ -1278,8 +1287,9 @@ enum GPUControlChannelTests { .tooSoon: .busy, .belowFloor: .notAllowed, .aboveBoot: .notAllowed, .notAStep: .notAllowed, .timeout: .unconfirmed, .failed: .unconfirmed, .notOwner: .notOwner, .cancelled: .notReady, .od8Refused: .notAllowed, .noFloor: .noFloor, .stillApplied: .stillApplied, + .aboveCeiling: .notAllowed, .noReadings: .settingMissing, ] - suite.expect(replies.count == 20, "20 replies besides ok") + suite.expect(replies.count == 22, "22 replies besides ok") for reply in GPUControlReply.allCases { suite.expect(G.forReply(reply.rawValue) == replies[reply], "reply \(reply.rawValue) \(reply): its group") suite.expect(!reply.kextText.isEmpty, "reply \(reply): the kext's words") @@ -1289,9 +1299,9 @@ enum GPUControlChannelTests { .notRead: .notReady, .drifted: .notReady, .memoryMoved: .notReady, .noFeature: .settingMissing, .curveRange: .notAllowed, .curveOrder: .notAllowed, .curveFirst: .notAllowed, .curveLast: .notAllowed, .curveCooling: .notAllowed, .gfxRange: .notAllowed, .noReadings: .settingMissing, - .gfxMinRange: .notAllowed, + .gfxMinRange: .notAllowed, .voltRange: .notAllowed, ] - suite.expect(checks.count == 12, "12 OD8 reasons besides ok") + suite.expect(checks.count == 13, "13 OD8 reasons besides ok") for check in GPUControlOD8Check.allCases { suite.expect(G.forOD8Check(check.rawValue) == checks[check], "OD8 check \(check.rawValue) \(check): its group") if check != .ok { @@ -1299,8 +1309,8 @@ enum GPUControlChannelTests { "OD8 refused for \(check): the reason's group") } } - suite.expect(G.forOD8Check(13) == nil, "an unknown OD8 reason has no group") - suite.expect(G.forReply(GPUControlReply.od8Refused.rawValue, check: 13) == .notAllowed, + suite.expect(G.forOD8Check(14) == nil, "an unknown OD8 reason has no group") + suite.expect(G.forReply(GPUControlReply.od8Refused.rawValue, check: 14) == .notAllowed, "refused for an unknown reason: not allowed") let offs: [GPUControlWriteOff: G] = [ .ctlOff: .offNotAsExpected, .notOneCard: .offNotAsExpected, .otherAmdGpu: .offNotAsExpected, @@ -1308,15 +1318,17 @@ enum GPUControlChannelTests { .secondObject: .offNotAsExpected, .bootImplausible: .offNotAsExpected, .start: .offNotAsExpected, .sendFailed: .offChangeUnconfirmed, .revertFailed: .offChangeUnconfirmed, .teardown: .offDriverStopped, .od8Failed: .offChangeUnconfirmed, .od8Watchdog: .offWatchdog, .readOnlyCard: .readOnlyCard, + .powerWatchdog: .offPowerWatchdog, ] - suite.expect(offs.count == 15, "15 write-off reasons") + suite.expect(offs.count == 16, "16 write-off reasons") for reason in GPUControlWriteOff.allCases { suite.expect(G.forWriteOff(reason.rawValue) == offs[reason], "write off \(reason.rawValue) \(reason): its group") suite.expect(reason == .none || !reason.kextText.isEmpty, "write off \(reason): the kext's words") } - suite.expect(G.forWriteOff(16) == nil, "an unknown write-off reason has no group") + suite.expect(G.forWriteOff(17) == nil, "an unknown write-off reason has no group") let answer = GPUControlAnswer(replyCode: GPUControlReply.od8Refused.rawValue, checkCode: 10) - suite.expect(answer.kextText == "GFX max must be between 1500 MHz and the stock maximum", + suite.expect(answer.kextText + == "GFX max must be between 1500 MHz and the stock maximum (with overclock: the card's own maximum)", "a refused OD8 state shows the reason in the kext's words") suite.expect(GPUControlAnswer(replyCode: 77).kextText == "reply 77", "an unknown reply shows its number") } @@ -1338,33 +1350,44 @@ enum GPUControlChannelTests { (.ok, 0), (.badVersion, 1), (.badArgs, 2), (.notPrivileged, 3), (.off, 4), (.notArmed, 5), (.noBootValue, 6), (.notReady, 7), (.sleeping, 8), (.busy, 9), (.tooSoon, 10), (.belowFloor, 11), (.aboveBoot, 12), (.notAStep, 13), (.timeout, 14), (.failed, 15), (.notOwner, 16), (.cancelled, 17), - (.od8Refused, 18), (.stillApplied, 19), (.noFloor, 20), + (.od8Refused, 18), (.stillApplied, 19), (.noFloor, 20), (.aboveCeiling, 21), (.noReadings, 22), ] - suite.expect(replies.allSatisfy { $0.0.rawValue == $0.1 } && GPUControlReply.allCases.count == 21, - "replies: ok 0 ... noFloor 20, as gpuctl::Reply") + suite.expect(replies.allSatisfy { $0.0.rawValue == $0.1 } && GPUControlReply.allCases.count == 23, + "replies: ok 0 ... noReadings 22, as gpuctl::Reply") let checks: [(GPUControlOD8Check, UInt64)] = [ (.ok, 0), (.notRead, 1), (.drifted, 2), (.memoryMoved, 3), (.noFeature, 4), (.curveRange, 5), (.curveOrder, 6), (.curveFirst, 7), (.curveLast, 8), (.curveCooling, 9), (.gfxRange, 10), - (.noReadings, 11), (.gfxMinRange, 12), + (.noReadings, 11), (.gfxMinRange, 12), (.voltRange, 13), ] - suite.expect(checks.allSatisfy { $0.0.rawValue == $0.1 } && GPUControlOD8Check.allCases.count == 13, - "OD8 checks: ok 0 ... gfxMinRange 12, as gpuctl::Od8Check") + suite.expect(checks.allSatisfy { $0.0.rawValue == $0.1 } && GPUControlOD8Check.allCases.count == 14, + "OD8 checks: ok 0 ... voltRange 13, as gpuctl::Od8Check") suite.expect(GPUControlOD8Held.gfxMin.rawValue == 16 && GPUControlFlags.gfxMin.rawValue == 512, "0.9.0: the GFX minimum's held bit 16 and status flag 512, as kOd8HeldGfxMin and kFlagGfxMin") + suite.expect(GPUControlOD8Held.volt.rawValue == 32 && GPUControlOD8Held.gfxMaxUp.rawValue == 64 + && GPUControlFlags.volt.rawValue == 1024 && GPUControlFlags.raise.rawValue == 2048, + "0.9.0: held bits 32 and 64, status flags 1024 and 2048, as kOd8HeldVolt, kOd8HeldGfxUp, " + + "kFlagVolt and kFlagRaise") + suite.expect(GPUControlWire.wantOverclock == 4 && GPUControlWire.setWantRaise == 1, + "the overclock flag 4 (kOd8WantOverclock) and the raise flag 1 (kSetWantRaise)") suite.expect(GPUControlWire.Selector.setOD8.takes(inputCount: 13) && GPUControlWire.Selector.setOD8.takes(inputCount: 14) + && GPUControlWire.Selector.setOD8.takes(inputCount: 15) && !GPUControlWire.Selector.setOD8.takes(inputCount: 12) - && !GPUControlWire.Selector.setOD8.takes(inputCount: 15) + && !GPUControlWire.Selector.setOD8.takes(inputCount: 16) && GPUControlWire.Selector.set.takes(inputCount: 2) - && !GPUControlWire.Selector.set.takes(inputCount: 14), - "setOD8 takes 13 or 14 scalars (od8WireCountOk), every other call its one count") + && GPUControlWire.Selector.set.takes(inputCount: 3) + && !GPUControlWire.Selector.set.takes(inputCount: 4) + && !GPUControlWire.Selector.status.takes(inputCount: 2), + "setOD8 takes 13, 14 or 15 scalars (od8WireCountOk), set 2 or 3 (setWireCountOk), " + + "every other call its one count") let offs: [(GPUControlWriteOff, UInt64)] = [ (.none, 0), (.ctlOff, 1), (.notOneCard, 2), (.otherAmdGpu, 3), (.library, 4), (.routes, 5), (.cwdde, 6), (.secondObject, 7), (.bootImplausible, 8), (.start, 9), (.sendFailed, 10), (.revertFailed, 11), (.teardown, 12), (.od8Failed, 13), (.od8Watchdog, 14), (.readOnlyCard, 15), + (.powerWatchdog, 16), ] - suite.expect(offs.allSatisfy { $0.0.rawValue == $0.1 } && GPUControlWriteOff.allCases.count == 16, - "write-off reasons: none 0 ... readOnlyCard 15, as gpuctl::WriteOff") + suite.expect(offs.allSatisfy { $0.0.rawValue == $0.1 } && GPUControlWriteOff.allCases.count == 17, + "write-off reasons: none 0 ... powerWatchdog 16, as gpuctl::WriteOff") kextConstants(suite) } @@ -1388,8 +1411,12 @@ enum GPUControlChannelTests { ("kWakeReadyMarginMs", GPUControlWire.wakeReadyMarginMs), ("kSetWaitMs", GPUControlWire.setWaitMs), ("kMaxPowerPercentDown", UInt64(GPUControlPowerRange.maxPercentDown)), - ("kOd8WireCount", UInt64(GPUControlWire.setOD8InputCountGfxMin)), + ("kOd8WireCount", UInt64(GPUControlWire.setOD8InputCountVolt)), + ("kOd8WireCountV090", UInt64(GPUControlWire.setOD8InputCountGfxMin)), ("kOd8WireCountV070", UInt64(GPUControlWire.setOD8InputCount)), + ("kSetWireCount", UInt64(GPUControlWire.Selector.set.inputCount)), + ("kSetWireCountRaise", UInt64(GPUControlWire.setInputCountRaise)), + ("kOd8VoltStepMV", UInt64(GPUControlWire.voltStepMV)), ] let kext = constants(in: source) for (name, app) in mirrored { diff --git a/Tests/Suites/GPUControlFanTests.swift b/Tests/Suites/GPUControlFanTests.swift index 535f09de..5326d9c2 100644 --- a/Tests/Suites/GPUControlFanTests.swift +++ b/Tests/Suites/GPUControlFanTests.swift @@ -83,7 +83,8 @@ enum GPUControlFanTests { return } let lines = text.split(separator: "\n") - suite.expect(lines.count == 120, "120 cases (100 from 0.7.2, 20 for the GFX minimum of 0.9.0)") + suite.expect(lines.count == 149, + "149 cases (100 from 0.7.2, 20 for the GFX minimum of 0.9.0, 29 for its GFX voltage and overclock)") var seen: [UInt64: Int] = [:] for (index, line) in lines.enumerated() { guard let object = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any], @@ -104,7 +105,7 @@ enum GPUControlFanTests { "case \(index + 1): never a code od8CheckWant does not give") seen[expected, default: 0] += 1 } - suite.expect(seen == [0: 42, 2: 14, 3: 5, 4: 13, 5: 9, 6: 4, 7: 3, 8: 6, 9: 6, 10: 9, 12: 9], + suite.expect(seen == [0: 55, 2: 15, 3: 5, 4: 15, 5: 9, 6: 4, 7: 3, 8: 6, 9: 6, 10: 14, 12: 10, 13: 7], "every code od8CheckWant gives is in the file: \(seen)") // The GFX drift boundary, by hand: +25 MHz is taken, +26 is not. var drift = base @@ -120,10 +121,13 @@ enum GPUControlFanTests { let curve = (dict["curve"] as? Bool) == true ? zip(temps, speeds).map { GPUControlFanPoint(temperatureC: $0, speedPercent: $1) } : nil let gfx = (dict["gfx"] as? Int) ?? 0 - // GPUSensors 0.9.0: written only when it is not stock. + // GPUSensors 0.9.0: written only when it is not stock (the voltage) + // or set (the overclock flag). let low = (dict["gfxMin"] as? Int) ?? 0 + let mv = (dict["volt"] as? Int) ?? 0 return GPUControlOD8Want(curve: curve, zeroRpmOff: (dict["zeroRpmOff"] as? Bool) == true, - gfxMaxMHz: gfx == 0 ? nil : gfx, gfxMinMHz: low == 0 ? nil : low) + gfxMaxMHz: gfx == 0 ? nil : gfx, gfxMinMHz: low == 0 ? nil : low, + voltMV: mv == 0 ? nil : mv, overclock: (dict["overclock"] as? Bool) == true) } private static func apply(_ mutation: [String: Any], to state: inout Rules.State) { @@ -147,6 +151,8 @@ enum GPUControlFanTests { case "firstEntry": change(&state.first[id]) case "bothEntry": change(&state.fresh[id]); change(&state.first[id]) case "cur": state.current[id] = Int(value) + // GPUSensors 0.9.0: the current read's mask, as 32 bits. + case "notAllowed": state.notAllowed = UInt32(truncatingIfNeeded: value) default: break } } diff --git a/Tests/Suites/GPUControlOverclockTests.swift b/Tests/Suites/GPUControlOverclockTests.swift new file mode 100644 index 00000000..f652ade4 --- /dev/null +++ b/Tests/Suites/GPUControlOverclockTests.swift @@ -0,0 +1,416 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 RyzenStatus + +import Foundation + +/// GPUSensors 0.9.0's GFX voltage and raises: the wire forms and numbers, +/// the rules one step past every limit, the recommended starting point, the +/// model and the controller, what is never asked for again at launch, the +/// overclock switch, the gating, the words. +enum GPUControlOverclockTests { + static func run(_ suite: TestSuite) { + wire(suite) + rules(suite) + voltLogic(suite) + overclockLogic(suite) + model(suite) + controller(suite) + remembering(suite) + gating(suite) + strings(suite) + } + + private typealias Want = GPUControlOD8Want + private typealias Harness = GPUControlChannelTests.Harness + private typealias Policy = GPUControlRememberPolicy + + /// The test card's table (`ioreg-0.7.2-2026-11-20.plist`): GfxVoltOffset + /// 881 to 1075 mV, stock 1075; GfxMaxMHz up to 2800, stock 2359. + private static func realWriting(takes: GPUControlOD8Held? = [.curve, .zeroRpmOff, .gfxMax, .gfxMin, .volt, .gfxMaxUp]) + -> GPUControlStatus.Writing? { + let path = FileManager.default.currentDirectoryPath + "/Tests/Fixtures/GPUSensors/ioreg-0.7.2-2026-11-20.plist" + guard let data = FileManager.default.contents(atPath: path), + let dict = (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [String: Any], + var writing = GPUControlStatus.parse(dict)?.writing else { return nil } + writing.od8State?.takes = takes + return writing + } + + // MARK: Wire + + private static func wire(_ suite: TestSuite) { + suite.expect(Want(voltMV: 1_050).scalars() == [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1_050], + "a voltage: 15 scalars, the 15th in mV, a stock minimum as 0") + suite.expect(Want(gfxMinMHz: 1_500, voltMV: 1_050).scalars()?.suffix(2) == [1_500, 1_050], + "a minimum and a voltage: both in the 15-scalar form") + suite.expect(Want(gfxMaxMHz: 2_500, overclock: true).scalars() + == [2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2_500], + "a raised maximum: the 13-scalar form with the overclock flag 4") + suite.expect(Want(gfxMaxMHz: 2_500, gfxMinMHz: 1_500, overclock: true).scalars()?.count == 14, + "with a minimum and no voltage: 14 scalars, the shortest form") + suite.expect(Want(voltMV: 0).scalars() == nil, "a voltage of 0 would read as stock: not sent") + suite.expect(Want(overclock: true).isStock && !Want(voltMV: 1_050).isStock, + "the overclock flag alone is the stock state; a voltage is a hold") + suite.expect(Want(voltMV: 1_050).heldFlags == .volt, "a voltage: held bit 32") + let raised = Want(gfxMaxMHz: 2_500, overclock: true) + suite.expect(raised.heldFlags == .gfxMax && raised.heldFlags(stockGfxMaxMHz: 2_359) == [.gfxMax, .gfxMaxUp] + && Want(gfxMaxMHz: 2_359, overclock: true).heldFlags(stockGfxMaxMHz: 2_359) == .gfxMax, + "a maximum above stock with the flag: bits 4 and 64; at stock, 4 alone (od8RaisesGfxMax)") + suite.expect(raised.matches(held: [.gfxMax, .gfxMaxUp]) && raised.matches(held: .gfxMax) + && !Want(gfxMaxMHz: 2_000).matches(held: [.gfxMax, .gfxMaxUp]) + && !Want(voltMV: 1_050).matches(held: .gfxMax), + "status matches a raised maximum with or without bit 64, a lowered one never with it") + // The raise form of set, through the model's dispatcher. + let fake = FakeGPUControlKext() + fake.takesOverclock = true + fake.arm() + let c = fake.connection() + _ = c.open() + let answer = c.setPower(watts: 250, raise: true) + suite.expect(fake.calls.last?.input == [2, 250, 1] && answer?.reply == .ok, + "set's raise form: {version, watts, 1}") + suite.expect(c.call(.set, input: [2, 250, 2], outputCount: 1) == [GPUControlReply.badArgs.rawValue], + "a set flag the kext does not know: malformed") + } + + // MARK: Rules + + private static func rules(_ suite: TestSuite) { + guard let table = realWriting()?.od8, let base = GPUControlCurveRules.State(table: table) else { + suite.expect(false, "rules: the 0.7.2 table loads") + return + } + typealias R = GPUControlCurveRules + suite.expect(base.first[R.gfxVolt] == R.Entry(feature: 0x20000, min: 881, max: 1_075, def: 1_075) + && base.notAllowed == 0xfffc_c0f2, + "the card's voltage entry and the NotAllowed mask, from the table") + func check(_ want: Want, _ state: R.State = base) -> GPUControlOD8Check { R.check(want, state).check } + suite.expect(check(Want(gfxMaxMHz: 2_800, overclock: true)) == .ok + && check(Want(gfxMaxMHz: 2_801, overclock: true)) == .gfxRange, + "overclock: the card's 2800 MHz is taken, one step above (2801) is refused") + suite.expect(check(Want(gfxMaxMHz: 2_360)) == .gfxRange, "above stock without the flag: refused") + suite.expect(check(Want(voltMV: 1_050)) == .ok && check(Want(voltMV: 900)) == .ok, + "1050 and 900 mV: whole 25 mV steps inside the card's range") + suite.expect(check(Want(voltMV: 1_076)) == .voltRange, "stock + 1 mV: refused (lower only)") + suite.expect(check(Want(voltMV: 880)) == .voltRange, "the card's minimum - 1 mV: refused") + suite.expect(check(Want(voltMV: 1_060)) == .voltRange, "not a 25 mV step from stock: refused") + var blocked = base + blocked.notAllowed |= 0x20000 + suite.expect(check(Want(voltMV: 1_050), blocked) == .noFeature, "the driver does not allow it now: no feature") + var missing = base + missing.first[R.gfxVolt].feature = 0 + missing.fresh[R.gfxVolt].feature = 0 + suite.expect(check(Want(voltMV: 1_050), missing) == .noFeature, "not offered: no feature") + } + + // MARK: The voltage control + + private static func voltLogic(_ suite: TestSuite) { + typealias V = GPUControlVoltLogic + let card = V.Limits(min: 881, stock: 1_075) + suite.expect(V.range(card) == 900...1_075, "900 to 1075 mV: the lowest 25 mV step at or above 881") + suite.expect(V.lowers(1_050, limits: card) && V.lowers(900, limits: card), "1050 and 900 lower it") + suite.expect(!V.lowers(1_075, limits: card) && !V.lowers(1_076, limits: card) && !V.lowers(875, limits: card) + && !V.lowers(1_060, limits: card) && !V.lowers(1_050, limits: nil), + "stock, above, below the minimum, off a step, or no table: never a hold") + suite.expect(V.request(1_075, stockMV: 1_075) == nil && V.request(1_050, stockMV: 1_075) == 1_050, + "choosing stock is the way back") + suite.expect(V.snapped(1_040, range: 900...1_075) == 1_050 && V.snapped(870, range: 900...1_075) == 900 + && V.snapped(1_090, range: 900...1_075) == 1_075, + "25 mV steps from stock, inside the range") + suite.expect(V.tickCount(range: 900...1_075) == 8, "a tick every step") + // The starting point: relative to the card's own stock value. + suite.expect(V.recommended(card) == 1_050, "one step below stock: 1050 mV on the test card") + suite.expect(V.recommended(V.Limits(min: 900, stock: 1_100)) == 1_075, "from the table, never a fixed number") + suite.expect(V.recommended(V.Limits(min: 1_060, stock: 1_075)) == nil, "below the card's minimum: not offered") + suite.expect(V.recommended(nil) == nil, "no voltage offered: no starting point") + // From the table. + if let writing = realWriting() { + suite.expect(V.limits(writing: writing, od8Ready: true) == card, "the card's voltage: 881, stock 1075") + suite.expect(V.limits(writing: writing, od8Ready: false) == nil, "no clean read: no voltage") + var older = writing + older.od8State?.takes = [.curve, .zeroRpmOff, .gfxMax, .gfxMin] + suite.expect(V.limits(writing: older, od8Ready: true) == nil, "Takes without 32: no voltage") + var blocked = writing + let mask = blocked.od8?.notAllowed ?? 0 + blocked.od8?.notAllowed = mask | 0x20000 + suite.expect(V.limits(writing: blocked, od8Ready: true) == nil, "NotAllowed has the voltage: none") + var page = GPUControlPageInput(facts: facts(), state: .ready, snapshot: nil) + page.writing = writing + suite.expect(GPUControlVoltSection.recommendedMV(page) == 1_050, "the section offers 1050 mV here") + page.writing = older + suite.expect(GPUControlVoltSection.recommendedMV(page) == nil && !GPUControlVoltSection.shows(page), + "not offered: no section, no starting point") + } else { + suite.expect(false, "volt: the 0.7.2 fixture loads") + } + suite.expect(V.checked(Want(gfxMaxMHz: 2_000, voltMV: 1_060), limits: card) == Want(gfxMaxMHz: 2_000) + && V.checked(Want(voltMV: 1_050), limits: nil) == .stock + && V.checked(Want(voltMV: 1_050), limits: card) == Want(voltMV: 1_050), + "a voltage the kext would not take is left out, the rest kept") + } + + // MARK: The overclock control + + private static func overclockLogic(_ suite: TestSuite) { + typealias O = GPUControlOverclockLogic + let limits = O.GfxLimits(stock: 2_359, max: 2_800) + suite.expect(O.raises(2_800, limits: limits) && O.raises(2_360, limits: limits), "up to the card's 2800 MHz") + suite.expect(!O.raises(2_801, limits: limits) && !O.raises(2_359, limits: limits) && !O.raises(2_500, limits: nil), + "one step above the card's maximum, stock, or no table: never a raise") + suite.expect(O.request(2_359, stockMHz: 2_359) == nil && O.request(2_500, stockMHz: 2_359) == 2_500, + "stock is the way back") + suite.expect(O.snapped(2_363, range: 2_359...2_800) == 2_359 && O.snapped(2_797, range: 2_359...2_800) == 2_800, + "10 MHz steps from stock, the card's top on its own") + if let writing = realWriting() { + suite.expect(O.gfxLimits(writing: writing, od8Ready: true) == limits, "from the table: 2359 to 2800 MHz") + var older = writing + older.od8State?.takes = [.curve, .zeroRpmOff, .gfxMax, .gfxMin, .volt] + suite.expect(O.gfxLimits(writing: older, od8Ready: true) == nil, "Takes without 64: no raised maximum") + } + suite.expect(O.powerChoices(bootW: 240, ceilW: 261) == [240, 250, 260, 261], + "start-up, the 10 W steps above it, and the ceiling itself") + suite.expect(O.powerChoices(bootW: 240, ceilW: 240).isEmpty && O.powerChoices(bootW: 240, ceilW: nil).isEmpty, + "nothing above the start-up limit: no raised pop-up") + var f = facts() + suite.expect(O.ceilingW(facts: f) == 261, "CeilW 261 above MaxW 240, with the raise flag") + f.takesRaise = false + suite.expect(O.ceilingW(facts: f) == nil, "a kext without the raise flag: no ceiling") + f = facts() + f.powerRange?.ceilW = 240 + suite.expect(O.ceilingW(facts: f) == nil, "CeilW = MaxW: nothing higher") + } + + /// The test card's power facts: 240 W at start-up, 225 to 261 W. + private static func facts() -> GPUControlFacts { + var f = GPUControlFacts(source: .properties) + f.ready = true + f.armed = true + f.od8Ready = true + f.takesRaise = true + f.bootW = 240 + f.powerRange = GPUControlPowerRange(source: .kext, floorW: 225, maxW: 240, ceilW: 261, stepW: 10, + percentMin: -6, percentMax: 9) + return f + } + + // MARK: The model + + private static func model(_ suite: TestSuite) { + let fake = FakeGPUControlKext() + fake.takesOverclock = true + fake.powerPercentMax = 9 + fake.arm() + let c = fake.connection() + _ = c.open() + let range = GPUControlService.fakeControl(fake)?.writing?.powerRange + suite.expect(range?.ceilW == 261 && range?.maxW == 240, "PowerRange CeilW 261 at 240 W (+9 %)") + suite.expect(c.status()?.flags.isSuperset(of: [.volt, .raise]) == true + && GPUControlService.fakeControl(fake)?.writing?.od8State?.takes?.rawValue == 119, + "status flags 1024 and 2048, Takes 119") + // The power ceiling, one past it, a step past it. + func set(_ watts: UInt32) -> GPUControlReply? { + let reply = c.setPower(watts: watts, raise: true)?.reply + fake.advance(by: 3_000) + return reply + } + suite.expect(set(262) == .aboveCeiling && set(271) == .aboveCeiling, "CeilW + 1 and CeilW + 10: above the ceiling") + suite.expect(set(255) == .notAStep, "off a 10 W step: refused") + suite.expect(c.setPower(watts: 250)?.reply == .aboveBoot, "above start-up without the raise flag: as before") + suite.expect(set(261) == .ok && c.status()?.heldW == 261, "the ceiling itself is taken") + _ = c.release() + fake.advance(by: 3_000) + fake.dogSees = false + suite.expect(set(250) == .noReadings, "no fresh readings: no raised limit") + fake.dogSees = true + // A voltage. + suite.expect(c.setOD8(Want(voltMV: 1_050))?.reply == .ok + && GPUControlService.fakeControl(fake)?.writing?.od8State?.voltHeld == 1_050 + && c.status()?.od8Held == .volt, "a voltage held: VoltHeld 1050, held bit 32") + fake.advance(by: 3_000) + let refused = c.setOD8(Want(voltMV: 1_060)) + suite.expect(refused?.reply == .od8Refused && refused?.check == .voltRange, "off a step: VoltRange") + fake.advance(by: 3_000) + let up = c.setOD8(Want(gfxMaxMHz: 2_801, overclock: true)) + suite.expect(up?.check == .gfxRange, "2801 MHz with the flag: refused") + fake.advance(by: 3_000) + suite.expect(c.setOD8(Want(gfxMaxMHz: 2_800, overclock: true))?.reply == .ok + && c.status()?.od8Held == [.gfxMax, .gfxMaxUp], "2800 MHz with the flag: held bits 4 and 64") + } + + // MARK: The controller + + private static func controller(_ suite: TestSuite) { + do { + let h = Harness { $0.takesOverclock = true } + h.engine.choose(.power(watts: 250)) + h.run(ms: 0) + suite.expect(h.calls(.set).last?.input == [2, 250, 1] && h.held == .power(watts: 250), + "a limit above start-up goes in the raise form, and is held") + h.run(ms: 3_000) + h.engine.choose(.power(watts: 230)) + h.run(ms: 0) + suite.expect(h.calls(.set).last?.input == [2, 230] && h.held == .power(watts: 230), + "a lower limit keeps the 2-scalar form") + } + do { + let h = Harness { $0.takesOverclock = true } + h.engine.choose(.power(watts: 260)) + h.run(ms: 0) + h.fake.tripFanWatchdog() + h.run(ms: 5_000) + suite.expect(h.engine.snapshot.stopped == .writingOff(GPUControlWriteOff.powerWatchdog.rawValue), + "the watchdog takes a raised limit back: writing off (PowerWatchdog)") + } + do { + let h = Harness { $0.takesOverclock = true } + h.engine.chooseGfxMax(2_000) + h.run(ms: 3_000) + h.engine.chooseVolt(1_050) + h.run(ms: 0) + suite.expect(h.calls(.setOD8).last?.input == [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2_000, 0, 1_050] + && h.held == .od8(Want(gfxMaxMHz: 2_000, voltMV: 1_050)), + "the voltage goes with the held maximum, in the 15-scalar form") + h.run(ms: 3_000) + h.engine.chooseGfxMaxRaised(2_600) + h.run(ms: 0) + suite.expect(h.calls(.setOD8).last?.input.prefix(2) == [2, 4] + && h.held == .od8(Want(gfxMaxMHz: 2_600, voltMV: 1_050, overclock: true)), + "a raised maximum replaces the lowered one, with the flag, the voltage kept") + h.run(ms: 3_000) + h.engine.chooseGfxMax(nil) + h.run(ms: 0) + suite.expect(h.held == .od8(Want(gfxMaxMHz: 2_600, voltMV: 1_050, overclock: true)), + "the lowering control's stock leaves a raised maximum alone") + h.engine.dropRaises() + h.run(ms: 0) + suite.expect(h.held == .od8(Want(voltMV: 1_050)), "overclock off: the raise goes, the voltage stays") + } + do { + let h = Harness { $0.takesOverclock = true } + h.engine.choose(.power(watts: 250)) + h.run(ms: 0) + h.engine.dropRaises() + h.run(ms: 3_000) + suite.expect(h.held == nil && !(h.fake.statusFor(h.connection)?.holdsPower ?? true), + "overclock off: a raised power limit goes back to start-up") + } + } + + // MARK: Remembering + + private static func remembering(_ suite: TestSuite) { + let suiteName = "ryzenstatus.tests.gpucontrol.overclock.\(getpid())" + guard let defaults = UserDefaults(suiteName: suiteName) else { return } + let all = Want(gfxMaxMHz: 2_600, gfxMinMHz: 1_500, voltMV: 1_050, overclock: true) + GPUControlRemembered.od8(all).save(defaults) + suite.expect(GPUControlRemembered.load(defaults) == .od8(all), "a voltage and a raise round-trip") + GPUControlRemembered.power(watts: 230).save(defaults) + suite.expect(defaults.object(forKey: DefaultsKey.gpuControlRememberedVoltMV) == nil + && defaults.object(forKey: DefaultsKey.gpuControlRememberedOverclock) == nil, + "saving power clears them") + defaults.removePersistentDomain(forName: suiteName) + + let f = facts() + let minLimits = GPUControlClockMinLogic.Limits(min: 500, max: 2_800, stock: 500) + func atLaunch(_ remembered: GPUControlRemembered) -> GPUControlRequest? { + Policy.request(remembered: remembered, active: true, facts: f, stopped: nil, stockGfxMaxMHz: 2_359, + gfxMin: minLimits) + } + suite.expect(atLaunch(.od8(all)) == .od8(Want(gfxMinMHz: 1_500)), + "at launch: no voltage and no raised maximum, the rest still asked for") + suite.expect(atLaunch(.od8(Want(gfxMaxMHz: 2_000, voltMV: 1_050))) == .od8(Want(gfxMaxMHz: 2_000)), + "at launch: a lowered maximum stays, the voltage goes") + suite.expect(atLaunch(.od8(Want(voltMV: 1_050))) == nil, "a voltage alone: nothing asked for at launch") + suite.expect(atLaunch(.power(watts: 250)) == nil && atLaunch(.power(watts: 230)) == .power(watts: 230), + "a limit above start-up is never asked for at launch; a lower one is") + // After a wake, in the same run: they follow the remember switch. + let volt = GPUControlVoltLogic.Limits(min: 881, stock: 1_075) + let up = GPUControlOverclockLogic.GfxLimits(stock: 2_359, max: 2_800) + suite.expect(Policy.checkedAgain(.od8(all), stockGfxMaxMHz: 2_359, gfxMin: minLimits, volt: volt, overclock: up) + == .od8(all), "after a wake: asked again as it was") + suite.expect(Policy.checkedAgain(.od8(all), stockGfxMaxMHz: 2_359, gfxMin: minLimits) + == .od8(Want(gfxMinMHz: 1_500)), "after a wake with a kext that takes neither: the rest") + suite.expect(Policy.checkedAgain(.power(watts: 250), stockGfxMaxMHz: 2_359) == .power(watts: 250), + "a raised limit after a wake: asked again") + } + + // MARK: Gating + + private static func gating(_ suite: TestSuite) { + guard let writing = realWriting() else { + suite.expect(false, "gating: the 0.7.2 fixture loads") + return + } + var page = GPUControlPageInput(facts: facts(), state: .ready, snapshot: nil) + page.writing = writing + suite.expect(GPUControlVoltSection.shows(page) && GPUControlOverclockSection.shows(page), + "an RX 6800 XT with 0.9.0: both sections") + suite.expect(GPUControlOverclockSection.powerChoices(page) == [240, 250, 260, 261], + "the raised pop-up: start-up to CeilW") + page.state = .readOnlyCard + suite.expect(!GPUControlVoltSection.shows(page) && !GPUControlOverclockSection.shows(page), + "the read-only card: neither section") + page.state = .ready + page.writing?.od8State?.takes = [.curve, .zeroRpmOff, .gfxMax, .gfxMin] + page.facts?.takesRaise = false + suite.expect(!GPUControlVoltSection.shows(page) && !GPUControlOverclockSection.shows(page), + "a kext without the voltage or the raises: neither section") + page.facts?.od8Ready = false + page.writing = writing + page.facts?.takesRaise = true + suite.expect(!GPUControlVoltSection.shows(page) && GPUControlOverclockSection.gfxLimits(page) == nil, + "OD8 not read cleanly: no voltage, no raised maximum") + // The switch is off by default. + let suiteName = "ryzenstatus.tests.gpucontrol.overclock.switch.\(getpid())" + if let defaults = UserDefaults(suiteName: suiteName) { + defaults.removePersistentDomain(forName: suiteName) + MainActor.assumeIsolated { + let service = GPUControlService(defaults: defaults) + suite.expect(!service.overclock, "Allow overclocking is off by default") + service.overclock = true + suite.expect(defaults.bool(forKey: DefaultsKey.gpuControlOverclock) + && GPUControlService(defaults: defaults).overclock, "and kept once turned on") + } + defaults.removePersistentDomain(forName: suiteName) + } + suite.expect(GPUControlPageInput(facts: nil, state: nil, snapshot: nil).overclock == false, + "the page's input starts with the switch off") + } + + // MARK: Words + + private static func strings(_ suite: TestSuite) { + func placeholders(_ text: String) -> [String] { + let pattern = try? NSRegularExpression(pattern: "%(?:[0-9]+\\$)?[@d%]") + let range = NSRange(text.startIndex..., in: text) + return pattern?.matches(in: text, range: range).compactMap { Range($0.range, in: text).map { String(text[$0]) } } + .filter { $0 != "%%" } ?? [] + } + let english = GPUControlOverclockStrings.enUS.all + suite.expect(english.count == 22, "22 texts") + for language in AppLanguage.allCases { + let table = FeatureStrings.gpuControlOverclock(language).all + suite.expect(table.count == english.count && table.allSatisfy { !$0.trimmingCharacters(in: .whitespaces).isEmpty }, + "\(language.rawValue): every overclock text") + for (text, reference) in zip(table, english) { + suite.expect(Set(placeholders(text)) == Set(placeholders(reference)), + "\(language.rawValue): the same placeholders as English in \(reference.prefix(30))") + } + let page = FeatureStrings.gpuControlPage(language) + suite.expect(page.voltItemFormat.contains("%d") && !page.offPowerWatchdog.isEmpty, + "\(language.rawValue): the held voltage and the power watchdog sentence") + let names = GPUControlVoltSection.accessibilityNames(FeatureStrings.gpuControlOverclock(language)) + let up = GPUControlOverclockSection.accessibilityNames(FeatureStrings.gpuControlOverclock(language)) + suite.expect(Set([names.slider, names.field, names.stepper, up.slider, up.field, up.stepper]).count == 6, + "\(language.rawValue): each control has its own VoiceOver name") + } + suite.expect(GPUControlPageStrings.enUS.od8Held(Want(gfxMaxMHz: 2_600, voltMV: 1_050, overclock: true)) + == "RyzenStatus is holding a GFX maximum of 2600 MHz and a GFX voltage of 1050 mV", + "a raised maximum and a voltage, in one sentence") + suite.expect(GPUControlPageStrings.enUS.sentence(.offPowerWatchdog) + == "Off: the watchdog put the start-up power limit back.", "the power watchdog's sentence") + suite.expect(GPUControlOverclockStrings.enUS.voltRecommendedFormat.contains("not a guarantee"), + "the starting point says it is not a guarantee") + } +} diff --git a/Tests/Suites/GPUControlPageTests.swift b/Tests/Suites/GPUControlPageTests.swift index 230b51da..0e807c4a 100644 --- a/Tests/Suites/GPUControlPageTests.swift +++ b/Tests/Suites/GPUControlPageTests.swift @@ -853,7 +853,7 @@ enum GPUControlPageTests { return pattern?.matches(in: text, range: range).compactMap { Range($0.range, in: text).map { String(text[$0]) } } ?? [] } let english = GPUControlPageStrings.enUS.all - suite.expect(english.count == 95, "95 texts") + suite.expect(english.count == 97, "97 texts") for language in AppLanguage.allCases { let table = FeatureStrings.gpuControlPage(language).all suite.expect(table.count == english.count && table.allSatisfy { !$0.trimmingCharacters(in: .whitespaces).isEmpty }, diff --git a/docs/GPU_CONTROL.md b/docs/GPU_CONTROL.md new file mode 100644 index 00000000..caef3c0e --- /dev/null +++ b/docs/GPU_CONTROL.md @@ -0,0 +1,136 @@ +# GPU control + +Settings › GPU control changes an AMD Radeon RX 6000 card's power limit, fan, clocks and +voltage through the optional GPUSensors.kext (see [GPU/sensors](../GPU/sensors/README.md)). +This page lists every control, the range it takes, what it does and what can go wrong. + +Every value comes from the card itself: the ranges are the ones its own firmware tables +publish to the driver (the OverDrive data, the same limits AMD's Radeon Software offers on +Windows). Nothing here is a number written into the app for one card, and the kext refuses +anything outside those ranges instead of rounding it. + +Some things hold for all of it: + +- Changes are closed until an administrator allows them (Allow GPU Changes), and they stay + allowed only until the Mac restarts or you close them again. +- One program holds one change at a time. The kext puts the card back to stock on its own + when RyzenStatus quits or crashes, when it stops answering for 30 seconds, after every + sleep, and on restart. Nothing is stored on the card. +- The power limit and the OverDrive settings (fan, clocks, voltage) are never held at the + same time: while one is held, the other answers "busy". +- Whatever raises a clock or the power limit, and the fan curve, are held under a watchdog + that reads the hotspot temperature every second. At 95 °C, or when the readings stop for + 10 seconds, it puts stock back and closes changes until restart. + +## Which cards + +| Card | What the page does | +|---|---| +| RX 6800 XT (Navi 21, 73BF rev C1) | everything below; the card the kext was built and tested on | +| RX 6900 XT (Navi 21, 73BF rev C0) | readings only: the kext reads it the same way and never writes | +| RX 6800, RX 6950 XT, Pro W6800 / W6900X, every Navi 23 (RX 6600, 6600 XT, 6650 XT, Pro W6600) | not read by the control yet; the sensors still work | + +A control only shows when the kext says it takes it and the card offers it (its OverDrive +feature bit is set). + +## Power limit + +From the card's minimum up to the limit it started with, in 10 W steps. The minimum is +worked out the way Linux does it: the start-up limit less the card's own power percent +(225 W on a card that starts at 240 W). Less power means less heat and lower clocks under +load. + +## Fan curve and zero RPM + +Five points, temperature and speed. The kext only takes curves that give at least as much +air as the stock curve at every point and reach 100 % well below the card's target +temperature. Zero RPM can only be turned off (the fan always spins). + +## GFX maximum and minimum clock + +The maximum can be lowered from stock down to 1500 MHz. The minimum can be raised from its +stock value up to the maximum in force: it keeps the clock up at idle, so the card draws +more power and runs warmer. + +## GFX voltage (undervolt) + +From the card's stock voltage down to its own minimum, in 25 mV steps (on the test RX 6800 +XT: 1075 mV stock, 881 mV minimum, so 1050, 1025 ... 900). It only lowers. The value is the +highest voltage the GPU may use; the driver turns it into an offset (the firmware's +VddGfxOffset) that moves the whole voltage curve down by the difference, so the card runs +cooler and draws less at every clock. It needs SMU firmware 58.41.0 or later, as on Linux +(the test card has 58.76.0). + +The page suggests a starting point of stock minus 25 mV (1050 mV on the test card). It is +only filled in, never applied by itself, and it is a value to test, not a promise. + +What can go wrong: too low a voltage makes the GPU unstable. A game or benchmark freezes, +the driver resets, or the screen goes black and the Mac has to be restarted. Nothing is +damaged and nothing is kept: after the restart the card starts at stock, and RyzenStatus +never sends a voltage again by itself at launch (only after a wake, if Remember is on). +Every chip is different. + +How to use it: go down 25 mV at a time, run a game or a benchmark for a while after each +step, and once you find the lowest value that is stable, go back up 10 to 20 mV and keep +that. + +Community reports (RX 6800 XT): ComputerBase took its card from 1.15 V to 1.025 V stable +and it crashed below that +([computerbase.de](https://www.computerbase.de/2020-11/amd-radeon-rx-6800-xt-oc-uv/)); +Igor's Lab calls values up to 1075 mV sensible for an XT and advises staying 10 to 20 mV +above the lowest stable voltage. + +## Overclock + +A separate section, off until you turn on Allow overclocking. It raises things above stock, +always inside the card's own OverDrive limits and never past them: + +- **GFX maximum above stock**, up to the card's own maximum (2800 MHz on the RX 6800 XT, + the same cap Radeon Software has). The firmware may round it down a few MHz. +- **Power limit above the start-up limit**, up to the start-up limit plus the card's own + power percent, and never more than +15 % (AMD's own cap on these cards). On the test card + that is 240 W + 9 % = 261 W (its table offers +9 %). + +There are no suggested values here. Inside AMD's limits nothing can burn, but a value can be +unstable: freezes and driver resets mean the clock is too high for the voltage. Everything +goes back to stock when you turn the section off, when RyzenStatus quits, on restart and +after sleep, and raised values are never sent again by themselves at launch. The watchdog +holds every raise (95 °C). + +More clock rarely gains anything without more power, and the two are held separately (see +above). Raising the clock on a card with a lowered power limit mostly adds heat. + +Community reports: a reference RX 6800 XT with +15 % power typically holds about 2400 MHz, +some cards 2500, for about 5 % more performance and about 15 % more power (KitGuru, Igor's +Lab, Guru3D). Igor's Lab advises not to go past about 330 W for the chip. Raise one thing at +a time, 25 MHz at a time, and test each step. + +## Not offered: memory clock and fast memory timings + +The cards offer a higher memory clock (2000 to 2150 MHz on the RX 6800 XT) and a "fast +timings" switch, but on macOS the driver cannot apply either. Both start with a call that +asks the display driver to prepare for a memory overclock, and Apple's part of the driver +does not implement that call, so the driver gives up: a memory clock is never written (and +the request fails), and fast timings are recorded without ever being programmed. The kext +therefore never sends them, and the page has no control for them. Read in the driver of +macOS 26.7.3 (25G342), 2026-11-25. + +For reference, community reports on Windows: around 2100 to 2112 MHz many RDNA2 cards start +to show artifacts or get slower instead of faster, and 2150 MHz with fast timings is the +edge (TechPowerUp RX 6000 owners club, Overclockers UK; Guru3D advises backing down 25 MHz +at the first white dots). On the test card memory overclocking was unstable on Windows too. + +## Other RX 6000 cards (community reports) + +These are for when the control supports them; today only the RX 6800 XT writes. + +- **RX 6900 XT**: always power-limited, so overclocking gains little (about 5 to 7 % in + games); reference cards cap memory at 2150 MHz and fast timings vary from card to card + (TechPowerUp's RX 6900 XT review, TheFPSReview, KitGuru). +- **RX 6600 XT**: memory often reaches 2250 to 2300 MHz, but pushed too far it retries + transfers and gets slower without any artifact, so benchmark instead of looking for + artifacts (TechPowerUp's MSI RX 6600 XT review); fast timings caused artifacts and crashes + for some users (Steam forum); without a higher power limit an overclock shows no gain. + +For every card: change one thing at a time, in 25 mV or 25 MHz steps, and undervolt before +you overclock. From 9a8911abeb7fd56ffede1303ba1df61f76b060f9 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Wed, 25 Nov 2026 21:37:22 -0300 Subject: [PATCH 3/3] GPU control: remembered settings come back at launch and wake At launch the remembered OD8 state was refused once with "the fan watchdog has no fresh hotspot and fan readings" and never asked for again. The kext's PMLog copy only moves when someone reads the accelerator's PerformanceStatistics, and right after launch nothing had yet. Now the app reads PerformanceStatistics right before every OD8 change and every raised power limit, and a remembered request refused for missing readings is tried again every 3 s for 30 s. Real refusals (out of range, not allowed, another program) are never sent again, and the owner's own choices still show a refusal at once. The remembered GFX voltage and the raised GFX maximum now come back at launch too, the raise only while "Allow overclocking" is on (also checked again after a wake). A raised power limit is still not asked for at launch. Footers, docs and the changelog say so in every language. The "Fan always on" switch only edited the fan editor's draft, which went out with "Apply curve"; the voltage and clock controls sent the held state without it, so the switch could read on while the kext held zero RPM at stock. While a curve is held the switch now sends at once with that curve. gpucontrol status says "GFX max raised" for a maximum above stock and shows a held voltage. ./build.sh --test: 34986 checks OK; concurrency gate OK. --- CHANGELOG.md | 2 +- GPU/CHANGELOG.md | 2 + GPU/sensors/tool/gpucontrol.cpp | 8 +- .../RyzenStatus/Core/DefaultsKey+App.swift | 8 +- .../Core/GPUControlOverclockStrings.swift | 56 +++---- .../Metrics/GPUControlController.swift | 94 +++++++++++ .../Services/Metrics/GPUControlPage.swift | 48 +++--- .../Services/Metrics/GPUControlService.swift | 29 +++- .../UI/Settings/GPUControlFanSection.swift | 24 ++- Tests/Suites/GPUControlFanTests.swift | 29 ++++ Tests/Suites/GPUControlOverclockTests.swift | 149 ++++++++++++++++-- docs/GPU_CONTROL.md | 11 +- 12 files changed, 383 insertions(+), 77 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6b48720..91788dd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ **GPU minimum clock, from GPUSensors.kext 0.9.0**: Settings › GPU control has a GFX minimum clock under the maximum. It only raises the minimum, from the card's stock value up to the GFX maximum in force, and keeps the clock up at idle, so the card draws more power and runs warmer; the kext checks every request, watches the temperature while it is held, and goes back to stock in the same cases as the other GPU changes. The section shows only with GPUSensors.kext 0.9.0. The memory clock, fan minimum speed and fan target temperature stay out: on the RX 6800 XT the driver offers no lower memory clock and no fan minimum or target while it offers the fan curve. Tested with unit tests only. -**GPU voltage and Overclock, from GPUSensors.kext 0.9.0**: Settings › GPU control has a GFX voltage section that only lowers the voltage, from the card's stock value down to its own minimum in 25 mV steps (an undervolt: the whole voltage curve moves down, so the card runs cooler). It suggests stock minus 25 mV as a starting point to test and never applies it by itself. A separate Overclock section, off by default, raises the GFX maximum clock up to the card's own maximum and the power limit up to the card's own power percent (never more than +15 %); it has no suggested values. Every value stays inside the limits the card publishes, the kext refuses anything else, holds every raise under its temperature watchdog and goes back to stock in the same cases as the other GPU changes; a voltage or a raise is never sent again by itself at launch. Memory clock and fast memory timings are not offered: on macOS the driver cannot apply them. Only the RX 6800 XT writes; the RX 6900 XT shows readings only. All of it is in [docs/GPU_CONTROL.md](docs/GPU_CONTROL.md). Tested with unit tests only. +**GPU voltage and Overclock, from GPUSensors.kext 0.9.0**: Settings › GPU control has a GFX voltage section that only lowers the voltage, from the card's stock value down to its own minimum in 25 mV steps (an undervolt: the whole voltage curve moves down, so the card runs cooler). It suggests stock minus 25 mV as a starting point to test and never applies it by itself. A separate Overclock section, off by default, raises the GFX maximum clock up to the card's own maximum and the power limit up to the card's own power percent (never more than +15 %); it has no suggested values. Every value stays inside the limits the card publishes, the kext refuses anything else, holds every raise under its temperature watchdog and goes back to stock in the same cases as the other GPU changes; with Remember on, a voltage comes back at launch and after a wake like the other settings, and a raised GFX maximum too while Allow overclocking is on. Memory clock and fast memory timings are not offered: on macOS the driver cannot apply them. Only the RX 6800 XT writes; the RX 6900 XT shows readings only. All of it is in [docs/GPU_CONTROL.md](docs/GPU_CONTROL.md). Tested with unit tests only. **AWDL / AirDrop activity in the Network card**: with a Wi-Fi driver that publishes AWDL activity in the I/O Registry (`RTLAwdlPeers` and `RTLAwdlChannel` on the `awdl0` interface, and optionally the `RTLLed` status LED mode), the panel's Network card shows a line with the number of peers exchanging data over AWDL (AirDrop, Sidecar, Continuity) and its current channel. Settings › Monitor › Alerts adds an optional notification when AWDL goes from no peers to some; it is off by default and fires at most once a minute. The line can be hidden like the card's other blocks. With other Wi-Fi hardware nothing changes and nothing extra is read. diff --git a/GPU/CHANGELOG.md b/GPU/CHANGELOG.md index 2363a3fe..9fa3bb1a 100644 --- a/GPU/CHANGELOG.md +++ b/GPU/CHANGELOG.md @@ -60,6 +60,8 @@ The encoding fix keeps its own history in `encode/CHANGELOG.md`. (nothing could be read back). Also not added: the fan minimum speed (id 10) and fan target temperature (id 12), which the driver does not offer while the fan curve is offered (feature 0, and `PhwComm_OD8_SetGenericSetting` skips a setting whose feature is 0). +- `gpucontrol status` names a held GFX maximum above stock "GFX max raised" (it said + "lowered" for every held maximum) and shows a held voltage as "GFX voltage lowered". ## Decoders 0.3.5 (RyzenStatus 1.89.0) diff --git a/GPU/sensors/tool/gpucontrol.cpp b/GPU/sensors/tool/gpucontrol.cpp index e1bf3399..4d3ffc22 100644 --- a/GPU/sensors/tool/gpucontrol.cpp +++ b/GPU/sensors/tool/gpucontrol.cpp @@ -200,11 +200,15 @@ int doStatus() { else if (h == 0) printf(" OD8 at stock\n"); else - printf(" OD8 %s%s%s%s%s\n", + // 0.9.0: bit 64 says the held GFX maximum is above stock (overclock). + printf(" OD8 %s%s%s%s%s%s\n", (h & kOd8HeldCurve) ? "fan curve " : "", (h & kOd8HeldZeroRpmOff) ? "zero RPM off " : "", - (h & kOd8HeldGfx) ? "GFX max lowered " : "", + !(h & kOd8HeldGfx) ? "" + : (h & kOd8HeldGfxUp) ? "GFX max raised " + : "GFX max lowered ", (h & kOd8HeldGfxMin) ? "GFX min raised " : "", + (h & kOd8HeldVolt) ? "GFX voltage lowered " : "", (h & kOd8HeldUnknown) ? "not confirmed, going back to stock" : ""); if (f & kFlagOwned) printf(" held by a program\n"); if (f & kFlagReverting) printf(" going back to the start-up limit\n"); diff --git a/Sources/RyzenStatus/Core/DefaultsKey+App.swift b/Sources/RyzenStatus/Core/DefaultsKey+App.swift index 9219f34f..fff038cf 100644 --- a/Sources/RyzenStatus/Core/DefaultsKey+App.swift +++ b/Sources/RyzenStatus/Core/DefaultsKey+App.swift @@ -1104,12 +1104,12 @@ extension DefaultsKey { static let gpuControlRememberedGfxMHz = "gpuControlRememberedGfxMHz" /// A raised GFX minimum (GPUSensors 0.9.0), in MHz. static let gpuControlRememberedGfxMinMHz = "gpuControlRememberedGfxMinMHz" - /// A lowered GFX voltage (GPUSensors 0.9.0), in mV. Saved with the rest - /// of the state, never asked for again at launch. + /// A lowered GFX voltage (GPUSensors 0.9.0), in mV. Asked for again at + /// launch and after a wake with the rest of the state. static let gpuControlRememberedVoltMV = "gpuControlRememberedVoltMV" /// The overclock flag of a remembered raised GFX maximum (GPUSensors - /// 0.9.0). Saved with the rest of the state, never asked for again at - /// launch. + /// 0.9.0). The raised maximum is asked for again at launch and after a + /// wake only while "Allow overclocking" is on. static let gpuControlRememberedOverclock = "gpuControlRememberedOverclock" /// The "Allow overclocking" switch of Settings > GPU control (off by /// default). diff --git a/Sources/RyzenStatus/Core/GPUControlOverclockStrings.swift b/Sources/RyzenStatus/Core/GPUControlOverclockStrings.swift index 7e5949ab..5aa15a00 100644 --- a/Sources/RyzenStatus/Core/GPUControlOverclockStrings.swift +++ b/Sources/RyzenStatus/Core/GPUControlOverclockStrings.swift @@ -93,10 +93,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "Recommended starting point: %d mV. A starting point to test, not a guarantee.", voltUseRecommended: "Use Starting Point", voltApply: "Apply", - voltFooter: "Lowers the whole GPU voltage curve by the difference to stock: less heat and less power. If it is too low, the GPU can freeze, reset its driver or show a black screen. Go down 25 mV at a time, test with a game or a benchmark, and stay 10–20 mV above the lowest value that was stable. It goes back to stock when RyzenStatus quits, on restart and after sleep. Silicon varies from card to card.", + voltFooter: "Lowers the whole GPU voltage curve by the difference to stock: less heat and less power. If it is too low, the GPU can freeze, reset its driver or show a black screen. Go down 25 mV at a time, test with a game or a benchmark, and stay 10–20 mV above the lowest value that was stable. It goes back to stock when RyzenStatus quits, on restart and after sleep. With Remember on, RyzenStatus sets it again at launch and after a wake. Silicon varies from card to card.", ocSection: "Overclock", ocToggle: "Allow overclocking", - ocWarning: "Inside AMD’s own limits for this card nothing can burn, but a value can be unstable: the GPU can freeze or reset its driver. Everything goes back to stock when you turn this off, when RyzenStatus quits, on restart and after sleep, and the watchdog puts stock back at 95 °C.", + ocWarning: "Inside AMD’s own limits for this card nothing can burn, but a value can be unstable: the GPU can freeze or reset its driver. Everything goes back to stock when you turn this off, when RyzenStatus quits, on restart and after sleep, and the watchdog puts stock back at 95 °C. With Remember on, RyzenStatus sets the raised GFX maximum again at launch and after a wake, only while this is on.", ocGfxLabel: "GFX maximum above stock", ocGfxFieldLabel: "Raised GFX maximum clock in MHz", ocGfxStepperFormat: "Raised GFX maximum clock, steps of %d MHz", @@ -117,10 +117,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "Punto de partida recomendado: %d mV. Es un punto de partida para probar, no una garantía.", voltUseRecommended: "Usar punto de partida", voltApply: "Aplicar", - voltFooter: "Baja toda la curva de voltaje de la GPU en la diferencia con el de fábrica: menos calor y menos consumo. Si queda demasiado bajo, la GPU puede congelarse, reiniciar su driver o dejar la pantalla en negro. Baja 25 mV cada vez, prueba con un juego o un benchmark y quédate 10–20 mV por encima del valor más bajo que fue estable. Vuelve al de fábrica al salir de RyzenStatus, al reiniciar y después del reposo. Cada chip es distinto, aun en el mismo modelo de tarjeta.", + voltFooter: "Baja toda la curva de voltaje de la GPU en la diferencia con el de fábrica: menos calor y menos consumo. Si queda demasiado bajo, la GPU puede congelarse, reiniciar su driver o dejar la pantalla en negro. Baja 25 mV cada vez, prueba con un juego o un benchmark y quédate 10–20 mV por encima del valor más bajo que fue estable. Vuelve al de fábrica al salir de RyzenStatus, al reiniciar y después del reposo. Con Recordar activado, RyzenStatus lo vuelve a aplicar al abrir y al despertar. Cada chip es distinto, aun en el mismo modelo de tarjeta.", ocSection: "Overclock", ocToggle: "Permitir overclock", - ocWarning: "Dentro de los límites que AMD fija para esta tarjeta nada se puede quemar, pero un valor puede ser inestable: la GPU puede congelarse o reiniciar su driver. Todo vuelve a los valores de fábrica al apagar esto, al salir de RyzenStatus, al reiniciar y después del reposo, y el vigilante vuelve a los valores de fábrica a los 95 °C.", + ocWarning: "Dentro de los límites que AMD fija para esta tarjeta nada se puede quemar, pero un valor puede ser inestable: la GPU puede congelarse o reiniciar su driver. Todo vuelve a los valores de fábrica al apagar esto, al salir de RyzenStatus, al reiniciar y después del reposo, y el vigilante vuelve a los valores de fábrica a los 95 °C. Con Recordar activado, RyzenStatus vuelve a aplicar el máximo de GFX subido al abrir y al despertar, solo mientras esto esté activado.", ocGfxLabel: "Máximo de GFX sobre el de fábrica", ocGfxFieldLabel: "Reloj máximo de GFX subido, en MHz", ocGfxStepperFormat: "Reloj máximo de GFX subido, pasos de %d MHz", @@ -141,10 +141,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "Ponto de partida recomendado: %d mV. Um ponto de partida para testar, não uma garantia.", voltUseRecommended: "Usar ponto de partida", voltApply: "Aplicar", - voltFooter: "Reduz toda a curva de tensão da GPU pela diferença em relação ao padrão: menos calor e menos consumo. Se ficar baixa demais, a GPU pode travar, reiniciar o driver ou deixar a tela preta. Desça 25 mV por vez, teste com um jogo ou benchmark e fique 10–20 mV acima do menor valor que foi estável. Volta ao padrão quando o RyzenStatus fecha, ao reiniciar e depois do repouso. Cada chip é diferente, mesmo no mesmo modelo de placa.", + voltFooter: "Reduz toda a curva de tensão da GPU pela diferença em relação ao padrão: menos calor e menos consumo. Se ficar baixa demais, a GPU pode travar, reiniciar o driver ou deixar a tela preta. Desça 25 mV por vez, teste com um jogo ou benchmark e fique 10–20 mV acima do menor valor que foi estável. Volta ao padrão quando o RyzenStatus fecha, ao reiniciar e depois do repouso. Com Lembrar ativado, o RyzenStatus aplica de novo ao abrir e ao despertar. Cada chip é diferente, mesmo no mesmo modelo de placa.", ocSection: "Overclock", ocToggle: "Permitir overclock", - ocWarning: "Dentro dos limites da própria AMD para esta placa nada pode queimar, mas um valor pode ser instável: a GPU pode travar ou reiniciar o driver. Tudo volta ao padrão ao desligar isto, quando o RyzenStatus fecha, ao reiniciar e depois do repouso, e o vigilante restaura o padrão a 95 °C.", + ocWarning: "Dentro dos limites da própria AMD para esta placa nada pode queimar, mas um valor pode ser instável: a GPU pode travar ou reiniciar o driver. Tudo volta ao padrão ao desligar isto, quando o RyzenStatus fecha, ao reiniciar e depois do repouso, e o vigilante restaura o padrão a 95 °C. Com Lembrar ativado, o RyzenStatus aplica de novo o máximo de GFX elevado ao abrir e ao despertar, só enquanto isto estiver ativado.", ocGfxLabel: "Máximo da GFX acima do padrão", ocGfxFieldLabel: "Clock máximo da GFX elevado em MHz", ocGfxStepperFormat: "Clock máximo da GFX elevado, passos de %d MHz", @@ -165,10 +165,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "Önerilen başlangıç noktası: %d mV. Denemek için bir başlangıç noktasıdır, garanti değildir.", voltUseRecommended: "Başlangıç noktasını kullan", voltApply: "Uygula", - voltFooter: "GPU'nun tüm gerilim eğrisini fabrika değerine olan fark kadar düşürür: daha az ısı ve daha az güç. Fazla düşükse GPU donabilir, sürücüsünü sıfırlayabilir veya siyah ekran gösterebilir. Her seferinde 25 mV düşürün, bir oyun veya benchmark ile deneyin ve kararlı kalan en düşük değerin 10–20 mV üstünde kalın. RyzenStatus kapanınca, yeniden başlatınca ve uykudan sonra fabrika değerine döner. Her çip farklıdır.", + voltFooter: "GPU'nun tüm gerilim eğrisini fabrika değerine olan fark kadar düşürür: daha az ısı ve daha az güç. Fazla düşükse GPU donabilir, sürücüsünü sıfırlayabilir veya siyah ekran gösterebilir. Her seferinde 25 mV düşürün, bir oyun veya benchmark ile deneyin ve kararlı kalan en düşük değerin 10–20 mV üstünde kalın. RyzenStatus kapanınca, yeniden başlatınca ve uykudan sonra fabrika değerine döner. Hatırla açıksa RyzenStatus bunu açılışta ve uyanınca yeniden uygular. Her çip farklıdır.", ocSection: "Hız aşırtma", ocToggle: "Hız aşırtmaya izin ver", - ocWarning: "AMD'nin bu kart için koyduğu sınırlar içinde hiçbir şey yanamaz, ama bir değer kararsız olabilir: GPU donabilir veya sürücüsünü sıfırlayabilir. Bunu kapattığınızda, RyzenStatus kapanınca, yeniden başlatınca ve uykudan sonra her şey fabrika değerine döner; bekçi 95 °C'de fabrika değerlerini geri getirir.", + ocWarning: "AMD'nin bu kart için koyduğu sınırlar içinde hiçbir şey yanamaz, ama bir değer kararsız olabilir: GPU donabilir veya sürücüsünü sıfırlayabilir. Bunu kapattığınızda, RyzenStatus kapanınca, yeniden başlatınca ve uykudan sonra her şey fabrika değerine döner; bekçi 95 °C'de fabrika değerlerini geri getirir. Hatırla açıksa RyzenStatus yükseltilmiş GFX üst sınırını açılışta ve uyanınca, yalnızca bu açıkken yeniden uygular.", ocGfxLabel: "Fabrika değerinin üstünde maks. GFX", ocGfxFieldLabel: "MHz cinsinden yükseltilmiş maks. GFX saat hızı", ocGfxStepperFormat: "Yükseltilmiş maks. GFX saat hızı, %d MHz adımlarla", @@ -189,10 +189,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "Рекомендуемая отправная точка: %d мВ. Это точка для проверки, а не гарантия.", voltUseRecommended: "Взять отправную точку", voltApply: "Применить", - voltFooter: "Снижает всю кривую напряжения GPU на разницу с заводским: меньше нагрев и потребление. Если слишком низко, GPU может зависнуть, перезапустить драйвер или показать чёрный экран. Снижайте по 25 мВ, проверяйте игрой или бенчмарком и держитесь на 10–20 мВ выше самого низкого стабильного значения. Возвращается к заводскому при выходе из RyzenStatus, при перезагрузке и после сна. Каждый чип отличается.", + voltFooter: "Снижает всю кривую напряжения GPU на разницу с заводским: меньше нагрев и потребление. Если слишком низко, GPU может зависнуть, перезапустить драйвер или показать чёрный экран. Снижайте по 25 мВ, проверяйте игрой или бенчмарком и держитесь на 10–20 мВ выше самого низкого стабильного значения. Возвращается к заводскому при выходе из RyzenStatus, при перезагрузке и после сна. Если включено «Запоминать», RyzenStatus снова задаёт его при запуске и после пробуждения. Каждый чип отличается.", ocSection: "Разгон", ocToggle: "Разрешить разгон", - ocWarning: "В пределах, которые AMD задаёт для этой карты, ничего не сгорит, но значение может быть нестабильным: GPU может зависнуть или перезапустить драйвер. Всё возвращается к заводскому, когда вы выключаете это, при выходе из RyzenStatus, при перезагрузке и после сна, а сторож возвращает заводские значения при 95 °C.", + ocWarning: "В пределах, которые AMD задаёт для этой карты, ничего не сгорит, но значение может быть нестабильным: GPU может зависнуть или перезапустить драйвер. Всё возвращается к заводскому, когда вы выключаете это, при выходе из RyzenStatus, при перезагрузке и после сна, а сторож возвращает заводские значения при 95 °C. Если включено «Запоминать», RyzenStatus снова задаёт повышенный максимум GFX при запуске и после пробуждения, только пока это включено.", ocGfxLabel: "Макс. частота GFX выше заводской", ocGfxFieldLabel: "Повышенная макс. частота GFX в МГц", ocGfxStepperFormat: "Повышенная макс. частота GFX, шаг %d МГц", @@ -213,10 +213,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "Odporúčaný východiskový bod: %d mV. Východiskový bod na skúšanie, nie záruka.", voltUseRecommended: "Použiť východiskový bod", voltApply: "Použiť", - voltFooter: "Zníži celú krivku napätia GPU o rozdiel oproti továrenskej hodnote: menej tepla a menšia spotreba. Ak je príliš nízko, GPU môže zamrznúť, reštartovať ovládač alebo ukázať čiernu obrazovku. Znižujte po 25 mV, skúšajte hrou alebo benchmarkom a zostaňte 10–20 mV nad najnižšou stabilnou hodnotou. Po ukončení RyzenStatus, reštarte a po spánku sa vráti na továrenskú hodnotu. Každý čip je iný.", + voltFooter: "Zníži celú krivku napätia GPU o rozdiel oproti továrenskej hodnote: menej tepla a menšia spotreba. Ak je príliš nízko, GPU môže zamrznúť, reštartovať ovládač alebo ukázať čiernu obrazovku. Znižujte po 25 mV, skúšajte hrou alebo benchmarkom a zostaňte 10–20 mV nad najnižšou stabilnou hodnotou. Po ukončení RyzenStatus, reštarte a po spánku sa vráti na továrenskú hodnotu. Keď je zapnuté Pamätať, RyzenStatus ho znova nastaví pri spustení a po prebudení. Každý čip je iný.", ocSection: "Pretaktovanie", ocToggle: "Povoliť pretaktovanie", - ocWarning: "V rámci limitov, ktoré AMD určuje pre túto kartu, nič nezhorí, ale hodnota môže byť nestabilná: GPU môže zamrznúť alebo reštartovať ovládač. Všetko sa vráti na továrenské hodnoty po vypnutí tejto voľby, po ukončení RyzenStatus, po reštarte a po spánku a strážca vráti továrenské hodnoty pri 95 °C.", + ocWarning: "V rámci limitov, ktoré AMD určuje pre túto kartu, nič nezhorí, ale hodnota môže byť nestabilná: GPU môže zamrznúť alebo reštartovať ovládač. Všetko sa vráti na továrenské hodnoty po vypnutí tejto voľby, po ukončení RyzenStatus, po reštarte a po spánku a strážca vráti továrenské hodnoty pri 95 °C. Keď je zapnuté Pamätať, RyzenStatus znova nastaví zvýšené maximum GFX pri spustení a po prebudení, len kým je táto voľba zapnutá.", ocGfxLabel: "Maximum GFX nad továrenskou hodnotou", ocGfxFieldLabel: "Zvýšený maximálny takt GFX v MHz", ocGfxStepperFormat: "Zvýšený maximálny takt GFX, kroky po %d MHz", @@ -237,10 +237,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "Empfohlener Startpunkt: %d mV. Ein Startpunkt zum Testen, keine Garantie.", voltUseRecommended: "Startpunkt verwenden", voltApply: "Anwenden", - voltFooter: "Senkt die ganze Spannungskurve der GPU um den Abstand zum Werkswert: weniger Wärme und weniger Verbrauch. Ist sie zu niedrig, kann die GPU einfrieren, ihren Treiber neu starten oder ein schwarzes Bild zeigen. Geh in Schritten von 25 mV nach unten, teste mit einem Spiel oder Benchmark und bleib 10–20 mV über dem niedrigsten stabilen Wert. Beim Beenden von RyzenStatus, beim Neustart und nach dem Ruhezustand geht sie auf den Werkswert zurück. Jeder Chip ist anders.", + voltFooter: "Senkt die ganze Spannungskurve der GPU um den Abstand zum Werkswert: weniger Wärme und weniger Verbrauch. Ist sie zu niedrig, kann die GPU einfrieren, ihren Treiber neu starten oder ein schwarzes Bild zeigen. Geh in Schritten von 25 mV nach unten, teste mit einem Spiel oder Benchmark und bleib 10–20 mV über dem niedrigsten stabilen Wert. Beim Beenden von RyzenStatus, beim Neustart und nach dem Ruhezustand geht sie auf den Werkswert zurück. Mit eingeschaltetem Merken setzt RyzenStatus sie beim Start und nach dem Aufwachen wieder. Jeder Chip ist anders.", ocSection: "Übertakten", ocToggle: "Übertakten erlauben", - ocWarning: "Innerhalb der Grenzen, die AMD für diese Karte selbst setzt, kann nichts durchbrennen, aber ein Wert kann instabil sein: Die GPU kann einfrieren oder ihren Treiber neu starten. Alles geht auf die Werkswerte zurück, wenn du das ausschaltest, wenn RyzenStatus beendet wird, beim Neustart und nach dem Ruhezustand, und der Wächter stellt bei 95 °C die Werkswerte wieder her.", + ocWarning: "Innerhalb der Grenzen, die AMD für diese Karte selbst setzt, kann nichts durchbrennen, aber ein Wert kann instabil sein: Die GPU kann einfrieren oder ihren Treiber neu starten. Alles geht auf die Werkswerte zurück, wenn du das ausschaltest, wenn RyzenStatus beendet wird, beim Neustart und nach dem Ruhezustand, und der Wächter stellt bei 95 °C die Werkswerte wieder her. Mit eingeschaltetem Merken setzt RyzenStatus das erhöhte GFX-Maximum beim Start und nach dem Aufwachen wieder, nur solange das hier eingeschaltet ist.", ocGfxLabel: "GFX-Maximum über dem Werkswert", ocGfxFieldLabel: "Erhöhter maximaler GFX-Takt in MHz", ocGfxStepperFormat: "Erhöhter maximaler GFX-Takt, Schritte von %d MHz", @@ -261,10 +261,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "Point de départ recommandé : %d mV. Un point de départ à tester, pas une garantie.", voltUseRecommended: "Utiliser le point de départ", voltApply: "Appliquer", - voltFooter: "Baisse toute la courbe de tension du GPU de l’écart avec la valeur d’usine : moins de chaleur et moins de consommation. Trop basse, le GPU peut se figer, réinitialiser son pilote ou afficher un écran noir. Descendez de 25 mV à la fois, testez avec un jeu ou un benchmark et restez 10 à 20 mV au-dessus de la plus basse valeur restée stable. Elle revient à la valeur d’usine quand RyzenStatus quitte, au redémarrage et après la veille. Chaque puce est différente.", + voltFooter: "Baisse toute la courbe de tension du GPU de l’écart avec la valeur d’usine : moins de chaleur et moins de consommation. Trop basse, le GPU peut se figer, réinitialiser son pilote ou afficher un écran noir. Descendez de 25 mV à la fois, testez avec un jeu ou un benchmark et restez 10 à 20 mV au-dessus de la plus basse valeur restée stable. Elle revient à la valeur d’usine quand RyzenStatus quitte, au redémarrage et après la veille. Avec Mémoriser activé, RyzenStatus la remet à l’ouverture et au réveil. Chaque puce est différente.", ocSection: "Overclocking", ocToggle: "Autoriser l’overclocking", - ocWarning: "Dans les limites qu’AMD fixe pour cette carte, rien ne peut griller, mais une valeur peut être instable : le GPU peut se figer ou réinitialiser son pilote. Tout revient aux valeurs d’usine quand vous désactivez ceci, quand RyzenStatus quitte, au redémarrage et après la veille, et le gardien remet les valeurs d’usine à 95 °C.", + ocWarning: "Dans les limites qu’AMD fixe pour cette carte, rien ne peut griller, mais une valeur peut être instable : le GPU peut se figer ou réinitialiser son pilote. Tout revient aux valeurs d’usine quand vous désactivez ceci, quand RyzenStatus quitte, au redémarrage et après la veille, et le gardien remet les valeurs d’usine à 95 °C. Avec Mémoriser activé, RyzenStatus remet le maximum GFX relevé à l’ouverture et au réveil, seulement tant que ceci est activé.", ocGfxLabel: "Maximum GFX au-dessus de l’usine", ocGfxFieldLabel: "Fréquence GFX maximale relevée en MHz", ocGfxStepperFormat: "Fréquence GFX maximale relevée, pas de %d MHz", @@ -285,10 +285,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "Punto di partenza consigliato: %d mV. Un punto di partenza da provare, non una garanzia.", voltUseRecommended: "Usa punto di partenza", voltApply: "Applica", - voltFooter: "Abbassa tutta la curva di tensione della GPU della differenza dal valore di fabbrica: meno calore e meno consumo. Se è troppo bassa, la GPU può bloccarsi, riavviare il driver o mostrare uno schermo nero. Scendi di 25 mV alla volta, prova con un gioco o un benchmark e resta 10–20 mV sopra il valore più basso rimasto stabile. Torna al valore di fabbrica quando RyzenStatus esce, al riavvio e dopo lo stop. Ogni chip è diverso.", + voltFooter: "Abbassa tutta la curva di tensione della GPU della differenza dal valore di fabbrica: meno calore e meno consumo. Se è troppo bassa, la GPU può bloccarsi, riavviare il driver o mostrare uno schermo nero. Scendi di 25 mV alla volta, prova con un gioco o un benchmark e resta 10–20 mV sopra il valore più basso rimasto stabile. Torna al valore di fabbrica quando RyzenStatus esce, al riavvio e dopo lo stop. Con Ricorda attivo, RyzenStatus la reimposta all’apertura e al risveglio. Ogni chip è diverso.", ocSection: "Overclock", ocToggle: "Consenti l’overclock", - ocWarning: "Entro i limiti che AMD stessa fissa per questa scheda non può bruciarsi nulla, ma un valore può essere instabile: la GPU può bloccarsi o riavviare il driver. Tutto torna ai valori di fabbrica quando lo disattivi, quando RyzenStatus esce, al riavvio e dopo lo stop, e il supervisore rimette i valori di fabbrica a 95 °C.", + ocWarning: "Entro i limiti che AMD stessa fissa per questa scheda non può bruciarsi nulla, ma un valore può essere instabile: la GPU può bloccarsi o riavviare il driver. Tutto torna ai valori di fabbrica quando lo disattivi, quando RyzenStatus esce, al riavvio e dopo lo stop, e il supervisore rimette i valori di fabbrica a 95 °C. Con Ricorda attivo, RyzenStatus reimposta il massimo GFX alzato all’apertura e al risveglio, solo finché questo è attivo.", ocGfxLabel: "Massimo GFX sopra quello di fabbrica", ocGfxFieldLabel: "Clock GFX massimo alzato in MHz", ocGfxStepperFormat: "Clock GFX massimo alzato, passi di %d MHz", @@ -309,10 +309,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "推奨の出発点: %d mV。試すための出発点であり、保証ではありません。", voltUseRecommended: "出発点を使う", voltApply: "適用", - voltFooter: "GPU の電圧カーブ全体を純正との差だけ下げます。発熱と消費電力が減ります。下げすぎると GPU がフリーズしたり、ドライバがリセットされたり、画面が真っ暗になったりします。25 mV ずつ下げてゲームやベンチマークで試し、安定した最低値より 10〜20 mV 上にとどめてください。RyzenStatus の終了時、再起動時、スリープ後に純正に戻ります。チップの個体差があります。", + voltFooter: "GPU の電圧カーブ全体を純正との差だけ下げます。発熱と消費電力が減ります。下げすぎると GPU がフリーズしたり、ドライバがリセットされたり、画面が真っ暗になったりします。25 mV ずつ下げてゲームやベンチマークで試し、安定した最低値より 10〜20 mV 上にとどめてください。RyzenStatus の終了時、再起動時、スリープ後に純正に戻ります。「覚える」がオンなら、RyzenStatus は起動時とスリープ解除時にもう一度設定します。チップの個体差があります。", ocSection: "オーバークロック", ocToggle: "オーバークロックを許可", - ocWarning: "AMD がこのカードに定めた範囲内なら壊れることはありませんが、値によっては不安定になり、GPU がフリーズしたりドライバがリセットされたりします。これをオフにしたとき、RyzenStatus の終了時、再起動時、スリープ後にはすべて純正に戻り、95 °C で監視が純正に戻します。", + ocWarning: "AMD がこのカードに定めた範囲内なら壊れることはありませんが、値によっては不安定になり、GPU がフリーズしたりドライバがリセットされたりします。これをオフにしたとき、RyzenStatus の終了時、再起動時、スリープ後にはすべて純正に戻り、95 °C で監視が純正に戻します。「覚える」がオンなら、これがオンの間だけ、RyzenStatus は起動時とスリープ解除時に引き上げた GFX 最大値をもう一度設定します。", ocGfxLabel: "純正を超える GFX 最大クロック", ocGfxFieldLabel: "引き上げた GFX 最大クロック(MHz)", ocGfxStepperFormat: "引き上げた GFX 最大クロック、%d MHz 刻み", @@ -333,10 +333,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "권장 시작점: %d mV. 시험해 볼 시작점이며 보장은 아닙니다.", voltUseRecommended: "시작점 사용", voltApply: "적용", - voltFooter: "GPU 전압 곡선 전체를 기본값과의 차이만큼 낮춥니다. 발열과 전력이 줄어듭니다. 너무 낮으면 GPU가 멈추거나, 드라이버가 재설정되거나, 화면이 검게 될 수 있습니다. 25 mV씩 낮추며 게임이나 벤치마크로 시험하고, 안정적이었던 가장 낮은 값보다 10~20 mV 위에 두세요. RyzenStatus를 종료할 때, 재시동할 때, 잠자기 후에는 기본값으로 돌아갑니다. 칩마다 차이가 있습니다.", + voltFooter: "GPU 전압 곡선 전체를 기본값과의 차이만큼 낮춥니다. 발열과 전력이 줄어듭니다. 너무 낮으면 GPU가 멈추거나, 드라이버가 재설정되거나, 화면이 검게 될 수 있습니다. 25 mV씩 낮추며 게임이나 벤치마크로 시험하고, 안정적이었던 가장 낮은 값보다 10~20 mV 위에 두세요. RyzenStatus를 종료할 때, 재시동할 때, 잠자기 후에는 기본값으로 돌아갑니다. 기억이 켜져 있으면 RyzenStatus가 실행할 때와 깨어날 때 다시 설정합니다. 칩마다 차이가 있습니다.", ocSection: "오버클럭", ocToggle: "오버클럭 허용", - ocWarning: "AMD가 이 카드에 정한 한도 안에서는 아무것도 타지 않지만, 값이 불안정할 수 있어 GPU가 멈추거나 드라이버가 재설정될 수 있습니다. 이 옵션을 끌 때, RyzenStatus를 종료할 때, 재시동할 때, 잠자기 후에는 모두 기본값으로 돌아가며, 95 °C에서는 감시가 기본값으로 되돌립니다.", + ocWarning: "AMD가 이 카드에 정한 한도 안에서는 아무것도 타지 않지만, 값이 불안정할 수 있어 GPU가 멈추거나 드라이버가 재설정될 수 있습니다. 이 옵션을 끌 때, RyzenStatus를 종료할 때, 재시동할 때, 잠자기 후에는 모두 기본값으로 돌아가며, 95 °C에서는 감시가 기본값으로 되돌립니다. 기억이 켜져 있으면 이 옵션이 켜져 있는 동안에만 RyzenStatus가 실행할 때와 깨어날 때 올린 GFX 최대값을 다시 설정합니다.", ocGfxLabel: "기본값을 넘는 최대 GFX", ocGfxFieldLabel: "높인 최대 GFX 클록(MHz)", ocGfxStepperFormat: "높인 최대 GFX 클록, %d MHz 단위", @@ -357,10 +357,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "推荐起点:%d mV。这是用来测试的起点,并非保证。", voltUseRecommended: "使用起点", voltApply: "应用", - voltFooter: "将整条 GPU 电压曲线按与出厂值的差值降低:发热和功耗都会减少。过低时 GPU 可能卡死、重置驱动或黑屏。每次降低 25 mV,用游戏或基准测试检验,并保持比最低稳定值高 10–20 mV。退出 RyzenStatus、重新启动和睡眠后会恢复出厂值。每颗芯片都不一样。", + voltFooter: "将整条 GPU 电压曲线按与出厂值的差值降低:发热和功耗都会减少。过低时 GPU 可能卡死、重置驱动或黑屏。每次降低 25 mV,用游戏或基准测试检验,并保持比最低稳定值高 10–20 mV。退出 RyzenStatus、重新启动和睡眠后会恢复出厂值。开启“记住”时,RyzenStatus 会在打开时和唤醒时重新设置。每颗芯片都不一样。", ocSection: "超频", ocToggle: "允许超频", - ocWarning: "在 AMD 为这张显卡设定的范围内不会烧坏任何东西,但某个数值可能不稳定:GPU 可能卡死或重置驱动。关闭此项时、退出 RyzenStatus、重新启动和睡眠后一切都会恢复出厂值,监控会在 95 °C 时恢复出厂值。", + ocWarning: "在 AMD 为这张显卡设定的范围内不会烧坏任何东西,但某个数值可能不稳定:GPU 可能卡死或重置驱动。关闭此项时、退出 RyzenStatus、重新启动和睡眠后一切都会恢复出厂值,监控会在 95 °C 时恢复出厂值。开启“记住”时,RyzenStatus 会在打开时和唤醒时重新设置提高的 GFX 最大值,仅限此项开启期间。", ocGfxLabel: "高于出厂值的 GFX 最大值", ocGfxFieldLabel: "提高后的 GFX 最大时钟频率(MHz)", ocGfxStepperFormat: "提高后的 GFX 最大时钟频率,步长 %d MHz", @@ -381,10 +381,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "建議起點:%d mV。這是用來測試的起點,並非保證。", voltUseRecommended: "使用起點", voltApply: "套用", - voltFooter: "將整條 GPU 電壓曲線依與原廠值的差值降低:發熱與耗電都會減少。太低時 GPU 可能當機、重設驅動程式或黑畫面。每次降低 25 mV,用遊戲或基準測試檢驗,並保持比最低穩定值高 10–20 mV。結束 RyzenStatus、重新開機與睡眠後會恢復原廠值。每顆晶片都不一樣。", + voltFooter: "將整條 GPU 電壓曲線依與原廠值的差值降低:發熱與耗電都會減少。太低時 GPU 可能當機、重設驅動程式或黑畫面。每次降低 25 mV,用遊戲或基準測試檢驗,並保持比最低穩定值高 10–20 mV。結束 RyzenStatus、重新開機與睡眠後會恢復原廠值。開啟「記住」時,RyzenStatus 會在打開時和喚醒時重新設定。每顆晶片都不一樣。", ocSection: "超頻", ocToggle: "允許超頻", - ocWarning: "在 AMD 為這張顯示卡設定的範圍內不會燒壞任何東西,但某個數值可能不穩定:GPU 可能當機或重設驅動程式。關閉此項時、結束 RyzenStatus、重新開機與睡眠後一切都會恢復原廠值,監控會在 95 °C 時恢復原廠值。", + ocWarning: "在 AMD 為這張顯示卡設定的範圍內不會燒壞任何東西,但某個數值可能不穩定:GPU 可能當機或重設驅動程式。關閉此項時、結束 RyzenStatus、重新開機與睡眠後一切都會恢復原廠值,監控會在 95 °C 時恢復原廠值。開啟「記住」時,RyzenStatus 會在打開時和喚醒時重新設定提高的 GFX 最大值,僅限此項開啟期間。", ocGfxLabel: "高於原廠值的 GFX 最大值", ocGfxFieldLabel: "提高後的 GFX 最大時脈(MHz)", ocGfxStepperFormat: "提高後的 GFX 最大時脈,間隔 %d MHz", @@ -405,10 +405,10 @@ extension GPUControlOverclockStrings { voltRecommendedFormat: "Рекомендована відправна точка: %d мВ. Це точка для перевірки, а не гарантія.", voltUseRecommended: "Узяти відправну точку", voltApply: "Застосувати", - voltFooter: "Знижує всю криву напруги GPU на різницю із заводською: менше нагріву й споживання. Якщо надто низько, GPU може зависнути, перезапустити драйвер або показати чорний екран. Знижуйте по 25 мВ, перевіряйте грою чи бенчмарком і тримайтеся на 10–20 мВ вище найнижчого стабільного значення. Повертається до заводської після виходу з RyzenStatus, перезавантаження та сну. Кожен чип інший.", + voltFooter: "Знижує всю криву напруги GPU на різницю із заводською: менше нагріву й споживання. Якщо надто низько, GPU може зависнути, перезапустити драйвер або показати чорний екран. Знижуйте по 25 мВ, перевіряйте грою чи бенчмарком і тримайтеся на 10–20 мВ вище найнижчого стабільного значення. Повертається до заводської після виходу з RyzenStatus, перезавантаження та сну. Якщо ввімкнено «Пам’ятати», RyzenStatus знову задає її під час запуску й після пробудження. Кожен чип інший.", ocSection: "Розгін", ocToggle: "Дозволити розгін", - ocWarning: "У межах, які AMD задає для цієї карти, нічого не згорить, але значення може бути нестабільним: GPU може зависнути або перезапустити драйвер. Усе повертається до заводського, коли ви вимикаєте це, після виходу з RyzenStatus, перезавантаження та сну, а сторож повертає заводські значення при 95 °C.", + ocWarning: "У межах, які AMD задає для цієї карти, нічого не згорить, але значення може бути нестабільним: GPU може зависнути або перезапустити драйвер. Усе повертається до заводського, коли ви вимикаєте це, після виходу з RyzenStatus, перезавантаження та сну, а сторож повертає заводські значення при 95 °C. Якщо ввімкнено «Пам’ятати», RyzenStatus знову задає підвищений максимум GFX під час запуску й після пробудження, лише поки це ввімкнено.", ocGfxLabel: "Макс. частота GFX вище заводської", ocGfxFieldLabel: "Підвищена макс. частота GFX у МГц", ocGfxStepperFormat: "Підвищена макс. частота GFX, крок %d МГц", diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift index 0b309321..ab6862b2 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift @@ -3,6 +3,7 @@ import AppKit import Foundation +import IOKit /// What the app asks GPUSensors.kext to hold. enum GPUControlRequest: Equatable, Hashable, Sendable { @@ -76,6 +77,28 @@ enum GPUControlOrigin: Equatable, Sendable { case remembered } +/// Which refusals of a remembered request are tried again (at launch and +/// after a wake). Only the ones that pass by themselves: the fan watchdog's +/// readings were not fresh yet (an OD8 state with a curve, a raised minimum +/// or the overclock flag; a raised power limit). "Busy", "not ready", "too +/// soon" and "sleeping" already wait for every request. Everything else is a +/// real answer (out of range, writing not allowed, another program holds +/// the control) and is never sent again by itself. +enum GPUControlRetryPolicy { + static func isTemporary(_ answer: GPUControlAnswer) -> Bool { + switch answer.reply { + case .noReadings?: return true + case .od8Refused?: return answer.check == .noReadings + default: return false + } + } + + /// Still inside the window that started with the first such refusal. + static func retries(firstRefusalAt since: UInt64, now: UInt64) -> Bool { + now < since + GPUControlEngine.temporaryRetryWindowMs + } +} + /// What the controller knows, for the page. `held` comes from `status` /// (mine, and the values match), never from what was asked. struct GPUControlSnapshot: Equatable, Sendable { @@ -147,6 +170,11 @@ final class GPUControlEngine { /// After a wake the kext goes back 2 to 12 s later; `mine` is not trusted /// and nothing is asked until this much has passed. static let wakeSettleMs: UInt64 = 15_000 + /// A remembered request the kext refused for a reason that passes (the + /// watchdog's readings were not fresh yet) is tried again this often... + static let temporaryRetryMs: UInt64 = 3_000 + /// ...for this long after the first such refusal, then the refusal stands. + static let temporaryRetryWindowMs: UInt64 = 30_000 private let channel: GPUControlChannel? private let clock: () -> UInt64 @@ -163,6 +191,12 @@ final class GPUControlEngine { /// right before it goes out (the stock GFX maximum moves across wakes): /// the request to send, or nil for nothing. var reaskFilter: ((GPUControlRequest) -> GPUControlRequest?)? + /// Right before an OD8 state or a raised power limit goes out: makes the + /// watchdog's readings fresh (the kext's PMLog copy only moves when + /// someone reads the accelerator's `PerformanceStatistics`, and the kext + /// refuses a curve, a raised minimum or a raise with readings older than + /// 2 s). Nil in tests. + var freshenReadings: (() -> Void)? private(set) var snapshot = GPUControlSnapshot() { didSet { if snapshot != oldValue { onSnapshot?(snapshot) } } @@ -173,6 +207,9 @@ final class GPUControlEngine { private var wanted: GPUControlRequest? private var wantedOrigin: GPUControlOrigin = .owner private var wantedSince: UInt64 = 0 + /// The first refusal of the waiting remembered request that passes by + /// itself (`GPUControlRetryPolicy`), nil before one. + private var temporarySince: UInt64? private var nextTryAt: UInt64 = 0 private var nextPollAt: UInt64 = 0 private var statusRequested = false @@ -232,6 +269,7 @@ final class GPUControlEngine { wanted = request wantedOrigin = origin wantedSince = now + temporarySince = nil nextTryAt = Swift.max(now, wokeAt.map { $0 + Self.wakeSettleMs } ?? 0) snapshot.outcome = nil } @@ -368,6 +406,7 @@ final class GPUControlEngine { wanted = held wantedOrigin = .remembered wantedSince = now + temporarySince = nil } } if wanted != nil { @@ -652,12 +691,14 @@ final class GPUControlEngine { // kext that takes it; an older one refuses the value either way. let status = snapshot.status let raise = status.map { $0.flags.contains(.raise) && $0.bootW != 0 && UInt64(watts) > $0.bootW } ?? false + if raise { freshenReadings?() } answer = channel.setPower(watts: watts, raise: raise) case .od8(let want): guard want.scalars() != nil else { refuse(request, GPUControlAnswer(replyCode: GPUControlReply.badArgs.rawValue)) return } + freshenReadings?() answer = channel.setOD8(want) case .startUp: return } @@ -721,10 +762,31 @@ final class GPUControlEngine { case .notArmed: notSent(.closed) default: + // A remembered request goes through at launch and after a wake + // with nobody watching: a refusal that passes by itself is tried + // again for a while. The owner's own choice shows it at once. + if wantedOrigin == .remembered, GPUControlRetryPolicy.isTemporary(answer) { + return retryTemporary(request, answer) + } refuse(request, answer) } } + /// A remembered request refused for a reason that passes: tried again + /// every `temporaryRetryMs` (never closer than the kext's 2 s between + /// writes), until `temporaryRetryWindowMs` after the first such refusal; + /// then the refusal stands and shows as any other. + private func retryTemporary(_ request: GPUControlRequest, _ answer: GPUControlAnswer) { + let now = clock() + let since = temporarySince ?? now + temporarySince = since + guard GPUControlRetryPolicy.retries(firstRefusalAt: since, now: now) else { + return refuse(request, answer) + } + snapshot.activity = .retrying(request, .reply(answer.reply ?? .od8Refused)) + nextTryAt = now + Self.temporaryRetryMs + } + // MARK: Closing (kext 0.8.0) /// One step of "close changes": the app's own hold goes back first; the @@ -798,6 +860,7 @@ final class GPUControlEngine { private func finishRequest() { wanted = nil + temporarySince = nil switching = false wokeAt = nil snapshot.activity = .none @@ -922,6 +985,13 @@ final class GPUControlController: @unchecked Sendable { queue.async { [self] in engine.reaskFilter = filter } } + /// What makes the watchdog's readings fresh right before an OD8 state or + /// a raised power limit goes out (`GPUControlReadings.freshen` with the + /// real kext). + func setFreshenReadings(_ freshen: @escaping @Sendable () -> Void) { + queue.async { [self] in engine.freshenReadings = freshen } + } + /// `applicationWillTerminate`: `release` at once on a helper thread, /// then close; waits `timeout` seconds at most. /// `release` answers right away and wins over a `set` already waiting in @@ -1005,3 +1075,27 @@ final class GPUControlController: @unchecked Sendable { private static func nowMs() -> UInt64 { DispatchTime.now().uptimeNanoseconds / 1_000_000 } } + +/// The fan watchdog's readings, from the app's side. GPUSensors.kext copies +/// the PMLog only when the driver reads it, and the driver reads it when +/// someone reads the accelerator's `PerformanceStatistics` (what +/// `ioreg -r -c IOAccelerator -l -d1` does too). One read right before a +/// change makes them fresh, whether or not the app's own GPU readings run +/// yet (right after launch, right after a wake). +enum GPUControlReadings { + /// Reads `PerformanceStatistics` of the first accelerator that has it. + /// The values are not used here; `IOAcceleratorCache` keeps its own. + static func freshen() { + var iterator: io_iterator_t = 0 + guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), + &iterator) == kIOReturnSuccess else { return } + defer { IOObjectRelease(iterator) } + while case let entry = IOIteratorNext(iterator), entry != 0 { + defer { IOObjectRelease(entry) } + if IORegistryEntryCreateCFProperty(entry, "PerformanceStatistics" as CFString, + kCFAllocatorDefault, 0)?.takeRetainedValue() != nil { + return + } + } + } +} diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift index d7bed525..0f22ef4a 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift @@ -508,14 +508,24 @@ enum GPUControlRememberPolicy { /// `gfxMin`: the GFX minimum the kext takes now (`GPUControlClockMinLogic /// .limits`), nil when it takes none (a kext before 0.9.0): a remembered /// minimum outside it is left out of the request, like the maximum. - /// This is the request at launch: a GFX voltage and every raise (a GFX - /// maximum above stock, a power limit above the start-up one) are never - /// asked for again here. A value that froze the Mac would freeze it again - /// at the next launch, and again. The rest of the state still goes. + /// `volt`: the card's range for the GFX voltage now + /// (`GPUControlVoltLogic.limits`), nil when the kext takes none: a + /// remembered voltage outside it is left out of the request. + /// `overclock`: the card's range for a raised GFX maximum + /// (`GPUControlOverclockLogic.gfxLimits`), and `overclockAllowed`: the + /// "Allow overclocking" switch. A remembered raised maximum goes only + /// with the switch on and inside that range; otherwise it is left out + /// with its flag (a lowered maximum stays). The owner's choice: a + /// voltage and a raised maximum come back at launch like the rest. + /// A power limit above the start-up one is still never asked for at + /// launch. The rest of the state still goes. static func request(remembered: GPUControlRemembered, active: Bool, facts: GPUControlFacts?, stopped: GPUControlStop?, stockGfxMaxMHz: Int? = nil, kextVersion: String? = nil, - gfxMin: GPUControlClockMinLogic.Limits? = nil) -> GPUControlRequest? { + gfxMin: GPUControlClockMinLogic.Limits? = nil, + volt: GPUControlVoltLogic.Limits? = nil, + overclock: GPUControlOverclockLogic.GfxLimits? = nil, + overclockAllowed: Bool = false) -> GPUControlRequest? { guard active, stopped == nil, let facts, facts.armed, !facts.off, facts.writeOffCode == 0, !(facts.owned && !facts.mine) else { return nil } switch remembered { @@ -527,28 +537,23 @@ enum GPUControlRememberPolicy { guard watts > 0, let boot = facts.bootW, watts < boot, GPUControlPageLogic.powerChoices(bootW: boot, range: facts.powerRange).contains(watts) else { return nil } return .power(watts: UInt32(watts)) - case .od8(var want): + case .od8(let want): // OD8 not read cleanly: the kext could not take it. guard facts.od8Ready else { return nil } // A fan state and another kext build: the rules were not checked // with it, and Apply is off too. Nothing goes, not even the clock: // only what was held is asked for again, never a part of it. if want.curve != nil || want.zeroRpmOff, !GPUControlCurveRules.isChecked(kextVersion) { return nil } - want = strippedAtLaunch(want) - if let mhz = want.gfxMaxMHz, !GPUControlClockLogic.lowers(mhz, stockGfxMaxMHz: stockGfxMaxMHz) { - want.gfxMaxMHz = nil - } - want = GPUControlClockMinLogic.checked(want, limits: gfxMin, stockGfxMaxMHz: stockGfxMaxMHz) - return want.isStock ? nil : .od8(want) + return checkedAgain(.od8(want), stockGfxMaxMHz: stockGfxMaxMHz, gfxMin: gfxMin, volt: volt, + overclock: overclock, overclockAllowed: overclockAllowed) } } - /// A remembered OD8 state without what is never asked for at launch: the - /// GFX voltage, and the overclock flag with the raised GFX maximum it - /// allowed (a lowered maximum stays). - static func strippedAtLaunch(_ want: GPUControlOD8Want) -> GPUControlOD8Want { + /// An OD8 state without its raise: the overclock flag with the raised + /// GFX maximum it allowed (a lowered maximum stays). What is left of a + /// remembered state while "Allow overclocking" is off. + static func withoutRaise(_ want: GPUControlOD8Want) -> GPUControlOD8Want { var want = want - want.voltMV = nil if want.overclock { want.overclock = false want.gfxMaxMHz = nil @@ -699,13 +704,16 @@ extension GPUControlRememberPolicy { /// goes), and so is a minimum the kext does not take now (`gfxMin` nil: /// a kext before 0.9.0, or no clean OD8 read). The same for a GFX voltage /// (`volt`) and a raised GFX maximum (`overclock`, the card's range for - /// it): kept only while the kext takes them and inside the card's range. - /// Nil when nothing is left to ask. + /// it): kept only while the kext takes them and inside the card's range, + /// and the raise only while "Allow overclocking" is on + /// (`overclockAllowed`). Nil when nothing is left to ask. static func checkedAgain(_ request: GPUControlRequest, stockGfxMaxMHz: Int?, gfxMin: GPUControlClockMinLogic.Limits? = nil, volt: GPUControlVoltLogic.Limits? = nil, - overclock: GPUControlOverclockLogic.GfxLimits? = nil) -> GPUControlRequest? { + overclock: GPUControlOverclockLogic.GfxLimits? = nil, + overclockAllowed: Bool = true) -> GPUControlRequest? { guard case .od8(var want) = request else { return request } + if !overclockAllowed { want = withoutRaise(want) } if let mhz = want.gfxMaxMHz { let raised = want.overclock && GPUControlOverclockLogic.raises(mhz, limits: overclock) if !raised, !GPUControlClockLogic.lowers(mhz, stockGfxMaxMHz: stockGfxMaxMHz) { want.gfxMaxMHz = nil } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift index 654d09a1..53e0e93f 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift @@ -4,6 +4,7 @@ import AppKit import Combine import Foundation +import os /// Whether the GPU control page and its panel row exist: only with a kext /// that has the write path (0.5.0 and later), or with the model in a @@ -72,11 +73,16 @@ final class GPUControlService: ObservableObject { didSet { guard overclock != oldValue else { return } defaults.set(overclock, forKey: DefaultsKey.gpuControlOverclock) + let on = overclock + overclockNow.withLock { $0 = on } if !overclock { controller?.dropRaises() } } } private let defaults: UserDefaults + /// The switch for the controller's queue: a remembered raise is checked + /// against it right before it goes out. + private let overclockNow = OSAllocatedUnfairLock(initialState: false) private var controller: GPUControlController? private var fake: FakeGPUControlKext? private var viewers = 0 @@ -93,7 +99,9 @@ final class GPUControlService: ObservableObject { init(defaults: UserDefaults = .standard) { self.defaults = defaults remember = defaults.bool(forKey: DefaultsKey.gpuControlRemember) - overclock = defaults.bool(forKey: DefaultsKey.gpuControlOverclock) + let on = defaults.bool(forKey: DefaultsKey.gpuControlOverclock) + overclock = on + overclockNow.withLock { $0 = on } } var facts: GPUControlFacts? { GPUControlPageLogic.facts(snapshot: snapshot, control: control) } @@ -134,6 +142,7 @@ final class GPUControlService: ObservableObject { } controller.setReaskAfterWake(rememberActive) let model = fake + let overclockNow = overclockNow controller.setReaskFilter { request in let control = model.flatMap(GPUControlService.fakeControl) ?? GPUSensorsService.shared.currentControl() let od8Ready = control?.writing?.od8Read == .read @@ -141,8 +150,12 @@ final class GPUControlService: ObservableObject { request, stockGfxMaxMHz: control?.writing?.od8?.stockGfxMaxMHz, gfxMin: GPUControlClockMinLogic.limits(writing: control?.writing, od8Ready: od8Ready), volt: GPUControlVoltLogic.limits(writing: control?.writing, od8Ready: od8Ready), - overclock: GPUControlOverclockLogic.gfxLimits(writing: control?.writing, od8Ready: od8Ready)) + overclock: GPUControlOverclockLogic.gfxLimits(writing: control?.writing, od8Ready: od8Ready), + overclockAllowed: overclockNow.withLock { $0 }) } + // The kext refuses a curve or a raise while the watchdog's readings + // are older than 2 s: one read right before each such change. + if mode == .real { controller.setFreshenReadings { GPUControlReadings.freshen() } } controller.start() self.controller = controller if mode == .real { startForeignWatch() } @@ -447,12 +460,18 @@ final class GPUControlService: ObservableObject { GPUControlRemembered.nothing.save(defaults) return } + let writing = control?.writing if let request = GPUControlRememberPolicy.request(remembered: remembered, active: rememberActive, facts: facts, stopped: snapshot?.stopped, - stockGfxMaxMHz: control?.writing?.od8?.stockGfxMaxMHz, - kextVersion: control?.writing?.kextVersion, + stockGfxMaxMHz: writing?.od8?.stockGfxMaxMHz, + kextVersion: writing?.kextVersion, gfxMin: GPUControlClockMinLogic.limits( - writing: control?.writing, od8Ready: facts.od8Ready)) { + writing: writing, od8Ready: facts.od8Ready), + volt: GPUControlVoltLogic.limits( + writing: writing, od8Ready: facts.od8Ready), + overclock: GPUControlOverclockLogic.gfxLimits( + writing: writing, od8Ready: facts.od8Ready), + overclockAllowed: overclock) { controller.choose(request, origin: .remembered) } } diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlFanSection.swift b/Sources/RyzenStatus/UI/Settings/GPUControlFanSection.swift index 1e01f7d9..c53458e1 100644 --- a/Sources/RyzenStatus/UI/Settings/GPUControlFanSection.swift +++ b/Sources/RyzenStatus/UI/Settings/GPUControlFanSection.swift @@ -54,7 +54,7 @@ struct GPUControlFanSection: View { // "Toggles": the label says what turning it on does ("Writing"). // The regular size, not mini: "Accessibility" asks for at least // 20 x 20 pt on macOS (a11y A8). - Toggle(fan.zeroRpmToggle, isOn: $draft.zeroRpmOff) + Toggle(fan.zeroRpmToggle, isOn: Binding(get: { draft.zeroRpmOff }, set: { zeroRpmSwitched($0) })) .toggleStyle(.switch) .controlSize(.regular) .disabled(!enabled) @@ -135,6 +135,28 @@ struct GPUControlFanSection: View { /// How far the curve editor sits in from its switch. static let editorIndent: CGFloat = 20 + /// The zero RPM switch. While a curve is held it goes out at once with + /// that curve, as the clock and voltage controls do; otherwise it is part + /// of the draft "Apply curve" sends. Point edits not applied yet stay in + /// the editor and are not sent with it. + private func zeroRpmSwitched(_ on: Bool) { + let otherEdits = draft.want.curve != heldOD8.curve + draft.zeroRpmOff = on + guard enabled, let send = Self.zeroRpmAtOnce(held: heldOD8, zeroRpmOff: on), + GPUControlCurvePreview.make(want: send.want, writing: input.writing).allowsApply else { return } + lastOD8Source = .fan + apply(send) + if !otherEdits { draft = draft.applied } + } + + /// What the zero RPM switch sends by itself: the held curve with the new + /// zero RPM state, only while a curve is held and the state changes. Nil + /// otherwise (the switch then only edits the draft). + static func zeroRpmAtOnce(held: GPUControlOD8Want, zeroRpmOff: Bool) -> GPUControlFanDraft? { + guard let curve = held.curve, held.zeroRpmOff != zeroRpmOff else { return nil } + return GPUControlFanDraft(held: GPUControlOD8Want(curve: curve, zeroRpmOff: zeroRpmOff)) + } + private func applyDraft() { lastOD8Source = .fan apply(draft) diff --git a/Tests/Suites/GPUControlFanTests.swift b/Tests/Suites/GPUControlFanTests.swift index 5326d9c2..25d2d4a9 100644 --- a/Tests/Suites/GPUControlFanTests.swift +++ b/Tests/Suites/GPUControlFanTests.swift @@ -284,6 +284,35 @@ enum GPUControlFanTests { suite.expect(!GPUControlFanDraft(held: held).givesBack(held), "a curve over a curve: Apply") suite.expect(!GPUControlFanDraft().givesBack(GPUControlOD8Want(curve: held.curve, gfxMaxMHz: 2_000)), "a clock held too: not the whole way back, so Apply") + + // The zero RPM switch while a curve is held goes out at once with + // the held curve (it did nothing until "Apply curve" before, while the + // switch already read on). + let curveHeld = GPUControlOD8Want(curve: GPUControlFanDraft.testedCurve, gfxMaxMHz: 2_404, voltMV: 1_000, + overclock: true) + let atOnce = GPUControlFanSection.zeroRpmAtOnce(held: curveHeld, zeroRpmOff: true) + suite.expect(atOnce?.want == GPUControlOD8Want(curve: GPUControlFanDraft.testedCurve, zeroRpmOff: true), + "zero RPM on over a held curve: the held curve and the fan always on, at once") + var curveAndZero = curveHeld + curveAndZero.zeroRpmOff = true + suite.expect(GPUControlFanSection.zeroRpmAtOnce(held: curveAndZero, zeroRpmOff: false)?.want + == GPUControlOD8Want(curve: GPUControlFanDraft.testedCurve), + "and off again: the held curve alone, at once") + suite.expect(GPUControlFanSection.zeroRpmAtOnce(held: curveAndZero, zeroRpmOff: true) == nil, + "no change from what is held: nothing sent") + suite.expect(GPUControlFanSection.zeroRpmAtOnce(held: .stock, zeroRpmOff: true) == nil + && GPUControlFanSection.zeroRpmAtOnce(held: GPUControlOD8Want(gfxMaxMHz: 2_000), zeroRpmOff: true) == nil, + "no curve held: the switch is part of the draft for Apply") + // Through the controller: the held clocks and voltage go with it. + do { + let h = Harness { $0.takesOverclock = true } + h.engine.choose(.od8(curveHeld)) + h.run(ms: 3_000) + if let send = atOnce { h.engine.chooseFan(curve: send.want.curve, zeroRpmOff: send.want.zeroRpmOff) } + h.run(ms: 0) + suite.expect(h.engine.snapshot.held == .od8(curveAndZero) && h.replies(.setOD8) == 2, + "zero RPM over a held curve, voltage and raise: one call, all of it held") + } } // MARK: The controller against the model diff --git a/Tests/Suites/GPUControlOverclockTests.swift b/Tests/Suites/GPUControlOverclockTests.swift index f652ade4..6ed5af90 100644 --- a/Tests/Suites/GPUControlOverclockTests.swift +++ b/Tests/Suites/GPUControlOverclockTests.swift @@ -5,8 +5,9 @@ import Foundation /// GPUSensors 0.9.0's GFX voltage and raises: the wire forms and numbers, /// the rules one step past every limit, the recommended starting point, the -/// model and the controller, what is never asked for again at launch, the -/// overclock switch, the gating, the words. +/// model and the controller, what is asked for again at launch and after a +/// wake, the retries of a remembered request, the overclock switch, the +/// gating, the words. enum GPUControlOverclockTests { static func run(_ suite: TestSuite) { wire(suite) @@ -16,6 +17,7 @@ enum GPUControlOverclockTests { model(suite) controller(suite) remembering(suite) + retries(suite) gating(suite) strings(suite) } @@ -313,26 +315,151 @@ enum GPUControlOverclockTests { let f = facts() let minLimits = GPUControlClockMinLogic.Limits(min: 500, max: 2_800, stock: 500) - func atLaunch(_ remembered: GPUControlRemembered) -> GPUControlRequest? { + let volt = GPUControlVoltLogic.Limits(min: 881, stock: 1_075) + let up = GPUControlOverclockLogic.GfxLimits(stock: 2_359, max: 2_800) + func atLaunch(_ remembered: GPUControlRemembered, overclockOn: Bool = true, + takesVolt: Bool = true, takesRaise: Bool = true) -> GPUControlRequest? { Policy.request(remembered: remembered, active: true, facts: f, stopped: nil, stockGfxMaxMHz: 2_359, - gfxMin: minLimits) + gfxMin: minLimits, volt: takesVolt ? volt : nil, overclock: takesRaise ? up : nil, + overclockAllowed: overclockOn) } - suite.expect(atLaunch(.od8(all)) == .od8(Want(gfxMinMHz: 1_500)), - "at launch: no voltage and no raised maximum, the rest still asked for") - suite.expect(atLaunch(.od8(Want(gfxMaxMHz: 2_000, voltMV: 1_050))) == .od8(Want(gfxMaxMHz: 2_000)), - "at launch: a lowered maximum stays, the voltage goes") - suite.expect(atLaunch(.od8(Want(voltMV: 1_050))) == nil, "a voltage alone: nothing asked for at launch") + // The owner's day: a curve, the fan always on, 1000 mV and 2404 MHz + // with overclock (stock 2354 that day). + let owner = Want(curve: GPUControlFanDraft.testedCurve, zeroRpmOff: true, gfxMaxMHz: 2_404, voltMV: 1_000, + overclock: true) + let ownerFacts = Policy.request(remembered: .od8(owner), active: true, facts: f, stopped: nil, + stockGfxMaxMHz: 2_354, kextVersion: "REL-090-2026-11-25", + gfxMin: minLimits, volt: volt, + overclock: GPUControlOverclockLogic.GfxLimits(stock: 2_354, max: 2_800), + overclockAllowed: true) + suite.expect(ownerFacts == .od8(owner), "at launch: the whole remembered state, voltage and raise included") + suite.expect(atLaunch(.od8(all)) == .od8(all), "at launch with overclocking allowed: everything as it was") + suite.expect(atLaunch(.od8(all), overclockOn: false) == .od8(Want(gfxMinMHz: 1_500, voltMV: 1_050)), + "at launch with overclocking off: no raised maximum and no flag, the voltage and the rest go") + suite.expect(atLaunch(.od8(Want(gfxMaxMHz: 2_000, voltMV: 1_050)), overclockOn: false) + == .od8(Want(gfxMaxMHz: 2_000, voltMV: 1_050)), + "at launch: a lowered maximum and the voltage stay, switch or not") + suite.expect(atLaunch(.od8(Want(voltMV: 1_050))) == .od8(Want(voltMV: 1_050)), + "a voltage alone is asked for at launch") + suite.expect(atLaunch(.od8(Want(voltMV: 1_050)), takesVolt: false) == nil, + "a voltage with a kext that takes none: nothing asked for") + suite.expect(atLaunch(.od8(Want(voltMV: 1_060))) == nil && atLaunch(.od8(Want(voltMV: 850))) == nil, + "a voltage off the 25 mV steps or below the card's minimum: left out") + suite.expect(atLaunch(.od8(Want(gfxMaxMHz: 2_600, overclock: true)), takesRaise: false) == nil, + "a raised maximum with a kext that takes no raise: nothing asked for") + suite.expect(atLaunch(.od8(Want(gfxMaxMHz: 2_900, overclock: true))) == nil, + "a raised maximum past the card's top: left out") suite.expect(atLaunch(.power(watts: 250)) == nil && atLaunch(.power(watts: 230)) == .power(watts: 230), "a limit above start-up is never asked for at launch; a lower one is") // After a wake, in the same run: they follow the remember switch. - let volt = GPUControlVoltLogic.Limits(min: 881, stock: 1_075) - let up = GPUControlOverclockLogic.GfxLimits(stock: 2_359, max: 2_800) suite.expect(Policy.checkedAgain(.od8(all), stockGfxMaxMHz: 2_359, gfxMin: minLimits, volt: volt, overclock: up) == .od8(all), "after a wake: asked again as it was") suite.expect(Policy.checkedAgain(.od8(all), stockGfxMaxMHz: 2_359, gfxMin: minLimits) == .od8(Want(gfxMinMHz: 1_500)), "after a wake with a kext that takes neither: the rest") + suite.expect(Policy.checkedAgain(.od8(all), stockGfxMaxMHz: 2_359, gfxMin: minLimits, volt: volt, overclock: up, + overclockAllowed: false) == .od8(Want(gfxMinMHz: 1_500, voltMV: 1_050)), + "after a wake with overclocking off: no raise, the voltage stays") suite.expect(Policy.checkedAgain(.power(watts: 250), stockGfxMaxMHz: 2_359) == .power(watts: 250), "a raised limit after a wake: asked again") + // Saved again once held: the voltage and the raise stay remembered. + suite.expect(Policy.toSave(held: .od8(owner), ownerChoseStartUp: false, active: true) == .od8(owner), + "a restored state is saved whole") + } + + // MARK: Retries of a remembered request + + private static func retries(_ suite: TestSuite) { + typealias Retry = GPUControlRetryPolicy + func answer(_ reply: GPUControlReply, _ check: GPUControlOD8Check = .ok) -> GPUControlAnswer { + GPUControlAnswer(replyCode: reply.rawValue, checkCode: check.rawValue) + } + suite.expect(Retry.isTemporary(answer(.od8Refused, .noReadings)) && Retry.isTemporary(answer(.noReadings)), + "no fresh watchdog readings (OD8 or a raised limit): passes by itself") + let real: [GPUControlAnswer] = [ + answer(.od8Refused, .voltRange), answer(.od8Refused, .gfxRange), answer(.od8Refused, .curveCooling), + answer(.od8Refused, .notRead), answer(.od8Refused, .noFeature), answer(.aboveCeiling), + answer(.belowFloor), answer(.notPrivileged), answer(.badArgs), answer(.stillApplied), + GPUControlAnswer(replyCode: 99), + ] + suite.expect(real.allSatisfy { !Retry.isTemporary($0) }, + "out of range, not offered, not allowed or unknown: never tried again by itself") + suite.expect(Retry.retries(firstRefusalAt: 1_000, now: 30_999) && !Retry.retries(firstRefusalAt: 1_000, now: 31_000), + "tried again for 30 s after the first such refusal") + suite.expect(GPUControlEngine.temporaryRetryMs >= GPUControlWire.minChangeGapMs, + "retries are never closer than the kext's 2 s between writes") + + let curve = Want(curve: GPUControlFanDraft.testedCurve, gfxMaxMHz: 2_404, voltMV: 1_000, overclock: true) + // At launch the readings are not fresh yet: tried again until they are. + do { + let h = Harness { $0.takesOverclock = true; $0.dogSees = false } + h.engine.choose(.od8(curve), origin: .remembered) + h.run(ms: 0) + suite.expect(h.replies(.setOD8) == 1 && h.held == nil && h.engine.snapshot.outcome == nil, + "no fresh readings: refused, no refusal shown yet") + if case .retrying(.od8(curve), _) = h.engine.snapshot.activity {} else { + suite.expect(false, "no fresh readings: the remembered request waits to be tried again") + } + h.run(ms: 10_000) + h.fake.dogSees = true + h.run(ms: 5_000) + suite.expect(h.held == .od8(curve) && h.engine.snapshot.outcome == nil, + "readings fresh again: the remembered state is held") + suite.expect(h.replies(.setOD8) >= 3 && h.gapsKept, "tried again, never closer than 2 s") + } + // Readings that never come: the refusal stands after 30 s. + do { + let h = Harness { $0.takesOverclock = true; $0.dogSees = false } + h.engine.choose(.od8(curve), origin: .remembered) + h.run(ms: 40_000) + if case .refused(.od8(curve), let a)? = h.engine.snapshot.outcome { + suite.expect(a.check == .noReadings, "after 30 s: the kext's refusal shows") + } else { + suite.expect(false, "after 30 s: the kext's refusal shows") + } + let tries = h.replies(.setOD8) + suite.expect(tries >= 8 && tries <= 12, "about one try every 3 s for 30 s (\(tries))") + h.run(ms: 30_000) + suite.expect(h.replies(.setOD8) == tries, "and nothing more") + } + // The owner's own choice shows the refusal at once. + do { + let h = Harness { $0.takesOverclock = true; $0.dogSees = false } + h.engine.choose(.od8(curve)) + h.run(ms: 10_000) + suite.expect(h.replies(.setOD8) == 1 && h.engine.snapshot.outcome.map { if case .refused = $0 { true } else { false } } == true, + "the owner's choice: refused once, shown at once") + } + // A real refusal is never tried again, remembered or not. + do { + let h = Harness { $0.takesOverclock = true } + h.engine.choose(.od8(Want(voltMV: 1_060)), origin: .remembered) + h.run(ms: 30_000) + suite.expect(h.replies(.setOD8) == 1, "a voltage off the steps: one call, never again") + } + // A raised power limit without readings, remembered after a wake. + do { + let h = Harness { $0.takesOverclock = true; $0.dogSees = false } + h.engine.choose(.power(watts: 250), origin: .remembered) + h.run(ms: 6_000) + h.fake.dogSees = true + h.run(ms: 5_000) + suite.expect(h.held == .power(watts: 250) && h.replies(.set) >= 2, + "a raised limit refused for readings: tried again, then held") + } + // The read that makes the readings fresh comes right before the call. + do { + let h = Harness { $0.takesOverclock = true; $0.dogSees = false } + var reads = 0 + h.engine.freshenReadings = { [fake = h.fake] in reads += 1; fake.dogSees = true } + h.engine.choose(.od8(curve), origin: .remembered) + h.run(ms: 0) + suite.expect(reads == 1 && h.replies(.setOD8) == 1 && h.held == .od8(curve), + "fresh readings first: taken at the first call") + h.run(ms: 3_000) + h.engine.choose(.power(watts: 230)) + h.run(ms: 3_000) + suite.expect(reads == 1, "a lower power limit needs no readings: no read") + } } // MARK: Gating diff --git a/docs/GPU_CONTROL.md b/docs/GPU_CONTROL.md index caef3c0e..9bf06a5c 100644 --- a/docs/GPU_CONTROL.md +++ b/docs/GPU_CONTROL.md @@ -66,9 +66,9 @@ only filled in, never applied by itself, and it is a value to test, not a promis What can go wrong: too low a voltage makes the GPU unstable. A game or benchmark freezes, the driver resets, or the screen goes black and the Mac has to be restarted. Nothing is -damaged and nothing is kept: after the restart the card starts at stock, and RyzenStatus -never sends a voltage again by itself at launch (only after a wake, if Remember is on). -Every chip is different. +damaged: after the restart the card starts at stock. With Remember on, RyzenStatus sends +the same voltage again at launch and after a wake: if a voltage froze the Mac, turn Remember +off or set the voltage back to stock before you test again. Every chip is different. How to use it: go down 25 mV at a time, run a game or a benchmark for a while after each step, and once you find the lowest value that is stable, go back up 10 to 20 mV and keep @@ -94,8 +94,9 @@ always inside the card's own OverDrive limits and never past them: There are no suggested values here. Inside AMD's limits nothing can burn, but a value can be unstable: freezes and driver resets mean the clock is too high for the voltage. Everything goes back to stock when you turn the section off, when RyzenStatus quits, on restart and -after sleep, and raised values are never sent again by themselves at launch. The watchdog -holds every raise (95 °C). +after sleep. With Remember on, a raised GFX maximum is sent again at launch and after a +wake, only while Allow overclocking is on; a raised power limit is sent again after a wake, +never at launch. The watchdog holds every raise (95 °C). More clock rarely gains anything without more power, and the two are held separately (see above). Raising the clock on a card with a lowered power limit mostly adds heat.