diff --git a/PEANUTS.md b/PEANUTS.md index 821d6489f..25d0d2830 100644 --- a/PEANUTS.md +++ b/PEANUTS.md @@ -15,7 +15,7 @@ Banana Native ships several releases a day, so this fork is kept as a **thin ove `onCreate` that touches the last-3-played list for dynamic shortcuts (`dev.peanuts.launch.RecentGames`, `peanuts/docs/LAUNCHERS.md`); (2026-11-21) one line at the top of `fpsTick` and one in `onDestroy` for the total play time (`dev.peanuts.launch.PlayTime`; the game page's Played row is one line in `MainActivity`'s More card); and (2026-11-13) in `start()`'s env assembly, two lines adding `DM_ROMFS_OVERLAY`/`DM_CHEATS` for the enabled Mods (`dev.peanuts.mods.ModRuntime`, - `design/platform/DESIGN-MODS.md`); (2026-11-18) one line in `settingsEnv` after `ResScale.env`: `dev.peanuts.Companion.env(this, id, env)` adds `PN_COMPANION=off` when the title's Second screen is Off, which is the default on a device without a second display (`Companion.hasSecondDisplay`); internal shader-preparation mode (`dev.peanuts.build.ShaderCapture`) covers the game surface, isolates its save/environment, suppresses play-session hooks and input, and reports errors to Build. + `design/platform/DESIGN-MODS.md`); (2026-11-18) one line in `settingsEnv` after `ResScale.env`: `dev.peanuts.Companion.env(this, id, env)` adds `PN_COMPANION=off` when the title's Second screen is Off, which is the default on a device without a second display (`Companion.hasSecondDisplay`); (2026-11-24) one line after it: `dev.peanuts.shaders.HostWatch.env(this, id, env)` registers the Peanuts tab's Smoother next start backend (`ShaderWatch`) in the game's process and adds `PN_SHADERWATCH=1` when learning is on for the title (`peanuts/UPSTREAM-EDITS.md` "Smoother next start"); internal shader-preparation mode (`dev.peanuts.build.ShaderCapture`) covers the game surface, isolates its save/environment, suppresses play-session hooks and input, and reports errors to Build. (2026-11-17) `hostSetup` and the active existing `fpsTick` forward the current display's presentation deadline through a marked helper. The same tick applies `dev.peanuts.display.RunningDisplayMode` before reading the deadline; pause and destruction release its window-local request. Only the running effective 30 fps cap with requested FG off selects a same-resolution 60 Hz mode; pending restart preferences are ignored. - `android/app/src/main/cpp/nxlaunch.c` — JNI entry points forwarded to `dm/peanuts`; (2026-11-17) `Native.java`/`nxlaunch.c` weakly forward the active display's queue lead to `nxhost_presentation_deadline_set`, exported in `vk_android.h`. Nonpositive or unavailable deadlines become zero; older hosts ignore the hint. - `android/app/src/main/java/dev/nxnative/android/Lsfg.java` — (2026-11-17) `push` releases the Activity's display request before its native FG enable call; actual display switching is asynchronous. @@ -23,6 +23,7 @@ Banana Native ships several releases a day, so this fork is kept as a **thin ove - `android/host/CMakeLists.txt`, `android/app/src/main/cpp/CMakeLists.txt` — add the `dm/peanuts` sources. - `dm/gfx/vk_android/vka_present.c` — one call per presented frame (`peanuts_tick()`), beside `ovl_draw`; (2026-11-17) one weak declaration and one argument in `ovl_draw`'s `vko_place(...)`: `peanuts_ovl_corner(s, g_ocorner[s])` (the stats block's corner chosen in the launcher; the build tag steps aside from a top-left block). - `dm/host/hle_audren.c` — (2026-11-20, audio follows the game's pace) in `render_main`, a weak declaration of `pn_audio_follow` and two marked lines: the rendered frame goes through `pn_audio_follow` (`dm/peanuts/peanuts_audiosync.c`; the clock's next render moves by the frames it gave out), and a call that gives nothing out yet (the stretch filling its look-ahead) appends no block. `dm/peanuts/peanuts_audiovoice.c` takes over `nn::audio::SetVoicePlayState` with its own `HLE_FORCE` (calls the SDK's own first): if upstream ever takes that symbol over too, merge the two. `peanuts_tick` feeds the game's frames (`pn_as_frame`, `nvn_game_fps` weak). `PN_AUDIO_FOLLOW` 0 / 1 (automatic, default) / 2. + - `dm/gfx/vk_android/vka_pso.c` — (2026-11-24, Smoother next start) the prewarm list's counts for the Peanuts tab (`vka_pso_watch`, read through `dm/peanuts/peanuts_shaderwatch.c`) and, with `PN_SHADERWATCH=1`, the pipelines a game's runs used made first and before the game starts, also on Qualcomm's driver before 512.800 (`sw_*` in one `PEANUTS begin`/`end` block, the file format and merge in `dm/peanuts/peanuts_swhot.h`; transform feedback capture pipelines with their layout in `dm/peanuts/peanuts_swtf.h`, made ahead by `sw_tf_make` through `vka_tf.c` `vka_tf_learned`); one-line marked hooks in `pc_open_once`, `save_now`, `vka_pso_save`, `vka_pso_prepare_launch`, `nxhost_prewarm_progress`, `pw_note`, `pw_main`, `pw_start`, `gfx_obtain`, `cs_obtain` and the entry `gval` (`swh`). Rule 2's exception, as the startup prewarm beside it. `peanuts/UPSTREAM-EDITS.md` "Smoother next start". - `dm/gfx/vk_android/vka_dev.c` `vka_gpu_floor` — (2026-11-23, #113/#257) one weak call into `dm/peanuts/peanuts_gpufloor.c`: the KGSL clock floor's beat on kernels that apply the constraint only to flagged commands (`PN_GPU_FLOOR_BEAT`). `peanuts/UPSTREAM-EDITS.md` Round 62. - `dm/gfx/vk_android/vka_dev.c` `vka_cap_period_clamp`, `vka_perf.c` — (2026-11-24, 0.1.8 hardening) the active frame cap's period as the shortest, one function for the GPU floor's period and the ADPF target (`dm_fps_cap_get` / `nxhost_fps_limit_get`, weak). `peanuts/UPSTREAM-EDITS.md` "0.1.8 hardening". - `dm/gfx/vk_android/vka_tex.c` `vka_tex_b2t_mirror`, `vka_dlss.c` `dpass`, `vka_fsr3.c` `pass` — (2026-11-24, 0.1.8 hardening) one `vka_dyn_invalidate()` each after a compute pass recorded between the game's dispatches, so the next dispatch pushes its descriptors again (`vka_draw.c` `push_same`). `peanuts/UPSTREAM-EDITS.md` "0.1.8 hardening". diff --git a/android/app/src/jvmtest/java/dev/peanuts/shaders/HostCountsJvmTest.java b/android/app/src/jvmtest/java/dev/peanuts/shaders/HostCountsJvmTest.java new file mode 100644 index 000000000..a85d62a25 --- /dev/null +++ b/android/app/src/jvmtest/java/dev/peanuts/shaders/HostCountsJvmTest.java @@ -0,0 +1,44 @@ +// PEANUTS: a test of the fork's own classes (HostCounts: the host's numbers as the Peanuts tab shows them); upstream has no dev.peanuts tests +package dev.peanuts.shaders; + +/** HostCounts on the JVM (peanuts/tests/test_shader_watch.py): the host's four numbers as the Peanuts tab's */ +public final class HostCountsJvmTest { + private static int failed; + + private static void check(boolean ok, String what) { + if (!ok) { failed++; System.out.println("FAIL " + what); } + } + + public static void main(String[] args) { + // the host cannot say (no libnxhost of this version, or not loaded) + check(!HostCounts.available(null), "no host: not available"); + check(HostCounts.learned(null) == HostCounts.UNKNOWN && HostCounts.ready(null) == HostCounts.UNKNOWN, "no host: unknown numbers"); + check(!HostCounts.available(new int[3]), "a short answer is no answer"); + + // the list not read yet: the game has not drawn its first program (its menus, a logo); a list is still to come + int[] early = {-1, 0, 0, 0}; + check(HostCounts.available(early), "not read yet: still available"); + check(HostCounts.learned(early) == HostCounts.UNKNOWN && HostCounts.ready(early) == HostCounts.UNKNOWN, "not read yet: numbers unknown"); + + // no list at all (no DM_TEMP: the host keeps nothing) + int[] none = {0, 0, 0, 0}; + check(!HostCounts.available(none), "no list: not available"); + check(HostCounts.learned(none) == HostCounts.UNKNOWN, "no list: learned unknown"); + + // a list: this run's new pipelines and what the next start makes ahead + int[] list = {1, 12, 642, 868}; + check(HostCounts.available(list), "a list: available"); + check(HostCounts.learned(list) == 12, "learned this run"); + check(HostCounts.ready(list) == 642, "made ahead next start on this driver, not every driver's records"); + + // a driver whose next start makes none ahead (prewarm off there): ready 0, learned still counts + int[] off = {1, 5, 0, 868}; + check(HostCounts.ready(off) == 0 && HostCounts.learned(off) == 5, "prewarm off: 0 ready, learned counted"); + + // never a negative count from a host that misbehaves + check(HostCounts.learned(new int[]{1, -3, -1, 0}) == 0 && HostCounts.ready(new int[]{1, -3, -1, 0}) == 0, "no negative counts"); + + if (failed > 0) { System.out.println(failed + " failed"); System.exit(1); } + System.out.println("ok"); + } +} diff --git a/android/app/src/main/java/dev/nxnative/android/GameActivity.java b/android/app/src/main/java/dev/nxnative/android/GameActivity.java index 7af7de659..9aefd4340 100644 --- a/android/app/src/main/java/dev/nxnative/android/GameActivity.java +++ b/android/app/src/main/java/dev/nxnative/android/GameActivity.java @@ -630,6 +630,7 @@ private String settingsEnv(String id, Pack pack, List env) { // PEANUT ScreenMode.env(this, id, env); // PEANUTS: Console mode (DM_OPMODE) for a game whose Resolution does not set it ResScale.env(this, id, env); // PEANUTS: Resolution scale (DM_RES_SCALE) when it is not 1x dev.peanuts.Companion.env(this, id, env); // PEANUTS: companions off (PN_COMPANION=off) when the title's Second screen is Off, the default without a second display + dev.peanuts.shaders.HostWatch.env(this, id, env); // PEANUTS: Smoother next start: the Peanuts tab's backend (ShaderWatch) in the game's process if (prof != null) env.addAll(prof.resolutionEnv(Prefs.startWindow(this, id))); // a Resolution preset's window, else Game resolution's (Prefs.startWindow, ResPresets) // Resolution, Upscaling quality and Graphics quality (a render_cfg row: Profile.renderCfg), kept as the setting this run starts with: the loader sizes the render target // pool for it, and the in-game panel compares a pick with it (Profile.renderRestartNote) diff --git a/android/app/src/main/java/dev/peanuts/Bridge.java b/android/app/src/main/java/dev/peanuts/Bridge.java index e38c90c45..0140043a2 100644 --- a/android/app/src/main/java/dev/peanuts/Bridge.java +++ b/android/app/src/main/java/dev/peanuts/Bridge.java @@ -44,6 +44,16 @@ private Bridge() {} /** opMode(), or -1 when the host does not have it (an older libnxhost), is not loaded, or the game has not shown a frame yet (asking earlier would fix the mode) */ public static int opModeSafe() { try { return opMode(); } catch (UnsatisfiedLinkError e) { return -1; } } + /** The host's prewarm list for Smoother next start (dm/peanuts/peanuts_shaderwatch.c, vka_pso.c vka_pso_watch) into out[0..3]: the list (1 kept, 0 none, -1 not read + * yet), the pipelines new to it this run, those the next start makes ahead on this driver, its records in all; false when the host cannot say */ + public static native boolean shaderWatch(int[] out); + /** shaderWatch(out), false when the host does not have it (an older libnxhost) or is not loaded */ + public static boolean shaderWatchSafe(int[] out) { try { return shaderWatch(out); } catch (UnsatisfiedLinkError e) { return false; } } + /** Smoother next start's learning turned on or off while the game runs (the start reads PN_SHADERWATCH): false when the host cannot */ + public static native boolean shaderWatchLearn(boolean on); + /** shaderWatchLearn(on), false when the host does not have it or is not loaded */ + public static boolean shaderWatchLearnSafe(boolean on) { try { return shaderWatchLearn(on); } catch (UnsatisfiedLinkError e) { return false; } } + public static final int RT_PENDING = 0, RT_LOADED = 1, RT_NONE = 2, RT_FAILED = 3; /** Core::Mods::HapticKind (dm/peanuts/peanuts.h): what raised a pulse. */ diff --git a/android/app/src/main/java/dev/peanuts/shaders/HostCounts.java b/android/app/src/main/java/dev/peanuts/shaders/HostCounts.java new file mode 100644 index 000000000..8778f578d --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/shaders/HostCounts.java @@ -0,0 +1,24 @@ +package dev.peanuts.shaders; + +/** + * The host's four numbers (dev.peanuts.Bridge.shaderWatch, dm/gfx/vk_android/vka_pso.c vka_pso_watch) as {@link ShaderWatch}'s, for {@link HostWatch}. Pure, so + * HostCountsJvmTest checks it on the JVM. v: null when the host cannot say, else {the list: 1 kept, 0 none, -1 not read yet; pipelines new to it this run; + * pipelines the next start makes ahead on this driver; records in all}. + */ +final class HostCounts { + private HostCounts() {} + + /** ShaderWatch.UNKNOWN (that class reads Android's prefs, so it is not compiled into the JVM test; HostWatch checks the two are equal) */ + static final int UNKNOWN = -1; + + /** Whether the host keeps a list for this game: it can say, and the list is not off (-1, not read yet, is a list still to come) */ + static boolean available(int[] v) { return v != null && v.length >= 4 && v[0] != 0; } + + /** The pipelines new to the list this run, UNKNOWN before the host has read the list */ + static int learned(int[] v) { return read(v) ? Math.max(0, v[1]) : UNKNOWN; } + + /** The pipelines the next start makes ahead on this driver, UNKNOWN before the host has read the list */ + static int ready(int[] v) { return read(v) ? Math.max(0, v[2]) : UNKNOWN; } + + private static boolean read(int[] v) { return v != null && v.length >= 4 && v[0] == 1; } +} diff --git a/android/app/src/main/java/dev/peanuts/shaders/HostWatch.java b/android/app/src/main/java/dev/peanuts/shaders/HostWatch.java new file mode 100644 index 000000000..7fe5a565a --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/shaders/HostWatch.java @@ -0,0 +1,64 @@ +package dev.peanuts.shaders; + +import android.app.Activity; +import android.os.SystemClock; + +import java.util.List; + +/** + * The backend of {@link ShaderWatch} (Smoother next start): the Vulkan replay's prewarm list. While a game runs the host puts every pipeline it makes on the + * frame path or in the background into the game's list (DM_TEMP/vk_pipelines.keys, dm/gfx/vk_android/vka_pso.c pw_note): the shaders and the state a draw + * needed, by the shader library's keys, so the list holds for every driver and drops what a game update or a new shader library no longer has. Where the driver + * allows it the next start makes the whole list in the background; on Qualcomm's driver before 512.800 it makes none of it (a pipeline holds memory outside the + * process there), and those pipelines are made again while the game plays, at every start, their draws skipped until then. + *

+ * Learning on (the tab's switch for this game, {@link #LINE} at the start): each run also keeps the pipelines it used, per game and driver (vka_pso.c sw_*), and + * the next start makes those first and before the game starts, behind "Preparing shaders", also on that driver, where it stops when memory runs short. Off: the + * host does as upstream's does, and nothing of this is read or written. The numbers come from the list itself through + * {@link dev.peanuts.Bridge#shaderWatch} (dm/peanuts/peanuts_shaderwatch.c, vka_pso.c vka_pso_watch). + *

+ * Registered once in the game's process: {@link #env} runs at every start of the game (GameActivity.settingsEnv), before the host and the tab. + */ +public final class HostWatch implements ShaderWatch.Backend { + private static final HostWatch INSTANCE = new HostWatch(); + /** The host is asked at most this often (the tab reads status about once a second, and the walk holds the list's lock) */ + static final long READ_MS = 500; + + private final int[] v = new int[4]; + private boolean ok; + private long readAt = Long.MIN_VALUE / 2; + + private HostWatch() {} + + static { if (HostCounts.UNKNOWN != ShaderWatch.UNKNOWN) throw new AssertionError("HostCounts.UNKNOWN"); } + + /** The line that turns learning on for a run (vka_pso.c sw_on); without it the host learns and prepares as upstream's does */ + static final String LINE = "PN_SHADERWATCH=1"; + + /** + * At the start of a game, in its process: the backend registered (once is enough; again is harmless), and learning on for this run when the player turned it on + * for this game. A preparation boot of Build (dev.peanuts.build.ShaderCapture) is no play: never + */ + public static void env(Activity a, String titleId, List env) { + ShaderWatch.backend(INSTANCE); + env.removeIf(s -> s.startsWith("PN_SHADERWATCH=")); + if (titleId != null && ShaderWatch.on(a, titleId) && !dev.peanuts.build.ShaderCapture.active(a)) env.add(LINE); + } + + private synchronized int[] read() { + long now = SystemClock.elapsedRealtime(); + if (now - readAt >= READ_MS) { + int[] o = new int[4]; + ok = dev.peanuts.Bridge.shaderWatchSafe(o); + if (ok) System.arraycopy(o, 0, v, 0, 4); + readAt = now; + } + return ok ? v.clone() : null; + } + + @Override public boolean available(android.content.Context c, String titleId) { return HostCounts.available(read()); } + @Override public int learned() { return HostCounts.learned(read()); } + @Override public int ready(android.content.Context c, String titleId) { return HostCounts.ready(read()); } + /** The switch turned while the game runs: the host keeps (or stops keeping) this run's pipelines at once; the next start follows the switch as it is then */ + @Override public void learning(android.content.Context c, String titleId, boolean on) { dev.peanuts.Bridge.shaderWatchLearnSafe(on); } +} diff --git a/android/app/src/main/java/dev/peanuts/shaders/ShaderWatch.java b/android/app/src/main/java/dev/peanuts/shaders/ShaderWatch.java new file mode 100644 index 000000000..3b52fd6ba --- /dev/null +++ b/android/app/src/main/java/dev/peanuts/shaders/ShaderWatch.java @@ -0,0 +1,103 @@ +package dev.peanuts.shaders; + +import android.content.Context; +import android.content.SharedPreferences; + +/** + * Smoother next start (experimental; a switch per game in the quick menu's Peanuts tab): while a game runs, Peanuts counts + * its stutters and learns the shaders the host had to build during play, so that the next start's shader preparation builds them before play begins and the + * same hitch does not come twice. + *

+ * This class is the contract between the tab and the backend. The tab reads {@link #available}, {@link #on} and {@link #status}, and feeds the frame times + * it reads anyway ({@link #frames}): the stutter count is the tab's own. The backend (a record of the shaders and pipelines the host builds at run time, + * kept per game and build, and the next start's preparation taking them) registers itself with {@link #backend} and fills in what was learned and what is + * ready. Until a backend is there, {@link #available} is false and those numbers are {@link #UNKNOWN}: the tab shows the switch, marked Experimental, and + * says it is not active yet. + */ +public final class ShaderWatch { + private ShaderWatch() {} + + /** A number the backend does not know (or there is no backend) */ + public static final int UNKNOWN = -1; + + /** What this session has seen: stutters (the tab's count), shaders learned this session and shaders ready for the next start (the backend's) */ + public static final class Status { + public final int stutters, learned, ready; + public final long lastStutterAt; // SystemClock.elapsedRealtime of the newest stutter, 0 none + Status(int stutters, int learned, int ready, long lastStutterAt) { this.stutters = stutters; this.learned = learned; this.ready = ready; this.lastStutterAt = lastStutterAt; } + } + + /** The backend: whether it works for this game (its build, the driver), what it learned this session and what is ready, and learning on or off */ + public interface Backend { + boolean available(Context c, String titleId); + int learned(); + int ready(Context c, String titleId); + void learning(Context c, String titleId, boolean on); + } + + private static volatile Backend backend; + + /** The backend registers itself here (in the game's process, before the tab opens); null takes it away */ + public static void backend(Backend b) { backend = b; } + + public static boolean available(Context c, String titleId) { + Backend b = backend; + try { return b != null && b.available(c, titleId); } catch (RuntimeException e) { return false; } + } + + /** Learning while playing, for this game: off until the player turns it on (an experimental feature); kept in the game's prefs file */ + public static boolean on(Context c, String titleId) { return prefs(c).getBoolean("learn_" + titleId, false); } + + public static void on(Context c, String titleId, boolean on) { + prefs(c).edit().putBoolean("learn_" + titleId, on).apply(); + Backend b = backend; + if (b != null) try { b.learning(c, titleId, on); } catch (RuntimeException ignored) { } + } + + private static SharedPreferences prefs(Context c) { return c.getSharedPreferences("peanuts_panel", Context.MODE_PRIVATE); } + + public static Status status(Context c, String titleId) { + Backend b = backend; + int learned = UNKNOWN, ready = UNKNOWN; + if (b != null) { + try { learned = b.learned(); ready = b.ready(c, titleId); } catch (RuntimeException ignored) { } + } + synchronized (ShaderWatch.class) { return new Status(stutters, learned, ready, lastStutterAt); } + } + + // ---- Stutters, from the frame times (Bridge.frameTimes, newest last) ---- + + /** A stutter: a frame over STUTTER_MS that also takes more than RATIO times the median of the frames read with it (a scene's own slow pace is no stutter) */ + static final float STUTTER_MS = 50f, RATIO = 2.5f; + + private static int stutters; + private static long lastStutterAt; + private static float[] prev = new float[0]; + private static int prevN; + + /** The newest frame times (ms, oldest first, n of them): the new ones since the last call are checked for stutters */ + public static synchronized void frames(float[] ms, int n) { + int fresh = dev.peanuts.ui.GameStats.newFrames(prev, prevN, ms, n); + if (fresh > 0 && prevN > 0) { // the first read only sets the base: its frames are older than the tab + int found = count(ms, n, fresh); + if (found > 0) { stutters += found; lastStutterAt = android.os.SystemClock.elapsedRealtime(); } + } + if (prev.length < n) prev = new float[ms.length]; + System.arraycopy(ms, 0, prev, 0, n); + prevN = n; + } + + /** How many of the newest k frames of ms[0..n) are stutters (pure: ShaderWatchJvmTest) */ + static int count(float[] ms, int n, int k) { + if (n <= 0 || k <= 0) return 0; + float[] sorted = java.util.Arrays.copyOf(ms, n); + java.util.Arrays.sort(sorted); + float median = sorted[n / 2]; + int c = 0; + for (int i = Math.max(0, n - k); i < n; i++) if (ms[i] > STUTTER_MS && ms[i] > median * RATIO) c++; + return c; + } + + /** A new run of the game (its process): the count starts again */ + public static synchronized void reset() { stutters = 0; lastStutterAt = 0; prevN = 0; } +} diff --git a/android/host/CMakeLists.txt b/android/host/CMakeLists.txt index e19d17863..3f1d7b5cd 100644 --- a/android/host/CMakeLists.txt +++ b/android/host/CMakeLists.txt @@ -79,6 +79,7 @@ list(APPEND HOST_C ${ROOT}/dm/peanuts/peanuts_frametime.c) # PEANUTS: the time list(APPEND HOST_C ${ROOT}/dm/peanuts/peanuts_audiosync.c) # PEANUTS: the audio renderer's output follows the game's pace (peanuts_audiosync.h) list(APPEND HOST_C ${ROOT}/dm/peanuts/peanuts_audiovoice.c) # PEANUTS: the game's voice play-state changes for the audio follower (peanuts_audiovoice.c) list(APPEND HOST_C ${ROOT}/dm/peanuts/peanuts_gpufloor.c) # PEANUTS: the GPU clock floor on "highest only" KGSL kernels and an earlier first part (peanuts_gpufloor.c) +list(APPEND HOST_C ${ROOT}/dm/peanuts/peanuts_shaderwatch.c) # PEANUTS: Smoother next start: the prewarm list's counts for the Peanuts tab (Bridge.shaderWatch) # PEANUTS begin: the RomFS read straight from the player's dumps (DM_ROMFS=nsp:..., dm/peanuts/peanuts_nsp.h, DM_NSP_DIRECT below): the image over the dumps and # the three files of the importer that read them (keys, containers, NCA sections, AES, LZ4; dm/peanuts/import). Their AES and SHA paths for arm64 are picked at # run time and carry their own target attributes, so no file needs a flag for them; -O2 as the importer's own build (the cipher and the decoder are the cost of a read) diff --git a/dm/games/010051F0207B2000/README.md b/dm/games/010051F0207B2000/README.md index e58f48411..7c5a938b9 100644 --- a/dm/games/010051F0207B2000/README.md +++ b/dm/games/010051F0207B2000/README.md @@ -53,6 +53,7 @@ On the Thor with the issue's save, the boot crashed in eight of fifteen starts, General host changes first needed here; each applies to every game: +- **Pipelines made again while playing at every start** on Qualcomm's driver before 512.800 (Smoother next start, `vka_pso.c` `sw_*`): [Pipelines made again while playing at every start](../../../docs/reference/rendering.md#pipelines-made-again-while-playing-at-every-start-android). - **The steady clock runs through sleep and restarts:** [The steady clock runs through sleep and restarts](../../../docs/reference/services.md#the-steady-clock-runs-through-sleep-and-restarts). - **Two threads of one core in a font engine:** [Two threads of one core in a font engine](../../../docs/reference/threads.md#two-threads-of-one-core-in-a-font-engine): the boot crash below. diff --git a/dm/games/0100F43008C44000/README.md b/dm/games/0100F43008C44000/README.md index b4c00445e..6a0d109df 100644 --- a/dm/games/0100F43008C44000/README.md +++ b/dm/games/0100F43008C44000/README.md @@ -131,6 +131,7 @@ One shared 40-profile dev APK was used for all device runs. Its per-title test e General host changes first needed here; each applies to every game: +- **Pipelines made again while playing at every start** on Qualcomm's driver before 512.800 (Smoother next start, `vka_pso.c` `sw_*`; PEANUTS): [Pipelines made again while playing at every start](../../../docs/reference/rendering.md#pipelines-made-again-while-playing-at-every-start-android). - **Shader extraction reuse after translation-only updates:** [Shader extraction reruns after translation-only updates](../../../docs/reference/shaders.md#shader-extraction-reruns-after-translation-only-updates). - **Offline pipeline archive reuse across chains:** [Offline pipeline archive rebuilt after a chain-only update](../../../docs/reference/shaders.md#offline-pipeline-archive-rebuilt-after-a-chain-only-update). - **The pool enforced as on Horizon** (`mem_map_limit`, `hle_svc.c`): [the profile keys](../README.md#keys), [Maps past the application pool fail as on Horizon](../../../docs/reference/memory.md#maps-past-the-application-pool-fail-as-on-horizon). diff --git a/dm/gfx/vk_android/vka_pso.c b/dm/gfx/vk_android/vka_pso.c index c73b1bab6..00d29c278 100644 --- a/dm/gfx/vk_android/vka_pso.c +++ b/dm/gfx/vk_android/vka_pso.c @@ -7,6 +7,8 @@ #if defined(__ANDROID__) #include "vka.h" #include "vk_android.h" // PEANUTS: startup pipeline prewarm +#include "../../peanuts/peanuts_swhot.h" // PEANUTS: Smoother next start (learning on): the pipelines a game's runs used (sw_*) +#include "../../peanuts/peanuts_swtf.h" // PEANUTS: and the transform feedback capture pipelines they made (sw_tf_*) #include "vka_memu_abi.h" #include "vka_pwlist.h" #include "vka_psogate.h" @@ -174,6 +176,13 @@ static pthread_t g_pw_workers[4]; static int g_pw_threads; static _Atomic int g_pp_skip; // PEANUTS: Play anyway (nxhost_prewarm_skip): the startup prewarm and the preparing step stop where they are static _Atomic int g_pw_running; // PEANUTS: prewarm threads not yet returned (pp_prepare waits for them before it drops the shader modules) +static _Atomic uint32_t g_sw_new; static _Atomic int g_sw_open; // PEANUTS: the records new to the list this run, and whether pw_load has run (vka_pso_watch) +// PEANUTS: Smoother next start, learning on (sw_*, after pw_mark_bad): the switch (-1 not read yet), the file, the records the start makes first and waits for +static _Atomic int g_sw_on = -1, g_sw_dirty, g_sw_loaded, g_sw_wait; static char g_sw_path[1200]; static uint32_t g_sw_hot_n; static _Atomic uint32_t g_sw_hot_done; static int g_sw_only; // PEANUTS +static _Atomic int g_pw_counting; // PEANUTS: the prewarm threads count into g_pw_processed: only while the start waits for them (pp_prepare counts its own there after) +static __thread uint64_t t_sw_h; // PEANUTS: the record a prewarm thread is making (gfx_obtain / cs_obtain keep it in the entry for sw_used) +struct gval; static int sw_on(void); static void sw_path(void); static void sw_load(void); static void sw_save(void); static void sw_wait_hot(void); static void sw_used(struct gval *g); static void sw_run_add(uint64_t h, int learned); static void *pl_slurp(const char *path, size_t *n); // PEANUTS +static void sw_tf_note(vka_shader *const sh[5], const void *kb, uint32_t klen); // PEANUTS: Smoother next start: a capture pipeline made while the game ran static pthread_mutex_t g_pw_start_mu = PTHREAD_MUTEX_INITIALIZER; static void pw_path(char *out, size_t n) { @@ -200,6 +209,7 @@ static void pc_open_once(void) { } // The prewarm list (pw_*): the pipeline keys of earlier runs, whatever the driver (a key names shaders and state, not driver code). DM_VK_PREWARM_FILE overrides pw_path(g_pw_path, sizeof g_pw_path); // PEANUTS: share cache key path selection + sw_path(); // PEANUTS: Smoother next start's file beside the list void *data = NULL; size_t n = 0; FILE *f = g_pc_path[0] ? fopen(g_pc_path, "rb") : NULL; if (f) { @@ -252,9 +262,11 @@ static void pc_open_once(void) { free(data); pcl_open(); // PEANUTS pw_load(); + sw_load(); // PEANUTS: Smoother next start: the pipelines the runs before used (learning on) pthread_t th; if (!pthread_create(&th, NULL, saver_main, NULL)) { pthread_detach(th); g_sv_up = 1; } pw_start(g_pw_startup && !n && g_pc && g_pc_path[0]); // PEANUTS: wait only for a cold cache that can be saved + atomic_store_explicit(&g_sw_open, 1, memory_order_release); // PEANUTS: the list is read and ordered (vka_pso_watch, vka_pso_watch_learn) cw_start(); // PEANUTS } static void pc_open(void) { static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once(&once, pc_open_once); } // (the prewarm threads it starts call it too: they wait for it) @@ -301,6 +313,7 @@ static void save_now(void) { } } int keys = pw_save(); + sw_save(); // PEANUTS: Smoother next start (learning on) pcl_save(atomic_exchange(&g_pcl_due, 0)); // PEANUTS: the learned programs; the shader parts' cache when due uint64_t dt = now_ns() - t; atomic_fetch_add(&g_save_ns_total, dt); if (d || keys > 0) VLOG("pipeline cache: %zu bytes written to %s (%llu pipelines made this run), prewarm list %d keys, %.0f ms (on the saver thread)", n, g_pc_path[0] ? g_pc_path : "(none)", @@ -325,7 +338,7 @@ void vka_pso_save(int force) { if (!g_pc) return; uint64_t t = now_ns(); if (force != 1) { - if (__atomic_load_n(&g_made, __ATOMIC_RELAXED) == g_saved_at && !atomic_load(&g_pcl_due)) return; // PEANUTS: g_pcl_due (the shader parts' cache has something to save) + if (__atomic_load_n(&g_made, __ATOMIC_RELAXED) == g_saved_at && !atomic_load(&g_pcl_due) && !atomic_load(&g_sw_dirty)) return; // PEANUTS: g_pcl_due (the shader parts' cache has something to save), g_sw_dirty (Smoother next start) int s = force == 2 ? VKA_ENV("DM_VK_PCACHE_SAVE_SLOW_S", 3) : VKA_ENV("DM_VK_PCACHE_SAVE_S", 20); if (s < 1) s = 1; if (t - g_save_ns < (uint64_t)s * 1000000000ull) return; g_save_ns = t; @@ -339,12 +352,15 @@ void vka_pso_save(int force) { void vka_pso_prepare_launch(void) { const char *enabled = getenv("DM_VK_PREWARM"); int seed = dm_vk_prewarm_seed_len && VKA_ENV("DM_VK_PREWARM_SEED", 1); - if (seed && (!enabled || atoi(enabled) > 0) && !getenv("DM_GLSLC_CAPTURE") - && vka_init() && (!V.qcom_old || enabled)) { + int sw = sw_on(); // PEANUTS: Smoother next start (learning on): a start without the profile's seed, and one on a driver that does not prewarm, waits too + if ((seed || sw) && (!enabled || atoi(enabled) > 0) && !getenv("DM_GLSLC_CAPTURE") // PEANUTS: sw + && vka_init() && (!V.qcom_old || enabled || sw)) { // PEANUTS: sw g_pw_startup = 1; pc_open(); // the workers use the same once too, so join only after it returns if (atomic_load(&g_pw_start_total) > 0) { + if (g_sw_wait) sw_wait_hot(); else // PEANUTS: the pipelines the runs before used only; the rest of the list goes on in the background for (int i = 0; i < g_pw_threads; i++) pthread_join(g_pw_workers[i], NULL); + atomic_store(&g_pw_counting, 0); // PEANUTS: what goes on in the background counts no more (pp_prepare's progress below is its own) vka_pso_save(1); VLOG("startup prewarm complete: %u keys processed before guest entry", (unsigned)atomic_load(&g_pw_processed)); } @@ -358,7 +374,7 @@ void nxhost_prewarm_skip(void) { atomic_store(&g_pp_skip, 1); } int64_t nxhost_prewarm_progress(void) { int total = atomic_load(&g_pw_start_total); - return total <= 0 ? total : ((int64_t)total << 32) | atomic_load(&g_pw_processed); + return total <= 0 ? total : ((int64_t)total << 32) | (atomic_load(&g_sw_wait) ? atomic_load(&g_sw_hot_done) : atomic_load(&g_pw_processed)); // PEANUTS: g_sw_wait (Smoother next start) } void vka_gpl_line(char *out, size_t n); @@ -389,7 +405,7 @@ void vka_pso_waits(uint64_t *save_ns, uint64_t *pw_wait_ns) { if (save_ns) *save // ---------- Graphics pipelines ---------- // The map's value: the pipeline (VK_NULL_HANDLE = failed, its draws skipped), whether it is a fast-linked one, and whether a thread is still making it (busy: the frame path // waits for that thread instead of making it a second time). p and linked change in place when the optimized pipeline replaces the linked one -typedef struct gval { VkPipeline p; uint8_t linked, busy, pw; pid_t tid; } gval; // pw, tid: a prewarm thread is making it (busy), that thread (busy_wait) +typedef struct gval { VkPipeline p; uint8_t linked, busy, pw; pid_t tid; uint64_t swh; } gval; // pw, tid: a prewarm thread is making it (busy), that thread (busy_wait); PEANUTS: swh, the list record it was made from (sw_used) typedef struct { vka_shader *sh[VKA_NSTAGE]; VkPipelineLayout layout; vka_gkey k; } gkey_full; // (sh[5], compute, stays NULL) static kmap g_gfx = {.klen = sizeof(gkey_full)}; static pthread_cond_t g_busy_cv = PTHREAD_COND_INITIALIZER; @@ -1078,14 +1094,16 @@ static void pw_note(int kind, vka_shader *const sh[5], const void *kb, uint32_t pwrec r; memset(&r, 0, sizeof r); r.kind = (uint8_t)kind; r.klen = klen; for (int i = 0; i < 5; i++) { // an instanced variant: its base key and its binding, so the next run makes it ahead too (its pipeline was a frame-path hitch every run) if (!vka_shader_is_variant(sh[i])) { r.key[i] = sh[i] ? sh[i]->key : 0; continue; } + if (!i && kind == VKA_PW_GFX && vka_tf_is_variant(sh[0])) { sw_tf_note(sh, kb, klen); return; } // PEANUTS: a capture variant's pipeline: never in the list, Smoother next start keeps it (sw_tf_note) uint32_t lo = sh[i]->e->stage * DMSH_VK_STAGE_BINDINGS, b = sh[i]->inst_bind - 1; if (kind != VKA_PW_GFX || i > 1 || !sh[i]->inst_bind || b < lo || b - lo >= DMSH_VK_STAGE_BINDINGS) return; r.key[i] = sh[i]->e->key; r.inst[i] = (uint8_t)(b - lo + 1); } uint64_t h = vka_pw_hash(&r, kb); pthread_mutex_lock(&g_pw_mu); - if (pw_set_add(h)) { pw_append(&r, kb); g_pw_dirty = 1; } + if (pw_set_add(h)) { pw_append(&r, kb); g_pw_dirty = 1; atomic_fetch_add_explicit(&g_sw_new, 1, memory_order_relaxed); } // PEANUTS: g_sw_new (vka_pso_watch) pthread_mutex_unlock(&g_pw_mu); + if (sw_on()) sw_run_add(h, 1); // PEANUTS: Smoother next start: made while the game ran } // The records of one list into the run's (caller holds g_pw_mu), those already there skipped: the count taken, *skipped those with impossible values. -1 = not read (*why) static int pw_take(const uint8_t *d, size_t len, uint32_t *skipped, const char **why) { @@ -1151,6 +1169,180 @@ static void pw_mark_bad(size_t off) { // the record at off of the loaded list: if (off + sizeof(pwrec) <= g_pw_len) { g_pw_buf[off + offsetof(pwrec, bad)] = 1; g_pw_dirty = 1; } pthread_mutex_unlock(&g_pw_mu); } +// PEANUTS begin: Smoother next start, learning on (the quick menu's Peanuts tab, a switch per game: PN_SHADERWATCH=1 from dev.peanuts.shaders.HostWatch at the start, +// Bridge.shaderWatchLearn while the game runs; dm/peanuts/peanuts_shaderwatch.c). The prewarm list above holds every pipeline any run made, and the next start makes all +// of it ahead, except where that is off: on Qualcomm's driver before 512.800 (V.qcom_old) a pipeline holds about 6 MB outside the process, so the whole list made ahead ran +// games out of memory, and every start there made its pipelines again while it played, its draws skipped until each was there (the AYN Thor's own driver, 512.676: +// 2,300-2,700 draws skipped in each of eight runs of one game with the pipeline cache warm, where those 226 pipelines took 59 ms to make; Pokemon Legends: Z-A 11,253 in +// 70 s; docs/reference/rendering.md "Pipelines made again while playing at every start (Android)"). With learning on, each run also keeps the pipelines it used: those it made +// while it played (pw_note) and those the prewarm had made for it that a draw or dispatch then used (sw_used). They go into a file of this game and this driver beside the +// list (dm/peanuts/peanuts_swhot.h: record hashes, the runs since each was used, at most 4,096, 64 KB). The next start makes those records first, and before the game +// starts (behind "Preparing shaders": vka_pso_prepare_launch waits for them, the rest of the list goes on in the background where the driver prewarms it); where the driver +// does not prewarm, only those, by two threads that stop when the phone has less than DM_VK_PREWARM_MEM_MB available. An entry whose record is gone (a game update, +// another shader library) or another driver's matches nothing and ages out. With learning off nothing here runs: no file is read or written, the list is upstream's +static pthread_mutex_t g_sw_mu = PTHREAD_MUTEX_INITIALIZER; // a leaf: taken under g_mu (sw_used) and g_pw_mu (vka_pso_watch_learn), it takes no other lock +static pn_sw_ent *g_sw_old; static size_t g_sw_oldn; // the file as read: the runs before this one (under g_sw_mu) +static uint64_t *g_sw_run; static size_t g_sw_runcap, g_sw_runn; // this run's records used (under g_sw_mu) +static _Atomic uint32_t g_sw_learned; // of them, made while the game ran (not ahead) +static uint32_t g_sw_next; // the entries the last save wrote, or the file's: what the next start makes first (under g_sw_mu) +static uint8_t *g_sw_mark; // pw_start's order: 1 where it holds a record the runs before used (sw_step) +// The transform feedback capture pipelines (dm/peanuts/peanuts_swtf.h, ..tf): the list never takes them (a capture variant's modules carry the layout +// the game's program notes while it runs, vka_tf.c), so each is kept with its layout, and the next start makes its variant (vka_tf_learned) and pipeline first, before +// the game starts; a draw's first use checks that this run's program notes the same layout. Each has an entry in the .hot file too and ages out with it +static char g_sw_tf_path[1200]; +static pn_swtf_ent *g_sw_tfl; static size_t g_sw_tfln; // the file as read (under g_sw_mu; pw_main reads the first g_sw_tf_n, which stay) +static pn_swtf_ent *g_sw_tfr; static size_t g_sw_tfrn, g_sw_tfrcap; // this run's, made while the game ran (under g_sw_mu) +static uint32_t g_sw_tf_n; static _Atomic uint32_t g_sw_tf_next; // pw_start: those the prewarm makes, and the next one a thread takes +static int sw_on(void) { + int v = atomic_load_explicit(&g_sw_on, memory_order_relaxed); + if (v < 0) { const char *e = getenv("PN_SHADERWATCH"); int want = -1; atomic_compare_exchange_strong(&g_sw_on, &want, e && !strcmp(e, "1")); v = atomic_load(&g_sw_on); } + return v > 0; +} +static void sw_run_add(uint64_t h, int learned) { // a record this run used; learned: made while the game ran + pthread_mutex_lock(&g_sw_mu); + int n = pn_sw_set_add(&g_sw_run, &g_sw_runcap, &g_sw_runn, h); + pthread_mutex_unlock(&g_sw_mu); + if (n) { atomic_store_explicit(&g_sw_dirty, 1, memory_order_relaxed); if (learned) atomic_fetch_add_explicit(&g_sw_learned, 1, memory_order_relaxed); } +} +// The first use of a pipeline the prewarm made from a record (gfx_obtain / cs_obtain, caller holds g_mu): that record is this run's too +static void sw_used(gval *g) { + uint64_t h = __atomic_exchange_n(&g->swh, 0, __ATOMIC_RELAXED); + if (h && sw_on()) sw_run_add(h, 0); +} +static void sw_path(void) { + if (!g_pw_path[0]) return; + const char *tag = vka_driver_tag(); + snprintf(g_sw_path, sizeof g_sw_path, "%s.%s.hot", g_pw_path, tag ? tag : "system"); + snprintf(g_sw_tf_path, sizeof g_sw_tf_path, "%s.%s.tf", g_pw_path, tag ? tag : "system"); +} +static void sw_load_now(void) { // the file of the runs before, once (sw_load, vka_pso_watch_learn) + if (!g_sw_path[0] || atomic_exchange(&g_sw_loaded, 1)) return; + size_t len = 0; uint8_t *d = pl_slurp(g_sw_path, &len); + pn_sw_ent *e = NULL; size_t n = 0; uint64_t lib = 0; + const char *why = d ? pn_sw_parse(d, len, vka_pw_layout(), &e, &n, &lib) : NULL; + int had = d != NULL; + free(d); + if (!had) VLOG("Smoother next start: on, %s none yet (written as this run uses pipelines)", g_sw_path); + else if (why) VLOG("Smoother next start: on, %s %s: not used (this run's replaces it)", g_sw_path, why); + else VLOG("Smoother next start: on, %s: %zu pipelines of the runs before%s", g_sw_path, n, lib && g_pc_lib && lib != g_pc_lib ? " (another shader library: what it no longer has is skipped)" : ""); + pthread_mutex_lock(&g_sw_mu); free(g_sw_old); g_sw_old = e; g_sw_oldn = n; g_sw_next = (uint32_t)n; pthread_mutex_unlock(&g_sw_mu); + size_t tl = 0; uint8_t *td = pl_slurp(g_sw_tf_path, &tl); + pn_swtf_ent *te = NULL; size_t tn = 0, tskip = 0; + const char *twhy = td ? pn_swtf_parse(td, tl, vka_pw_layout(), &te, &tn, &tskip) : NULL; + if (td && twhy) VLOG("Smoother next start: %s %s: not used", g_sw_tf_path, twhy); + else if (td) VLOG("Smoother next start: %s: %zu transform feedback capture pipelines of the runs before%s", g_sw_tf_path, tn, tskip ? " (some damaged: skipped)" : ""); + free(td); + pthread_mutex_lock(&g_sw_mu); free(g_sw_tfl); g_sw_tfl = te; g_sw_tfln = tn; pthread_mutex_unlock(&g_sw_mu); +} +static void sw_load(void) { if (sw_on()) sw_load_now(); } // pc_open_once, after the list: learning on from the start +// sw_save, after the .hot file is written: the capture pipelines whose entries it keeps (this run's, then the runs before's), written when there are any or were +static void sw_tf_save(const pn_sw_ent *keep, size_t kn) { + pthread_mutex_lock(&g_sw_mu); + size_t had = g_sw_tfln, want = g_sw_tfrn + g_sw_tfln, n = 0; + pn_swtf_ent *e = want ? malloc(PN_SWTF_MAX * sizeof *e) : NULL; + if (e) n = pn_swtf_keep(g_sw_tfr, g_sw_tfrn, g_sw_tfl, g_sw_tfln, keep, kn, e, PN_SWTF_MAX); + pthread_mutex_unlock(&g_sw_mu); + static _Atomic int wrote; // (a file this run wrote, or read: rewritten when it empties) + if (want && !e) return; // (no memory: the file stays as it was) + if (!n && !had && !atomic_load(&wrote)) { free(e); return; } + size_t len = sizeof(pn_swtf_hdr) + n * sizeof(pn_swtf_ent); uint8_t *d = malloc(len); + if (d) { + pn_swtf_hdr h; memset(&h, 0, sizeof h); memcpy(h.magic, PN_SWTF_MAGIC, 8); h.n = (uint32_t)n; h.layout = vka_pw_layout(); h.ent_size = sizeof(pn_swtf_ent); + memcpy(d, &h, sizeof h); if (n) memcpy(d + sizeof h, e, n * sizeof *e); + char tmp[1300]; snprintf(tmp, sizeof tmp, "%s.tmp", g_sw_tf_path); + if (pc_write_atomic(g_sw_tf_path, tmp, d, len)) atomic_store(&wrote, 1); else VRED_ONCE("Smoother next start: %s not written", g_sw_tf_path); + } + free(d); free(e); +} +// A capture pipeline the frame path made (pw_note, learning on): its record (key[0] the variant's base vertex shader), key bytes and the layout its variant was made +// with, into this run's table and the .hot file's run (sw_run_add) +static void sw_tf_note(vka_shader *const sh[5], const void *kb, uint32_t klen) { + if (!sw_on() || klen > sizeof(vka_gkey) || !sh[0]->e) return; + pn_swtf_ent e; memset(&e, 0, sizeof e); + e.r.kind = VKA_PW_GFX; e.r.klen = klen; e.r.key[0] = sh[0]->e->key; + for (int i = 1; i < 5; i++) { if (vka_shader_is_variant(sh[i])) return; e.r.key[i] = sh[i] ? sh[i]->key : 0; } + memcpy(&e.k, kb, klen); + if (!vka_tf_layout_of(sh[0], &e.L)) return; + e.h = pn_swtf_hash(&e.r, &e.k); + if (!pn_swtf_ok(&e)) return; + pthread_mutex_lock(&g_sw_mu); + int added = pn_swtf_add(&g_sw_tfr, &g_sw_tfrn, &g_sw_tfrcap, &e); + pthread_mutex_unlock(&g_sw_mu); + if (added) { static _Atomic int nlog; if (atomic_fetch_add(&nlog, 1) < 8) VLOG("Smoother next start: transform feedback capture pipeline of vertex shader %016llx kept for the next start", (unsigned long long)e.r.key[0]); } + sw_run_add(e.h, 1); +} +static void sw_save(void) { // save_now: this run's records and the runs before's (pn_sw_merge), when this run added any + if (!g_sw_path[0] || !sw_on()) { atomic_store(&g_sw_dirty, 0); return; } // (learning turned off: vka_pso_save's early return holds again) + if (!atomic_exchange(&g_sw_dirty, 0)) return; + pthread_mutex_lock(&g_sw_mu); + size_t cap = g_sw_runn + g_sw_oldn; if (cap > PN_SW_MAX) cap = PN_SW_MAX; + uint8_t *out = malloc(sizeof(pn_sw_hdr) + (cap ? cap : 1) * sizeof(pn_sw_ent)); + size_t n = out ? pn_sw_merge(g_sw_run, g_sw_runcap, g_sw_old, g_sw_oldn, (pn_sw_ent *)(out + sizeof(pn_sw_hdr)), cap, PN_SW_AGE_MAX) : 0; + if (out) g_sw_next = (uint32_t)n; + pthread_mutex_unlock(&g_sw_mu); + if (!out) { atomic_store(&g_sw_dirty, 1); return; } + pn_sw_hdr h; memset(&h, 0, sizeof h); memcpy(h.magic, PN_SW_MAGIC, 8); h.n = (uint32_t)n; h.layout = vka_pw_layout(); h.lib = g_pc_lib; memcpy(out, &h, sizeof h); + char tmp[1300]; snprintf(tmp, sizeof tmp, "%s.tmp", g_sw_path); + if (!pc_write_atomic(g_sw_path, tmp, out, sizeof h + n * sizeof(pn_sw_ent))) { atomic_store(&g_sw_dirty, 1); VRED_ONCE("Smoother next start: %s not written", g_sw_path); } + else sw_tf_save((const pn_sw_ent *)(out + sizeof(pn_sw_hdr)), n); + free(out); +} +// The switch turned while the game runs (Bridge.shaderWatchLearn): on, the pipelines this run added to the list so far count too; off, nothing more is kept and the +// file stays as it was. What this start made ahead was the start's: the next start follows the switch +void vka_pso_watch_learn(int on) { + sw_on(); // (the environment's value read first, so the store below wins) + int open = atomic_load_explicit(&g_sw_open, memory_order_acquire); + if (on && open) sw_load_now(); // before learning counts as on: a save meanwhile would merge without the runs before's entries and lose them + atomic_store(&g_sw_on, on ? 1 : 0); + if (!on) atomic_store(&g_sw_dirty, 0); + if (!on || !open) return; + pthread_mutex_lock(&g_pw_mu); + for (size_t o = g_pw_load_len; o + sizeof(pwrec) <= g_pw_len;) { + pwrec r; memcpy(&r, g_pw_buf + o, sizeof r); const uint8_t *kb = g_pw_buf + o + sizeof r; o += pw_size(&r); + if (!r.bad) sw_run_add(vka_pw_hash(&r, kb), 1); + } + pthread_mutex_unlock(&g_pw_mu); +} +// pw_start: the loaded records the runs before used go first in their kind's part, in the list's order (pn_sw_order); with only (a driver that does not prewarm), +// none of the others. *n and *nm follow. Returns their count; 0 and the order upstream's when not learning +static uint32_t sw_order(size_t *offs, uint32_t *n, uint32_t *nm, int only) { + if (!sw_on() || !*n) return 0; + pthread_mutex_lock(&g_sw_mu); + uint64_t *set = NULL; size_t cap = 0, cnt = 0; + for (size_t i = 0; i < g_sw_oldn; i++) pn_sw_set_add(&set, &cap, &cnt, g_sw_old[i].h); + pthread_mutex_unlock(&g_sw_mu); + uint8_t *hot = cnt ? calloc(*n, 1) : NULL, *mark = hot ? calloc(*n, 1) : NULL; uint32_t *order = mark ? malloc(*n * sizeof *order) : NULL; + size_t *was = order ? malloc(*n * sizeof *was) : NULL; + uint32_t hn = 0; + if (was) { + for (uint32_t i = 0; i < *n; i++) { pwrec r; memcpy(&r, g_pw_load + offs[i], sizeof r); hot[i] = (uint8_t)pn_sw_set_has(set, cap, vka_pw_hash(&r, g_pw_load + offs[i] + sizeof r)); } + memcpy(was, offs, *n * sizeof *was); + uint32_t m = pn_sw_order(hot, *n, nm, only, order, mark, &hn); + for (uint32_t i = 0; i < m; i++) offs[i] = was[order[i]]; + *n = m; + free(g_sw_mark); g_sw_mark = mark; mark = NULL; + } + free(hot); free(mark); free(order); free(was); free(set); + return hn; +} +static void sw_step(uint32_t *cur) { // pw_main, after each record: the start's count while it waits for the threads, and one of those done + if (atomic_load(&g_pw_counting)) atomic_fetch_add(&g_pw_processed, 1); + if (*cur != UINT32_MAX && g_sw_mark && *cur < g_pw_limit && g_sw_mark[*cur]) atomic_fetch_add(&g_sw_hot_done, 1); + *cur = UINT32_MAX; +} +// vka_pso_prepare_launch: the start waits for those records only; the threads go on with the rest of the list in the background (where the driver prewarms it) +static void sw_wait_hot(void) { + uint64_t t0 = now_ns(); + while (atomic_load(&g_sw_hot_done) < g_sw_hot_n && atomic_load(&g_pw_running) > 0 && !atomic_load(&g_pp_skip)) usleep(5000); + for (int i = 0; i < g_pw_threads; i++) pthread_detach(g_pw_workers[i]); + atomic_store(&g_pw_counting, 0); atomic_store(&g_sw_wait, 0); // the start's progress is pp_prepare's from here (it counts in g_pw_processed); a pp_prepare with + // programs to prepare still waits for these threads before it drops the shader modules, as before + uint32_t done = atomic_load(&g_sw_hot_done); + VLOG("Smoother next start: %u of the %u pipelines the runs before used made before the game starts, in %.2f s%s%s", done, g_sw_hot_n, (now_ns() - t0) / 1e9, + atomic_load(&g_pp_skip) ? " (Play anyway)" : done < g_sw_hot_n ? " (the threads stopped: memory)" : "", + g_sw_only ? "; the rest of the list is not made ahead on this driver" : "; the rest of the list follows in the background"); +} +// PEANUTS end // Why a pipeline the frame path made was not made ahead (the first DM_VK_PREWARM_WHY of them, 64; 0 = none): the loaded list's records with the same shaders, and the // fields in which the nearest of them differs from the key asked for. "no record with these shaders" = new to the list (an area or effect no earlier run reached: prewarm // cannot help, only GPL or a faster compile); fields named = the list held a pipeline of the same shaders in another state (a state the key keeps that earlier runs did @@ -1204,6 +1396,70 @@ static int pw_memu_rec(const pwrec *r) { for (int s = 0; s < (r->kind == VKA_PW_CS ? 1 : 5); s++) if (r->key[s] && vka_shader_memu_key(r->key[s])) return 1; return 0; } +// PEANUTS begin: Smoother next start (the quick menu's Peanuts tab: dev.peanuts.shaders.HostWatch through Bridge.shaderWatch, dm/peanuts/peanuts_shaderwatch.c). +// What the host learned while the game ran and what the next start makes ahead of the game, from the prewarm list itself, so the tab's numbers are this list's: +// out[0] 1: this run keeps a prewarm list; 0: it keeps none (no DM_TEMP); -1: not read yet (the game has not drawn its first program) +// out[1] learning on: the pipelines this run made while the game ran (pw_note: on the frame path or in the background), which the next start makes first; +// off: those of them new to the list +// out[2] the records the next start makes ahead on this driver: not dropped, of this driver's vertex input form (a record of the other form is another driver's), +// no mesh record where mesh draws go through compute (pw_main skips those), at most DM_VK_PREWARM_MAX; +// where the driver does not prewarm (DM_VK_PREWARM's default 0 on Qualcomm's driver before 512.800), with learning on the runs' records the next start +// makes (sw_save), off 0 +// out[3] the list's records in all (every driver's) +// A walk of the run's records under g_pw_mu: at most DM_VK_PREWARM_KEEP + this run's new ones, microseconds, called by the tab about once a second +void vka_pso_watch(int out[4]) { + out[0] = -1; out[1] = out[2] = out[3] = 0; + if (!atomic_load_explicit(&g_sw_open, memory_order_acquire)) return; + out[0] = g_pw_path[0] ? 1 : 0; + int sw = sw_on(); + out[1] = (int)atomic_load_explicit(sw ? &g_sw_learned : &g_sw_new, memory_order_relaxed); + if (!out[0]) return; + int ahead = VKA_ENV("DM_VK_PREWARM", V.qcom_old ? 0 : 4) > 0; + uint32_t max = (uint32_t)VKA_ENV("DM_VK_PREWARM_MAX", 8192), here = 0, all = 0; + pthread_mutex_lock(&g_pw_mu); + for (size_t o = 0; o + sizeof(pwrec) <= g_pw_len;) { + pwrec r; memcpy(&r, g_pw_buf + o, sizeof r); const uint8_t *kb = g_pw_buf + o + sizeof r; o += pw_size(&r); + if (r.bad) continue; + all++; + if (!vka_pw_rec_ok(&r, kb) || (r.kind == VKA_PW_MESH && V.memu)) continue; + if (r.kind == VKA_PW_GFX) { uint32_t vs = 0; if (r.klen >= offsetof(vka_gkey, vin_static) + sizeof vs) memcpy(&vs, kb + offsetof(vka_gkey, vin_static), sizeof vs); + if (vs != (uint32_t)!V.vin_dyn) continue; } // (as pw_main reads it: a short key has none) + here++; + } + pthread_mutex_unlock(&g_pw_mu); + if (ahead) { if (sw) { pthread_mutex_lock(&g_sw_mu); here += (uint32_t)(g_sw_tfrn > g_sw_tfln ? g_sw_tfrn : g_sw_tfln); pthread_mutex_unlock(&g_sw_mu); } // (the capture pipelines: made too) + out[2] = (int)(here < max ? here : max); } + else if (sw && !getenv("DM_VK_PREWARM")) { pthread_mutex_lock(&g_sw_mu); uint32_t nx = g_sw_next > g_sw_runn ? g_sw_next : (uint32_t)g_sw_runn; pthread_mutex_unlock(&g_sw_mu); out[2] = (int)(nx < max ? nx : max); } + else out[2] = 0; + out[3] = (int)all; +} +// PEANUTS end +// PEANUTS begin: Smoother next start (learning on): one of the capture pipelines the runs before made (sw_tf_*), by a prewarm thread before the list's records: its +// shaders from the library, the capture variant made with the layout it was learned with (vka_tf_learned), its pipeline as the frame path asks for it (the variant +// takes the base shader's layout, vka_draw.c). One whose shaders the library no longer has, which this device cannot capture, or of the other vertex input form, is +// skipped and ages out +static _Atomic uint32_t g_sw_tf_made, g_sw_tf_skip; +static void sw_tf_make(uint32_t t) { + const pn_swtf_ent *e = &g_sw_tfl[t]; + vka_shader *sh[VKA_NSTAGE]; memset(sh, 0, sizeof sh); + int bad = e->k.vin_static != (uint32_t)!V.vin_dyn; + for (int s = 0; s < 5 && !bad; s++) if (e->r.key[s] && !(sh[s] = vka_shader_by_key(e->r.key[s]))) bad = 1; + if (!bad && !(sh[0] = vka_tf_learned(sh[0], &e->L))) bad = 1; + vka_layout lay; + if (!bad && !vka_layout_of(sh, 0, &lay)) bad = 1; + if (bad) { atomic_fetch_add(&g_sw_tf_skip, 1); atomic_fetch_add(&g_sw_hot_done, 1); return; } + int tok = gate_enter(0, gate_heavy(sh[0], sh[1])); + atomic_fetch_add(&g_pw_heavywait_ns, gate_hold(tok, sh[0]->key)); + t_sw_h = e->h; // (the entry made notes it at its first use: sw_used) + gkey_full fk; memset(&fk, 0, sizeof fk); memcpy(fk.sh, sh, sizeof fk.sh); fk.layout = lay.layout; fk.k = e->k; + size_t len = e->k.vin_static ? sizeof fk : offsetof(gkey_full, k.va); + int made = 0; + gfx_obtain(&fk, fnv(&fk, len, 1469598103934665603ull), len, sh, &lay, &fk.k, 1, &made); + gate_leave(tok); + if (made) { atomic_fetch_add(&g_pw_made, 1); atomic_fetch_add(&g_sw_tf_made, 1); } else atomic_fetch_add(&g_pw_had, 1); + atomic_fetch_add(&g_sw_hot_done, 1); +} +// PEANUTS end static void *pw_main(void *a) { (void)a; pthread_setname_np(pthread_self(), "vk-prewarm"); vka_fp_host("vk-prewarm"); setpriority(PRIO_PROCESS, 0, 10); // this thread (Linux: per-thread nice), under the game's threads @@ -1217,13 +1473,17 @@ static void *pw_main(void *a) { uint32_t mem_mb = (uint32_t)VKA_ENV("DM_VK_PREWARM_MEM_MB", 2048); // Each build goes through the gate (gate_enter: the frame's compiles first, as many at once as memory allows, a known long one alone) and holds while another build // of the same shader runs (gate_hold); with DM_VK_PREWARM_OVERLAP=1 each thread builds on its own and holds while any long compile runs (DM_VK_PREWARM_HEAVY_MS) - for (;; atomic_fetch_add(&g_pw_processed, 1)) { // PEANUTS: report each processed key + uint32_t sw_cur = UINT32_MAX; // PEANUTS: the record in hand, for sw_step (Smoother next start) + for (;; sw_step(&sw_cur)) { // PEANUTS: report each processed key while the start waits for them (sw_step, g_pw_counting) pause_point(); - if (me > 0 && mem_mb) { uint64_t t0 = 0, av; while ((av = mem_avail_mb()) && av < mem_mb && nm < limit && atomic_load(&g_pw_next) < limit - nm) { if (!t0) t0 = now_ns(); usleep(250000); pause_point(); } + if (g_sw_only && mem_mb) { uint64_t av = mem_avail_mb(); if (av && av < mem_mb) { static _Atomic int once; if (!atomic_exchange(&once, 1)) VLOG("Smoother next start: the prewarm stopped at %llu MB available (DM_VK_PREWARM_MEM_MB=%u): this driver holds memory for each pipeline", (unsigned long long)av, mem_mb); break; } } // PEANUTS: on a driver that does not prewarm, every thread stops (before the wait below, which would wait for a thread that stopped) + if (me > 0 && mem_mb && !g_sw_only) { uint64_t t0 = 0, av; while ((av = mem_avail_mb()) && av < mem_mb && nm < limit && atomic_load(&g_pw_next) < limit - nm) { if (!t0) t0 = now_ns(); usleep(250000); pause_point(); } // PEANUTS: !g_sw_only if (t0) atomic_fetch_add(&g_pw_memwait_ns, now_ns() - t0); } + if (g_sw_tf_n && !atomic_load(&g_pp_skip)) { uint32_t t = atomic_fetch_add(&g_sw_tf_next, 1); if (t < g_sw_tf_n) { sw_tf_make(t); continue; } } // PEANUTS: Smoother next start's capture pipelines first (sw_tf_make) uint32_t i = me == 0 ? atomic_fetch_add(&g_pw_next_mesh, 1) : nm; // the mesh thread: the next mesh record while there is one if (i >= nm) { uint32_t q = atomic_fetch_add(&g_pw_next, 1); i = nm + q; } if (i >= limit || atomic_load(&g_pp_skip)) break; // PEANUTS: match the startup progress total; Play anyway + sw_cur = i; // PEANUTS pwrec r; memcpy(&r, g_pw_load + offs[i], sizeof r); const uint8_t *kb = g_pw_load + offs[i] + sizeof r; vka_shader *sh[VKA_NSTAGE]; memset(sh, 0, sizeof sh); int bad = !vka_pw_rec_ok(&r, kb); @@ -1258,6 +1518,7 @@ static void *pw_main(void *a) { atomic_fetch_add(&g_pw_heavywait_ns, gate_hold(tok, key)); } int made = 0; + t_sw_h = !bad && sw_on() ? vka_pw_hash(&r, kb) : 0; // PEANUTS: the entry made from this record notes it (sw_used) if (bad) { atomic_fetch_add(&g_pw_bad, 1); pw_mark_bad(offs[i]); } else if (r.kind == VKA_PW_CS) { uint64_t m2[2] = {0, 0}; if (r.klen == 16) memcpy(m2, kb, 16); cs_obtain(sh[5], &lay, 1, &made, m2[0], m2[1], 0); } // PEANUTS: the retyped variant's masks else { @@ -1278,6 +1539,7 @@ static void *pw_main(void *a) { } if (atomic_fetch_add(&g_pw_done, 1) + 1 == (uint32_t)g_pw_threads) { free(g_pw_offsets); // PEANUTS: the last worker releases the shared list + free(g_sw_mark); g_sw_mark = NULL; // PEANUTS: and Smoother next start's marks VLOG("prewarm: %u of %u pipeline keys in %.1f s on %d threads: %u made, %u already there, %u dropped (shaders no longer in the library, another device's keys); the frame path waited %.0f ms for them; " "threads waited %.1f s for memory (DM_VK_PREWARM_MEM_MB), %.1f s for a long compile (DM_VK_PREWARM_HEAVY_MS)", (unsigned)(atomic_load(&g_pw_made) + atomic_load(&g_pw_had) + atomic_load(&g_pw_bad)), n, (now_ns() - g_pw_t0) / 1e9, g_pw_threads, (unsigned)atomic_load(&g_pw_made), @@ -1295,10 +1557,14 @@ static void *pw_main(void *a) { // PEANUTS: prepare one ordered list, then either detach or join its workers. static void pw_start(int wait) { int nt = VKA_ENV("DM_VK_PREWARM", V.qcom_old ? 0 : 4); + g_sw_tf_n = sw_on() && V.xfb ? (uint32_t)g_sw_tfln : 0; // PEANUTS: Smoother next start's capture pipelines (sw_tf_make; none where the device cannot capture) + int sw_only = nt <= 0 && !getenv("DM_VK_PREWARM") && sw_on() && g_sw_oldn && g_pw_load_n; // PEANUTS: Smoother next start on a driver that does not prewarm + if (sw_only) nt = 2; // PEANUTS: the pipelines the runs before used, only, on two threads (sw_order; pw_main stops them when memory is short) uint32_t max = (uint32_t)VKA_ENV("DM_VK_PREWARM_MAX", 8192); if (nt <= 0 || !g_pw_load_n || !max) { if (g_pw_load_n) VLOG("prewarm: off (%s): %u keys not made ahead", getenv("DM_VK_PREWARM") ? "DM_VK_PREWARM=0" : "default on Qualcomm's driver before 512.800; DM_VK_PREWARM=4 on", g_pw_load_n); return; } if (nt > 4) nt = 4; g_pw_limit = max < g_pw_load_n ? max : g_pw_load_n; + if (sw_on()) g_pw_limit = g_pw_load_n; // PEANUTS: Smoother next start: every record ordered, the cap after sw_order (the runs before's records are never the ones it cuts) g_pw_offsets = malloc(g_pw_limit * sizeof *g_pw_offsets); if (!g_pw_offsets) return; // Mesh first (compiled by one worker), then compute, then graphics. Within each kind keep the first-use order. @@ -1314,6 +1580,18 @@ static void pw_start(int wait) { if (!k) g_pw_mesh_count = iout; } g_pw_limit = iout; + // PEANUTS begin: Smoother next start (learning on): the records the runs before used first, and the start waits for them alone (sw_wait_hot), with a cold + // pipeline cache too; on a driver that does not prewarm, only those are made + g_sw_hot_n = sw_order(g_pw_offsets, &g_pw_limit, &g_pw_mesh_count, sw_only); + if (g_pw_limit > max) { g_pw_limit = max; if (g_pw_mesh_count > max) g_pw_mesh_count = max; } + if (g_sw_mark) { uint32_t c = 0; for (uint32_t i = 0; i < g_pw_limit; i++) c += g_sw_mark[i]; g_sw_hot_n = c; } + g_sw_hot_n += g_sw_tf_n; // (the capture pipelines are the runs before's too: made first, waited for) + g_sw_only = sw_only; g_sw_wait = g_pw_startup && g_sw_hot_n > 0; + if (g_sw_wait) wait = 0; // (a cold cache too: the start waits for those, the rest is made in the background) + if (sw_on()) VLOG("Smoother next start: %u of the list's %u pipelines are ones the runs before used, and %u transform feedback capture pipelines: made first%s%s", g_sw_hot_n - g_sw_tf_n, g_pw_load_n, g_sw_tf_n, + g_sw_wait ? ", before the game starts" : wait ? ", the start waits for the whole list (a cold pipeline cache)" : "", sw_only ? ", and only they (this driver does not prewarm)" : ""); + if (!g_pw_limit && !g_sw_tf_n) { free(g_pw_offsets); g_pw_offsets = NULL; return; } + // PEANUTS end heavy_load(); // the shaders earlier runs found long on this driver (build_end) g_pw_t0 = now_ns(); pthread_mutex_lock(&g_pw_start_mu); // PEANUTS: publish worker count before workers enter the loop @@ -1321,12 +1599,13 @@ static void pw_start(int wait) { pthread_t *thread = &g_pw_workers[g_pw_threads]; atomic_fetch_add(&g_pw_running, 1); // PEANUTS if (pthread_create(thread, NULL, pw_main, NULL)) { atomic_fetch_sub(&g_pw_running, 1); continue; } // PEANUTS: g_pw_running - if (!wait) pthread_detach(*thread); + if (!wait && !g_sw_wait) pthread_detach(*thread); // PEANUTS: g_sw_wait (sw_wait_hot detaches them) g_pw_threads++; } - if (wait && g_pw_threads) { - atomic_store(&g_pw_start_total, (int)g_pw_limit); - VLOG("startup prewarm: preparing %u pipeline keys before guest entry", g_pw_limit); + if ((wait || g_sw_wait) && g_pw_threads) { // PEANUTS: g_sw_wait + atomic_store(&g_pw_counting, 1); // PEANUTS (the threads wait on g_pw_start_mu until it is unlocked below) + atomic_store(&g_pw_start_total, (int)(wait ? g_pw_limit : g_sw_hot_n)); // PEANUTS: g_sw_hot_n + VLOG("startup prewarm: preparing %u pipeline keys before guest entry", wait ? g_pw_limit : g_sw_hot_n); // PEANUTS: g_sw_hot_n (the rest of the list goes on in the background) } if (!g_pw_threads) free(g_pw_offsets); pthread_mutex_unlock(&g_pw_start_mu); @@ -1883,12 +2162,14 @@ static gval *gfx_obtain(const gkey_full *fk, uint64_t h, size_t len, vka_shader pthread_mutex_lock(&g_mu); gval *g = km_get(&g_gfx, fk, h); if (g) { + if (!prewarm && g->swh) sw_used(g); // PEANUTS: Smoother next start: a pipeline made ahead from the list, used if (g->busy && (prewarm || async)) { pthread_mutex_unlock(&g_mu); return prewarm ? NULL : g; } if (g->busy) busy_wait(g); pthread_mutex_unlock(&g_mu); return g; } g = calloc(1, sizeof *g); g->busy = 1; g->pw = (uint8_t)(prewarm != 0); g->tid = prewarm ? gettid() : 0; km_put(&g_gfx, fk, h, g); + if (g && prewarm) g->swh = t_sw_h; // PEANUTS: the record it is made from (Smoother next start) pthread_mutex_unlock(&g_mu); uint64_t t_make = now_ns(); if (async) { @@ -2144,6 +2425,7 @@ static VkPipeline cs_obtain(vka_shader *cs, const vka_layout *lay, int prewarm, pthread_mutex_lock(&g_mu); gval *g = km_get(&g_cs, &k, h); if (g) { + if (!prewarm && g->swh) sw_used(g); // PEANUTS: Smoother next start: a pipeline made ahead from the list, used if (g->busy && (prewarm || async)) { // (a frame dispatch: skipped while another thread makes it) pthread_mutex_unlock(&g_mu); if (async) atomic_fetch_add_explicit(&g_as_skips, 1, memory_order_relaxed); @@ -2153,6 +2435,7 @@ static VkPipeline cs_obtain(vka_shader *cs, const vka_layout *lay, int prewarm, VkPipeline p = g->p; pthread_mutex_unlock(&g_mu); return p; } g = calloc(1, sizeof *g); g->busy = 1; g->pw = (uint8_t)(prewarm != 0); g->tid = prewarm ? gettid() : 0; km_put(&g_cs, &k, h, g); + if (g && prewarm) g->swh = t_sw_h; // PEANUTS: the record it is made from (Smoother next start) pthread_mutex_unlock(&g_mu); *made = 1; if (async) { diff --git a/dm/gfx/vk_android/vka_tf.c b/dm/gfx/vk_android/vka_tf.c index e27b4c6e2..69e3725d3 100644 --- a/dm/gfx/vk_android/vka_tf.c +++ b/dm/gfx/vk_android/vka_tf.c @@ -25,10 +25,13 @@ static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; // Capture layouts by library key, noted at nvnProgramSetShaders (the game's threads); st: 1 read, -1 a form not known typedef struct { uint64_t key; int st; vka_tf_layout L; } lay_ent; static lay_ent *g_lay; static int g_nlay, g_clay; -// The variants made, by base shader (v NULL: refused, logged); the replay thread makes them, a module-making thread reads L by v's key (vka_tf_prep) +// The variants made, by base shader (v NULL: refused, logged); the replay thread makes them, a module-making thread reads L by v's key (vka_tf_prep). Smoother next +// start (learning on, vka_pso.c sw_tf_*) also makes one ahead on a prewarm thread with the layout an earlier run noted (learned: vka_tf_learned); its first use by a draw +// checks that this run's program noted the same layout (checked), else it is dead and the draw makes its own as before. Appended under g_mu, g_nvar published last enum { NVAR = 256 }; -static struct { vka_shader *s, *v; vka_tf_layout L; } g_var[NVAR]; static _Atomic int g_nvar; +static struct { vka_shader *s, *v; vka_tf_layout L; uint8_t learned, checked, dead; } g_var[NVAR]; static _Atomic int g_nvar; static uint32_t g_max_loc, g_max_stride, g_max_bufs; static VkDeviceSize g_max_size; +static pthread_once_t g_caps_once = PTHREAD_ONCE_INIT; // (caps: the replay thread and the prewarm's) void nvn_tf_ctl_note(const uint8_t key[8], const void *control) { // hle_nvn.c, for each stage of a program whose key was made (the section is readable for 0x760 bytes there) lay_ent e; e.st = vka_tf_layout_read(control, 0x760, &e.L); @@ -42,8 +45,7 @@ void nvn_tf_ctl_note(const uint8_t key[8], const void *control) { // hle_nvn.c } pthread_mutex_unlock(&g_mu); } -static void caps(void) { - if (g_max_loc) return; +static void caps_read(void) { VkPhysicalDeviceTransformFeedbackPropertiesEXT tp = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT}; VkPhysicalDeviceProperties2 p2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &tp}; vk.vkGetPhysicalDeviceProperties2(V.pd, &p2); @@ -51,10 +53,42 @@ static void caps(void) { uint32_t l = p2.properties.limits.maxVertexOutputComponents / 4; g_max_loc = l < 1 ? 1 : l > 32 ? 32 : l; VLOG("transform feedback: VK_EXT_transform_feedback, %u buffers of at most %llu bytes, stride at most %u, %u vertex output locations", g_max_bufs, (unsigned long long)g_max_size, g_max_stride, g_max_loc); } +static void caps(void) { pthread_once(&g_caps_once, caps_read); } +// The capture variant of library vertex shader s for layout lay, tried here so a draw only takes a variant whose modules will capture; NULL with the reason in err +static vka_shader *make_variant(vka_shader *s, const vka_tf_layout *lay, char *err, size_t errn) { + vka_shader *v = NULL; + if (vka_shader_is_variant(s) || (s->e->flags & DMSH_VK_F_SUBGROUP)) { snprintf(err, errn, "it is a variant already, or has subgroup operations"); return NULL; } + for (uint32_t b = 0; b < 4 && !err[0]; b++) if (lay->stride[b] && (b >= g_max_bufs || lay->stride[b] > g_max_stride)) + snprintf(err, errn, "buffer %u of stride %u is past the device's %u buffers of stride %u", b, lay->stride[b], g_max_bufs, g_max_stride); + size_t nb = 0, on = 0; uint32_t *w = err[0] ? NULL : vka_shader_memu_words(s, &nb, err, errn); // (the base module's words, as the library has them) + uint32_t *o = w ? vka_spv_xfb(w, nb / 4, lay, g_max_loc, &on, err, errn) : NULL; + int ok = o != NULL; free(w); free(o); + if (ok && (v = calloc(1, sizeof *v))) { + *v = *s; memset(v->mods, 0, sizeof v->mods); memset(v->frz, 0, sizeof v->frz); v->vin = v->fout = NULL; v->img = NULL; v->tex = NULL; v->gslink = NULL; + v->gs_claim = VK_NULL_HANDLE; v->memu_d = NULL; v->key = s->key ^ VKA_TF_KEY_XOR; + } else if (ok) snprintf(err, errn, "no memory"); + return v; +} +// A variant made ahead (learned), at its first use by a draw (the replay thread): kept when this run's program noted the layout it was made with, else dead (its +// pipelines are never used again) and the draw makes its own as before +static int learned_holds(int i) { + vka_tf_layout lay; int st = 0; + pthread_mutex_lock(&g_mu); + for (int j = 0; j < g_nlay; j++) if (g_lay[j].key == g_var[i].s->key) { st = g_lay[j].st; lay = g_lay[j].L; break; } + int ok = st == 1 && !memcmp(&lay, &g_var[i].L, sizeof lay); + if (ok) g_var[i].checked = 1; else g_var[i].dead = 1; + pthread_mutex_unlock(&g_mu); + if (ok) VLOG("transform feedback: vertex shader %016llx draws with the capture variant Smoother next start made ahead", (unsigned long long)g_var[i].s->key); + else VRED("transform feedback: vertex shader %016llx's capture variant made ahead has another layout than this run's program notes (or none): made again", (unsigned long long)g_var[i].s->key); + return ok; +} // The capture variant of vertex shader s and its layout; NULL = it cannot capture (logged when first asked) static vka_shader *variant(vka_shader *s, const vka_tf_layout **L) { int nv = atomic_load(&g_nvar); - for (int i = 0; i < nv; i++) if (g_var[i].s == s) { *L = &g_var[i].L; return g_var[i].v; } + for (int i = 0; i < nv; i++) if (g_var[i].s == s && !g_var[i].dead) { + if (g_var[i].learned && !g_var[i].checked && !learned_holds(i)) continue; + *L = &g_var[i].L; return g_var[i].v; + } if (nv == NVAR) { VRED_ONCE("transform feedback: more than %d capturing vertex shaders: the rest are not captured", NVAR); return NULL; } caps(); vka_shader *v = NULL; vka_tf_layout lay = {0}; int st = 0; char err[256] = ""; // (lay is kept with a refused shader too: never left unset) @@ -63,36 +97,62 @@ static vka_shader *variant(vka_shader *s, const vka_tf_layout **L) { pthread_mutex_unlock(&g_mu); if (!st) snprintf(err, sizeof err, "no capture layout was noted for it (its control section declares none, or its program came from a capture file)"); else if (st < 0) snprintf(err, sizeof err, "its control section's capture layout has a form not known"); - else if (vka_shader_is_variant(s) || (s->e->flags & DMSH_VK_F_SUBGROUP)) snprintf(err, sizeof err, "it is a variant already, or has subgroup operations"); - else { - for (uint32_t b = 0; b < 4 && !err[0]; b++) if (lay.stride[b] && (b >= g_max_bufs || lay.stride[b] > g_max_stride)) - snprintf(err, sizeof err, "buffer %u of stride %u is past the device's %u buffers of stride %u", b, lay.stride[b], g_max_bufs, g_max_stride); - size_t nb = 0, on = 0; uint32_t *w = err[0] ? NULL : vka_shader_memu_words(s, &nb, err, sizeof err); // (the base module's words, as the library has them) - uint32_t *o = w ? vka_spv_xfb(w, nb / 4, &lay, g_max_loc, &on, err, sizeof err) : NULL; // tried here, so a draw only takes a variant whose modules will capture - int ok = o != NULL; free(w); free(o); - if (ok && (v = calloc(1, sizeof *v))) { - *v = *s; memset(v->mods, 0, sizeof v->mods); memset(v->frz, 0, sizeof v->frz); v->vin = v->fout = NULL; v->img = NULL; v->tex = NULL; v->gslink = NULL; - v->gs_claim = VK_NULL_HANDLE; v->memu_d = NULL; v->key = s->key ^ VKA_TF_KEY_XOR; - } else if (ok) snprintf(err, sizeof err, "no memory"); - } + else v = make_variant(s, &lay, err, sizeof err); if (v) VLOG("transform feedback: vertex shader %016llx captures %u + %u + %u + %u outputs into buffers of stride %u / %u / %u / %u", (unsigned long long)s->key, lay.n[0], lay.n[1], lay.n[2], lay.n[3], lay.stride[0], lay.stride[1], lay.stride[2], lay.stride[3]); else VRED("transform feedback: vertex shader %016llx is not captured: %s", (unsigned long long)s->key, err); pthread_mutex_lock(&g_mu); - g_var[nv].s = s; g_var[nv].v = v; g_var[nv].L = lay; atomic_store(&g_nvar, nv + 1); + int k = atomic_load(&g_nvar); // (a prewarm thread may have added entries meanwhile: one for s is dead, this run's layout is the one) + for (int i = nv; i < k; i++) if (g_var[i].s == s) g_var[i].dead = 1; + if (k == NVAR) { pthread_mutex_unlock(&g_mu); free(v); VRED_ONCE("transform feedback: more than %d capturing vertex shaders: the rest are not captured", NVAR); return NULL; } + g_var[k].s = s; g_var[k].v = v; g_var[k].L = lay; g_var[k].learned = g_var[k].checked = g_var[k].dead = 0; atomic_store(&g_nvar, k + 1); pthread_mutex_unlock(&g_mu); - *L = &g_var[nv].L; + *L = &g_var[k].L; return v; } void vka_tf_prep(uint64_t key, uint32_t **w, size_t *nb) { int nv = atomic_load(&g_nvar), i = 0; if (!nv) return; // (no capture variant was made: every game without transform feedback) - while (i < nv && !(g_var[i].v && g_var[i].v->key == key)) i++; + vka_tf_layout L = {0}; + pthread_mutex_lock(&g_mu); // (a variant's entry can turn dead: vka_tf_learned, learned_holds) + while (i < nv && !(g_var[i].v && g_var[i].v->key == key && !g_var[i].dead)) i++; + if (i < nv) L = g_var[i].L; + pthread_mutex_unlock(&g_mu); if (i == nv) return; - size_t on = 0; char err[256]; uint32_t *o = vka_spv_xfb(*w, *nb / 4, &g_var[i].L, g_max_loc, &on, err, sizeof err); + caps(); + size_t on = 0; char err[256]; uint32_t *o = vka_spv_xfb(*w, *nb / 4, &L, g_max_loc, &on, err, sizeof err); if (!o) { VRED("transform feedback: module of vertex shader %016llx not made to capture: %s", (unsigned long long)(key ^ VKA_TF_KEY_XOR), err); return; } // (it was, when the variant was made) free(*w); *w = o; *nb = on * 4; } +// Smoother next start (vka_pso.c sw_tf_*): whether v is a capture variant, the layout it was made with (pw_note: what the next start needs to make it ahead), and a +// variant made ahead on a prewarm thread with the layout an earlier run noted, the same checks as a draw's (NULL: refused, the reason logged for the first few) +int vka_tf_is_variant(const vka_shader *v) { return v && v->e && !v->inst_bind && v->key == (v->e->key ^ VKA_TF_KEY_XOR); } +int vka_tf_layout_of(const vka_shader *v, vka_tf_layout *L) { + int nv = atomic_load(&g_nvar), ok = 0; + pthread_mutex_lock(&g_mu); + for (int i = 0; i < nv && !ok; i++) if (g_var[i].v == v) { *L = g_var[i].L; ok = 1; } + pthread_mutex_unlock(&g_mu); + return ok; +} +vka_shader *vka_tf_learned(vka_shader *s, const vka_tf_layout *lay) { + if (!V.xfb || !s || !s->e) return NULL; + vka_shader *v = NULL, *r = NULL; int known = 0; + pthread_mutex_lock(&g_mu); + int nv = atomic_load(&g_nvar); + for (int i = 0; i < nv && !known; i++) if (g_var[i].s == s && !g_var[i].dead) { known = 1; r = g_var[i].v && !memcmp(&g_var[i].L, lay, sizeof *lay) ? g_var[i].v : NULL; } + pthread_mutex_unlock(&g_mu); + if (known) return r; + caps(); + char err[256] = ""; v = make_variant(s, lay, err, sizeof err); + if (!v) { static _Atomic int n; if (atomic_fetch_add(&n, 1) < 8) VLOG("Smoother next start: the capture variant of vertex shader %016llx is not made ahead: %s", (unsigned long long)s->key, err); return NULL; } + pthread_mutex_lock(&g_mu); + nv = atomic_load(&g_nvar); + for (int i = 0; i < nv && !known; i++) if (g_var[i].s == s && !g_var[i].dead) { known = 1; r = g_var[i].v && !memcmp(&g_var[i].L, lay, sizeof *lay) ? g_var[i].v : NULL; } + if (!known && nv < NVAR) { g_var[nv].s = s; g_var[nv].v = v; g_var[nv].L = *lay; g_var[nv].learned = 1; g_var[nv].checked = g_var[nv].dead = 0; atomic_store(&g_nvar, nv + 1); r = v; v = NULL; } + pthread_mutex_unlock(&g_mu); + free(v); + return r; +} // ---------- Staging memory: what a pass's draws capture, until the pass ends ---------- enum { NCHUNK = 16, NPEND = 64 }; diff --git a/dm/gfx/vk_android/vka_tf.h b/dm/gfx/vk_android/vka_tf.h index e58fae5b5..a20171860 100644 --- a/dm/gfx/vk_android/vka_tf.h +++ b/dm/gfx/vk_android/vka_tf.h @@ -26,4 +26,9 @@ void vka_tf_end(VkCommandBuffer cb); // after the draw call void vka_tf_flush(VkCommandBuffer cb); // vka_rp_end, outside the pass: what the pass's draws captured is copied into the game's buffers void vka_tf_state(const p_tf_state *s, VkCommandBuffer cb); // vka_exec.c at OP_TF_STATE (the replayed one, not a look-ahead) void vka_tf_prep(uint64_t key, uint32_t **w, size_t *nb); // vka_shader.c prep_words: a capture variant's words made to capture +// Smoother next start (vka_pso.c sw_tf_*, learning on): whether v is a capture variant; the layout capture variant v was made with (0: none); the capture variant of +// library vertex shader s made ahead on a prewarm thread with layout L an earlier run noted (NULL: refused; a draw's first use of it checks this run's layout) +int vka_tf_is_variant(const vka_shader *v); +int vka_tf_layout_of(const vka_shader *v, vka_tf_layout *L); +vka_shader *vka_tf_learned(vka_shader *s, const vka_tf_layout *L); #endif diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile index 4fcc69431..a80d17571 100644 --- a/dm/host/tests/Makefile +++ b/dm/host/tests/Makefile @@ -795,4 +795,20 @@ peanuts-audren-svc: $(B)/t_peanuts_audren_svc peanuts-host: peanuts-audren-svc $(B)/t_peanuts_audren_svc: t_peanuts_audren_svc.c ../hle_audren_svc.c ../hle_sf.c ../hle.h ../dm.h $(GAME_H) | $(B) $(CLANG) -O1 -g -Wall -Wno-unused-function -fsanitize=address,undefined $(PN_ASIF) -D_GNU_SOURCE -I.. $(GINC) -o $@ t_peanuts_audren_svc.c -lpthread -lm +# t_peanuts_swhot: Smoother next start's file of the pipelines a game's runs used (dm/peanuts/peanuts_swhot.h, vka_pso.c sw_*): the set, the file's check, the save's +# merge (this run first, the runs before by age, aged out, at most PN_SW_MAX) and the prewarm's order (the runs' records first, mesh records in front) +.PHONY: peanuts-swhot +peanuts-swhot: $(B)/t_peanuts_swhot + $(B)/t_peanuts_swhot +peanuts-host: peanuts-swhot +$(B)/t_peanuts_swhot: t_peanuts_swhot.c ../../peanuts/peanuts_swhot.h | $(B) + $(CLANG) -std=c11 -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined -o $@ t_peanuts_swhot.c +# t_peanuts_swtf: its file of the transform feedback capture pipelines (dm/peanuts/peanuts_swtf.h, vka_pso.c sw_tf_*): an entry's check, the file's, the run's table +# and the save's choice (the entries the .hot file keeps) +.PHONY: peanuts-swtf +peanuts-swtf: $(B)/t_peanuts_swtf + $(B)/t_peanuts_swtf +peanuts-host: peanuts-swtf +$(B)/t_peanuts_swtf: t_peanuts_swtf.c ../../peanuts/peanuts_swtf.h ../../peanuts/peanuts_swhot.h $(VKA)/vka_pwlist.h $(VKA)/vka_gkey.h $(VKA)/vka_tf.h | $(B) + $(CLANG) -std=c11 -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined -o $@ t_peanuts_swtf.c # PEANUTS end diff --git a/dm/host/tests/t_peanuts_swhot.c b/dm/host/tests/t_peanuts_swhot.c new file mode 100644 index 000000000..522618047 --- /dev/null +++ b/dm/host/tests/t_peanuts_swhot.c @@ -0,0 +1,94 @@ +// PEANUTS: Smoother next start's file of the pipelines a game's runs used (dm/peanuts/peanuts_swhot.h, vka_pso.c sw_*): the set, the file's check, the save's merge (this run first, +// the runs before by age, aged out after PN_SW_AGE_MAX runs, at most PN_SW_MAX) and the prewarm's order (the hot records first in their part, mesh records in front) +#include +#include +#include +#include "../../peanuts/peanuts_swhot.h" + +static int fails; +#define CHECK(c) do { if (!(c)) { fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } } while (0) + +static size_t file(uint8_t *buf, uint32_t layout, const pn_sw_ent *e, uint32_t n) { + pn_sw_hdr h; memset(&h, 0, sizeof h); memcpy(h.magic, PN_SW_MAGIC, 8); h.n = n; h.layout = layout; h.lib = 0x1234; + memcpy(buf, &h, sizeof h); if (n) memcpy(buf + sizeof h, e, n * sizeof *e); + return sizeof h + n * sizeof *e; +} + +static int has_ent(const pn_sw_ent *e, size_t n, uint64_t h, int age) { + for (size_t i = 0; i < n; i++) if (e[i].h == (h | 1) && e[i].age == age) return 1; + return 0; +} + +int main(void) { + // the set: added once, found with or without bit 0, grown past its first size + uint64_t *set = NULL; size_t cap = 0, n = 0; + CHECK(pn_sw_set_add(&set, &cap, &n, 0x10) == 1); + CHECK(pn_sw_set_add(&set, &cap, &n, 0x11) == 0); // the same hash with bit 0 set: 0 is an empty slot, every hash is stored with bit 0 + CHECK(pn_sw_set_has(set, cap, 0x10) && pn_sw_set_has(set, cap, 0x11) && !pn_sw_set_has(set, cap, 0x20)); + for (uint64_t i = 1; i <= 5000; i++) pn_sw_set_add(&set, &cap, &n, i * 0x9E3779B97F4A7C15ull); + CHECK(n == 5001 && cap >= 2 * n); + for (uint64_t i = 1; i <= 5000; i++) CHECK(pn_sw_set_has(set, cap, i * 0x9E3779B97F4A7C15ull)); + CHECK(!pn_sw_set_has(NULL, 0, 1)); + free(set); + + // the file: read back; another form, layout, length, a damaged entry or one too many is not used + static uint8_t buf[sizeof(pn_sw_hdr) + (PN_SW_MAX + 2) * sizeof(pn_sw_ent)]; + pn_sw_ent e3[3] = {{.h = 0x101}, {.h = 0x203, .age = 2}, {.h = 0x305, .age = 7}}; + size_t len = file(buf, 77, e3, 3); + pn_sw_ent *got; size_t gn; uint64_t lib; + CHECK(pn_sw_parse(buf, len, 77, &got, &gn, &lib) == NULL && gn == 3 && lib == 0x1234 && got && got[1].h == 0x203 && got[1].age == 2); + free(got); + CHECK(pn_sw_parse(buf, len, 78, &got, &gn, &lib) != NULL && !got && gn == 0); // another list layout: its hashes name no record + CHECK(pn_sw_parse(buf, len - 1, 77, &got, &gn, &lib) != NULL && gn == 0); // short + CHECK(pn_sw_parse(buf, len + 16, 77, &got, &gn, &lib) != NULL && gn == 0); // longer than its count + CHECK(pn_sw_parse(buf, 10, 77, &got, &gn, &lib) != NULL && pn_sw_parse(NULL, 0, 77, &got, &gn, &lib) != NULL); + buf[0] = 'X'; CHECK(pn_sw_parse(buf, len, 77, &got, &gn, &lib) != NULL); buf[0] = 'P'; + e3[2].h = 0x304; len = file(buf, 77, e3, 3); CHECK(pn_sw_parse(buf, len, 77, &got, &gn, &lib) != NULL && !got); // an entry without bit 0: damaged + { pn_sw_hdr h; memcpy(&h, buf, sizeof h); h.n = PN_SW_MAX + 1; memcpy(buf, &h, sizeof h); CHECK(pn_sw_parse(buf, sizeof h + (PN_SW_MAX + 1) * sizeof(pn_sw_ent), 77, &got, &gn, &lib) != NULL); } + len = file(buf, 77, NULL, 0); CHECK(pn_sw_parse(buf, len, 77, &got, &gn, &lib) == NULL && gn == 0 && !got); // an empty file of this form + + // the merge: this run's (age 0) first, the runs before's it did not use a run older, the youngest first; past PN_SW_AGE_MAX gone + uint64_t *run = NULL; size_t rcap = 0, rn = 0; + pn_sw_set_add(&run, &rcap, &rn, 0xA1); pn_sw_set_add(&run, &rcap, &rn, 0x203); // 0x203: used again this run + pn_sw_ent old[4] = {{.h = 0x203, .age = 3}, {.h = 0x305, .age = PN_SW_AGE_MAX - 1}, {.h = 0x407, .age = PN_SW_AGE_MAX}, {.h = 0x509, .age = 0}}; + pn_sw_ent out[16]; + size_t m = pn_sw_merge(run, rcap, old, 4, out, 16, PN_SW_AGE_MAX); + CHECK(m == 4); + CHECK(out[0].age == 0 && out[1].age == 0); // this run's first + CHECK(has_ent(out, m, 0xA1, 0) && has_ent(out, m, 0x203, 0)); // used again: young again + CHECK(has_ent(out, m, 0x509, 1)); // a run older + CHECK(has_ent(out, m, 0x305, PN_SW_AGE_MAX)); // the last run it is kept + CHECK(!has_ent(out, m, 0x407, PN_SW_AGE_MAX) && !has_ent(out, m, 0x407, PN_SW_AGE_MAX + 1)); // unused for PN_SW_AGE_MAX runs: gone + CHECK(out[2].h == 0x509 && out[3].h == 0x305); // the youngest of the runs before first + // the cap: the oldest go first + m = pn_sw_merge(run, rcap, old, 4, out, 3, PN_SW_AGE_MAX); + CHECK(m == 3 && has_ent(out, m, 0x509, 1) && !has_ent(out, m, 0x305, PN_SW_AGE_MAX)); + // a run with nothing used: everything a run older + m = pn_sw_merge(NULL, 0, old, 4, out, 16, PN_SW_AGE_MAX); + CHECK(m == 3 && has_ent(out, m, 0x203, 4) && has_ent(out, m, 0x509, 1)); + // the bound over many runs: a run of PN_SW_MAX new records leaves none of the runs before + uint64_t *big = NULL; size_t bcap = 0, bn = 0; + for (uint64_t i = 1; i <= PN_SW_MAX; i++) pn_sw_set_add(&big, &bcap, &bn, i << 8); + static pn_sw_ent bout[PN_SW_MAX]; + m = pn_sw_merge(big, bcap, old, 4, bout, PN_SW_MAX, PN_SW_AGE_MAX); + CHECK(m == PN_SW_MAX); + for (size_t i = 0; i < m; i++) CHECK(bout[i].age == 0); + free(big); free(run); + + // the order: 3 mesh records then 5 others; hot ones first in each part, the list's order kept; with only, the hot ones alone + uint8_t hot[8] = {0, 1, 0, 1, 0, 0, 1, 1}; uint32_t order[8], hn, nm = 3; uint8_t mark[8]; + uint32_t k = pn_sw_order(hot, 8, &nm, 0, order, mark, &hn); + uint32_t want[8] = {1, 0, 2, 3, 6, 7, 4, 5}; uint8_t wmark[8] = {1, 0, 0, 1, 1, 1, 0, 0}; + CHECK(k == 8 && nm == 3 && hn == 4 && !memcmp(order, want, sizeof want) && !memcmp(mark, wmark, sizeof wmark)); + nm = 3; k = pn_sw_order(hot, 8, &nm, 1, order, mark, &hn); + uint32_t want1[4] = {1, 3, 6, 7}; + CHECK(k == 4 && nm == 1 && hn == 4 && !memcmp(order, want1, sizeof want1) && mark[0] && mark[1] && mark[2] && mark[3]); + uint8_t none[4] = {0}; nm = 0; k = pn_sw_order(none, 4, &nm, 1, order, mark, &hn); + CHECK(k == 0 && hn == 0 && nm == 0); // nothing the runs before used: a driver that does not prewarm makes nothing + nm = 9; k = pn_sw_order(hot, 8, &nm, 0, order, mark, &hn); // a mesh count past the list: every record is a mesh one + CHECK(k == 8 && nm == 8 && hn == 4); + + if (fails) { fprintf(stderr, "%d failed\n", fails); return 1; } + printf("t_peanuts_swhot: ok\n"); + return 0; +} diff --git a/dm/host/tests/t_peanuts_swtf.c b/dm/host/tests/t_peanuts_swtf.c new file mode 100644 index 000000000..a9b7f2dbf --- /dev/null +++ b/dm/host/tests/t_peanuts_swtf.c @@ -0,0 +1,91 @@ +// PEANUTS: Smoother next start's file of the transform feedback capture pipelines a game's runs made (dm/peanuts/peanuts_swtf.h, vka_pso.c sw_tf_*): an entry's check +// (a record the prewarm may take, its own hash, a layout of vka_tf_layout_read's form), the file's check (damaged entries skipped, another form or layout not used), the +// run's table (once each, at most PN_SWTF_MAX) and the save's choice (the entries the .hot file keeps: this run's first, then the runs before's) +#include +#include +#include +#include "../../peanuts/peanuts_swtf.h" + +static int fails; +#define CHECK(c) do { if (!(c)) { fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } } while (0) + +// A capture pipeline's entry: vertex shader vs, pixel shader fs, one buffer of two outputs (Location 0, 4 components; Location 3, 2 components: 24 bytes a vertex) +static pn_swtf_ent ent(uint64_t vs, uint64_t fs) { + pn_swtf_ent e; memset(&e, 0, sizeof e); + e.r.kind = VKA_PW_GFX; e.r.key[0] = vs; e.r.key[1] = fs; e.r.klen = (uint32_t)offsetof(vka_gkey, va); + e.k.ncolor = 1; e.k.samples = 1; e.k.topo = 3; + e.L.stride[0] = 24; e.L.n[0] = 2; e.L.loc[0][0] = 0; e.L.comp[0][0] = 4; e.L.loc[0][1] = 3; e.L.comp[0][1] = 2; + e.h = pn_swtf_hash(&e.r, &e.k); + return e; +} +static size_t file(uint8_t *buf, uint32_t layout, const pn_swtf_ent *e, uint32_t n) { + pn_swtf_hdr h; memset(&h, 0, sizeof h); memcpy(h.magic, PN_SWTF_MAGIC, 8); h.n = n; h.layout = layout; h.ent_size = sizeof(pn_swtf_ent); + memcpy(buf, &h, sizeof h); if (n) memcpy(buf + sizeof h, e, n * sizeof *e); + return sizeof h + n * sizeof *e; +} + +int main(void) { + // an entry's hash: bit 0 set, never a list record's own (the .hot file holds both) + pn_swtf_ent a = ent(0x1111, 0x2222), b = ent(0x3333, 0x2222), c = ent(0x5555, 0x6666); + CHECK((a.h & 1) && a.h != b.h && a.h != (vka_pw_hash(&a.r, &a.k) | 1)); + CHECK(pn_swtf_ok(&a) && pn_swtf_ok(&b) && pn_swtf_ok(&c)); + + // what may not reach the prewarm + pn_swtf_ent x = a; x.h ^= 2; CHECK(!pn_swtf_ok(&x)); // a hash that is not its own + x = a; x.r.inst[0] = 1; x.h = pn_swtf_hash(&x.r, &x.k); CHECK(!pn_swtf_ok(&x)); // instanced (a capture is drawn alone) + x = a; x.r.kind = VKA_PW_CS; x.r.klen = 0; memset(&x.k, 0, sizeof x.k); x.h = pn_swtf_hash(&x.r, &x.k); CHECK(!pn_swtf_ok(&x)); // not a vertex pipeline + x = a; x.k.ncolor = 200; x.h = pn_swtf_hash(&x.r, &x.k); CHECK(!pn_swtf_ok(&x)); // a key vka_pw_rec_ok refuses + x = a; ((uint8_t *)&x.k)[sizeof x.k - 1] = 1; CHECK(!pn_swtf_ok(&x)); // bytes past klen + x = a; x.L.stride[0] = 28; CHECK(!pn_swtf_ok(&x)); // a stride its outputs do not make + x = a; x.L.comp[0][1] = 5; x.L.stride[0] = 36; CHECK(!pn_swtf_ok(&x)); // five components + x = a; x.L.loc[0][1] = 32; CHECK(!pn_swtf_ok(&x)); // past the generic outputs + x = a; x.L.n[1] = 1; CHECK(!pn_swtf_ok(&x)); // outputs in a buffer with no stride + x = a; x.L.n[0] = VKA_TF_OUTS + 1; CHECK(!pn_swtf_ok(&x)); + x = a; memset(&x.L, 0, sizeof x.L); CHECK(!pn_swtf_ok(&x)); // nothing captured + + // the file: read back; a damaged entry skipped and the others kept; another form, layout, entry size or length, or too many entries, not used + static uint8_t buf[sizeof(pn_swtf_hdr) + (PN_SWTF_MAX + 2) * sizeof(pn_swtf_ent)]; + pn_swtf_ent three[3] = {a, b, c}; + size_t len = file(buf, 77, three, 3); + pn_swtf_ent *got; size_t gn, skipped; + CHECK(pn_swtf_parse(buf, len, 77, &got, &gn, &skipped) == NULL && gn == 3 && !skipped && got && got[2].h == c.h && !memcmp(&got[0].L, &a.L, sizeof a.L)); + free(got); + three[1].L.stride[0] = 4; // damaged + len = file(buf, 77, three, 3); + CHECK(pn_swtf_parse(buf, len, 77, &got, &gn, &skipped) == NULL && gn == 2 && skipped == 1 && got[0].h == a.h && got[1].h == c.h); + free(got); + CHECK(pn_swtf_parse(buf, len, 78, &got, &gn, &skipped) != NULL && !got && !gn); // another list layout + CHECK(pn_swtf_parse(buf, len - 1, 77, &got, &gn, &skipped) != NULL && !got); // short + CHECK(pn_swtf_parse(buf, 10, 77, &got, &gn, &skipped) != NULL && !got); + CHECK(pn_swtf_parse(NULL, 0, 77, &got, &gn, &skipped) != NULL && !got); + buf[0] ^= 1; CHECK(pn_swtf_parse(buf, len, 77, &got, &gn, &skipped) != NULL && !got); buf[0] ^= 1; + { pn_swtf_hdr h; memcpy(&h, buf, sizeof h); h.ent_size += 8; memcpy(buf, &h, sizeof h); CHECK(pn_swtf_parse(buf, len, 77, &got, &gn, &skipped) != NULL && !got); } + { static pn_swtf_ent many[PN_SWTF_MAX + 1]; for (int i = 0; i <= PN_SWTF_MAX; i++) many[i] = ent(0x100 + (uint64_t)i, 0x2222); + len = file(buf, 77, many, PN_SWTF_MAX + 1); CHECK(pn_swtf_parse(buf, len, 77, &got, &gn, &skipped) != NULL && !got); + len = file(buf, 77, many, PN_SWTF_MAX); CHECK(pn_swtf_parse(buf, len, 77, &got, &gn, &skipped) == NULL && gn == PN_SWTF_MAX); free(got); } + len = file(buf, 77, NULL, 0); + CHECK(pn_swtf_parse(buf, len, 77, &got, &gn, &skipped) == NULL && !got && !gn); + + // the run's table: each once, at most PN_SWTF_MAX + pn_swtf_ent *run = NULL; size_t rn = 0, rcap = 0; + CHECK(pn_swtf_add(&run, &rn, &rcap, &a) == 1 && pn_swtf_add(&run, &rn, &rcap, &a) == 0 && rn == 1); + for (int i = 0; i < 2 * PN_SWTF_MAX; i++) { pn_swtf_ent e = ent(0x9000 + (uint64_t)i, 0x2222); pn_swtf_add(&run, &rn, &rcap, &e); } + CHECK(rn == PN_SWTF_MAX && run[0].h == a.h); + free(run); + + // the save: the entries the .hot file keeps, this run's first, then the runs before's, each once; one the .hot file aged out is dropped + pn_swtf_ent mine[2] = {b, a}, before[2] = {a, c}; + pn_sw_ent keep[3]; memset(keep, 0, sizeof keep); keep[0].h = a.h; keep[1].h = b.h; keep[2].h = 0x77 | 1; + pn_swtf_ent out[PN_SWTF_MAX]; + size_t n = pn_swtf_keep(mine, 2, before, 2, keep, 3, out, PN_SWTF_MAX); + CHECK(n == 2 && out[0].h == b.h && out[1].h == a.h); // c aged out + keep[2].h = c.h; + n = pn_swtf_keep(mine, 2, before, 2, keep, 3, out, PN_SWTF_MAX); + CHECK(n == 3 && out[2].h == c.h); + CHECK(pn_swtf_keep(mine, 2, before, 2, keep, 3, out, 1) == 1 && out[0].h == b.h); // at most max + CHECK(pn_swtf_keep(NULL, 0, before, 2, NULL, 0, out, PN_SWTF_MAX) == 0); // learning on, nothing kept: none + + if (fails) { fprintf(stderr, "%d checks failed\n", fails); return 1; } + printf("t_peanuts_swtf: ok\n"); + return 0; +} diff --git a/dm/peanuts/peanuts_shaderwatch.c b/dm/peanuts/peanuts_shaderwatch.c new file mode 100644 index 000000000..dbbeedd81 --- /dev/null +++ b/dm/peanuts/peanuts_shaderwatch.c @@ -0,0 +1,46 @@ +// Smoother next start (the quick menu's Peanuts tab, dev.peanuts.shaders.ShaderWatch): the host's prewarm list as the tab shows it. +// +// The Vulkan replay learns while a game runs: every pipeline it makes on the frame path or in the background goes into the game's prewarm list +// (DM_TEMP/vk_pipelines.keys, dm/gfx/vk_android/vka_pso.c pw_note), and the next start makes the list ahead of the game (pw_start, the startup prewarm behind +// "Preparing shaders"). With learning on for the game (PN_SHADERWATCH=1, the tab's switch) each run also keeps the pipelines it used, and the next start makes those +// first and before the game starts, also on a driver that does not prewarm the list (vka_pso.c sw_*). vka_pso_watch counts what this run learned and what the next +// start makes ahead on this driver; this file hands that to dev.peanuts.Bridge.shaderWatch for dev.peanuts.shaders.HostWatch, the backend the tab reads, and the +// switch to vka_pso_watch_learn. +#include + +// dm/gfx/vk_android/vka_pso.c (PEANUTS): weak, so a host without the Vulkan replay (the Mac's unit tests) links and answers "not known" +void vka_pso_watch(int out[4]) __attribute__((weak)); +void vka_pso_watch_learn(int on) __attribute__((weak)); + +// out[0] the list (1 kept, 0 none, -1 not read yet), out[1] pipelines learned this run, out[2] made ahead at the next start on this driver, out[3] its records +int pn_shaderwatch(int out[4]) { + if (!vka_pso_watch) { out[0] = -1; out[1] = out[2] = out[3] = 0; return 0; } + vka_pso_watch(out); + return 1; +} + +// Learning turned on or off while the game runs (the start reads PN_SHADERWATCH): 0 when this host cannot +int pn_shaderwatch_learn(int on) { + if (!vka_pso_watch_learn) return 0; + vka_pso_watch_learn(on); + return 1; +} + +#if defined(__ANDROID__) +#include +// dev.peanuts.Bridge.shaderWatch(int[] out): false when this host has no prewarm list to report (out untouched) +JNIEXPORT jboolean JNICALL Java_dev_peanuts_Bridge_shaderWatch(JNIEnv *env, jclass cls, jintArray out) { + (void)cls; + if (!out || (*env)->GetArrayLength(env, out) < 4) return JNI_FALSE; + int v[4]; + if (!pn_shaderwatch(v)) return JNI_FALSE; + jint j[4] = {v[0], v[1], v[2], v[3]}; + (*env)->SetIntArrayRegion(env, out, 0, 4, j); + return JNI_TRUE; +} +// dev.peanuts.Bridge.shaderWatchLearn(boolean on): false when this host cannot +JNIEXPORT jboolean JNICALL Java_dev_peanuts_Bridge_shaderWatchLearn(JNIEnv *env, jclass cls, jboolean on) { + (void)env; (void)cls; + return pn_shaderwatch_learn(on ? 1 : 0) ? JNI_TRUE : JNI_FALSE; +} +#endif diff --git a/dm/peanuts/peanuts_swhot.h b/dm/peanuts/peanuts_swhot.h new file mode 100644 index 000000000..3cca41d3e --- /dev/null +++ b/dm/peanuts/peanuts_swhot.h @@ -0,0 +1,87 @@ +// Smoother next start, learning on: the pipelines a game's runs used, as dm/gfx/vk_android/vka_pso.c (sw_*) keeps them per game and GPU driver beside the prewarm +// list (..hot). Free of Vulkan, so the Mac's and Linux's unit test (dm/host/tests/t_peanuts_swhot.c) checks it. +// +// An entry is a prewarm list record's hash (vka_pwlist.h vka_pw_hash, bit 0 set: 0 marks an empty slot) and the number of runs since a run last used it. A save writes +// this run's records first (0 runs), then the runs before's that this run did not use, a run older each, the youngest first; one unused for PN_SW_AGE_MAX runs is +// dropped, and at most PN_SW_MAX are kept (64 KB), so the oldest go first. A record a game update or another shader library no longer has, or another driver's, +// matches no record of the list: it is never made, and it ages out. +// file: pn_sw_hdr (magic PNSWHOT1, n, the list's layout fingerprint vka_pw_layout, the shader library it was saved with), then n pn_sw_ent +#ifndef PEANUTS_SWHOT_H +#define PEANUTS_SWHOT_H +#include +#include +#include + +#define PN_SW_MAX 4096 +#define PN_SW_AGE_MAX 8 +static const char PN_SW_MAGIC[8] = {'P', 'N', 'S', 'W', 'H', 'O', 'T', '1'}; +typedef struct { char magic[8]; uint32_t n, layout; uint64_t lib; } pn_sw_hdr; +typedef struct { uint64_t h; uint8_t age, pad[7]; } pn_sw_ent; +_Static_assert(sizeof(pn_sw_hdr) == 24 && sizeof(pn_sw_ent) == 16, "file records"); + +// A set of hashes (open addressing, a power of two slots, at most half full): 1 = added, 0 = there already (or no memory) +static inline int pn_sw_set_add(uint64_t **set, size_t *cap, size_t *n, uint64_t h) { + h |= 1; + if (2 * (*n + 1) > *cap) { + size_t nc = *cap ? 2 * *cap : 1024; uint64_t *t = (uint64_t *)calloc(nc, sizeof *t); if (!t) return 0; + for (size_t i = 0; i < *cap; i++) if ((*set)[i]) { size_t j = (*set)[i] & (nc - 1); while (t[j]) j = (j + 1) & (nc - 1); t[j] = (*set)[i]; } + free(*set); *set = t; *cap = nc; + } + size_t j = h & (*cap - 1); + for (; (*set)[j]; j = (j + 1) & (*cap - 1)) if ((*set)[j] == h) return 0; + (*set)[j] = h; (*n)++; + return 1; +} +static inline int pn_sw_set_has(const uint64_t *set, size_t cap, uint64_t h) { + if (!cap) return 0; + h |= 1; + for (size_t j = h & (cap - 1); set[j]; j = (j + 1) & (cap - 1)) if (set[j] == h) return 1; + return 0; +} + +// A file's bytes: NULL and *out (malloc'd, NULL when empty), *n, *lib; else why it is not used (*out NULL, *n 0) +static inline const char *pn_sw_parse(const uint8_t *d, size_t len, uint32_t layout, pn_sw_ent **out, size_t *n, uint64_t *lib) { + *out = NULL; *n = 0; *lib = 0; + pn_sw_hdr h; + if (!d || len < sizeof h) return "short"; + memcpy(&h, d, sizeof h); + if (memcmp(h.magic, PN_SW_MAGIC, 8)) return "not a file of this form"; + if (h.layout != layout) return "of another list layout (its hashes name no record of this one)"; + if (h.n > PN_SW_MAX) return "longer than it may be"; + if (len != sizeof h + (size_t)h.n * sizeof(pn_sw_ent)) return "short"; + if (h.n) { + pn_sw_ent *e = (pn_sw_ent *)malloc((size_t)h.n * sizeof *e); if (!e) return "no memory"; + memcpy(e, d + sizeof h, (size_t)h.n * sizeof *e); + for (uint32_t i = 0; i < h.n; i++) if (!(e[i].h & 1)) { free(e); return "damaged"; } + *out = e; + } + *n = h.n; *lib = h.lib; + return NULL; +} + +// The entries a save writes: run, a set of runcap slots (this run's records), then old (the runs before's) by age, the youngest first, each a run older, none the run +// used again nor any past agemax; at most max. out holds max entries. Returns their count +static inline size_t pn_sw_merge(const uint64_t *run, size_t runcap, const pn_sw_ent *old, size_t oldn, pn_sw_ent *out, size_t max, unsigned agemax) { + size_t n = 0; + for (size_t i = 0; i < runcap && n < max; i++) if (run[i]) { memset(&out[n], 0, sizeof out[n]); out[n].h = run[i]; n++; } + for (unsigned age = 0; age < agemax; age++) + for (size_t i = 0; i < oldn && n < max; i++) + if (old[i].age == age && !pn_sw_set_has(run, runcap, old[i].h)) { out[n] = old[i]; out[n].age = (uint8_t)(age + 1); n++; } + return n; +} + +// The prewarm's order (vka_pso.c pw_start): n records, the first nm of them mesh records (one thread takes those first); hot[i] = record i is one the runs before used. +// Writes order (the indices: in each of the two parts the hot ones first, the list's order kept; with only, the hot ones alone) and mark (1 where order holds a hot one), +// moves *nm to the mesh part's new size. Returns the new count; *hot_n the hot ones +static inline uint32_t pn_sw_order(const uint8_t *hot, uint32_t n, uint32_t *nm, int only, uint32_t *order, uint8_t *mark, uint32_t *hot_n) { + uint32_t o = 0, h = 0, m = *nm < n ? *nm : n; + for (int part = 0; part < 2; part++) { + uint32_t a = part ? m : 0, b = part ? n : m; + for (uint32_t i = a; i < b; i++) if (hot[i]) { mark[o] = 1; order[o++] = i; h++; } + if (!only) for (uint32_t i = a; i < b; i++) if (!hot[i]) { mark[o] = 0; order[o++] = i; } + if (!part) *nm = o; + } + *hot_n = h; + return o; +} +#endif diff --git a/dm/peanuts/peanuts_swtf.h b/dm/peanuts/peanuts_swtf.h new file mode 100644 index 000000000..67868ef20 --- /dev/null +++ b/dm/peanuts/peanuts_swtf.h @@ -0,0 +1,92 @@ +// Smoother next start, learning on: the transform feedback capture pipelines a game's runs made, as dm/gfx/vk_android/vka_pso.c (sw_tf_*) keeps them per game and GPU +// driver beside the prewarm list (..tf). Free of Vulkan, so the Mac's and Linux's unit test (dm/host/tests/t_peanuts_swtf.c) checks it. +// +// The prewarm list never holds them: a capture pipeline draws with its vertex shader's capture variant (dm/gfx/vk_android/vka_tf.c), whose modules carry the layout +// the game's program declares at nvnProgramSetShaders, and a start that makes pipelines ahead of the game has no layout noted yet. So an entry is the list record of the +// pipeline (vka_pwlist.h: key[0] the variant's base vertex shader, its key bytes, never instanced) with the capture layout it was made with, and its hash: the record's +// vka_pw_hash XOR PN_SWTF_SALT, which is also its entry in the .hot file (peanuts_swhot.h). A save keeps the entries whose hash the .hot file keeps, so they age out with +// it; at most PN_SWTF_MAX (about 84 KB). +// file: pn_swtf_hdr (magic PNSWTF01, n, the list's layout fingerprint vka_pw_layout, the entry's size), then n pn_swtf_ent +#ifndef PEANUTS_SWTF_H +#define PEANUTS_SWTF_H +#include +#include +#include +#include "../gfx/vk_android/vka_pwlist.h" +#include "../gfx/vk_android/vka_tf.h" +#include "peanuts_swhot.h" + +#define PN_SWTF_MAX 64 +#define PN_SWTF_SALT 0x46545753504e4950ull // a capture entry's hash: its record's vka_pw_hash XOR this (no record of the list has it) +static const char PN_SWTF_MAGIC[8] = {'P', 'N', 'S', 'W', 'T', 'F', '0', '1'}; +typedef struct { char magic[8]; uint32_t n, layout, ent_size, pad; } pn_swtf_hdr; +typedef struct { uint64_t h; pwrec r; vka_gkey k; vka_tf_layout L; uint8_t pad[4]; } pn_swtf_ent; // k: r.klen bytes, the rest 0 +_Static_assert(sizeof(pn_swtf_hdr) == 24 && sizeof(pn_swtf_ent) % 8 == 0, "file records"); + +static inline uint64_t pn_swtf_hash(const pwrec *r, const void *kb) { return (vka_pw_hash(r, kb) ^ PN_SWTF_SALT) | 1; } + +// An entry that may reach the prewarm: a vertex pipeline's record that passes vka_pw_rec_ok, not instanced, whose hash is its own, and a layout of the form +// vka_tf_layout_read gives (vka_tf_spv.c): a buffer with no stride has no outputs, one with a stride 1 to VKA_TF_OUTS outputs of 1-4 components at a Location +// below 32 whose bytes make the stride, and at least one buffer (vka_tf.c checks it against the device too) +static inline int pn_swtf_ok(const pn_swtf_ent *e) { + if (e->r.kind != VKA_PW_GFX || e->r.bad || e->r.inst[0] || e->r.inst[1] || e->r.klen > sizeof e->k) return 0; + if (!vka_pw_rec_ok(&e->r, (const uint8_t *)&e->k) || e->h != pn_swtf_hash(&e->r, &e->k)) return 0; + const uint8_t *k = (const uint8_t *)&e->k; + for (size_t i = e->r.klen; i < sizeof e->k; i++) if (k[i]) return 0; + int any = 0; + for (int b = 0; b < 4; b++) { + if (!e->L.stride[b]) { if (e->L.n[b]) return 0; continue; } + if (e->L.n[b] < 1 || e->L.n[b] > VKA_TF_OUTS) return 0; + unsigned sum = 0; + for (int i = 0; i < e->L.n[b]; i++) { if (e->L.loc[b][i] >= 32 || e->L.comp[b][i] < 1 || e->L.comp[b][i] > 4) return 0; sum += e->L.comp[b][i]; } + if (e->L.stride[b] != 4 * sum) return 0; + any = 1; + } + return any; +} + +// A file's bytes: NULL and *out (malloc'd, NULL when empty) with the entries that may reach the prewarm (*skipped the others); else why it is not used (*out NULL, *n 0) +static inline const char *pn_swtf_parse(const uint8_t *d, size_t len, uint32_t layout, pn_swtf_ent **out, size_t *n, size_t *skipped) { + *out = NULL; *n = 0; *skipped = 0; + pn_swtf_hdr h; + if (!d || len < sizeof h) return "short"; + memcpy(&h, d, sizeof h); + if (memcmp(h.magic, PN_SWTF_MAGIC, 8)) return "not a file of this form"; + if (h.layout != layout || h.ent_size != sizeof(pn_swtf_ent)) return "of another list layout (its records name no pipeline of this host)"; + if (h.n > PN_SWTF_MAX) return "longer than it may be"; + if (len != sizeof h + (size_t)h.n * sizeof(pn_swtf_ent)) return "short"; + if (!h.n) return NULL; + pn_swtf_ent *e = (pn_swtf_ent *)malloc((size_t)h.n * sizeof *e); if (!e) return "no memory"; + size_t k = 0; + for (uint32_t i = 0; i < h.n; i++) { memcpy(&e[k], d + sizeof h + (size_t)i * sizeof *e, sizeof *e); if (pn_swtf_ok(&e[k])) k++; else (*skipped)++; } + if (!k) { free(e); e = NULL; } + *out = e; *n = k; + return NULL; +} + +// One more entry for this run's table (*e of *n, *cap slots): 1 = added, 0 = one of its hash is there, the table is full (PN_SWTF_MAX) or there is no memory +static inline int pn_swtf_add(pn_swtf_ent **e, size_t *n, size_t *cap, const pn_swtf_ent *x) { + for (size_t i = 0; i < *n; i++) if ((*e)[i].h == x->h) return 0; + if (*n >= PN_SWTF_MAX) return 0; + if (*n == *cap) { size_t c = *cap ? 2 * *cap : 8; pn_swtf_ent *t = (pn_swtf_ent *)realloc(*e, c * sizeof *t); if (!t) return 0; *e = t; *cap = c; } + (*e)[(*n)++] = *x; + return 1; +} + +// The entries a save writes, into out (max entries): run's (this run's), then old's (the runs before's) that run does not hold, each only while keep (the entries the +// .hot file's save writes, kn of them) holds its hash, so an entry ages out with it. Returns their count +static inline size_t pn_swtf_keep(const pn_swtf_ent *run, size_t runn, const pn_swtf_ent *old, size_t oldn, const pn_sw_ent *keep, size_t kn, pn_swtf_ent *out, size_t max) { + uint64_t *set = NULL; size_t cap = 0, cnt = 0, n = 0; + for (size_t i = 0; i < kn; i++) pn_sw_set_add(&set, &cap, &cnt, keep[i].h); + for (int part = 0; part < 2; part++) { + const pn_swtf_ent *src = part ? old : run; size_t sn = part ? oldn : runn; + for (size_t i = 0; i < sn && n < max; i++) { + if (!pn_sw_set_has(set, cap, src[i].h)) continue; + size_t j = 0; while (j < n && out[j].h != src[i].h) j++; + if (j == n) out[n++] = src[i]; + } + } + free(set); + return n; +} +#endif diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index ccfe883b6..78c1c57ce 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -798,6 +798,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - (Android) mid-play the picture and the input stop for 3-4 s, then the game goes on acting on the stick held meanwhile; the log has `[vk] long compile: compute pipeline of shader 9e52219432f52a98 took 3.6 s` and a `[longframe]` line with `new pipelines 1 … 3668.4 ms in all`, `replay recording 3708.6 (its CPU 3603.5)` and the game waiting as long on GPU fences. → [A new compute pipeline stopped the frame for seconds on the Vulkan replay (Android)](../reference/rendering.md#a-new-compute-pipeline-stopped-the-frame-for-seconds-on-the-vulkan-replay-android) - (Android, Turnip Gen8 V39, Adreno 840) with background compiles at several slots (`background pipeline compiles: 4 at once`, then 3 and 2 as memory fell), Mario Kart World loses the device while it loads: `[RED] vk: GPU hang: a submission returned -4 (the device is lost)`, `submission N: -4 (its effects run without the GPU)`, at frames 484 and 416 of two runs. → [Concurrent background pipeline compiles lose the device on Turnip (Android)](../reference/rendering.md#concurrent-background-pipeline-compiles-lose-the-device-on-turnip-android) - (Android, Vulkan; PEANUTS, an entry of this fork; `DM_VK_PSO_ASYNC`, the launcher's default through Game settings › Background pipelines) on a game's first run, with no pipeline cache and no prewarm list yet (`vk_pipelines*.bin`, `vk_pipelines.keys`), the picture is black with only the HUD's text for the whole session: `[RED] vk: 7 % of draws skipped over the last 300 frames (causes: pipelines not made 11521)`, about 650 graphics pipelines made in the background over the first minute, and still black once none is waiting. Right with `DM_VK_PSO_ASYNC=0` (frame-time maxima of 127-267 ms while pipelines compile), and right on a later run with the cache present. → [A draw skipped for its pipeline left a result the game kept (Android)](../reference/rendering.md#a-draw-skipped-for-its-pipeline-left-a-result-the-game-kept-android) +- (Android, Qualcomm's own driver before 512.800, the AYN Thor's 512.676) every start of a game, with the pipeline cache warm too, skips thousands of draws for pipelines still being made (`draws skipped waiting` in the `pipelines up to frame` line: 2,300-2,700 in each of eight runs of about 40 s; geometry missing for a moment) and makes some on the frame path, while the log says `prewarm: off (default on Qualcomm's driver before 512.800 ...): N keys not made ahead`. The same game on Turnip makes its list ahead and skips none from its second start on. → [Pipelines made again while playing at every start (Android)](../reference/rendering.md#pipelines-made-again-while-playing-at-every-start-android) - (Android, Vulkan) `[RED] vk: shader binding : texture ID has no view of shape 0x1 (storage)` during compute passes that bind an RGBA8 storage image. → [Storage image views for textures with sRGB format lists on the Vulkan replay](../reference/rendering.md#storage-image-views-for-textures-with-srgb-format-lists-on-the-vulkan-replay) - (Android, Vulkan, a driver with graphics pipeline libraries: Turnip; PEANUTS, an entry of this fork) the build has translated every shader, yet whatever is drawn for the first time stutters, or with background pipelines (`DM_VK_PSO_ASYNC`, the launcher's default) is missing or black for a moment, and stays so where the game keeps what it drew. Super Mario Odyssey 1.4.1 on the AYN Thor (Turnip 26.2.0-R5), no pipeline cache and no prewarm (`DM_VK_PREWARM=0`), from the title screen through the opening cutscene (6,300 frames): 16,743 draws skipped waiting for 304 pipelines, the longest 2.3 s after its miss; 26 pipelines of small targets made on the frame path in 875 ms, the worst frame 957 ms. → [A program's first draw compiled or skipped: shader parts prepared before the game starts (Android)](../reference/rendering.md#a-programs-first-draw-compiled-or-skipped-shader-parts-prepared-before-the-game-starts-android) - (Android, Vulkan) compute passes that write the scene's HDR and UI targets do not run as the game asked. The log has `[RED] vk: shader binding : texture ID has no view of shape 0x81 (storage): it reads as unbound (… format 0x25 … view … format 0xb …)` (also for formats `0x40` and `0x14`), and `image VkFormat 122 (NVN 0x3f, 1024x576) asked for a view as VkFormat 98, which its format list does not have: viewed in its own format`. → [Shader-image views in another format of the same texel size on the Vulkan replay](../reference/rendering.md#shader-image-views-in-another-format-of-the-same-texel-size-on-the-vulkan-replay) diff --git a/docs/reference/rendering.md b/docs/reference/rendering.md index 1d11f4fc4..616a24ce2 100644 --- a/docs/reference/rendering.md +++ b/docs/reference/rendering.md @@ -1661,6 +1661,14 @@ On the Retroid Pocket Flip 2, PurpleVK T30 (`git-62ac221a33`) reports a 33.11 ns - **Cold startup (PEANUTS, 2026-11-18)** Android waits for the prewarm workers before entering the guest when a profile ships a seed and the driver cache starts empty. The launcher shows “Preparing shaders” with the number of processed pipeline keys. The workers save the cache before the game starts, and a later launch with a usable cache skips the progress screen. See the Thor measurements in [Captain Tsubasa 2](../../dm/games/01009720213B0000/README.md#shaders). - **Found on:** [Super Mario Odyssey](../../dm/games/0100000000010000/README.md) on an AYN Thor (Adreno 740, Turnip). + +### Pipelines made again while playing at every start (Android) + +- **Symptom:** (Android, Qualcomm's own driver before 512.800, the AYN Thor's 512.676) every start of a game, with the pipeline cache warm too, skips thousands of draws for pipelines still being made (`draws skipped waiting` in the `pipelines up to frame` line: 2,300-2,700 in each of eight runs of about 40 s; geometry missing for a moment) and makes some on the frame path, while the log says `prewarm: off (default on Qualcomm's driver before 512.800 ...): N keys not made ahead`. The same game on Turnip makes its list ahead and skips none from its second start on. +- **Cause:** the prewarm list (`vk_pipelines.keys`, [Pipelines made on the frame path on the Vulkan replay](#pipelines-made-on-the-frame-path-on-the-vulkan-replay)) is off by default on that driver: it keeps about 6 MB outside the process for each pipeline, so making the whole list ahead (every pipeline any run reached: 2,135 records for one game) ran games out of memory ([Fire Emblem Fortune's Weave](../../dm/games/04007EF01F8AE000/README.md)). Each start then makes what it draws again while it plays, from the pipeline cache (there 226 pipelines in 59 ms), and skips its draws until each one is there. +- **Fix:** Smoother next start, a switch for each game in the quick menu's Peanuts tab, off by default (`PN_SHADERWATCH=1`; `dev.peanuts.shaders.HostWatch`, `vka_pso.c` `sw_*`, `dm/peanuts/peanuts_swhot.h`). With it on, each run also keeps the list's records it used (made while it played, or made ahead and then drawn with) in a file of the game and the driver, `..hot`: their hashes and the runs since each was used, at most 4,096 entries (64 KB), an entry unused for 8 runs dropped, the oldest first past the cap. The next start makes those first and before the game starts, behind Preparing shaders, the rest of the list following in the background where the driver prewarms it; where it does not, only those, on two threads that stop when less than `DM_VK_PREWARM_MEM_MB` is available. An entry whose record is gone (a game update, another shader library) or of another driver matches no record and ages out. The list never holds a transform feedback capture pipeline (its vertex shader's capture variant carries the layout the game's program declares while it runs, `vka_tf.c`), so with the switch on each one made while playing is kept apart, with that layout, in `..tf` (`dm/peanuts/peanuts_swtf.h`: at most 64, each with an entry in the `.hot` file and aged out with it); the next start makes its variant (`vka_tf_learned`) and pipeline first, with the others it waits for, and a draw's first use checks that this run's program declares the same layout, else the draw makes its own as before. Off, no file is read or written and the list is upstream's. The tab's numbers are the list's (`vka_pso_watch`: the pipelines learned this run, those the next start makes ahead on this driver). +- **Found on:** [Tomodachi Life: Living the Dream](../../dm/games/010051F0207B2000/README.md) on the AYN Thor's own driver, eight runs of 2026-11-21/22 with the pipeline cache warm (8.7 MB) and 2,135 records in the list; [Pokémon Legends: Z-A](../../dm/games/0100F43008C44000/README.md), 11,253 draws skipped in a 70 s run on that driver, while on Turnip T30 a second start made 642 records ahead in 0.2 s and skipped none. With the switch on (2026-11-25, Z-A on a copy of a save on the Thor's own driver, each run the same: load the save, 60 s standing in Lumiose): the first start learned and played as one without it (439 draws skipped, 15 pipelines on the frame path, 223 made in the background; without it 510, 15, 233); the second made the 224 records and 2 capture pipelines the first had used in 0.17 s before the game started, then 0 on the frame path, 7 in the background and 23 draws skipped, and the long frames with a new pipeline went from 2 to 0. On Turnip T30 the same runs made 642 or 643 records ahead in 0.1 to 0.2 s and skipped no draw with the switch on or off; the one pipeline still made on the frame path without it, Z-A's capture pipeline, was made ahead from the second start on. + ### Storage image views for textures with sRGB format lists on the Vulkan replay - **Symptom:** (Android, Vulkan) `[RED] vk: shader binding : texture ID has no view of shape 0x1 (storage)` during compute passes that bind an RGBA8 storage image. diff --git a/peanuts/UPSTREAM-EDITS.md b/peanuts/UPSTREAM-EDITS.md index 08b4e8c49..c4e6286a1 100644 --- a/peanuts/UPSTREAM-EDITS.md +++ b/peanuts/UPSTREAM-EDITS.md @@ -2796,3 +2796,34 @@ Left as they were: the hunks the check also flags that were unmarked before 0.1. `dm/games/0100A6301214E000/game.tsv`, `dm/games/game.py`, `hle_nvn.c` `nvnWindowGetPresentInterval`, `vka_tex.c` (one line), `dm/host/dm.h`, `hle_fpslock.c` `limit_raw`, `loader.c` (two lines), `dm/host/tests/t_android_smap.c`, `dm/tools/docs_patches.py`, and the tests `test_android_soc.py`, `test_fpslocker_plan.py`, `test_game_profile.py`, `test_option_patch.py`, `test_vka_tex_registration.py`. + +### Smoother next start: what a game's runs used is made before the next start (2026-11-24, the Peanuts tab's contract `dev.peanuts.shaders.ShaderWatch`; off by default) + +The host already learns while a game runs: every pipeline it makes goes into the game's prewarm list (`vk_pipelines.keys`), and the next start makes the +list ahead. On Qualcomm's driver before 512.800 (the AYN Thor's own, 512.676) that is off by default, because the driver keeps about 6 MB outside the process +for each pipeline and the whole list made ahead ran games out of memory; every start there made its pipelines again while it played and skipped their draws +meanwhile (2,300-2,700 draws in each of eight runs of Tomodachi Life: Living the Dream with the pipeline cache warm). The Peanuts tab's switch, Learn shaders +while playing, turns on for one game (`PN_SHADERWATCH=1`, `dev.peanuts.shaders.HostWatch.env`): each run keeps the list's records it used, made while it +played or made ahead and then used, in a file of the game and the driver beside the list (`..hot`, `dm/peanuts/peanuts_swhot.h`: +hashes and the runs since each was used, at most 4,096 entries and 64 KB, an entry unused for 8 runs dropped). The next start makes those first and waits for +them before the game starts, behind Preparing shaders; the rest of the list follows in the background where the driver prewarms it, and where it does not only +those are made, by two threads that stop when less than `DM_VK_PREWARM_MEM_MB` is available. A record a game update or another shader library no longer has, +or another driver's, matches nothing and ages out. Transform feedback capture pipelines, which the list never holds (their variant's modules carry the layout +the game's program declares while it runs), are kept apart with that layout (`..tf`, `dm/peanuts/peanuts_swtf.h`, at most 64, aged out with the +`.hot` file) and made first too (`vka_tf_learned`); a draw's first use checks this run's layout. Off, nothing of it is read or written, and an explicit `DM_VK_PREWARM=0` still turns every prewarm off. The +tab's numbers come from the list (`vka_pso_watch`, `Bridge.shaderWatch`); turning the switch while the game runs takes effect at once for what this run keeps +(`Bridge.shaderWatchLearn`). [Pipelines made again while playing at every start (Android)](../docs/reference/rendering.md#pipelines-made-again-while-playing-at-every-start-android). + +| File | Hunks | Change | Marker | +|---|---|---|---| +| `dm/gfx/vk_android/vka_pso.c` | 3 blocks, a span in `pw_start`, one-line hooks | the `sw_*` block (after `pw_mark_bad`, with `sw_tf_*`), `vka_pso_watch` and `sw_tf_make` (before `pw_main`); the includes of `peanuts_swhot.h` and `peanuts_swtf.h`; the declarations; `sw_path` and `sw_load` in `pc_open_once`, the list read flag after `pw_start`; `sw_save` in `save_now`; `g_sw_dirty` in `vka_pso_save`'s early return; `vka_pso_prepare_launch` enters the startup phase for learning on too (no seed needed; on Qualcomm's driver before 512.800 too) and waits for those records only (`sw_wait_hot`); `nxhost_prewarm_progress` counts them; `pw_note` notes the record this run made, and hands a capture variant's pipeline to `sw_tf_note`; `pw_main` counts the records done (`sw_step`; the start's progress only while the start waits for the threads, `g_pw_counting`, so `pp_prepare`'s count after it is its own), stops every thread below the memory floor where the driver does not prewarm before the old wait for memory (which it skips there: it waited for a thread that had stopped), and hands the record it makes to the entry (`t_sw_h`), and takes the capture pipelines first (`sw_tf_make`); `pw_start` orders every record before the cap (`sw_order`), two threads where the driver does not prewarm, joinable while the start waits; `gfx_obtain` and `cs_obtain` note a first use of an entry made ahead (`sw_used`, one field test) and keep the record in a new entry; `gval.swh` | `PEANUTS`; a `PEANUTS begin`/`PEANUTS end` block | +| `android/app/src/main/java/dev/nxnative/android/GameActivity.java` | 1 | `settingsEnv`: `HostWatch.env` after `Companion.env` | `// PEANUTS` | +| `android/host/CMakeLists.txt` | 1 | `dm/peanuts/peanuts_shaderwatch.c` in the host | `# PEANUTS` | +| `dm/host/tests/Makefile` | 1 | `peanuts-swhot`, `peanuts-swtf` (in the Peanuts block) | inside `# PEANUTS begin` / `end` | +| `docs/reference/rendering.md`, `docs/agents/symptoms.md` | 1 each | the entry and its symptom line | ``; generated | +| `dm/games/0100F43008C44000/README.md` | 1 | the Found on this game line | `PEANUTS` | + +Peanuts-owned: `dev.peanuts.shaders.HostWatch`, `HostCounts`, `dev.peanuts.Bridge.shaderWatch` / `shaderWatchLearn`, `dm/peanuts/peanuts_shaderwatch.c`, +`dm/peanuts/peanuts_swhot.h`, `dm/peanuts/peanuts_swtf.h`, `dm/gfx/vk_android/vka_tf.c` and `vka_tf.h` (Peanuts' transform feedback: `vka_tf_learned`, +`vka_tf_layout_of`, `vka_tf_is_variant`, the first-draw check `learned_holds`), the Found on line of `dm/games/010051F0207B2000/README.md`. Tests: +`peanuts/tests/test_shader_watch.py` (with `HostCountsJvmTest`, `dm/host/tests/t_peanuts_swhot.c` and `t_peanuts_swtf.c`). diff --git a/peanuts/tests/test_shader_watch.py b/peanuts/tests/test_shader_watch.py new file mode 100644 index 000000000..988c34fa3 --- /dev/null +++ b/peanuts/tests/test_shader_watch.py @@ -0,0 +1,238 @@ +"""Smoother next start (the quick menu's Peanuts tab, dev.peanuts.shaders.ShaderWatch): its backend dev.peanuts.shaders.HostWatch, the host's numbers +(dm/gfx/vk_android/vka_pso.c vka_pso_watch, dm/peanuts/peanuts_shaderwatch.c) and learning on (vka_pso.c sw_*, dm/peanuts/peanuts_swhot.h): what the runs of a +game used, kept per game and driver, made first and before the game starts at the next start; the transform feedback capture pipelines too (vka_pso.c sw_tf_*, +dm/peanuts/peanuts_swtf.h, dm/gfx/vk_android/vka_tf.c vka_tf_learned). The JVM part is skipped without a JDK, the C part without a C +compiler (dm/host/tests/Makefile peanuts-swhot runs it too).""" +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +JAVA = REPO / 'android/app/src/main/java' +WATCH = JAVA / 'dev/peanuts/shaders/HostWatch.java' +COUNTS = JAVA / 'dev/peanuts/shaders/HostCounts.java' +CONTRACT = JAVA / 'dev/peanuts/shaders/ShaderWatch.java' +BRIDGE = JAVA / 'dev/peanuts/Bridge.java' +GAME = JAVA / 'dev/nxnative/android/GameActivity.java' +JVM_TEST = REPO / 'android/app/src/jvmtest/java/dev/peanuts/shaders/HostCountsJvmTest.java' +PSO = REPO / 'dm/gfx/vk_android/vka_pso.c' +JNI = REPO / 'dm/peanuts/peanuts_shaderwatch.c' +HOT = REPO / 'dm/peanuts/peanuts_swhot.h' +SWTF = REPO / 'dm/peanuts/peanuts_swtf.h' +TF = REPO / 'dm/gfx/vk_android/vka_tf.c' +C_TEST = REPO / 'dm/host/tests/t_peanuts_swhot.c' +C_TEST_TF = REPO / 'dm/host/tests/t_peanuts_swtf.c' +CMAKE = REPO / 'android/host/CMakeLists.txt' + + +def read(p): return p.read_text(encoding='utf-8') + + +def body(src, head): + """The braces' body of the definition that starts with head (a declaration of it, ending in ';' first, is passed over)""" + i = src.index(head) + while True: + semi, brace = src.find(';', i), src.find('{', i) + if brace >= 0 and (semi < 0 or brace < semi): break + i = src.index(head, i + 1) + j = brace + depth = 0 + for k in range(j, len(src)): + if src[k] == '{': depth += 1 + elif src[k] == '}': + depth -= 1 + if not depth: return src[j:k + 1] + raise AssertionError('no body after ' + head) + + +class Wiring(unittest.TestCase): + def test_one_hook_in_the_game_activity(self): + s = read(GAME) + self.assertEqual(s.count('dev.peanuts.shaders.HostWatch.env(this, id, env);'), 1) + line = [l for l in s.splitlines() if 'HostWatch.env(' in l][0] + self.assertIn('// PEANUTS', line) + settings = s[s.index('private String settingsEnv('):] + self.assertLess(settings.index('HostWatch.env('), settings.index('\n }\n')) + + def test_the_backend_registers_and_learns_only_when_on(self): + env = body(read(WATCH), 'public static void env(') + self.assertIn('ShaderWatch.backend(INSTANCE);', env) + self.assertIn('ShaderWatch.on(a, titleId)', env) + self.assertIn('!dev.peanuts.build.ShaderCapture.active(a)', env) # a preparation boot of Build is no play + self.assertIn('env.removeIf(s -> s.startsWith("PN_SHADERWATCH="))', env) + self.assertIn('static final String LINE = "PN_SHADERWATCH=1";', read(WATCH)) + self.assertIn('Bridge.shaderWatchLearnSafe(on)', body(read(WATCH), 'public void learning(')) + + def test_the_contract_is_kept(self): + c = read(CONTRACT) + self.assertIn('public interface Backend', c) + w = read(WATCH) + self.assertIn('implements ShaderWatch.Backend', w) + for m in ('boolean available(android.content.Context c, String titleId)', 'int learned()', 'int ready(android.content.Context c, String titleId)', + 'void learning(android.content.Context c, String titleId, boolean on)'): + self.assertIn(m, w) + self.assertIn('static final int UNKNOWN = -1;', read(COUNTS)) + self.assertIn('public static final int UNKNOWN = -1;', c) + + def test_jni_names_match(self): + b, j = read(BRIDGE), read(JNI) + self.assertIn('public static native boolean shaderWatch(int[] out);', b) + self.assertIn('public static native boolean shaderWatchLearn(boolean on);', b) + self.assertIn('Java_dev_peanuts_Bridge_shaderWatch(JNIEnv *env, jclass cls, jintArray out)', j) + self.assertIn('Java_dev_peanuts_Bridge_shaderWatchLearn(JNIEnv *env, jclass cls, jboolean on)', j) + self.assertIn('void vka_pso_watch(int out[4]) __attribute__((weak));', j) + self.assertIn('void vka_pso_watch_learn(int on) __attribute__((weak));', j) + self.assertIn('${ROOT}/dm/peanuts/peanuts_shaderwatch.c', read(CMAKE)) + + +class OffMeansOff(unittest.TestCase): + """Learning off: nothing of Smoother next start is read, written, ordered or waited for; the list and the prewarm are upstream's""" + + def setUp(self): self.s = read(PSO) + + def test_the_switch_is_the_environment(self): + on = body(self.s, 'static int sw_on(void)') + self.assertIn('getenv("PN_SHADERWATCH")', on) + self.assertIn('!strcmp(e, "1")', on) + + def test_every_step_asks_the_switch(self): + for head in ('static void sw_load(void)', 'static void sw_save(void)', 'static uint32_t sw_order('): + b = body(self.s, head) + first = b.split('\n')[1] if '\n' in b else b # the first statement (a one-line body is its own) + self.assertIn('sw_on()', first, head + ' must return first when learning is off') + learn = body(self.s, 'void vka_pso_watch_learn(int on)') + self.assertLess(learn.index('sw_load_now()'), learn.index('atomic_store(&g_sw_on, on ? 1 : 0);')) # the runs before's file first: no save merges without it + self.assertIn('if (!on) atomic_store(&g_sw_dirty, 0);', learn) + self.assertIn('if (h && sw_on()) sw_run_add(h, 0);', body(self.s, 'static void sw_used(gval *g)')) + self.assertIn('if (sw_on()) sw_run_add(h, 1);', body(self.s, 'static void pw_note(')) + self.assertIn('t_sw_h = !bad && sw_on() ? vka_pw_hash(&r, kb) : 0;', self.s) + start = body(self.s, 'static void pw_start(int wait)') + self.assertIn('sw_on() && g_sw_oldn', start) # a driver that does not prewarm makes nothing without it + self.assertIn('if (sw_on()) g_pw_limit = g_pw_load_n;', start) + launch = body(self.s, 'void vka_pso_prepare_launch(void)') + self.assertIn('int sw = sw_on();', launch) + self.assertIn('(seed || sw)', launch) + self.assertIn('(!V.qcom_old || enabled || sw)', launch) + + def test_an_explicit_prewarm_off_wins(self): + start = body(self.s, 'static void pw_start(int wait)') + self.assertIn('nt <= 0 && !getenv("DM_VK_PREWARM")', start) + self.assertIn('(!enabled || atoi(enabled) > 0)', body(self.s, 'void vka_pso_prepare_launch(void)')) + + def test_no_cost_on_the_frame_path(self): + # the lookups test one field of an entry they hold already; the record's hash is made by the prewarm thread, never by a draw + g = body(self.s, 'static gval *gfx_obtain(const gkey_full *fk') + self.assertIn('if (!prewarm && g->swh) sw_used(g);', g) + self.assertNotIn('vka_pw_hash', g) + c = body(self.s, 'static VkPipeline cs_obtain(vka_shader *cs') + self.assertIn('if (!prewarm && g->swh) sw_used(g);', c) + self.assertNotIn('vka_pw_hash', c) + + def test_the_memory_floor_never_waits(self): + # on a driver that does not prewarm every thread stops below the floor, before the wait for the others (which would wait for a thread that stopped) + m = body(self.s, 'static void *pw_main(void *a)') + floor = m.index('if (g_sw_only && mem_mb) {') + wait = m.index('if (me > 0 && mem_mb && !g_sw_only) {') + self.assertLess(floor, wait) + self.assertIn('break;', m[floor:wait]) + + def test_the_start_counts_only_what_it_waits_for(self): + self.assertIn('for (;; sw_step(&sw_cur)) {', self.s) + self.assertIn('if (atomic_load(&g_pw_counting)) atomic_fetch_add(&g_pw_processed, 1);', body(self.s, 'static void sw_step(uint32_t *cur)')) + self.assertIn('atomic_store(&g_pw_counting, 0); atomic_store(&g_sw_wait, 0);', body(self.s, 'static void sw_wait_hot(void)')) + + def test_bounded(self): + h = read(HOT) + self.assertIn('#define PN_SW_MAX 4096', h) + self.assertIn('#define PN_SW_AGE_MAX 8', h) + self.assertIn('if (cap > PN_SW_MAX) cap = PN_SW_MAX;', body(self.s, 'static void sw_save(void)')) + self.assertIn('if (h.n > PN_SW_MAX) return', h) + tf = read(SWTF) + self.assertIn('#define PN_SWTF_MAX 64', tf) + self.assertIn('if (h.n > PN_SWTF_MAX) return', tf) + self.assertIn('n = pn_swtf_keep(g_sw_tfr, g_sw_tfrn, g_sw_tfl, g_sw_tfln, keep, kn, e, PN_SWTF_MAX);', self.s) + + def test_per_driver_file(self): + p = body(self.s, 'static void sw_path(void)') + self.assertIn('vka_driver_tag()', p) + self.assertIn('"%s.%s.hot", g_pw_path, tag ? tag : "system"', p) + + def test_capture_pipelines_only_when_learning(self): + # the list never takes a capture variant's pipeline: with learning off pw_note returns at it as before, with learning on sw_tf_note keeps it + self.assertIn('if (!i && kind == VKA_PW_GFX && vka_tf_is_variant(sh[0])) { sw_tf_note(sh, kb, klen); return; }', body(self.s, 'static void pw_note(')) + note = body(self.s, 'static void sw_tf_note(vka_shader *const sh[5], const void *kb, uint32_t klen)') + self.assertIn('if (!sw_on()', note.splitlines()[1]) + self.assertIn('if (!pn_swtf_ok(&e)) return;', note) + start = body(self.s, 'static void pw_start(int wait)') + self.assertIn('g_sw_tf_n = sw_on() && V.xfb ? (uint32_t)g_sw_tfln : 0;', start) + self.assertIn('g_sw_hot_n += g_sw_tf_n;', start) # made first and waited for, as the runs' other pipelines + self.assertIn('if (g_sw_tf_n && !atomic_load(&g_pp_skip))', body(self.s, 'static void *pw_main(void *a)')) + self.assertIn('else sw_tf_save(', body(self.s, 'static void sw_save(void)')) # written only after the .hot file, with the entries it keeps + self.assertIn('"%s.%s.tf", g_pw_path, tag ? tag : "system"', body(self.s, 'static void sw_path(void)')) + + def test_a_capture_made_ahead_is_checked_at_its_first_draw(self): + t = read(TF) + self.assertIn('if (g_var[i].learned && !g_var[i].checked && !learned_holds(i)) continue;', body(t, 'static vka_shader *variant(')) + self.assertIn('int ok = st == 1 && !memcmp(&lay, &g_var[i].L, sizeof lay);', body(t, 'static int learned_holds(int i)')) + learned = body(t, 'vka_shader *vka_tf_learned(vka_shader *s, const vka_tf_layout *lay)') + self.assertIn('if (!V.xfb || !s || !s->e) return NULL;', learned.splitlines()[1]) + self.assertEqual(t.count('.learned = 1;'), 1) # only vka_tf_learned makes one + self.assertIn('!g_var[i].dead', body(t, 'void vka_tf_prep(')) + + def test_marked(self): + # the functions sit in one PEANUTS block; every other line that uses them carries a PEANUTS marker or sits in a PEANUTS span + a = self.s.index('// PEANUTS begin: Smoother next start, learning on') + b = self.s.index('// PEANUTS end', a) + block = self.s[a:b] + for f in ('static int sw_on(void) {', 'static void sw_save(void) {', 'static uint32_t sw_order(', 'void vka_pso_watch_learn(int on) {'): + self.assertIn(f, block) + lines = self.s.splitlines() + first = self.s[:a].count('\n') + last = first + block.count('\n') + span = False + for n, line in enumerate(lines): + if '// PEANUTS begin' in line: span = True + if '// PEANUTS end' in line: span = False + if first <= n <= last or line.lstrip().startswith('//'): continue + if re.search(r'\bsw_(on|load|save|path|order|step|used|run_add|wait_hot|tf_\w+)\(|g_sw_wait|g_sw_hot|g_sw_dirty|g_sw_tf|t_sw_h', line): + self.assertTrue(span or 'PEANUTS' in line, line.strip()[:120]) + + +class Voice(unittest.TestCase): + def test_no_em_dash(self): + for p in (WATCH, COUNTS, JNI, HOT, SWTF, C_TEST, C_TEST_TF, JVM_TEST): + self.assertNotIn('—', read(p), p.name) + + +@unittest.skipUnless(shutil.which('javac') and shutil.which('java'), 'no JDK') +class Jvm(unittest.TestCase): + def test_jvm(self): + with tempfile.TemporaryDirectory() as d: + r = subprocess.run(['javac', '-Xlint:all', '-Werror', '-encoding', 'UTF-8', '-d', d, str(COUNTS), str(JVM_TEST)], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + r = subprocess.run(['java', '-cp', d, 'dev.peanuts.shaders.HostCountsJvmTest'], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('ok', r.stdout) + + +CC = shutil.which('cc') or shutil.which('gcc') or shutil.which('clang') + + +@unittest.skipUnless(CC, 'no C compiler') +class C(unittest.TestCase): + def test_swhot(self): + for src in (C_TEST, C_TEST_TF): + with tempfile.TemporaryDirectory() as d: + exe = str(Path(d) / src.stem) + r = subprocess.run([CC, '-std=c11', '-O1', '-Wall', '-Wextra', '-Werror', '-o', exe, str(src)], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + r = subprocess.run([exe], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('ok', r.stdout) + + +if __name__ == '__main__': + unittest.main() diff --git a/peanuts/upstream-unmarked.txt b/peanuts/upstream-unmarked.txt index 1e8fe87b3..aec3c9733 100644 --- a/peanuts/upstream-unmarked.txt +++ b/peanuts/upstream-unmarked.txt @@ -368,3 +368,5 @@ dm/games/01003D100E9C6000/shader_pairs.tsv tables shader_split.py wrote for The dm/games/01006F8002326000/speedfix60/NOTICE.md the third-party licence notice of tmouh's ACNH 60 FPS + SpeedFix data (CC BY-NC 4.0): a licence text, kept as the licence asks, with no marker line dm/games/01003D100E9C6000/vk_prewarm.bin a prewarm seed made by dm/tools/vk_prewarm.py from The Witcher 3 (EU) 4.04b on an AYN Thor (292 pipeline keys collected on Turnip, commit c02e6414): binary, tied to this host's key layout; game.tsv and README.md carry the PEANUTS markers dm/games/010075101EF84000/patches.py Stray's patches.py, a file of a profile this fork added (dnyan007, #379): its bytes are part of every Stray module's rewrite key (scripts/pack_android.py rewrite_keys), so a marker comment would make every Stray build convert its code again; game.tsv and README.md carry the PEANUTS markers +dm/gfx/vk_android/vka_tf.c a Peanuts-owned file (its first line starts with "PEANUTS:": NVN transform feedback on the Vulkan replay, since 0.1.2) in upstream's vk_android directory: every line of it is Peanuts', so its hunks carry no marker of their own (Smoother next start: vka_tf_learned) +dm/gfx/vk_android/vka_tf.h its header, Peanuts-owned the same way (its first line starts with "PEANUTS:"; Smoother next start: vka_tf_learned, vka_tf_layout_of, vka_tf_is_variant)