diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a1b99673..2fceeb61 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,6 +74,13 @@ jobs: - name: AMD concurrency gate run: ./Tools/concurrency-gate.sh + # 1.90.0 shipped an installer that called /usr/bin/chown, which is not there on macOS; + # every install stopped after the password. This reads what the root installers and the + # installer window name and fails on a path this runner does not have, before any disk + # image is built. + - name: Installer command paths + run: zsh GPU/tests/command_paths.sh + # Build and packaging are independent of the tests. Running them in parallel # keeps the PR's wall clock near the longer half instead of their sum; a # failed test job still fails the workflow and release.yml only reuses a run diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fc504a5..2ac2f573 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,58 @@ # Changelog +## [1.90.1] — 2026-11-26 — kexts 3.42.0 (No kext changes) + +**Videos keep playing through a system sleep with every GPU decoder, GPU sensors keep their readings fresh while a GPU setting is held, and fixes in the GPU installer.** The AMD processor kexts stay at 3.42.0, so your EFI's CPU kexts need no change. If you use the RyzenStatus GPU parts, open the RyzenStatus GPU installer in the disk image's "GPU RX 6000" folder to update the decoders to 0.3.9 and GPU sensors to 0.9.3. + +### GPU decoders (0.3.9) + +- **A sleep in the middle of a frame**: when the Mac slept while a frame was on the GPU, AV1 and VP9 video stopped with an error right after the wake. That frame is now dropped and the decoder starts over at the next key frame, and the first frame on it gets the longer limit a GPU coming out of a sleep needs. +- **MPEG-2, VC-1 and MPEG-4 after a sleep**: these decoders now live through a sleep too. The pictures up to the next I picture are dropped without an error and the video carries on from there. +- **VP9 with references of another size**: a frame that predicts from a picture more than twice as small (spatial SVC streams) is refused instead of showing a wrong picture, and a frame that fails no longer leaves AV1 or VP9 decoding the next frames against older pictures. +- **A session that ends starts clean**: ending an MPEG-2, VC-1 or MPEG-4 session clears the picture dropping a sleep rebuild uses, so a video that stops and plays again does not keep dropping pictures from the old session; the rebuild after a sleep turns that dropping back on as before. +- **A rebuild that fails after a sleep closes the session cleanly**: when AV1 or VP9 cannot recreate its GPU context after the wake, the session is closed on the background queue like every other close, never from the decode thread. +- **A stream with no I picture after a sleep stops instead of dropping forever**: MPEG-2, VC-1 and MPEG-4 now fail with a device failure after 600 pictures dropped without an I picture, like AV1 and VP9 already do, so the player can hand the stream to another decoder. +- **A reference of another bit depth** (AV1): a frame whose reference picture is another bit depth is refused instead of asking the driver to rebuild its picture buffers underneath a running frame (the same check VP9 makes of its references). +- **A cut-short sequence header** (AV1): a sequence header that fails to parse leaves the stored one in place instead of emptying it mid-stream. +- **A VP9 profile that does not match the stream's bit depth**: such a frame is refused, and the stream's bit depth stays as the stream set it. +- The line written after a queued session close now carries the reason the session was dropped (for example "the system slept since it opened") instead of calling every dropped session stuck or lost, and a decoder that cannot create its log falls back to the system's default log. + +### GPU sensors (0.9.3) + +- **Fresh readings while a setting is held**: with a fan curve, a clock or voltage change or a raised power limit held, GPUSensors takes the card's readings itself once a second, so the temperature watchdog keeps working when nothing else is reading the card. Nothing extra is asked of the card while nothing is held. +- **No crash after a sleep**: the reading the kext takes itself no longer uses the power object it saw before a sleep. Loading a GPU profile some minutes after a wake could crash the Mac; now the kext waits until the driver reads the card again after the wake. +- RyzenStatus finds the card's accelerator by the driver's real class name, so the statistics it reads from it refresh again. +- The number of AMD GPUs the kext reports was read through the wrong channel and always came back 0, so the GPU temperatures and powers the kext publishes were never taken. The count is now read as the scalar the kext answers with. + +### GPU control (needs GPUSensors.kext) + +- **Zero RPM**: the switch goes out together with the held fan curve, and it is checked against the whole state the card will get. When that state is refused, the reason shows next to the switch. +- **The refusal note follows the card**: when a later reading would let the held state go out, the note next to the Zero RPM switch clears by itself; while the state is still refused, the note stays. + +### GPU installer + +- **AMFI**: the installer also sees AMFI switched off with `amfi=0x80`, and an AMFIPass switched off with `-amfipassoff` or `-liluoff`, before it decides whether the loader is needed. +- Building the install plan no longer says that a password is coming; only the steps that need one do. +- The installer carries 1.90.1's install scripts and all the decoders (AV1, VP9, MPEG-2, VC-1, MPEG-4, Motion JPEG). +- Every command the installers run is now checked before a release, so a tool missing on macOS (1.90.0's `/usr/bin/chown`) cannot ship again. +- **Interrupting the EFI search leaves nothing mounted**: the installer mounts EFI partitions to look inside them for OpenCore; interrupting it between the mount and the unmount used to leave the partition mounted. The interrupt now unmounts it like a normal end of the run. +- **An interrupted encoding fix run cleans up after itself**: the exit cleanup was set inside the install step and stopped at its first function call, so a failed or interrupted run left the staged package copy in `/private/tmp`. One top-level trap now unmounts the EFI and removes the staged copy however the run ends. +- **The encoding fix's `--efi` is validated**: a value that is not a partition like `disk0s1` or `auto` is rejected with a usage message before anything is opened. +- **The undo plan leaves the encoding fix alone when OpenCore's start partition is not an EFI partition**: the plan skips the encoding fix step and says to run it by hand with `--efi diskNsM`, instead of searching other EFI partitions for it. +- **Access control lists are seen on folders that also carry extended attributes**: the folder checks read the wrong column of the listing when an entry showed `@`, so an ACL slipped past; the checks now look at the ACL lines themselves. +- **The parts already installed are named right**: when an install stops partway, the "Done before it:" line now spells the tools entry out (`gpucontrol and gpusensors`) beside the other parts instead of printing `tools`. +- **An aborted kext removal keeps its record**: when the EFI kext remover stops because config.plist cannot be edited, its install record is not deleted, so a later check still reports the kext as installed on that EFI. +- **The sensors uninstaller says when its record could not be written**: until the restart, the check cannot tell the kext was removed here; the uninstaller prints that note when the record write fails. + +### AMD Ryzen Power + +- **Per-CCD and all-core clock overrides report success again**: the kext answers those writes with eight values, and with no room reserved for them the call came back failed even though the write had already gone through. Both write paths reserve the room now. +- Auto EPP no longer stalls the interface while it sets or lifts the idle clock limit. + +### Fans + +- **The manual fan's thermal guard survives App Nap**: with every RyzenStatus window closed, macOS could coalesce the timer that watches the temperature while a manual fan curve is held. The app holds an App Nap activity while that guard polls and lets it go when the poll stops; system sleep is still allowed. + ## [1.90.0] — 2026-11-26 — kexts 3.42.0 (No kext changes) **More GPU control (minimum clock, undervolt, overclock and profiles), HDR colour and a fix for decoding after sleep in the GPU decoders, optional MPEG-2, VC-1, MPEG-4 and Motion JPEG decoders, FaceTime and Continuity Camera fixes in the encoding fix, and an AWDL line in the Network card.** The AMD processor kexts stay at 3.42.0, so your EFI's CPU kexts need no change. If you use the RyzenStatus GPU parts, open the RyzenStatus GPU installer in the disk image's "GPU RX 6000" folder to update the decoders to 0.3.7, the encoding fix to 1.3.0 and GPU sensors to 0.9.0. @@ -19,9 +72,10 @@ - **HDR colour (decoders 0.3.7)**: AV1 and VP9 pictures now carry their colour and HDR information, so HDR video is no longer shown washed out. Not tested on the GPU yet. - **After a sleep (decoders 0.3.7)**: a video that was playing before a sleep keeps decoding after the wake and switches to fresh decoder state at its next key frame, without dropping frames. 0.3.6 was never released: in a real sleep test it made those videos fail. +- **One window for all the GPU parts**: the GPU installer now has JPEG and MPEG-2, VC-1 and MPEG-4 boxes next to the encoding fix and GPU sensors ones. They start ticked when that part is on this Mac, so an update keeps what you installed instead of taking it off, and all of them can be installed or removed from there without Terminal. - **MPEG-2, VC-1 and MPEG-4 decoders (optional, macOS 26.7.2 to 26.7.4)**: hardware decoding of these older formats on the RX 6800 XT. Not installed by default: run `install/install.sh --with-legacy-decoders` from the GPU parts. Installed, they replace Apple's decoders for these formats. MPEG-4 streams with B-frames are left to Apple's decoder, and MPEG-2 field pictures are not decoded on the GPU. - **JPEG and Motion JPEG decoder (optional, macOS 26.7.3 only)**: decodes JPEG and Motion JPEG video on the card's JPEG block. Not installed by default: `install/install.sh --with-jpeg`. It needs a reboot, and the block is powered only while pictures arrive. -- **Encoding fix 1.3.0**: Continuity Camera and FaceTime video are decoded by the GPU instead of the CPU, and with a MacPro7,1 or iMacPro1,1 SMBIOS FaceTime's encoder no longer looks for a T2 chip, so outgoing video works. This part is for macOS 15.8.2, 26.7.2 and 26.7.3 and is turned off with `--no-cc`. Not tried in a real FaceTime call yet. +- **Encoding fix 1.3.0**: Continuity Camera and FaceTime video are decoded by the GPU instead of the CPU, and with a MacPro7,1 or iMacPro1,1 SMBIOS FaceTime's encoder no longer looks for a T2 chip, so outgoing video works. This part is for macOS 14.8.9, 15.8.2, 15.8.3, 26.7.3 and 26.7.4 and is turned off with `--no-cc`. Not tried in a real FaceTime call yet. - **macOS 26.7.4**: the decoders and the encoding fix know 26.7.4's drivers. Checked from the installer only, not run on a card with 26.7.4 yet. ### Network diff --git a/GPU/CHANGELOG.md b/GPU/CHANGELOG.md index b67c3c51..fc2b0e16 100644 --- a/GPU/CHANGELOG.md +++ b/GPU/CHANGELOG.md @@ -2,6 +2,136 @@ The encoding fix keeps its own history in `encode/CHANGELOG.md`. +## GPU sensors 0.9.3 (host tests only, not booted) + +- **The keeper is gone.** 0.9.1's keeper, which called + `PEM_CWDDEPM_QueryPMLogData` from the kext's own worker thread through the power + management object the driver had used, panicked this Mac twice on 2026-11-27 (02:42 and + 02:45, both while a remembered GPU profile was applied; one 34 s after boot). The library + cleared a word of that object while the call was running: `PECI_LockPowerPlayOnly(pem[4])` + succeeded and `PECI_UnlockPowerPlayOnly` then read `pem[4]` as NULL (CR2 0x180, RDI 0). + 0.9.2 checked the object before the call and could not see a clear in the middle of it, so + the kext no longer calls into the library at all: `sampleNow`, `keeperStep`, their counters + and the `Keeper` and `KeeperState` properties are removed, and the power management object + is no longer stored. The kext still copies the PMLog the driver reads (the routed function + is unchanged); the app reads the accelerator's `PerformanceStatistics` at least once a + second while it holds a fan curve, an OD8 state or a raised power limit, which is what makes + the driver read. 0.9.2's other fixes stay: the copy is dropped at sleep and teardown, and a + ppCWDDE call is refused when the sleep or wake watcher did not route. +- The app's checked releases are 080, 081, 090 and 093; 091 and 092 are dropped (0.9.1 and + 0.9.2 panicked, and neither was published). A loaded GPUSensors older than the package this + app carries, or outside that set, turns GPU control off and the page says to open the + installer from the DMG and install the GPU package again: auto-update replaces the app but + not the kexts. + +## GPU sensors 0.9.2 (host tests only, not booted) + +- **Kernel panic after a sleep (found on this Mac, 2026-11-27)**: a GPU profile loaded about five minutes after a wake started the keeper, which called `PEM_CWDDEPM_QueryPMLogData` with the power object stored before the sleep; its `pem[2]` was already NULL and the library faulted in `PSM_IsIPState` (page fault at 0x27c). The object seen while the GPU sleeps (ppSleep to the end of ppWake) is no longer stored, the stored one is dropped at every wake, and the keeper asks only once the driver read with an object after that wake. It also refuses an object whose `pem[2]`, `pem[3]` or `pem[4]` is NULL, and the pointer is now written before its sleep count and read after it (audit findings K2 and K3). +- A second review of the fix: the keeper checks the object right before the call, the PowerPlay object is dropped when the GPU goes away, and a ppCWDDE call is refused when the sleep or wake watcher did not route (findings F1, F3, F4; none of them reproduces the panic). +- The app's checked releases gain 092. + +## Decoders 0.3.9 (not released; host tests only) + +- The MPEG-2, VC-1 and MPEG-4 decoders now live through a system sleep the way AV1 and VP9 + have since 0.3.8. A session from before the sleep keeps its place in the plug-in: the + pictures up to the next I picture are dropped with no error, that one starts a new session, + and the pictures after it decode on it. Before, every picture of such a session was a + malfunction, so VideoToolbox made a new decoder for each one and the stream stopped at the + first picture after the wake. +- The picture that starts the new session is intra coded in all three codecs, so it decodes + the same in a session that has seen nothing: an MPEG-2 I picture (ISO/IEC 13818-2 6.3.1), a + VC-1 I or BI frame (SMPTE 421M 7.1.1.3) or an MPEG-4 I-VOP (ISO/IEC 14496-2 6.3.3). A GOP + header's `closed_gop` says the pictures after the I need nothing from before it; with an + open GOP, or with `broken_link` set, the leading B pictures predict from the previous GOP, + which the new session never decoded, and are dropped too instead of drawn wrong. +- A driver call that fails, a command that does not finish and a firmware error are still a + session stopped, as before: only a system sleep is something to rebuild from. +- VP9 refuses a frame whose reference picture is more than 2x smaller than the frame. The + video engine predicts from such a reference wrong: the 1280x720 layer of the spatial-SVC + vector `vp90-2-22-svc_1280x720_3` (320x180 reference, 4x) matched libvpx's per-frame MD5 on + 0 of 20 pictures, right only in its first 180 rows, while references 1.25x, 1.6x and 2x + smaller or larger (`vp90-2-05-resize`, `vp90-2-06-resize`, `vp90-2-13-mv-with-scaling`) + matched on 113 of 113. The frame is refused as a stream failure instead of showing a + wrong picture; whether VideoToolbox then plays it with another decoder was not checked. + Ratios between 2x and 4x were not measured and are refused too. The rule comes from Izzy's 1caa8b41 in vcn-video-decoders. +- A frame that fails, in VP9 and AV1, empties the reference slots it should have refreshed, + so the frames that predict from them are refused ("missing reference") until a frame + refreshes those slots, instead of decoding against older pictures. +- In AV1 and VP9, a `CreateContexts` failure during the rebuild after a sleep closes the + session on the background teardown queue, like the success path does, never on the decode + thread (24d1300a). +- Ending a session in MPEG-2, MPEG-4 and VC-1 now also clears its ramping state and dropped + count; the sleep rebuild still sets ramping again right after it (24d1300a). +- The MPEG-2, MPEG-4 and VC-1 rebuilds after a sleep are bounded like the AV1 and VP9 ones: + a stream that sends no intra picture is stopped as a device failure after 600 dropped + frames, so the host can hand it to another decoder, instead of dropping pictures for as + long as the stream goes without one (7e9c2940). +- The AV1 decoder refuses a reference picture of another bit depth than the frame (the + sequence header changed mid-stream, and with it the depth the DPB is allocated at), failed + like a missing reference so the host can recover, as VP9 already did (7e9c2940). +- The AV1 parser keeps the sequence header it has when a new one is refused (one cut short, + say), so frames after it still parse with the stored header; a different valid header + replaces it (0e6e5df5). +- The VP9 parser refuses a frame whose profile does not match the stream's bit depth (a + profile 0 frame after a 10-bit profile 2 key frame, say), with the stream's depth as it + was; libvpx ties the depth to the profile the same way (0e6e5df5). +- A queued close's log lines now say why the session was closed, not just "stuck" or + "lost", so a session dropped after a sleep is logged with its real reason (7e9c2940, + 4e5fc126). The queued close keeps its own reference to the log it logs with (the close may + give up the caller's last one) and never retains or releases the default log; where + `os_log_create` returns nothing, the AV1, VP9 and legacy decoders fall back to that + default log (7e9c2940, 4e5fc126). + +## Decoders 0.3.8 (not released; host tests only) + +- A review of 0.3.7 found five things to fix in the sleep work; this release is those fixes. +- A sleep that lands inside a decode call is no longer taken for a broken GPU. The clock the + 1 s timeout is measured on stops while the Mac is asleep, so the frame that was on the GPU + when it slept times out right after the wake, and 0.3.7 stopped the session there with + -12911. The session is now rebuilt the way any other failure after a wake is: the frame is + dropped with no error, the frames up to the next key frame too, and the key frame decodes + on the new driver (AV1 and VP9). +- The rule for where a session can start over is in one place per codec, with a test: + an AV1 key frame that refreshes all eight slots; a VP9 key frame, or a VP9 intra-only + frame that refreshes all eight and resets all four probability contexts + (error-resilient mode or `reset_frame_context` 3), as in 0.3.7. +- The 15 s limit now also covers the first command on the rebuilt session. Right after a wake + the engine can still take seconds, and 0.3.7 gave the fresh context the usual 1 s, which + could stop a healthy session on its first frame. +- The old accelerator is now always closed on the background queue, not on the thread that + decoded the key frame. The quiet path (the last command had finished) closed it inline, + where the kernel's close of a video context can still wait after a wake. +- The replacement log line now says what the old driver objects cost (up to 96 MiB per + replacement, not returned until the process ends), so the log accounts for them where they + are left behind, not only when such a session is closed. +- A dead counter (`rebuilds`) is gone. +- The firmware-result rule of 0.3.7 is unchanged: a nonzero result on a session from before a + sleep still forces the replacement. What each value means has not been checked on a GPU, + so reacting to all of them is the safe side; the real sleep test measures whether a + healthy wake ever reports one. + +## Decoders 0.3.7 (not released; host tests only) + +## GPU sensors 0.9.1 (host tests only, not booted) + +- The readings keep up when nothing outside polls them. The driver reads the PMLog only when + someone reads the accelerator's `PerformanceStatistics`, so with nothing polling it the kext's + copy went stale and the fan watchdog refused a held curve, a raised GFX minimum or a raised + power limit with "no fresh hotspot and fan readings"; the app worked around it by reading the + statistics right before each write, and the owner's test script ran an `ioreg` loop every 0.5 s. + While something is held, the kext's worker now asks the library for that reading itself, once a + second, and stops as soon as nothing is held. +- It is the call the driver makes, not a new one: `PEM_CWDDEPM_QueryPMLogData`, the function the + kext already routes (AMDRadeonX6000HWLibs 25G342, `0xf6322`): it clears the 2052-byte log, + returns before touching the card when the GPU's IP block is off or hardware access is blocked, + takes PowerPlay's lock and asks the power firmware for the metrics table. One message a second + while something is held, nothing otherwise, on the worker thread with none of the kext's locks + held. After a wake it only asks a power management object the driver itself read with since that + wake. +- `Keeper` (what the keeper is doing, or why not) and `KeeperState` (`Tries`, `Samples`, + `Refused`, `LastResult`) are published next to the readings. The app's read before each write + (`GPUControlReadings.freshen()`) is no longer needed with this kext, and still does no harm. + ## JPEG decoder 1.0.0 (RyzenStatus 1.90.0) - New, optional, macOS 26.7.3 only: `VCNJpeg.kext` (`jpeg/`) and the VideoToolbox plug-in @@ -384,6 +514,30 @@ made-up driver. ## Installers and gpusensors (not released) +- `encoder.sh --efi` now takes only a partition like `disk0s1` or `auto`, the check + `install.sh` and `undo.sh` already make; anything else stops with a usage error before + anything is changed (b8e36c28). +- `undo.sh` no longer takes another EFI in the place of the one OpenCore started from when + that is not an EFI partition: the encoder step is left out of the plan and the printout + says to run `install/encoder.sh uninstall --efi diskNsM` by hand (b8e36c28). +- The access-control-list checks of `common.zsh` (`gpu_dir_unsafe`) and `sensors.sh` see an + entry that also has extended attributes: they look at the ACL lines `ls -lde` prints after + the first one, where an `@` for the attributes used to hide the `+` for the ACL (b8e36c28). +- The "Done before it:" line of `install.sh` spells "gpucontrol and gpusensors" out for the + `tools` part itself, so the list names every part however many ran before; the old + substitution inside the join only matched a list of exactly one (b8e36c28). +- `efikext.zsh` removes a kext's install record only after the `config.plist` check that can + still stop the uninstall, so a run that changes nothing leaves the record, and `check`'s + answer with it, as it was (b8e36c28). +- `encoder.sh` cleans up through one exit trap at the top of the script: the one it set + inside `do_install`/`do_uninstall` was function-local and stopped at its first function + call when an exit unwound through it, so the staged copy of the package stayed in + `/private/tmp` on every failed or interrupted run (64de787e). +- `sensors.sh uninstall` says so when it cannot write the removal record: until the restart, + `check` cannot tell the kext was removed here (24d1300a). +- `install.sh` unmounts the EFI partition it mounted while looking for OpenCore when the run + is stopped with Ctrl-C (or killed) during that search, instead of leaving it mounted + (74f6d771). - `decoders.sh install` and `repair` copy each plug-in under another name, check it, and only then put it in place of the old one: a copy that fails half way leaves the installed plug-in as it was. The system volume they mount is unmounted again when they end. diff --git a/GPU/decode/VERSION b/GPU/decode/VERSION index 0f826853..940ac09a 100644 --- a/GPU/decode/VERSION +++ b/GPU/decode/VERSION @@ -1 +1 @@ -0.3.7 +0.3.9 diff --git a/GPU/decode/av1/av1parse.c b/GPU/decode/av1/av1parse.c index 748141ab..cf26ff11 100644 --- a/GPU/decode/av1/av1parse.c +++ b/GPU/decode/av1/av1parse.c @@ -1481,7 +1481,12 @@ static int parse_obus(AV1Parser* p, const uint8_t* data, size_t size, switch (obu_type) { case OBU_SEQUENCE_HEADER: { BR b = {payload, obu_size, 0, false}; - if (parse_sequence_header(&b, &p->seq)) return -1; + // Parse into a local and store it only on success, so a header cut + // short leaves the stored one as it was (the frame-header case below + // does the same for the reference slots). + AV1Seq seq; + if (parse_sequence_header(&b, &seq)) return -1; + p->seq = seq; break; } case OBU_TEMPORAL_DELIMITER: diff --git a/GPU/decode/av1/vcnav1.c b/GPU/decode/av1/vcnav1.c index 36bc19fa..ad115ccc 100644 --- a/GPU/decode/av1/vcnav1.c +++ b/GPU/decode/av1/vcnav1.c @@ -71,12 +71,16 @@ struct VcnAV1 { // it is rebuilt at the next key frame (on_frame). bool rebuildAtKey; unsigned keptAfterWake; // frames decoded on it since the sleep was seen - bool needKey; // rebuilt after a failure: drop frames until a key frame - unsigned dropped; // frames dropped since that rebuild - unsigned rebuilds; // driver objects rebuilt in this session (one per sleep) - uint32_t lastFw; // firmware result of the last command that finished - int failure; // VCNAV1_FAIL_* of the last error - bool shown; // the current decode call output a frame + bool needKey; // rebuilt after a failure: drop frames until a key frame + unsigned dropped; // frames dropped since that rebuild + // The long limit applies to the first command on the rebuilt session too: + // right after a wake the engine can still take seconds, and a timeout there + // would stop a session that is healthy. Cleared by the first command that + // finishes on it. + bool wakeGrace; + uint32_t lastFw; // firmware result of the last command that finished + int failure; // VCNAV1_FAIL_* of the last error + bool shown; // the current decode call output a frame CVPixelBufferRef hidden; // retained: last frame it decoded without showing unsigned fwErrors; // decodes the firmware reported as failed unsigned done; // decode commands that finished @@ -89,6 +93,7 @@ static os_log_t vlog(void) { static dispatch_once_t once; dispatch_once(&once, ^{ l = os_log_create("com.droga.vtav1vcn", "driver"); + if (!l) l = OS_LOG_DEFAULT; }); return l; } @@ -282,11 +287,10 @@ VcnAV1* vcnav1_create(uint32_t maxWidth, uint32_t maxHeight, char* err, // plug-in session, so the host's decoder object lives on. The references live // in the old driver's DPB, so the DPB pictures and the reference slots go; the // parser keeps the sequence header (a key frame does not always repeat it) and -// the frame header being decoded. busy: the old session's last command may -// still be on the GPU, so its accelerator is closed on the teardown queue and -// the pictures are let go only after that. False when the rebuild fails: the -// caller then stops the session as PR 160 did. -static bool av1_rebuild(VcnAV1* d, bool busy, char* why, size_t whyLen) { +// the frame header being decoded. The old accelerator is closed on the teardown +// queue, never on this thread (see the note below). False when the rebuild +// fails: the caller then stops the session as PR 160 did. +static bool av1_rebuild(VcnAV1* d, char* why, size_t whyLen) { CVPixelBufferRef old[NUM_DPB + 1]; int n = 0; for (int i = 0; i < NUM_DPB; i++) @@ -298,20 +302,23 @@ static bool av1_rebuild(VcnAV1* d, bool busy, char* why, size_t whyLen) { old[n++] = d->hidden; d->hidden = NULL; } - if (busy) { - // Without memory for the list the pictures are never let go: a command - // still on the GPU may write into them. - CVPixelBufferRef* keep = n ? malloc((size_t)n * sizeof(*keep)) : NULL; - if (keep) memcpy(keep, old, (size_t)n * sizeof(*keep)); - int kept = keep ? n : 0; - vcn_session_drop_later(&d->s, "AV1 session from before the sleep", ^{ - for (int i = 0; i < kept; i++) CVPixelBufferRelease(keep[i]); - free(keep); - }); - } else { - vcn_session_drop(&d->s); - for (int i = 0; i < n; i++) CVPixelBufferRelease(old[i]); - } + // The old accelerator always goes on the teardown queue, not on this thread: + // its close still shuts three IOKit user clients, and on the kernel side the + // close of a video context goes through PowerPlay's notify, which can wait + // after a failed wake (vcnsession.c, vcn_session_close). Nothing of the new + // session waits for it, and the pictures are let go only after it, because a + // command the wake dropped may still write into them. 0.3.7 closed it here + // whenever the last command had finished, which is the normal path and the + // one the teardown queue exists for. Without memory for the list the pictures + // are never let go. + CVPixelBufferRef* keep = n ? malloc((size_t)n * sizeof(*keep)) : NULL; + if (keep) memcpy(keep, old, (size_t)n * sizeof(*keep)); + int kept = keep ? n : 0; + vcn_session_drop_later(&d->s, "AV1 session from before the sleep", + "the system slept since it opened", ^{ + for (int i = 0; i < kept; i++) CVPixelBufferRelease(keep[i]); + free(keep); + }); vcnav1_flush(d); d->bsNext = 0; VcnDriverLib lib; @@ -330,21 +337,20 @@ static bool av1_rebuild(VcnAV1* d, bool busy, char* why, size_t whyLen) { int r = av1_create_context(d); if (r) { snprintf(why, whyLen, "CreateContexts(AV1) %d", r); - vcn_session_drop(&d->s); + vcn_session_drop_later(&d->s, "AV1 session, CreateContexts failed", + "no command was ever sent to it", ^{}); return false; } - d->rebuilds++; return true; } // Rebuilds now (av1_rebuild) and leaves the session decoding on the new driver; // dropUntilKey: the frames before the next key frame are dropped. False, with // the session stopped as a device failure, when the rebuild fails. -static bool rebuild_now(VcnAV1* d, bool busy, bool dropUntilKey, - const char* cause) { +static bool rebuild_now(VcnAV1* d, bool dropUntilKey, const char* cause) { char why[200]; unsigned kept = d->keptAfterWake; - if (!av1_rebuild(d, busy, why, sizeof(why))) { + if (!av1_rebuild(d, why, sizeof(why))) { d->rebuildAtKey = false; d->broken = true; d->failure = VCNAV1_FAIL_DEVICE; @@ -360,29 +366,36 @@ static bool rebuild_now(VcnAV1* d, bool busy, bool dropUntilKey, d->keptAfterWake = 0; d->needKey = dropUntilKey; d->dropped = 0; + // A fresh context may still be coming out of the wake: the first command on + // it gets the long limit (0.3.7 gave it the usual second straight away). + d->wakeGrace = true; if (dropUntilKey) os_log_error( vlog(), "the session from before the sleep failed after the wake " "(%{public}s, %u frames decoded on it before): driver rebuilt, " - "frames are dropped until the next key frame", - cause, kept); + "frames are dropped until the next key frame; the old driver objects " + "stay allocated, up to %d MiB not returned to the system", + cause, kept, + (int)(VCN_NUM_BS * (long long)VCN_BS_SIZE / (1024 * 1024))); else os_log_error(vlog(), "driver rebuilt at the first key frame after the sleep (%u " "frames decoded on the session from before it), no frame " - "dropped", - kept); + "dropped; the old driver objects stay allocated, up to %d MiB " + "not returned to the system", + kept, + (int)(VCN_NUM_BS * (long long)VCN_BS_SIZE / (1024 * 1024))); return true; } // The session from before the sleep failed on the frame being decoded: it is // rebuilt at once and this frame is dropped, like the ones after it until a // key frame. 0, or -1 when the rebuild fails. -static int failed_after_wake(VcnAV1* d, bool busy) { +static int failed_after_wake(VcnAV1* d) { char cause[256]; snprintf(cause, sizeof(cause), "%s", d->err); - if (!rebuild_now(d, busy, true, cause)) return -1; + if (!rebuild_now(d, true, cause)) return -1; d->err[0] = 0; d->failure = VCNAV1_FAIL_STREAM; d->dropped = 1; @@ -405,7 +418,8 @@ static void destroy_now(VcnAV1* d) { void vcnav1_destroy(VcnAV1* d) { if (!d) return; - vcn_teardown(d->stuck, vcn_session_lost(&d->s), vlog(), "AV1 session", ^{ + vcn_teardown(d->stuck, vcn_session_lost(&d->s), vlog(), "AV1 session", NULL, + ^{ destroy_now(d); }); } @@ -677,10 +691,11 @@ static int submit(VcnAV1* d, AV1Params* prm, double* sched, double* wait) { } uint32_t fw = 0; int ds = 0; - // Longer on the session from before a sleep: right after a wake the driver - // can take seconds before a command runs (vcndriver.h). - unsigned limit = - d->rebuildAtKey ? vcn_wake_command_timeout_ms : VCN_COMMAND_TIMEOUT_MS; + // Longer on the session from before a sleep, and until one command on the + // rebuilt one has finished: right after a wake the driver can take seconds + // before a command runs (vcndriver.h). + unsigned limit = d->rebuildAtKey || d->wakeGrace ? vcn_wake_command_timeout_ms + : VCN_COMMAND_TIMEOUT_MS; VcnWaitResult w = vcn_wait_command(FN(QueryAVDCommandStatus), d->s.drv, refcons[0], limit, &fw, &ds); *sched = t1 - t0; @@ -690,6 +705,22 @@ static int submit(VcnAV1* d, AV1Params* prm, double* sched, double* wait) { // The GPU still holds this command. Sending more work, or reading the // target, could only make things worse: the session stops here. d->stuck = d->broken = true; + // Unless the system slept inside this call. The timeout is measured on a + // clock that stops while the machine is asleep, so the frame that was on + // the GPU when it slept times out right after the wake, and nothing looked + // again at the sleep: 0.3.7 stopped the session there instead of rebuilding + // it, which is the one thing 0.3.7 exists to avoid. + if (!d->rebuildAtKey && vcn_session_lost(&d->s)) { + d->rebuildAtKey = true; + d->keptAfterWake = 0; + os_log_error(vlog(), + "the system slept while a frame was on the GPU: the frame " + "was given up on after the wake, the session is rebuilt"); + snprintf(d->err, sizeof(d->err), + "the GPU did not finish the frame in %u ms after the sleep", + limit); + return -1; + } snprintf(d->err, sizeof(d->err), "the GPU did not finish a frame in %u ms; session stopped", limit); return -1; @@ -704,6 +735,9 @@ static int submit(VcnAV1* d, AV1Params* prm, double* sched, double* wait) { d->failure = VCNAV1_FAIL_STREAM; d->done++; d->lastFw = fw; + // One command finished on the rebuilt session: the engine came back, and the + // usual limit applies again. + d->wakeGrace = false; // Counted, not refused: what each firmware result means for the picture // has not been checked on a GPU yet. The first one of a session is logged // at once, the count goes in the stats line. @@ -721,21 +755,17 @@ static bool seq_supported(const AV1Seq* s) { !s->mono_chrome && s->subsampling_x == 1 && s->subsampling_y == 1; } -static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { +static int decode_one(void* vctx, AV1Parser* p, AV1ParseResult kind) { VcnAV1* d = vctx; const AV1Frame* h = &p->fh; - // A key frame that refreshes every reference slot (a shown key frame always - // does): nothing decoded before it is used after it, so the driver objects - // can be replaced here without losing a frame. A hidden key frame that keeps - // some slots is not one: the frames after it may still use those. - bool restart = kind == AV1_PARSE_FRAME_READY && - h->frame_type == AV1_KEY_FRAME && - h->refresh_frame_flags == 0xFF; + // A frame nothing decoded before it is used after: a key frame that + // refreshes all eight slots (vcnav1_is_restart). A hidden key frame that + // keeps some slots is not one: the frames after it may still use those. + bool restart = vcnav1_is_restart(h, kind); // The system slept since the driver side opened, and it kept decoding (a // real sleep on this Mac did not break it): it is replaced at the first such - // key frame, which then decodes on the new one. - if (d->rebuildAtKey && restart && !rebuild_now(d, false, false, NULL)) - return -1; + // frame, which then decodes on the new one. + if (d->rebuildAtKey && restart && !rebuild_now(d, false, NULL)) return -1; // After a rebuild that followed a failure nothing from before it can be // used: every frame but such a key frame is dropped (no picture for this // sample, which is what a hidden frame looks like to the host, not an @@ -796,6 +826,19 @@ static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { d->failure = VCNAV1_FAIL_REFERENCE; return -1; } + // A reference of another bit depth means the sequence header changed + // mid-stream; the message sets the depth for the whole DPB, and a new + // depth makes the driver allocate it again while the frame reads from + // it (the same check vcnvp9.c makes of its references). Failed like the + // missing reference above: the stream's references are the problem, not + // the device. + if (r->bit_depth != p->seq.BitDepth) { + snprintf(d->err, sizeof(d->err), + "%d-bit reference for a %d-bit frame", r->bit_depth, + p->seq.BitDepth); + d->failure = VCNAV1_FAIL_REFERENCE; + return -1; + } } if (w > d->maxW || hh > d->maxH) { snprintf(d->err, sizeof(d->err), "%ux%u is over the session maximum", w, @@ -875,12 +918,12 @@ static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { if (submit(d, &prm, &tSched, &tWait)) // On the session from before a sleep, a driver failure is taken for the // sleep's doing: rebuilt at once, instead of stopping the session. - return d->rebuildAtKey && d->broken ? failed_after_wake(d, d->stuck) : -1; + return d->rebuildAtKey && d->broken ? failed_after_wake(d) : -1; if (d->rebuildAtKey) { if (d->lastFw) { // A firmware error on it after the wake: its picture is not trusted. snprintf(d->err, sizeof(d->err), "firmware result %u", d->lastFw); - return failed_after_wake(d, false); + return failed_after_wake(d); } d->keptAfterWake++; } @@ -925,6 +968,21 @@ int vcnav1_configure(VcnAV1* d, const uint8_t* obus, size_t size) { return 0; } +// A frame that was not decoded leaves the reference slots it should have +// refreshed holding older pictures. Frames that predict from them would decode +// without an error and show a wrong picture, so those slots are emptied: the +// frames that read them are refused ("missing reference") until a frame +// refreshes them again, which is how libaom treats a frame it could not decode. +static int on_frame(void* vctx, AV1Parser* p, AV1ParseResult kind) { + int r = decode_one(vctx, p, kind); + if (r && kind == AV1_PARSE_FRAME_READY) { + for (int i = 0; i < 8; i++) + if (p->fh.refresh_frame_flags & (1u << i)) p->ref[i].valid = 0; + release_slot_refs((VcnAV1*)vctx); + } + return r; +} + int vcnav1_decode(VcnAV1* d, const uint8_t* tu, size_t size, int64_t userTag, VcnAV1OutputFn fn, void* ctx) { d->out = fn; diff --git a/GPU/decode/av1/vcnav1.h b/GPU/decode/av1/vcnav1.h index d027f1a3..ec1c3043 100644 --- a/GPU/decode/av1/vcnav1.h +++ b/GPU/decode/av1/vcnav1.h @@ -33,6 +33,18 @@ int vcnav1_decode(VcnAV1* d, const uint8_t* tu, size_t size, int64_t userTag, VcnAV1OutputFn fn, void* ctx); // Drop all reference state (e.g. after a seek) void vcnav1_flush(VcnAV1* d); + +// True when a parsed frame is a place a session can start over: nothing decoded +// before it is used after it, which in AV1 is a key frame that refreshes all +// eight slots. An intra-only frame cannot be one: the spec makes +// refresh_frame_flags 0xFF on an intra-only frame a conformance error (dav1d +// refuses it in strict mode, src/obu.c), so such a frame always keeps a slot a +// later frame may read. +#define VCN_AV1_RESTART_PREDICATE 1 +static inline bool vcnav1_is_restart(const AV1Frame* h, AV1ParseResult kind) { + return kind == AV1_PARSE_FRAME_READY && h->frame_type == AV1_KEY_FRAME && + h->refresh_frame_flags == 0xFF; +} const char* vcnav1_last_error(VcnAV1* d); // What made the last configure or decode fail: the stream (it cannot be // decoded as it is), the device (a driver call failed or the GPU did not diff --git a/GPU/decode/common/vcndriver.h b/GPU/decode/common/vcndriver.h index e0906ecb..8b0b94f4 100644 --- a/GPU/decode/common/vcndriver.h +++ b/GPU/decode/common/vcndriver.h @@ -188,9 +188,10 @@ void vcn_session_drop(VcnDriverSession* s); // destroyed on the teardown queue (vcn_teardown), because that close can wait // for the command in the kernel, and then `after` runs there (the codec lets go // of the pictures the command may still write). The session is empty when this -// returns and can be opened again at once. +// returns and can be opened again at once. why is the reason for the close, in +// the teardown's log line. void vcn_session_drop_later(VcnDriverSession* s, const char* what, - void (^after)(void)); + const char* why, void (^after)(void)); // True once the system has slept since s opened (see VcnSleepMark), and from // then on; the first time, it says so in the log. The AV1 or VP9 codec that @@ -223,9 +224,10 @@ void vcn_session_close(VcnDriverSession* s); // finished) or lost (the system slept since the session opened), with a log // line before and after: the teardown may then wait in the kernel, and the // caller (VideoToolbox's invalidate) must not wait with it. what names the -// session in the log. +// session in the log. why is the reason printed after the name; NULL keeps the +// wording above ("a command never finished", or the sleep for a lost session). void vcn_teardown(bool stuck, bool lost, os_log_t log, const char* what, - void (^close)(void)); + const char* why, void (^close)(void)); // Waits until every teardown handed to the background queue has finished, at // most timeoutMs. False when one is still running: its kernel call may never diff --git a/GPU/decode/common/vcnlegacy.c b/GPU/decode/common/vcnlegacy.c index 7421bb1f..701f95b1 100644 --- a/GPU/decode/common/vcnlegacy.c +++ b/GPU/decode/common/vcnlegacy.c @@ -660,7 +660,7 @@ static void destroy_now(VcnLegacy* d) { vcn_session_close(&d->s); reg_remove(d); if (d->pool) CVPixelBufferPoolRelease(d->pool); - if (d->log) os_release(d->log); + if (d->log && d->log != OS_LOG_DEFAULT) os_release(d->log); free(d->seq); free(d->frame); free(d->bsinfo); @@ -670,7 +670,7 @@ static void destroy_now(VcnLegacy* d) { void vcnlegacy_destroy(VcnLegacy* d) { if (!d) return; vcn_teardown(d->stuck, vcn_session_lost(&d->s), d->log, - "legacy codec session", ^{ + "legacy codec session", NULL, ^{ destroy_now(d); }); } @@ -723,6 +723,7 @@ VcnLegacy* vcnlegacy_create(const VcnLegacyConfig* cfg, char* err, d->log = os_log_create( cfg->logSubsystem ? cfg->logSubsystem : "com.droga.vtlegacyvcn", "driver"); + if (!d->log) d->log = OS_LOG_DEFAULT; d->seq = calloc(1, SEQ_BYTES); d->frame = calloc(1, FRAME_BYTES); d->bsinfo = calloc(1, BSINFO_BYTES); @@ -821,6 +822,16 @@ int vcnlegacy_failure(VcnLegacy* d) { unsigned vcnlegacy_firmware_errors(VcnLegacy* d) { return d ? d->fwErrors : 0; } uint32_t vcnlegacy_width(VcnLegacy* d) { return d ? d->cfg.width : 0; } uint32_t vcnlegacy_height(VcnLegacy* d) { return d ? d->cfg.height : 0; } +bool vcnlegacy_session_lost(VcnLegacy* d) { + return d && !d->broken && vcn_session_lost(&d->s); +} +void vcnlegacy_log_rebuild(VcnLegacy* d, const char* what, unsigned dropped) { + if (!d) return; + os_log_info(d->log, + "a session from before a system sleep: a new one at %{public}s, " + "%u picture(s) dropped meanwhile", + what, dropped); +} bool vcnlegacy_last_status(VcnLegacy* d, bool* executed, uint32_t* status) { if (!d || !d->haveStatus) return false; if (executed) *executed = d->executed; @@ -856,14 +867,23 @@ int vcnlegacy_decode(VcnLegacy* d, const void* block, uint32_t blockSize, d->err[0] = 0; d->failure = VCNLEGACY_FAIL_STREAM; d->haveStatus = false; - // Nothing goes into the pool or to the engine for a session from before a - // system sleep (vcndriver.h). - if (!d->broken && vcn_session_lost(&d->s)) d->broken = true; + // A session from before a system sleep never decodes another picture: the + // engine lost it at the wake (vcndriver.h). That is not a failure of the + // decoder: the codec layer drops the pictures up to its next intra picture + // and starts a new session there (mpeg2/vcnmpeg2.c, vc1/vcnvc1.c, + // mpeg4/vcnmpeg4.c), as AV1 and VP9 have done since 0.3.8. Only a session + // that stopped for another reason stops the decoder. Nothing goes into the + // pool or to the engine here. + if (vcnlegacy_session_lost(d)) { + snprintf(d->err, sizeof(d->err), + "session stopped: the system slept since it opened"); + d->failure = VCNLEGACY_FAIL_DEVICE; + return -1; + } if (d->broken) { snprintf(d->err, sizeof(d->err), "session stopped: %s", - d->stuck ? "the GPU did not finish an earlier picture" - : d->s.lost ? "the system slept since it opened" - : "an earlier driver call failed"); + d->stuck ? "the GPU did not finish an earlier picture" + : "an earlier driver call failed"); d->failure = VCNLEGACY_FAIL_DEVICE; return -1; } diff --git a/GPU/decode/common/vcnlegacy.h b/GPU/decode/common/vcnlegacy.h index 2016217f..571d79e4 100644 --- a/GPU/decode/common/vcnlegacy.h +++ b/GPU/decode/common/vcnlegacy.h @@ -187,3 +187,14 @@ unsigned vcnlegacy_firmware_errors(VcnLegacy* d); bool vcnlegacy_last_status(VcnLegacy* d, bool* executed, uint32_t* status); uint32_t vcnlegacy_width(VcnLegacy* d); uint32_t vcnlegacy_height(VcnLegacy* d); +// True when the system has slept since this session opened (vcn_session_lost, +// vcndriver.h): nothing can be decoded on it any more. The codec layer drops +// the pictures up to its next intra picture and starts a new session there +// (mpeg2/vcnmpeg2.c, vc1/vcnvc1.c, mpeg4/vcnmpeg4.c), so the host keeps its +// decoder object and no error reaches it. vcnlegacy_decode says the same in +// its error until then. +bool vcnlegacy_session_lost(VcnLegacy* d); +// Says in the session's log that a new session replaces this one, which the +// system slept through, at `what`, and how many pictures were dropped while +// there was no session to decode them. +void vcnlegacy_log_rebuild(VcnLegacy* d, const char* what, unsigned dropped); diff --git a/GPU/decode/common/vcnsession.c b/GPU/decode/common/vcnsession.c index d746a11b..4fefc359 100644 --- a/GPU/decode/common/vcnsession.c +++ b/GPU/decode/common/vcnsession.c @@ -326,13 +326,13 @@ void vcn_session_drop(VcnDriverSession* s) { } void vcn_session_drop_later(VcnDriverSession* s, const char* what, - void (^after)(void)) { + const char* why, void (^after)(void)) { AVD_Accelerator* accel; io_service_t svc; detach(s, &accel, &svc); AVD_DestroyAVDAccelerator_fn destroy = s->destroy; // vcn_teardown copies the block, and with it `after`. - vcn_teardown(true, false, s->log, what, ^{ + vcn_teardown(true, false, s->log, what, why, ^{ if (accel && destroy) destroy(accel); // Released only after the driver is gone: it may hold on to the service. if (svc) IOObjectRelease(svc); @@ -416,28 +416,41 @@ static void pin_this_image(void) { } void vcn_teardown(bool stuck, bool lost, os_log_t log, const char* what, - void (^close)(void)) { + const char* why, void (^close)(void)) { if (!stuck && !lost) { close(); return; } // Kept for the line after the close, which runs once the caller is gone. char* name = strdup(what ? what : "session"); + // The reason too, carried the same way: the line after the close prefers it + // over "stuck"/"lost", and falls back to those when strdup failed or `why` + // was not set. + char* whyCopy = why ? strdup(why) : NULL; + // The log too: the close may give up the caller's last reference to it + // (destroy_now in vcnlegacy.c does), and the block below logs with it after + // the close. This reference is given up on the block's last line. The + // default log is a global that must not be retained or released. + if (log != OS_LOG_DEFAULT) os_retain(log); os_log_error( log, "%{public}s: %{public}s; closing the session on a background " "thread, the close may wait for the GPU", name ? name : "session", - stuck ? "a command never finished" : "the system slept since it opened"); + why ? why : (stuck ? "a command never finished" + : "the system slept since it opened")); dispatch_queue_t q = teardown_queue(); // also makes the group // dispatch_group_async copies this block, and with it close. dispatch_group_async(teardown_group, q, ^{ double t0 = wait_now_ms(); close(); os_log_error(log, "%{public}s: %{public}s session closed after %.0f ms", - name ? name : "session", stuck ? "stuck" : "lost", + name ? name : "session", + whyCopy ? whyCopy : (stuck ? "stuck" : "lost"), wait_now_ms() - t0); free(name); + free(whyCopy); + if (log != OS_LOG_DEFAULT) os_release(log); }); } diff --git a/GPU/decode/mpeg2/vcnmpeg2.c b/GPU/decode/mpeg2/vcnmpeg2.c index 083c121b..a0696e78 100644 --- a/GPU/decode/mpeg2/vcnmpeg2.c +++ b/GPU/decode/mpeg2/vcnmpeg2.c @@ -31,6 +31,12 @@ typedef struct { char err[256]; int failure; unsigned fwErrors; // of sessions already closed + // Pictures that did not go to the engine because no session could take + // them: the ones a sleep took the session away from, and the ones that + // needed a reference the session rebuilt at the wake does not have yet. + unsigned dropped; + bool ramping; // rebuilt after a sleep: drop what has no reference yet + bool broken; // stopped: the stream sent no intra picture after the sleep } VcnMpeg2; // Mesa's NUM_MPEG2_REFS: a reference index is kept within the last six @@ -106,6 +112,9 @@ static void end_session(VcnMpeg2* d) { d->frameNumber = 0; d->refs = 0; d->refNumber[0] = d->refNumber[1] = 0; + // The rebuild after a sleep sets ramping back right after end_session. + d->ramping = false; + d->dropped = 0; } static int on_picture(void* ctx, Mpeg2Parser* p, const Mpeg2Picture* pic) { @@ -127,6 +136,36 @@ static int on_picture(void* ctx, Mpeg2Parser* p, const Mpeg2Picture* pic) { if (d->vcn && (vcnlegacy_width(d->vcn) != p->width || vcnlegacy_height(d->vcn) != p->height)) end_session(d); + // A session from before a system sleep cannot take another picture. An I + // picture is coded from nothing before it (ISO/IEC 13818-2 6.3.1, Table + // 6-12: I pictures use no motion-compensated prediction), so it decodes the + // same in a new session: the pictures up to it are dropped without an error + // — the host sees the stream carry on — and it starts the new session. A GOP + // header's closed_gop says the pictures after the I need nothing from the + // one before (6.2.2.6); with an open GOP, or with broken_link, they predict + // from the previous GOP, whose pictures this session never decoded, and are + // dropped by the reference check below (ramping). + if (d->vcn && vcnlegacy_session_lost(d->vcn)) { + if (pic->coding_type != MPEG2_I) { + // Bounded like the AV1 and VP9 rebuilds (REBUILD_MAX_DROPPED there): a + // stream that sends no intra picture is stopped as a device failure, so + // the host can hand it to another decoder, instead of dropping pictures + // for however long the stream goes without one. + if (++d->dropped > 600) { + d->broken = true; + d->failure = VCNLEGACY_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "no intra picture in %u frames after the system sleep", + d->dropped); + return -1; + } + return 0; + } + vcnlegacy_log_rebuild(d->vcn, "an MPEG-2 I picture", d->dropped); + end_session(d); + d->dropped = 0; + d->ramping = true; + } if (!d->vcn) { VcnLegacyConfig cfg = {.codecId = VCN_CODEC_MPEG2_VLD, .messageId = VCN_MESSAGE_MPEG2_VLD, @@ -154,6 +193,11 @@ static int on_picture(void* ctx, Mpeg2Parser* p, const Mpeg2Picture* pic) { : 0; if (second && pic->coding_type == MPEG2_P) need = 0; if (d->refs < need) { + if (d->ramping) { + drop_field(d); + d->dropped++; + return 0; + } snprintf(d->err, sizeof(d->err), "%s picture without its reference picture%s", pic->coding_type == MPEG2_B ? "B" : "P", need == 2 ? "s" : ""); @@ -207,6 +251,7 @@ static int on_picture(void* ctx, Mpeg2Parser* p, const Mpeg2Picture* pic) { d->refNumber[1] = n; if (d->refs < 2) d->refs++; } + if (d->ramping && d->refs >= 2) d->ramping = false; int stop = d->out ? d->out(d->outCtx, target, type == MPEG2_B ? VCNLEGACY_PIC_B : VCNLEGACY_PIC_REFERENCE, @@ -245,6 +290,14 @@ static int decode(void* v, const uint8_t* chunk, size_t size, d->outCtx = ctx; d->err[0] = 0; d->failure = VCNLEGACY_FAIL_STREAM; + if (d->broken) { + snprintf(d->err, sizeof(d->err), + "session stopped: no intra picture in %u frames after the " + "system sleep", + d->dropped); + d->failure = VCNLEGACY_FAIL_DEVICE; + return -1; + } int r = mpeg2_parse_chunk(&d->parser, chunk, size, on_picture, d); if (r && !d->err[0]) { snprintf(d->err, sizeof(d->err), "%s", diff --git a/GPU/decode/mpeg4/vcnmpeg4.c b/GPU/decode/mpeg4/vcnmpeg4.c index f3a3566a..f800c911 100644 --- a/GPU/decode/mpeg4/vcnmpeg4.c +++ b/GPU/decode/mpeg4/vcnmpeg4.c @@ -22,6 +22,12 @@ typedef struct { char err[256]; int failure; unsigned fwErrors; // of sessions already closed + // VOPs that did not go to the engine because no session could take them: + // the ones a sleep took the session away from, and the ones that needed a + // reference the session rebuilt at the wake does not have yet. + unsigned dropped; + bool ramping; // rebuilt after a sleep: drop what has no reference yet + bool broken; // stopped: the stream sent no intra picture after the sleep } VcnMpeg4; #define NUM_REFS 6 // Mesa uses NUM_MPEG2_REFS for this codec too @@ -124,6 +130,9 @@ static void end_session(VcnMpeg4* d) { d->frameNumber = 0; d->refs = 0; d->refNumber[0] = d->refNumber[1] = 0; + // The rebuild after a sleep sets ramping back right after end_session. + d->ramping = false; + d->dropped = 0; } static int on_picture(void* ctx, Mpeg4Parser* p, const Mpeg4Picture* pic) { @@ -136,6 +145,36 @@ static int on_picture(void* ctx, Mpeg4Parser* p, const Mpeg4Picture* pic) { if (d->vcn && (vcnlegacy_width(d->vcn) != p->width || vcnlegacy_height(d->vcn) != p->height)) end_session(d); + // A session from before a system sleep cannot take another VOP. An I-VOP is + // intra coded and uses no motion compensation from another VOP (ISO/IEC + // 14496-2 6.3.3, vop_coding_type in Table 6-7), so it decodes the same in a + // new session: the VOPs up to it are dropped without an error — the host + // sees the stream carry on — and it starts the new session. The VOL and its + // size are what a new sequence can change, and both come with the session + // (the size check above, vcnmpeg4_fill_block for the flags). The P-VOPs + // after it that predict from a VOP this session never decoded are dropped by + // the reference check below (ramping). + if (d->vcn && vcnlegacy_session_lost(d->vcn)) { + if (pic->coding_type != MPEG4_I) { + // Bounded like the AV1 and VP9 rebuilds (REBUILD_MAX_DROPPED there): a + // stream that sends no intra picture is stopped as a device failure, so + // the host can hand it to another decoder, instead of dropping pictures + // for however long the stream goes without one. + if (++d->dropped > 600) { + d->broken = true; + d->failure = VCNLEGACY_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "no intra picture in %u frames after the system sleep", + d->dropped); + return -1; + } + return 0; + } + vcnlegacy_log_rebuild(d->vcn, "an MPEG-4 I-VOP", d->dropped); + end_session(d); + d->dropped = 0; + d->ramping = true; + } if (!d->vcn) { VcnLegacyConfig cfg = {.codecId = VCN_CODEC_MPEG4, .messageId = VCN_MESSAGE_MPEG4_ASP_VLD, @@ -176,6 +215,10 @@ static int on_picture(void* ctx, Mpeg4Parser* p, const Mpeg4Picture* pic) { : 0; if (!pic->vop_coded) need = 1; if (d->refs < need) { + if (d->ramping) { + d->dropped++; + return 0; + } snprintf(d->err, sizeof(d->err), "VOP without its reference VOP%s", need == 2 ? "s" : ""); d->failure = VCNLEGACY_FAIL_REFERENCE; @@ -226,6 +269,7 @@ static int on_picture(void* ctx, Mpeg4Parser* p, const Mpeg4Picture* pic) { if (d->lastRef) CVPixelBufferRelease(d->lastRef); d->lastRef = CVPixelBufferRetain(target); } + if (d->ramping && d->refs >= 2) d->ramping = false; int stop = d->out ? d->out(d->outCtx, target, b ? VCNLEGACY_PIC_B : VCNLEGACY_PIC_REFERENCE, p->width, p->height) @@ -282,6 +326,14 @@ static int decode(void* v, const uint8_t* chunk, size_t size, d->outCtx = ctx; d->err[0] = 0; d->failure = VCNLEGACY_FAIL_STREAM; + if (d->broken) { + snprintf(d->err, sizeof(d->err), + "session stopped: no intra picture in %u frames after the " + "system sleep", + d->dropped); + d->failure = VCNLEGACY_FAIL_DEVICE; + return -1; + } int r = mpeg4_parse_chunk(&d->parser, chunk, size, on_picture, d); if (r && !d->err[0]) { snprintf(d->err, sizeof(d->err), "%s", diff --git a/GPU/decode/tests/av1state.c b/GPU/decode/tests/av1state.c index 341ef08b..ed2d5afb 100644 --- a/GPU/decode/tests/av1state.c +++ b/GPU/decode/tests/av1state.c @@ -11,6 +11,14 @@ // 5. A still picture header with more than 14 luma or 10 chroma film grain // points is refused and leaves the references as they were; the same // header with 14 and 10 points parses. +// 6. A sequence header cut short is refused and leaves the stored one as +// it was; a frame after it still parses with the first header; a +// different valid sequence header replaces it. +// 7. What the parser hands the decoder across a change of sequence header: +// a key frame at 8 bits, then a 10-bit sequence header and an inter +// frame using slot 0 hand over seq.BitDepth 10 with the reference's +// bit_depth still 8 (the state the decoder-side check relies on; no +// code change, this pins it). // // usage: av1state file.ivf (a single-tile AV1 stream; exit status 0 = pass) #include @@ -65,6 +73,22 @@ static int on_header_bytes(void* ctx, AV1Parser* p, AV1ParseResult kind) { return 0; } +// The depths of the handover, recorded before the reference update replaces +// the slots. +static int handover_seq_depth, handover_ref_depth; +static int on_handover(void* ctx, AV1Parser* p, AV1ParseResult kind) { + Seen* s = ctx; + if (kind == AV1_PARSE_SHOW_EXISTING) { + s->shown++; + return 0; + } + s->ready++; + handover_seq_depth = p->seq.BitDepth; + handover_ref_depth = p->ref[p->fh.ref_frame_idx[0]].bit_depth; + av1_reference_update(p, 0); + return 0; +} + static size_t put_obu(uint8_t* out, int type, const uint8_t* payload, size_t size) { size_t n = 0; @@ -310,6 +334,60 @@ int main(int argc, char** argv) { expect("the refused grain headers leave the references as they were", kept_refs); + // 6. a refused sequence header leaves the stored one as it was; a + // different valid one replaces it + av1_parser_init(p); + got = (Seen){0}; + av1_parse_temporal_unit(p, seq_obu, seq_n, on_frame, &got); + AV1Seq seq_before; + memcpy(&seq_before, &p->seq, sizeof(seq_before)); + nb = put_obu(buf, kObuSequenceHeader, seq, 1); // truncated: refused + r = av1_parse_temporal_unit(p, buf, nb, on_frame, &got); + expect("a cut sequence header is refused", r != 0); + expect("the stored sequence header is as it was before it", + !memcmp(&seq_before, &p->seq, sizeof(seq_before))); + memcpy(buf, hdr_obu, hdr_n); + memcpy(buf + hdr_n, tiles_obu, tiles_n); + r = av1_parse_temporal_unit(p, buf, hdr_n + tiles_n, on_frame, &got); + expect("a frame after a refused sequence header still parses with the first", + !r && got.ready == 1 && got.tile_hash == want.tile_hash); + nb = grain_still(buf, 0, 0, 0); + const uint8_t* grain_seq; + size_t grain_seq_size; + if (!find_obu(buf, nb, kObuSequenceHeader, &grain_seq, &grain_seq_size)) { + fprintf(stderr, "could not find the grain sequence header\n"); + return 1; + } + nb = put_obu(hdr_obu, kObuSequenceHeader, grain_seq, grain_seq_size); + r = av1_parse_temporal_unit(p, hdr_obu, nb, on_frame, &got); + expect("a different valid sequence header replaces the stored one", + !r && p->seq.valid && p->seq.film_grain_params_present == 1 && + memcmp(&seq_before, &p->seq, sizeof(seq_before)) != 0); + av1_parser_free(p); + + // 7. what the parser hands the decoder across a change of sequence header: + // a key frame at 8 bits, then a 10-bit sequence header and an inter + // frame that uses slot 0 (the a1 scenario, a1-harness.c). No code + // change here: this pins the state the decoder-side check relies on. + static const uint8_t tu1[] = {0x0a, 0x08, 0x18, 0x3f, 0xc0, 0x0f, 0xc0, + 0x0f, 0xc0, 0x00, 0x32, 0x06, 0x16, 0x40, + 0x00, 0x00, 0x00, 0x55}; + static const uint8_t tu2[] = {0x0a, 0x0c, 0x00, 0x00, 0x00, 0x07, 0xf8, + 0x01, 0xf8, 0x01, 0xf8, 0x03, 0x10, 0x00, + 0x32, 0x0e, 0x30, 0xe1, 0xe0, 0x00, 0x00, + 0x01, 0x64, 0x00, 0xa2, 0x8a, 0x28, 0x00, + 0x00, 0x66}; + av1_parser_init(p); + got = (Seen){0}; + r = av1_parse_temporal_unit(p, tu1, sizeof tu1, on_handover, &got); + expect("the 8-bit key frame temporal unit parses", + !r && got.ready == 1 && handover_seq_depth == 8); + r = av1_parse_temporal_unit(p, tu2, sizeof tu2, on_handover, &got); + expect("the inter frame hands over seq 10 with its reference at 8", + !r && got.ready == 2 && handover_seq_depth == 10 && + handover_ref_depth == 8); + av1_parser_free(p); + free(p); return failures ? 1 : 0; } diff --git a/GPU/decode/tests/gpu/vtvp9test.c b/GPU/decode/tests/gpu/vtvp9test.c index 62bc90df..d16e281c 100644 --- a/GPU/decode/tests/gpu/vtvp9test.c +++ b/GPU/decode/tests/gpu/vtvp9test.c @@ -4,11 +4,16 @@ // vtvp9test [-load bundle] list // shows the vp09 decoders VideoToolbox knows about // vtvp9test [-load bundle] file [reference] [-n] [-a] [-pace fps] [-loop N] -// [-renew] [-frames N] [-id decoder] [-sw] [-attach] +// [-renew] [-frames N] [-id decoder] [-sw] [-attach] [-dump dir] // [-color primaries,transfer,matrix] [-hdr] // decodes the file (IVF or WebM) and compares the MD5 of every frame as // I420 with a reference in the format of FFmpeg's FATE suite // +// -dump writes every frame to /f_x.yuv as planar I420, to +// compare pixels with a reference decoder when an MD5 differs; it needs +// SVC_TEST_GO=1 in the environment, so that no stray script starts a decode on +// this Mac's card and writes files. +// // -load registers the bundle in this process only, nothing is installed on the // system. -n reads no pixels, -a decodes asynchronously, -pace feeds at a fixed // rate and reports lateness, -loop feeds the file N times in one session (a @@ -123,6 +128,7 @@ typedef struct { FILE* ref; int frames, mismatches, errors, dropped, nohash, attach; char lastAttach[1024]; + const char* dumpDir; // -dump: every frame as planar I420, one file each double *fed, *lat; } Ctx; @@ -172,6 +178,28 @@ static void out_cb(void* refcon, void* frameRefcon, OSStatus st, *uv = CVPixelBufferGetBaseAddressOfPlane(img, 1); size_t ys = CVPixelBufferGetBytesPerRowOfPlane(img, 0), uvs = CVPixelBufferGetBytesPerRowOfPlane(img, 1); + if (c->dumpDir && !ten) { + char path[PATH_MAX]; + snprintf(path, sizeof(path), "%s/f%03d_%dx%d.yuv", c->dumpDir, c->frames, w, + h); + FILE* f = fopen(path, "wb"); + uint8_t* line = malloc((size_t)((w + 1) / 2)); + if (f && line) { + for (int r = 0; r < h; r++) fwrite(y + (size_t)r * ys, 1, (size_t)w, f); + for (int pl = 0; pl < 2; pl++) + for (int r = 0; r < (h + 1) / 2; r++) { + for (int i = 0; i < (w + 1) / 2; i++) + line[i] = uv[(size_t)r * uvs + 2 * i + pl]; + fwrite(line, 1, (size_t)((w + 1) / 2), f); + } + fclose(f); + } else { + if (f) fclose(f); + printf("frame %d: cannot write %s\n", c->frames, path); + c->errors++; + } + free(line); + } CC_MD5_CTX m; CC_MD5_Init(&m); int cw = (w + 1) / 2, ch = (h + 1) / 2; @@ -236,7 +264,7 @@ static int usage(void) { "usage: vtvp9test [-load bundle] list\n" " vtvp9test [-load bundle] file [reference] [-n] [-a] " "[-pace fps] [-loop N] [-renew] [-frames N] [-id decoder] [-sw] " - "[-attach]\n" + "[-attach] [-dump dir]\n" " [-color primaries,transfer,matrix] [-hdr]\n" "A decode run goes to the GPU: there is no switch to arm.\n"); return 1; @@ -286,6 +314,12 @@ int main(int argc, char** argv) { require_hw = 0; } else if (!strcmp(argv[i], "-attach")) { c.attach = 1; + } else if (!strcmp(argv[i], "-dump") && i + 1 < argc) { + // Writing pixels is for a measured comparison, not for a script that + // happens to pass by: it needs SVC_TEST_GO=1. + const char* go = getenv("SVC_TEST_GO"); + if (!go || strcmp(go, "1")) return fail("-dump needs SVC_TEST_GO=1"); + c.dumpDir = argv[++i]; } else if (!strcmp(argv[i], "-color") && i + 1 < argc) { if (sscanf(argv[++i], "%d,%d,%d", &color[0], &color[1], &color[2]) != 3) return fail("invalid -color"); diff --git a/GPU/decode/tests/layertest.c b/GPU/decode/tests/layertest.c index 2a7d2b2f..ec3dab64 100644 --- a/GPU/decode/tests/layertest.c +++ b/GPU/decode/tests/layertest.c @@ -16,7 +16,13 @@ // VCNMPEG4_ALLOW_B=1; without that switch no B-VOP does; with it, a B-VOP // with its time distances goes out in block mode 3 with TRB/TRD; cut mode // 1 sends a unit from its VOP start code; the session asks for the size -// aligned to 16. +// aligned to 16; +// 4. after a system sleep (the stand-in says the session is from before one) +// the three codecs drop the pictures up to their next intra picture with +// no command and no error, start a new session at that one, and decode +// the pictures after it in the new session; a P picture that has no +// reference before any sleep is still refused, so the quiet dropping +// hides no stream that starts in the middle. #include #include #include @@ -44,6 +50,12 @@ static struct { uint32_t blockSize; } g_cmd[MAX_CMDS]; static int g_cmds, g_created, g_destroyed; +// The session the layers hold is from before a system sleep (each wake test +// sets this), and what the layers asked for at the restart point. +static bool g_lost; +static int g_rebuilds; +static unsigned g_rebuildDropped; +static const char* g_rebuildWhat; static VcnLegacyConfig g_cfg; // of the last session made struct VcnLegacy { @@ -58,6 +70,7 @@ VcnLegacy* vcnlegacy_create(const VcnLegacyConfig* cfg, char* err, d->cfg = *cfg; g_cfg = *cfg; g_created++; + g_lost = false; // a session made now is from after the sleep return d; } void vcnlegacy_destroy(VcnLegacy* d) { @@ -107,6 +120,13 @@ unsigned vcnlegacy_firmware_errors(VcnLegacy* d) { } uint32_t vcnlegacy_width(VcnLegacy* d) { return d ? d->cfg.width : 0; } uint32_t vcnlegacy_height(VcnLegacy* d) { return d ? d->cfg.height : 0; } +bool vcnlegacy_session_lost(VcnLegacy* d) { return d && g_lost; } +void vcnlegacy_log_rebuild(VcnLegacy* d, const char* what, unsigned dropped) { + (void)d; + g_rebuildWhat = what; + g_rebuildDropped = dropped; + g_rebuilds++; +} // ---- what the layer shows enum { MAX_OUT = 64 }; @@ -128,6 +148,10 @@ static void reset(void) { for (int i = 0; i < g_outs; i++) if (g_out[i].pb) CVPixelBufferRelease(g_out[i].pb); g_outs = g_cmds = g_created = g_destroyed = 0; + g_rebuilds = 0; + g_rebuildDropped = 0; + g_rebuildWhat = NULL; + g_lost = false; } // ---- a bit writer for the made-up streams @@ -453,10 +477,141 @@ static void test_mpeg4_b(void) { unsetenv("VCNMPEG4_ALLOW_B"); } +// ---- 4. after a system sleep + +static void test_mpeg2_wake(void) { + W s1 = {0}, s2 = {0}, s3 = {0}, s4 = {0}, s5 = {0}, bad = {0}; + mpeg2_headers(&s1); + mpeg2_field(&s1, 1, 3); // I, frame pictures throughout + mpeg2_field(&s2, 2, 3); // P + mpeg2_field(&s3, 2, 3); // P + mpeg2_field(&s4, 1, 3); // I + mpeg2_field(&s5, 2, 3); // P + mpeg2_headers(&bad); + mpeg2_field(&bad, 2, 3); // a P picture with no reference before it + char err[256] = ""; + // First, on a decoder of its own: the refusal must not depend on a wake. + void* d0 = vcnmpeg2_codec.create(NULL, 0, 64, 64, err, sizeof(err)); + if (!d0) { + expect("mpeg2 wake: a decoder is made", 0); + return; + } + reset(); + int r = vcnmpeg2_codec.decode(d0, bad.d, bytes(&bad), on_frame, NULL); + expect("mpeg2 wake: a P picture with no reference is refused before a sleep", + r != 0 && g_cmds == 0 && g_outs == 0 && + vcnmpeg2_codec.failure(d0) == VCNLEGACY_FAIL_REFERENCE); + vcnmpeg2_codec.destroy(d0); + reset(); + void* d = vcnmpeg2_codec.create(NULL, 0, 64, 64, err, sizeof(err)); + if (!d) { + expect("mpeg2 wake: a second decoder is made", 0); + return; + } + r = vcnmpeg2_codec.decode(d, s1.d, bytes(&s1), on_frame, NULL); + r |= vcnmpeg2_codec.decode(d, s2.d, bytes(&s2), on_frame, NULL); + expect("mpeg2 wake: I and P decode, one session, two commands", + r == 0 && g_created == 1 && g_cmds == 2 && g_outs == 2); + g_lost = true; // the system slept + r = vcnmpeg2_codec.decode(d, s3.d, bytes(&s3), on_frame, NULL); + expect( + "mpeg2 wake: the P picture after the sleep is dropped, no command, " + "no error", + r == 0 && g_cmds == 2 && g_outs == 2 && g_created == 1 && + vcnmpeg2_codec.failure(d) == VCNLEGACY_FAIL_STREAM); + r = vcnmpeg2_codec.decode(d, s4.d, bytes(&s4), on_frame, NULL); + expect("mpeg2 wake: the I picture starts a new session and decodes", + r == 0 && g_created == 2 && g_cmds == 3 && g_outs == 3 && + g_rebuilds == 1 && g_rebuildDropped == 1 && g_rebuildWhat); + r = vcnmpeg2_codec.decode(d, s5.d, bytes(&s5), on_frame, NULL); + expect("mpeg2 wake: the P picture after it decodes in the new session", + r == 0 && g_cmds == 4 && g_outs == 4 && g_created == 2); + vcnmpeg2_codec.destroy(d); + expect("mpeg2 wake: both sessions are closed", g_destroyed == 2); + reset(); +} + +static void test_vc1_wake(void) { + static const uint8_t structc[4] = {0x40, 0, 0, 0}; + static const uint8_t fi[8] = {0x00, 1, 2, 3, 4, 5, 6, 7}; + static const uint8_t fp[8] = {0x20, 1, 2, 3, 4, 5, 6, 7}; + char err[256] = ""; + void* d = + vcnvc1_codec.create(structc, sizeof(structc), 320, 240, err, sizeof(err)); + if (!d) { + expect("vc1 wake: a decoder is made", 0); + return; + } + reset(); + int r = vcnvc1_codec.decode(d, fi, sizeof(fi), on_frame, NULL); + r |= vcnvc1_codec.decode(d, fp, sizeof(fp), on_frame, NULL); + expect("vc1 wake: I and P decode, one session, two commands", + r == 0 && g_created == 1 && g_cmds == 2 && g_outs == 2); + g_lost = true; + r = vcnvc1_codec.decode(d, fp, sizeof(fp), on_frame, NULL); + expect( + "vc1 wake: the P frame after the sleep is dropped, no command, no " + "error", + r == 0 && g_cmds == 2 && g_outs == 2 && g_created == 1 && + vcnvc1_codec.failure(d) == VCNLEGACY_FAIL_STREAM); + r = vcnvc1_codec.decode(d, fi, sizeof(fi), on_frame, NULL); + expect("vc1 wake: the I frame starts a new session and decodes", + r == 0 && g_created == 2 && g_cmds == 3 && g_outs == 3 && + g_rebuilds == 1 && g_rebuildDropped == 1 && g_rebuildWhat); + r = vcnvc1_codec.decode(d, fp, sizeof(fp), on_frame, NULL); + expect("vc1 wake: the P frame after it decodes in the new session", + r == 0 && g_cmds == 4 && g_outs == 4 && g_created == 2); + vcnvc1_codec.destroy(d); + expect("vc1 wake: both sessions are closed", g_destroyed == 2); + reset(); +} + +static void test_mpeg4_wake(void) { + W h = {0}, s1 = {0}, s2 = {0}, s3 = {0}, s4 = {0}, s5 = {0}; + mpeg4_headers(&h); + mpeg4_vop(&s1, 0, 0); // I + mpeg4_vop(&s2, 1, 3); // P + mpeg4_vop(&s3, 1, 6); // P + mpeg4_vop(&s4, 0, 9); // I + mpeg4_vop(&s5, 1, 12); // P + char err[256] = ""; + void* d = vcnmpeg4_codec.create(NULL, 0, 0, 0, err, sizeof(err)); + if (!d) { + expect("mpeg4 wake: a decoder is made", 0); + return; + } + reset(); + int r = vcnmpeg4_codec.decode(d, h.d, bytes(&h), on_frame, NULL); + r |= vcnmpeg4_codec.decode(d, s1.d, bytes(&s1), on_frame, NULL); + r |= vcnmpeg4_codec.decode(d, s2.d, bytes(&s2), on_frame, NULL); + expect("mpeg4 wake: I and P decode, one session, two commands", + r == 0 && g_created == 1 && g_cmds == 2 && g_outs == 2); + g_lost = true; + r = vcnmpeg4_codec.decode(d, s3.d, bytes(&s3), on_frame, NULL); + expect( + "mpeg4 wake: the P-VOP after the sleep is dropped, no command, no " + "error", + r == 0 && g_cmds == 2 && g_outs == 2 && g_created == 1 && + vcnmpeg4_codec.failure(d) == VCNLEGACY_FAIL_STREAM); + r = vcnmpeg4_codec.decode(d, s4.d, bytes(&s4), on_frame, NULL); + expect("mpeg4 wake: the I-VOP starts a new session and decodes", + r == 0 && g_created == 2 && g_cmds == 3 && g_outs == 3 && + g_rebuilds == 1 && g_rebuildDropped == 1 && g_rebuildWhat); + r = vcnmpeg4_codec.decode(d, s5.d, bytes(&s5), on_frame, NULL); + expect("mpeg4 wake: the P-VOP after it decodes in the new session", + r == 0 && g_cmds == 4 && g_outs == 4 && g_created == 2); + vcnmpeg4_codec.destroy(d); + expect("mpeg4 wake: both sessions are closed", g_destroyed == 2); + reset(); +} + int main(void) { test_vc1_skipped(); test_mpeg2_fields(); test_mpeg4_b(); + test_mpeg2_wake(); + test_vc1_wake(); + test_mpeg4_wake(); printf("%s\n", failures ? "FAILED" : "all passed"); return failures ? 1 : 0; } diff --git a/GPU/decode/tests/legacypick.c b/GPU/decode/tests/legacypick.c index be59ba51..c58c1a2c 100644 --- a/GPU/decode/tests/legacypick.c +++ b/GPU/decode/tests/legacypick.c @@ -5,7 +5,11 @@ // common/vcnlegacy.c, and any decode or driver session fails the test. It // checks: // -// 1. a Simple profile stream goes to our plug-in, not to AppleMP4V; +// 1. a Simple profile stream goes to our plug-in, not to AppleMP4V (the +// plug-in is +// registered with a rating above Apple's: 400 was not enough on 26.7.3, +// where another MPEG-4 decoder answered first and our plug-in was never +// asked); // 2. an Advanced Simple stream whose VOL allows B-VOPs is refused by our // plug-in when the session starts, and VideoToolbox goes on to the next // decoder; @@ -14,9 +18,12 @@ // profile only, codecBadDataErr -8969 for Advanced Simple, interlaced // or MPEG quantisation), and the session fails with our error, so the // app uses its own decoder; -// 4. when our plug-in cannot start a session (no usable driver), a Simple -// stream goes on to AppleMP4V: VideoToolbox tries the next decoder after -// a refused session start. +// 4. when our plug-in cannot start a session (no usable driver), another +// decoder takes the Simple stream: VideoToolbox tries the next one after a +// refused session start. Whether that decoder is AppleMP4V and whether it +// calls itself hardware accelerated is not ours to decide (on 26.7.3 the +// one that answers does), so the check is that a session starts and that +// it is not ours. // 3 and 4 are skipped where VideoToolbox lists no AppleMP4V. // // The VOL headers are those of two clips made with FFmpeg's mpeg4 encoder @@ -88,6 +95,13 @@ uint32_t vcnlegacy_height(VcnLegacy* d) { (void)d; return 0; } +bool vcnlegacy_session_lost(VcnLegacy* d) { + (void)d; + return false; // the stand-in never gets a session to lose +} +void vcnlegacy_log_rebuild(VcnLegacy* d, const char* what, unsigned dropped) { + (void)d, (void)what, (void)dropped; +} // ---- the streams' headers static const uint8_t kSimple[] = { // profile 0x01, object type 1 @@ -200,7 +214,11 @@ int main(void) { dlsym(RTLD_DEFAULT, "VTRegisterVideoDecoderWithInfo"); expect("VideoToolbox exports VTRegisterVideoDecoderWithInfo", reg != NULL); if (!reg) return 1; - int rating = 400; + // Above Apple's own MPEG-4 decoder, or VideoToolbox takes that one and the + // plug-in is never asked: on 26.7.3 a rating of 400 already sits below what + // answers for a Simple profile stream, and the test failed for a reason that + // was not the plug-in's. + int rating = 2000; CFNumberRef r = CFNumberCreate(NULL, kCFNumberIntType, &rating); const void* k[] = {CFSTR("CMClassImplementationID"), CFSTR("CodecName"), CFSTR("VTCodecType"), CFSTR("VTRating"), @@ -241,9 +259,9 @@ int main(void) { st = session(kSimple, sizeof(kSimple), &hw); g_unavailable = false; expect( - "4. with our plug-in unable to start, a Simple stream goes on to " - "AppleMP4V (a session, not hardware accelerated)", - st == noErr && !hw && g_reached == 0); + "4. with our plug-in unable to start, another decoder takes the " + "Simple stream", + st == noErr && g_reached == 0); } else { printf("SKIP 3 and 4: VideoToolbox lists no AppleMP4V here (status %d)\n", (int)st); diff --git a/GPU/decode/tests/mutants.sh b/GPU/decode/tests/mutants.sh new file mode 100755 index 00000000..b7300ea2 --- /dev/null +++ b/GPU/decode/tests/mutants.sh @@ -0,0 +1,52 @@ +#!/bin/zsh +# mutants.sh - does sessiontest-vp9 notice when the VP9 session's two new rules +# are broken? Builds it from three damaged copies of decode/vp9/vcnvp9.c and +# requires each to fail: +# no-guard the 2x-smaller-reference check removed (the 4x frame decodes) +# no-drop the emptying of the slots of a failed frame removed (later +# frames decode on stale pictures) +# too-eager the check refuses any reference smaller than the frame (the 2x +# frame, which the engine does bit-exactly, is refused) +# Nothing opens the GPU. Needs tests/media (tests/fetch_media.sh). +# Exit status 0 = every damaged build was caught. +emulate -L zsh +setopt no_unset pipe_fail +cd "${0:A:h:h:h}" # GPU/ +B=decode/build/mutants +/bin/rm -rf $B && mkdir -p $B +SRC=decode/vp9/vcnvp9.c +TFLAGS=(-arch x86_64 -O1 -g -Wno-unused-function -Wno-unused-parameter + -fsanitize=address,undefined -fno-sanitize-recover=undefined) +CLIPS=(tests/media/vp9/vp90-2-12-droppable_1.ivf + tests/media/vp9-invalid/invalid-vp90-2-09-aq2.webm.ivf.s3984_r01-05_b6-.ivf + tests/media/vp9/vp90-2-22-svc_1280x720_3.ivf tests/media/vp9/vp90-2-13-mv-with-scaling.ivf) +# old text -> new text, exactly as in vcnvp9.c (perl quotes them, so no regex +# characters to escape) +typeset -A OLD=( + no-guard 'if (2 * r->width < h->width || 2 * r->height < h->height) {' + no-drop 'if (p->fh.refresh_frame_flags & (1u << i)) p->ref[i].valid = false;' + too-eager 'if (2 * r->width < h->width || 2 * r->height < h->height) {' +) +typeset -A NEW=( + no-guard 'if (0) {' + no-drop ';' + too-eager 'if (r->width < h->width || r->height < h->height) {' +) +bad=0 +for m in no-guard no-drop too-eager; do + OLDTXT=${OLD[$m]} NEWTXT=${NEW[$m]} perl -0pe 's/\Q$ENV{OLDTXT}\E/$ENV{NEWTXT}/' $SRC > "$B/vcnvp9-$m.c" + if cmp -s $SRC "$B/vcnvp9-$m.c"; then + print "FAIL $m: the edit did not change vcnvp9.c (the source moved?)"; bad=1; continue + fi + xcrun clang "${TFLAGS[@]}" -DTEST_VP9 -Idecode/common -Idecode/vp9 decode/tests/sessiontest.c \ + "$B/vcnvp9-$m.c" decode/vp9/vp9parse.c decode/common/vcnsession.c \ + -framework CoreFoundation -framework CoreVideo -framework IOKit -framework IOSurface \ + -o "$B/sessiontest-$m" 2> "$B/$m.log" \ + || { print "FAIL $m: the damaged copy does not build"; tail -3 "$B/$m.log"; bad=1; continue } + if "$B/sessiontest-$m" "${CLIPS[@]}" > "$B/$m.txt" 2>&1; then + print "FAIL $m: sessiontest still passes with this damage"; bad=1 + else + print "ok $m: caught ($(grep -c '^FAIL' "$B/$m.txt") failed checks)" + fi +done +exit $bad diff --git a/GPU/decode/tests/sessiontest.c b/GPU/decode/tests/sessiontest.c index e52d6258..fa22cb98 100644 --- a/GPU/decode/tests/sessiontest.c +++ b/GPU/decode/tests/sessiontest.c @@ -54,6 +54,13 @@ // alone or a wall clock that ran ahead counts as a sleep, a change of // the time asleep under 1 ms or both clocks moving together does not; a // new session opens beside one from before the sleep and decodes. +// 13. 0.3.8: a sleep that lands inside a decode call (the frame was on the GPU +// when the machine slept) rebuilds the session instead of stopping it; the +// quiet rebuild closes the old accelerator on the background queue; the +// 15 s limit covers the first command on the rebuilt session, and the +// usual 1 s is back once one has finished; the restart predicate takes an +// AV1 intra-only frame that refreshes all eight slots and a VP9 one that +// resets all four contexts, with its negatives. // // usage: sessiontest [clip with hidden frames] // Exit status 0 = pass. @@ -143,6 +150,9 @@ static struct { bool noDestroy; // the build has no AVD_DestroyAVDAccelerator bool rebuildFail; // CreateDriver fails: the rebuild after a sleep cannot open + bool sleepWhileHanging; // the machine sleeps while a command is on the GPU + unsigned hangMs; // commands finish after this long (0: at once) + double hangStart; // when the current slow command started } fault; enum { kFakeBuffer = 1 << 20 }; // larger than any frame of the test clips @@ -276,6 +286,25 @@ static int f_query(void* h, AVD_QueryList* q) { st.queries++; AVD_QueryEntry* e = q->entries; if (fault.queryFail) return fault.queryFail; + if (fault.sleepWhileHanging) { + // The machine slept while this command was on the GPU: the session's sleep + // mark moves under the wait, whose own clock does not run while asleep. + fault.sleepWhileHanging = false; + sleep_for(10000000000ull); + } + if (fault.hangMs) { + // Finishes, but only after this long: what a 1 s limit stops. + double t = (double)clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e6; + if (!fault.hangStart) fault.hangStart = t; + if (t - fault.hangStart < (double)fault.hangMs) { + e->status = 2; + return 0; + } + fault.hangStart = 0; + e->status = 1; + e->status2 = e->wait ? fault.firmware : 0; + return 0; + } if (fault.hang) { if (e->wait) return 99; // the real one would block here e->status = 2; @@ -575,9 +604,64 @@ static void hidden_frames(const char* path) { expect("a frame whose reference was never decoded is a reference failure", d && rm != 0 && FAILURE(d) == FAIL_REFERENCE); if (d) DESTROY(d); - for (int i = 0; i < clipCount; i++) free(clip[i].data); + clip_clear(); } +#if defined(TEST_VP9) +// The video engine predicts bit-exactly from a reference up to 2x smaller than +// the frame and not from a smaller one: vp90-2-22-svc_1280x720_3's 1280x720 +// layer predicts from a 320x180 reference (4x) and differed from libvpx in +// more than half the picture, while its 640x360 layer (a 2x smaller reference) +// was identical. A frame it cannot do is refused, and the slots it should have +// refreshed are emptied, so the frames that read them are refused too instead +// of decoding against older pictures. +static void scaled_references(const char* svc, const char* scaled) { + clip_clear(); + expect("the clip that predicts from a 2x smaller reference reads", + read_clip(scaled)); + reset(); + Vcn* d = make(); + int shown = 0, bad = d ? 0 : -1; + for (int i = 0; d && i < clipCount; i++) + if (DECODE(d, clip[i].data, clip[i].size, i, on_out, &shown)) { + printf(" sample %d: %s\n", i, LASTERR(d)); + bad++; + } + expect("references up to 2x smaller are not refused (mv-with-scaling)", + d && bad == 0 && shown > 0); + if (d) DESTROY(d); + expect("and that session closes fully", all_released()); + + clip_clear(); + expect("the spatial-SVC clip reads", read_clip(svc) && clipCount >= 3); + if (clipCount < 3) return; + reset(); + d = make(); + shown = 0; + int r0 = d ? DECODE(d, clip[0].data, clip[0].size, 0, on_out, &shown) : 0; + if (r0) printf(" chunk 0: %s\n", d ? LASTERR(d) : ""); + expect("a frame whose reference is 4x smaller is refused as a stream failure", + d && r0 != 0 && FAILURE(d) == FAIL_STREAM && + strstr(LASTERR(d), "2x smaller")); + expect("the two layers before it were sent to the engine, it was not", + st.schedules == 2); + int sent = st.schedules; + int r1 = d ? DECODE(d, clip[1].data, clip[1].size, 1, on_out, &shown) : 0; + expect( + "a frame predicted from what it should have refreshed is a reference " + "failure and sends nothing", + d && r1 != 0 && FAILURE(d) == FAIL_REFERENCE && st.schedules == sent); + int r2 = d ? DECODE(d, clip[2].data, clip[2].size, 2, on_out, &shown) : 0; + expect("and so is the next one", d && r2 != 0 && st.schedules == sent); + int rk = d ? DECODE(d, frame0, frame0Size, 3, on_out, &shown) : -1; + expect("a key frame refreshes every slot and decodes again", + d && rk == 0 && st.schedules > sent); + if (d) DESTROY(d); + expect("and that session closes fully", all_released()); + clip_clear(); +} +#endif + static void hung(int sig) { (void)sig; static const char msg[] = "FAIL a test hung\n"; @@ -586,10 +670,11 @@ static void hung(int sig) { } int main(int argc, char** argv) { - if ((argc != 2 && argc != 3) || !read_first_frame(argv[1])) { + if (argc < 2 || argc > 5 || !read_first_frame(argv[1])) { fprintf(stderr, "usage: sessiontest [clip with " - "hidden frames]\n"); + "hidden frames [VP9: spatial-SVC clip, clip with 2x scaled " + "references]]\n"); return 1; } signal(SIGALRM, hung); @@ -1065,8 +1150,139 @@ int main(int argc, char** argv) { expect("a session opened after the wake decodes and closes fully", rn2 == 0 && st.deleteCtx == 1 && st.destroys == 1 && all_released()); + // 13. 0.3.8. A sleep that lands inside a decode call: the frame was on the + // GPU when the machine slept, and the wait's clock stopped with it, so the + // frame times out right after the wake. It must be rebuilt at once, not + // taken for a stuck GPU (0.3.7 stopped the session here). + reset(); + d = make(); + if (d) DECODE(d, frame0, frame0Size, 0, on_out, NULL); + fault.hang = true; + fault.sleepWhileHanging = true; + int shownS = 0; + int ds = d ? DECODE(d, frame0, frame0Size, 1, on_out, &shownS) : -1; + fault.hang = false; + printf(" sleep inside the decode call: %s\n", + d && ds ? LASTERR(d) : "rebuilt"); + expect( + "a sleep inside a decode call rebuilds the session and drops the frame, " + "with no error", + d && ds == 0 && shownS == 0 && st.creates == 2); + int shownS2 = 0; + int ds2 = d ? DECODE(d, frame0, frame0Size, 2, on_out, &shownS2) : -1; + expect("and the frame after it decodes on the rebuilt driver", + d && ds2 == 0 && shownS2 == 1 && st.creates == 2); + if (d) DESTROY(d); + expect("and that session closes, only the dropped driver left", + closed_after_rebuild(1)); + + // The quiet rebuild, with the last command finished, closes the old + // accelerator on the background queue too, never on this thread. + reset(); + d = make(); + if (d) DECODE(d, frame0, frame0Size, 0, on_out, NULL); + sleep_for(10000000000ull); + closeGate = dispatch_semaphore_create(0); // marks a close on this thread + int shownQ = 0; + int dq = d ? DECODE(d, frame0, frame0Size, 1, on_out, &shownQ) : -1; + bool drainedQ = vcn_teardown_drain(10000); + if (drainedQ) dispatch_release(closeGate); + closeGate = NULL; + expect( + "the rebuild at the restart point closes the old accelerator on the " + "background queue, not on the decoding thread", + d && dq == 0 && shownQ == 1 && drainedQ && st.creates == 2 && + st.destroys == 1 && !st.destroyOnMain && st.deleteCtx == 0); + if (d) DESTROY(d); + expect("and that session closes fully, only the dropped driver left", + closed_after_rebuild(1)); + + // The 15 s limit covers the first command on the rebuilt session too. + reset(); + d = make(); + if (d) DECODE(d, frame0, frame0Size, 0, on_out, NULL); + sleep_for(10000000000ull); + vcn_wake_command_timeout_ms = 1500; + fault.hangMs = 1200; // finishes, but after the usual 1 s limit + int shownG = 0; + int dg = d ? DECODE(d, frame0, frame0Size, 1, on_out, &shownG) : -1; + printf(" the first frame on the rebuilt session: %s\n", + d && dg ? LASTERR(d) : "decoded"); + expect( + "the first command on the rebuilt session is still waited for up to the " + "wake limit, so a slow one does not stop a healthy session", + d && dg == 0 && shownG == 1 && st.creates == 2); + int dg2 = d ? DECODE(d, frame0, frame0Size, 2, on_out, &shownG) : -1; + printf(" a slow command after the first one: %s\n", d ? LASTERR(d) : ""); + expect("and the usual limit is back once one has finished", + d && dg2 != 0 && FAILURE(d) == FAIL_DEVICE); + fault.hangMs = 0; + vcn_wake_command_timeout_ms = VCN_WAKE_COMMAND_TIMEOUT_MS; + if (d) DESTROY(d); + // The stuck close runs on the background queue: wait for it before looking. + bool drainedG = vcn_teardown_drain(10000); + expect("and the session it stopped still releases everything", + drainedG && st.liveAccels == 0 && !st.useAfterDestroy); + + // The restart points the stream may send with no key frame at all. +#if defined(VCN_AV1_RESTART_PREDICATE) || defined(VCN_VP9_RESTART_PREDICATE) + { +#if defined(TEST_AV1) + AV1Frame f; + memset(&f, 0, sizeof(f)); + f.frame_type = AV1_KEY_FRAME; + f.refresh_frame_flags = 0xFF; + bool key = vcnav1_is_restart(&f, AV1_PARSE_FRAME_READY); + f.frame_type = AV1_INTRA_ONLY_FRAME; + bool intraAll = vcnav1_is_restart(&f, AV1_PARSE_FRAME_READY); + f.refresh_frame_flags = 0x7F; + bool intraHalf = vcnav1_is_restart(&f, AV1_PARSE_FRAME_READY); + f.refresh_frame_flags = 0xFF; + f.frame_type = AV1_INTER_FRAME; + bool inter = vcnav1_is_restart(&f, AV1_PARSE_FRAME_READY); + bool other = vcnav1_is_restart(&f, AV1_PARSE_SHOW_EXISTING); + expect("AV1 restarts at a key frame", key); + expect( + "not at an intra-only frame, which the spec never lets refresh all " + "eight slots", + !intraAll && !intraHalf); + expect("nor at an inter frame, nor at show_existing", !inter && !other); +#else + VP9Frame f; + memset(&f, 0, sizeof(f)); + f.frame_type = 1; + f.intra_only = 1; + f.refresh_frame_flags = 0xff; + f.reset_frame_context = 2; + bool ctxAll = vcnvp9_is_restart(&f, VP9_PARSE_DECODE); + f.reset_frame_context = 1; + bool ctxOne = vcnvp9_is_restart(&f, VP9_PARSE_DECODE); + f.error_res = 1; + f.reset_frame_context = 3; + bool errRes = vcnvp9_is_restart(&f, VP9_PARSE_DECODE); + f.frame_type = 0; + bool key = vcnvp9_is_restart(&f, VP9_PARSE_DECODE); + expect( + "VP9 does not restart at an intra-only frame with " + "reset_frame_context 2, which resets one context", + !ctxAll); + expect("and at one with error_resilient mode and reset_frame_context 3", + errRes); + expect("not at one that resets no context", !ctxOne); + expect("and at a key frame", key); +#endif + } +#else + printf( + "SKIP the restart predicate is not exposed in this tree (0.3.7 takes " + "key frames only)\n"); +#endif + clip_clear(); - if (argc == 3) hidden_frames(argv[2]); + if (argc >= 3) hidden_frames(argv[2]); +#if defined(TEST_VP9) + if (argc == 5) scaled_references(argv[3], argv[4]); +#endif free(frame0); return failures ? 1 : 0; diff --git a/GPU/decode/tests/vp9state.c b/GPU/decode/tests/vp9state.c index 03bbd56c..85777d39 100644 --- a/GPU/decode/tests/vp9state.c +++ b/GPU/decode/tests/vp9state.c @@ -10,6 +10,9 @@ // 4. A 65536 wide key frame header that codes more than 64 tile columns is // refused and leaves the state as it was; the same header with 64 tile // columns parses. +// 5. A profile 0 inter frame after a 10-bit profile 2 key frame is refused +// (the profile table has no such frame) and leaves the stream depth as +// it was; the next valid key frame decodes. // // usage: vp9state file.ivf (a profile 0 VP9 stream; exit status 0 = pass) #include @@ -220,6 +223,31 @@ int main(int argc, char** argv) { expect("the refused wide frame leaves the state as it was", same_state(p, before)); + // A profile 2 key frame at 10 bits, then a profile 0 inter frame: the + // profile table has no "profile 0, 10 bits", so the inter frame is refused + // with the stream depth as it was, and the next valid key frame decodes. + // The three chunks are the V1 finding's inputs. + static const uint8_t v1key[] = {0x93, 0x49, 0x83, 0x42, 0x10, 0x01, 0xf8, + 0x01, 0xf8, 0x00, 0x19, 0x00, 0x00, 0x04, + 0x42, 0x00, 0x00}; + static const uint8_t v1inter[] = {0x86, 0x03, 0xc0, 0x02, 0x08, 0x00, 0x32, + 0x00, 0x00, 0x04, 0x42, 0x00, 0x00}; + static const uint8_t v1next[] = {0x83, 0x49, 0x83, 0x42, 0x20, 0x03, 0xf0, + 0x03, 0xf0, 0x00, 0x32, 0x00, 0x00, 0x08, + 0x42, 0x00, 0x00}; + vp9_parser_init(q); + expect("a profile 2 key frame at 10 bits decodes", + !vp9_parse_chunk(q, v1key, sizeof v1key, on_frame, NULL) && + q->fh.profile == 2 && q->fh.bit_depth == 10 && + q->ref[0].valid && q->ref[0].bit_depth == 10); + expect("a profile 0 inter frame after it is refused", + vp9_parse_chunk(q, v1inter, sizeof v1inter, on_frame, NULL) != 0 && + q->bit_depth == 10 && q->err[0]); + expect("the next valid key frame decodes", + !vp9_parse_chunk(q, v1next, sizeof v1next, on_frame, NULL) && + q->fh.profile == 0 && q->fh.bit_depth == 8 && q->ref[0].valid && + q->ref[0].bit_depth == 8); + free(p); free(before); free(q); diff --git a/GPU/decode/vc1/vcnvc1.c b/GPU/decode/vc1/vcnvc1.c index b2004dd3..d76393d2 100644 --- a/GPU/decode/vc1/vcnvc1.c +++ b/GPU/decode/vc1/vcnvc1.c @@ -14,6 +14,12 @@ typedef struct { char err[256]; int failure; unsigned fwErrors; // of sessions already closed + // Frames that did not go to the engine because no session could take them: + // the ones a sleep took the session away from, and the ones that needed a + // reference the session rebuilt at the wake does not have yet. + unsigned dropped; + bool ramping; // rebuilt after a sleep: drop what has no reference yet + bool broken; // stopped: the stream sent no intra picture after the sleep } VcnVc1; // Bit positions of Mesa's get_vc1_msg (radeon_vcn_dec.c) and build_vc1_msg @@ -71,6 +77,9 @@ static void end_session(VcnVc1* d) { d->vcn = NULL; } d->refs = 0; + // The rebuild after a sleep sets ramping back right after end_session. + d->ramping = false; + d->dropped = 0; } static bool is_b(uint8_t type) { return type == VC1_B || type == VC1_BI; } @@ -86,6 +95,37 @@ static int on_picture(void* ctx, Vc1Parser* p, const Vc1Picture* pic) { if (d->vcn && (vcnlegacy_width(d->vcn) != p->width || vcnlegacy_height(d->vcn) != p->height)) end_session(d); + // A session from before a system sleep cannot take another frame. An I or + // BI frame is intra coded and predicts from no other frame (SMPTE 421M + // 7.1.1.3, frame type in Table 20), so it decodes the same in a new session: + // the frames up to it are dropped without an error — the host sees the + // stream carry on — and it starts the new session. A sequence header or an + // entry point header in front of it is what can change the coded size or the + // loop filter state, and both are rebuilt with the session (the size check + // above, vcnvc1_fill_block for the flags). The P and skipped frames after an + // I frame of an open stream need frames this session never decoded, and the + // reference check below drops them (ramping). + if (d->vcn && vcnlegacy_session_lost(d->vcn)) { + if (pic->type != VC1_I && pic->type != VC1_BI) { + // Bounded like the AV1 and VP9 rebuilds (REBUILD_MAX_DROPPED there): a + // stream that sends no intra picture is stopped as a device failure, so + // the host can hand it to another decoder, instead of dropping pictures + // for however long the stream goes without one. + if (++d->dropped > 600) { + d->broken = true; + d->failure = VCNLEGACY_FAIL_DEVICE; + snprintf(d->err, sizeof(d->err), + "no intra picture in %u frames after the system sleep", + d->dropped); + return -1; + } + return 0; + } + vcnlegacy_log_rebuild(d->vcn, "a VC-1 I frame", d->dropped); + end_session(d); + d->dropped = 0; + d->ramping = true; + } if (!d->vcn) { VcnLegacyConfig cfg = { .codecId = VCN_CODEC_VC1, @@ -108,6 +148,10 @@ static int on_picture(void* ctx, Vc1Parser* p, const Vc1Picture* pic) { : (pic->type == VC1_P || pic->type == VC1_SKIPPED) ? 1 : 0; if (d->refs < need) { + if (d->ramping) { + d->dropped++; + return 0; + } snprintf(d->err, sizeof(d->err), "VC-1 frame without its reference frame%s", need == 2 ? "s" : ""); d->failure = VCNLEGACY_FAIL_REFERENCE; @@ -163,6 +207,7 @@ static int on_picture(void* ctx, Vc1Parser* p, const Vc1Picture* pic) { if (d->lastRef) CVPixelBufferRelease(d->lastRef); d->lastRef = CVPixelBufferRetain(target); } + if (d->ramping && d->refs >= 2) d->ramping = false; int stop = d->out ? d->out(d->outCtx, target, is_b(pic->type) ? VCNLEGACY_PIC_B : VCNLEGACY_PIC_REFERENCE, @@ -217,6 +262,14 @@ static int decode(void* v, const uint8_t* chunk, size_t size, d->outCtx = ctx; d->err[0] = 0; d->failure = VCNLEGACY_FAIL_STREAM; + if (d->broken) { + snprintf(d->err, sizeof(d->err), + "session stopped: no intra picture in %u frames after the " + "system sleep", + d->dropped); + d->failure = VCNLEGACY_FAIL_DEVICE; + return -1; + } bool raw = d->parser.have_sequence && d->parser.profile != VC1_PROFILE_ADVANCED; int r = raw ? vc1_parse_frame(&d->parser, chunk, size, on_picture, d) diff --git a/GPU/decode/vp9/vcnvp9.c b/GPU/decode/vp9/vcnvp9.c index 8c25df3a..b27d8d24 100644 --- a/GPU/decode/vp9/vcnvp9.c +++ b/GPU/decode/vp9/vcnvp9.c @@ -77,12 +77,16 @@ struct VcnVP9 { // it is rebuilt at the next key frame (on_frame). bool rebuildAtKey; unsigned keptAfterWake; // frames decoded on it since the sleep was seen - bool needKey; // rebuilt after a failure: drop frames until a key frame - unsigned dropped; // frames dropped since that rebuild - unsigned rebuilds; // driver objects rebuilt in this session (one per sleep) - uint32_t lastFw; // firmware result of the last command that finished - int failure; // VCNVP9_FAIL_* of the last error - bool shown; // the current decode call output a frame + bool needKey; // rebuilt after a failure: drop frames until a key frame + unsigned dropped; // frames dropped since that rebuild + // The long limit applies to the first command on the rebuilt session too: + // right after a wake the engine can still take seconds, and a timeout there + // would stop a session that is healthy. Cleared by the first command that + // finishes on it. + bool wakeGrace; + uint32_t lastFw; // firmware result of the last command that finished + int failure; // VCNVP9_FAIL_* of the last error + bool shown; // the current decode call output a frame CVPixelBufferRef hidden; // retained: last frame it decoded without showing unsigned fwErrors; // decodes the firmware reported as failed unsigned done; // decode commands that finished @@ -95,6 +99,7 @@ static os_log_t vlog(void) { static dispatch_once_t once; dispatch_once(&once, ^{ l = os_log_create("com.droga.vtvp9vcn", "driver"); + if (!l) l = OS_LOG_DEFAULT; }); return l; } @@ -680,11 +685,10 @@ VcnVP9* vcnvp9_create(uint32_t maxWidth, uint32_t maxHeight, char* err, // plug-in session, so the host's decoder object lives on. The references live // in the old driver's DPB and the probability contexts in its context, so the // pictures and the reference slots go; the parser keeps the header being -// decoded. busy: the old session's last command may still be on the GPU, so -// its accelerator is closed on the teardown queue and the pictures are let go -// only after that. False when the rebuild fails: the caller then stops the -// session as PR 160 did. -static bool vp9_rebuild(VcnVP9* d, bool busy, char* why, size_t whyLen) { +// decoded. The old accelerator is closed on the teardown queue, never on this +// thread (see the note below). False when the rebuild fails: the caller then +// stops the session as PR 160 did. +static bool vp9_rebuild(VcnVP9* d, char* why, size_t whyLen) { CVPixelBufferRef old[NUM_DPB + 1]; int n = 0; for (int i = 0; i < NUM_DPB; i++) @@ -696,20 +700,23 @@ static bool vp9_rebuild(VcnVP9* d, bool busy, char* why, size_t whyLen) { old[n++] = d->hidden; d->hidden = NULL; } - if (busy) { - // Without memory for the list the pictures are never let go: a command - // still on the GPU may write into them. - CVPixelBufferRef* keep = n ? malloc((size_t)n * sizeof(*keep)) : NULL; - if (keep) memcpy(keep, old, (size_t)n * sizeof(*keep)); - int kept = keep ? n : 0; - vcn_session_drop_later(&d->s, "VP9 session from before the sleep", ^{ - for (int i = 0; i < kept; i++) CVPixelBufferRelease(keep[i]); - free(keep); - }); - } else { - vcn_session_drop(&d->s); - for (int i = 0; i < n; i++) CVPixelBufferRelease(old[i]); - } + // The old accelerator always goes on the teardown queue, not on this thread: + // its close still shuts three IOKit user clients, and on the kernel side the + // close of a video context goes through PowerPlay's notify, which can wait + // after a failed wake (vcnsession.c, vcn_session_close). Nothing of the new + // session waits for it, and the pictures are let go only after it, because a + // command the wake dropped may still write into them. 0.3.7 closed it here + // whenever the last command had finished, which is the normal path and the + // one the teardown queue exists for. Without memory for the list the pictures + // are never let go. + CVPixelBufferRef* keep = n ? malloc((size_t)n * sizeof(*keep)) : NULL; + if (keep) memcpy(keep, old, (size_t)n * sizeof(*keep)); + int kept = keep ? n : 0; + vcn_session_drop_later(&d->s, "VP9 session from before the sleep", + "the system slept since it opened", ^{ + for (int i = 0; i < kept; i++) CVPixelBufferRelease(keep[i]); + free(keep); + }); memset(d->dpbRefs, 0, sizeof(d->dpbRefs)); for (size_t i = 0; i < sizeof(d->parser.ref) / sizeof(d->parser.ref[0]); i++) { @@ -735,21 +742,20 @@ static bool vp9_rebuild(VcnVP9* d, bool busy, char* why, size_t whyLen) { } if (!vcn_session_reopen(&d->s, &lib, svc, vlog(), why, whyLen)) return false; if (vp9_create_context(d, why, whyLen)) { - vcn_session_drop(&d->s); + vcn_session_drop_later(&d->s, "VP9 session, CreateContexts failed", + "no command was ever sent to it", ^{}); return false; } - d->rebuilds++; return true; } // Rebuilds now (vp9_rebuild) and leaves the session decoding on the new driver; // dropUntilKey: the frames before the next key frame are dropped. False, with // the session stopped as a device failure, when the rebuild fails. -static bool rebuild_now(VcnVP9* d, bool busy, bool dropUntilKey, - const char* cause) { +static bool rebuild_now(VcnVP9* d, bool dropUntilKey, const char* cause) { char why[200]; unsigned kept = d->keptAfterWake; - if (!vp9_rebuild(d, busy, why, sizeof(why))) { + if (!vp9_rebuild(d, why, sizeof(why))) { d->rebuildAtKey = false; d->broken = true; d->failure = VCNVP9_FAIL_DEVICE; @@ -765,29 +771,36 @@ static bool rebuild_now(VcnVP9* d, bool busy, bool dropUntilKey, d->keptAfterWake = 0; d->needKey = dropUntilKey; d->dropped = 0; + // A fresh context may still be coming out of the wake: the first command on + // it gets the long limit (0.3.7 gave it the usual second straight away). + d->wakeGrace = true; if (dropUntilKey) os_log_error( vlog(), "the session from before the sleep failed after the wake " "(%{public}s, %u frames decoded on it before): driver rebuilt, " - "frames are dropped until the next key frame", - cause, kept); + "frames are dropped until the next key frame; the old driver objects " + "stay allocated, up to %d MiB not returned to the system", + cause, kept, + (int)(VCN_NUM_BS * (long long)VCN_BS_SIZE / (1024 * 1024))); else os_log_error(vlog(), "driver rebuilt at the first key frame after the sleep (%u " "frames decoded on the session from before it), no frame " - "dropped", - kept); + "dropped; the old driver objects stay allocated, up to %d MiB " + "not returned to the system", + kept, + (int)(VCN_NUM_BS * (long long)VCN_BS_SIZE / (1024 * 1024))); return true; } // The session from before the sleep failed on the frame being decoded: it is // rebuilt at once and this frame is dropped, like the ones after it until a // key frame. 0, or -1 when the rebuild fails. -static int failed_after_wake(VcnVP9* d, bool busy) { +static int failed_after_wake(VcnVP9* d) { char cause[256]; snprintf(cause, sizeof(cause), "%s", d->err); - if (!rebuild_now(d, busy, true, cause)) return -1; + if (!rebuild_now(d, true, cause)) return -1; d->err[0] = 0; d->failure = VCNVP9_FAIL_STREAM; d->dropped = 1; @@ -809,7 +822,8 @@ static void destroy_now(VcnVP9* d) { void vcnvp9_destroy(VcnVP9* d) { if (!d) return; - vcn_teardown(d->stuck, vcn_session_lost(&d->s), vlog(), "VP9 session", ^{ + vcn_teardown(d->stuck, vcn_session_lost(&d->s), vlog(), "VP9 session", NULL, + ^{ destroy_now(d); }); } @@ -863,16 +877,33 @@ static int submit(VcnVP9* d, VP9Params* prm) { } uint32_t fw = 0; int ds = 0; - // Longer on the session from before a sleep: right after a wake the driver - // can take seconds before a command runs (vcndriver.h). - unsigned limit = - d->rebuildAtKey ? vcn_wake_command_timeout_ms : VCN_COMMAND_TIMEOUT_MS; + // Longer on the session from before a sleep, and until one command on the + // rebuilt one has finished: right after a wake the driver can take seconds + // before a command runs (vcndriver.h). + unsigned limit = d->rebuildAtKey || d->wakeGrace ? vcn_wake_command_timeout_ms + : VCN_COMMAND_TIMEOUT_MS; VcnWaitResult w = vcn_wait_command(FN(QueryAVDCommandStatus), d->s.drv, refcons[0], limit, &fw, &ds); if (w == VCN_WAIT_TIMEOUT) { // The GPU still holds this command. Sending more work, or reading the // target, could only make things worse: the session stops here. d->stuck = d->broken = true; + // Unless the system slept inside this call. The timeout is measured on a + // clock that stops while the machine is asleep, so the frame that was on + // the GPU when it slept times out right after the wake, and nothing looked + // again at the sleep: 0.3.7 stopped the session there instead of rebuilding + // it, which is the one thing 0.3.7 exists to avoid. + if (!d->rebuildAtKey && vcn_session_lost(&d->s)) { + d->rebuildAtKey = true; + d->keptAfterWake = 0; + os_log_error(vlog(), + "the system slept while a frame was on the GPU: the frame " + "was given up on after the wake, the session is rebuilt"); + snprintf(d->err, sizeof(d->err), + "the GPU did not finish the frame in %u ms after the sleep", + limit); + return -1; + } snprintf(d->err, sizeof(d->err), "the GPU did not finish a frame in %u ms; session stopped", limit); return -1; @@ -887,6 +918,9 @@ static int submit(VcnVP9* d, VP9Params* prm) { d->failure = VCNVP9_FAIL_STREAM; d->done++; d->lastFw = fw; + // One command finished on the rebuilt session: the engine came back, and the + // usual limit applies again. + d->wakeGrace = false; // Counted, not refused: the VP9 result goes through the AV1 processor's // status reader, and what it reports for VP9 has not been checked on a GPU. // The first one of a session is logged at once, the count goes in the stats @@ -899,25 +933,20 @@ static int submit(VcnVP9* d, VP9Params* prm) { return 0; } -static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, - const uint8_t* data, size_t size) { +static int decode_one(void* vctx, VP9Parser* p, VP9ParseResult kind, + const uint8_t* data, size_t size) { VcnVP9* d = vctx; const VP9Frame* h = &p->fh; - // A frame after which nothing decoded before it is used: a key frame - // (refreshes every slot and resets the four probability contexts), or an - // intra-only frame that does both (all eight slots refreshed, and - // error_res or reset_frame_context 3). Another intra-only frame keeps - // slots or contexts the frames after it may use, which live in the old - // driver's DPB and context. - bool restart = - kind == VP9_PARSE_DECODE && - (h->frame_type == 0 || (h->intra_only && h->refresh_frame_flags == 0xff && - (h->error_res || h->reset_frame_context == 3))); + // A frame after which nothing decoded before it is used: a key frame, or an + // intra-only frame that refreshes all eight slots and resets the four + // probability contexts (vcnvp9_is_restart, with the spec sections). Another + // intra-only frame keeps slots or contexts the frames after it may use, which + // live in the old driver's DPB and context. + bool restart = vcnvp9_is_restart(h, kind); // The system slept since the driver side opened, and it kept decoding (a // real sleep on this Mac did not break it): it is replaced at the first such // frame, which then decodes on the new one. - if (d->rebuildAtKey && restart && !rebuild_now(d, false, false, NULL)) - return -1; + if (d->rebuildAtKey && restart && !rebuild_now(d, false, NULL)) return -1; // After a rebuild that followed a failure nothing from before it can be // used: every frame but such a key frame is dropped, with no picture and no // error, and the key frame starts the decoder again. Bounded: a stream that @@ -977,6 +1006,28 @@ static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, r->bit_depth, h->bit_depth); return -1; } + // The video engine predicts from a reference up to twice as small as the + // frame bit-exactly (vp90-2-22-svc_1280x720_3, 640x360 layer: 320x180 + // reference, identical to libvpx). From one smaller than that (its + // 1280x720 layer: 320x180 reference, 4x) the picture matches libvpx only + // in its first 180 rows, the reference's height, and is wrong below them + // (mean PSNR Y 7.9 dB over the 20 pictures), and the error carries into + // every frame predicted from it. A wrong picture is worse than no + // picture: refuse the frame (whether VideoToolbox then tries another + // decoder was not checked). Which of the three references a block uses is + // known only to the engine, so any reference out of range refuses the + // frame. The limit came from comparing pictures, not from the firmware; + // ratios between 2x and 4x were not tried and are refused too. A + // reference larger than the frame is not refused: the resize vectors + // predict from one up to 2x larger bit-exactly. + if (2 * r->width < h->width || 2 * r->height < h->height) { + snprintf( + d->err, sizeof(d->err), + "reference %ux%u is more than 2x smaller than the %ux%u frame: " + "the video engine does not scale it bit-exactly", + r->width, r->height, h->width, h->height); + return -1; + } } if (h->width > d->maxW || h->height > d->maxH) { snprintf(d->err, sizeof(d->err), "%ux%u is over the session maximum", @@ -1044,12 +1095,12 @@ static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, if (submit(d, &prm)) // On the session from before a sleep, a driver failure is taken for the // sleep's doing: rebuilt at once, instead of stopping the session. - return d->rebuildAtKey && d->broken ? failed_after_wake(d, d->stuck) : -1; + return d->rebuildAtKey && d->broken ? failed_after_wake(d) : -1; if (d->rebuildAtKey) { if (d->lastFw) { // A firmware error on it after the wake: its picture is not trusted. snprintf(d->err, sizeof(d->err), "firmware result %u", d->lastFw); - return failed_after_wake(d, false); + return failed_after_wake(d); } d->keptAfterWake++; } @@ -1065,6 +1116,22 @@ static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, return 0; } +// A frame that was not decoded leaves the reference slots it should have +// refreshed holding older pictures. Frames that predict from them would decode +// without an error and show a wrong picture, so those slots are emptied: the +// frames that read them are refused ("missing reference") until a frame +// refreshes them again, which is how libvpx treats a frame it could not decode. +static int on_frame(void* vctx, VP9Parser* p, VP9ParseResult kind, + const uint8_t* data, size_t size) { + int r = decode_one(vctx, p, kind, data, size); + if (r && kind == VP9_PARSE_DECODE) { + for (int i = 0; i < 8; i++) + if (p->fh.refresh_frame_flags & (1u << i)) p->ref[i].valid = false; + recount_refs((VcnVP9*)vctx); + } + return r; +} + int vcnvp9_decode(VcnVP9* d, const uint8_t* chunk, size_t size, int64_t tag, VcnVP9OutputFn fn, void* ctx) { d->out = fn; diff --git a/GPU/decode/vp9/vcnvp9.h b/GPU/decode/vp9/vcnvp9.h index a4c451f9..c2ae6908 100644 --- a/GPU/decode/vp9/vcnvp9.h +++ b/GPU/decode/vp9/vcnvp9.h @@ -56,3 +56,19 @@ CVPixelBufferRef vcnvp9_hidden_picture(VcnVP9* d); void vcnvp9_color(VcnVP9* d, VcnColor* c); // Decodes the GPU firmware reported as failed (the picture was still output). unsigned vcnvp9_firmware_errors(VcnVP9* d); + +// True when a parsed frame is a place a session can start over: nothing decoded +// before it is used after it. A key frame, or an intra-only frame that replaces +// all eight slots and resets all four probability contexts: +// error_resilient_mode or reset_frame_context 3. reset_frame_context 2 resets +// only the context frame_context_idx names (libvpx +// vp9_setup_past_independence), and the other three live in the old driver's +// buffers: a later frame that reads one of them would decode with the new +// session's default probabilities. +#define VCN_VP9_RESTART_PREDICATE 1 +static inline bool vcnvp9_is_restart(const VP9Frame* h, VP9ParseResult kind) { + if (kind != VP9_PARSE_DECODE) return false; + if (h->frame_type == 0) return true; + return h->intra_only && h->refresh_frame_flags == 0xff && + (h->error_res || h->reset_frame_context == 3); +} diff --git a/GPU/decode/vp9/vp9parse.c b/GPU/decode/vp9/vp9parse.c index 6c423792..1b3a6ee3 100644 --- a/GPU/decode/vp9/vp9parse.c +++ b/GPU/decode/vp9/vp9parse.c @@ -222,6 +222,13 @@ static int parse_header(VP9Parser* p, const uint8_t* data, size_t size) { h->bit_depth = p->bit_depth; h->subsampling_x = p->subsampling_x; h->subsampling_y = p->subsampling_y; + // The profile table leaves no room for an inherited depth of another + // profile: 8 bits only under profiles 0 and 1, 10 or 12 under 2 and 3 + // (libvpx ties the depth to the profile the same way, in + // read_bitdepth_colorspace_sampling). Refuse the frame; the depth of the + // stream stays as it was. + if ((h->profile < 2) != (h->bit_depth == 8)) + return fail(p, "profile %d frame at %d bits", h->profile, h->bit_depth); if (!h->error_res) { h->refresh_frame_context = (int)f(b, 1); h->frame_parallel = (int)f(b, 1); diff --git a/GPU/docs/how-it-works.md b/GPU/docs/how-it-works.md index 4ff87d83..afc36b28 100644 --- a/GPU/docs/how-it-works.md +++ b/GPU/docs/how-it-works.md @@ -145,7 +145,7 @@ ends. A failed driver call or a stuck command is reported to VideoToolbox as a m `canAcceptFormatDescription` says no from then on. It reads the format under a lock of its own, so it never waits for a frame the GPU is decoding. -### A system sleep (0.3.7) +### A system sleep (0.3.9) Apple's kernel driver keeps a decoder's video context across a sleep, but restarts the video engine under it. Read in IDA (AMDRadeonX6000, 26.7.3 KDK): `systemWillSleep` calls @@ -163,19 +163,27 @@ a hang after a wake, which was not reproduced here. So an AV1 or VP9 session from before a sleep keeps decoding (`vcn_session_lost` in `decode/common/vcnsession.c` only notices the sleep), and its driver objects are replaced at -its next key frame, where nothing decoded before is needed any more (`rebuild_now` in -`vcnav1.c` and `vcnvp9.c`): an AV1 key frame that refreshes all eight reference slots, a VP9 -key frame, or a VP9 intra-only frame that refreshes all eight and resets all four -probability contexts. The old accelerator is closed with `AVD_DestroyAVDAccelerator` only, -a new accelerator, driver, context and bitstream pool are opened in the same plug-in -session, and the key frame decodes on them; no frame is dropped. If the old session fails -after the wake (a driver call fails, a command does not finish, or the firmware reports an -error), it is replaced at once and the frames up to the next such key frame are dropped: -noErr with no picture, as for a hidden frame, at most 600 of them, then a malfunction -(-12911). A command that did not finish has its accelerator closed on the background -queue, and its pictures are let go after that. Until the replacement, a command on the old -session may take 15 s instead of 1 s. A replacement that fails stops the session with --12911, and VideoToolbox makes a new decoder. +its next restart point, where nothing decoded before is needed any more (`rebuild_now` in +`vcnav1.c` and `vcnvp9.c`, and the rule itself in `vcnav1_is_restart` / `vcnvp9_is_restart`): +an AV1 key frame that refreshes all eight reference slots (an intra-only frame never may), +a VP9 key frame, or a VP9 intra-only frame that refreshes all eight slots and resets all +four probability contexts (`reset_frame_context` 3 or error-resilient mode; 2 resets only +one). The old accelerator is closed with `AVD_DestroyAVDAccelerator` only, on the +teardown queue and never on the decoding thread, a new accelerator, driver, context and +bitstream pool are opened in the same plug-in session, and the frame decodes on them; no +frame is dropped. If the old session fails after the wake (a driver call fails, a command +does not finish, the firmware reports an error, or the machine slept while a frame was on the +GPU), it is replaced at once and the frames up to the next restart point are dropped: noErr +with no picture, as for a hidden frame, at most 600 of them, then a malfunction (-12911). A +command that did not finish has its accelerator closed on the background queue, and its +pictures are let go after that. Until the replacement, and for the first command that +finishes on the new session, a command may take 15 s instead of 1 s: right after a wake a +fresh context can still be slow, and 0.3.7 dropped that protection at the replacement itself. +A replacement that fails stops the session with -12911, and VideoToolbox makes a new decoder. + +The sleep may also land inside a decode call: the frame is on the GPU, the 1 s timeout is +measured on a clock that stops while the machine is asleep, so the wait expires right after +the wake. That case now reaches the same replacement instead of stopping the session. A sleep is seen without any notification: the time the Mac has spent asleep (`mach_continuous_time` minus `mach_absolute_time`), the time of the last wake @@ -196,9 +204,22 @@ or such close. New sessions open while one from before a sleep is still open; the plug-ins only count those for the log, through the process's local notification center (`CFNotificationCenterGetLocalCenter`, which calls every observer on the posting thread), -because each plug-in bundle has its own copy of the session code. The MPEG-2, VC-1 and -MPEG-4 decoders (`vcnlegacy.c`) do not replace their sessions: one from before a sleep -fails its pictures as a malfunction, as in 0.3.6. +because each plug-in bundle has its own copy of the session code. + +The MPEG-2, VC-1 and MPEG-4 decoders (`common/vcnlegacy.c`) replace their session the same +way since 0.3.9, with one difference: they do drop pictures. An intra picture is the first +one a new session can decode, so the pictures between the sleep and the next I picture are +dropped with no error — the host sees the stream carry on and no malfunction — and the I +picture starts the new session (`vcnlegacy_session_lost` in the codec layer, `end_session` +and `vcnlegacy_create` at the picture). An MPEG-2 I picture (13818-2 6.3.1), a VC-1 I or BI +frame (SMPTE 421M 7.1.1.3) and an MPEG-4 I-VOP (14496-2 6.3.3) are coded from nothing +before them, so they decode the same in a session that has seen nothing. A GOP header's +`closed_gop` says the pictures after the I need nothing from the one before (13818-2 +6.2.2.6); with an open GOP, or with `broken_link`, the leading B pictures predict from the +previous GOP, and the reference check of the codec layer drops them while the new session +has not decoded it (`ramping`), instead of drawing them from a DPB it does not have. A +driver call that fails, a command that does not finish or a firmware error still stops the +session as in 0.3.6: only a sleep is rebuilt from. What still waits with no limit the plug-in can set is inside Apple's code: the driver calls themselves (`ScheduleAVDCommands`, `QueryAVDCommandStatus`, `CreateAVDAccelerator`, diff --git a/GPU/docs/testing.md b/GPU/docs/testing.md index aa66c24a..97a02a4e 100644 --- a/GPU/docs/testing.md +++ b/GPU/docs/testing.md @@ -113,7 +113,7 @@ them, when, on which card and macOS build, and add the result to `docs/status.md leaves no context to delete, and `QueryAVDCommandStatus` with `.wait = 0` returns at once (status 1 done, 2 running). Still open: how long the kernel's own wait can last after a GPU restart. -- Decoders 0.3.7, a system sleep during a decode: `vtvp9test` and `vtav1test` with +- Decoders 0.3.8, a system sleep during a decode: `vtvp9test` and `vtav1test` with `-loop N -pace 30` keep one session going across `pmset sleepnow`, and `-renew` makes a new session for every pass in the same process. No pass may have errors or frames that differ from the reference, before or after the wake, and the kernel log must show no GPU @@ -121,6 +121,16 @@ them, when, on which card and macOS build, and add the result to `docs/status.md "keeps decoding and is rebuilt at the next key frame" and "driver rebuilt at the first key frame after the sleep"; "failed after the wake" means the old session failed and frames were dropped up to a key frame. A first real run of 0.3.6 on this Mac (2026-11-25) failed - every frame of the old sessions; 0.3.5 passed. Only `sessiontest` and `staletest` (made-up - driver and sleep) have run for 0.3.7. + every frame of the old sessions; 0.3.5 passed. For 0.3.8, also count "the system slept + while a frame was on the GPU" (a sleep that landed inside a decode call; it must be + followed by a replacement line, not by -12911) and any malfunction in the first frame + after a replacement (the 15 s limit must cover it). Only `sessiontest` and `staletest` + (made-up driver and sleep) have run for 0.3.8. +- Decoders 0.3.9, the three legacy codecs after a sleep: `layertest` tells the codec layer its + session is from before a sleep, and checks that the pictures up to the next I picture are + dropped with no command and no error, that the I picture starts a new session, and that the + pictures after it decode on it — for MPEG-2, VC-1 and MPEG-4. A real sleep with those three + (a video in `quicklookd` or Safari across `pmset sleepnow`) is still the owner's test: the + picture must come back at the next I picture, with "a session from before a system sleep: a + new one at …" in the log and no -12911. - Everything at once: `install/check.sh` ends in one line. diff --git a/GPU/install/common.zsh b/GPU/install/common.zsh index 6e97b4e6..08ebf88e 100644 --- a/GPU/install/common.zsh +++ b/GPU/install/common.zsh @@ -95,7 +95,9 @@ gpu_dir_unsafe() { # folder mode=$(/usr/bin/stat -f '%Lp' "$d") [[ $owner == root ]] || { print -r -- "$d belongs to $owner, not root"; return 0; } (( (8#$mode & 8#022) == 0 )) || { print -r -- "$d can be written by others than root (mode $mode)"; return 0; } - [[ $(/bin/ls -lde "$d" 2>/dev/null | head -1 | cut -c11) == "+" ]] && + # an entry that also has extended attributes shows @ in the mode column, so look for + # the ACL lines ls -lde prints after the first one + [[ -n $(/bin/ls -lde "$d" 2>/dev/null | sed -n '2,$p') ]] && { print -r -- "$d has an access control list"; return 0; } fi d=${d:h} @@ -177,12 +179,57 @@ help_of() { # script # Those processes only map code macOS trusts (library validation). The plug-ins get in when # one of these holds: AMFI is switched off, AMFIPass runs, the plug-ins are signed under a CA # the Mac has been made to trust, or VCNVTLoader runs and lists them. See decode/loader/README.md. -boot_args() { /usr/sbin/sysctl -n kern.bootargs 2>/dev/null; } -amfi_off() { boot_args | grep -qE '(^| )amfi_get_out_of_my_way=(0x)?0*[1-9a-fA-F]'; } -# A loaded AMFIPass does nothing when Lilu or AMFIPass itself is switched off by boot-args. +# The boot arguments of this boot, and the kexts loaded now. A test stands in for either by +# setting VCNVT_BOOT_ARGS or VCNVT_LOADED_KEXTS (tests/amfidetect.sh); nothing else sets them, +# and with neither the system is asked as before. +boot_args() { print -r -- "${VCNVT_BOOT_ARGS-$(/usr/sbin/sysctl -n kern.bootargs 2>/dev/null)}"; } +loaded_kexts() { print -r -- "${VCNVT_LOADED_KEXTS-$(/usr/sbin/kextstat 2>/dev/null)}"; } +# The value of one boot argument as a number, or nothing when the argument is not there. Both +# forms a boot loader writes are taken, -name and name, with or without =value, and a switch +# with no value counts as 1 (the app counts it so: Sources/RyzenStatus/Core/Permissions.swift, +# promptsBlocked). 0x80 is read as hex, 128 as decimal; anything else is not a number. +boot_arg_number() { # name + emulate -L zsh + local name=$1 args=$(boot_args) a v hex found=0 + args=${args//$'\n'/ } + for a in ${(s: :)args}; do + case $a in + ($name|-${name}) v=1; found=1 ;; + (${name}=*|-${name}=*) v=${a#*=}; found=1 ;; + esac + (( found )) && break + done + (( found )) || return 0 + [[ -n $v ]] || v=1 + if [[ $v == 0[xX]* ]]; then + hex=${v#0[xX]} + [[ $hex =~ '^[0-9a-fA-F]+$' ]] || return 0 + print -r -- "$(( 16#$hex ))" + else + [[ $v =~ '^[0-9]+$' ]] || return 0 + print -r -- "$(( 10#$v ))" + fi +} +# AMFI is out of the way at boot: amfi_get_out_of_my_way set to anything but 0, or amfi with bit +# 0x80 set. The app reads the same two arguments (Permissions.swift, promptsBlocked); before +# 1.90.1 the installer knew only the first, so a Mac booted with amfi=0x80 was told its loader +# kext was needed although nothing gets in the plug-ins' way there. +amfi_off() { + local n=$(boot_arg_number amfi_get_out_of_my_way) + [[ -n $n && $n != 0 ]] && return 0 + n=$(boot_arg_number amfi) + [[ -n $n ]] && (( n & 0x80 )) && return 0 + return 1 +} +# A loaded AMFIPass does nothing when Lilu or AMFIPass itself is switched off by boot-args: +# -amfipassoff and -liluoff, and the same names without the dash, with or without a value (0 +# means it stays on). Lilu reads them with the kernel's own argument parser, which takes both +# spellings (Apple's PE_parse_boot_argn; Lilu's README lists the dashed ones). amfipass_on() { - /usr/sbin/kextstat 2>/dev/null | grep -q 'com.dhinakg.AMFIPass' || return 1 - boot_args | grep -qE '(^| )(-amfipassoff|-liluoff)( |$)' && return 1 + loaded_kexts | grep -q 'com.dhinakg.AMFIPass' || return 1 + local n + n=$(boot_arg_number amfipassoff); [[ -n $n && $n != 0 ]] && return 1 + n=$(boot_arg_number liluoff); [[ -n $n && $n != 0 ]] && return 1 return 0 } # The version of a loaded kext, or nothing when it is not loaded. diff --git a/GPU/install/decoders.sh b/GPU/install/decoders.sh index d6acb55d..dc203adb 100755 --- a/GPU/install/decoders.sh +++ b/GPU/install/decoders.sh @@ -301,7 +301,7 @@ preflight() { if ! all_built; then : elif amfi_off; then - add_check loading "$label" ok "AMFI is switched off (amfi_get_out_of_my_way), so any plug-in loads" + add_check loading "$label" ok "AMFI is switched off in the boot arguments, so any plug-in loads" elif amfipass_on; then add_check loading "$label" ok "AMFIPass is running" elif [[ ! -x $PROBE ]]; then diff --git a/GPU/install/efikext.zsh b/GPU/install/efikext.zsh index 1a3d3413..c9f81c1b 100644 --- a/GPU/install/efikext.zsh +++ b/GPU/install/efikext.zsh @@ -407,12 +407,13 @@ kext_install() { kext_uninstall() { [[ -x $ENTRY ]] || die "$ENTRY is missing; decode/build.sh builds it" open_target nolilu - # the install record goes first: from here on the kext may be gone - record_remove $KNAME local cfg=$OC/config.plist dst=$OC/Kexts/$NAME entry_state "$cfg" local before=$ENTRY_STATE [[ $before != unreadable ]] || die "config.plist cannot be edited: $ENTRY_DETAIL. Nothing was changed." + # the install record goes here: the check above can still abort without changing anything, + # and the record must not go with it + record_remove $KNAME if [[ $before == none ]] && ! exists "$dst" && ! exists "$dst.new" && ! exists "$dst.old"; then cleanup print -r -- "$KNAME is not on that EFI. Nothing to remove." diff --git a/GPU/install/encoder.sh b/GPU/install/encoder.sh index 6cdca623..97a564c2 100755 --- a/GPU/install/encoder.sh +++ b/GPU/install/encoder.sh @@ -57,7 +57,9 @@ JSON=0 while (( $# )); do case $1 in --efi) - (( $# >= 2 )) && [[ -n $2 ]] || usage_error "--efi needs a partition, for example disk0s1" + # the same check install.sh and undo.sh make (auto is resolved later, by resolve_efi) + (( $# >= 2 )) && [[ $2 == auto || $2 =~ '^disk[0-9]+s[0-9]+$' ]] || + usage_error "--efi takes a partition like disk0s1, or auto" EFI_ID=$2 shift ;; --package) @@ -378,7 +380,11 @@ emit_check() { # The partition a run mounted (OPEN_ID, in common.zsh) is unmounted again however the run # ends. enc_cleanup() { [[ -n $OPEN_ID ]] && efi_close "$OPEN_ID"; OPEN_ID=""; } -trap enc_cleanup EXIT +# One function as the only element, at the top level: a trap list set inside a function stops at its +# first function call when an exit unwinds through it (emulate -L zsh = local traps), and the staged +# copy was left in /private/tmp. Both are no-ops until something is opened or staged. +enc_exit_cleanup() { enc_cleanup; stage_cleanup } +trap enc_exit_cleanup EXIT trap 'enc_cleanup; exit 130' INT TERM HUP # --efi auto: find the partition now, or stop before anything is changed. @@ -411,7 +417,6 @@ do_install() { [[ $CAN_INSTALL -eq 1 ]] || { echo "the encoding fix cannot be installed on this Mac (see the checks)" >&2; print -rl -u2 -- "${CHECK_LINES[@]}"; exit 2; } local rc stage_package "$PKG" || { echo "cannot verify a root-owned copy of the encoding fix package" >&2; exit 1; } - trap stage_cleanup EXIT resolve_efi if [[ -n "$EFI_ID" ]]; then OPEN_ID=$EFI_ID @@ -442,7 +447,6 @@ do_uninstall() { [[ -f $PKG/uninstall.sh ]] || { echo "$(pick "no VCNEncodeFix package in $PKG; build it with encode/build.sh" "no VCNEncodeFix package inside RyzenStatus GPU.app; $APP_DAMAGED")" >&2; exit 1; } local rc stage_package "$PKG" || { echo "cannot verify a root-owned copy of the encoding fix package" >&2; exit 1; } - trap stage_cleanup EXIT resolve_efi if [[ -n "$EFI_ID" ]]; then # taking the kext off needs no Lilu on that EFI diff --git a/GPU/install/install.sh b/GPU/install/install.sh index e551b2bc..e741402a 100755 --- a/GPU/install/install.sh +++ b/GPU/install/install.sh @@ -338,7 +338,12 @@ fi (( PLAN )) && exit 0 # ---- the EFI, once for every part that needs it ---------------------------------------------- +# The EXIT trap does not run when the shell is killed by an untrapped signal, and +# efi_find_opencore below mounts partitions to look inside them: catch the +# signals too, or an interrupt between its mount and its unmount leaves the +# partition mounted. Same shape as encoder.sh and efikext.zsh. trap '[[ -n $OPEN_ID ]] && efi_close "$OPEN_ID"' EXIT +trap '[[ -n $OPEN_ID ]] && efi_close "$OPEN_ID"; OPEN_ID=""; exit 130' INT TERM HUP if needs_efi && [[ -z $EFI_ID ]]; then if efi_find_opencore; then EFI_ID=$EFI_FOUND @@ -374,7 +379,11 @@ for part in $ORDER; do if [[ $part == decoders ]] && (( DEC_AFTER_LOADER )); then print -r -u2 -- "The loader kext is on the EFI and starts at the next boot. Reboot, then $(pick "run 'sudo install/install.sh' again" "open RyzenStatus GPU and use Install what this Mac needs again"): the decoders go in then." fi - (( ${#DONE} )) && print -r -u2 -- "Done before it: ${(j:, :)${DONE/#%tools/gpucontrol and gpusensors}}. $(pick "'sudo install/undo.sh'" "Remove all in this window") takes everything off." + # spell 'tools' out element-wise: a substitution inside the join operates on the joined + # string and would only match a DONE of exactly one element + done_names=() + for done_p in $DONE; do [[ $done_p == tools ]] && done_p="gpucontrol and gpusensors"; done_names+=($done_p); done + (( ${#DONE} )) && print -r -u2 -- "Done before it: ${(j:, :)done_names}. $(pick "'sudo install/undo.sh'" "Remove all in this window") takes everything off." exit 1 fi DONE+=($part) @@ -384,7 +393,8 @@ print print -r -- "== check" /bin/zsh "$SELF_DIR/check.sh" || true print -done_names=${(j:, :)${DONE/#%tools/gpucontrol and gpusensors}} +done_names=() +for done_p in $DONE; do [[ $done_p == tools ]] && done_p="gpucontrol and gpusensors"; done_names+=($done_p); done if [[ ${(j: :)DONE} == tools ]]; then print -r -- "Installed: $done_names, in /usr/local/bin. They work now; no reboot needed." else diff --git a/GPU/install/sensors.sh b/GPU/install/sensors.sh index 0c5cdc39..b6a81274 100755 --- a/GPU/install/sensors.sh +++ b/GPU/install/sensors.sh @@ -233,9 +233,33 @@ RESULT_OK=1 # any) is another version. Nothing is left to install then; check --json calls it # "pendingReboot". PENDING_REBOOT=0 +# What the record of this boot session says waits for the reboot: "remove" when the +# kext was taken off the EFI here and still runs, "none" otherwise. The app's row says +# "removed" with it; check --json calls it "pending". +PENDING=none +# The record of a removal (0.9.1 and 0.9.2 panicked; batch 256): the same file an +# install writes (efikext.zsh), so a check in this boot knows the EFI changed even +# though the kext it started with still runs. +look_removed() { + PENDING=none + local file line boot="" action="" bundle="" + file=$(record_file $KNAME) || return 0 + while IFS= read -r line; do + case $line in + boot=*) boot=${line#*=} ;; + action=*) action=${line#*=} ;; + bundle=*) bundle=${line#*=} ;; + esac + done < "$file" + [[ -n $boot && $boot == $(boot_session) && $action == remove && $bundle == $KBUNDLE ]] || return 0 + # An EFI that still holds the kext wins over the record. + [[ -z $READY_ON ]] || return 0 + PENDING=remove +} conclude() { RESULT_OK=1 PENDING_REBOOT=0 + look_removed local new=$(kext_file_version "$KEXT") on_efi=0 [[ -n $READY_ON && -z $STALE_ON && -n $new && $RUN_VERSION != "$new" ]] && on_efi=1 # what the next boot changes, for the results about a kext that runs now @@ -246,6 +270,12 @@ conclude() { # the kext that runs is what check is about; checks marked FAIL only stop a new install local blocked="" (( CAN_INSTALL )) || blocked=" The checks marked FAIL stop a new install." + # Taken off the EFI in this boot session: say so, whichever state the kext that + # still runs is in. The next boot has no GPUSensors.kext. + if [[ $PENDING == remove ]]; then + RESULT="removed: GPUSensors is off the EFI. It stays loaded until you restart, then it is gone.$TOOLS_NOTE" + return 0 + fi if [[ $RUN_STATE == active && ${RUN_SAMPLES:-0} -gt 0 ]]; then RESULT="working: GPUSensors is active and has readings ($(pick "sensors/build/gpusensors shows them" "RyzenStatus shows them")).$next$update$TOOLS_NOTE$blocked" PENDING_REBOOT=$on_efi @@ -279,7 +309,7 @@ check_json() { print -rn -- "\"version\":\"$(jesc "$(kext_file_version "$KEXT")")\",\"running\":\"$(jesc "$RUN_LINE")\"," print -rn -- "\"tools\":\"$TOOLS_STATE\",\"toolsOnly\":$([[ $TOOLS_ONLY -eq 1 ]] && echo true || echo false)," print -rn -- "\"toolsInstalled\":$([[ $TOOLS_OURS -eq 1 ]] && echo true || echo false)," - print -rn -- "\"pendingReboot\":$([[ $PENDING_REBOOT -eq 1 ]] && echo true || echo false)," + print -rn -- "\"pending\":\"$PENDING\",\"pendingReboot\":$([[ $PENDING_REBOOT -eq 1 ]] && echo true || echo false)," print -rn -- "\"result\":\"$(jesc "$RESULT")\",\"efis\":[${(j:,:)EFI_JSON}],\"checks\":[${(j:,:)CHECKS}]}" print } @@ -331,6 +361,11 @@ do_uninstall() { need_root uninstall [[ $EUID -eq 0 && -z $EFI_DIR ]] && tools_uninstall kext_uninstall || return 0 + # The record of this boot session: the kext still runs, and a check in the same + # boot has to say it is gone from the EFI, not read the running one as installed. + # When the record cannot be written, say what check will miss until the restart. + record_put $KNAME "boot=$(boot_session)" "action=remove" "bundle=$KBUNDLE" "version=$(kext_file_version "$KEXT")" "hash=" || print -r -u2 -- "note: until the restart, 'check' cannot tell the kext was removed here." + return 0 } # Only the commands, for a Mac where the kext is gone already (taken off the EFI by hand, @@ -357,7 +392,9 @@ do_uninstall_tools() { TOOL_DIR=$GPU_TOOL_DIR TOOLS=($GPU_TOOL_NAMES) tool_id() { gpu_tool_id "$1"; } -has_acl() { [[ $(/bin/ls -lde "$1" 2>/dev/null | head -1 | cut -c11) == "+" ]]; } +# an entry that also has extended attributes shows @ in the mode column, so look for the ACL +# lines ls -lde prints after the first one +has_acl() { [[ -n $(/bin/ls -lde "$1" 2>/dev/null | sed -n '2,$p') ]]; } tool_dir_unsafe() { gpu_dir_unsafe "$TOOL_DIR"; } tool_file_unsound() { # file name local f=$1 owner mode diff --git a/GPU/install/undo.sh b/GPU/install/undo.sh index 60179c83..be0d39df 100755 --- a/GPU/install/undo.sh +++ b/GPU/install/undo.sh @@ -102,14 +102,22 @@ if [[ $encoder == yes ]]; then # The partition for the encoding fix's kext: the one given, the one OpenCore started from, # or the mounted EFI that holds VCNEncodeFloor.kext. enc_efi=$EFI_ID - [[ -n $enc_efi ]] || enc_efi=$(efi_booted 2>/dev/null) + enc_efi_refused=0 + if [[ -z $enc_efi ]]; then + local_booted=$(efi_booted 2>/dev/null); local_booted_rc=$? + # efi_booted returning 2: OpenCore started from a partition that is not an EFI partition, + # and no other EFI may be taken in its place (efi_booted in common.zsh). The step is + # skipped and the user is told what to do, below. + (( local_booted_rc == 0 )) && enc_efi=$local_booted + (( local_booted_rc == 2 )) && enc_efi_refused=1 + fi # The same rule install.sh uses: the only EFI partition that holds OpenCore (mounted to # look if need be). Some OpenCore setups do not publish the boot path. - if [[ -z $enc_efi ]] && efi_find_opencore 2>/dev/null; then enc_efi=$EFI_FOUND; fi + if (( ! enc_efi_refused )) && [[ -z $enc_efi ]] && efi_find_opencore 2>/dev/null; then enc_efi=$EFI_FOUND; fi # Never a guess: only an EFI-type partition (a rescue USB stick usually is not one), and # only when exactly one of them holds the kext. Otherwise the kext stays and the user is # told to name the partition. - if [[ -z $enc_efi ]]; then + if (( ! enc_efi_refused )) && [[ -z $enc_efi ]]; then local_cands=() for id in $(efi_ids); do [[ $(efi_field $id Mounted) == Yes ]] || continue @@ -119,7 +127,7 @@ if [[ $encoder == yes ]]; then (( ${#local_cands} == 1 )) && enc_efi=$local_cands[1] fi if [[ -n $enc_efi ]]; then steps+=("install/encoder.sh uninstall --efi $enc_efi") - else steps+=("install/encoder.sh uninstall"); fi + elif (( ! enc_efi_refused )); then steps+=("install/encoder.sh uninstall"); fi fi [[ $decoders == yes ]] && steps+=("install/decoders.sh uninstall") @@ -128,8 +136,12 @@ print -r -- "Steps, in this order:" local_i=1 for s in $steps; do print -r -- " $local_i. sudo $s"; local_i=$((local_i + 1)); done if [[ $encoder == yes && -z ${enc_efi:-} ]]; then - print -r -- " (the encoding fix's kext stays on the EFI: it is not clear which EFI partition is" - print -r -- " yours; run again with --efi diskNsM to take it off too)" + if [[ $enc_efi_refused == 1 ]]; then + print -r -- " (the encoding fix's kext stays on the EFI: OpenCore started from a partition that is not an EFI partition, so no other may be taken in its place; run install/encoder.sh uninstall --efi diskNsM by hand)" + else + print -r -- " (the encoding fix's kext stays on the EFI: it is not clear which EFI partition is" + print -r -- " yours; run again with --efi diskNsM to take it off too)" + fi fi (( DRY )) && { print; print -r -- "Dry run: nothing was changed."; exit 0; } diff --git a/GPU/installer/main.swift b/GPU/installer/main.swift index e28f78bf..82f16eea 100644 --- a/GPU/installer/main.swift +++ b/GPU/installer/main.swift @@ -77,6 +77,10 @@ struct SensorsCheck: Decodable { /// This version is on the EFI and the next boot loads it (an older one, or none, runs /// now): nothing to install. let pendingReboot: Bool? + /// What the record of this boot session says waits for the restart: "install", + /// "remove" (the kext was taken off the EFI here and still runs until the reboot) or + /// "none". Absent from a check that predates it. + let pending: String? let efis: [EFIInfo] let checks: [CheckItem] } @@ -300,7 +304,9 @@ enum ConfirmAction: Identifiable { enum Phase: Equatable { case idle case checking - case running(String) + /// A step is running. privileged: the step asks for the administrator password, which is + /// worth saying before it happens; building the plan runs as the user and asks for nothing. + case running(String, privileged: Bool) case done(String) case failed(String) /// The administrator password prompt (or a restart) was cancelled: nothing changed, @@ -423,6 +429,10 @@ final class Engine: ObservableObject { phase = .failed("Select the GPU tools folder to check this Mac.") return } + // After an action the footer keeps what the action came to: the check runs to + // refresh the rows, and leaving the phase at `.checking` kept the window (and + // its buttons) in the middle of a check that had already finished. + let phaseBefore = phase phase = .checking if !preserveOutput { lastOutput = "" @@ -471,7 +481,7 @@ final class Engine: ObservableObject { : "Could not read one or more check results from install/.") } else { self.suggestion = OptionalSuggestion(encoder: enc, sensors: sns) - if !preserveOutput { self.phase = .idle } + self.phase = preserveOutput ? phaseBefore : .idle } } } @@ -505,7 +515,7 @@ final class Engine: ObservableObject { phase = .failed("GPU tools folder is not selected.") return } - phase = .running("Building install plan") + phase = .running("Building install plan", privileged: false) var args = ["plan"] if withEncoder { args.append("--with-encoder") } if withSensors { args.append("--with-sensors") } @@ -540,7 +550,7 @@ final class Engine: ObservableObject { phase = .failed("This window shows a made-up Mac (RYZENSTATUS_GPU_FAKE_DIR): nothing is installed.") return } - phase = .running(title) + phase = .running(title, privileged: true) lastActionTitle = title lastOutput = "" let inner = Self.stagedCommand(root: root, script: script, args: args) @@ -1184,6 +1194,9 @@ struct ContentView: View { if let sns = engine.sensors { let onEfi = sns.efis.contains(where: { $0.kext != "none" && $0.kext != "unknown" }) let loaded = sns.running.hasPrefix("loaded") + // Taken off the EFI in this boot session: the kext that still runs is not + // installed any more, and the restart finishes the removal. + let removed = sns.pending == "remove" // The EFI copy is this build's and it runs, or it loads at the next boot: nothing // to update. let upToDate = (sns.efis.contains(where: { $0.kext == "current" }) && sns.result.hasPrefix("working:")) @@ -1192,7 +1205,7 @@ struct ContentView: View { let toolsOnly = sns.toolsOnly == true // No kext to take off, but our gpucontrol or gpusensors is still there: Remove // takes just those. - let kextThere = onEfi || loaded || sns.pendingReboot == true + let kextThere = (onEfi || loaded || sns.pendingReboot == true) && !removed let toolsInstalled = sns.toolsInstalled == true let installTitle: String = { if toolsOnly { return sns.tools == "outdated" ? "Update tools" : "Install tools" } @@ -1206,6 +1219,7 @@ struct ContentView: View { ComponentSection( title: "GPU sensors", subtitle: { + if removed { return "Removed — goes away after the next restart" } if !kextThere && !toolsInstalled { return "Optional — not installed" } if sns.pendingReboot == true { return "Optional — installed, starts after the next restart" } if toolsOnly || engine.suggestion?.sensors == true { return "Optional — update ready" } @@ -1326,8 +1340,12 @@ struct ContentView: View { @ViewBuilder var phaseBanner: some View { switch engine.phase { - case .running(let title): - banner(icon: "gearshape.fill", color: .blue, text: "\(title)… enter your administrator password when asked.") + case .running(let title, let privileged): + // Only the steps that run as root ask for a password: the plan is built as the + // user, and saying otherwise made the first moment of the window wrong. + banner(icon: "gearshape.fill", color: .blue, + text: privileged ? "\(title)… enter your administrator password when asked." + : "\(title)…") case .done(let msg): banner(icon: "checkmark.seal.fill", color: .green, text: msg) case .failed(let msg): diff --git a/GPU/sensors/README.md b/GPU/sensors/README.md index 92c213c6..b6960f83 100644 --- a/GPU/sensors/README.md +++ b/GPU/sensors/README.md @@ -375,6 +375,30 @@ accelerator (`AMDAccelChannel::resetHardwareAndReplay`), which never tells Power escape during it is a normal firmware message, not refused, and the read-back still checks it. The kext does not route it. +## Readings that keep up (0.9.3) + +The driver reads the PMLog only when someone reads the accelerator's `PerformanceStatistics` +(`ioreg -r -c IOAccelerator` does). With nothing polling it, the copies stop, after 5 s the kext +publishes no readings, and the fan watchdog refuses a curve, a raised GFX minimum or a raised +power limit with "no fresh readings". + +0.9.1 closed that gap the wrong way: while the kext held one of those, its worker called +`PEM_CWDDEPM_QueryPMLogData` itself, on its own thread, through the power management object the +driver had used. The driver can clear that object while such a call runs (it did, twice on +2026-11-27: `PECI_LockPowerPlayOnly(pem[4])` succeeded and `PECI_UnlockPowerPlayOnly` then read +`pem[4]` as NULL), and no check made before the call can see a clear in the middle of it. 0.9.2 +added those checks; the panic was still possible, so 0.9.3 removes the keeper entirely. + +Now the app does the reading the safe way: while it holds something, RyzenStatus reads the +accelerator's `PerformanceStatistics` at least once a second, so the driver takes its own PMLog +sample and this kext copies it, exactly as it does for any other reader. The kext calls nothing +outside a call the driver itself makes, keeps no power management object, and publishes `Samples` +and `SampleAgeMs` from those reads only. If the app is closed, nothing outside polls: the +watchdog gives the fan back to the firmware, which is safe. + +One second: the watchdog looks once a second and takes a change only while the copy is at most +2 s old (10 s without readings trips it), and the driver's own rate is about once a second too. + ## What has been checked | What | Result | diff --git a/GPU/sensors/VERSION b/GPU/sensors/VERSION index ac39a106..965065db 100644 --- a/GPU/sensors/VERSION +++ b/GPU/sensors/VERSION @@ -1 +1 @@ -0.9.0 +0.9.3 diff --git a/GPU/sensors/kext/kern_control.cpp b/GPU/sensors/kext/kern_control.cpp index e164bdf7..d353ee23 100644 --- a/GPU/sensors/kext/kern_control.cpp +++ b/GPU/sensors/kext/kern_control.cpp @@ -618,7 +618,11 @@ bool callCwdde(const void* in, uint32_t inSize, void* out, uint32_t* outSize, uint32_t* ret) { IOLockLock(gStateLock); void* pp = __atomic_load_n(&gPP, __ATOMIC_ACQUIRE); - if (gTornDown || pp == nullptr || gCwdde == 0 || sleepingLocked() || + // Without the sleep and wake watchers the sleep count never moves, so an + // object from before a sleep would pass: refuse here as well, not only in + // the start-up refusal (review F4). + if (gTornDown || pp == nullptr || gCwdde == 0 || !gWatchSleep || + !gWatchWake || sleepingLocked() || __atomic_load_n(&gSleepGen, __ATOMIC_SEQ_CST) != wSeenGen) { IOLockUnlock(gStateLock); return false; @@ -1531,6 +1535,9 @@ void teardown(bool waitForCall) { bool late = false; IOLockLock(gStateLock); gTornDown = true; + // The object dies with the GPU: drop it here too, so the pointer itself + // never names a dead object (review F3; gTornDown already stops every call). + __atomic_store_n(&gPP, static_cast(nullptr), __ATOMIC_RELEASE); turnOffLocked(gpuctl::WriteOff::Teardown); if (waitForCall && gInFlight) { uint64_t deadline = 0; @@ -1642,6 +1649,29 @@ void startWriting(const char* library) { } // namespace +uint64_t GPUControl::sleepCount() { + return __atomic_load_n(&gSleepGen, __ATOMIC_RELAXED); +} +bool GPUControl::inSleep() { + return __atomic_load_n(&gInSleep, __ATOMIC_SEQ_CST) != 0; +} + +// Wider than what the fan watchdog runs on (od8DogPass, which watches a curve, +// an unknown state, raised GFX clocks and a raised power limit only): an OD8 +// state not confirmed stock, or a power limit above the start-up one. Nothing +// is kept fresh while writing is off, the card is only read, or the GPU went +// away. +bool GPUControl::holdsAny() { + if (gStateLock == nullptr) return false; + uint32_t boot = bootW(); + IOLockLock(gStateLock); + bool on = !gTornDown && !gOwner.isOff() && !gReadOnlyCard; + bool od8 = gOd8Dirty; + bool power = !gOd8Dirty && gHeldW > boot && !gPowerOffAfterWayBack; + IOLockUnlock(gStateLock); + return on && (od8 || power); +} + void GPUControl::init() { gStateLock = IOLockAlloc(); gOd8Lock = IOLockAlloc(); diff --git a/GPU/sensors/kext/kern_control.hpp b/GPU/sensors/kext/kern_control.hpp index 99ba48d6..c92a8887 100644 --- a/GPU/sensors/kext/kern_control.hpp +++ b/GPU/sensors/kext/kern_control.hpp @@ -23,6 +23,22 @@ void init(); void onLibrary(KernelPatcher& patcher, size_t index, mach_vm_address_t address, size_t size, const char* name); +// How many sleeps started since boot (0.9.1). The kext keeps no power +// management object any more (0.9.3), so nothing here pairs a call with the +// sleep count of the object it would use; the count still tells a reader +// whether the kext has seen a sleep. +uint64_t sleepCount(); +// True from ppSleep's start to the end of ppWake. +bool inSleep(); + +// Whether something of the control is on the card and not confirmed stock: a +// fan curve, a clock or voltage change (an OD8 state), or a raised power limit. +// Wider than what the fan watchdog runs on (od8DogPass watches a curve, an +// unknown state, raised GFX clocks and a raised power limit only). Nothing +// calls this: the app reads PerformanceStatistics once a second while it holds +// (0.9.3), not while this is true. +bool holdsAny(); + // What the control did, for ioreg (rebuilt when read). const char* statusText(); const char* profileText(); // the boot profile: asked, set, or why not diff --git a/GPU/sensors/kext/kern_pmlog.cpp b/GPU/sensors/kext/kern_pmlog.cpp index 12f1b962..53497cee 100644 --- a/GPU/sensors/kext/kern_pmlog.cpp +++ b/GPU/sensors/kext/kern_pmlog.cpp @@ -23,8 +23,21 @@ // This file routes the library's _PEM_CWDDEPM_QueryPMLogData. The route calls // the original first, with the same arguments, and returns its result // untouched; when it succeeded and the log looks filled, it copies the 2052 -// bytes. Nothing new is ever asked of the GPU or of its power firmware: the -// readings are the ones the driver takes anyway, at the driver's own pace. +// bytes. The readings are the ones the driver takes anyway, at the driver's +// own pace. +// +// Never from this kext's own thread (0.9.3). The driver reads the log when +// someone reads the accelerator's PerformanceStatistics, and since 0.9.1 the +// kext also called the library itself, once a second, while it held a fan +// curve, an OD8 state or a raised power limit. That call used the power +// management object the driver had used, and the driver can clear that object +// while the call runs: `PECI_LockPowerPlayOnly(pem[4])` succeeded and the +// unlock then read `pem[4]` as NULL, which panicked this Mac on 2026-11-27 +// (0.9.1 and 0.9.2, both while a remembered GPU profile was applied). No check +// made before the call can see a clear in the middle of it, so the kext no +// longer calls into the library at all. The app reads PerformanceStatistics at +// least once a second while it holds something; nothing is asked of the card +// from here. // // The function is found by symbol and only routed when its first 17 bytes are // the ones in pmlog_logic.hpp. The route is a long jump (routeMultipleLong), @@ -92,9 +105,9 @@ static uint64_t gSamples{0}; // the log again. gSamples keeps counting, so "since boot" stays true. static bool gValid{false}; -static void keep(const void* out) { +static bool keep(const void* out) { auto log = static_cast(out); - if (gLock == nullptr || !gpusens::plausible(log)) return; + if (gLock == nullptr || !gpusens::plausible(log)) return false; uint64_t now = mach_absolute_time(); IOSimpleLockLock(gLock); memcpy(gLog, log, sizeof(gLog)); @@ -102,12 +115,16 @@ static void keep(const void* out) { gSamples++; gValid = true; IOSimpleLockUnlock(gLock); + return true; } template static uint32_t wrapQuery(void* pem, void* in, void* out) { uint32_t result = orgQuery[K](pem, in, out); if (result == 0 && out != nullptr) keep(out); + // The power management object is not kept (0.9.3): nothing here calls the + // library outside the driver's own calls, so there is no pointer to go stale + // across a sleep or a teardown. return result; } static_assert(arrsize(kHWLibs) == 2, "one wrapper per library"); @@ -348,3 +365,4 @@ void PMLogCopy::invalidate() { gValid = false; IOSimpleLockUnlock(gLock); } + diff --git a/GPU/sensors/kext/kern_pmlog.hpp b/GPU/sensors/kext/kern_pmlog.hpp index 6486bdd0..163c2e56 100644 --- a/GPU/sensors/kext/kern_pmlog.hpp +++ b/GPU/sensors/kext/kern_pmlog.hpp @@ -40,6 +40,11 @@ bool snapshot(uint8_t* out, uint64_t* ageNs, uint64_t* samples); // the clock the age is taken from can pause while the Mac sleeps. void invalidate(); +// The kext copies what the driver reads and nothing else (0.9.3): the keeper +// of 0.9.1 and 0.9.2, which called the library from this kext's own thread, is +// gone. The app reads the accelerator's PerformanceStatistics at least once a +// second while it holds something, which is what makes the driver read. + } // namespace PMLogCopy #endif // GPUSENSORS_KERN_PMLOG_HPP diff --git a/GPU/sensors/kext/pmlog_logic.hpp b/GPU/sensors/kext/pmlog_logic.hpp index 0119b790..60ff4d55 100644 --- a/GPU/sensors/kext/pmlog_logic.hpp +++ b/GPU/sensors/kext/pmlog_logic.hpp @@ -51,6 +51,15 @@ inline bool publishable(bool have, uint64_t ageMs) { return have && sampleFresh(ageMs); } +// The driver asks the library for a sample only when someone reads the +// accelerator's PerformanceStatistics, so with nothing outside polling the +// kext's copy ages out and the fan watchdog has nothing to look at. The kext +// does not ask for a sample itself (0.9.3: that call, from this kext's own +// thread, is what panicked the Mac on 2026-11-27, see kern_pmlog.cpp): the app +// reads PerformanceStatistics at least once a second while it holds a fan +// curve, an OD8 state or a raised power limit, which is a read of the +// statistics with the same effect as any other and none of the risk. + // A filled log: every flag is 0 or 1, and at least one is 1. The library // returns success without filling anything while the GPU is powered down, and // the caller then holds whatever its buffer had (the driver's own caller clears diff --git a/GPU/sensors/tests/pmlogtest.cpp b/GPU/sensors/tests/pmlogtest.cpp index 05a858c0..a6a32982 100644 --- a/GPU/sensors/tests/pmlogtest.cpp +++ b/GPU/sensors/tests/pmlogtest.cpp @@ -9,6 +9,7 @@ #include #include +#include "control_logic.hpp" #include "pmlog_logic.hpp" static int failures = 0; @@ -58,6 +59,15 @@ int main(int argc, char** argv) { check(!publishable(true, kMaxSampleAgeMs + 1), "a stale log is not published"); + // 0.9.3: the kext takes no sample of its own; the app's read of + // PerformanceStatistics is what makes the driver sample. The watchdog still + // needs a reading inside its fresh window and gives up only after more than + // one missed second of them. + check(gpuctl::kOd8DogFreshMs >= 1000, + "the watchdog's fresh window spans a second of readings"); + check(gpuctl::kOd8DogStaleMs >= 2000, + "the watchdog goes blind only after more than one missed reading"); + // The ids the samplePMStatistics of the driver reads must keep their names. struct { uint16_t id; diff --git a/GPU/tests/amfidetect.sh b/GPU/tests/amfidetect.sh new file mode 100755 index 00000000..06349a62 --- /dev/null +++ b/GPU/tests/amfidetect.sh @@ -0,0 +1,62 @@ +#!/bin/zsh +# amfidetect.sh - the two boot-argument answers the installers decide the loader kext on, on +# made-up Macs: amfi_off (AMFI is out of the way) and amfipass_on (AMFIPass is loaded and +# running). It sources install/common.zsh and stands in for the system with VCNVT_BOOT_ARGS and +# VCNVT_LOADED_KEXTS; nothing is installed, nothing is read from this Mac and nothing runs. +# +# tests/amfidetect.sh exit 0 when every case decides as expected +emulate -L zsh +setopt no_unset +ROOT=${0:A:h:h} +source $ROOT/install/common.zsh +failed=0 + +case_check() { # name expected-exit boot-args loaded-kexts function + local name=$1 want=$2 boot=$3 kexts=$4 fn=$5 got + VCNVT_BOOT_ARGS=$boot VCNVT_LOADED_KEXTS=$kexts $fn + got=$? + if (( got == want )); then + print -r -- " ok $name" + else + print -r -- " FAIL $name (expected exit $want, got $got)" + failed=1 + fi +} + +# What kextstat prints for a loaded AMFIPass, and its header alone when nothing is loaded. +KEXTS_PASS=' 60 0 0xffffff80041d7000 0xcf000 0xcf000 com.dhinakg.AMFIPass (1.4.1) 7DF1CDFC-7EFE-3D82-A3A2-7DACE8B1D097 <56 9 8 7 6 3 2 1>' +KEXTS_NONE='Index Refs Address Size Wired Name (Version) UUID ' +# The boot arguments of this Mac (26.7.3, 2026-11-26): Lilu and AMFIPass are loaded, and +# AMFIPass is switched off there, so it does nothing and the installer must not count it. +THIS_MAC='-lilubetaall agdpmod=pikera alcid=7 debug=0x100 keepsyms=1 unfairgva=1 revcpu=1 revpatch=cpuname,sbvmm -amdcppcactive -amdpnopchk -FIOff rhv_enable_svm=1 -amfipassoff -btleadv -vcnhevc10 ' +PLAIN='debug=0x100 keepsyms=1 ' + +print -r -- "AMFIPass: a kext that is loaded is only running when Lilu and it were not switched off" +case_check "loaded, and -amfipassoff in the boot arguments: absent" 1 "$THIS_MAC" "$KEXTS_PASS" amfipass_on +case_check "loaded, nothing switching it off: running" 0 "$PLAIN" "$KEXTS_PASS" amfipass_on +case_check "not loaded: absent, whatever the boot arguments say" 1 "$PLAIN" "$KEXTS_NONE" amfipass_on +case_check "loaded, -liluoff: absent (a Lilu plugin without Lilu)" 1 "-liluoff " "$KEXTS_PASS" amfipass_on +case_check "loaded, -amfipassoff=1: absent" 1 "-amfipassoff=1 " "$KEXTS_PASS" amfipass_on +case_check "loaded, amfipassoff=1 without the dash: absent" 1 "amfipassoff=1 " "$KEXTS_PASS" amfipass_on +case_check "loaded, amfipassoff without a value: absent" 1 "amfipassoff " "$KEXTS_PASS" amfipass_on +case_check "loaded, -amfipassoff=0: running (0 leaves it on)" 0 "-amfipassoff=0 " "$KEXTS_PASS" amfipass_on + +print -r -- "AMFI: out of the way by amfi_get_out_of_my_way, or by amfi with bit 0x80" +case_check "amfi_get_out_of_my_way=1: off" 0 "amfi_get_out_of_my_way=1 " "$KEXTS_NONE" amfi_off +case_check "amfi_get_out_of_my_way=0x1: off" 0 "amfi_get_out_of_my_way=0x1 " "$KEXTS_NONE" amfi_off +case_check "amfi_get_out_of_my_way without a value: off (it counts as 1)" 0 "amfi_get_out_of_my_way " "$KEXTS_NONE" amfi_off +case_check "amfi_get_out_of_my_way=0: on" 1 "amfi_get_out_of_my_way=0 " "$KEXTS_NONE" amfi_off +case_check "amfi=0x80: off (the form the app knows too)" 0 "amfi=0x80 " "$KEXTS_NONE" amfi_off +case_check "amfi=128: off (the same bit in decimal)" 0 "amfi=128 " "$KEXTS_NONE" amfi_off +case_check "amfi=0xFF: off" 0 "amfi=0xFF " "$KEXTS_NONE" amfi_off +case_check "amfi=0x7F: on (bit 0x80 clear)" 1 "amfi=0x7F " "$KEXTS_NONE" amfi_off +case_check "amfi=1: on" 1 "amfi=1 " "$KEXTS_NONE" amfi_off +case_check "no amfi argument at all: on" 1 "$PLAIN" "$KEXTS_NONE" amfi_off +case_check "this Mac's arguments: AMFI on (it has no amfi argument)" 1 "$THIS_MAC" "$KEXTS_PASS" amfi_off + +print -r -- "This Mac as it is: AMFIPass loaded but switched off, AMFI on" +case_check "the installer counts no AMFIPass here" 1 "$THIS_MAC" "$KEXTS_PASS" amfipass_on +case_check "and AMFI is on here" 1 "$THIS_MAC" "$KEXTS_PASS" amfi_off + +if (( failed )); then print -r -- "FAILED"; exit 1; fi +print -r -- "all passed" diff --git a/GPU/tests/command_paths.sh b/GPU/tests/command_paths.sh new file mode 100755 index 00000000..371a1904 --- /dev/null +++ b/GPU/tests/command_paths.sh @@ -0,0 +1,76 @@ +#!/bin/zsh +# command_paths.sh - every absolute command path the root installers run exists on this Mac. +# +# 1.90.0 shipped an installer that called /usr/bin/chown. There is no /usr/bin/chown on macOS +# (it is /usr/sbin/chown), so the copy step failed after the password had been typed and every +# install stopped there. Nothing caught it before the disk image went out: the path was a string +# in a shell script and in a Swift file, not a call this machine had ever made. +# +# This test reads the files that run as root - install/*.sh, install/common.zsh, the C helper and +# the installer window - and takes every absolute path they name under the folders macOS keeps +# commands in. Each one has to exist and be executable here. A path built at run time from a +# variable is reported and not checked, because there is nothing to check; a comment that names +# a missing command fails too, which is the right answer for a comment about a command. +# +# tests/command_paths.sh the files that run as root, and the installer window +# tests/command_paths.sh ... only these files, which is how this test is checked itself +# +# Runs on the build Mac and on a CI runner: it reads files and stats paths, nothing else. +# Exit status 0 = every path exists. +emulate -L zsh +setopt no_unset pipe_fail +ROOT=${0:A:h:h} + +# The folders macOS keeps commands in. A path anywhere else is data - a folder the installer +# writes to, a log, a device - and not this test's business. +BINS=(/bin /sbin /usr/bin /usr/sbin /usr/libexec) +alt=${(j:|:)BINS} +# The installer creates these folders itself, so naming them is not a mistake. +CREATED=(/usr/local/bin /usr/local/libexec /Library/Video/Plug-Ins) + +if (( $# )); then + files=($@) +else + files=($ROOT/install/*.sh $ROOT/install/common.zsh $ROOT/install/kextentry.c + $ROOT/installer/main.swift) +fi + +failed=0 +checked=0 +missing=() + +local hits hit line cmd p created +for f in $files; do + if [[ ! -f $f ]]; then + print -r -- " FAIL no such file: $f" + failed=1 + continue + fi + # "line:path", one per match: /usr/local/bin/gpucontrol is skipped by the boundary, since the + # installer fills that folder and the file is not a command anyone runs. + hits=$(grep -noE "(^|[^-A-Za-z0-9_./])($alt)/[A-Za-z0-9_+.-]+" "$f" 2>/dev/null || true) + for hit in ${(f)hits}; do + line=${hit%%:*} + cmd=${hit#*:} + [[ $cmd == /* ]] || cmd=/${cmd#*/} + checked=$((checked + 1)) + [[ -x $cmd ]] && continue + created=0 + for p in $CREATED; do + [[ $cmd == $p || $cmd == $p/* ]] && created=1 + done + (( created )) || missing+=("${f:t}:$line: $cmd") + done +done + +if (( ${#missing} )); then + local m + for m in $missing; do print -r -- " FAIL does not exist: $m"; done + print -r -- "" + print -r -- "${#missing} of $checked command paths do not exist on this Mac." + failed=1 +else + print -r -- " ok $checked command paths, all there" +fi + +(( ! failed )) diff --git a/GPU/tests/loader_install.sh b/GPU/tests/loader_install.sh index d6cdc5ed..57f721c8 100755 --- a/GPU/tests/loader_install.sh +++ b/GPU/tests/loader_install.sh @@ -211,7 +211,7 @@ VCNVT_FAKE_RECORDS=$R $SN install --efi-folder $T/s > $T/s2.out 2>&1 rm -f $rec VCNVT_FAKE_RECORDS=$R $SN install --efi-folder $T/s > /dev/null 2>&1 VCNVT_FAKE_RECORDS=$R $SN uninstall --efi-folder $T/s > /dev/null 2>&1 -[[ ! -e $rec ]] && ok "uninstall deletes the record" || bad "record after uninstall" +grep -qx "action=remove" $rec && ok "uninstall deletes the install record and writes the removal one" || bad "record after uninstall: $(cat $rec 2>&1)" VCNVT_FAKE_RECORDS=$R $L install --efi-folder $T/s > /dev/null 2>&1 grep -qx "bundle=com.droga.VCNVTLoader" $R/installed-VCNVTLoader.txt && VCNVT_FAKE_RECORDS=$R $L check --efi-folder $T/r 2>&1 | grep -q "this build was put there in this boot session (install record)" && @@ -394,6 +394,50 @@ dlcheck $SYS --json | spy 'd["installed"] == "outdated" and [c for c in d["check dput > $T/lj2.out 2>&1 && [[ ! -e $SYS/JPEGVCNDecoder.bundle && -d $SYS/AV1VCNDecoder.bundle ]] && grep -q "removed .*JPEGVCNDecoder.bundle (an earlier install with --jpeg put it there)" $T/lj2.out && ok "install without --jpeg takes the JPEG plug-in off, keeps AV1 and VP9" || bad "install drops jpeg: $(cat $T/lj2.out; ls $SYS)" +# 18. encoder.sh takes only a partition like disk0s1, or auto, for --efi (b8e36c28 made it +# the check install.sh and undo.sh make). A wrong value stops with a usage error before +# anything runs; a value that passes the check is then seen by the command's own rules +# (check refuses --efi on its own, install reaches its root check). No root and no +# package are needed: the argument parser runs first. +E=$ROOT/install/encoder.sh +$E install --efi bogus > $T/e1.out 2>&1; [[ $? == 64 ]] && grep -q "takes a partition like disk0s1, or auto" $T/e1.out && + ok "encoder.sh refuses an --efi value that is not a partition or auto" || bad "encoder --efi bogus: $(cat $T/e1.out)" +$E uninstall --efi disk0 > $T/e2.out 2>&1; [[ $? == 64 ]] && grep -q "takes a partition like disk0s1, or auto" $T/e2.out && + ok "encoder.sh refuses an --efi value without an sN" || bad "encoder --efi disk0: $(cat $T/e2.out)" +$E install --efi disk0s1extra > $T/e3.out 2>&1; [[ $? == 64 ]] && grep -q "takes a partition like disk0s1, or auto" $T/e3.out && + ok "encoder.sh refuses an --efi value with something after diskNsM" || bad "encoder --efi suffix: $(cat $T/e3.out)" +$E check --efi "" > $T/e4.out 2>&1; [[ $? == 64 ]] && grep -q "takes a partition like disk0s1, or auto" $T/e4.out && + ok "encoder.sh refuses an empty --efi value" || bad "encoder --efi empty: $(cat $T/e4.out)" +$E install --efi > $T/e5.out 2>&1; [[ $? == 64 ]] && grep -q "takes a partition like disk0s1, or auto" $T/e5.out && + ok "encoder.sh refuses --efi without a value" || bad "encoder --efi missing: $(cat $T/e5.out)" +$E check --efi disk0s1 > $T/e6.out 2>&1; [[ $? == 64 ]] && grep -q "check looks at every EFI partition" $T/e6.out && + ok "a partition like disk0s1 passes the value check (check refuses --efi on its own)" || bad "encoder check --efi disk0s1: $(cat $T/e6.out)" +$E check --efi auto > $T/e7.out 2>&1; [[ $? == 64 ]] && grep -q "check looks at every EFI partition" $T/e7.out && + ok "auto passes the value check too" || bad "encoder check --efi auto: $(cat $T/e7.out)" +$E install --efi disk0s1 > $T/e8.out 2>&1; [[ $? == 1 ]] && grep -q "must run as root" $T/e8.out && + ok "a valid --efi takes install all the way to its root check" || bad "encoder install --efi disk0s1: $(cat $T/e8.out)" + +# 19. efikext.zsh removes the install record only after the config.plist check that can still +# abort the uninstall (b8e36c28): a refused uninstall leaves the record, so a check in the +# same boot still knows the kext was put there. The record went first before, and the +# refusal looked like the kext was never installed. +make_efi u +VCNVT_FAKE_RECORDS=$R $SN install --efi-folder $T/u > $T/u1.out 2>&1 && + [[ -f $rec ]] && ok "the sensors kext installs on one more folder, its record written" || + bad "sensors install u: $(cat $T/u1.out)" +plutil -convert binary1 $T/u/EFI/OC/config.plist +VCNVT_FAKE_RECORDS=$R $SN uninstall --efi-folder $T/u > $T/u2.out 2>&1 +[[ $? -ne 0 ]] && grep -q "cannot be edited" $T/u2.out && [[ -f $rec ]] && + ok "an uninstall that cannot edit config.plist changes nothing, record included" || + bad "uninstall on binary config: $(cat $T/u2.out; ls $R)" +rjson | spy 'd["pendingReboot"]' && + ok "after the refused uninstall the check still believes the record" || bad "check after refused uninstall: $(rjson)" +plutil -convert xml1 $T/u/EFI/OC/config.plist +VCNVT_FAKE_RECORDS=$R $SN uninstall --efi-folder $T/u > $T/u3.out 2>&1 && + grep -qx "action=remove" $rec && + ok "the uninstall then goes ahead; the record left is the removal one" || + bad "uninstall after restore: $(cat $T/u3.out; cat $rec 2>&1)" + cd /; /bin/rm -rf -- "$T" print "loader install tests: $pass passed, $fail failed" (( fail == 0 )) diff --git a/GPU/tests/run.sh b/GPU/tests/run.sh index 176050de..325fa584 100755 --- a/GPU/tests/run.sh +++ b/GPU/tests/run.sh @@ -6,7 +6,9 @@ # # What it checks: # 1. the repository is clean (tools/check_clean.sh) and formatted (tools/format.sh --check); -# what install/install.sh plan decides on made-up Macs (tests/install_plan.sh) +# what install/install.sh plan decides on made-up Macs (tests/install_plan.sh); that every +# absolute command path the root installers and the installer window name exists here +# (tests/command_paths.sh) # 2. the decoders build, twice, to the same bytes # 3. the AV1 and VP9 parsers read the public test streams exactly as recorded in # tests/expected-digests.txt @@ -27,7 +29,9 @@ # (staletest) # 5b. the loader kext: its decisions, that it builds twice to the same bytes and lists the # plug-ins just built, that install/loader.sh puts it on an EFI and takes it off again -# (on made-up EFI folders), and that it accepts the AMFI functions of this Mac +# (on made-up EFI folders), and that it accepts the AMFI functions of this Mac; and the +# boot arguments that decide whether it is needed at all: AMFI switched off and AMFIPass +# loaded but off, on made-up Macs (amfidetect) # 5c. the GPU sensors: they build twice to the same bytes, their decisions, and that the # kext accepts the PMLog function of this Mac's driver # 5d. the JPEG decoder kext: it builds twice to the same bytes, its door and the rule that @@ -86,6 +90,7 @@ check "every shell script parses" syntax check "the validated builds list agrees with the decoders' driver lists" install/check_lists.sh check "install.sh plan decides as expected on made-up Macs" tests/install_plan.sh check "root installers refuse folders another user can change" tests/install_paths.sh +check "every command the installers run exists on this Mac" tests/command_paths.sh step "decoders: build" build_twice() { @@ -138,6 +143,9 @@ check "the plug-ins' VideoToolbox side, with a stand-in decoder" plugins legacyparse() { decode/build/tests/legacyparse > decode/build/tests/legacyparse.txt || { cat decode/build/tests/legacyparse.txt; return 1; }; } check "the MPEG-2, VC-1 and MPEG-4 parsers and messages, with made-up and damaged streams" legacyparse +bootargs() { tests/amfidetect.sh > decode/build/tests/amfidetect.txt 2>&1 || + { cat decode/build/tests/amfidetect.txt; return 1; }; } +check "the boot arguments that decide whether the loader kext is needed" bootargs layers() { decode/build/tests/layertest > decode/build/tests/layertest.txt || { cat decode/build/tests/layertest.txt; return 1; }; } check "the MPEG-2, VC-1 and MPEG-4 codec layers send the firmware only what it decodes" layers @@ -162,10 +170,14 @@ check "two plug-ins of one process: a session from before a sleep is seen, new o sessions() { decode/build/tests/sessiontest-av1 tests/media/av1/av1-1-b8-01-size-16x16.ivf tests/media/av1/av1-1-b8-05-mv.ivf > decode/build/tests/sessiontest-av1.txt && decode/build/tests/sessiontest-vp9 tests/media/vp9/vp90-2-12-droppable_1.ivf \ - tests/media/vp9-invalid/invalid-vp90-2-09-aq2.webm.ivf.s3984_r01-05_b6-.ivf > decode/build/tests/sessiontest-vp9.txt || + tests/media/vp9-invalid/invalid-vp90-2-09-aq2.webm.ivf.s3984_r01-05_b6-.ivf \ + tests/media/vp9/vp90-2-22-svc_1280x720_3.ivf \ + tests/media/vp9/vp90-2-13-mv-with-scaling.ivf \ + > decode/build/tests/sessiontest-vp9.txt || { cat decode/build/tests/sessiontest-av1.txt decode/build/tests/sessiontest-vp9.txt 2>/dev/null | grep -v ^PASS; return 1; } } -check "decoder sessions release the driver once, also after failures and a stuck GPU; a sleep: decode on, rebuild at a key frame; hidden frames keep their picture (made-up driver)" sessions +check "decoder sessions release the driver once, also after failures and a stuck GPU; a sleep: decode on, rebuild at a key frame; hidden frames keep their picture; a VP9 reference more than 2x smaller is refused and such a frame empties its slots (made-up driver)" sessions +check "sessiontest-vp9 notices when those two rules are broken (3 damaged builds)" ./decode/tests/mutants.sh step "decoders: loader kext" check "the kext's decisions" decode/build/tests/loadertest diff --git a/README.md b/README.md index 540c0d8a..cc5f179a 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,8 @@

- Latest release - Downloads + Latest release + Downloads CI status macOS 14 to 26 (Sonoma to Tahoe), AMD/Intel @@ -64,7 +64,7 @@ The rest bends the same way: Settings is grouped by tool and searchable down to - **Session lowest and highest.** Click the CPU row in the panel for the lowest and highest CPU temperature, package power, average clock and fan speed since RyzenStatus opened, with a Reset. - **Monitor window.** A window of its own, like Activity Monitor, with Overview, Processes, Processor, Network, History and Diagnostics. Processes is one sortable, searchable table of every app with CPU, memory, GPU and estimated energy; Terminate asks first and refuses protected system processes. History charts the last 30 days, and with the AMD kext also CPU package power and the average core clock. Control-Shift-Escape opens it from any app, and ⌘1 to ⌘6 switch sections. It reads only the section on screen, and nothing while it is closed. - **CSV log and export.** Settings › Monitor writes one row a second to a file you choose, and saves the history for a range you pick as a CSV, with commas and a dot for decimals in every language. -- **Network.** Live rates in MB/s or Mbps, session totals, the per app list, each interface's local IP address and a built in speed test. +- **Network.** Live rates in MB/s or Mbps, session totals, the per app list, each interface's local IP address, AWDL and AirDrop activity when supported by the Wi-Fi driver, and a built in speed test. - **Alerts.** Optional notifications for sustained CPU load, CPU and GPU temperature, CPU package power, GPU power, memory pressure, low disk space, low battery, VRAM temperature and CPU or GPU throttling, in your temperature unit. Any alert can wait until its reading has stayed over the limit for 10 to 60 seconds. ### AMD Processors & Power Management @@ -73,7 +73,7 @@ All AMD pages live together in their own **AMD Ryzen** section of Settings: fans - **One CCD per app (new, `AMDCCDScheduler.kext`):** On a Ryzen with two CCDs, stock macOS keeps scattering each app's threads across both, so every hand-off between them crosses the Infinity Fabric (about 155 ns instead of 65 ns on a 5900XT). This kext fixes the macOS scheduler itself: each app gets a home CCD and its threads stay there while it has a free physical core, and spread to the other CCD only when it is full. On a 5900XT a Node worker pool ran **about 12% faster** with much steadier times, and an all-core zstd job ran at the same speed. As far as we could find, nothing else does this on macOS. It checks the kernel byte for byte before hooking it and stays off on any macOS build it was not checked against. [How it works and every measurement](docs/CCD_SCHEDULER.md). - **AMD Telemetry:** Real-time monitoring of AMD CPU package/core temperatures, power draw against the PPT limit, and frequencies per core. -- **Kernel-Native Dynamic Fan Curves:** Hardware fan control evaluated directly inside `AMDRyzenCPUPowerManagement.kext` at a 500 ms cadence with 256-point LUT interpolation, exponential moving average smoothing ($\alpha = 0.2$), hardware hysteresis, ramp rate limiting, and an emergency thermal guard ($\ge 85$ °C $\to$ PWM $\ge 200$), eliminating userspace polling overhead. Curves are put back at launch and after the kext reconnects, and the fan safety checks keep running with Settings closed. +- **Kernel-Native Dynamic Fan Curves:** Hardware fan control evaluated directly inside `AMDRyzenCPUPowerManagement.kext` at a 500 ms cadence with 256-point LUT interpolation, exponential moving average smoothing ($\alpha = 0.2$), hardware hysteresis, ramp rate limiting, and an emergency thermal guard ($\ge 85$ °C $\to$ PWM $\ge 200$), eliminating userspace polling overhead. Curves are put back at launch and after the kext reconnects, and the fan safety checks keep running with Settings closed. With kext 3.42.0, two programs talking to the CPU kext coordinate fan writes so they no longer undo each other. The curve editor in Settings can also use GPU temperature from GPUSensors when the CPU kext sees no GPU. - **GPU Temperature Bridge:** Native discrete GPU temperature forwarding (selector 103) allowing fan curves driven directly by GPU thermal loads. - **Interactive Staged Curve Editor:** Curve editor featuring 256-point visual preview, live sensor tracking markers, 4-curve slot management, 1% minimum duty cycle floor, and explicit Apply / Revert actions to prevent unintended fan spin-ups while editing. - **SuperIO Hardware Read-Back:** Accurate fan speed (RPM) and duty cycle (PWM %) derived directly from physical SuperIO chips (Nuvoton NCT668X / NCT67XX, ITE IT86XXE). @@ -86,17 +86,17 @@ All AMD pages live together in their own **AMD Ryzen** section of Settings: fans - **EPP through MSRs or ACPI:** Energy Performance Preference reaches CPUs with the CPPC MSRs directly and, on CPUs that publish CPPC only through ACPI (`_CPC` and PCC shared memory, such as Ryzen 5000 desktop parts), through PCC. Hardware Validation shows which path your CPU uses and what the driver found. - **SMU controls for every family:** PPT/TDC/EDC (or STAPM/fast/slow on APUs), cHTC, PBO scalar, OC mode with frequency and voltage, Curve Optimizer and a boost ceiling go through the command set of your CPU's family (Zen and Zen+, Zen 2, Zen 3, AM5, and the Raven Ridge, Renoir/Cezanne and Rembrandt/Phoenix APUs). A control your CPU does not accept says so instead of sending a command meant for another chip. - **Gaming Mode:** A one-click toggle to apply the Extreme power preset and prevent display sleep during intense workloads. -- **Hardware Validation:** Lists every power control your CPU accepts, the deep idle state, which path EPP takes and what the driver found in ACPI, and reads the CPPC values back from the firmware, so you can see what really reaches the processor. +- **Hardware Validation:** Lists every power control your CPU accepts, the deep idle state, which path EPP takes and what the driver found in ACPI, whether another driver attaches to the AMD SMU, whether GPUSensors.kext loaded on a supported card, and reads the CPPC values back from the firmware, so you can see what really reaches the processor. ### AMD Radeon RX 6000 graphics -For the Radeon RX 6800, 6800 XT and 6900 XT on an OpenCore Mac (an RX 6950 XT should work too, but has not been run). macOS ships a working driver for these cards but leaves part of their video engine unused; these parts fill the gaps without replacing any Apple driver. The disk image carries them in the **GPU RX 6000** folder, with an installer of their own. +For the Radeon RX 6800, 6800 XT and 6900 XT on an OpenCore Mac (an RX 6950 XT should work too, but has not been run). NVIDIA cards and NullMoth are not supported or tested. macOS ships a working driver for these cards but leaves part of their video engine unused; these parts fill the gaps without replacing any Apple driver. The disk image carries them in the **GPU RX 6000** folder, with an installer of their own. -- **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, 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. +- **Hardware video decoding.** Safari and Chrome play AV1 and VP9 on the GPU instead of the CPU, YouTube in 4K60 included, with HDR colour metadata (BT.2020, PQ, HLG). Videos survive system sleep across every decoder: frames in flight during sleep are dropped without error and playback carries on from the next key frame. Optional hardware decoders for MPEG-2, VC-1 and MPEG-4 (macOS 26.7.2 to 26.7.4) and JPEG / Motion JPEG (`VCNJpeg.kext`, macOS 26.7.3) decode legacy and camera video on the GPU. On Macs with an Intel iGPU, the VP9 decoder declares high priority so macOS picks the Radeon. +- **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. A service fix corrects 10-bit HEVC (Main10) encoding on VCN 3 (macOS 26.7.3, `-vcnhevc10`). Continuity Camera and FaceTime video decode on the GPU instead of the CPU, and outgoing FaceTime video is fixed on MacPro7,1 and iMacPro1,1 board IDs. +- **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. While a setting is held, GPUSensors polls readings once a second so the temperature watchdog stays active. Readings older than 5 seconds are dropped so numbers stay fresh. +- **GPU control.** With GPUSensors.kext, a Settings page for the power limit (in 10 W steps down to the card's own minimum), a five-point fan curve with zero RPM, minimum and maximum GFX clocks, GFX voltage undervolt (in 25 mV steps), an Overclock section (up to +15% power limit and card maximum clock, off by default), and named profiles. Only the RX 6800 XT writes; the RX 6900 XT is readings only. Memory clock and fast timings are not offered because the macOS driver cannot apply them. Changes are opened with your administrator password until restart, and **Allow changes after restart too** lets remembered settings come back after a reboot as well. Every control, range and safety limit: [GPU control](docs/GPU_CONTROL.md). +- **GPU RX 6000 installer.** A single window in the disk image installs or updates all GPU parts (decoders, encoding fix, GPUSensors, VCNJpeg), checks AMFI configuration (`amfi=0x80`, `-amfipassoff`, `-liluoff`, VCNVTLoader), and only asks for a password on steps that require one. 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). @@ -104,8 +104,8 @@ Every part runs only on the macOS builds it was checked against and stays off on - **Dynamic Island.** An optional island at the top of the screen that brings music, controls and everyday tools together: Now Playing with lyrics, queue and a live equalizer, timers, downloads, notifications, upcoming calendar events, gestures, accessory and input source notices, and live CPU, GPU and memory cards. Off by default. - **No notch needed.** On displays without a notch, compact activities and the resting companion stay in the menu bar and expanded panels open below it. The middle of the capsule can show the song, a live metric or the time. -- **Watch any window.** Turn any part of any window into a live activity, with an alert when it changes, finishes or shows what you are waiting for. -- **A companion that grows.** Give it a name and watch it reach ten levels with pats and time together, unlocking accessories (glasses, scarf, headphones, a crown and more), with seasonal costumes and its own greetings. It follows your AMD hardware: the fan companion spins at your CPU fan's real speed and the chip glows with package power. +- **Watch any window.** Turn any part of any window into a live activity, with an alert when it changes, finishes or shows what you are waiting for, with custom sounds and repeats. Calendar in the island can ignore events by title keywords, and island hover expands the closed island under the pointer while keeping camera controls visible. +- **A companion that grows.** Give it a name and watch it reach ten levels with pats and time together, unlocking accessories (glasses, scarf, headphones, a crown and more), seasonal costumes, its own greetings, and items from the lab and mayhem sets, with chain reactions, rare sights, combos, fusions, and a searchable wardrobe. It follows your AMD hardware: the fan companion spins at your CPU fan's real speed and the chip glows with package power. - **AI agents, opt in.** Tokens, plan limits and work in progress for Claude Code, Codex, OpenCode and GitHub Copilot, read from their local history files. Off by default.

@@ -117,7 +117,7 @@ Every part runs only on the macOS builds it was checked against and stays off on - **Volume mixer.** Slide any single app up or down while the rest of the Mac stays put, and push a quiet one past 100 percent when a video is just too low. No audio driver, no setup. - **Per app output.** Send your music to the speakers and a call to your headset at the same time. -- **Output switcher and audio priority.** Cycle between chosen outputs with one shortcut, rank your devices so the best one connected is used automatically, and drop the volume when headphones disconnect. +- **Output switcher and audio priority.** Cycle between chosen outputs with one shortcut, rank your devices so the best one connected is used automatically, remove unused entries, and drop the volume when headphones disconnect. Also handles monitor speakers that never answer volume queries. - **Microphone tools.** Pin your favorite input so the Mac stops guessing, and mute the mic everywhere with a click or shortcut. - **Music app blocker.** Stops the Music app from bursting in when a media key or headphones launch it, opens the player you prefer instead, and can start playback in it. - **Every player.** On macOS 15.4 and later, TIDAL, browsers, video players and every other app that publishes what it plays show up with title, artist, album, position, cover and controls. @@ -158,13 +158,13 @@ Every part runs only on the macOS builds it was checked against and stays off on ### Everyday tools - **Quick panel and toggles.** ⌃⌘V opens a floating palette with your favorite tools, and one-click system actions sit in their own panel tab: dark mode, empty the Trash, eject every disk, hidden files, lock the screen and more. -- **Radial menu.** Hold a shortcut, or a spare mouse button, and a wheel of your favorite actions opens around the pointer. +- **Radial menu.** Hold a shortcut, or a spare mouse button, and a wheel of your favorite actions opens around the pointer, with quick insertion of saved text snippets. - **Screen Recorder.** Record the screen, a window or an area with optional microphone audio, then trim, annotate and export in the built-in editor. -- **Screenshot & Annotation Suite.** Capture on a frozen picture, then annotate, crop, redact, style the background and pin captures. QR codes are detected and decoded. +- **Screenshot & Annotation Suite.** Capture on a frozen picture, then annotate, crop, redact, style the background, add tiled watermarks and pin captures. QR codes are detected and decoded. - **Copy text from screen.** Select any area and its text is recognized offline via Apple's Vision framework, straight onto the clipboard. - **Image converter.** Saved profiles, exact or proportional resizing, renaming with tokens, text or logo watermarks, and video compression and GIFs, all locally. -- **Scratchpad.** A floating pad for short-lived text with Markdown preview, find, text size and background opacity. It saves as you type. -- **Cleaner and uninstaller.** Sweep app leftovers, caches, logs and forgotten screenshots by hand or on a schedule, and remove apps with all their files, including Homebrew casks. +- **Scratchpad.** A floating pad for short-lived text with Markdown preview, find, text size, background opacity and a completed tasks section. It saves as you type. +- **Cleaner and uninstaller.** Sweep app leftovers, caches, logs and forgotten screenshots by hand or on a schedule, and remove apps with all their files, including Homebrew casks. A backup button in Settings › Advanced saves settings to `~/.config/ryzenstatus/`. - **Homebrew and MacPorts.** Search, install, update and remove packages without opening a terminal, and find updates for the apps you have. - **Kill Process and Port Manager.** Search running processes and end whole process trees, and see which apps listen on which network ports. - **Camera preview, color picker, wallpaper gallery and Cleaning Mode**, which locks the keyboard and blacks out every display while you clean. @@ -172,7 +172,7 @@ Every part runs only on the macOS builds it was checked against and stays off on ### Energy and display - **Keep awake.** Keep the Mac up for a timer, until a chosen time, until you say stop, or automatically with an external display or power connection, with the remaining time beside the icon. -- **Displays.** Adjust brightness or turn individual displays on and off from the menu bar panel, with hardware control on external screens when available. +- **Displays.** Adjust brightness or turn individual displays on and off from the menu bar panel, with hardware control on external screens when available, and dimming for virtual displays (DisplayLink and dummy screens). - **Bluetooth.** Turn Bluetooth off when the Mac sleeps and back on when it wakes. On a Hackintosh with a slow or missing Bluetooth controller, one switch stops the app's own Bluetooth queries. ## Install @@ -231,6 +231,9 @@ By default, any local process may read telemetry from the kext, while hardware * - **`-amdpnopchk`**: *(Optional — Security Trade-off)* Disables UserClient root privilege checks so RyzenStatus can control fans, EPP, P-States, and Curve Optimizer without running as `root`. **Warning:** when `-amdpnopchk` is set, *any* local process on the machine can issue privileged hardware writes through the UserClient; enable only on trusted single-user systems. - **`-amdoff`**: Keeps the CPU kext from starting (kext 3.42.0), a way out if a kext update stops the Mac from booting. Remove it once the old pair is back. - **`-amdpdbg`**: Enables verbose debug logging (for troubleshooting panics or missing sensors). +- **`-vcnhevc10`**: *(GPU)* Enables the 10-bit HEVC (Main10) gate on AMD Radeon RX 6000 cards; held back until the encoding service confirms the driver patch is active. +- **`vcnfloor=N`**: *(GPU)* Sets a custom video clock floor in MHz for cards outside Navi 21 and Navi 23. +- **`vcnjpegpool=`**: *(GPU)* Sets the buffer pool size for the optional JPEG decoder kext (8 to 128 MiB, default 128). #### Supported Sensors & Fan Control The kext includes SuperIO support for reading and controlling fans on the following chip families: diff --git a/ReleaseAssets/GPU-Package.zip b/ReleaseAssets/GPU-Package.zip index b0af19de..2bb17fae 100644 Binary files a/ReleaseAssets/GPU-Package.zip and b/ReleaseAssets/GPU-Package.zip differ diff --git a/Resources/Info.plist b/Resources/Info.plist index 3b6658f0..e5703100 100644 --- a/Resources/Info.plist +++ b/Resources/Info.plist @@ -37,13 +37,13 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.90.0 + 1.90.1 CFBundleSupportedPlatforms MacOSX CFBundleVersion - 163 + 164 LSApplicationCategoryType public.app-category.utilities LSMinimumSystemVersion diff --git a/SMCAMDProcessor_Source/AMDCCDScheduler/AMDCCDScheduler.cpp b/SMCAMDProcessor_Source/AMDCCDScheduler/AMDCCDScheduler.cpp index 0b655333..cfe2ce9d 100644 --- a/SMCAMDProcessor_Source/AMDCCDScheduler/AMDCCDScheduler.cpp +++ b/SMCAMDProcessor_Source/AMDCCDScheduler/AMDCCDScheduler.cpp @@ -336,6 +336,8 @@ static void *ccdLegacyFirstPlacement(void *node, void *thread, void **processor_ c.same++; return orig; } + // The original may have set a processor hint inside its own pset; it does not apply to ours. + if (processor_hint != nullptr) *processor_hint = nullptr; c.kept++; return home; } @@ -472,14 +474,21 @@ static void ccdInstall(KernelPatcher &patcher) { gGetThreadTask = reinterpret_cast(gtt); gCpuNumber = reinterpret_cast(cpuNum); gKernelTask = *kernelTask; - mach_vm_address_t org = patcher.routeFunction(fn, reinterpret_cast(ccdChooseStartingPset), true); - if (patcher.getError() != KernelPatcher::Error::NoError || !org) { + // routeMultiple, not routeFunction: Lilu stores the original in gOrg BEFORE it writes the jump + // (kern_patcher.cpp routeFunctionInternal, "to avoid null pointer dereference"). With routeFunction + // gOrg was set after the route was live, and a CPU entering the hook in between called a null pointer. + KernelPatcher::RouteRequest req("_choose_starting_pset", ccdChooseStartingPset, gOrg); + // Lilu can report the route as done with gOrg written and no jump in place (a failed patch + // allocation or memory protection change after the trampoline): it leaves the error code set then. + patcher.clearError(); + if (!patcher.routeMultiple(KernelPatcher::KernelID, &req, 1) || !gOrg + || patcher.getError() != KernelPatcher::Error::NoError) { gState = 4; - ccdLog("routeFunction failed (%d)", static_cast(patcher.getError())); + ccdLog("routeMultiple failed (%d)", static_cast(patcher.getError())); patcher.clearError(); return; } - gOrg = reinterpret_cast(org); + if (req.from != fn) ccdLog("warning: routed %llx, checked %llx", (unsigned long long)req.from, (unsigned long long)fn); gState = 1; ccdLog("installed: %s layout, %d processor sets, mode %d", gL.name, gPsets, gMode); } diff --git a/SMCAMDProcessor_Source/AMDCCDScheduler/tests/hook_test.cpp b/SMCAMDProcessor_Source/AMDCCDScheduler/tests/hook_test.cpp index fea8c4b2..0503187e 100644 --- a/SMCAMDProcessor_Source/AMDCCDScheduler/tests/hook_test.cpp +++ b/SMCAMDProcessor_Source/AMDCCDScheduler/tests/hook_test.cpp @@ -214,6 +214,72 @@ static void runSuite() { printf("concurrent placements with a different home for the same process: %d\n", mismatch.load()); } +// The install path: ccdInstall on a fake prologue built from each layout's own tables, with every +// symbol solved from a table. The route outcome decides between state 1 and 4: a route that reports +// done with the original written and no error installs; a refused route, a route that left the +// original null, or one that leaves an error behind (a patch that did not land, guarded since +// b4b3caaf) all do not. +static void installPath() { + printf("-- install path\n"); + for (size_t i = 0; i < arrsize(kLayouts); i++) { + const Layout &L = kLayouts[i]; + static uint8_t fn[0x400], picker[0x800]; + memset(fn, 0xcc, sizeof fn); memset(picker, 0xcc, sizeof picker); + for (size_t k = 0; k < L.headLen; k++) if (L.head[k] <= 0xff) fn[k] = static_cast(L.head[k]); + for (size_t k = 0; k < L.moreLen; k++) memcpy(fn + L.more[k].off, L.more[k].bytes, L.more[k].len); + memcpy(picker + L.pickerOff, L.pick, L.pickLen); + const mach_vm_address_t f = reinterpret_cast(fn), gtt = f + 0x3f0; + int32_t rel = static_cast(gtt - (f + L.callOff + 5)); + memcpy(fn + L.callOff + 1, &rel, sizeof rel); + const mach_vm_address_t pk = reinterpret_cast(picker); + static void *kernelTask = kernelTaskObj.b; + static uint32_t numPsets = 2; + static Obj cpuObj; + KernelPatcher::Solved table[] = { + {"_choose_starting_pset", f}, + {"_get_threadtask", gtt}, + {"_kernel_task", reinterpret_cast(&kernelTask)}, + {"_cpu_number", reinterpret_cast(cpuObj.b)}, + {"_sched_num_psets", reinterpret_cast(&numPsets)}, + {L.picker, pk}, + }; + KernelPatcher::solveTable = table; + KernelPatcher::solveCount = arrsize(table); + KernelPatcher patcher; + + // Route done, original written, no error: installed. + gOrg = nullptr; + KernelPatcher::routeResult = true; KernelPatcher::routeWritesOrg = true; + KernelPatcher::routeError = KernelPatcher::Error::NoError; + ccdInstall(patcher); + CHECK(gState == 1 && gOrg != nullptr); + CHECK(gL.name == L.name && gPsets == 2); + + // Route refused (the error is what a failed patch leaves): not installed. + gOrg = nullptr; + KernelPatcher::routeResult = false; + KernelPatcher::routeError = KernelPatcher::Error::MemoryIssue; + ccdInstall(patcher); + CHECK(gState == 4); + + // Route reported done but the original was never written: not installed. + gOrg = nullptr; + KernelPatcher::routeResult = true; KernelPatcher::routeWritesOrg = false; + KernelPatcher::routeError = KernelPatcher::Error::NoError; + ccdInstall(patcher); + CHECK(gState == 4 && gOrg == nullptr); + + // Route done, original written, but an error is left behind: not installed. + KernelPatcher::routeWritesOrg = true; + KernelPatcher::routeError = KernelPatcher::Error::MemoryIssue; + ccdInstall(patcher); + CHECK(gState == 4 && gOrg != nullptr); + KernelPatcher::solveTable = nullptr; KernelPatcher::solveCount = 0; + KernelPatcher::routeResult = false; KernelPatcher::routeWritesOrg = false; + KernelPatcher::routeError = KernelPatcher::Error::NoError; + } +} + // Each layout's byte checks, run on a buffer built from that layout's own tables: it must match its // own bytes, reject the other layouts', reject a changed byte and reject a call that is not to // get_threadtask. Catches overlapping or out-of-order entries in the tables. @@ -249,6 +315,7 @@ static void layoutTables() { } int main() { + installPath(); layoutTables(); for (size_t i = 0; i < arrsize(kLayouts); i++) { gL = kLayouts[i]; diff --git a/SMCAMDProcessor_Source/AMDCCDScheduler/tests/stub/Headers/plugin_start.hpp b/SMCAMDProcessor_Source/AMDCCDScheduler/tests/stub/Headers/plugin_start.hpp index c99bbd8a..692800ec 100644 --- a/SMCAMDProcessor_Source/AMDCCDScheduler/tests/stub/Headers/plugin_start.hpp +++ b/SMCAMDProcessor_Source/AMDCCDScheduler/tests/stub/Headers/plugin_start.hpp @@ -16,13 +16,45 @@ template constexpr size_t arrsize(const T (&)[N]) { retur inline int parseModuleVersion(const char *) { return 0; } inline bool PE_parse_boot_argn(const char *, void *, int) { return false; } +// The test drives the patcher through the knobs below: solveSymbol reads solveTable, routeMultiple +// resolves req.from, writes *req.org only when routeWritesOrg asks, returns routeResult and leaves +// routeError behind (getError reports it; clearError resets it, as Lilu's does). struct KernelPatcher { - enum class Error { NoError }; + enum class Error { NoError, MemoryIssue }; static constexpr size_t KernelID = 0; - mach_vm_address_t solveSymbol(size_t, const char *) { return 0; } - void clearError() {} - Error getError() { return Error::NoError; } + struct Solved { const char *name; mach_vm_address_t address; }; + static inline Solved *solveTable = nullptr; + static inline size_t solveCount = 0; + static inline bool routeResult = false; + static inline bool routeWritesOrg = false; + static inline Error routeError = Error::NoError; + static inline Error error = Error::NoError; + mach_vm_address_t solveSymbol(size_t, const char *name) { + if (solveTable) + for (size_t i = 0; i < solveCount; i++) + if (!strcmp(solveTable[i].name, name)) return solveTable[i].address; + return 0; + } + void clearError() { error = Error::NoError; } + Error getError() { return error; } mach_vm_address_t routeFunction(mach_vm_address_t, mach_vm_address_t, bool) { return 0; } + struct RouteRequest { + const char *symbol {nullptr}; + mach_vm_address_t from {0}, to {0}; + mach_vm_address_t *org {nullptr}; + template + RouteRequest(const char *s, T t, O &o) : + symbol(s), to(reinterpret_cast(t)), org(reinterpret_cast(&o)) {} + }; + bool routeMultiple(size_t, RouteRequest *reqs, size_t n) { + if (reqs) + for (size_t i = 0; i < n; i++) { + reqs[i].from = solveSymbol(KernelID, reqs[i].symbol); + if (routeWritesOrg && reqs[i].org) *reqs[i].org = reqs[i].from; + } + error = routeError; + return routeResult; + } }; enum class LiluAPI { AllowNormal }; enum class KernelVersion { Sonoma, Tahoe }; diff --git a/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/AMDRyzenCPUPowerManagement.cpp b/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/AMDRyzenCPUPowerManagement.cpp index 21a95550..d473a83f 100644 --- a/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/AMDRyzenCPUPowerManagement.cpp +++ b/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/AMDRyzenCPUPowerManagement.cpp @@ -1350,6 +1350,12 @@ void AMDRyzenCPUPowerManagement::applyPowerControl(){ } return; } + // The gate set_PState honors: with P1 never rewritten to a checked + // definition, selector 10 must not step the cores into it either. + if (!pmRyzen_p1_gate()) { + IOLog("AMDRyzenCPUPowerManagement::applyPowerControl ignored - P1 not a checked definition\n"); + return; + } IOLockLock(rendezvousLock); mp_rendezvous(nullptr, [](void *obj) { @@ -3346,6 +3352,43 @@ void AMDRyzenCPUPowerManagement::writePstate(const uint64_t *buf){ // Vet the definitions once, here in thread context, with the same // 400 MHz floor in integer form: Zen 5 runs at FID * 5 MHz, earlier // families at FID / DfsId * 200 MHz. The rendezvous only writes. + // CpuVid [21:14] is clamped to the firmware's most-voltage enabled + // P-state: P0 when it is enabled (the normal case), otherwise the + // lowest VID among the enabled states, so a board with P0 disabled + // (e.g. CPB off) still gets a real cap. A lower VID asks the SMU for + // MORE core voltage than the firmware ever programs, and no caller of + // this selector validated that field. Undervolting (a higher VID, less + // voltage) stays possible. The cap is read once, before the first + // write: clamping to the live P0 would leave an undervolted P0 unable + // to go back to stock until a reboot. With no enabled state readable at + // all there is no way to vet VID, so the write is refused instead of + // passing raw definitions through (fail closed). + uint64_t defs[kMSR_PSTATE_LEN] = {}; + if (!firmwareP0VidKnown) { + uint64_t capVid = 0; + bool haveAny = false; + for (uint32_t i = 0; i < kMSR_PSTATE_LEN; i++) { + uint64_t d = 0; + if (!read_msr(kMSR_PSTATE_0 + i, &d) || !(d >> 63)) continue; + const uint64_t vid = (d >> 14) & 0xFFULL; + if (!haveAny || vid < capVid) { + capVid = vid; + haveAny = true; + } + } + if (!haveAny) { + static bool loggedNoVidCap = false; + if (!loggedNoVidCap) { + loggedNoVidCap = true; + IOLog("AMDRyzenCPUPowerManagement::writePstate refused: no enabled P-state readable, VID clamp unavailable\n"); + } + return; + } + firmwareP0Vid = capVid; + firmwareP0VidKnown = true; + } + const bool haveP0 = firmwareP0VidKnown; + const uint64_t p0Vid = firmwareP0Vid; uint32_t writeMask = 0; for (uint32_t i = 0; i < kMSR_PSTATE_LEN; i++) { uint64_t def = buf[i]; @@ -3357,7 +3400,11 @@ void AMDRyzenCPUPowerManagement::writePstate(const uint64_t *buf){ uint64_t curCpuDfsId = ((def >> 8) & 0x3f); uint64_t curCpuFid = (def & 0xff); if (curCpuDfsId == 0 || curCpuFid == 0 || curCpuFid < 2 * curCpuDfsId) continue; + if (haveP0 && ((def >> 14) & 0xFFULL) < p0Vid) { + def = (def & ~(0xFFULL << 14)) | (p0Vid << 14); + } } + defs[i] = def; writeMask |= (1u << i); } @@ -3365,7 +3412,7 @@ void AMDRyzenCPUPowerManagement::writePstate(const uint64_t *buf){ AMDRyzenCPUPowerManagement *provider; const uint64_t *defs; // kMSR_PSTATE_LEN entries uint32_t mask; - } args{this, buf, writeMask}; + } args{this, defs, writeMask}; IOLockLock(rendezvousLock); mp_rendezvous(nullptr, [](void *obj) { @@ -3465,6 +3512,15 @@ void AMDRyzenCPUPowerManagement::resumeSuperIO() { superIO->resume(); fanTelemetryLastMs = 0; firmwareTempLastMs = 0; + // The firmware rewrites the CPU-temperature input (ITE 0x29) on wake + // with whatever it measured at resume - 36 C was observed on an + // IT8665E board, i.e. possibly far below a hot CPU. Re-feed the real + // package temperature right here instead of waiting for the first + // sensor tick, and make the cached value impossible to match so the + // next tick cannot skip its write. A failed read keeps the pre-sleep + // trusted timestamp, so the 10 s failsafe (90 C) still fires at once. + firmwareTempLast = 0xFF; + feedFirmwareCPUTemp(getPackageTemp(), getCurrentTimeNs() / 1000000); for (size_t i = 0; i < kMAX_FANS; i++) { lastPWMAssertMs[i] = 0; } @@ -3591,6 +3647,35 @@ void AMDRyzenCPUPowerManagement::evaluateFanCurves() { // ISSuperIOSMCFamily::beginAccess) and not at all on a tick that writes // nothing. bool chipTaken = false; + // Emergency guard for MANUAL fans (selector 95). The selector clamps + // every duty it is asked for, but a client that hangs without dying (so + // clientClose's dead-man never fires for it) leaves its fan latched at + // the last duty indefinitely. Re-judge the package temperature here, on + // every sensor tick, and raise any fan still under a client's manual + // control that sits below the guard while the CPU is hot. The duty and + // the control mode are read from the chip right here (see below). Curve fans get the same guard further below; fans the user + // handed back to the BIOS (selector 96 / auto mode) are left alone. + if (isTempValid(cpuTemp) && cpuTemp >= kTHERMAL_GUARD_TEMP_C) { + // Judge on the chip's live control mode and duty, not on the shared + // telemetry cache: that cache is at most kFAN_TELEMETRY_MIN_INTERVAL_MS + // old and selector 95/96 write the registers under superIOLock without + // refreshing it, so right after either it can still show a duty the + // client has since raised above the guard (knocking it back down) or a + // manual mode the user has since handed back to the BIOS (grabbing the + // fan back). One extra register-read burst per tick, only while hot. + superIO->updateFanControl(); + for (int fanIdx = 0; fanIdx < fanCount && fanIdx < (int)kMAX_FANS; fanIdx++) { + const int8_t manualCurve = fanToCurveMap[fanIdx]; + if (manualCurve >= 0 && manualCurve < MAX_FAN_CURVES) continue; // curve fan + if (fanOwner[fanIdx] == nullptr) continue; // nobody owns it + if (superIO->getFanAutoControlMode(fanIdx)) continue; // released to BIOS + if (superIO->getFanThrottle(fanIdx) >= kTHERMAL_GUARD_PWM) continue; + if (!chipTaken) { superIO->beginAccess(); chipTaken = true; } + superIO->overrideFanControl(fanIdx, kTHERMAL_GUARD_PWM); + lastAppliedPWM[fanIdx] = kTHERMAL_GUARD_PWM; + lastPWMUpdateTime[fanIdx] = now; + } + } for (int fanIdx = 0; fanIdx < fanCount && fanIdx < (int)kMAX_FANS; fanIdx++) { int8_t curveIdx = fanToCurveMap[fanIdx]; if (curveIdx < 0 || curveIdx >= MAX_FAN_CURVES) { diff --git a/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/AMDRyzenCPUPowerManagement.hpp b/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/AMDRyzenCPUPowerManagement.hpp index 1d5e4f96..bc47a912 100644 --- a/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/AMDRyzenCPUPowerManagement.hpp +++ b/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/AMDRyzenCPUPowerManagement.hpp @@ -625,6 +625,9 @@ class AMDRyzenCPUPowerManagement : public IOService { uint8_t PStateCur_perCore[CPUInfo::MaxCpus] {}; uint8_t PStateCtl = 0; uint64_t PStateDef_perCore[8] {}; + // writePstate: the firmware's own P0 VID, read before our first write (overvolt clamp) + uint64_t firmwareP0Vid {0}; + bool firmwareP0VidKnown {false}; uint8_t PStateEnabledLen = 0; float PStateDefClock_perCore[8] {}; bool cpbSupported {false}; diff --git a/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/pmAMDRyzen.c b/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/pmAMDRyzen.c index f05b2335..f560ce5f 100644 --- a/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/pmAMDRyzen.c +++ b/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/pmAMDRyzen.c @@ -67,38 +67,57 @@ pmDispatch_t pmRyzen_cpuFuncs = { #pragma mark - P-State Initialization -void pmRyzen_init_PState(void){ +// Set once pmRyzen_init_PState rewrote P1 to a checked definition. Until then no +// MSR_PSTATE_CTL write happens, whatever limit the app sets later. +static volatile int pmRyzen_p1_ready = 0; + +// Read from C++: applyPowerControl refuses MSR_PSTATE_CTL while the gate is closed. +int pmRyzen_p1_gate(void){ return pmRyzen_p1_ready; } + +int pmRyzen_init_PState(void){ // P1 = 80% of P0 by default. Override via boot-arg `amdpp1ratio=0.75` etc. - static float p1_ratio = 0.0f; - if (p1_ratio == 0.0f) { + // Integer percent: the SSE state belongs to the current thread, and float + // math here would clobber it (see pmRyzen_machine_idle). + static int p1_ratio_pct = 0; + if (p1_ratio_pct == 0) { uint32_t bootRatio = 0; PE_parse_boot_argn("amdpp1ratio", &bootRatio, sizeof(bootRatio)); - p1_ratio = (bootRatio > 0 && bootRatio <= 100) ? (float)bootRatio / 100.0f : 0.80f; + p1_ratio_pct = (bootRatio > 0 && bootRatio <= 100) ? (int)bootRatio : 80; } uint64_t p0 = pmRyzen_rdmsr_safe(pmRyzen_io_service_handle, MSR_PSTATE_0); - if (!(p0 & (1ULL << 63))) return; + if (!(p0 & (1ULL << 63))) return 0; + uint64_t p0fid = p0 & 0xff; uint64_t p0dfsid = (p0 >> 8) & 0x3f; - if (p0dfsid == 0) return; - - float p0spd = ((float)(p0 & 0xff) / (float)p0dfsid) * 200.0f; + if (p0dfsid == 0) return 0; uint64_t p1 = pmRyzen_rdmsr_safe(pmRyzen_io_service_handle, MSR_PSTATE_0 + 1); + // A P1 the firmware left disabled carries no VID worth enabling: its whole + // definition is unvalidated. Leave it alone and say so to the caller. + if (!(p1 & (1ULL << 63))) return 0; uint64_t p1dfsid = (p1 >> 8) & 0x3f; - if (p1dfsid == 0) return; + if (p1dfsid == 0) return 0; - uint32_t fid_raw = (uint32_t)((p0spd * p1_ratio) / 200.0f * (float)p1dfsid); + // fid = p0spd * ratio / 200 * p1dfsid, with p0spd = p0fid / p0dfsid * 200: + // fid = p0fid * ratio_pct * p1dfsid / (100 * p0dfsid), all in integers + uint32_t fid_raw = (uint32_t)((p0fid * (uint64_t)p1_ratio_pct * p1dfsid) / (100 * p0dfsid)); if (fid_raw > 0xFF) fid_raw = 0xFF; if (fid_raw < 0x10) fid_raw = 0x10; + // Never a P1 faster than P0: the 0x10 floor above can raise it when P1's + // DfsID is lower than P0's. FID of P0's speed at P1's DfsID: + uint32_t fid_max = (uint32_t)((p0fid * p1dfsid) / p0dfsid); + if (fid_max < 0x10) return 0; + if (fid_raw > fid_max) fid_raw = fid_max; uint64_t p1fid = (uint64_t)fid_raw; pmRyzen_wrmsr_safe(pmRyzen_io_service_handle, MSR_PSTATE_0 + 1, (p1 & ~0xFFULL) | p1fid | (1ULL << 63)); + return 1; } static inline void set_PState(pmProcessor_t *cpu, uint8_t state){ // Zen 3+ never writes MSR_PSTATE_CTL, whatever PPM/LPM ask for. - if(!pmRyzen_pstate_control || pmRyzen_pstatelimit == 0) return; + if(!pmRyzen_pstate_control || pmRyzen_pstatelimit == 0 || (!pmRyzen_p1_ready && state != 0)) return; if (state >= 8) state = 7; if (state > pmRyzen_pstatelimit) state = (uint8_t)pmRyzen_pstatelimit; if(cpu->PState == state) return; @@ -202,13 +221,21 @@ void pmRyzen_init(void *handle, int allowDispatch, int pstateControl){ pkg = pkg->next; } - pmRyzen_effective_timetsc = ((double)pmRyzen_tsc_freq * EFF_INTERVAL); - pmRyzen_p_sdtsc = (uint64_t)((double)pmRyzen_effective_timetsc * PSTATE_STEPDOWN_THRE); - pmRyzen_p_sutsc = (uint64_t)((double)pmRyzen_effective_timetsc * PSTATE_STEPUP_THRE); + // Same values as EFF_INTERVAL 0.15, PSTATE_STEPDOWN_THRE 0.12 and + // PSTATE_STEPUP_THRE 0.38, without touching the FPU (see pmRyzen_machine_idle) + pmRyzen_effective_timetsc = pmRyzen_tsc_freq * 15 / 100; + pmRyzen_p_sdtsc = pmRyzen_effective_timetsc * 12 / 100; + pmRyzen_p_sutsc = pmRyzen_effective_timetsc * 38 / 100; if (pmRyzen_pstate_control) { - pmRyzen_init_PState(); - pmRyzen_PState_reset(); + pmRyzen_p1_ready = 0; + if (pmRyzen_init_PState()) { + pmRyzen_p1_ready = 1; + pmRyzen_PState_reset(); + } else { + // P1 was never rewritten to a valid definition: never step into it + pmRyzen_pstatelimit = 0; + } } cb.initComplete(); diff --git a/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/pmAMDRyzen.h b/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/pmAMDRyzen.h index 5bb1fcbb..4c75f514 100644 --- a/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/pmAMDRyzen.h +++ b/SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/pmAMDRyzen.h @@ -87,6 +87,9 @@ void pmRyzen_stop(void); // Every later idle entry goes to CC6 through `port`, or to CC1 with 0. void pmRyzen_set_c6_port(uint32_t port); void pmRyzen_PState_reset(void); +// 1 once pmRyzen_init_PState rewrote P1 to a checked definition: no MSR_PSTATE_CTL +// write before that, not even the app's own applyPowerControl (state 0 is always safe). +int pmRyzen_p1_gate(void); float pmRyzen_avgload_pcpu(uint32_t); uint64_t pmRyzen_machine_idle(uint64_t); diff --git a/Sources/RyzenStatus/Core/GPUControlPageStrings.swift b/Sources/RyzenStatus/Core/GPUControlPageStrings.swift index 2283126b..fdded1fe 100644 --- a/Sources/RyzenStatus/Core/GPUControlPageStrings.swift +++ b/Sources/RyzenStatus/Core/GPUControlPageStrings.swift @@ -154,6 +154,10 @@ struct GPUControlPageStrings { let kextSaysFormat: String /// A reading of the live row that is missing, in words. let noReading: String + /// The GPU package the app carries is not the one that runs (0.9.3). + /// 0.9.1 and 0.9.2 panicked this Mac, so GPU control stays off until the + /// package is installed again. + let kextOutdated: String /// Why the arm button is not offered. func sentence(_ reason: GPUControlArmTool.UnsafeReason) -> String { @@ -235,7 +239,8 @@ struct GPUControlPageStrings { 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] + nothingToLower, otherProgramChanged, powerHint, openWritingHint, kextSaysFormat, noReading, + kextOutdated] } } @@ -359,7 +364,8 @@ extension GPUControlPageStrings { powerHint: "Applies when chosen. Only lowers the limit, down to the card's minimum.", openWritingHint: "Asks for an administrator password. Changes stay allowed until you close them or restart the Mac.", kextSaysFormat: "From the kext: %@", - noReading: "no data") + noReading: "no data", + kextOutdated: "The GPU package is out of date. Open the RyzenStatus GPU installer from the DMG and install the update, then restart.") static let es = GPUControlPageStrings( stateSection: "Estado", @@ -459,7 +465,8 @@ extension GPUControlPageStrings { powerHint: "Se aplica al elegir. Solo baja el límite, hasta el mínimo de la tarjeta.", openWritingHint: "Pide la contraseña de un administrador. Los cambios quedan permitidos hasta que los cierres o reinicies el Mac.", kextSaysFormat: "Del kext: %@", - noReading: "sin dato") + noReading: "sin dato", + kextOutdated: "El paquete de GPU está desactualizado. Abre el instalador de GPU de RyzenStatus desde el DMG, instala la actualización y reinicia el Mac.") static let ptBR = GPUControlPageStrings( stateSection: "Estado", @@ -559,7 +566,8 @@ extension GPUControlPageStrings { powerHint: "Aplica ao escolher. Só reduz o limite, até o mínimo da placa.", openWritingHint: "Pede a senha de um administrador. As alterações ficam liberadas até você fechá-las ou reiniciar o Mac.", kextSaysFormat: "Do kext: %@", - noReading: "sem dado") + noReading: "sem dado", + kextOutdated: "O pacote de GPU está desatualizado. Abra o instalador de GPU do RyzenStatus no DMG, instale a atualização e reinicie o Mac.") static let tr = GPUControlPageStrings( stateSection: "Durum", @@ -659,7 +667,8 @@ extension GPUControlPageStrings { powerHint: "Seçildiğinde uygulanır. Sınırı yalnızca kartın minimumuna kadar düşürür.", openWritingHint: "Bir yönetici parolası ister. Değişikliklere, siz kapatana ya da Mac yeniden başlatılana kadar izin verilir.", kextSaysFormat: "Kext'ten: %@", - noReading: "veri yok") + noReading: "veri yok", + kextOutdated: "GPU paketi güncel değil. DMG'den RyzenStatus GPU yükleyicisini açın, güncellemeyi kurun ve Mac'i yeniden başlatın.") static let ru = GPUControlPageStrings( stateSection: "Состояние", @@ -759,7 +768,8 @@ extension GPUControlPageStrings { powerHint: "Применяется при выборе. Только снижает лимит, до минимума карты.", openWritingHint: "Запрашивает пароль администратора. Изменения разрешены, пока вы их не закроете или не перезапустите Mac.", kextSaysFormat: "Сообщение kext: %@", - noReading: "нет данных") + noReading: "нет данных", + kextOutdated: "Пакет GPU устарел. Откройте установщик RyzenStatus GPU из DMG, установите обновление и перезагрузите Mac.") static let sk = GPUControlPageStrings( stateSection: "Stav", @@ -859,7 +869,8 @@ extension GPUControlPageStrings { powerHint: "Použije sa pri výbere. Limit iba znižuje, až po minimum karty.", openWritingHint: "Vyžiada heslo správcu. Zmeny zostanú povolené, kým ich nezatvoríte alebo nereštartujete Mac.", kextSaysFormat: "Od kextu: %@", - noReading: "bez údaja") + noReading: "bez údaja", + kextOutdated: "Balík GPU je zastaraný. Otvorte inštalátor RyzenStatus GPU z DMG, nainštalujte aktualizáciu a reštartujte Mac.") static let de = GPUControlPageStrings( stateSection: "Status", @@ -959,7 +970,8 @@ extension GPUControlPageStrings { powerHint: "Wird bei der Auswahl angewendet. Senkt das Limit nur, bis zum Minimum der Karte.", openWritingHint: "Fragt nach einem Administratorpasswort. Änderungen bleiben erlaubt, bis Sie sie schließen oder den Mac neu starten.", kextSaysFormat: "Vom Kext: %@", - noReading: "keine Daten") + noReading: "keine Daten", + kextOutdated: "Das GPU-Paket ist veraltet. Öffne den RyzenStatus-GPU-Installer aus dem DMG, installiere das Update und starte den Mac neu.") static let fr = GPUControlPageStrings( stateSection: "État", @@ -1059,7 +1071,8 @@ extension GPUControlPageStrings { powerHint: "S’applique dès la sélection. Abaisse seulement la limite, jusqu’au minimum de la carte.", openWritingHint: "Demande le mot de passe d’un administrateur. Les modifications restent autorisées jusqu’à ce que vous les fermiez ou redémarriez le Mac.", kextSaysFormat: "Du kext : %@", - noReading: "aucune donnée") + noReading: "aucune donnée", + kextOutdated: "Le paquet GPU n’est pas à jour. Ouvrez l’installateur GPU de RyzenStatus depuis le DMG, installez la mise à jour, puis redémarrez le Mac.") static let it = GPUControlPageStrings( stateSection: "Stato", @@ -1159,7 +1172,8 @@ extension GPUControlPageStrings { powerHint: "Si applica alla scelta. Abbassa solo il limite, fino al minimo della scheda.", openWritingHint: "Chiede la password di un amministratore. Le modifiche restano abilitate finché non le chiudi o riavvii il Mac.", kextSaysFormat: "Dal kext: %@", - noReading: "nessun dato") + noReading: "nessun dato", + kextOutdated: "Il pacchetto GPU non è aggiornato. Apri l’installer GPU di RyzenStatus dal DMG, installa l’aggiornamento e riavvia il Mac.") static let ja = GPUControlPageStrings( stateSection: "状態", @@ -1259,7 +1273,8 @@ extension GPUControlPageStrings { powerHint: "選ぶとすぐに適用されます。制限はカードの最小値まで下げるだけです。", openWritingHint: "管理者のパスワードを求めます。変更を閉じるか Mac を再起動するまで、変更が許可されます。", kextSaysFormat: "kext から: %@", - noReading: "データなし") + noReading: "データなし", + kextOutdated: "GPU パッケージが古くなっています。DMG から RyzenStatus GPU インストーラを開き、アップデートをインストールしてから Mac を再起動してください。") static let ko = GPUControlPageStrings( stateSection: "상태", @@ -1359,7 +1374,8 @@ extension GPUControlPageStrings { powerHint: "선택하면 적용됩니다. 한도는 카드 최소값까지 낮추기만 합니다.", openWritingHint: "관리자 암호를 요청합니다. 변경을 닫거나 Mac을 재시동할 때까지 변경이 허용됩니다.", kextSaysFormat: "kext 메시지: %@", - noReading: "데이터 없음") + noReading: "데이터 없음", + kextOutdated: "GPU 패키지가 오래되었습니다. DMG에서 RyzenStatus GPU 설치 프로그램을 열고 업데이트를 설치한 다음 Mac을 재시작하십시오.") static let zhHans = GPUControlPageStrings( stateSection: "状态", @@ -1459,7 +1475,8 @@ extension GPUControlPageStrings { powerHint: "选择后即应用。只会降低上限,最低至显卡的最低值。", openWritingHint: "需要管理员密码。在你关闭更改或重新启动 Mac 之前,允许更改。", kextSaysFormat: "来自 kext:%@", - noReading: "无数据") + noReading: "无数据", + kextOutdated: "GPU 软件包已过期。请从 DMG 打开 RyzenStatus GPU 安装程序,安装更新后重新启动 Mac。") static let zhTW = GPUControlPageStrings( stateSection: "狀態", @@ -1559,7 +1576,8 @@ extension GPUControlPageStrings { powerHint: "選擇後即套用。只會降低上限,最低至顯示卡的最低值。", openWritingHint: "需要管理員密碼。在你關閉更改或重新啟動 Mac 之前,允許更改。", kextSaysFormat: "來自 kext:%@", - noReading: "無資料") + noReading: "無資料", + kextOutdated: "GPU 套件已過期。請從 DMG 開啟 RyzenStatus GPU 安裝程式,安裝更新後重新啟動 Mac。") static let uk = GPUControlPageStrings( stateSection: "Стан", @@ -1659,5 +1677,6 @@ extension GPUControlPageStrings { powerHint: "Застосовується під час вибору. Лише знижує ліміт, до мінімуму картки.", openWritingHint: "Запитує пароль адміністратора. Зміни дозволені, доки ви їх не закриєте або не перезапустите Mac.", kextSaysFormat: "Повідомлення kext: %@", - noReading: "немає даних") + noReading: "немає даних", + kextOutdated: "Пакет GPU застарів. Відкрийте інсталятор RyzenStatus GPU з DMG, встановіть оновлення та перезавантажте Mac.") } diff --git a/Sources/RyzenStatus/Services/AMD/AutoEppService.swift b/Sources/RyzenStatus/Services/AMD/AutoEppService.swift index e3e3e20b..33c88c43 100644 --- a/Sources/RyzenStatus/Services/AMD/AutoEppService.swift +++ b/Sources/RyzenStatus/Services/AMD/AutoEppService.swift @@ -63,6 +63,10 @@ final class AutoEppService: ObservableObject { fileprivate var idleLimitWrites = AMDIdleClockLimitWrites() /// Retries a refused lift while the loop is stopped. private var liftRetryTask: Task? + /// The serial queue behind every selector-69 write (see the class at the + /// bottom of this file): one IPC in flight, off the main actor, values + /// dispatched in the order they were asked for. + fileprivate var idleLimitQueue = IdleLimitWriteQueue() /// The CPU's CPPC range, read once per kext load (selector 68). fileprivate var cppcRange: AMDCppcRange? fileprivate var cppcUnsupported = false @@ -205,7 +209,16 @@ final class AutoEppService: ObservableObject { /// kext lifts the limit itself when the connection closes. private func liftIdleClockLimit() { guard idleLimitWrites.mayBeCapped, canRun else { return } - if !writeIdleClockLimit(0) { scheduleLiftRetry() } + // The write leaves the main actor now (it runs on the serial queue); + // the guards are re-checked after the hop, and a refusal still arms + // the retry loop. + Task { [weak self] in + guard let self else { return } + guard self.pollTask == nil, self.canRun, + self.idleLimitWrites.mayBeCapped else { return } + let lifted = await self.writeIdleClockLimit(0) + if !lifted { self.scheduleLiftRetry() } + } } private func scheduleLiftRetry() { @@ -222,7 +235,7 @@ final class AutoEppService: ObservableObject { try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) continue } - if self.writeIdleClockLimit(0) { break } + if await self.writeIdleClockLimit(0) { break } } // start() and stop() cancel and clear it themselves. if !Task.isCancelled { self?.liftRetryTask = nil } @@ -230,16 +243,33 @@ final class AutoEppService: ObservableObject { } /// Sends the CPPC max perf (min stays the CPU's own) and records the - /// answer. A refusal leaves the written value unknown, so whatever the - /// next poll wants is sent, and a lift is still owed while a cap may be - /// in force. True when the kext took it. + /// answer on the main actor, in the order the values were asked for. A + /// refusal leaves the written value unknown, so whatever the next poll + /// wants is sent, and a lift is still owed while a cap may be in force. + /// + /// Coalescing: when several values are pending, the queue sends only the + /// newest — a superseded value was about to be overwritten anyway, and + /// the kext ends at the last value asked for. A superseded value answers + /// nil: nothing was sent, so no answer is recorded. Its `willWrite` + /// already ran, so a superseded cap can only cost one extra lift. + /// + /// True when the kext took THIS value. @discardableResult - fileprivate func writeIdleClockLimit(_ maxPerf: UInt8) -> Bool { + fileprivate func writeIdleClockLimit(_ maxPerf: UInt8) async -> Bool { + // Before the value leaves: a lift asked for while this cap is still + // queued or in flight must see that a cap may be in force. idleLimitWrites.willWrite(maxPerf) - let ok = ProcessorModel.shared.setCppcLimits(minPerf: 0, maxPerf: maxPerf) == KERN_SUCCESS - appliedIdleMaxPerf = ok ? maxPerf : nil + // The continuation is made here, on the main actor, so the value + // joins the queue before this call suspends: two writes asked for in + // a row reach the queue in that order. + let queue = idleLimitQueue + let answer = await withCheckedContinuation { (cont: CheckedContinuation) in + queue.submit(maxPerf, cont: cont) + } + guard let verdict = answer else { return false } + appliedIdleMaxPerf = verdict.succeeded ? maxPerf : nil let now = Self.uptime - if idleLimitWrites.record(maxPerf, succeeded: ok, now: now) { + if idleLimitWrites.record(maxPerf, succeeded: verdict.succeeded, now: now) { NSLog("AutoEppService: the kext refused CPPC max perf %u %ld times; trying it again every %.0f s", UInt32(maxPerf), AMDIdleClockLimitWrites.maxFailures, AMDIdleClockLimitWrites.retryAfter) } @@ -247,12 +277,34 @@ final class AutoEppService: ObservableObject { // kext reloads. let failed = idleLimitWrites.anyGivenUp(now: now) if idleClockLimitFailed != failed { idleClockLimitFailed = failed } - return ok + return verdict.succeeded } + /// How long `stop()` may wait for the queued writes to land: the kernel + /// side of selector 69 is a handful of MSR writes (microseconds) or one + /// PCC transaction (the latency PCCT declares, single-digit + /// milliseconds on these boards), so 750 ms is two orders of magnitude + /// of margin while still shorter than a delay a quitting user notices. + private static let quitDrainTimeout: TimeInterval = 0.75 + /// Stops the monitoring loop. Called on termination. func stop() { stopLoop() + // `stopLoop()` asks for its lift through an async task, which needs + // the main actor — about to be blocked by the drain below. Enqueue + // the lift synchronously too (same guard `liftIdleClockLimit` uses): + // the value is on the serial queue before this returns, the queue + // needs no main actor to run, and a second lift from the async path + // either coalesces into this one or repeats the same idempotent 0. + if idleLimitWrites.mayBeCapped, canRun { + idleLimitQueue.enqueueDetached(0) + } + // Leave the lift written before the process ends, without hanging + // the quit on a kext that does not answer. A lift that still fails + // (refused, or past the cap) is covered by the kext itself: closing + // the connection in `closeDriver()` runs clientClose → the CPPC + // limits are lifted there. + idleLimitQueue.waitUntilIdle(until: Date().addingTimeInterval(Self.quitDrainTimeout)) liftRetryTask?.cancel() liftRetryTask = nil // Deinit never fires on a `static let shared` singleton. @@ -380,7 +432,7 @@ final class AutoEppService: ObservableObject { // the limit. No preset is applied and nothing is published, since // Auto EPP itself is off. if let profileLimit { - applyIdleClockLimit(for: settled.target.preset, limitMHz: profileLimit) + await applyIdleClockLimit(for: settled.target.preset, limitMHz: profileLimit) return } // On battery the On battery mode may lower the load's target; the @@ -398,9 +450,9 @@ final class AutoEppService: ObservableObject { Task { await AmdPowerControlsModel.shared.syncFromKext() } } if lastAppliedPreset == preset { - applyIdleClockLimit(for: AMDBatteryPowerPolicy.idleLimitPreset(loadTarget: settled.target, - appliedTarget: target), - limitMHz: AmdSettingsStore.shared.autoEppIdleClockLimitMHz) + await applyIdleClockLimit(for: AMDBatteryPowerPolicy.idleLimitPreset(loadTarget: settled.target, + appliedTarget: target), + limitMHz: AmdSettingsStore.shared.autoEppIdleClockLimitMHz) } // A loop stopped while this poll ran must not publish its target. @@ -440,7 +492,7 @@ extension AutoEppService { /// A refused write records nothing, so the next poll retries, up to /// `AMDIdleClockLimitWrites.maxFailures` refusals of the same value and /// then once every `retryAfter`. - fileprivate func applyIdleClockLimit(for preset: AMDPowerPreset, limitMHz limit: Int) { + fileprivate func applyIdleClockLimit(for preset: AMDPowerPreset, limitMHz limit: Int) async { guard let range = currentCppcRange() else { return } let maxPerf = AMDIdleClockLimitPolicy.maxPerf(preset: preset, limitMHz: limit, range: range) let now = Self.uptime @@ -448,7 +500,104 @@ extension AutoEppService { let failed = idleLimitWrites.anyGivenUp(now: now) if idleClockLimitFailed != failed { idleClockLimitFailed = failed } guard maxPerf != appliedIdleMaxPerf, !idleLimitWrites.hasGivenUp(on: maxPerf, now: now) else { return } - writeIdleClockLimit(maxPerf) + await writeIdleClockLimit(maxPerf) + } +} + +/// One serial queue for every selector-69 write, so the kext receives the +/// values in the order the service asked for them — a cap sent before a lift +/// can never land after it — and the main thread never waits on the IPC: the +/// write itself runs on a dedicated serial queue, and `enqueue` suspends its +/// caller instead of blocking it. +/// +/// Coalescing: a write that has not started yet is replaced by a newer one. +/// When the queue picks the next value it takes the NEWEST pending, resumes +/// the waiters it superseded with nil (nothing was sent, nothing is to be +/// recorded) and answers the newest waiter with the kext's real verdict — so +/// the last value asked for always reaches the kext, and its result is +/// recorded on the main actor, in request order. +final class IdleLimitWriteQueue: @unchecked Sendable { + struct Verdict: Sendable { let value: UInt8; let succeeded: Bool } + + private struct Waiter: Sendable { + let value: UInt8 + let cont: CheckedContinuation? + } + + private let lock = NSLock() + private var waiters: [Waiter] = [] + private var running = false + private let queue = DispatchQueue(label: "wtf.spinach.RyzenStatus.idle-limit-69", qos: .utility) + + /// Queues `value`. Nil when a newer value superseded this one before its + /// write started; otherwise the kext's answer for the write that carried + /// the newest value at dispatch time — the caller's own whenever no newer + /// value arrived in between. + func enqueue(_ value: UInt8) async -> Verdict? { + await withCheckedContinuation { (cont: CheckedContinuation) in + submit(value, cont: cont) + } + } + + /// Queues `value` with the continuation that gets its answer, from the + /// caller's own context: the value is on the queue when this returns. + func submit(_ value: UInt8, cont: CheckedContinuation) { + enqueue(value, cont: cont) + } + + /// Fire-and-forget variant: the value is on the queue before this + /// returns and no verdict is delivered. For the termination path, where + /// the caller is about to block the main actor and only the write + /// landing matters. + func enqueueDetached(_ value: UInt8) { + enqueue(value, cont: nil) + } + + /// True when nothing is pending and no write is in flight. + var isIdle: Bool { + lock.lock(); defer { lock.unlock() } + return waiters.isEmpty && !running + } + + /// Blocks the calling thread until the queue settles or `deadline` + /// passes (checked every 5 ms). The queue needs no main actor, so this + /// is safe to call with the main thread blocked. + func waitUntilIdle(until deadline: Date) { + while !isIdle, Date() < deadline { + Thread.sleep(forTimeInterval: 0.005) + } + } + + private func enqueue(_ value: UInt8, cont: CheckedContinuation?) { + lock.lock() + waiters.append(Waiter(value: value, cont: cont)) + let start = !running + if start { running = true } + lock.unlock() + if start { queue.async { self.run() } } + } + + /// The queue's own thread: one IPC at a time, newest value first. + private func run() { + while true { + lock.lock() + guard let newest = waiters.last else { + running = false + lock.unlock() + return + } + let superseded = Array(waiters.dropLast()) + waiters.removeAll() + lock.unlock() + + let status = ProcessorModel.shared.setCppcLimits(minPerf: 0, maxPerf: newest.value) + let verdict = Verdict(value: newest.value, succeeded: status == KERN_SUCCESS) + + // Request order: those asked first (and superseded) resume + // first, with nothing to record. + for waiter in superseded { waiter.cont?.resume(returning: nil) } + newest.cont?.resume(returning: verdict) + } } } diff --git a/Sources/RyzenStatus/Services/AMD/FanCurveController.swift b/Sources/RyzenStatus/Services/AMD/FanCurveController.swift index 6899c915..cf0e98ac 100644 --- a/Sources/RyzenStatus/Services/AMD/FanCurveController.swift +++ b/Sources/RyzenStatus/Services/AMD/FanCurveController.swift @@ -38,6 +38,11 @@ final class FanCurveController: ObservableObject { // MARK: - Internal Synchronization & Storage private var pollTimer: Timer? + /// Activity assertion held while the poll timer runs with every window + /// closed: without it App Nap may coalesce the timer that carries the + /// manual-mode thermal guard (the kext's 85 °C clamp only fires on a + /// write, and a manual fan is never touched by the curve loop). + private var pollActivity: (any NSObjectProtocol)? /// The full fan read (names included). Polls wait for it instead of /// cancelling it, so a slow first read always lands. private var refreshTask: Task? @@ -942,10 +947,21 @@ final class FanCurveController: ObservableObject { pollTimer = nil pollTask?.cancel() pollTask = nil + if let pollActivity { + ProcessInfo.processInfo.endActivity(pollActivity) + self.pollActivity = nil + } // Nothing refreshes it any more; a later hint must not show it. lastPackageTempC = nil return } + if pollActivity == nil { + // No App Nap while the guard polls; system sleep is still allowed + // (the willSleep observer suspends the poll for that). + pollActivity = ProcessInfo.processInfo.beginActivity( + options: .userInitiatedAllowingIdleSystemSleep, + reason: "RyzenStatus manual-fan thermal guard") + } if let pollTimer, pollTimer.isValid, pollTimer.timeInterval == interval { return } pollTimer?.invalidate() // `.common` mode, not `.default`: a timer in the default mode does not diff --git a/Sources/RyzenStatus/Services/AMD/HardwareValidation.swift b/Sources/RyzenStatus/Services/AMD/HardwareValidation.swift index 6d054ba5..54575315 100644 --- a/Sources/RyzenStatus/Services/AMD/HardwareValidation.swift +++ b/Sources/RyzenStatus/Services/AMD/HardwareValidation.swift @@ -43,7 +43,7 @@ enum HardwareValidation { /// The app release that introduced this harness. Informational — the app /// version coming from the bundle is what gets reported. - static let expectedAppVersion = "1.90.0" + static let expectedAppVersion = "1.90.1" /// The reference machine's Super I/O family. The probe expectations (the /// ~15.7 % rotor-start floor, the six ITE channels) are calibrated for it; diff --git a/Sources/RyzenStatus/Services/AMD/IOAcceleratorCache.swift b/Sources/RyzenStatus/Services/AMD/IOAcceleratorCache.swift index fed9f5ab..6bca0cc7 100644 --- a/Sources/RyzenStatus/Services/AMD/IOAcceleratorCache.swift +++ b/Sources/RyzenStatus/Services/AMD/IOAcceleratorCache.swift @@ -66,11 +66,14 @@ actor IOAcceleratorCache { /// Ordered list of IOAccelerator service class names to try. /// Navi 21 (RX 6800 XT) exposes `AMDRadeonX6000_AMDAcceleratedVKDriver` - /// first in Ventura+; we list the generic one as final fallback. + /// first in Ventura+; `AMDRadeonX6000_AMDGraphicsAccelerator` is the class + /// every RX 6000 accelerator inherits, and `IOAccelerator` is the last + /// fallback for a card whose class is not named here. (The list used to try + /// `AMDRadeonX6000_Amd…` and `AMDGPUAccelerator`, which match no service, so + /// only the fallback ever read anything.) private let serviceClasses = [ "AMDRadeonX6000_AMDAcceleratedVKDriver", - "AMDGPUAccelerator", - "AMDRadeonX6000_AmdRadeonGraphicsAccelerator", + "AMDRadeonX6000_AMDGraphicsAccelerator", "IOAccelerator" ] diff --git a/Sources/RyzenStatus/Services/AMD/ProcessorModel.swift b/Sources/RyzenStatus/Services/AMD/ProcessorModel.swift index a094e0da..71fba967 100644 --- a/Sources/RyzenStatus/Services/AMD/ProcessorModel.swift +++ b/Sources/RyzenStatus/Services/AMD/ProcessorModel.swift @@ -1517,8 +1517,15 @@ actor ProcessorModel { /// Number of AMD GPUs detected by the kext (selector 27). /// Returns 0 if selectors are not implemented in the loaded kext. nonisolated func getKextGPUCount() -> Int { - let result = kernelGetUInt64(count: 1, selector: AMDKextSelector.gpuLoad) - return result.isEmpty ? 0 : Int(result[0]) + // Selector 27 answers with a scalar output (kext case 27 writes + // scalarOutput[0]); kernelGetUInt64 reads the structure buffer the + // kext never touches, so it always returned 0. + var output: UInt64 = 0 + var outputCount: UInt32 = 1 + let res = safeIOConnectCallMethod(AMDKextSelector.gpuLoad, nil, 0, nil, 0, + &output, &outputCount, nil, nil) + guard res == KERN_SUCCESS, outputCount >= 1 else { return 0 } + return Int(output) } /// GPU temperatures from kext in integer degrees Celsius (selector 28, no conversion needed). @@ -2152,7 +2159,13 @@ actor ProcessorModel { return kIOReturnBadArgument } var input: [UInt64] = [0, UInt64(arg)] - return safeIOConnectCallMethod(AMDKextSelector.ocFreqWrite.id, &input, 2, nil, 0, nil, nil, nil, nil) + // The kext answers with 8 scalar outputs on the success path; with no + // room for them the call comes back failed even though the SMU write + // already ran (same trap forcePMTableCapture documents for selector 57). + var output = [UInt64](repeating: 0, count: 8) + var outputCount = UInt32(output.count) + return safeIOConnectCallMethod(AMDKextSelector.ocFreqWrite.id, &input, 2, nil, 0, + &output, &outputCount, nil, nil) } /// Program per-CCD frequency overrides via 0x5D (selector 51, mode 1). @@ -2179,7 +2192,11 @@ actor ProcessorModel { } input[10] = UInt64(startCcd) input[11] = UInt64(targets.count) - return safeIOConnectCallMethod(AMDKextSelector.ocFreqWrite.id, &input, 12, nil, 0, nil, nil, nil, nil) + // Same 8 scalar outputs as the all-core path (see above). + var output = [UInt64](repeating: 0, count: 8) + var outputCount = UInt32(output.count) + return safeIOConnectCallMethod(AMDKextSelector.ocFreqWrite.id, &input, 12, nil, 0, + &output, &outputCount, nil, nil) } // MARK: — SMU PM-table plumbing (selectors 56/57) diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift index 349ef6e3..48e39697 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift @@ -195,7 +195,8 @@ final class GPUControlEngine { /// 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. + /// 2 s). The controller calls the same read once a second while anything + /// is held. Nil in tests. var freshenReadings: (() -> Void)? private(set) var snapshot = GPUControlSnapshot() { @@ -894,11 +895,22 @@ final class GPUControlEngine { /// the real channel, once, at launch (`AppDelegate`); without a channel it /// cannot open anything. final class GPUControlController: @unchecked Sendable { + /// How often the app reads the accelerator's `PerformanceStatistics` while + /// something is held: the driver takes its PMLog sample on that read, and + /// GPUSensors copies it, so the fan watchdog never goes blind. The kext + /// does not sample on its own any more (0.9.3: that call, from the kext's + /// thread, panicked the Mac). One second matches the watchdog, which takes + /// a change only while the copy is at most 2 s old. + static let readingsInterval: TimeInterval = 1 + private let queue = DispatchQueue(label: "ryzenstatus.gpu-control", qos: .userInitiated) private let channel: GPUControlChannel? private let gate = Gate() private var engine: GPUControlEngine! private var timer: DispatchSourceTimer? + /// The 1 s read of `PerformanceStatistics` while something is held. + private var readingsTimer: DispatchSourceTimer? + private var freshen: (@Sendable () -> Void)? private var activity: NSObjectProtocol? private var wakeObserver: NSObjectProtocol? private var started = false @@ -946,6 +958,7 @@ final class GPUControlController: @unchecked Sendable { deinit { if let wakeObserver { NSWorkspace.shared.notificationCenter.removeObserver(wakeObserver) } timer?.cancel() + readingsTimer?.cancel() endActivity() } @@ -995,11 +1008,16 @@ 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). + /// What makes the watchdog's readings fresh: one read of the accelerator's + /// `PerformanceStatistics` (`GPUControlReadings.freshen` with the real + /// kext). Called right before an OD8 state or a raised power limit goes + /// out, and once a second while anything is held. func setFreshenReadings(_ freshen: @escaping @Sendable () -> Void) { - queue.async { [self] in engine.freshenReadings = freshen } + queue.async { [self] in + engine.freshenReadings = freshen + self.freshen = freshen + syncReadings(snapshot) + } } /// `applicationWillTerminate`: `release` at once on a helper thread, @@ -1029,6 +1047,8 @@ final class GPUControlController: @unchecked Sendable { queue.async { [self] in timer?.cancel() timer = nil + readingsTimer?.cancel() + readingsTimer = nil if let wakeObserver { NSWorkspace.shared.notificationCenter.removeObserver(wakeObserver) } wakeObserver = nil engine.shutdown(callingChannel: false) @@ -1079,10 +1099,31 @@ final class GPUControlController: @unchecked Sendable { lastSnapshot = snapshot return changeHandler } + syncReadings(snapshot) guard let handler else { return } DispatchQueue.main.async { handler(snapshot) } } + /// One read of `PerformanceStatistics` a second while something is held, + /// none of its own while nothing is (the app's own GPU readings keep + /// today's rate then). On the queue: called from `publish` and from + /// `setFreshenReadings`. + private func syncReadings(_ snapshot: GPUControlSnapshot) { + let wanted = snapshot.held != nil && !gate.isDown && freshen != nil + if wanted, readingsTimer == nil { + let source = DispatchSource.makeTimerSource(queue: queue) + source.schedule(deadline: .now() + Self.readingsInterval, + repeating: Self.readingsInterval, + leeway: .milliseconds(100)) + source.setEventHandler { [weak self] in self?.freshen?() } + readingsTimer = source + source.resume() + } else if !wanted, let source = readingsTimer { + source.cancel() + readingsTimer = nil + } + } + private static func nowMs() -> UInt64 { DispatchTime.now().uptimeNanoseconds / 1_000_000 } } @@ -1091,14 +1132,21 @@ final class GPUControlController: @unchecked Sendable { /// 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). +/// yet (right after launch, right after a wake), and the controller reads +/// once a second while anything is held, which is what keeps the watchdog +/// fed now that the kext never samples by itself (0.9.3). enum GPUControlReadings { /// The AMD accelerator classes, most specific first, so an Intel iGPU or - /// another card that enumerates first is never the one read. + /// another card that enumerates first is never the one read. The names are + /// the driver's own: the Vulkan driver's class exists while a Vulkan app + /// holds the card, and `AMDRadeonX6000_AMDGraphicsAccelerator` is the class + /// every RX 6000 accelerator inherits, so `IOServiceMatching` finds the + /// card through it. (Two names used here before, `AMDRadeonX6000_Amd…` and + /// `AMDGPUAccelerator`, match no service at all, so the whole walk found + /// nothing and the readings were never actually refreshed.) private static let amdClasses = [ "AMDRadeonX6000_AMDAcceleratedVKDriver", - "AMDRadeonX6000_AmdRadeonGraphicsAccelerator", - "AMDGPUAccelerator" + "AMDRadeonX6000_AMDGraphicsAccelerator" ] /// Reads `PerformanceStatistics` of the AMD accelerator. The values are diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift index 41a15aca..418ece3f 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlCurveRules.swift @@ -39,6 +39,11 @@ enum GPUControlCurveRules { /// any other build the preview says so and does not decide. static let checkedVersions: Set = ["REL-072-2026-11-19"] + /// The GPUSensors release this app carries (`GPU/sensors/VERSION`): an + /// older kext that runs is one the app's own update did not replace, since + /// auto-update replaces the app but not the GPU package. + static let shippedRelease = "093" + /// Kext versions checked as a whole: `VersionInfo` is "REL-", the /// version's digits, then the build date, and the date comes from /// SOURCE_DATE_EPOCH when the GPU package is built (the date of the last @@ -50,8 +55,12 @@ enum GPUControlCurveRules { /// ("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, then (the same 0.9.0) its - /// GFX voltage and overclock cases, after the first 120. - static let checkedReleases: Set = ["080", "081", "090"] + /// GFX voltage and overclock cases, after the first 120. GPUSensors 0.9.3 + /// ("093") is 0.9.2 without the PMLog keeper, these checks unchanged. + /// 0.9.1 ("091") and 0.9.2 ("092") are not in the set: the keeper called + /// the driver's library from the kext's own thread and panicked this Mac + /// (2026-11-27), and neither was ever published. + static let checkedReleases: Set = ["080", "081", "090", "093"] /// The kext build is one this copy was checked against. Neither the /// editor nor a remembered fan state sends anything to another build. @@ -60,6 +69,19 @@ enum GPUControlCurveRules { return checkedVersions.contains(version) || release(of: version).map(checkedReleases.contains) == true } + /// The loaded kext is older than the release this app ships, or a release + /// this copy was not checked against: GPU control stays off and the page + /// says to install the GPU package again. Auto-update replaces the app but + /// not the GPU package, so this happens to anyone who updates the app + /// without the installer. + /// + /// The rule is membership in `checkedReleases`, not a comparison with + /// `shippedRelease`: a kext older than the shipped one that is in the set + /// (0.8.0, 0.8.1, 0.9.0) is still allowed, and a build this copy never saw + /// (a newer one included) gets nothing. Safe in both directions; the page + /// still words it as an out-of-date GPU package. + static func isOutdated(_ version: String?) -> Bool { !isChecked(version) } + /// "080" for "REL-080-2026-11-21": a release build's version digits, /// when the rest is a date. Nil for a debug build ("DBG-…") or any /// other shape. diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift index 3aef55c4..41f082c6 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift @@ -29,6 +29,52 @@ enum GPUControlVisibility { static func setFake(_ on: Bool) { lock.withLock { fake = on } } } +/// What may be sent to the kext that runs now. +/// +/// GPUSensors 0.9.1 and 0.9.2 panic this Mac, so a build outside +/// `GPUControlCurveRules.checkedReleases` gets nothing at all. A kext that +/// publishes no `VersionInfo` is not trusted either: "I don't know which +/// build this is" is not "fine". Giving a hold back is not a change, so the +/// way back to the start-up values is never gated (see `backToStartUp` and +/// `closeChanges`). +enum GPUControlKextGate { + enum Verdict: Equatable, Sendable { + /// A build this copy was checked against: values may go out. + case allowed + /// A build outside `checkedReleases` (0.9.1 and 0.9.2 among them). + case outdated + /// No build name read (yet, or none published). + case unknown + } + + static func verdict(_ version: String?) -> Verdict { + let text = version?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard !text.isEmpty else { return .unknown } + return GPUControlCurveRules.isOutdated(text) ? .outdated : .allowed + } + + /// What a remembered setting does with the verdict while it waits to be + /// re-applied after launch. + enum Remembered: Equatable, Sendable { + /// Send it: a build this copy was checked against. + case send + /// Keep waiting, the flag untouched: the version has not been read + /// yet. The first read fills it (within half a second of the page, the + /// row or the sensors asking), so a normal kext still gets it. + case wait + /// Give it up until the next launch: the kext is outdated. + case drop + } + + static func remembered(_ verdict: Verdict) -> Remembered { + switch verdict { + case .allowed: return .send + case .unknown: return .wait + case .outdated: return .drop + } + } +} + /// The live row: the card's power and fan as macOS publishes them, and the /// hotspot from GPUSensors.kext. struct GPUControlLive: Equatable, Sendable { @@ -118,6 +164,35 @@ final class GPUControlService: ObservableObject { var facts: GPUControlFacts? { GPUControlPageLogic.facts(snapshot: snapshot, control: control).map(withHolder) } + /// The kext's `VersionInfo` from the last read: the page's own read, or + /// the sensors' (`nil` before either). The model has none. + private var kextVersionNow: String? { + control?.writing?.kextVersion ?? GPUSensorsService.shared.versionNow + } + + /// What the gate says about the kext that runs now. The model is not a + /// kext and always allows: it has no `VersionInfo` to read. + var kextVerdict: GPUControlKextGate.Verdict { + guard fake == nil else { return .allowed } + return GPUControlKextGate.verdict(kextVersionNow) + } + + /// The kext that runs is not the one this app carries (auto-update replaces + /// the app but not the GPU package), or a release GPU control was not + /// checked against: 0.9.1 and 0.9.2 panicked this Mac, so nothing is sent + /// and the page says to install the package again. + var kextOutdated: Bool { kextVerdict == .outdated } + + /// No build name read (yet, or at all). "I don't know which build this + /// is" is not "fine": a value is only sent to a build the app knows. + var kextVersionUnknown: Bool { kextVerdict == .unknown } + + /// Nothing that sends a value goes out: an outdated build, or one that + /// has not said which build it is. The way back to the start-up values + /// (`backToStartUp`, `closeChanges`) is not a change and keeps no guard, + /// on purpose. + var kextRefusesWrites: Bool { kextVerdict != .allowed } + /// Who else holds the control, asked only while the kext says a program /// does and it is not this one (GPUControlHolder): `gpucontrol hold` /// keeping the OD8 table is our own tool, not another program. The probe @@ -167,7 +242,16 @@ final class GPUControlService: ObservableObject { let model = fake let overclockNow = overclockNow controller.setReaskFilter { request in - let control = model.flatMap(GPUControlService.fakeControl) ?? GPUSensorsService.shared.currentControl() + let modelControl = model.flatMap(GPUControlService.fakeControl) + let control = modelControl ?? GPUSensorsService.shared.currentControl() + // A wake re-applies what is held, so it is gated too: a kext that + // is outdated, or that has not said which build it is, is sent + // nothing. The model is not a kext and has no version to read. + if modelControl == nil, + GPUControlKextGate.verdict(control?.writing?.kextVersion + ?? GPUSensorsService.shared.versionNow) != .allowed { + return nil + } let od8Ready = control?.writing?.od8Read == .read return GPUControlRememberPolicy.checkedAgain( request, stockGfxMaxMHz: control?.writing?.od8?.stockGfxMaxMHz, @@ -201,6 +285,7 @@ final class GPUControlService: ObservableObject { /// The pop-up and the panel row: the start-up value is the way back. func choosePower(_ watts: Int) { + guard !kextRefusesWrites else { return } guard let controller, let facts else { return } if watts == facts.bootW { backToStartUp() @@ -214,6 +299,7 @@ final class GPUControlService: ObservableObject { func applyFan(_ draft: GPUControlFanDraft) { // Always through the controller: a stock fan keeps a held clock, and // never gives back a power limit. + guard !kextRefusesWrites else { return } controller?.chooseFan(curve: draft.want.curve, zeroRpmOff: draft.want.zeroRpmOff) } @@ -221,24 +307,28 @@ final class GPUControlService: ObservableObject { /// The controller keeps a held fan state with it and gives a power limit /// back first. func chooseGfxMax(_ mhz: Int?) { + guard !kextRefusesWrites else { return } 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?) { + guard !kextRefusesWrites else { return } 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?) { + guard !kextRefusesWrites else { return } 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?) { + guard !kextRefusesWrites else { return } controller?.chooseVolt(mv) } @@ -257,6 +347,7 @@ final class GPUControlService: ObservableObject { /// "Open writing…": the administrator dialog runs the installed tool's /// fixed command, only when the owner presses the button. func openWriting(prompt: String) { + guard !kextOutdated else { return } guard !isArming else { return } if let fake { fake.arm() @@ -455,6 +546,7 @@ final class GPUControlService: ObservableObject { /// profile the kext confirms becomes the remembered state like any other /// change (`received`). func loadProfile(_ profile: GPUControlProfile) { + guard !kextRefusesWrites else { return } let writing = control?.writing let od8Ready = facts?.od8Ready ?? false let load = GPUControlProfiles.load( @@ -543,6 +635,21 @@ final class GPUControlService: ObservableObject { } if viewers == 0 { control = fake.flatMap(Self.fakeControl) ?? GPUSensorsService.shared.currentControl() } guard let facts else { return } + // The gate: an outdated build is sent nothing and the remembered + // setting is given up until the next launch; a version not read yet + // keeps it waiting (the read that fills it is this call's own, or the + // page's, within half a second), so a good kext still applies it. + switch GPUControlKextGate.remembered(kextVerdict) { + case .send: + break + case .wait: + return + case .drop: + pendingRemembered = false + rememberTimer?.invalidate() + rememberTimer = nil + return + } // Closed: keep waiting for an administrator to open it. Off, or held // by another program: give up until the next launch. if facts.off || facts.writeOffCode != 0 || (facts.owned && !facts.mine) { diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlFanSection.swift b/Sources/RyzenStatus/UI/Settings/GPUControlFanSection.swift index c53458e1..dde19c99 100644 --- a/Sources/RyzenStatus/UI/Settings/GPUControlFanSection.swift +++ b/Sources/RyzenStatus/UI/Settings/GPUControlFanSection.swift @@ -15,6 +15,10 @@ struct GPUControlFanSection: View { /// The section that asked last, so a refusal shows next to its control. @Binding var lastOD8Source: GPUControlOD8Source let apply: (GPUControlFanDraft) -> Void + /// The zero RPM switch's own answer when the state it would send is not + /// one the card takes: shown next to the switch, in the page's words for + /// a refusal. + @State private var zeroRpmRefusal: GPUControlCurvePreview? private var curveState: GPUControlCurveRules.State? { input.writing?.od8.flatMap(GPUControlCurveRules.State.init(table:)) @@ -58,6 +62,9 @@ struct GPUControlFanSection: View { .toggleStyle(.switch) .controlSize(.regular) .disabled(!enabled) + if let refused = zeroRpmRefusal { + refusalNote(refused) + } Toggle(fan.curveToggle, isOn: $draft.customCurve) .toggleStyle(.switch) .controlSize(.regular) @@ -130,6 +137,17 @@ struct GPUControlFanSection: View { .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } + // The switch's refusal is judged against the table it read then. When + // the next read gives another one, ask the same preview again and drop + // the note when the state would go out now (a drift that settled); a + // read that still refuses it keeps the note. + .onChange(of: input.writing) { _, _ in + guard zeroRpmRefusal != nil else { return } + let answer = GPUControlCurvePreview.make( + want: Self.stateSent(held: heldOD8, zeroRpmOff: draft.zeroRpmOff), + writing: input.writing) + if answer.allowsApply { zeroRpmRefusal = nil } + } } /// How far the curve editor sits in from its switch. @@ -139,16 +157,50 @@ struct GPUControlFanSection: View { /// 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. + /// + /// The preview judges the whole state the card will get, not the two + /// fields the switch builds: the controller adds the held clocks and the + /// voltage back before the call. When that state is refused, the section + /// says so next to the switch instead of reading on as if it went out. 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 } + zeroRpmRefusal = nil + guard enabled, let send = Self.zeroRpmAtOnce(held: heldOD8, zeroRpmOff: on) else { return } + let answer = GPUControlCurvePreview.make(want: Self.stateSent(held: heldOD8, zeroRpmOff: on), + writing: input.writing) + guard answer.allowsApply else { + zeroRpmRefusal = answer + return + } lastOD8Source = .fan apply(send) if !otherEdits { draft = draft.applied } } + /// The whole OD8 state the card gets when the switch sends `zeroRpmOff` + /// while `held` is held: the controller takes every setting from the held + /// state (what the kext has), so the preview must see the same one. + static func stateSent(held: GPUControlOD8Want, zeroRpmOff: Bool) -> GPUControlOD8Want { + GPUControlOD8Want(curve: held.curve, zeroRpmOff: zeroRpmOff, gfxMaxMHz: held.gfxMaxMHz, + gfxMinMHz: held.gfxMinMHz, voltMV: held.voltMV, overclock: held.overclock) + } + + /// A refusal in the page's own words (the live row's), with the kext's + /// sentence under it, as the page shows one. + private func refusalNote(_ answer: GPUControlCurvePreview) -> some View { + let (text, detail, _) = sentence(for: answer) + return VStack(alignment: .leading, spacing: 2) { + GPUControlProblemLabel(text: text, isProblem: true) + if let detail { + Text(detail) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + } + /// 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). @@ -330,7 +382,10 @@ struct GPUControlFanSection: View { .accessibilityElement(children: .combine) } - private var previewText: (String, String?, Bool) { + private var previewText: (String, String?, Bool) { sentence(for: preview) } + + /// One preview's sentence: the live row's, and the zero RPM switch's. + private func sentence(for preview: GPUControlCurvePreview) -> (String, String?, Bool) { switch preview { case .accepted: return (fan.curveOK, nil, true) diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift b/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift index 32d0730e..a4cd0e2a 100644 --- a/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift +++ b/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift @@ -103,8 +103,14 @@ struct GPUControlPageInput: Equatable { bootArm = service.bootArm isChangingBootArm = service.isChangingBootArm bootArmFailed = service.bootArmFailed - kextVersion = service.control?.writing?.kextVersion + let version = service.control?.writing?.kextVersion + kextVersion = version + // A kext this app was not checked against (older than the package it + // carries, or a release that is not in `checkedReleases`): the page + // says so and every control stays off. 0.9.1 and 0.9.2 panicked the + // Mac; auto-update brings the app without the GPU package. canChoose = service.mode != .none + && !(version.map(GPUControlCurveRules.isOutdated) ?? false) writing = service.control?.writing overclock = service.overclock profiles = service.profiles @@ -132,6 +138,15 @@ extension GPUControlPageInput { /// A request is out, or waits to be tried again: the kext has not taken it. var isPending: Bool { GPUControlPageLogic.pending(snapshot) != nil } + /// The kext that runs is not one this app was checked against: older than + /// the release it carries, or a release outside `checkedReleases` + /// (GPUSensors 0.9.1 and 0.9.2 panicked this Mac). A kext that publishes + /// no build name is not judged here. + var kextOutdated: Bool { + guard let kextVersion else { return false } + return GPUControlCurveRules.isOutdated(kextVersion) + } + /// The hold is the gpucontrol this app installs, not another program /// (GPUControlHolder): the page says so, and it is no problem to report. var holderIsOwnTool: Bool { facts?.holder.isOwnTool ?? false } @@ -272,6 +287,7 @@ struct GPUControlPageContent: View { var body: some View { Form { + if input.kextOutdated { kextOutdatedSection } stateSection if showsPower { powerSection } if showsPower, input.facts?.od8Ready == true { @@ -325,6 +341,25 @@ struct GPUControlPageContent: View { } } + // MARK: Outdated GPU package + + /// The GPU package that runs is not the one this app carries (or a release + /// GPU control was not checked against, like 0.9.1 and 0.9.2, which + /// panicked the Mac): said first, where GPU control lives, with every + /// control under it off. + private var kextOutdatedSection: some View { + Section { + HStack(alignment: .firstTextBaseline, spacing: 10) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(.orange) + .accessibilityHidden(true) + Text(s.kextOutdated) + .fixedSize(horizontal: false, vertical: true) + } + .accessibilityElement(children: .combine) + } + } + // MARK: Status /// "Feedback": the state next to what it describes; never color alone diff --git a/Tests/MetricsTests.swift b/Tests/MetricsTests.swift index 1b27f4e7..5ea2d364 100644 --- a/Tests/MetricsTests.swift +++ b/Tests/MetricsTests.swift @@ -11303,7 +11303,7 @@ struct MetricsTests { expect(!kextCppC6.contains("write_msr(kMSR_CSTATE_ADDR, 0xf0)"), "the kext never overwrites the firmware C-state address") let pmIdle = kextSource("SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/pmAMDRyzen.c") - expect(pmIdle.contains("(void)inb((uint16_t)c6Port);") && pmIdle.contains("if(!pmRyzen_pstate_control || pmRyzen_pstatelimit == 0) return;"), + expect(pmIdle.contains("(void)inb((uint16_t)c6Port);") && pmIdle.contains("if(!pmRyzen_pstate_control || pmRyzen_pstatelimit == 0 || (!pmRyzen_p1_ready && state != 0)) return;"), "CC6 idle enters through the C-state port and Zen 3+ never steps P-states") let kextHppS9d = kextSource("SMCAMDProcessor_Source/AMDRyzenCPUPowerManagement/AMDRyzenCPUPowerManagement.hpp") expect(kextHppS9d.contains("bool runMailboxDiagnostics(SMUDiagnosticReport &out);"), @@ -14507,6 +14507,7 @@ struct MetricsTests { ("GPUControlTests", GPUControlTests.run), ("GPUControlChannelTests", GPUControlChannelTests.run), ("GPUControlKext080Tests", GPUControlKext080Tests.run), + ("GPUControlKextGateTests", GPUControlKextGateTests.run), ("GPUControlPageTests", GPUControlPageTests.run), ("GPUControlHolderTests", GPUControlHolderTests.run), ("GPUControlBootArmTests", GPUControlBootArmTests.run), @@ -14516,6 +14517,7 @@ struct MetricsTests { ("GPUControlOverclockTests", GPUControlOverclockTests.run), ("GPUControlProfileTests", GPUControlProfileTests.run), ("GPUControlA11yTests", GPUControlA11yTests.run), + ("GPUControlReleaseTests", GPUControlReleaseTests.run), ("GPUFolderTests", GPUFolderTests.run), ("GPUInstallerDMGTests", GPUInstallerDMGTests.run), ("MonitorShortcutTests", MonitorShortcutTests.run), diff --git a/Tests/Suites/CppcIdleClockLimitTests.swift b/Tests/Suites/CppcIdleClockLimitTests.swift index 097c7fe8..46197827 100644 --- a/Tests/Suites/CppcIdleClockLimitTests.swift +++ b/Tests/Suites/CppcIdleClockLimitTests.swift @@ -155,10 +155,11 @@ enum CppcIdleClockLimitTests { return } suite.expect(!svc.contains("appliedIdleMaxPerf = 0") - && svc.contains("appliedIdleMaxPerf = ok ? maxPerf : nil"), + && svc.contains("appliedIdleMaxPerf = verdict.succeeded ? maxPerf : nil"), "the written max perf is recorded only after the kext took it") suite.expect(svc.contains("guard idleLimitWrites.mayBeCapped, canRun else { return }") - && svc.contains("if !writeIdleClockLimit(0) { scheduleLiftRetry() }"), + && svc.contains("if !lifted { self.scheduleLiftRetry() }") + && svc.contains("idleLimitWrites.willWrite(maxPerf)\n // The continuation"), "a lift follows the cap, not the last value, and a refused one is retried") } diff --git a/Tests/Suites/GPUControlKextGateTests.swift b/Tests/Suites/GPUControlKextGateTests.swift new file mode 100644 index 00000000..25dc7e67 --- /dev/null +++ b/Tests/Suites/GPUControlKextGateTests.swift @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 RyzenStatus + +import Foundation + +/// The kext version gate (batch 84, job 259): a kext outside +/// `GPUControlCurveRules.checkedReleases`, or one that publishes no +/// `VersionInfo`, is sent no value — the six controls that send one, "Load +/// profile", the remembered setting after launch and the wake re-ask. The way +/// back to the start-up values (`backToStartUp`, `closeChanges`) is not a +/// change and stays open. +enum GPUControlKextGateTests { + static func run(_ suite: TestSuite) { + verdicts(suite) + remembered(suite) + policy(suite) + wiring(suite) + } + + // MARK: The verdict + + private static func verdicts(_ suite: TestSuite) { + suite.expect(GPUControlKextGate.verdict(nil) == .unknown, "no version read: unknown, not fine") + suite.expect(GPUControlKextGate.verdict(" ") == .unknown, "a blank version: unknown too") + suite.expect(GPUControlKextGate.verdict("REL-091-2026-11-27") == .outdated, + "0.9.1, one of the two that panicked this Mac: outdated") + suite.expect(GPUControlKextGate.verdict("REL-092-2026-11-27") == .outdated, + "0.9.2, the other one: outdated") + suite.expect(GPUControlKextGate.verdict("REL-093-2026-11-27") == .allowed, + "0.9.3, the release this app carries: allowed") + suite.expect(GPUControlKextGate.verdict("REL-080-2026-11-21") == .allowed, "0.8.0: allowed") + suite.expect(GPUControlKextGate.verdict("REL-072-2026-11-19") == .allowed, + "the exact build the curve rules were checked against: allowed") + suite.expect(GPUControlKextGate.verdict("DBG-abc") == .outdated, + "a debug build (no release digits): not a build this copy was checked against") + suite.expect(GPUControlKextGate.verdict(" REL-093-2026-11-27\n ") == .allowed, + "the version is trimmed before it is judged") + } + + // MARK: What the remembered setting does + + private static func remembered(_ suite: TestSuite) { + suite.expect(GPUControlKextGate.remembered(.allowed) == .send, + "a checked build: the remembered setting goes out") + suite.expect(GPUControlKextGate.remembered(.outdated) == .drop, + "an outdated build: given up, nothing sent") + suite.expect(GPUControlKextGate.remembered(.unknown) == .wait, + "no version read yet: it waits, the pending flag is kept") + suite.expect(GPUControlKextGate.remembered(GPUControlKextGate.verdict(nil)) == .wait, + "a kext that says nothing keeps the setting waiting, never sends it") + suite.expect(GPUControlKextGate.remembered(GPUControlKextGate.verdict("REL-092-2026-11-27")) == .drop, + "0.9.2 drops it before the request is even built") + suite.expect(GPUControlKextGate.remembered(GPUControlKextGate.verdict("REL-093-2026-11-27")) == .send, + "0.9.3 sends it") + } + + // MARK: The remembered request + + /// The second gate, inside the policy: a remembered fan state only ever + /// goes to a build the curve rules were checked against. The service's + /// gate drops a remembered setting before this runs; this one keeps the + /// fan state from leaving on its own. + private static func policy(_ suite: TestSuite) { + let fake = FakeGPUControlKext() + fake.arm() + // The channel's facts, as GPUControlKext080Tests reads them: the model's + // properties carry no `OD8State`, so only the status flags say the OD8 + // read is clean. + let channel = fake.connection() + _ = channel.open() + var snapshot = GPUControlSnapshot() + snapshot.status = channel.status() + guard let facts = GPUControlPageLogic.facts(snapshot: snapshot, + control: GPUControlService.fakeControl(fake)) else { + suite.expect(false, "the kext model's facts load") + return + } + suite.expect(facts.armed && facts.od8Ready, "the model is armed and its OD8 read") + let want = GPUControlOD8Want(curve: GPUControlFanDraft.testedCurve) + suite.expect(GPUControlRememberPolicy.request(remembered: .od8(want), active: true, facts: facts, + stopped: nil, kextVersion: nil) == nil, + "a remembered curve with no version read: nothing goes out") + suite.expect(GPUControlRememberPolicy.request(remembered: .od8(want), active: true, facts: facts, + stopped: nil, kextVersion: "REL-092-2026-11-27") == nil, + "a remembered curve with 0.9.2: nothing goes out") + suite.expect(GPUControlRememberPolicy.request(remembered: .od8(want), active: true, facts: facts, + stopped: nil, kextVersion: "REL-093-2026-11-27") != nil, + "a remembered curve with the build this copy was checked against: it goes") + } + + // MARK: The service's wiring + + /// Where the gate sits in `GPUControlService`. The service itself needs a + /// channel and a kext, which a unit test cannot install (a release build + /// always takes the real connection mode), so the paths are checked here: + /// every control that sends a value is behind the gate, the remembered + /// setting and the wake re-ask ask it, and the two way-back paths do not. + private static func wiring(_ suite: TestSuite) { + let path = FileManager.default.currentDirectoryPath + + "/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift" + let source = (try? String(contentsOfFile: path, encoding: .utf8)) ?? "" + suite.expect(!source.isEmpty, "the service's source is readable") + func count(_ needle: String) -> Int { source.components(separatedBy: needle).count - 1 } + suite.expect(count("guard !kextRefusesWrites else { return }") == 7, + "the six controls that send a value and load profile sit behind the gate") + suite.expect(count("GPUControlKextGate.remembered(kextVerdict)") == 1, + "the remembered setting asks the gate") + suite.expect(source.contains("GPUControlKextGate.verdict(control?.writing?.kextVersion"), + "the wake re-ask asks the gate") + suite.expect(!source.contains("guard let version = control?.writing?.kextVersion"), + "the old nil-is-fine check is gone") + + func body(of function: String) -> String { + guard let start = source.range(of: "func \(function)(") else { return "" } + let rest = source[start.upperBound...] + guard let end = rest.range(of: "\n }") else { return "" } + return String(rest[.. String { "REL-\(release)-2026-11-27" } + + private static func releases(_ suite: TestSuite) { + suite.expect(GPUControlCurveRules.checkedReleases == ["080", "081", "090", "093"], + "the checked releases are 080, 081, 090 and 093") + suite.expect(!GPUControlCurveRules.checkedReleases.contains("091"), + "0.9.1 is not a checked release") + suite.expect(!GPUControlCurveRules.checkedReleases.contains("092"), + "0.9.2 is not a checked release") + suite.expect(GPUControlCurveRules.shippedRelease == "093", + "the app says it ships GPUSensors 0.9.3") + + for release in ["090", "093"] { + suite.expect(GPUControlCurveRules.isChecked(build(release)), + "GPUSensors \(release) is a checked release") + suite.expect(!GPUControlCurveRules.isOutdated(build(release)), + "GPUSensors \(release) is not out of date") + } + } + + private static func refused(_ suite: TestSuite) { + for release in ["091", "092", "094"] { + suite.expect(!GPUControlCurveRules.isChecked(build(release)), + "GPUSensors \(release) is refused") + suite.expect(GPUControlCurveRules.isOutdated(build(release)), + "GPUSensors \(release) is reported as out of date") + } + // An older release outside the set, and builds that are not a release. + suite.expect(GPUControlCurveRules.isOutdated(build("072")), + "a release outside the set is out of date") + suite.expect(GPUControlCurveRules.isOutdated("DBG-2026-11-27"), + "a debug build is not a checked release") + suite.expect(GPUControlCurveRules.isOutdated(nil), + "an empty build name is not a checked release") + // The one build checked by name stays accepted. + suite.expect(GPUControlCurveRules.isChecked("REL-072-2026-11-19"), + "the build checked by name is accepted") + } + + private static func warning(_ suite: TestSuite) { + let en = FeatureStrings.gpuControlPage(.enUS) + suite.expect( + en.kextOutdated == "The GPU package is out of date. Open the RyzenStatus GPU installer from the DMG and install the update, then restart.", + "the warning is the sentence the job asks for") + suite.expect(en.all.contains(en.kextOutdated), + "the warning is part of the page's texts") + + for language in AppLanguage.allCases { + let strings = FeatureStrings.gpuControlPage(language) + suite.expect(!strings.kextOutdated.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + "\(language.rawValue) has the warning") + suite.expect(!strings.all.contains(where: { $0.trimmingCharacters(in: .whitespaces).isEmpty }), + "\(language.rawValue) has no empty page text") + } + + // The page's own rule: only a kext that says which build it is. + var input = GPUControlPageInput(facts: nil, state: nil, snapshot: nil) + input.kextVersion = build("091") + suite.expect(input.kextOutdated, "the page warns about 0.9.1") + input.kextVersion = build("092") + suite.expect(input.kextOutdated, "the page warns about 0.9.2") + input.kextVersion = build("093") + suite.expect(!input.kextOutdated, "the page says nothing about 0.9.3") + input.kextVersion = build("090") + suite.expect(!input.kextOutdated, "the page says nothing about 0.9.0") + input.kextVersion = nil + suite.expect(!input.kextOutdated, "a kext with no build name is not judged") + } +} diff --git a/Tools/build-gpu-assets.sh b/Tools/build-gpu-assets.sh index 4305d241..e0915f4a 100755 --- a/Tools/build-gpu-assets.sh +++ b/Tools/build-gpu-assets.sh @@ -163,7 +163,11 @@ cmp -s $P/SHA256SUMS $CHECK/GPU/SHA256SUMS || fail "the zip's SHA256SUMS is not mv -f $STAGE/GPU-Package.zip $OUT sums=$(shasum -a 256 $P/SHA256SUMS | awk '{print $1}') -sensors_info=$(strings -a $P/sensors/build/GPUSensors.kext/Contents/MacOS/GPUSensors | grep -m1 -E '^REL-' || print "?") +# The brace group's true takes the status out of the pipeline: strings dies of +# the SIGPIPE once grep -m1 has its match, and pipe_fail would fail the +# pipeline despite it, printing "?" for a marker that was read fine. +sensors_info=$( { strings -a "$P/sensors/build/GPUSensors.kext/Contents/MacOS/GPUSensors"; true; } \ + | grep -m1 -E '^REL-' || print "?") print print "GPU-Package: GPU sensors $(cat $G/sensors/VERSION) ($sensors_info), encoding fix $(cat $G/encode/VERSION)" print "commit $commit, SOURCE_DATE_EPOCH $SOURCE_DATE_EPOCH" diff --git a/Tools/make-dmg.sh b/Tools/make-dmg.sh index 932aaab5..e665b008 100755 --- a/Tools/make-dmg.sh +++ b/Tools/make-dmg.sh @@ -24,7 +24,7 @@ GPU_ZIP="ReleaseAssets/GPU-Package.zip" # Tools/build-gpu-assets.sh prints it; refresh it in the same commit as the zip. # The zip's own hash is not pinned: ditto stores modification times, so the same # files give another zip (the same lesson as the kext zip below). -GPU_PAYLOAD_SUMS_SHA256="252c4aad1470b7da15f3b794405db1fecb0a0e18a2699c4ea54d41e713c351d9" +GPU_PAYLOAD_SUMS_SHA256="c85c63afc10b7357952a9259b4beb2c60e925e9832d0f2c6de841afe2d7125c3" STAGING="" WORK="" MOUNT="" @@ -400,8 +400,15 @@ fi echo "▸ Creating writable image…" WORK="$(mktemp -d)" RW="$WORK/rw.dmg" -# Clear any stale mount left by a previous attempt on the same runner. -hdiutil detach "/Volumes/$VOLUME" -force 2>/dev/null || true +# Clear any stale mount left by a previous attempt on the same runner: only a +# disk image's, found by device in hdiutil info, so a volume of that name that +# hdiutil did not mount is left alone. The mount is matched as a whole field of +# the line (it can sit in the dev node's line or on one of its own), so a +# longer path that merely starts with it does not count. +stale_dev=$(hdiutil info 2>/dev/null | awk -v vol="/Volumes/$VOLUME" ' + $1 ~ /^\/dev\/disk/ { dev=$1 } + { for (i = 1; i <= NF; i++) if ($i == vol) { print dev; exit } }') || true +[[ -n "$stale_dev" ]] && hdiutil detach "$stale_dev" -force 2>/dev/null || true # hdiutil can fail transiently on CI runners; retry a few times. No -quiet, so a # real error is visible in the build log rather than swallowed. created=0 diff --git a/build.sh b/build.sh index cb7b4890..45b1b38f 100755 --- a/build.sh +++ b/build.sh @@ -348,7 +348,12 @@ rm -rf "$BUILD_STAGE" ditto --noextattr --noqtn "$STAGE" "$BUILD_STAGE" xattr -c -r "$BUILD_STAGE" 2>/dev/null || true if ! codesign --verify --deep --strict "$BUILD_STAGE" >/dev/null 2>&1; then - if xattr -lr "$BUILD_STAGE" 2>/dev/null | grep -Eq 'com\.apple\.(FinderInfo|ResourceFork|provenance|fileprovider)'; then + # The subshell's true takes the status out of the pipeline: grep -q exits at + # the first match and the listing is far more than a pipe buffer, so xattr + # would die of the SIGPIPE after it and pipefail would lose the match. A + # capture into a variable does not help: the print feeding grep then dies + # of the same SIGPIPE. + if ( xattr -lr "$BUILD_STAGE" 2>/dev/null; true ) | grep -Eq 'com\.apple\.(FinderInfo|ResourceFork|provenance|fileprovider)'; then echo " build/stage copy has local filesystem metadata; temp bundle was verified" else codesign --verify --deep --strict "$BUILD_STAGE" diff --git a/docs/GPU_CONTROL.md b/docs/GPU_CONTROL.md index 6e76f96e..92002077 100644 --- a/docs/GPU_CONTROL.md +++ b/docs/GPU_CONTROL.md @@ -12,15 +12,19 @@ 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. + allowed only until the Mac restarts or you close them again. With Allow changes after restart too, + asking for your password once lets remembered settings come back after a restart as well. +- One program holds one change at a time. When `gpucontrol hold` from Terminal holds the card, + Settings › GPU control says it is RyzenStatus's own tool instead of "Another program has the control". + 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. + 10 seconds, it puts stock back and closes changes until restart. While any setting is held, + GPUSensors takes the card's readings itself once a second so the watchdog stays active even + when no other tool is polling the card. ## Which cards @@ -30,6 +34,8 @@ Some things hold for all of it: | 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 | +NVIDIA cards and NullMoth are not supported or tested. + A control only shows when the kext says it takes it and the card offers it (its OverDrive feature bit is set). @@ -46,6 +52,11 @@ Five points, temperature and speed. The kext only takes curves that give at leas 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). +While a custom curve is held, the Zero RPM switch sends the change at once with that curve, +as the clock and voltage controls do; otherwise it is part of the curve that Apply curve +sends. The switch is sent only when the whole state the card would get passes the rules, and +when it does not, the section says why next to the switch and nothing is sent. + ## GFX maximum and minimum clock The maximum can be lowered from stock down to 1500 MHz. The minimum can be raised from its diff --git a/docs/KEXTS.md b/docs/KEXTS.md index e5cac878..286382ea 100644 --- a/docs/KEXTS.md +++ b/docs/KEXTS.md @@ -13,7 +13,7 @@ cp -R /Volumes/EFI/EFI ~/Desktop/EFI-backup ## 2. Replace the two kexts -Open the disk image's `Kexts` folder and drag both bundles into `/Volumes/EFI/EFI/OC/Kexts`, replacing the old ones. Leave every other kext alone, including the GPU kexts and `AMDCCDScheduler.kext` if you use them. +Open the disk image's `Kexts` folder and drag both bundles into `/Volumes/EFI/EFI/OC/Kexts`, replacing the old ones. Leave every other kext alone, including `AMDCCDScheduler.kext`. GPU kexts (`GPUSensors.kext`, `VCNJpeg.kext`) live in the disk image's "GPU RX 6000" folder and use their own installer, not manual copying into OC/Kexts. Keep the folder names as they are. OpenCore loads only the kexts listed under `Kernel › Add` in `config.plist`, and each entry's `BundlePath` must name a folder that is really there: if it points at a missing folder, OpenCore stops at boot. An extra copy under another name is ignored, so a backup in the same folder is harmless. @@ -23,7 +23,7 @@ Keep the folder names as they are. OpenCore loads only the kexts listed under `K kmutil showloaded | grep -E 'AMDRyzen|SMCAMD' ``` -Both lines should show the same, new version, for example `(3.42.0)`. If they differ, one kext is still the old one: replace it too before using the app. In RyzenStatus, Hardware Validation's kext version row should pass. If it still shows the old version, the old kext is the one OpenCore loaded: check that you copied into the EFI you boot from. +Both lines should show the same, new version, for example `(3.42.0)`. If they differ, one kext is still the old one: replace it too before using the app. In RyzenStatus, Hardware Validation's kext version row should pass. With 3.42.0, two programs talking to the CPU kext also coordinate fan writes so they no longer undo each other. If it still shows the old version, the old kext is the one OpenCore loaded: check that you copied into the EFI you boot from. ## 4. If the Mac does not boot diff --git a/docs/PERMISSIONS.md b/docs/PERMISSIONS.md index 558c5b0f..f73bc809 100644 --- a/docs/PERMISSIONS.md +++ b/docs/PERMISSIONS.md @@ -139,13 +139,13 @@ You can review or change every grant in System Settings, under Privacy and Secur ## Administrator, until restart and optional -**Why it comes up.** With the GPU sensors kext on an AMD Radeon RX 6000 card, the GPU control page can change the power limit, the fan curve and the maximum clock. Those changes reach the card's driver, so they are opened only when you click Allow GPU Changes and type your administrator password. +**Why it comes up.** With the GPU sensors kext on an AMD Radeon RX 6000 card, the GPU control page can change the power limit, the fan curve with zero RPM, minimum and maximum clocks, voltage (undervolt), overclock, and profiles. Those changes reach the card's driver, so they are opened only when you click Allow GPU Changes and type your administrator password. With Allow changes after restart too, asking for your password once lets remembered settings come back after a restart as well. NVIDIA cards and NullMoth are not supported or tested. **What uses it.** The GPU control page in Settings and its row in the menu bar panel. **If you say no.** The page still shows the card's readings and settings, but changes nothing. -**Optional.** Yes. Changes stay open until the Mac restarts or you close them again, and RyzenStatus never asks for the password on its own. +**Optional.** Yes. Changes stay open until the Mac restarts or you close them again, unless Allow changes after restart too is enabled. RyzenStatus never asks for the password on its own. ## Automation diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 4fa90441..3f80e4f1 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -63,9 +63,19 @@ Since macOS 15.4, Now Playing reads Music and Spotify by asking them directly, w - **The Mac restarts while booting after a kext update.** Add `-amdoff` to OpenCore's boot-args so the CPU kext does not start, or boot your backup EFI; then restore the old kexts. [Updating the AMD kexts](KEXTS.md#4-if-the-mac-does-not-boot) has both steps. - **You want to know whether the energy preference reaches the CPU.** Settings › AMD Ryzen › Hardware Validation shows the path it takes (CPPC MSRs or ACPI) and can read the values back from the firmware. - **Deep idle cannot be switched on.** The `amdcstate=1` or `-amdnoidle` boot arguments forbid it; remove them and restart. +- **Two programs fight over fan control.** With kext 3.42.0, programs talking to the CPU kext coordinate fan writes so they no longer undo each other. If another driver also attaches to the AMD host bridge at 00:00.0 to reach the SMU, the two drivers cannot share a lock, and their SMU mailbox commands could overlap. RyzenStatus checks for that before each of those writes and pauses its own power-limit, Curve Optimizer and preset writes while the other driver is there; sensors and readings keep working. Hardware Validation shows the same warning until the other driver is removed and the Mac restarts. +## AMD Radeon RX 6000 GPU & Video + +NVIDIA cards and NullMoth are not supported or tested. + +- **GPU control says changes are refused or busy.** Hardware writes need an administrator password via Allow GPU Changes (`-amdpnopchk` is for the CPU kext and does not open GPU changes). Power limit and OverDrive settings (clocks, fan, voltage) cannot be held at the same time. The hotspot temperature watchdog puts stock settings back and closes changes if hotspot hits 95 °C or if sensor readings stop for 10 seconds. +- **Only readings show, with no controls to change.** Only the RX 6800 XT writes. The RX 6900 XT is read-only, and other Navi cards are not supported for writes yet. Hardware Validation shows whether GPUSensors.kext is loaded and found a supported card. +- **Video playback after a system sleep.** GPU decoders (0.3.9) drop in-flight frames during sleep and start clean at the next key frame. If a video player hung after a wake on an older release, update the decoders using the GPU installer. +- **Safari or apps do not load the video decoders.** The decoders are ad-hoc signed, so macOS must accept them: with AMFIPass active, with the VCNVTLoader kext, or with AMFI switched off (`amfi=0x80`). `-amfipassoff` or `-liluoff` switch AMFIPass off, and then the loader or `amfi=0x80` is needed. The GPU installer reads your setup and tells you which one applies. + ## Resetting permissions To wipe RyzenStatus's granted permissions and let macOS ask again from scratch, pick one of these.