22 Commits
Author SHA1 Message Date
Valiantsin DzerakhandClaude Opus 5.5 7da078d1ab Merge task/bmerge: barrier_merge is on by default and ends the pass when a draw samples a target written in the pass that it does not write itself, as Savage Wind does; shrine passes 581 -> 128 a frame on an RDNA2 iGPU with the GPU time unchanged on AMD's Windows driver, RADV waterfall GPU 8.3 -> 4.1 ms (#1237)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:15:52 +03:00
Valiantsin DzerakhandClaude Opus 5.5 dca69306fb barrier_merge is on by default
With the unwritten-read rule every read that stays merged comes from a draw that samples a target it also writes,
the case Savage Wind runs the same way on every GPU. Shrine on the RDNA2 iGPU (AMD Windows driver, 1080p): passes
581 -> 128 a frame, GPU time unchanged (37.2 ms off, 38.0 and 36.5 ms on), the picture the same. PR #1237 measured
the waterfall on RADV at 1105 -> 117 passes and GPU 8.3 -> 4.1 ms, and an RTX 4080 shrine at +3% mean fps with the
1% low 83 -> 98. barrier_merge = 0 brings back a full barrier at each such Barrier.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:15:23 +03:00
Valiantsin DzerakhandClaude Opus 5.5 3c977bf78c Merge pull request #1435: Linux opens a text entry window for the software keyboard (horse naming) with keyboard and controller grid input, and falls back to the default name when no window opens (cheat45681) (#401)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:07:57 +03:00
Valiantsin DzerakhandClaude Opus 5.5 c3cd1e31c2 Text entry on SDL: hint lines come from the catalog, a password shows stars, a surrogate pair goes in and out whole and obeys the length limit, TOTK_SWKBD_TEST=ok presses OK, and the window redraws when exposed (#401)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:07:09 +03:00
Valiantsin DzerakhandClaude Opus 5.5 5aaa718eb6 barrier_merge ends the pass when a draw samples a target written in the pass that it does not write itself
The by-region barrier inside a merged pass orders only the pixel a fragment writes. A draw that reads a target other
draws wrote, without writing it, may read neighbouring pixels (blur, ambient occlusion, light composites), which only
the game's full Barrier orders on every driver. Such a draw now ends the pass, as Savage Wind does for the same case.
TOTK_TRACE=gfx counts these restarts by colour and depth. Shrine, town and field on 1.4.3: 0 restarts; every read
after a merged Barrier comes from a draw that writes the target it samples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:04:48 +03:00
cheat45681 37551aedad Linux text entry: controller letter grid (D-pad, bottom add, right delete, Start OK, top cancel); keyboard unchanged 2026-11-24 09:03:38 +03:00
cheat45681 a5c95fb971 Linux: add a text entry window for the software keyboard (horse naming, #401) 2026-11-24 09:03:38 +03:00
Valiantsin DzerakhandClaude Opus 5.5 be7ca2c275 Merge task/demoteini: on AMD's Windows driver a discarded pixel keeps running only in shaders that take a derivative after the discard, so grass, foliage and other alpha-tested draws no longer pay for their discarded pixels; demote is a totk.ini key (#1365, #164)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:57:41 +03:00
Valiantsin DzerakhandClaude Opus 5.5 c8b88f7428 Demote a discard only where a derivative follows it, and read demote from the ini (#164, #1365)
spirv_demote turned every OpKill inside a selection into OpDemoteToHelperInvocation on AMD's Windows driver. A
demoted fragment runs the rest of the shader, so every alpha-tested draw (grass, foliage, hair) paid for its
discarded pixels. The cloud fringe of #164 came from OpImageQueryLod after the discard. Now a discard is demoted only
when an OpImageQueryLod, an explicit derivative or a function call follows it in its function; the rest keep the
plain discard, as before 0.4.1. On the field save 1 of 128 shaders with a discard is demoted, and the picture keeps
the fix.

demote has a row in the settings table and a description in totk.ini.example, so demote = 0 or 1 in the ini no
longer logs an unknown key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:56:03 +03:00
Valiantsin DzerakhandClaude Opus 5.5 4f5a9d4754 Merge task/pr1369: heap_lazy = 1 commits the game heap on first use on Windows, off by default; the Vulkan import also commits the chunks its alignment widens into, and the commit census shows the heap's faults (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:50:35 +03:00
Valiantsin DzerakhandClaude Opus 5.5 de0b1f899f heap_lazy adds the committed heap and the first-use faults with their total time to the commit census lines, so a log shows what the setting saved and cost
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:44:45 +03:00
Valiantsin DzerakhandClaude Opus 5.5 a0587b59e7 heap_lazy also commits the chunks a Vulkan import widens into when the driver's host pointer alignment is above 4 KiB, and the memory.c comment names mem_heap_commit for save writes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:39:29 +03:00
Valiantsin DzerakhandClaude Opus 5.5 d66aeef75c Merge pull request #1369: heap_lazy = 1 commits the game heap on first use on Windows, off by default (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:35:07 +03:00
Valiantsin DzerakhandClaude Opus 5.5 011b80c948 Merge pull request #1408: the IPC probe's request helper clears its reply when the kernel call fails (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:34:47 +03:00
Valiantsin DzerakhandClaude Opus 5.5 a073e6d3c6 Merge pull request #1407: the custom cursor's sampler writes zero colour where it returns zero coverage (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:34:47 +03:00
Ruan Shannon 7ddb883992 Merge remote-tracking branch 'fork/perf/heap-lazy-commit' into perf/heap-lazy-commit 2026-11-23 13:39:47 -08:00
Ruan ShannonandClaude Opus 5.5 ab356192d7 heap_lazy: the docs say 1 MiB chunks, and with the setting off ipc, svc and save writes are as before
Review of #1369: the settings row still said 64 KiB though LAZY_CHUNK is 1 MiB, and two changes ran for every player.
ipc.c and svc.c readable() ask the OS again unless TOTK_HEAP_LAZY is on (mem_heap_lazy), and fs_host.c write_file calls
mem_heap_commit, which commits the buffer's reserved heap chunks in lazy mode and does nothing otherwise, instead of
mem_thaw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:38:10 -08:00
Ruan Shannon 54b2975d98 Merge remote-tracking branch 'origin/dev' into perf/heap-lazy-commit
# Conflicts:
#	runtime/cfg.c
2026-11-23 13:37:39 -08:00
ShannoonRuaaa fe45b876e0 Merge current dev while preserving heap and lightning settings 2026-11-22 15:23:19 -08:00
ICUMADETHIS 2ec4b3f04b Clear IPC probe replies after kernel failures 2026-11-22 21:34:13 +00:00
ICUMADETHIS 362fcfb3b7 Initialize transparent custom cursor samples 2026-11-22 21:24:54 +00:00
Ruan Shannon 6370c7c0b6 heap_lazy = 1 commits the game's heap a 1 MiB chunk at a time on first use (Windows, opt-in)
SetHeapSize takes the game's whole heap at boot (2.1 GiB on 1.4.3) and Windows charges all of it against the commit
limit, although a sky-island run touched about two thirds. With TOTK_HEAP_LAZY=1 the heap stays reserved: the first
read or write of a chunk faults and memory.c heap_fault commits it; read faults reach the hook only in this mode
(plat_mem_fault_reads). A byte per chunk (lazy_map) answers without asking the OS, so frozen-region write faults pay
nothing for it, and only clear chunks are committed, never pages a freeze made read-only. mem_thaw, which file reads,
save writes and Vulkan imports call before the kernel or driver touches guest memory, commits its range's chunks
first; ipc.c and svc.c check readability by the layout; vk_mem_host_room counts the uncommitted heap as taken. Default
off: the heap path is unchanged unless set.

Sky island, 120 s, this laptop (Iris Xe): peak commit 6345-6536 MiB on dev, 5736-5821 MiB with heap_lazy = 1; about
600 first-use faults, 8 ms in all.
2026-11-22 04:49:58 -08:00
25 changed files with 719 additions and 56 deletions

No files matched your search

+1 -1
View File
@@ -81,7 +81,7 @@ Source shorthands:
| 3.2 | **FMZ multiply mode** (`FMUL/FFMA/...` field `Fmz`, `.FMZ`): 0 × anything = 0, including Inf/NaN (DX9 rule). | IEEE: 0 × Inf = NaN. | Ryujinx decodes `Fmz` (`Decoders/InstDecoders.cs:306-309, 1901`) but no emitter reads it. Ours: same. Census needed (check 13). | RYU-SH | | 3.2 | **FMZ multiply mode** (`FMUL/FFMA/...` field `Fmz`, `.FMZ`): 0 × anything = 0, including Inf/NaN (DX9 rule). | IEEE: 0 × Inf = NaN. | Ryujinx decodes `Fmz` (`Decoders/InstDecoders.cs:306-309, 1901`) but no emitter reads it. Ours: same. Census needed (check 13). | RYU-SH |
| 3.3 | **Denormals**: per-instruction `.FTZ`. | AMD flushes fp32 denormals by default; `VK_KHR_shader_float_controls` sets it per shader. | Ryujinx ignores `.FTZ`. Low risk. | RYU-SH (no `Ftz` use in `Instructions/`) | | 3.3 | **Denormals**: per-instruction `.FTZ`. | AMD flushes fp32 denormals by default; `VK_KHR_shader_float_controls` sets it per shader. | Ryujinx ignores `.FTZ`. Low risk. | RYU-SH (no `Ftz` use in `Instructions/`) |
| 3.4 | **Warp size 32**: `SHFL`, `VOTE`, `S2R LANEID`, ballots are 32-bit. | AMD RDNA runs wave32 or wave64 per shader (the driver chooses; RADV fragment default wave64); `VK_EXT_subgroup_size_control` `requiredSubgroupSize = 32` fixes it. | Ryujinx adapts lane masks to `QueryHostSubgroupSize()` (default 32, `IGpuAccessor.cs:218`; `Instructions/InstEmitWarp.cs:72, 106`, `InstEmitMove.cs:175-185`). Ours: not overridden, no required size (check 6). | <https://docs.mesa3d.org/envvars.html> (`RADV_PERFTEST=pswave32`) | | 3.4 | **Warp size 32**: `SHFL`, `VOTE`, `S2R LANEID`, ballots are 32-bit. | AMD RDNA runs wave32 or wave64 per shader (the driver chooses; RADV fragment default wave64); `VK_EXT_subgroup_size_control` `requiredSubgroupSize = 32` fixes it. | Ryujinx adapts lane masks to `QueryHostSubgroupSize()` (default 32, `IGpuAccessor.cs:218`; `Instructions/InstEmitWarp.cs:72, 106`, `InstEmitMove.cs:175-185`). Ours: not overridden, no required size (check 6). | <https://docs.mesa3d.org/envvars.html> (`RADV_PERFTEST=pswave32`) |
| 3.5 | **Discard (`KIL`)** keeps the quad's derivatives valid (demote semantics). | `OpKill` terminates; later derivatives in the quad undefined. | Ryujinx emits `OpKill` (`CodeGen/Spirv/Instructions.cs:508`). Ours: on AMD's own drivers (`vk_caps.amd` without `mesa`) `vk_pipeline.c` `spirv_demote` turns each `OpKill` that a selection header branches to into `OpDemoteToHelperInvocation` plus a branch to the selection's merge block; `TOTK_DEMOTE` overrides. TotK's cloud shader discards and then takes `OpImageQueryLod`: with `OpKill` AMD's Windows driver lost fog in the fragments sharing a quad with a discarded one (#164). | <https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/EXT/SPV_EXT_demote_to_helper_invocation.asciidoc> | | 3.5 | **Discard (`KIL`)** keeps the quad's derivatives valid (demote semantics). | `OpKill` terminates; later derivatives in the quad undefined. | Ryujinx emits `OpKill` (`CodeGen/Spirv/Instructions.cs:508`). Ours: on AMD's own drivers (`vk_caps.amd` without `mesa`) `vk_pipeline.c` `spirv_demote` turns each `OpKill` that a selection header branches to, and that an `OpImageQueryLod`, an explicit derivative or a call follows in its function, into `OpDemoteToHelperInvocation` plus a branch to the selection's merge block; other kills stay `OpKill`, since a demoted fragment runs the rest of the shader and alpha-tested draws paid for every discarded pixel. `TOTK_DEMOTE` (ini `demote`) overrides. TotK's cloud shader discards and then takes `OpImageQueryLod`: with `OpKill` AMD's Windows driver lost fog in the fragments sharing a quad with a discarded one (#164). | <https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/EXT/SPV_EXT_demote_to_helper_invocation.asciidoc> |
| 3.6 | **Implicit-LOD sampling in divergent control flow** works on Maxwell (TEX unit uses quad neighbours). | Undefined in non-uniform control flow; AMD whole-quad mode usually works. | — | VKSPEC (derivatives) | | 3.6 | **Implicit-LOD sampling in divergent control flow** works on Maxwell (TEX unit uses quad neighbours). | Undefined in non-uniform control flow; AMD whole-quad mode usually works. | — | VKSPEC (derivatives) |
| 3.7 | **Integer division** does not exist (compiled to `XMAD`/`IMAD` sequences); MUFU.RCP(0) = +Inf, LG2(0) = -Inf. | Same IEEE edge cases through `1/x`, `Log2`. | Low risk. | — | | 3.7 | **Integer division** does not exist (compiled to `XMAD`/`IMAD` sequences); MUFU.RCP(0) = +Inf, LG2(0) = -Inf. | Same IEEE edge cases through `1/x`, `Log2`. | Low risk. | — |
| 3.8 | **FP64** in some TotK cutscene shaders. | No FP64 on some hosts. | yuzu FP64 → FP32 (YZ-2306, PR 10693); ours: `softfloat64` job flag (`tools/xlate/Program.cs` `QueryHostSupportsShaderFloat64`). | — | | 3.8 | **FP64** in some TotK cutscene shaders. | No FP64 on some hosts. | yuzu FP64 → FP32 (YZ-2306, PR 10693); ours: `softfloat64` job flag (`tools/xlate/Program.cs` `QueryHostSupportsShaderFloat64`). | — |
+2 -1
View File
@@ -28,7 +28,7 @@ Many rows below are developer tools that only act together with another setting
| `bind_stats` | `1` counts bindings and descriptors per draw of each stage and how much of the bound state changes between draws. | Adds per-draw bookkeeping to the render thread and extra log output; frames get slower. | Caution | | `bind_stats` | `1` counts bindings and descriptors per draw of each stage and how much of the bound state changes between draws. | Adds per-draw bookkeeping to the render thread and extra log output; frames get slower. | Caution |
| `contact_debug` | `1` draws the contact-shadow factor in grey in place of the picture; `2` draws the sun visibility the shadows are scaled by (white in the sun, black in shade and underground). | The frame shows a grey debug image while it is set; has no effect when contact shadows are off. | Caution | | `contact_debug` | `1` draws the contact-shadow factor in grey in place of the picture; `2` draws the sun visibility the shadows are scaled by (white in the sun, black in shade and underground). | The frame shows a grey debug image while it is set; has no effect when contact shadows are off. | Caution |
| `core_diag` | `1` records why ready guest threads wait for a virtual core and for how long, with a histogram every 60 presents. | Turns on host-call and SVC depth tracking and writes many log lines (one per present over 25 ms); frames get slower. | Caution | | `core_diag` | `1` records why ready guest threads wait for a virtual core and for how long, with a histogram every 60 presents. | Turns on host-call and SVC depth tracking and writes many log lines (one per present over 25 ms); frames get slower. | Caution |
| `barrier_merge` (default `0`) | Experimental. `1` keeps a render pass open through the game's Barrier calls that ask only for fragment ordering and texture invalidation, when no draw of the pass can write a storage buffer or image; the next draw that samples a written target gets a by-region barrier in the pass (the feedback layout). In scenes with about a thousand such barriers a frame this cuts the passes from about 1200 to 130 and the GPU time from 24.5 to 7.8 ms. | The game's barrier orders every pixel, the in-pass by-region barrier only the pixel a draw writes: a driver that runs it per screen tile can show flicker or squares at the edges of water, decals or particles. | Caution | | `barrier_merge` (default `1`) | `1` keeps a render pass open through the game's Barrier calls that ask only for fragment ordering and texture invalidation, when no draw of the pass can write a storage buffer or image; the next draw that samples a target it also writes gets a by-region barrier in the pass (the feedback layout), and a draw that samples a written target without writing it ends the pass. In scenes with about a thousand such barriers a frame this cuts the passes from about 1200 to 130 and, on RADV, the GPU time from 24.5 to 7.8 ms; AMD's Windows driver shows no GPU time change. `0` ends the pass at every such Barrier. | The game's barrier orders every pixel, the in-pass by-region barrier only the pixel a draw writes: a driver that runs it per screen tile could show flicker or squares at the edges of water, decals or particles; `0` rules that out. | Caution |
| `menu_cursor_log` | `1` logs what the menu cursor code reads at every screen change. | Only adds log lines. | Safe | | `menu_cursor_log` | `1` logs what the menu cursor code reads at every screen change. | Only adds log lines. | Safe |
| `plugin_tick_offset` (default `0`) | Added to every GetSystemTick in the plugin service run (`totk.exe --plugin-init DIR`), so `tools/exefs_plugins.py` can run a plugin's init twice with other ticks and compare the records. | Has no effect outside `--plugin-init`; a plugin's init at the start of the game gets the plain ticks. | Safe | | `plugin_tick_offset` (default `0`) | Added to every GetSystemTick in the plugin service run (`totk.exe --plugin-init DIR`), so `tools/exefs_plugins.py` can run a plugin's init twice with other ticks and compare the records. | Has no effect outside `--plugin-init`; a plugin's init at the start of the game gets the plain ticks. | Safe |
| `plugin_trace` (default `0`) | `1` logs the first call of each entry of a mod plugin's hooks (its callbacks, replace and call targets) as `plugins: hook entry ... reached`. | Each such call goes through a counting step; nothing changes without a mod plugin. | Safe | | `plugin_trace` (default `0`) | `1` logs the first call of each entry of a mod plugin's hooks (its callbacks, replace and call targets) as `plugins: hook entry ... reached`. | Each such call goes through a counting step; nothing changes without a mod plugin. | Safe |
@@ -221,6 +221,7 @@ Many rows below are developer tools that only act together with another setting
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `app_pool` | Size in bytes of the guest application memory pool; accepts decimal or `0x` hex. | The default depends on the resolution settings; `0` stops the start with a message, and too small a pool leaves the game without memory. | Risky | | `app_pool` | Size in bytes of the guest application memory pool; accepts decimal or `0x` hex. | The default depends on the resolution settings; `0` stops the start with a message, and too small a pool leaves the game without memory. | Risky |
| `audio_off` | Any value mixes audio without opening an output device. | The game runs in silence and reports two channels; same as `audio = none`. | Caution | | `audio_off` | Any value mixes audio without opening an output device. | The game runs in silence and reports two channels; same as `audio = none`. | Caution |
| `heap_lazy` (default `0`) | The game's heap is committed a 1 MiB chunk at a time when the game first touches it, instead of all at once when the game sets its size (about 2.1 GiB at boot on 1.4.3). File reads, save writes and Vulkan imports commit their pages first. Windows only; Linux already backs pages on first use. | `1` lowers the game's committed memory (RAM plus page file) by the heap the game never touches (sky island: peak commit about 6.4 to 5.8 GiB), which helps PCs whose commit limit is near the game's needs; each first touch of a 1 MiB chunk costs a fault and a commit (about 600 a run, 8 ms in all). | Caution |
| `kspin_us` (default `20`) | Microseconds a guest wait or a wait for a virtual core polls before it sleeps; `0` turns the poll off; `ab` polls only in the B blocks of `ab`. Off with fewer than 6 logical processors. | A wake within the poll costs no OS wake-up; a longer poll takes more CPU time from other threads. | Caution | | `kspin_us` (default `20`) | Microseconds a guest wait or a wait for a virtual core polls before it sleeps; `0` turns the poll off; `ab` polls only in the B blocks of `ab`. Off with fewer than 6 logical processors. | A wake within the poll costs no OS wake-up; a longer poll takes more CPU time from other threads. | Caution |
| `mem_reserve_mib` (default `1536`) | MiB of system memory kept free for Windows, other programs and the game's own heap when the renderer sizes what it keeps in device memory, where device memory takes system memory (integrated GPUs, and discrete GPUs whose driver charges it to the process). | A larger value keeps fewer released textures and spare blocks when the system runs short; a smaller one lets the game use more before it holds back. | Caution | | `mem_reserve_mib` (default `1536`) | MiB of system memory kept free for Windows, other programs and the game's own heap when the renderer sizes what it keeps in device memory, where device memory takes system memory (integrated GPUs, and discrete GPUs whose driver charges it to the process). | A larger value keeps fewer released textures and spare blocks when the system runs short; a smaller one lets the game use more before it holds back. | Caution |
| `one_per_core` (default `0`) | `1` keeps the process on the first logical processor of each physical core; `ab` switches it with the `ab` blocks. | Busy threads stop sharing a core with a sibling thread, which can help or hurt on the CPU; it only applies when the CPU has hyperthreads. | Caution | | `one_per_core` (default `0`) | `1` keeps the process on the first logical processor of each physical core; `ab` switches it with the `ab` blocks. | Busy threads stop sharing a core with a sibling thread, which can help or hurt on the CPU; it only applies when the CPU has hyperthreads. | Caution |
+5 -4
View File
@@ -41,7 +41,7 @@ static const char *const known[] = {
"BIND_INC", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", "BIND_INC", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y",
"BIND_ZL", "BIND_ZR", "BARRIER_MERGE", "BLOCK_VIEWS_3D", "CLIMB_FIX", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA", "BIND_ZL", "BIND_ZR", "BARRIER_MERGE", "BLOCK_VIEWS_3D", "CLIMB_FIX", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA",
"COLOR_PRESET", "COLOR_SATURATION", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT", "COLOR_PRESET", "COLOR_SATURATION", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT",
"DESC_TEMPLATE", "DESWIZZLE", "DEVICE_PROFILE", "DIALOGUE_CLICK", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_CAM_JITTER", "DLAA_EFFECTS_AFTER", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_FIXED_EXPOSURE", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DEMOTE", "DESC_TEMPLATE", "DESWIZZLE", "DEVICE_PROFILE", "DIALOGUE_CLICK", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_CAM_JITTER", "DLAA_EFFECTS_AFTER", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_FIXED_EXPOSURE", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR",
"DUMP_LOG", "DYNAMIC_RES", "DYN_DELTA", "EXEFS", "FEEDBACK", "FG_DEBUG", "FG_OBJECTS", "FG_SHOT", "FG_SHOT_DIR", "FG_TEST", "FG_TIMES", "FIXED_RES_PATCH", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "DUMP_LOG", "DYNAMIC_RES", "DYN_DELTA", "EXEFS", "FEEDBACK", "FG_DEBUG", "FG_OBJECTS", "FG_SHOT", "FG_SHOT_DIR", "FG_TEST", "FG_TIMES", "FIXED_RES_PATCH", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES",
"FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FLUSH_SPAN", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FRAME_GEN", "FRAME_QUEUE", "FREECAM_KEY", "FREECAM_PAD", "FREECAM_PATCH", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FLUSH_SPAN", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FRAME_GEN", "FRAME_QUEUE", "FREECAM_KEY", "FREECAM_PAD", "FREECAM_PATCH",
"FREEZE_IDLE", "FREE_CORES", "FSR3_DEBUG", "FSR3_VIEW", "FSR4_DEBUG", "FSR_SHARPNESS", "FREEZE_IDLE", "FREE_CORES", "FSR3_DEBUG", "FSR3_VIEW", "FSR4_DEBUG", "FSR_SHARPNESS",
@@ -52,7 +52,7 @@ static const char *const known[] = {
"GAMEPLAY_WEAPON_WHEEL", "GAMEPLAY_WEAPON_WHEEL",
"GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "GRASS_RANGE", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "GRASS_RANGE",
"GYRO_AUTO_BIAS", "GYRO_BIAS_PAD", "GYRO_BIAS_X", "GYRO_BIAS_Y", "GYRO_BIAS_Z", "GYRO_CALIBRATION", "HDR", "HDR_GAME_NITS", "HDR_HUE", "GYRO_AUTO_BIAS", "GYRO_BIAS_PAD", "GYRO_BIAS_X", "GYRO_BIAS_Y", "GYRO_BIAS_Z", "GYRO_CALIBRATION", "HDR", "HDR_GAME_NITS", "HDR_HUE",
"HDR_PEAK_NITS", "HDR_UI_NITS", "HIGHFPS_FIX", "HUD_WIDTH", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "KSPIN_US", "LANG", "LIB_PREBUILD", "HDR_PEAK_NITS", "HDR_UI_NITS", "HEAP_LAZY", "HIGHFPS_FIX", "HUD_WIDTH", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "KSPIN_US", "LANG", "LIB_PREBUILD",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LIGHTNING_FIX", "LOCALE", "LOD_GUARD", "LOD_STEADY", "LSTICK_DEADZONE", "MAP_CLICK", "MEMORY", "MEMX", "MENU_LANG", "MENU_TEST", "MENU_FONT_FONTCONFIG", "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LIGHTNING_FIX", "LOCALE", "LOD_GUARD", "LOD_STEADY", "LSTICK_DEADZONE", "MAP_CLICK", "MEMORY", "MEMX", "MENU_LANG", "MENU_TEST", "MENU_FONT_FONTCONFIG",
"MEM_RESERVE_MIB", "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_NO_CODE", "MODS_ORDER", "MODS_REBUILD", "MODS_WITHOUT_CODE", "MOTION", "MOUSE_AIM_SCALE", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_ASPECT", "MOVIE_HOST", "MOVIE_PACE", "MEM_RESERVE_MIB", "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_NO_CODE", "MODS_ORDER", "MODS_REBUILD", "MODS_WITHOUT_CODE", "MOTION", "MOUSE_AIM_SCALE", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_ASPECT", "MOVIE_HOST", "MOVIE_PACE",
"MVOBJ_ALL", "MVOBJ_BANKS", "MVOBJ_EQUAL", "MVOBJ_EXACT", "MVOBJ_EXEC", "MVOBJ_NOC4", "MVOBJ_ONLY", "MVOBJ_TIMES", "MVPREV_CHECK", "MVPREV_GROW", "MVPREV_SKIP", "MVPREV_TRUST", "MV_CHECK", "MVOBJ_ALL", "MVOBJ_BANKS", "MVOBJ_EQUAL", "MVOBJ_EXACT", "MVOBJ_EXEC", "MVOBJ_NOC4", "MVOBJ_ONLY", "MVOBJ_TIMES", "MVPREV_CHECK", "MVPREV_GROW", "MVPREV_SKIP", "MVPREV_TRUST", "MV_CHECK",
@@ -111,7 +111,7 @@ static const struct { const char *key, *section; } sections[] = {
{"TIMER_1MS", "performance"}, {"PIPE_WAIT", "performance"}, {"PIPE_SKIP", "performance"}, {"TIMER_1MS", "performance"}, {"PIPE_WAIT", "performance"}, {"PIPE_SKIP", "performance"},
{"BARRIER_MERGE", "performance"}, {"LIB_PREBUILD", "performance"}, {"LIB_PREBUILD_THREADS", "performance"}, {"PIPE_PREBUILD", "performance"}, {"BARRIER_MERGE", "performance"}, {"LIB_PREBUILD", "performance"}, {"LIB_PREBUILD_THREADS", "performance"}, {"PIPE_PREBUILD", "performance"},
{"PREWARM_XLATE", "performance"}, {"GPL", "performance"}, {"ASTC", "performance"}, {"MEMORY", "performance"}, {"PREWARM_XLATE", "performance"}, {"GPL", "performance"}, {"ASTC", "performance"}, {"MEMORY", "performance"},
{"TEX_ALIAS", "performance"}, {"TEX_VRAM_PRESSURE", "performance"}, {"TEX_RELEASED_MIB", "performance"}, {"TEX_BLOCK_MIB", "performance"}, {"VMA_BLOCK_MIB", "performance"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"}, {"TEX_ALIAS", "performance"}, {"TEX_VRAM_PRESSURE", "performance"}, {"TEX_RELEASED_MIB", "performance"}, {"TEX_BLOCK_MIB", "performance"}, {"VMA_BLOCK_MIB", "performance"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"}, {"DEMOTE", "performance"},
{"BIND_SKIP", "performance"}, {"SHADER_MEMO", "performance"}, {"PIPE_MEMO", "performance"}, {"MEMX", "performance"}, {"BIND_INC", "performance"}, {"TEX_MEMO", "performance"}, {"VB_USED", "performance"}, {"DESC_TEMPLATE", "performance"}, {"BIND_SKIP", "performance"}, {"SHADER_MEMO", "performance"}, {"PIPE_MEMO", "performance"}, {"MEMX", "performance"}, {"BIND_INC", "performance"}, {"TEX_MEMO", "performance"}, {"VB_USED", "performance"}, {"DESC_TEMPLATE", "performance"},
{"SYNC_AHEAD", "performance"}, {"SHADOW_DEFER", "performance"}, {"PUSH_SKIP", "performance"}, {"SPLIT_DRAWS", "performance"}, {"SPLIT_US", "performance"}, {"VK_VALIDATION", "performance"}, {"SYNC_AHEAD", "performance"}, {"SHADOW_DEFER", "performance"}, {"PUSH_SKIP", "performance"}, {"SPLIT_DRAWS", "performance"}, {"SPLIT_US", "performance"}, {"VK_VALIDATION", "performance"},
{"VK_DYN_VERTEX", "performance"}, {"VK_DYN_A2C", "performance"}, {"VK_SUBGROUP_PIN", "performance"}, {"VK_DYN_VERTEX", "performance"}, {"VK_DYN_A2C", "performance"}, {"VK_SUBGROUP_PIN", "performance"},
@@ -222,7 +222,7 @@ static const CfgMeta metas[] = {
{"FREE_CORES", "0", "0|1", RESTART}, {"TIMER_1MS", "1", "0|1", RESTART}, {"FREE_CORES", "0", "0|1", RESTART}, {"TIMER_1MS", "1", "0|1", RESTART},
// shaders and pipelines // shaders and pipelines
{"PIPE_WAIT", "default", "default|draw", RESTART}, {"PIPE_SKIP", "fullscreen", "strict|any|fullscreen", RESTART}, {"PIPE_WAIT", "default", "default|draw", RESTART}, {"PIPE_SKIP", "fullscreen", "strict|any|fullscreen", RESTART},
{"BARRIER_MERGE", "0", "0|1", RESTART}, {"LIB_PREBUILD", "1", "0|1", RESTART}, {"LIB_PREBUILD_THREADS", "", "1..64", RESTART}, {"BARRIER_MERGE", "1", "0|1", RESTART}, {"LIB_PREBUILD", "1", "0|1", RESTART}, {"LIB_PREBUILD_THREADS", "", "1..64", RESTART},
{"PIPE_PREBUILD", "1", "0|1", RESTART}, {"PREWARM_XLATE", "", "1..64", RESTART}, {"GPL", "1", "0|1", RESTART}, {"PIPE_PREBUILD", "1", "0|1", RESTART}, {"PREWARM_XLATE", "", "1..64", RESTART}, {"GPL", "1", "0|1", RESTART},
// textures and memory // textures and memory
{"ASTC", "auto", "auto|gpu|native|cpu", RESTART}, {"MEMORY", "auto", "auto|import|mirror|verify", RESTART}, {"ASTC", "auto", "auto|gpu|native|cpu", RESTART}, {"MEMORY", "auto", "auto|import|mirror|verify", RESTART},
@@ -232,6 +232,7 @@ static const CfgMeta metas[] = {
{"OPTREF_GUARD", "1", "0|1", RESTART}, {"ABILITY_GUARD", "1", "0|1", RESTART}, {"REPORT_GUARD", "1", "0|1", RESTART}, {"OPTREF_GUARD", "1", "0|1", RESTART}, {"ABILITY_GUARD", "1", "0|1", RESTART}, {"REPORT_GUARD", "1", "0|1", RESTART},
// render fixes // render fixes
{"LOD_GUARD", "1", "0|1", RESTART}, {"FIX_C0", "1", "0|1", RESTART}, {"FIX_ZERO", "1", "0|1", RESTART}, {"LOD_GUARD", "1", "0|1", RESTART}, {"FIX_C0", "1", "0|1", RESTART}, {"FIX_ZERO", "1", "0|1", RESTART},
{"DEMOTE", "", "0|1", RESTART}, // vk_pipeline.c spirv_demote: 1 on AMD's own driver, else 0
{"BIND_SKIP", "1", "0|1", RESTART}, {"SHADER_MEMO", "1", "0|1", RESTART}, {"PIPE_MEMO", "1", "0|1", RESTART}, {"MEMX", "1", "0|1|check", RESTART}, {"BIND_INC", "0", "0|1|check", RESTART}, {"TEX_MEMO", "1", "0|1", RESTART}, {"BIND_SKIP", "1", "0|1", RESTART}, {"SHADER_MEMO", "1", "0|1", RESTART}, {"PIPE_MEMO", "1", "0|1", RESTART}, {"MEMX", "1", "0|1|check", RESTART}, {"BIND_INC", "0", "0|1|check", RESTART}, {"TEX_MEMO", "1", "0|1", RESTART},
{"VB_USED", "1", "0|1", RESTART}, {"VB_USED", "1", "0|1", RESTART},
{"DESC_TEMPLATE", "1", "0|1", RESTART}, {"DESC_TEMPLATE", "1", "0|1", RESTART},
+1
View File
@@ -62,6 +62,7 @@ static float sample(V p, float *r, float *g, float *b) {
float a = ds < -0.8f ? 1 : (0.8f - ds) / 1.6f; float a = ds < -0.8f ? 1 : (0.8f - ds) / 1.6f;
return 0.38f * a; return 0.38f * a;
} }
*r = *g = *b = 0;
return 0; return 0;
} }
+1
View File
@@ -1024,6 +1024,7 @@ static uint32_t write_file(uint64_t h, int64_t offset, const void *buffer, uint6
if (!plat_file_id(f, &id)) rt_fatal("fs: host save size"); if (!plat_file_id(f, &id)) rt_fatal("fs: host save size");
if ((uint64_t)offset + size > id.size && !(mode & FS_OPEN_APPEND)) return FS_R_APPEND_REQUIRED; if ((uint64_t)offset + size > id.size && !(mode & FS_OPEN_APPEND)) return FS_R_APPEND_REQUIRED;
if (file->save) save_touched(); if (file->save) save_touched();
mem_heap_commit((uintptr_t)buffer, size); // TOTK_HEAP_LAZY: the kernel reads the buffer, so its chunks must exist
for (uint64_t done = 0; done < size;) { for (uint64_t done = 0; done < size;) {
uint32_t chunk = size - done > 0x40000000 ? 0x40000000 : (uint32_t)(size - done); uint32_t chunk = size - done > 0x40000000 ? 0x40000000 : (uint32_t)(size - done);
int64_t put = plat_file_pwrite(f, (const uint8_t *)buffer + done, chunk, (uint64_t)offset + done); int64_t put = plat_file_pwrite(f, (const uint8_t *)buffer + done, chunk, (uint64_t)offset + done);
+3
View File
@@ -27,6 +27,8 @@
#include "vk.h" #include "vk.h"
#include "platform/platform.h" #include "platform/platform.h"
int swkbd_sdl_event(const SDL_Event *e); // swkbd_sdl.c: the text entry window's events
static SDL_Window *g_win; static SDL_Window *g_win;
static uint32_t g_ev_base; // SDL_RegisterEvents: the user events below static uint32_t g_ev_base; // SDL_RegisterEvents: the user events below
enum { EV_RUN, EV_SETTINGS, EV_CLOSE, EV_COUNT }; enum { EV_RUN, EV_SETTINGS, EV_CLOSE, EV_COUNT };
@@ -158,6 +160,7 @@ static void handle(const SDL_Event *e) {
} }
if (e->type == g_ev_base + EV_CLOSE) gfx_window_closed(); if (e->type == g_ev_base + EV_CLOSE) gfx_window_closed();
if (!g_win) return; if (!g_win) return;
if (swkbd_sdl_event(e)) return;
input_sdl_event(e); input_sdl_event(e);
menu_sdl_event(e); menu_sdl_event(e);
switch (e->type) { switch (e->type) {
+8
View File
@@ -177,6 +177,14 @@ void mem_thaw(uint64_t a, uint64_t n); // makes the frozen r
void mem_freeze_stats(uint64_t *frozen, uint64_t *freezes, uint64_t *fault_thaws, uint64_t *other_thaws); void mem_freeze_stats(uint64_t *frozen, uint64_t *freezes, uint64_t *fault_thaws, uint64_t *other_thaws);
// regions frozen now; freezes and thaws since the last call // regions frozen now; freezes and thaws since the last call
void mem_kernel_free(void *p, uint64_t size); // TLR/TLS reuse after thread exit void mem_kernel_free(void *p, uint64_t size); // TLR/TLS reuse after thread exit
int mem_heap_lazy(void); // TOTK_HEAP_LAZY is on (Windows): heap pages commit on first use
void mem_heap_commit(uint64_t a, uint64_t n); // commits the not yet committed heap chunks of [a, a+n) before
// the kernel reads them; nothing when mem_heap_lazy is 0
void mem_heap_lazy_stats(uint64_t *faults, uint64_t *ns, uint64_t *committed, uint64_t *size);
// TOTK_HEAP_LAZY: first-use faults and their time since
// the start, committed heap bytes, heap size
uint64_t mem_heap_uncommitted(void); // heap bytes set by SetHeapSize but not committed yet
// (TOTK_HEAP_LAZY): commit the game can still claim
int mem_guest_readable(uint64_t a, uint64_t n); // [a, a+n) can be read without a fault: inside a loaded int mem_guest_readable(uint64_t a, uint64_t n); // [a, a+n) can be read without a fault: inside a loaded
// module or the committed heap answered from the layout, // module or the committed heap answered from the layout,
// anything else by plat_mem_readable (an OS query) // anything else by plat_mem_readable (an OS query)
+7 -2
View File
@@ -66,7 +66,11 @@ void ipc_handle_closed(int kind, void *obj) {
} }
// ---- helpers for services // ---- helpers for services
static int readable(uint64_t a, uint64_t n) { return plat_mem_readable(a, n); } // With TOTK_HEAP_LAZY the heap by the layout (its pages may not be committed before first use), anything else by
// the OS; without it the OS for everything, as before.
static int readable(uint64_t a, uint64_t n) {
return mem_heap_lazy() ? mem_guest_readable(a, n) : plat_mem_readable(a, n);
}
void ipc_backtrace(void) { void ipc_backtrace(void) {
const Cpu *c = t_req; const Cpu *c = t_req;
@@ -422,11 +426,12 @@ static void msg_parse(const uint32_t *m, int tipc, Reply *r) {
} }
// One request on the TLR message buffer; the kernel result of SendSyncRequest, the service result in r->result. // One request on the TLR message buffer; the kernel result of SendSyncRequest, the service result in r->result.
// A kernel failure has no reply: clear it before the probe reads fields in a failure diagnostic.
static uint32_t call(Cpu *c, uint32_t h, const Msg *q, Reply *r) { static uint32_t call(Cpu *c, uint32_t h, const Msg *q, Reply *r) {
uint32_t *m = (uint32_t *)(uintptr_t)c->tpidrro; uint32_t *m = (uint32_t *)(uintptr_t)c->tpidrro;
msg_build(m, q); msg_build(m, q);
uint32_t k = sv(c, 0x21, h, 0, 0, 0); uint32_t k = sv(c, 0x21, h, 0, 0, 0);
if (k) return k; if (k) { memset(r, 0, sizeof *r); return k; }
msg_parse(m, q->type >= T_TIPC_BASE, r); msg_parse(m, q->type >= T_TIPC_BASE, r);
return 0; return 0;
} }
+125 -3
View File
@@ -108,10 +108,13 @@ static void thaw_range_locked(uint64_t a, uint64_t n, int why) {
for (uint64_t r = r0; r <= r1; r++) thaw_locked(r, why); for (uint64_t r = r0; r <= r1; r++) thaw_locked(r, why);
} }
static void heap_commit_range(uint64_t a, uint64_t n);
void mem_thaw(uint64_t a, uint64_t n) { void mem_thaw(uint64_t a, uint64_t n) {
plat_mutex_lock(&frz_lock); // also when nothing is frozen: the hold keeps a read's buffer writable plat_mutex_lock(&frz_lock); // also when nothing is frozen: the hold keeps a read's buffer writable
thaw_range_locked(a, n, 2); thaw_range_locked(a, n, 2);
plat_mutex_unlock(&frz_lock); plat_mutex_unlock(&frz_lock);
heap_commit_range(a, n);
} }
// frz_lock held exclusively. Makes the committed pages of region r read-only when every one of them is read-write; // frz_lock held exclusively. Makes the committed pages of region r read-only when every one of them is read-write;
@@ -200,6 +203,105 @@ static void commit(uint64_t a, uint64_t n, const char *what) {
rt_fatal("memory: commit %s %#llx+%#llx failed", what, (unsigned long long)a, (unsigned long long)n); rt_fatal("memory: commit %s %#llx+%#llx failed", what, (unsigned long long)a, (unsigned long long)n);
} }
// ---- heap pages committed on first use (Windows)
// SetHeapSize asks for the game's whole heap at once (1.4.3: about 2.1 GiB at boot), and Windows charges every
// committed page against the system's commit limit, backed by RAM or the page file, whether the game touches it or not.
// In a sky-island scene it had touched about two thirds. With TOTK_HEAP_LAZY=1 (Windows, off by default) the part
// SetHeapSize adds stays reserved: the first read or write of a reserved page faults, and heap_fault commits its
// LAZY_CHUNK and retries. Freshly committed pages read as zero, as the Switch's heap does. Access by the kernel or the GPU
// driver does not fault: a file read into the heap, a save written from it and a Vulkan import of it would fail on a
// reserved page. File reads and Vulkan imports call mem_thaw first, so mem_thaw commits the reserved chunks of its
// range too (heap_commit_range); save writes only need the pages to exist and call mem_heap_commit. Linux backs mprotect'ed pages on first use by itself and keeps committing eagerly.
//
// lazy_map holds one byte per chunk, set once the chunk is committed, so neither path asks the OS for the page state:
// a VirtualQuery costs tens of microseconds here, and the write faults of frozen pool regions (thaw_fault) come through
// heap_fault first. Only whole chunks are committed and only when their byte is clear: VirtualAlloc(MEM_COMMIT) over
// committed pages would set them read-write again and undo a freeze.
#ifndef LAZY_CHUNK
#define LAZY_CHUNK 0x100000ull // divides the 2 MiB granularity of SetHeapSize
#endif
static int heap_lazy;
static uint8_t *lazy_map; // per chunk of L.heap: 1 committed; written under lazy_lock
static PlatMutex lazy_lock = PLAT_MUTEX_INIT; // commits and the heap's shrink; never held across a guest access
static volatile uint64_t heap_committed; // bytes of committed chunks (lazy mode), exact
static volatile int64_t lazy_faults, lazy_ns;
// Commits the clear chunks among [i0, i1) of the heap's first `size` bytes, runs of them in one call.
static void heap_commit_chunks(uint64_t i0, uint64_t i1, uint64_t size, const char *what) {
uint64_t base = L.heap.base, top = base + size;
plat_mutex_lock(&lazy_lock);
for (uint64_t i = i0; i < i1;) {
if (lazy_map[i]) { i++; continue; }
uint64_t j = i;
while (j < i1 && !lazy_map[j]) j++;
uint64_t lo = base + i * LAZY_CHUNK, hi = base + j * LAZY_CHUNK;
if (hi > top) hi = top;
commit(lo, hi - lo, what);
__atomic_add_fetch(&heap_committed, hi - lo, __ATOMIC_RELAXED);
for (uint64_t k = i; k < j; k++) __atomic_store_n(&lazy_map[k], 1, __ATOMIC_RELEASE);
i = j;
}
plat_mutex_unlock(&lazy_lock);
}
static void heap_commit_range(uint64_t a, uint64_t n) {
if (!heap_lazy || !n) return;
uint64_t base = L.heap.base, size = __atomic_load_n(&heap_size, __ATOMIC_ACQUIRE), top = base + size;
uint64_t lo = a > base ? a : base, hi = a + n < a || a + n > top ? top : a + n;
if (lo >= hi) return;
uint64_t i0 = (lo - base) / LAZY_CHUNK, i1 = (hi - base + LAZY_CHUNK - 1) / LAZY_CHUNK, i = i0;
while (i < i1 && __atomic_load_n(&lazy_map[i], __ATOMIC_ACQUIRE)) i++; // the usual case: all committed, no lock
if (i < i1) heap_commit_chunks(i, i1, size, "heap pages for a file, save or import");
}
// The platform's fault hook, ahead of thaw_fault: 1 retries the access. A committed chunk's fault is not this one's
// (a frozen page, or a guest error); heap_fault_raced catches a chunk committed by another thread in between.
static int heap_fault(uint64_t a) {
if (!heap_lazy) return 0;
uint64_t base = L.heap.base, size = __atomic_load_n(&heap_size, __ATOMIC_ACQUIRE);
if (a < base || a - base >= size) return 0;
uint64_t i = (a - base) / LAZY_CHUNK;
if (__atomic_load_n(&lazy_map[i], __ATOMIC_ACQUIRE)) return 0;
uint64_t t0 = plat_now_ns();
heap_commit_chunks(i, i + 1, size, "heap on first use");
int64_t ns = (int64_t)__atomic_add_fetch(&lazy_ns, (int64_t)(plat_now_ns() - t0), __ATOMIC_RELAXED);
int64_t n = (int64_t)plat_inc64(&lazy_faults);
if (!(n % (int64_t)((512ull << 20) / LAZY_CHUNK))) // every 512 MiB of chunks: how often and at what cost
rt_log("memory: heap committed on first use: %lld faults, %.1f ms in all (%.1f us each); heap %llu of %llu MiB "
"committed", (long long)n, (double)ns / 1e6, (double)ns / 1e3 / (double)n,
(unsigned long long)(__atomic_load_n(&heap_committed, __ATOMIC_RELAXED) >> 20),
(unsigned long long)(size >> 20));
return 1;
}
// Last, after thaw_fault declined: a chunk another thread committed between this thread's fault and heap_fault's read
// of lazy_map. Asks the OS, which only the faults no hook takes (a crash on its way) pay for.
static int heap_fault_raced(uint64_t a) {
uint64_t base = L.heap.base, size = __atomic_load_n(&heap_size, __ATOMIC_ACQUIRE), end;
if (!heap_lazy || a < base || a - base >= size) return 0;
return plat_mem_state(a & ~(PAGE - 1), (a & ~(PAGE - 1)) + PAGE, &end) == PLAT_PROT_RW;
}
int mem_heap_lazy(void) { return heap_lazy; }
void mem_heap_commit(uint64_t a, uint64_t n) { heap_commit_range(a, n); }
void mem_heap_lazy_stats(uint64_t *faults, uint64_t *ns, uint64_t *committed, uint64_t *size) {
*faults = (uint64_t)__atomic_load_n(&lazy_faults, __ATOMIC_RELAXED);
*ns = (uint64_t)__atomic_load_n(&lazy_ns, __ATOMIC_RELAXED);
*committed = __atomic_load_n(&heap_committed, __ATOMIC_RELAXED);
*size = __atomic_load_n(&heap_size, __ATOMIC_ACQUIRE);
}
uint64_t mem_heap_uncommitted(void) {
if (!heap_lazy) return 0;
uint64_t size = __atomic_load_n(&heap_size, __ATOMIC_ACQUIRE), done = __atomic_load_n(&heap_committed, __ATOMIC_RELAXED);
return size > done ? size - done : 0;
}
static int thaw_fault(uint64_t a);
static int mem_fault(uint64_t a) { return heap_fault(a) || thaw_fault(a) || heap_fault_raced(a); }
static void decommit(uint64_t a, uint64_t n, const char *what) { static void decommit(uint64_t a, uint64_t n, const char *what) {
plat_mutex_lock(&frz_lock); plat_mutex_lock(&frz_lock);
thaw_range_locked(a, n, 3); thaw_range_locked(a, n, 3);
@@ -253,12 +355,17 @@ void mem_init(void) {
if (reserve_at(at, ALIAS_SIZE, 1)) alias = at; if (reserve_at(at, ALIAS_SIZE, 1)) alias = at;
if (!alias) reexec_or_fail("a 64 GiB alias region below 2^39"); if (!alias) reexec_or_fail("a 64 GiB alias region below 2^39");
plat_mem_fault_hook(thaw_fault); // before the crash handler plat_mem_fault_hook(mem_fault); // before the crash handler
alias_pages = calloc(ALIAS_PAGES, 1); alias_pages = calloc(ALIAS_PAGES, 1);
if (!alias_pages) rt_fatal("memory: cannot allocate the alias page map"); if (!alias_pages) rt_fatal("memory: cannot allocate the alias page map");
// totk.ini is read here, once the address space is claimed and before the first setting: the pool size below // totk.ini is read here, once the address space is claimed and before the first setting: the pool size below
// depends on TOTK_APP_POOL and on the resolution settings (resolution.c decides them once, on this first call). // depends on TOTK_APP_POOL and on the resolution settings (resolution.c decides them once, on this first call).
cfg_init(); cfg_init();
#ifdef _WIN32
const char *lazy = cfg_get("TOTK_HEAP_LAZY");
heap_lazy = lazy && atoi(lazy) != 0; // opt-in: an untouched heap page then faults on its first read too
plat_mem_fault_reads(heap_lazy);
#endif
const char *pool = cfg_get("TOTK_APP_POOL"); const char *pool = cfg_get("TOTK_APP_POOL");
L = (RtGuestLayout){ L = (RtGuestLayout){
.aslr = {low, RT_ADDRESS_LIMIT - low}, .aslr = {low, RT_ADDRESS_LIMIT - low},
@@ -271,6 +378,8 @@ void mem_init(void) {
: DEFAULT_POOL + res_heap_extra_bytes() + res_tex_heap_extra_bytes() + res_grass_heap_extra_bytes(), : DEFAULT_POOL + res_heap_extra_bytes() + res_tex_heap_extra_bytes() + res_grass_heap_extra_bytes(),
}; };
if (!L.pool) rt_fatal("memory: TOTK_APP_POOL is 0"); if (!L.pool) rt_fatal("memory: TOTK_APP_POOL is 0");
if (heap_lazy && !(lazy_map = calloc(L.heap.size / LAZY_CHUNK + 1, 1)))
rt_fatal("memory: cannot allocate the heap chunk map");
} }
const RtGuestLayout *mem_layout(void) { return &L; } const RtGuestLayout *mem_layout(void) { return &L; }
@@ -306,8 +415,21 @@ uint32_t mem_set_heap_size(uint64_t size, uint64_t *addr) {
plat_mutex_unlock(&lock); plat_mutex_unlock(&lock);
return R_INVALID_STATE; return R_INVALID_STATE;
} }
if (size > heap_size) commit(L.heap.base + heap_size, size - heap_size, "heap"); if (size > heap_size && !heap_lazy) commit(L.heap.base + heap_size, size - heap_size, "heap"); // else heap_fault
if (size < heap_size) decommit(L.heap.base + size, heap_size - size, "heap"); if (size < heap_size && heap_lazy) { // the chunks above the new size go back to reserved
plat_mutex_lock(&lazy_lock);
for (uint64_t i = size / LAZY_CHUNK, end = (heap_size + LAZY_CHUNK - 1) / LAZY_CHUNK; i < end; i++)
if (lazy_map[i]) {
uint64_t lo = L.heap.base + i * LAZY_CHUNK, hi = lo + LAZY_CHUNK;
if (hi > L.heap.base + heap_size) hi = L.heap.base + heap_size;
decommit(lo, hi - lo, "heap");
__atomic_sub_fetch(&heap_committed, hi - lo, __ATOMIC_RELAXED);
__atomic_store_n(&lazy_map[i], 0, __ATOMIC_RELEASE);
}
plat_mutex_unlock(&lazy_lock);
} else if (size < heap_size) {
decommit(L.heap.base + size, heap_size - size, "heap");
}
heap_size = size; heap_size = size;
plat_mutex_unlock(&lock); plat_mutex_unlock(&lock);
if (addr) *addr = L.heap.base; if (addr) *addr = L.heap.base;
+2
View File
@@ -985,6 +985,8 @@ void plat_mem_fault_hook(int (*fn)(uint64_t addr)) {
fault_install(); fault_install();
} }
void plat_mem_fault_reads(int on) { (void)on; }
void plat_crash_hook(void (*fn)(const PlatCrash *c)) { void plat_crash_hook(void (*fn)(const PlatCrash *c)) {
crash_fn = fn; crash_fn = fn;
fault_install(); fault_install();
+3
View File
@@ -220,6 +220,9 @@ uint64_t plat_mem_written(uint64_t addr, uint64_t n, uint64_t *pages, uint64_t m
// A write that faulted on a read-only page at addr goes to fn first; fn returns 1 when it made the page writable and // A write that faulted on a read-only page at addr goes to fn first; fn returns 1 when it made the page writable and
// the write should run again, 0 to let the fault go on (to the crash handler). One hook per process. // the write should run again, 0 to let the fault go on (to the crash handler). One hook per process.
void plat_mem_fault_hook(int (*fn)(uint64_t addr)); void plat_mem_fault_hook(int (*fn)(uint64_t addr));
// Read faults go to the hook too (memory.c heap_fault, TOTK_HEAP_LAZY): Windows only, before the game starts; a no-op
// on Linux, which commits on first use by itself.
void plat_mem_fault_reads(int on);
// Starts this program again with the same arguments and ends this process with the new one's exit code (Windows), or // Starts this program again with the same arguments and ends this process with the new one's exit code (Windows), or
// replaces this process with it (Linux). Environment changes made before the call are passed on. // replaces this process with it (Linux). Environment changes made before the call are passed on.
_Noreturn void plat_reexec(void); _Noreturn void plat_reexec(void);
+10 -2
View File
@@ -721,10 +721,16 @@ uint64_t plat_mem_written(uint64_t addr, uint64_t n, uint64_t *pages, uint64_t m
static int (*fault_hook)(uint64_t addr); static int (*fault_hook)(uint64_t addr);
// A write access violation (ExceptionInformation[0] == 1) goes to the hook; registered first, before the crash handler. static ULONG_PTR fault_kinds = 1; // highest ExceptionInformation[0] the hook takes: 1 writes, 0 also reads
// A write access violation (ExceptionInformation[0] == 1) goes to the hook, and a read (0) too once
// plat_mem_fault_reads asked for it; registered first, before the crash handler. Writes thaw frozen regions; with
// TOTK_HEAP_LAZY reads and writes both commit heap pages on first use (memory.c, heap_fault). An execute fault (8) is
// never the hook's.
static LONG CALLBACK fault_veh(EXCEPTION_POINTERS *ep) { static LONG CALLBACK fault_veh(EXCEPTION_POINTERS *ep) {
const EXCEPTION_RECORD *er = ep->ExceptionRecord; const EXCEPTION_RECORD *er = ep->ExceptionRecord;
if (er->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || er->NumberParameters < 2 || er->ExceptionInformation[0] != 1) ULONG_PTR kind = er->NumberParameters >= 2 ? er->ExceptionInformation[0] : 8;
if (er->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || kind > 1 || (kind == 0 && fault_kinds != 0))
return EXCEPTION_CONTINUE_SEARCH; return EXCEPTION_CONTINUE_SEARCH;
return fault_hook((uint64_t)er->ExceptionInformation[1]) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; return fault_hook((uint64_t)er->ExceptionInformation[1]) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH;
} }
@@ -734,6 +740,8 @@ void plat_mem_fault_hook(int (*fn)(uint64_t addr)) {
AddVectoredExceptionHandler(1, fault_veh); AddVectoredExceptionHandler(1, fault_veh);
} }
void plat_mem_fault_reads(int on) { fault_kinds = on ? 0 : 1; }
static void (*crash_fn)(const PlatCrash *c); static void (*crash_fn)(const PlatCrash *c);
// The faulting thread's general registers, for the report to tie the faulting instruction to its operands. // The faulting thread's general registers, for the report to tie the faulting instruction to its operands.
+5 -1
View File
@@ -31,7 +31,11 @@ RtStats rt_stats(void) {
return (RtStats){__atomic_load_n(&g_svcs, __ATOMIC_RELAXED), kern_threads_created(), hostfn_calls()}; return (RtStats){__atomic_load_n(&g_svcs, __ATOMIC_RELAXED), kern_threads_created(), hostfn_calls()};
} }
static int readable(uint64_t a, uint64_t n) { return plat_mem_readable(a, n); } // With TOTK_HEAP_LAZY the heap by the layout (its pages may not be committed before first use), anything else by
// the OS; without it the OS for everything, as before.
static int readable(uint64_t a, uint64_t n) {
return mem_heap_lazy() ? mem_guest_readable(a, n) : plat_mem_readable(a, n);
}
void kern_backtrace(const Cpu *c) { void kern_backtrace(const Cpu *c) {
char d[160]; char d[160];
+235 -10
View File
@@ -1,21 +1,246 @@
// The software keyboard's front end for SDL windows (swkbd.h). Until the in-game text field exists (an ImGui entry in // The software keyboard's front end for SDL windows (swkbd.h): a text window of its own, opened on the window thread
// the menu overlay, which SDL_StartTextInput can pair with the Steam Deck's on-screen keyboard), the text entry takes // (gfx_window_sdl_run) and fed by that thread's events. The keyboard types, Backspace deletes, Enter is OK and Escape
// the starting text at once, as TOTK_SWKBD_ANSWER=<initial> does: the game's initial text, else the default name from // cancels. The controller moves a letter grid: D-pad moves the cursor, the bottom button adds the letter, the right
// the catalog. TotK asks only for a horse's name. TOTK_SWKBD_TEST=cancel stands for Cancel pressed, as in the Win32 // button deletes, Start is OK and the top button cancels. The guest thread waits for the answer. Without a game window
// window. // it takes the starting text at once.
#include <stdio.h>
#include <string.h> #include <string.h>
#include <SDL3/SDL.h>
#include "cfg.h" #include "cfg.h"
#include "host.h" #include "host.h"
#include "input_sdl.h"
#include "platform/platform.h"
#include "swkbd.h" #include "swkbd.h"
#include "ui_text.h"
#define GRID_COLS 10
static const char grid_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.";
#define GRID_N ((int)(sizeof grid_chars - 1))
typedef struct {
const SwkbdRequest *req;
uint16_t text[KB_LIMIT + 1];
size_t n;
int sel; // the grid cell the controller's cursor is on
int result; // 1 OK, -1 Cancel, 0 still open
int open;
SDL_Window *win;
SDL_Renderer *ren;
Uint32 id;
PlatEvent done;
} Box;
static Box *g_box; // one text entry at a time (swkbd.c holds the lock)
static void draw(const Box *b) {
char prompt[0x101 * 3 + 1], text[KB_LIMIT * 3 + 2], line[KB_LIMIT * 3 + 2];
size_t pl = 0;
while (pl < 0x100 && b->req->prompt[pl]) pl++;
if (pl) swkbd_utf16_to_utf8(b->req->prompt, pl, prompt, sizeof prompt);
else snprintf(prompt, sizeof prompt, "%s", ui_text(UI_SWKBD_PROMPT));
if (b->req->password) { // one star per character, not per UTF-16 unit
size_t k = 0;
for (size_t i = 0; i < b->n && k < KB_LIMIT; i++)
if (b->text[i] < 0xdc00 || b->text[i] >= 0xe000) text[k++] = '*';
text[k] = 0;
} else {
swkbd_utf16_to_utf8(b->text, b->n, text, sizeof text);
}
snprintf(line, sizeof line, "%s_", text);
SDL_SetRenderDrawColor(b->ren, 24, 24, 32, 255);
SDL_RenderClear(b->ren);
SDL_SetRenderScale(b->ren, 4.0f, 4.0f);
SDL_SetRenderDrawColor(b->ren, 240, 240, 240, 255);
SDL_RenderDebugText(b->ren, 4, 4, prompt);
SDL_RenderDebugText(b->ren, 4, 20, line);
for (int i = 0; i < GRID_N; i++) {
float x = 4.0f + (float)(i % GRID_COLS) * 14.0f, y = 40.0f + (float)(i / GRID_COLS) * 18.0f;
char c[2] = {grid_chars[i], 0};
if (i == b->sel) {
SDL_FRect cell = {x - 2.0f, y - 2.0f, 12.0f, 12.0f};
SDL_SetRenderDrawColor(b->ren, 200, 160, 40, 255);
SDL_RenderFillRect(b->ren, &cell);
SDL_SetRenderDrawColor(b->ren, 24, 24, 32, 255);
}
SDL_RenderDebugText(b->ren, x, y, c);
SDL_SetRenderDrawColor(b->ren, 240, 240, 240, 255);
}
// the debug font draws ASCII: the hints are the catalog's English text whatever the game's language
SDL_RenderDebugText(b->ren, 4, 116, ui_text_in("en", UI_SWKBD_SDL_KEYS_HINT));
SDL_RenderDebugText(b->ren, 4, 130, ui_text_in("en", UI_SWKBD_SDL_PAD_HINT1));
SDL_RenderDebugText(b->ren, 4, 144, ui_text_in("en", UI_SWKBD_SDL_PAD_HINT2));
SDL_RenderPresent(b->ren);
}
static void close_box(Box *b);
static void open_box(void *arg) {
Box *b = arg;
b->win = SDL_CreateWindow(ui_text(UI_SWKBD_TITLE), 1280, 720, 0);
if (!b->win) {
rt_log("swkbd: cannot open the text entry window (%s)", SDL_GetError());
return;
}
b->ren = SDL_CreateRenderer(b->win, NULL);
if (!b->ren) {
rt_log("swkbd: no renderer for the text entry (%s)", SDL_GetError());
SDL_DestroyWindow(b->win);
b->win = NULL;
return;
}
b->id = SDL_GetWindowID(b->win);
b->open = 1;
g_box = b;
SDL_StartTextInput(b->win);
SDL_RaiseWindow(b->win);
draw(b);
const char *test = cfg_get("TOTK_SWKBD_TEST");
if (test && !strcmp(test, "ok")) { // as the Win32 window: OK pressed at once
b->result = 1;
close_box(b);
}
}
static void close_box(Box *b) {
SDL_StopTextInput(b->win);
SDL_DestroyRenderer(b->ren);
SDL_DestroyWindow(b->win);
b->win = NULL;
b->ren = NULL;
g_box = NULL;
plat_event_set(&b->done);
}
// Appends typed UTF-16 within the game's limits: a surrogate pair goes in whole or not at all (as clean in swkbd.c),
// and a number pad takes digits only.
static void add_text(Box *b, const uint16_t *u, size_t k) {
const SwkbdRequest *r = b->req;
size_t max = (size_t)r->max_len < KB_LIMIT ? (size_t)r->max_len : KB_LIMIT;
for (size_t i = 0; i < k; i++) {
int pair = u[i] >= 0xd800 && u[i] < 0xdc00 && i + 1 < k && u[i + 1] >= 0xdc00 && u[i + 1] < 0xe000;
if (pair) {
if (!r->numeric && b->n + 2 <= max) b->text[b->n++] = u[i], b->text[b->n++] = u[i + 1];
i++;
} else if (b->n < max && swkbd_allowed(u[i], r->disabled, r->numeric)) {
b->text[b->n++] = u[i];
}
}
}
static void delete_last(Box *b) {
if (!b->n) return;
int pair = b->n >= 2 && b->text[b->n - 1] >= 0xdc00 && b->text[b->n - 1] < 0xe000 && b->text[b->n - 2] >= 0xd800 &&
b->text[b->n - 2] < 0xdc00;
b->n -= pair ? 2 : 1;
}
static void pad_button(Box *b, Uint8 button) {
switch (button) {
case SDL_GAMEPAD_BUTTON_DPAD_LEFT:
if (b->sel % GRID_COLS) b->sel--;
break;
case SDL_GAMEPAD_BUTTON_DPAD_RIGHT:
if (b->sel + 1 < GRID_N && (b->sel + 1) % GRID_COLS) b->sel++;
break;
case SDL_GAMEPAD_BUTTON_DPAD_UP:
if (b->sel >= GRID_COLS) b->sel -= GRID_COLS;
break;
case SDL_GAMEPAD_BUTTON_DPAD_DOWN:
if (b->sel + GRID_COLS < GRID_N) b->sel += GRID_COLS;
break;
case SDL_GAMEPAD_BUTTON_SOUTH: {
uint16_t one = (uint16_t)grid_chars[b->sel];
add_text(b, &one, 1);
break;
}
case SDL_GAMEPAD_BUTTON_EAST:
delete_last(b);
break;
case SDL_GAMEPAD_BUTTON_START:
if ((int)b->n >= b->req->min_len) b->result = 1;
break;
case SDL_GAMEPAD_BUTTON_NORTH:
b->result = -1;
break;
default:
break;
}
}
// The window thread's events for the text entry; returns 1 when the event was the text entry's.
int swkbd_sdl_event(const SDL_Event *e) {
Box *b = g_box;
if (!b) return 0;
if (e->type == SDL_EVENT_GAMEPAD_BUTTON_DOWN) {
pad_button(b, e->gbutton.button);
if (b->result) close_box(b);
else draw(b);
return 1;
}
Uint32 id;
switch (e->type) {
case SDL_EVENT_TEXT_INPUT: id = e->text.windowID; break;
case SDL_EVENT_KEY_DOWN: id = e->key.windowID; break;
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
case SDL_EVENT_WINDOW_EXPOSED: id = e->window.windowID; break;
default: return 0;
}
if (id != b->id) return 0;
const SwkbdRequest *r = b->req;
if (e->type == SDL_EVENT_WINDOW_CLOSE_REQUESTED) {
b->result = -1;
} else if (e->type == SDL_EVENT_WINDOW_EXPOSED) {
draw(b); // the compositor dropped the contents
return 1;
} else if (e->type == SDL_EVENT_TEXT_INPUT) {
uint16_t u[KB_LIMIT + 1];
size_t k = swkbd_utf8_to_utf16(e->text.text, u, KB_LIMIT + 1);
add_text(b, u, k);
} else {
switch (e->key.scancode) {
case SDL_SCANCODE_BACKSPACE:
delete_last(b);
break;
case SDL_SCANCODE_RETURN:
case SDL_SCANCODE_KP_ENTER:
if ((int)b->n >= r->min_len) b->result = 1;
break;
case SDL_SCANCODE_ESCAPE:
b->result = -1;
break;
default:
break;
}
}
if (b->result) close_box(b);
else draw(b);
return 1;
}
int text_entry_run(const SwkbdRequest *req, uint16_t *out, size_t cap, size_t *n) { int text_entry_run(const SwkbdRequest *req, uint16_t *out, size_t cap, size_t *n) {
const char *test = cfg_get("TOTK_SWKBD_TEST"); const char *test = cfg_get("TOTK_SWKBD_TEST");
if (test && !strcmp(test, "cancel")) { *n = 0; return 0; } if (test && !strcmp(test, "cancel")) { *n = 0; return 0; }
Box b = {.req = req};
size_t k = 0; size_t k = 0;
while (k < cap && req->initial[k]) k++; while (k < KB_LIMIT && req->initial[k]) k++;
memcpy(out, req->initial, k * 2); memcpy(b.text, req->initial, k * 2);
*n = k; b.n = k;
rt_log("swkbd: no text entry window on this host yet: the %s name is taken", req->game_initial ? "game's" : "default"); if (gfx_window_sdl()) {
return k > 0; plat_event_init(&b.done, 1, 0);
gfx_window_sdl_run(open_box, &b);
}
if (!b.open) {
rt_log("swkbd: no text entry window on this host: the %s name is taken", req->game_initial ? "game's" : "default");
size_t f = b.n < cap ? b.n : cap;
memcpy(out, b.text, f * 2);
*n = f;
return f > 0;
}
plat_event_wait(&b.done);
if (b.result != 1) { *n = 0; return 0; }
*n = b.n < cap ? b.n : cap;
memcpy(out, b.text, *n * 2);
return 1;
} }
+5
View File
@@ -40,6 +40,11 @@ typedef struct { const char *lang; const char *const *text; } Row;
static const char *const text_en[UI_TEXT_COUNT] = { static const char *const text_en[UI_TEXT_COUNT] = {
SWKBD("Text entry", "Enter a name", "Horse", "OK", "Cancel", "Controller: A = OK, B = Cancel"), SWKBD("Text entry", "Enter a name", "Horse", "OK", "Cancel", "Controller: A = OK, B = Cancel"),
// The SDL text entry draws with SDL's ASCII debug font, so these three exist in English only (the other rows fall
// back to it).
[UI_SWKBD_SDL_KEYS_HINT] = "Keys: type, Enter OK, Esc cancel",
[UI_SWKBD_SDL_PAD_HINT1] = "Pad: D-pad move, bottom add, right del",
[UI_SWKBD_SDL_PAD_HINT2] = "Start OK, top cancel",
[UI_MENU_TITLE] = "Settings", [UI_MENU_TITLE] = "Settings",
[UI_MENU_TAB_SCREEN] = "Screen", [UI_MENU_TAB_GAME] = "Game", [UI_MENU_TAB_MODS] = "Mods", [UI_MENU_TAB_SOUND] = "Sound", [UI_MENU_TAB_SCREEN] = "Screen", [UI_MENU_TAB_GAME] = "Game", [UI_MENU_TAB_MODS] = "Mods", [UI_MENU_TAB_SOUND] = "Sound",
+3
View File
@@ -10,6 +10,9 @@ typedef enum {
UI_SWKBD_OK, UI_SWKBD_OK,
UI_SWKBD_CANCEL, UI_SWKBD_CANCEL,
UI_SWKBD_PAD_HINT, // how a controller answers UI_SWKBD_PAD_HINT, // how a controller answers
UI_SWKBD_SDL_KEYS_HINT, // the SDL window's key line; English only: its debug font draws ASCII (swkbd_sdl.c)
UI_SWKBD_SDL_PAD_HINT1, // the SDL window's controller lines, the letter grid's buttons
UI_SWKBD_SDL_PAD_HINT2,
// Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English, Russian, Brazilian Portuguese, // Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English, Russian, Brazilian Portuguese,
// Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese, Korean and Vietnamese texts. // Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese, Korean and Vietnamese texts.
+11 -7
View File
@@ -90,12 +90,12 @@ void vk_exec_frame_log(const tex_t *p, uint64_t frame) {
fw[i].h, fw[i].fmt, fw[i].n); fw[i].h, fw[i].fmt, fw[i].n);
} }
rt_log("frame %llu: submits %llu passes %llu draws %llu/%llu clears %llu copies %llu dispatches %llu; present %p " rt_log("frame %llu: submits %llu passes %llu draws %llu/%llu clears %llu copies %llu dispatches %llu; present %p "
"%ux%u/%#x written %d; pass ends: targets %llu barrier %llu (%llu merged, %llu undone) bits %llu/%llu/%llu/%llu/%llu/%llu/%llu/%llu; feedback draws %llu barriers %llu restarts %llu layouts %llu; targets%s", "%ux%u/%#x written %d; pass ends: targets %llu barrier %llu (%llu merged, %llu undone, unwritten reads %llu colour %llu depth) bits %llu/%llu/%llu/%llu/%llu/%llu/%llu/%llu; feedback draws %llu barriers %llu restarts %llu layouts %llu; targets%s",
(unsigned long long)frame, (unsigned long long)f->submits, (unsigned long long)frame, (unsigned long long)f->submits,
(unsigned long long)f->passes, (unsigned long long)f->draws, (unsigned long long)f->draws_seen, (unsigned long long)f->passes, (unsigned long long)f->draws, (unsigned long long)f->draws_seen,
(unsigned long long)f->clears, (unsigned long long)f->copies, (unsigned long long)f->dispatches, (unsigned long long)f->clears, (unsigned long long)f->copies, (unsigned long long)f->dispatches,
p ? (const void *)p->mem : NULL, p ? p->d.width : 0, p ? p->d.height : 0, p ? (uint32_t)p->d.format : 0, p ? (const void *)p->mem : NULL, p ? p->d.width : 0, p ? p->d.height : 0, p ? (uint32_t)p->d.format : 0,
hit, (unsigned long long)f->pass_end_rt, (unsigned long long)f->pass_end_barrier, (unsigned long long)f->barrier_merged, (unsigned long long)f->barrier_undone, (unsigned long long)f->barrier_bit[0], (unsigned long long)f->barrier_bit[1], (unsigned long long)f->barrier_bit[2], (unsigned long long)f->barrier_bit[3], (unsigned long long)f->barrier_bit[4], (unsigned long long)f->barrier_bit[5], (unsigned long long)f->barrier_bit[6], (unsigned long long)f->barrier_bit[7], (unsigned long long)f->fb_draws, (unsigned long long)f->fb_barriers, (unsigned long long)f->fb_restarts, hit, (unsigned long long)f->pass_end_rt, (unsigned long long)f->pass_end_barrier, (unsigned long long)f->barrier_merged, (unsigned long long)f->barrier_undone, (unsigned long long)f->undone_color, (unsigned long long)f->undone_depth, (unsigned long long)f->barrier_bit[0], (unsigned long long)f->barrier_bit[1], (unsigned long long)f->barrier_bit[2], (unsigned long long)f->barrier_bit[3], (unsigned long long)f->barrier_bit[4], (unsigned long long)f->barrier_bit[5], (unsigned long long)f->barrier_bit[6], (unsigned long long)f->barrier_bit[7], (unsigned long long)f->fb_draws, (unsigned long long)f->fb_barriers, (unsigned long long)f->fb_restarts,
(unsigned long long)f->fb_layouts, list); (unsigned long long)f->fb_layouts, list);
memset(f, 0, sizeof *f); memset(f, 0, sizeof *f);
nfw = 0; nfw = 0;
@@ -984,7 +984,7 @@ static void clear_ds(VkExec *ex, const p_clear_ds *c) {
// ---- the op loop // ---- the op loop
// barrier_merge (TOTK_BARRIER_MERGE, off by default): TotK calls Barrier(ORDER_FRAGMENTS | INVALIDATE_TEXTURE) about // barrier_merge (TOTK_BARRIER_MERGE, on by default): TotK calls Barrier(ORDER_FRAGMENTS | INVALIDATE_TEXTURE) about
// 1200 times a frame in some scenes (water, decals): the next draw reads the render targets the last one wrote. A full // 1200 times a frame in some scenes (water, decals): the next draw reads the render targets the last one wrote. A full
// barrier there ends the Vulkan pass and flips every target's layout. What such a barrier asks for, an attachment write // barrier there ends the Vulkan pass and flips every target's layout. What such a barrier asks for, an attachment write
// made visible to a later fragment shader read of the open pass, feedback_prepare / feedback_barrier already do before the // made visible to a later fragment shader read of the open pass, feedback_prepare / feedback_barrier already do before the
@@ -992,10 +992,14 @@ static void clear_ds(VkExec *ex, const p_clear_ds *c) {
// that may write a storage buffer or image (pass_storage), which only a full barrier makes visible, or the barrier asks for // that may write a storage buffer or image (pass_storage), which only a full barrier makes visible, or the barrier asks for
// more than those two bits, or the feedback layout is not in use, or a target is a 3D BC stand-in (its texture gets the // more than those two bits, or the feedback layout is not in use, or a target is a 3D BC stand-in (its texture gets the
// pass's writes only at the pass end, bc_copy_back). The reads the by-region barrier does not cover end the pass at the // pass's writes only at the pass end, bc_copy_back). The reads the by-region barrier does not cover end the pass at the
// draw that makes them (vk_exec_draw.c merge_guard). The by-region barrier orders only reads of the pixel a fragment // draw that makes them (vk_exec_draw.c merge_guard), and so do reads of a target the draw does not write itself
// writes; NVN's ORDER_FRAGMENTS orders every pixel (ORDER_FRAGMENTS_TILED is the per-region one), so a draw that reads a // (vk_exec_draw.c merge_unwritten_reads): the by-region barrier orders only reads of the pixel a fragment writes, while
// neighbouring pixel of a target written in the pass relies on the driver running the barrier for the whole target, as // NVN's ORDER_FRAGMENTS orders every pixel (ORDER_FRAGMENTS_TILED is the per-region one). What stays merged is a draw
// RADV does; hence experimental. // that samples a target it also writes, which Savage Wind runs the same way on every GPU. If such a draw read a
// neighbouring pixel, it would rely on the driver running the barrier for the whole target, as RADV and the desktop
// drivers do. On 1.4.3 every read after a merged Barrier in the shrine, the town and the field is of that kind. Passes
// a frame in the shrine: 581 -> 128 on an RDNA2 iGPU with no GPU time change on AMD's Windows driver; the waterfall
// on RADV: 1105 -> 117, GPU 8.3 -> 4.1 ms.
int vk_exec_barrier_merge_on(void) { int vk_exec_barrier_merge_on(void) {
static int on = -1; static int on = -1;
if (on < 0) on = cfg_bool("TOTK_BARRIER_MERGE"); if (on < 0) on = cfg_bool("TOTK_BARRIER_MERGE");
+2
View File
@@ -57,6 +57,8 @@ typedef struct {
uint64_t barrier_bit[8]; // the game's Barrier calls that carry NVN barrier bit 0..7 (TOTK_TRACE=gfx) uint64_t barrier_bit[8]; // the game's Barrier calls that carry NVN barrier bit 0..7 (TOTK_TRACE=gfx)
uint64_t barrier_merged; // the game's Barrier calls the open pass went on through (barrier_merge) uint64_t barrier_merged; // the game's Barrier calls the open pass went on through (barrier_merge)
uint64_t barrier_undone; // passes a draw then ended for a read the merge cannot order (merge_guard) uint64_t barrier_undone; // passes a draw then ended for a read the merge cannot order (merge_guard)
uint64_t undone_color, undone_depth; // of those, for sampling a colour target / the depth target the draw does
// not write itself (vk_exec_draw.c merge_unwritten_reads)
uint64_t pass_end_rt, pass_end_barrier; // passes ended by other render targets, by the game's own Barrier (TOTK_TRACE=gfx) uint64_t pass_end_rt, pass_end_barrier; // passes ended by other render targets, by the game's own Barrier (TOTK_TRACE=gfx)
uint64_t fb_draws, fb_barriers, fb_restarts, fb_layouts; // feedback loops: draws sampling a written target of uint64_t fb_draws, fb_barriers, fb_restarts, fb_layouts; // feedback loops: draws sampling a written target of
// their pass, in-pass barriers, pass restarts, layout // their pass, in-pass barriers, pass restarts, layout
+29
View File
@@ -3128,6 +3128,23 @@ static int merge_guard(VkExec *ex, const GfxShader *vs, const GfxShader *fs) {
return m != 0; return m != 0;
} }
// barrier_merge: the attachments of fbl (sampled in the feedback layout) that a draw with state s reads after other
// draws of the pass wrote them, without writing them itself. A read of a target the draw also writes (G-buffer bits
// ORed in, blending in the shader) is a read of its own pixel, which the by-region barrier orders. A read of a target
// the draw leaves alone is a read of what earlier draws left there, often at neighbouring pixels (blur, ambient
// occlusion, light composites over the G-buffer, depth-based effects), which only the game's Barrier, a full one,
// orders on every driver; the caller ends the pass for it. The rule is Savage Wind's (runtime/nvn/vulkan/exec.c, the
// sampled-texture loop of the draw: a colour target the draw does not write ends the pass when it was written in the
// pass, a read-only depth target when depth was), which that port runs on every GPU. A colour target counts as
// written when the pipeline's write mask for it is not zero, depth as feedback_written counts it.
static uint32_t merge_unwritten_reads(const VkExec *ex, const VkPipeState *s, uint32_t fbl) {
uint32_t r = fbl & ex->fb_dirty;
for (uint32_t i = 0; r & 0xff && i < ex->pass_ncolor && i < 8; i++)
if ((r >> i & 1) && vk_pipeline_target_wmask(s, (int)i)) r &= ~(1u << i);
if ((r & 0x100) && ((s->ds.dt && s->ds.dw) || s->ds.st)) r &= ~0x100u;
return r;
}
// ---- incremental draw preparation (TOTK_BIND_INC) // ---- incremental draw preparation (TOTK_BIND_INC)
// A draw is prepared from what changed since the context's last prepared draw in the same command buffer: the bind // A draw is prepared from what changed since the context's last prepared draw in the same command buffer: the bind
// ops mark the slots whose bytes they changed (VkExec.dirt, vk_exec_bind), every write that changes the pipeline state // ops mark the slots whose bytes they changed (VkExec.dirt, vk_exec_bind), every write that changes the pipeline state
@@ -3450,6 +3467,18 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) {
if (memcmp(&s, &D->PM.s, sizeof s)) bi_mismatch(ex, BIM_PIPE, "pipeline memo: state differs from the memo its generation matched"); if (memcmp(&s, &D->PM.s, sizeof s)) bi_mismatch(ex, BIM_PIPE, "pipeline memo: state differs from the memo its generation matched");
} }
} }
// barrier_merge: a read of a target this draw does not write, made after a merged Barrier, ends the pass; nothing of
// the draw is recorded yet, and the new pass keeps the targets and their feedback layout, so fbl and the state hold.
if (ex->pass_merged && fbl & ex->fb_dirty) {
uint32_t r = merge_unwritten_reads(ex, sp, fbl);
if (r) {
vk_exec_pass_end(ex);
vk_exec_pass_begin(ex);
ex->fr.barrier_undone++;
if (r & 0xff) ex->fr.undone_color++;
else ex->fr.undone_depth++;
}
}
const VkPipeInfo *info = NULL; const VkPipeInfo *info = NULL;
int pending; int pending;
// A draw of at most 6 vertices over half the render area or more (a full-screen triangle or quad, a tile) waits for // A draw of at most 6 vertices over half the render area or more (a full-screen triangle or quad, a tile) waits for
+14
View File
@@ -128,6 +128,9 @@ static int import_pool(VkCtx *c, PoolRec *r, uint64_t addr, uint64_t size) {
r->import_lo = addr & ~(al - 1); r->import_lo = addr & ~(al - 1);
r->import_hi = (addr + size + al - 1) & ~(al - 1); r->import_hi = (addr + size + al - 1) & ~(al - 1);
uint64_t n = r->import_hi - r->import_lo; uint64_t n = r->import_hi - r->import_lo;
// TOTK_HEAP_LAZY: the caller's mem_thaw committed the pool's own chunks; an alignment above 4 KiB can widen the
// import into a neighbouring chunk the game never touched, and the driver refuses reserved pages.
mem_heap_commit(r->import_lo, n);
VkMemoryHostPointerPropertiesEXT hp = {.sType = VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; VkMemoryHostPointerPropertiesEXT hp = {.sType = VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT};
VkResult res = p_host_props ? p_host_props(c->device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, VkResult res = p_host_props ? p_host_props(c->device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
(void *)(uintptr_t)r->import_lo, &hp) (void *)(uintptr_t)r->import_lo, &hp)
@@ -582,6 +585,13 @@ void vk_mem_census(uint64_t frame) {
rt_log("mem: commit at frame %llu: this process %.0f MB, the system %.0f of %.0f MB; room for device memory %s%.0f MiB", rt_log("mem: commit at frame %llu: this process %.0f MB, the system %.0f of %.0f MB; room for device memory %s%.0f MiB",
(unsigned long long)frame, proc, used, limit, room == UINT64_MAX ? "not counted " : "", (unsigned long long)frame, proc, used, limit, room == UINT64_MAX ? "not counted " : "",
room == UINT64_MAX ? 0.0 : room / 1048576.0); room == UINT64_MAX ? 0.0 : room / 1048576.0);
if (mem_heap_lazy()) { // what the heap's first-use commits (memory.c heap_fault) cost and saved so far
uint64_t nf, ns, hc, hs;
mem_heap_lazy_stats(&nf, &ns, &hc, &hs);
rt_log("mem: heap at frame %llu: %llu of %llu MiB committed, %llu first-use faults, %.1f ms in all",
(unsigned long long)frame, (unsigned long long)(hc >> 20), (unsigned long long)(hs >> 20),
(unsigned long long)nf, ns / 1e6);
}
// Per heap, what VMA holds (blocks, and the allocations inside them) beside what the driver counts for the process: // Per heap, what VMA holds (blocks, and the allocations inside them) beside what the driver counts for the process:
// usage above VMA's blocks is the driver's own memory (pipelines, command buffers, descriptor pools). // usage above VMA's blocks is the driver's own memory (pipelines, command buffers, descriptor pools).
VkCtx *vc = vk_ctx(); VkCtx *vc = vk_ctx();
@@ -643,6 +653,10 @@ uint64_t vk_mem_host_room(void) {
if (at && now - at < 250) return __atomic_load_n(&room_cached, __ATOMIC_RELAXED); // a query costs a system call if (at && now - at < 250) return __atomic_load_n(&room_cached, __ATOMIC_RELAXED); // a query costs a system call
uint64_t commit, phys; uint64_t commit, phys;
plat_mem_room(&commit, &phys); plat_mem_room(&commit, &phys);
// The game's heap commits on first use (memory.c, heap_fault): the part it has not touched yet is commit it can
// still claim, which an eagerly committed heap had already taken. Its physical memory was never taken either way.
uint64_t later = mem_heap_uncommitted();
if (commit != UINT64_MAX) commit = commit > later ? commit - later : 0;
uint64_t r = host_backed == HB_UMA && phys < commit ? phys : commit; uint64_t r = host_backed == HB_UMA && phys < commit ? phys : commit;
r = r == UINT64_MAX ? r : r > room_reserve ? r - room_reserve : 0; r = r == UINT64_MAX ? r : r > room_reserve ? r - room_reserve : 0;
__atomic_store_n(&room_cached, r, __ATOMIC_RELAXED); __atomic_store_n(&room_cached, r, __ATOMIC_RELAXED);
+54 -17
View File
@@ -879,37 +879,72 @@ out:
// undefined. Mesa keeps computing after a discard; AMD's Windows compiler does not, and TotK's cloud shader, which // undefined. Mesa keeps computing after a discard; AMD's Windows compiler does not, and TotK's cloud shader, which
// discards where the scene is in front and then takes OpImageQueryLod for its noise textures, lost fog in the pixels // discards where the scene is in front and then takes OpImageQueryLod for its noise textures, lost fog in the pixels
// sharing a quad with a discarded one: a light fringe round every silhouette against clouds (issue #164). // sharing a quad with a discarded one: a light fringe round every silhouette against clouds (issue #164).
// Each OpKill whose block is a direct target of a selection header becomes OpDemoteToHelperInvocation plus a branch to // Each OpKill whose block is a direct target of a selection header, and which an explicit derivative follows (below),
// that selection's merge block, so the fragment goes on computing and writes nothing. An OpKill anywhere else (the end // becomes OpDemoteToHelperInvocation plus a branch to that selection's merge block, so the fragment goes on computing
// of a function, a switch case) stays. NULL: nothing to change. // and writes nothing. An OpKill anywhere else (the end of a function, a switch case) stays. NULL: nothing to change.
// Only kills that an OpImageQueryLod, an OpDPdx..OpFwidthCoarse or an OpFunctionCall (whose callee may take one)
// follows later in the same function change: the cloud shader's fringe came from OpImageQueryLod. A demoted fragment
// runs the rest of the shader, so demoting every kill made each alpha-tested draw (grass, foliage, hair) pay for its
// discarded pixels; implicit-LOD samples after a kill, which nearly every alpha-tested shader takes, kept the OpKill
// they had before demote existed, without a report. Program order stands for "after": a derivative in the other arm
// of the kill's selection demotes too (harmless), one reached only by a loop's back edge does not (that kill keeps
// its OpKill, as before demote).
// On by default on AMD's own drivers, where the fringe shows; other drivers keep the translator's OpKill, their output // On by default on AMD's own drivers, where the fringe shows; other drivers keep the translator's OpKill, their output
// unchanged. TOTK_DEMOTE=1 or 0 overrides on any driver that enables shaderDemoteToHelperInvocation (vk_caps.demote, // unchanged. TOTK_DEMOTE=1 or 0 (ini: demote) overrides on any driver that enables shaderDemoteToHelperInvocation
// set in vk_device.c create_device); without the feature the module keeps OpKill, since the capability would be invalid. // (vk_caps.demote, set in vk_device.c create_device); without the feature the module keeps OpKill, since the
// capability would be invalid.
static uint64_t demote_mods, demote_kept; // modules with an OpKill: some kill demoted, every kill kept (atomics)
// Logs the split of modules with an OpKill at each power of two of their count.
static void demote_note(int demoted) {
uint64_t d = demoted ? __atomic_add_fetch(&demote_mods, 1, __ATOMIC_RELAXED) : __atomic_load_n(&demote_mods, __ATOMIC_RELAXED);
uint64_t k = demoted ? __atomic_load_n(&demote_kept, __ATOMIC_RELAXED) : __atomic_add_fetch(&demote_kept, 1, __ATOMIC_RELAXED);
uint64_t t = d + k;
if (!(t & (t - 1)))
rt_log("vk_pipeline: discard as demote: %llu shaders with a discard demote it, %llu keep it (no derivative after)",
(unsigned long long)d, (unsigned long long)k);
}
static uint32_t *spirv_demote(const uint32_t *w, uint64_t n, uint64_t *out_n) { static uint32_t *spirv_demote(const uint32_t *w, uint64_t n, uint64_t *out_n) {
enum { OP_EXTENSION = 10, OP_CAPABILITY = 17, OP_SELECTION_MERGE = 247, OP_LABEL = 248, OP_BRANCH = 249, enum { OP_EXTENSION = 10, OP_CAPABILITY = 17, OP_FUNCTION_END = 56, OP_FUNCTION_CALL = 57, OP_IMAGE_QUERY_LOD = 105,
OP_DPDX = 207, OP_FWIDTH_COARSE = 215, OP_SELECTION_MERGE = 247, OP_LABEL = 248, OP_BRANCH = 249,
OP_BRANCH_CONDITIONAL = 250, OP_KILL = 252, OP_DEMOTE = 5380, CAP_DEMOTE = 5379 }; OP_BRANCH_CONDITIONAL = 250, OP_KILL = 252, OP_DEMOTE = 5380, CAP_DEMOTE = 5379 };
static const char ext_name[36] = "SPV_EXT_demote_to_helper_invocation"; // 35 characters and the terminator: 9 words static const char ext_name[36] = "SPV_EXT_demote_to_helper_invocation"; // 35 characters and the terminator: 9 words
static int on = -1; static int on = -1;
if (on < 0) { if (on < 0) {
on = vk_caps.demote && rt_knob("DEMOTE", vk_caps.amd && !vk_caps.mesa ? "1" : "0"); on = vk_caps.demote && rt_knob("DEMOTE", vk_caps.amd && !vk_caps.mesa ? "1" : "0");
rt_log("vk_pipeline: discard as demote: %s (shaderDemoteToHelperInvocation %d, TOTK_DEMOTE)", on ? "on" : "off", rt_log("vk_pipeline: discard as demote: %s, for discards a derivative follows (shaderDemoteToHelperInvocation "
vk_caps.demote); "%d, TOTK_DEMOTE)", on ? "on" : "off", vk_caps.demote);
} }
if (!on || n < 5) return NULL; if (!on || n < 5) return NULL;
uint64_t kills = 0; // Pass 1: check the words, count the kills, and note each function's last derivative (or call) by function order.
uint64_t kills = 0, nfn = 0, cap_fn = 8, last = 0;
uint64_t *fn_deriv = malloc(cap_fn * sizeof *fn_deriv);
if (!fn_deriv) return NULL;
for (uint64_t i = 5; i < n;) { for (uint64_t i = 5; i < n;) {
uint32_t op = w[i] & 0xffff, l = w[i] >> 16; uint32_t op = w[i] & 0xffff, l = w[i] >> 16;
if (!l || i + l > n) return NULL; if (!l || i + l > n || (op == OP_CAPABILITY && l >= 2 && w[i + 1] == CAP_DEMOTE)) { // malformed, or demotes already
if (op == OP_KILL) kills++; free(fn_deriv);
if (op == OP_CAPABILITY && l >= 2 && w[i + 1] == CAP_DEMOTE) return NULL; // already demotes return NULL;
}
kills += op == OP_KILL;
if (op == OP_IMAGE_QUERY_LOD || (op >= OP_DPDX && op <= OP_FWIDTH_COARSE) || op == OP_FUNCTION_CALL) last = i;
if (op == OP_FUNCTION_END) {
if (nfn == cap_fn) {
uint64_t *g = realloc(fn_deriv, 2 * cap_fn * sizeof *fn_deriv);
if (!g) { free(fn_deriv); return NULL; }
fn_deriv = g, cap_fn *= 2;
}
fn_deriv[nfn++] = last, last = 0;
}
i += l; i += l;
} }
if (!kills) return NULL; if (!kills) { free(fn_deriv); return NULL; }
uint32_t bound = w[3] < (1u << 22) ? w[3] : (1u << 22); uint32_t bound = w[3] < (1u << 22) ? w[3] : (1u << 22);
uint32_t *merge_of = calloc(bound ? bound : 1, sizeof *merge_of); // label -> merge block of the selection that branches to it uint32_t *merge_of = calloc(bound ? bound : 1, sizeof *merge_of); // label -> merge block of the selection that branches to it
uint32_t *o = malloc((n + 12 + 2 * kills) * 4); uint32_t *o = malloc((n + 12 + 2 * kills) * 4);
if (!merge_of || !o) { free(merge_of), free(o); return NULL; } if (!merge_of || !o) { free(merge_of), free(o), free(fn_deriv); return NULL; }
uint64_t on_w = 5, changed = 0; uint64_t on_w = 5, changed = 0, fn = 0;
uint32_t cur = 0, pending = 0; uint32_t cur = 0, pending = 0;
int declared = 0; int declared = 0;
memcpy(o, w, 5 * 4); memcpy(o, w, 5 * 4);
@@ -929,7 +964,7 @@ static uint32_t *spirv_demote(const uint32_t *w, uint64_t n, uint64_t *out_n) {
if (a[k] < bound && a[k] != pending) merge_of[a[k]] = merge_of[a[k]] ? ~0u : pending; // two headers: leave it if (a[k] < bound && a[k] != pending) merge_of[a[k]] = merge_of[a[k]] ? ~0u : pending; // two headers: leave it
} }
pending = op == OP_SELECTION_MERGE && l >= 3 ? a[0] : 0; pending = op == OP_SELECTION_MERGE && l >= 3 ? a[0] : 0;
uint32_t m = op == OP_KILL && cur < bound ? merge_of[cur] : 0; uint32_t m = op == OP_KILL && cur < bound && fn < nfn && fn_deriv[fn] > i ? merge_of[cur] : 0;
if (m && m != ~0u && m != cur) { if (m && m != ~0u && m != cur) {
o[on_w++] = 1u << 16 | OP_DEMOTE; o[on_w++] = 1u << 16 | OP_DEMOTE;
o[on_w++] = 2u << 16 | OP_BRANCH, o[on_w++] = m; o[on_w++] = 2u << 16 | OP_BRANCH, o[on_w++] = m;
@@ -937,9 +972,11 @@ static uint32_t *spirv_demote(const uint32_t *w, uint64_t n, uint64_t *out_n) {
} else { } else {
memcpy(o + on_w, w + i, l * 4), on_w += l; memcpy(o + on_w, w + i, l * 4), on_w += l;
} }
fn += op == OP_FUNCTION_END;
i += l; i += l;
} }
free(merge_of); free(merge_of), free(fn_deriv);
demote_note(changed != 0);
if (!changed) { free(o); return NULL; } if (!changed) { free(o); return NULL; }
*out_n = on_w; *out_n = on_w;
return o; return o;
+74
View File
@@ -0,0 +1,74 @@
"""The production custom cursor must not depend on uninitialized stack colours.
python tests/cursor_art_check.py --cc path/to/clang
"""
import argparse
from pathlib import Path
import shutil
import struct
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#endif
#include "input_wsys.h"
int main(int argc, char **argv) {
assert(argc == 2);
int size = atoi(argv[1]), hot;
assert(size > 0 && size <= 128);
uint32_t *pixels = malloc((size_t)size * size * sizeof *pixels);
assert(pixels);
cursor_art(pixels, size, &hot);
#ifdef _WIN32
assert(_setmode(_fileno(stdout), _O_BINARY) != -1);
#endif
assert(fwrite(&hot, sizeof hot, 1, stdout) == 1);
assert(fwrite(pixels, sizeof *pixels, (size_t)size * size, stdout) == (size_t)size * size);
free(pixels);
return 0;
}
'''
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--cc', default=shutil.which('clang') or r'C:\msys64\ucrt64\bin\clang.exe')
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='cursor-art-') as temp:
work = Path(temp)
source = work / 'probe.c'
source.write_text(HARNESS, encoding='utf-8')
outputs = {}
for mode in ('zero', 'pattern'):
exe = work / f'{mode}.exe'
subprocess.run([args.cc, '-O2', '-std=gnu11', f'-ftrivial-auto-var-init={mode}',
'-I', str(ROOT / 'runtime'), str(source), str(ROOT / 'runtime/cursor_art.c'),
'-lm', '-o', str(exe)], check=True)
outputs[mode] = {}
for size in (16, 24, 32, 48, 64, 96, 128):
data = subprocess.run([str(exe), str(size)], check=True, capture_output=True).stdout
assert len(data) == 4 + size * size * 4
pixels = struct.unpack(f'<{size * size}I', data[4:])
assert any(p == 0 for p in pixels), 'the cursor must have transparent pixels'
assert any(p >> 24 and p & 0xffffff for p in pixels), 'the cursor must contain visible colour'
outputs[mode][size] = data
differences = []
for size in outputs['zero']:
a, b = outputs['zero'][size], outputs['pattern'][size]
different = sum(a[i:i + 4] != b[i:i + 4] for i in range(4, len(a), 4))
if different or a[:4] != b[:4]:
differences.append((size, different))
print(f'cursor {size}x{size}: {different} pixels differ between zero and pattern stack initialization')
assert not differences, f'cursor pixels depend on uninitialized automatic variables: {differences}'
if __name__ == '__main__':
main()
+102
View File
@@ -0,0 +1,102 @@
"""The IPC probe must not use stale or indeterminate replies after a kernel error.
python tests/ipc_probe_check.py --cc path/to/clang
"""
import argparse
from pathlib import Path
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "ipc.h"
// The probe's expected failure diagnostics are kept off the test's stdout.
static int probe_printf(const char *format, ...) { (void)format; return 0; }
static int probe_putchar(int c) { return c; }
#define printf probe_printf
#define putchar probe_putchar
PRODUCTION
#undef printf
#undef putchar
static uint32_t kernel_result, service_result;
void rt_svc(Cpu *c, uint32_t imm, uint64_t pc) {
(void)pc;
assert(imm == 0x21);
c->x[0] = kernel_result;
if (kernel_result) return;
uint32_t *m = (uint32_t *)(uintptr_t)c->tpidrro;
int tipc = (m[0] & 0xffff) >= T_TIPC_BASE;
memset(m, 0, IPC_MSG_BYTES);
m[1] = 1u << 31;
m[2] = service_result ? 0 : 1u << 5;
uint32_t *p = m + 3;
if (!service_result) *p++ = 0x1234;
if (tipc) *p = service_result;
else {
p = m + (((p - m) + 3) & ~3);
p[0] = CMIF_OUT_MAGIC;
p[2] = service_result;
}
}
int main(void) {
Cpu c = {0};
uint32_t tlr[IPC_MSG_BYTES / 4] = {0};
c.tpidrro = (uintptr_t)tlr;
for (int tipc = 0; tipc <= 1; tipc++) {
failures = 0;
kernel_result = service_result = 0;
assert(get_service(&c, 1, "test:u", tipc) == 0x1234 && failures == 0);
kernel_result = IPC_R_BAD_HANDLE;
uint32_t h = get_service(&c, 1, "test:u", tipc);
if (h) fprintf(stderr, "%s kernel error returned stale service handle %#x\n", tipc ? "TIPC" : "CMIF", h);
assert(h == 0 && failures == 1);
}
Reply r;
kernel_result = service_result = 0;
assert(cmd(&c, 1, 0, NULL, 0, &r) == 0 && r.nmove == 1 && r.move[0] == 0x1234);
memset(&r, 0xa5, sizeof r);
kernel_result = IPC_R_BAD_HANDLE;
assert(cmd(&c, 1, 0, NULL, 0, &r) == IPC_R_BAD_HANDLE);
assert(r.result == 0 && r.ncopy == 0 && r.nmove == 0 && r.data == NULL);
for (unsigned i = 0; i < 8; i++) assert(r.copy[i] == 0 && r.move[i] == 0);
kernel_result = 0;
service_result = IPC_R_UNKNOWN_COMMAND;
assert(cmd(&c, 1, 0, NULL, 0, &r) == IPC_R_UNKNOWN_COMMAND && r.result == service_result);
assert(r.nmove == 0 && r.data != NULL);
puts("IPC probe: CMIF/TIPC success and kernel-error replies, reply reuse and service errors passed");
return 0;
}
'''
def production():
text = (ROOT / 'runtime/ipc.c').read_text(encoding='utf-8')
magic = '\n'.join(line for line in text.splitlines() if line.startswith(('#define CMIF_IN_MAGIC', '#define CMIF_OUT_MAGIC')))
start = text.index('enum { T_CLOSE')
types = text[start:text.index('};', start) + 2]
helpers = text[text.index('#define PROBE_FRAMES'):text.index('// A TotK-like renderer:')]
return magic + '\n' + types + '\n' + helpers
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--cc', default=shutil.which('clang') or r'C:\msys64\ucrt64\bin\clang.exe')
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='ipc-probe-') as temp:
work = Path(temp)
source = work / 'probe.c'
source.write_text(HARNESS.replace('PRODUCTION', production()), encoding='utf-8')
exe = work / 'probe.exe'
subprocess.run([args.cc, '-O2', '-std=gnu11', '-ftrivial-auto-var-init=pattern',
'-I', str(ROOT / 'runtime'), str(source), '-o', str(exe)], check=True)
subprocess.run([str(exe)], check=True)
if __name__ == '__main__':
main()
+2
View File
@@ -72,8 +72,10 @@ TESTS = {
'settings_doc_check': ('.venv', None, [], ''), 'settings_doc_check': ('.venv', None, [], ''),
'mouse_direct_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles its checks with clang'), 'mouse_direct_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles its checks with clang'),
'cheats_vm_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles runtime/cheats.c into a harness with clang'), 'cheats_vm_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles runtime/cheats.c into a harness with clang'),
'cursor_art_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the cursor with zero and pattern stack initialization'),
'romfs_shapes_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production overlay selection helpers'), 'romfs_shapes_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production overlay selection helpers'),
'frame_world_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production world-clock player walk'), 'frame_world_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production world-clock player walk'),
'ipc_probe_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the IPC probe helpers with forced kernel failures'),
'sync_ahead_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production sync-ahead wait selection'), 'sync_ahead_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production sync-ahead wait selection'),
'patches_v110_check': ('.venv', 'cc', [], 'compiles synthetic patch contracts for comparison with Unicorn'), 'patches_v110_check': ('.venv', 'cc', [], 'compiles synthetic patch contracts for comparison with Unicorn'),
'patches_v110_highfps_check': ('.venv', 'cc', [], 'compiles synthetic high-fps contracts for comparison with Unicorn'), 'patches_v110_highfps_check': ('.venv', 'cc', [], 'compiles synthetic high-fps contracts for comparison with Unicorn'),
+15 -8
View File
@@ -98,14 +98,16 @@
# the CPU threads). # the CPU threads).
# lib_prebuild = 1 # lib_prebuild = 1
# lib_prebuild_threads = 4 # lib_prebuild_threads = 4
# Experimental: 1 keeps a render pass open through the game's own Barrier calls (ORDER_FRAGMENTS | INVALIDATE_TEXTURE) when # 1 keeps a render pass open through the game's own Barrier calls (ORDER_FRAGMENTS | INVALIDATE_TEXTURE) when none of the
# none of the pass's draws can write a storage buffer or image, making the writes visible to the next draw with a by-region # pass's draws can write a storage buffer or image, making the writes visible to the next draw with a by-region barrier
# barrier instead of ending the pass. Scenes where the game issues about a thousand such barriers a frame (the water in # instead of ending the pass. A draw that samples a target written in the pass without writing it itself still ends the
# the Nachoyah Shrine, terrain decals) go from about 1200 passes and 10000 layout changes to about 130 passes and 150; # pass. Scenes where the game issues about a thousand such barriers a frame (the water in the Nachoyah Shrine, terrain
# the GPU time there fell from 24.5 to 7.8 ms a frame. The game's barrier orders every pixel, the one inside the pass only # decals) go from about 1200 passes and 10000 layout changes to about 130 passes and 150; the GPU time there fell from
# the pixel a draw writes: a driver that runs it per screen tile can show flicker or squares at the edges of water, decals # 24.5 to 7.8 ms a frame on Linux (RADV). The game's barrier orders every pixel, the one inside the pass only the pixel a
# or particles (report any). Needs the feedback layout (the default). Read at start. Default: 0. # draw writes: a driver that runs it per screen tile could show flicker or squares at the edges of water, decals or
# barrier_merge = 0 # particles; 0 brings back a full barrier each time (report it). Needs the feedback layout (the default). Read at start.
# Default: 1.
# barrier_merge = 1
# Build known pipelines ahead of time. # Build known pipelines ahead of time.
# pipe_prebuild = 1 # pipe_prebuild = 1
# Threads that translate known shaders at start (1 to 64; default: half the CPU threads, at most 16). # Threads that translate known shaders at start (1 to 64; default: half the CPU threads, at most 16).
@@ -150,6 +152,11 @@
# fix_c0 = 1 # fix_c0 = 1
# New GPU memory pools start zero-filled, as Switch memory does. # New GPU memory pools start zero-filled, as Switch memory does.
# fix_zero = 1 # fix_zero = 1
# Shaders that discard a pixel and then read how fast a value changes across neighbouring pixels (a texture's
# level of detail, a derivative) keep the discarded pixel running without output, as the Switch does: stops the light
# fringe round objects against clouds and fog on AMD. Default: 1 on AMD's own Windows driver, 0 elsewhere. 0 keeps
# the plain discard everywhere, 1 also uses it on other drivers. Read at start.
# demote = 1
# Optimisations, 0 turns each off: skip bindings that did not change, remember shader lookups, reuse the previous # Optimisations, 0 turns each off: skip bindings that did not change, remember shader lookups, reuse the previous
# draw's pipeline when its state repeats, remember texture descriptors between draws, update descriptors in bulk, # draw's pipeline when its state repeats, remember texture descriptors between draws, update descriptors in bulk,
# skip push constants that did not change, bind only the vertex buffers a draw reads, compare and copy each draw's # skip push constants that did not change, bind only the vertex buffers a draw reads, compare and copy each draw's