graphics: persistent pipeline and shader caches, a diagnostics report, typed boot failures, bounded logs, and a PM4 fuzzer #302

Closed
github-bot wants to merge 1 commit from gh-pr/302/head into gh-pr/302/base
Owner

@⁠Hyphaed on GitHub · 2026-08-20 16:13 UTC · original
Hyphaed:gb/gpu-memory-and-robustness → main · +2935 −107 · 35 files · 1 commits · closed without merging

  1. Games load faster the second time you run them, because the work the GPU driver does to compile shaders is now saved to disk instead of redone on every launch.
  2. When video memory runs low, the driver can now set something cheap aside itself, instead of the emulator having to delete textures and rebuild them.
  3. --diagnostics prints a short report you can paste into an issue: build, CPU, GPU, driver version. No paths, no usernames.
  4. A game that will not boot now tells you which check failed and what it means, instead of elf is not valid.
  5. Logs stop growing to gigabytes, so bug reports can be uploaded again (#200).

This replaces #301, which I closed. The change in it was fine, my description of it was not: I blamed a build error on header shadowing when I had simply built with GCC instead of clang. That work is included here.

Two caches that were not there

Pipelines. Every pipeline creation call passed a null cache handle, so the driver recompiled everything on every launch. The existing PipelineCache class is a lookup table of handles within one run, which is useful, but the driver never sees it and it disappears when the process exits.

There is now a real VkPipelineCache, loaded at startup and saved at exit. The file is checked against the current GPU and driver before the driver is allowed to read it, and ignored if it does not match. That happens after any driver update, so it is a log line rather than a warning.

Shaders. The GCN to SPIR-V translation was also redone from scratch each launch. This one is riskier than the pipeline cache, because a bad cache key here means wrong rendering rather than a slow start, so it is worth saying why it cannot do that.

Reusing a shader was never just a key lookup. After the key matches, the existing code re-checks the shader against the current register state before accepting it. I did not touch that check. Anything loaded from disk goes through it exactly like a shader compiled earlier in the same run, so a stale entry fails and gets recompiled. The worst case is a wasted compile, not a bad frame.

The file is also rejected outright unless it came from the same build: the header holds the git version plus a fingerprint of the recompiler's data structures. Strict on purpose, since a rejected cache costs one cold start and a wrongly accepted one costs correctness. Entries are checksummed individually, so one bad entry is dropped instead of the whole file, and both caches are written to a temp file and renamed, so being killed mid-write cannot corrupt them.

A bug this turned up: the emulator exits through quick_exit, which skips destructors and atexit handlers. Anything saved during teardown was never actually being saved. Both caches now flush from at_quick_exit. Worth knowing regardless of this PR.

Memory pressure

The renderer already reads the real memory budget and scales its GC around it, which is more care than most projects take. But when memory gets tight, the only move available is deleting resources, and the driver has no idea which ones matter.

Two optional extensions fix that: one lets each allocation carry a priority, the other lets the driver actually page video memory out instead of failing the allocation. Together they give the driver a cheaper option one step before the GC has to run. This does not replace the GC, it takes load off it.

They go on together or not at all, because priority alone only changes which allocation gets the out-of-memory error. Both are enabled only if the driver reports support, so a driver without them sees exactly what it saw before.

Only images get a raised priority. I left buffers alone deliberately: a dropped render target has to be fetched back before the next pass reads it, while most buffer data can be re-uploaded from guest memory you still hold. Buffer allocation is a shared path that also serves vertex and index data, and guessing wrong there costs performance with nothing in the log to show for it. Marking staging buffers as cheap looks right to me, but I would want to measure before claiming it.

Making bug reports usable

The compatibility list is this project's front door, so what a reporter can produce matters.

--diagnostics prints build, OS, CPU, and every GPU with its driver version, memory, and which optional extensions it has. It does not open a window or create a device, so it still works on a machine where the emulator will not start, which is exactly when you need it. No paths, no usernames, no game names, and a test fails if that ever changes.

Log size (#200). 5 GB in two minutes makes a log useless, as that issue and a comment on #281 both say. Filtering duplicate text would not help, because those lines carry an address that differs every time. What actually repeats is the line of code, so each log statement now counts itself: the first few hundred messages print in full, after that it is sampled, and a summary at the end names each noisy line with how often it really fired. Nothing vanishes silently, and a line that fires once still appears once.

This is your own pattern, generalised. Several hot spots already do exactly this by hand with a local counter; now nobody has to guess which line becomes the next problem. --log-repeat-limit 0 restores the old behaviour, and crash messages do not go through it at all. It is also faster, because the check happens before the string is formatted, so a skipped line costs an increment instead of a sprintf.

Ten million calls from one line produce 866 messages in the test.

Boot failures. Elf64::IsValid() was eleven checks, each logging a raw register comparison and returning false, after which the loader died with elf is not valid. Your shader code already has the right pattern for this, a named failure enum with a to-string; it just never reached game loading.

Those checks are now one standalone function returning a named reason plus a sentence someone can act on. A PC executable says it is not built for the FreeBSD ABI; a truncated file says it is too short to hold an ELF header. Standalone means it is testable with a made-up header and no emulator, so there is a case for every branch, including the ordering: telling someone "not x86-64" about a file that is not an ELF at all sends them the wrong way.

PM4 fuzzing

Command buffers come from the guest, and nothing tested that path except the buffers real games happen to produce. The harness has two halves.

The packet walker: random streams of padding words, variable-length NOPs and fixed-format packets. 20,000 buffers, 251,449 packets, full reset between runs. It does not feed random lengths, because a bad length is a deliberate abort, which is a guard working rather than a bug to find.

The register writes: roughly two thousand handlers unpacking bit fields out of guest words. The list of valid registers is read from the dispatch tables themselves, so this keeps covering new registers as they are added. Each one is first probed in a forked child with a zero payload. If it dies there it simply wants a different packet length, so it is skipped and counted; if it survives that and then dies on random values, that is a real bug and the run fails. Without the two steps you cannot tell those apart. Currently 471 of 474 registers, 256 rounds each.

Building a real render context needs a live GPU, which no CI runner has. The packets fuzzed here never touch the renderer, but that is an assumption, so the reference points at a page with no access permissions. If a handler ever reaches through it, the process dies immediately. The hardware enforces the boundary instead of a comment claiming it.

It found nothing. Said plainly: this is a regression net, not a list of bugs. I did check that it can fail, by breaking the generated packets and confirming it dies, then restoring them.

Draw, dispatch and DMA packets are not covered, since they need a real device and mapped guest memory. The forked half is skipped on Windows.

Testing

Built with clang, matching your CI. The five new test targets are wired into the build lists and the ctest filters on all three platforms, since a target in neither list does nothing. 11/11 locally.

The shader cache test uses real compiled SPIR-V from your own tiler shaders, and covers the first run, the round trip, truncation at every offset in the file, a corrupted entry, a cache from a different build, random junk files, and impossible length fields.

I have not measured a speedup and I am not claiming one. I do not have a title to test with here. The caches are verified to be written, validated and read back; whether that becomes a number you care about on a real game is something you can check far better than I can. Happy to split this into smaller PRs if that is easier to review.

**@⁠Hyphaed** on GitHub · 2026-08-20 16:13 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/302) `Hyphaed:gb/gpu-memory-and-robustness` → `main` · +2935 −107 · 35 files · 1 commits · closed without merging 1. Games load faster the second time you run them, because the work the GPU driver does to compile shaders is now saved to disk instead of redone on every launch. 2. When video memory runs low, the driver can now set something cheap aside itself, instead of the emulator having to delete textures and rebuild them. 3. `--diagnostics` prints a short report you can paste into an issue: build, CPU, GPU, driver version. No paths, no usernames. 4. A game that will not boot now tells you which check failed and what it means, instead of `elf is not valid`. 5. Logs stop growing to gigabytes, so bug reports can be uploaded again (#200). This replaces #301, which I closed. The change in it was fine, my description of it was not: I blamed a build error on header shadowing when I had simply built with GCC instead of clang. That work is included here. ## Two caches that were not there **Pipelines.** Every pipeline creation call passed a null cache handle, so the driver recompiled everything on every launch. The existing `PipelineCache` class is a lookup table of handles within one run, which is useful, but the driver never sees it and it disappears when the process exits. There is now a real `VkPipelineCache`, loaded at startup and saved at exit. The file is checked against the current GPU and driver before the driver is allowed to read it, and ignored if it does not match. That happens after any driver update, so it is a log line rather than a warning. **Shaders.** The GCN to SPIR-V translation was also redone from scratch each launch. This one is riskier than the pipeline cache, because a bad cache key here means wrong rendering rather than a slow start, so it is worth saying why it cannot do that. Reusing a shader was never just a key lookup. After the key matches, the existing code re-checks the shader against the current register state before accepting it. **I did not touch that check.** Anything loaded from disk goes through it exactly like a shader compiled earlier in the same run, so a stale entry fails and gets recompiled. The worst case is a wasted compile, not a bad frame. The file is also rejected outright unless it came from the same build: the header holds the git version plus a fingerprint of the recompiler's data structures. Strict on purpose, since a rejected cache costs one cold start and a wrongly accepted one costs correctness. Entries are checksummed individually, so one bad entry is dropped instead of the whole file, and both caches are written to a temp file and renamed, so being killed mid-write cannot corrupt them. **A bug this turned up:** the emulator exits through `quick_exit`, which skips destructors and `atexit` handlers. Anything saved during teardown was never actually being saved. Both caches now flush from `at_quick_exit`. Worth knowing regardless of this PR. ## Memory pressure The renderer already reads the real memory budget and scales its GC around it, which is more care than most projects take. But when memory gets tight, the only move available is deleting resources, and the driver has no idea which ones matter. Two optional extensions fix that: one lets each allocation carry a priority, the other lets the driver actually page video memory out instead of failing the allocation. Together they give the driver a cheaper option one step before the GC has to run. This does not replace the GC, it takes load off it. They go on together or not at all, because priority alone only changes which allocation gets the out-of-memory error. Both are enabled only if the driver reports support, so a driver without them sees exactly what it saw before. Only images get a raised priority. I left buffers alone deliberately: a dropped render target has to be fetched back before the next pass reads it, while most buffer data can be re-uploaded from guest memory you still hold. Buffer allocation is a shared path that also serves vertex and index data, and guessing wrong there costs performance with nothing in the log to show for it. Marking staging buffers as cheap looks right to me, but I would want to measure before claiming it. ## Making bug reports usable The compatibility list is this project's front door, so what a reporter can produce matters. **`--diagnostics`** prints build, OS, CPU, and every GPU with its driver version, memory, and which optional extensions it has. It does not open a window or create a device, so it still works on a machine where the emulator will not start, which is exactly when you need it. No paths, no usernames, no game names, and a test fails if that ever changes. **Log size (#200).** 5 GB in two minutes makes a log useless, as that issue and a comment on #281 both say. Filtering duplicate *text* would not help, because those lines carry an address that differs every time. What actually repeats is the line of code, so each log statement now counts itself: the first few hundred messages print in full, after that it is sampled, and a summary at the end names each noisy line with how often it really fired. Nothing vanishes silently, and a line that fires once still appears once. This is your own pattern, generalised. Several hot spots already do exactly this by hand with a local counter; now nobody has to guess which line becomes the next problem. `--log-repeat-limit 0` restores the old behaviour, and crash messages do not go through it at all. It is also faster, because the check happens before the string is formatted, so a skipped line costs an increment instead of a `sprintf`. Ten million calls from one line produce 866 messages in the test. **Boot failures.** `Elf64::IsValid()` was eleven checks, each logging a raw register comparison and returning false, after which the loader died with `elf is not valid`. Your shader code already has the right pattern for this, a named failure enum with a to-string; it just never reached game loading. Those checks are now one standalone function returning a named reason plus a sentence someone can act on. A PC executable says it is not built for the FreeBSD ABI; a truncated file says it is too short to hold an ELF header. Standalone means it is testable with a made-up header and no emulator, so there is a case for every branch, including the ordering: telling someone "not x86-64" about a file that is not an ELF at all sends them the wrong way. ## PM4 fuzzing Command buffers come from the guest, and nothing tested that path except the buffers real games happen to produce. The harness has two halves. **The packet walker:** random streams of padding words, variable-length NOPs and fixed-format packets. 20,000 buffers, 251,449 packets, full reset between runs. It does not feed random lengths, because a bad length is a deliberate abort, which is a guard working rather than a bug to find. **The register writes:** roughly two thousand handlers unpacking bit fields out of guest words. The list of valid registers is read from the dispatch tables themselves, so this keeps covering new registers as they are added. Each one is first probed in a forked child with a zero payload. If it dies there it simply wants a different packet length, so it is skipped and counted; if it survives that and then dies on random values, that is a real bug and the run fails. Without the two steps you cannot tell those apart. Currently 471 of 474 registers, 256 rounds each. Building a real render context needs a live GPU, which no CI runner has. The packets fuzzed here never touch the renderer, but that is an assumption, so the reference points at a page with no access permissions. If a handler ever reaches through it, the process dies immediately. The hardware enforces the boundary instead of a comment claiming it. **It found nothing.** Said plainly: this is a regression net, not a list of bugs. I did check that it can fail, by breaking the generated packets and confirming it dies, then restoring them. Draw, dispatch and DMA packets are **not** covered, since they need a real device and mapped guest memory. The forked half is skipped on Windows. ## Testing Built with clang, matching your CI. The five new test targets are wired into the build lists and the ctest filters on all three platforms, since a target in neither list does nothing. 11/11 locally. The shader cache test uses real compiled SPIR-V from your own tiler shaders, and covers the first run, the round trip, truncation at every offset in the file, a corrupted entry, a cache from a different build, random junk files, and impossible length fields. **I have not measured a speedup and I am not claiming one.** I do not have a title to test with here. The caches are verified to be written, validated and read back; whether that becomes a number you care about on a real game is something you can check far better than I can. Happy to split this into smaller PRs if that is easier to review.
Six changes that share one theme: the emulator was throwing away work and
information it already had.

- Enable VK_EXT_memory_priority and VK_EXT_pageable_device_local_memory, and
  give images a raised allocation priority, so the driver can demote something
  under pressure before the texture cache has to delete and rebuild it.

- Add a persistent VkPipelineCache. Every pipeline creation site passed a null
  cache, so the driver recompiled every pipeline on every launch. The blob is
  validated against the bound device before the driver sees it.

- Add a persistent recompiled-shader cache, so GCN to SPIR-V translation is not
  redone every launch. A loaded entry still has to pass the same runtime
  specialization check an in-run permutation passes, so a stale entry costs a
  recompile rather than a wrong frame.

- Write both caches from std::at_quick_exit. The normal exit path is
  std::quick_exit, which runs no destructors, so a cache written from teardown
  would never have reached disk.

- Add --diagnostics: build, OS, CPU and every Vulkan device with its driver and
  the extensions this emulator looks for. No paths, no usernames, no titles, so
  it is safe to paste into an issue.

- Classify boot failures. Elf64::IsValid was eleven inline checks that each
  logged a register-level line and returned false, after which the loader died
  with "elf is not valid". The checks are now one pure function returning a
  named BootFailure with a readable explanation.

- Rate limit logging per call site (issue #200). Logs reaching several GB in two
  minutes are a few lines in per-draw loops; each site now writes its first
  messages in full, is sampled after that, and is named with its true count in a
  summary. Fatal messages do not go through this path.

Adds boot_failure, log_rate_limit, shader_disk_cache, pm4_fuzz and diagnostics
test targets, wired into CI on all three platforms.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:16:10 +00:00
github-bot closed this pull request 2026-11-26 09:16:10 +00:00
Author
Owner

@⁠Nmzik on GitHub · 2026-08-29 08:30 UTC · original

1752f1382f in favor. Credited

**@⁠Nmzik** on GitHub · 2026-08-29 08:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/302#issuecomment-5461309011) 1752f1382f66308a2b5b57df956fe37dbe4b4dc4 in favor. Credited

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.